问:
Transfer Data from an Calendar Row to a TextBox
I'm using PlanningCalendar App to show the workers schedule.

But what I also need is, after I click on the worker (for example 'Carlos Pinho') his data (name and role) appear on the TextBox from the SimpleForm (red arrow)

Controller:

```<code>sap.ui.define([
'jquery.sap.global',
'sap/m/StandardListItem',
'sap/m/MessageToast',
'sap/ui/core/mvc/Controller',
'sap/m/Label',
'sap/m/Text',
'sap/m/TextArea',
'sap/ui/model/json/JSONModel'], function(jQuery, StandardListItem, MessageToast, Controller, Label, Text, TextArea, JSONModel) {
"use strict";

return Controller.extend("zapp_rej_absence.controller.Main", {

    onInit: function() {
        //this.getView().byId() //Para definir o que aparece na combo box
        // create model
        var oModel = new JSONModel();
        oModel.setData({
            startDate: new Date("2017", "4", "26", "8", "0"),
            people: [{
                pic: "sap-icon://employee", //Foto do Funcionario
                name: "Carlos Pinho", //Nome do Funcionario
                role: "Logística", //Area do Funcionario
                appointments: [{
                    start: new Date("2017", "4", "29", "12", "0"), //[Ano, Meses (cujo a ordem é Janeiro ->0), Dia, Horas, Minutos]
                    end: new Date("2017", "4", "29", "14", "0"),
                    title: "Reunião de Equipa",
                    info: "Sala A06",
                    type: "Type01", //Cor do Evento
                    pic: "sap-icon://manager",
                    tentative: false
                }, {
                    start: new Date("2017", "5", "10", "0", "0"), //[Ano, Meses (cujo a ordem é Janeiro ->0), Dia, Horas, Minutos]
                    end: new Date("2017", "5", "16", "23", "59"),
                    title: "Férias",
                    info: "Maldivas",
                    pic: "sap-icon://flight",
                    type: "Type04", //Cor do Evento
                    tentative: false
                }],
                headers: [{
                    start: new Date("2017", "4", "29", "08", "0"), //[Ano, Meses (cujo a ordem é Janeiro ->0), Dia, Horas, Minutos]
                    end: new Date("2017", "4", "29", "10", "0"),
                    title: "Privado",
                    type: "Type05"
                }]
            }, {
                pic: "sap-icon://employee", //Foto do Funcionario
                name: "Joaquim Agostinho", //Nome do Funcionario
                role: "Financeira", //Area do Funcionario
                appointments: [{
                    start: new Date("2017", "4", "29", "08", "30"), //[Ano, Meses (cujo a ordem é Janeiro ->0), Dia, Horas, Minutos]
                    end: new Date("2017", "4", "29", "09", "30"),
                    title: "Reunião",
                    pic: "sap-icon://world",
                    type: "Type02", //Cor do Evento
                    tentative: false
                }, {
                    start: new Date("2017", "4", "30", "10", "0"), //[Ano, Meses (cujo a ordem é Janeiro ->0), Dia, Horas, Minutos]
                    end: new Date("2017", "4", "30", "12", "0"),
                    title: "Reunião de Equipa",
                    info: "Sala 1",
                    type: "Type01", //Cor do Evento
                    pic: "sap-icon://manager",
                    tentative: false
                }, {
                    start: new Date("2017", "4", "30", "12", "30"), //[Ano, Meses (cujo a ordem é Janeiro ->0), Dia, Horas, Minutos]
                    end: new Date("2017", "4", "30", "13", "30"),
                    title: "Almoço",
                    type: "Type03", //Cor do Evento
                    pic: "sap-icon://meal",
                    tentative: true
                }],
                headers: [{
                    start: new Date("2017", "4", "29", "8", "0"), //[Ano, Meses (cujo a ordem é Janeiro ->0), Dia, Horas, Minutos]
                    end: new Date("2017", "4", "29", "10", "0"),
                    title: "Lembrete",
                    type: "Type06" //Cor do Evento
                }]
            }]
        });
        this.getView().setModel(oModel);

    },

    //Dialog do botão aceitar
    onMessageSuccessDialogPress: function(oEvent) {
        var dialog = new Dialog({
            title: 'Successo',
            type: 'Message',
            state: 'Success',
            content: new Text({
                text: "Foi aprovado com sucesso."
            }),
            beginButton: new Button({
                text: 'OK',
                press: function() {
                    MessageToast.show('Pedido Aprovado');
                    dialog.close();
                }
            }),
            afterClose: function() {
                dialog.destroy();
            }
        });

        dialog.open();
    },

    onMessageWarningDialogPress: function(oEvent) {
        var dialog = new Dialog({
            title: 'Aviso',
            type: 'Message',
            state: 'Warning',
            content: new Text({
                text: 'Tem a certeza que quer rejeitar este pedido?'
            }),

            beginButton: new Button({
                text: 'Sim',
                press: function() {
                    dialog.close();
                    var dialog1 = new Dialog({
                        title: 'Confirmação',
                        type: 'Message',
                        content: [
                            new Label({
                                text: 'Tem a certeza que pretende rejeitar o pedido?',
                                labelFor: 'submitDialogTextarea'
                            }),
                            new TextArea('submitDialogTextarea', {
                                liveChange: function(oEvent) {
                                    var sText = oEvent.getParameter('value');
                                    var parent = oEvent.getSource().getParent();

                                    parent.getBeginButton().setEnabled(sText.length > 0);
                                },
                                width: '100%',
                                placeholder: 'Adicionar nota (obrigatória)'
                            })
                        ],
                        beginButton: new Button({
                            text: 'Submit',
                            enabled: false,
                            press: function() {

                                MessageToast.show('Pedido Rejeitado');
                                dialog1.close();
                            }
                        }),
                        endButton: new Button({
                            text: 'Cancel',
                            press: function() {
                                dialog1.close();
                            }
                        }),
                        afterClose: function() {
                            dialog1.destroy();

                        }
                    });

                    dialog1.open();

                }
            }),

            endButton: new Button({
                text: 'Não',
                press: function() {
                    dialog.close();
                }
            }),

            afterClose: function() {
                dialog.destroy();
            }
        });

        dialog.open();
    },

    onSubmitDialog: function() {
        var dialog = new Dialog({
            title: 'Confirm',
            type: 'Message',
            content: [
                new Label({
                    text: 'Are you sure you want to submit your shopping cart?',
                    labelFor: 'submitDialogTextarea'
                }),
                new TextArea('submitDialogTextarea', {
                    liveChange: function(oEvent) {
                        var sText = oEvent.getParameter('value');
                        var parent = oEvent.getSource().getParent();

                        parent.getBeginButton().setEnabled(sText.length > 0);
                    },
                    width: '100%',
                    placeholder: 'Add note (required)'
                })
            ],
            beginButton: new Button({
                text: 'Submit',
                enabled: false,
                press: function() {
                    var sText = sap.ui.getCore().byId('submitDialogTextarea').getValue();
                    MessageToast.show('Note is: ' + sText);
                    dialog.close();
                }
            }),
            endButton: new Button({
                text: 'Cancel',
                press: function() {
                    dialog.close();
                }
            }),
            afterClose: function() {
                dialog.destroy();
            }
        });

        dialog.open();
    },

    onMessageDialogPress: function(oEvent) {
        var dialog = new Dialog({
            title: 'Meses Aprovados',
            icon: 'sap-icon://calendar',
            type: 'Message',
            content: new Text({
                text: 'A ideia é aparecer os meses todos em RadioButtons'
            }),
            beginButton: new Button({
                text: 'OK',
                press: function() {
                    dialog.close();
                }
            }),
            endButton: new Button({
                text: 'Cancelar',

                press: function() {
                    dialog.close();
                }
            }),

            afterClose: function() {
                dialog.destroy();
            }
        });

        dialog.open();
    },

    handlePopoverPress: function(oEvent) {

        // create popover
        if (!this._oPopover) {
            this._oPopover = sap.ui.xmlfragment("zapp_rej_absence.view.Popover", this);
            this.getView().addDependent(this._oPopover);
            this._oPopover.bindElement("/ProductCollection/0");
        }
        // delay because addDependent will do a async rerendering and the actionSheet will immediately close without it.
        var oButton = oEvent.getSource();
        jQuery.sap.delayedCall(0, this, function() {
            this._oPopover.openBy(oButton);
        });
    },

    //---------------------------------------------------------Eventos

    handleAppointmentSelect: function(oEvent) {
        var oAppointment = oEvent.getParameter("appointment"); //Selecçao do Evento
        if (oAppointment) {
            alert("Evento Selecionado: " + oAppointment.getTitle());
        } else {
            var aAppointments = oEvent.getParameter("appointments");
            var sValue = aAppointments.length + " Eventos Selecionados";
            alert(sValue);
        }
    }
}); });
</code>```

XML:

```<code><mvc:View controllerName="zapp_rej_absence.controller.Main" xmlns:html="http://www.w3.org/1999/xhtml" displayBlock="true" xmlns="sap.m"
xmlns:mvc="sap.ui.core.mvc" xmlns:unified="sap.ui.unified" xmlns:f="sap.ui.layout.form">
<Page title="Aprovação de Férias/Ausências" enableScrolling="true">
    <Panel class="sapUiSmallMargin" width="auto">
        <PlanningCalendar id="PC1" startDate="{path: '/startDate'}" rows="{path: '/people'}" appointmentsVisualization="Filled"
            appointmentSelect="handleAppointmentSelect" showEmptyIntervalHeaders="false" viewKey="One Month">
            <toolbarContent>
                <Title text="Calendário" titleStyle="H4"/>
                <ToolbarSpacer/>
                <SearchField width="300px" placeholder="Procurar..."/>
                <Button icon="sap-icon://legend" press="handlePopoverPress"/>
            </toolbarContent>
            <rows>
                <PlanningCalendarRow icon="{pic}" title="{name}" text="{role}" appointments="{appointments}" intervalHeaders="{headers}">
                    <appointments>
                        <unified:CalendarAppointment startDate="{start}" endDate="{end}" icon="{pic}" title="{title}" text="{info}" type="{type}"
                            tentative="{tentative}"></unified:CalendarAppointment>
                    </appointments>
                    <intervalHeaders>
                        <unified:CalendarAppointment startDate="{start}" endDate="{end}" icon="{pic}" title="{title}" type="{type}"></unified:CalendarAppointment>
                    </intervalHeaders>
                </PlanningCalendarRow>
            </rows>
        </PlanningCalendar>
        <f:SimpleForm id="SimpleFormDisplay354" class="sapUiLargeMarginTop" width="auto" editable="false" layout="ResponsiveGridLayout"
            title="Informações do Colaborador" labelSpanXL="3" labelSpanL="3" labelSpanM="3" labelSpanS="12" adjustLabelSpan="false" emptySpanXL="4"
            emptySpanL="4" emptySpanM="4" emptySpanS="0" columnsXL="1" columnsL="1" columnsM="1" singleContainerFullSize="false">
            <f:content>
                <Label text="Nome" width="100%" design="Bold"/>
                <Text text="{Name}" width="100%"/>
                <!--Depois ir buscar estes dados à BD-->
                <Label text="Equipa" width="100%" design="Bold"/>
                <Text text="{Street} {HouseNumber}" width="100%"/>
                <!--Depois ir buscar estes dados à BD-->
                <Label text="Total de Férias" width="100%" design="Bold"/>
                <Text text="{ZIPCode} {City}" width="100%"/>
                <!--Depois ir buscar estes dados à BD-->
                <Label text="Country" width="100%" design="Bold"/>
                <Text text="{Country}" width="100%"/><!--Depois ir buscar estes dados à BD--></f:content>
        </f:SimpleForm>
    </Panel>
    <footer>
        <Toolbar>
            <Button icon="sap-icon://past" text="Meses Aprovados" type="Emphasized" press="onMessageDialogPress"/>
            <ToolbarSpacer/>
            <Button icon="sap-icon://accept" text="Aprovar" type="Accept" press="onMessageSuccessDialogPress"/>
            <Button icon="sap-icon://sys-cancel-2" text="Rejeitar" type="Reject" press="onMessageWarningDialogPress" />
        </Toolbar>
    </footer>
</Page>
</code>```

Thanks in advance for your help.

答:
I used the binding context of selected row and bound it to the form below and it worked.
Below is the working code and steps:

Add "Row Selection Event" to planning calender.

```<code><PlanningCalendar id="PC1" startDate="{path: '/startDate'}" rows="{path: '/people'}"
    appointmentsVisualization="Filled"
    appointmentSelect="handleAppointmentSelect" showEmptyIntervalHeaders="false" viewKey="One Month"
    rowSelectionChange="onRowSelection">
</code>```

Step 2: Find the binding Context of selected row and bind it to the form:

```<code>    onRowSelection: function(oEvent) {
        var oForm = this.byId('SimpleFormDisplay354');
        var oBindingContext = oEvent.getSource().getSelectedRows()[0].getBindingContext();
        oForm.setBindingContext(oBindingContext);
    }
</code>```

Step 3: Bind correct Properties in the form:

```<code>    <f:SimpleForm id="SimpleFormDisplay354" class="sapUiLargeMarginTop" width="auto" editable="false" layout="ResponsiveGridLayout"
        title="Informações do Colaborador" labelSpanXL="3" labelSpanL="3" labelSpanM="3" labelSpanS="12" adjustLabelSpan="false" emptySpanXL="4"
        emptySpanL="4" emptySpanM="4" emptySpanS="0" columnsXL="1" columnsL="1" columnsM="1" singleContainerFullSize="false">
        <f:content>
            <Label text="Nome" width="100%" design="Bold"/>
            <Text text="{name}" width="100%"/>
            <!--Depois ir buscar estes dados à BD-->
            <Label text="Role" width="100%" design="Bold"/>
            <Text text="{role}" width="100%"/>
            </f:content>
    </f:SimpleForm>
</code>```

Let me know if this works for you.

Body:
I'm using PlanningCalendar App to show the workers schedule.

But what I also need is, after I click on the worker (for example 'Carlos Pinho') his data (name and role) appear on the TextBox from the SimpleForm (red arrow)

Controller:

sap.ui.define([
'jquery.sap.global',
'sap/m/StandardListItem',
'sap/m/MessageToast',
'sap/ui/core/mvc/Controller',
'sap/m/Label',
'sap/m/Text',
'sap/m/TextArea',
'sap/ui/model/json/JSONModel'], function(jQuery, StandardListItem, MessageToast, Controller, Label, Text, TextArea, JSONModel) {
"use strict";

return Controller.extend("zapp_rej_absence.controller.Main", {

    onInit: function() {
        //this.getView().byId() //Para definir o que aparece na combo box
        // create model
        var oModel = new JSONModel();
        oModel.setData({
            startDate: new Date("2017", "4", "26", "8", "0"),
            people: [{
                pic: "sap-icon://employee", //Foto do Funcionario
                name: "Carlos Pinho", //Nome do Funcionario
                role: "Logística", //Area do Funcionario
                appointments: [{
                    start: new Date("2017", "4", "29", "12", "0"), //[Ano, Meses (cujo a ordem é Janeiro ->0), Dia, Horas, Minutos]
                    end: new Date("2017", "4", "29", "14", "0"),
                    title: "Reunião de Equipa",
                    info: "Sala A06",
                    type: "Type01", //Cor do Evento
                    pic: "sap-icon://manager",
                    tentative: false
                }, {
                    start: new Date("2017", "5", "10", "0", "0"), //[Ano, Meses (cujo a ordem é Janeiro ->0), Dia, Horas, Minutos]
                    end: new Date("2017", "5", "16", "23", "59"),
                    title: "Férias",
                    info: "Maldivas",
                    pic: "sap-icon://flight",
                    type: "Type04", //Cor do Evento
                    tentative: false
                }],
                headers: [{
                    start: new Date("2017", "4", "29", "08", "0"), //[Ano, Meses (cujo a ordem é Janeiro ->0), Dia, Horas, Minutos]
                    end: new Date("2017", "4", "29", "10", "0"),
                    title: "Privado",
                    type: "Type05"
                }]
            }, {
                pic: "sap-icon://employee", //Foto do Funcionario
                name: "Joaquim Agostinho", //Nome do Funcionario
                role: "Financeira", //Area do Funcionario
                appointments: [{
                    start: new Date("2017", "4", "29", "08", "30"), //[Ano, Meses (cujo a ordem é Janeiro ->0), Dia, Horas, Minutos]
                    end: new Date("2017", "4", "29", "09", "30"),
                    title: "Reunião",
                    pic: "sap-icon://world",
                    type: "Type02", //Cor do Evento
                    tentative: false
                }, {
                    start: new Date("2017", "4", "30", "10", "0"), //[Ano, Meses (cujo a ordem é Janeiro ->0), Dia, Horas, Minutos]
                    end: new Date("2017", "4", "30", "12", "0"),
                    title: "Reunião de Equipa",
                    info: "Sala 1",
                    type: "Type01", //Cor do Evento
                    pic: "sap-icon://manager",
                    tentative: false
                }, {
                    start: new Date("2017", "4", "30", "12", "30"), //[Ano, Meses (cujo a ordem é Janeiro ->0), Dia, Horas, Minutos]
                    end: new Date("2017", "4", "30", "13", "30"),
                    title: "Almoço",
                    type: "Type03", //Cor do Evento
                    pic: "sap-icon://meal",
                    tentative: true
                }],
                headers: [{
                    start: new Date("2017", "4", "29", "8", "0"), //[Ano, Meses (cujo a ordem é Janeiro ->0), Dia, Horas, Minutos]
                    end: new Date("2017", "4", "29", "10", "0"),
                    title: "Lembrete",
                    type: "Type06" //Cor do Evento
                }]
            }]
        });
        this.getView().setModel(oModel);

    },

    //Dialog do botão aceitar
    onMessageSuccessDialogPress: function(oEvent) {
        var dialog = new Dialog({
            title: 'Successo',
            type: 'Message',
            state: 'Success',
            content: new Text({
                text: "Foi aprovado com sucesso."
            }),
            beginButton: new Button({
                text: 'OK',
                press: function() {
                    MessageToast.show('Pedido Aprovado');
                    dialog.close();
                }
            }),
            afterClose: function() {
                dialog.destroy();
            }
        });

        dialog.open();
    },

    onMessageWarningDialogPress: function(oEvent) {
        var dialog = new Dialog({
            title: 'Aviso',
            type: 'Message',
            state: 'Warning',
            content: new Text({
                text: 'Tem a certeza que quer rejeitar este pedido?'
            }),

            beginButton: new Button({
                text: 'Sim',
                press: function() {
                    dialog.close();
                    var dialog1 = new Dialog({
                        title: 'Confirmação',
                        type: 'Message',
                        content: [
                            new Label({
                                text: 'Tem a certeza que pretende rejeitar o pedido?',
                                labelFor: 'submitDialogTextarea'
                            }),
                            new TextArea('submitDialogTextarea', {
                                liveChange: function(oEvent) {
                                    var sText = oEvent.getParameter('value');
                                    var parent = oEvent.getSource().getParent();

                                    parent.getBeginButton().setEnabled(sText.length > 0);
                                },
                                width: '100%',
                                placeholder: 'Adicionar nota (obrigatória)'
                            })
                        ],
                        beginButton: new Button({
                            text: 'Submit',
                            enabled: false,
                            press: function() {

                                MessageToast.show('Pedido Rejeitado');
                                dialog1.close();
                            }
                        }),
                        endButton: new Button({
                            text: 'Cancel',
                            press: function() {
                                dialog1.close();
                            }
                        }),
                        afterClose: function() {
                            dialog1.destroy();

                        }
                    });

                    dialog1.open();

                }
            }),

            endButton: new Button({
                text: 'Não',
                press: function() {
                    dialog.close();
                }
            }),

            afterClose: function() {
                dialog.destroy();
            }
        });

        dialog.open();
    },

    onSubmitDialog: function() {
        var dialog = new Dialog({
            title: 'Confirm',
            type: 'Message',
            content: [
                new Label({
                    text: 'Are you sure you want to submit your shopping cart?',
                    labelFor: 'submitDialogTextarea'
                }),
                new TextArea('submitDialogTextarea', {
                    liveChange: function(oEvent) {
                        var sText = oEvent.getParameter('value');
                        var parent = oEvent.getSource().getParent();

                        parent.getBeginButton().setEnabled(sText.length > 0);
                    },
                    width: '100%',
                    placeholder: 'Add note (required)'
                })
            ],
            beginButton: new Button({
                text: 'Submit',
                enabled: false,
                press: function() {
                    var sText = sap.ui.getCore().byId('submitDialogTextarea').getValue();
                    MessageToast.show('Note is: ' + sText);
                    dialog.close();
                }
            }),
            endButton: new Button({
                text: 'Cancel',
                press: function() {
                    dialog.close();
                }
            }),
            afterClose: function() {
                dialog.destroy();
            }
        });

        dialog.open();
    },

    onMessageDialogPress: function(oEvent) {
        var dialog = new Dialog({
            title: 'Meses Aprovados',
            icon: 'sap-icon://calendar',
            type: 'Message',
            content: new Text({
                text: 'A ideia é aparecer os meses todos em RadioButtons'
            }),
            beginButton: new Button({
                text: 'OK',
                press: function() {
                    dialog.close();
                }
            }),
            endButton: new Button({
                text: 'Cancelar',

                press: function() {
                    dialog.close();
                }
            }),

            afterClose: function() {
                dialog.destroy();
            }
        });

        dialog.open();
    },

    handlePopoverPress: function(oEvent) {

        // create popover
        if (!this._oPopover) {
            this._oPopover = sap.ui.xmlfragment("zapp_rej_absence.view.Popover", this);
            this.getView().addDependent(this._oPopover);
            this._oPopover.bindElement("/ProductCollection/0");
        }
        // delay because addDependent will do a async rerendering and the actionSheet will immediately close without it.
        var oButton = oEvent.getSource();
        jQuery.sap.delayedCall(0, this, function() {
            this._oPopover.openBy(oButton);
        });
    },

    //---------------------------------------------------------Eventos

    handleAppointmentSelect: function(oEvent) {
        var oAppointment = oEvent.getParameter("appointment"); //Selecçao do Evento
        if (oAppointment) {
            alert("Evento Selecionado: " + oAppointment.getTitle());
        } else {
            var aAppointments = oEvent.getParameter("appointments");
            var sValue = aAppointments.length + " Eventos Selecionados";
            alert(sValue);
        }
    }
}); });

XML:

<mvc:View controllerName="zapp_rej_absence.controller.Main" xmlns:html="http://www.w3.org/1999/xhtml" displayBlock="true" xmlns="sap.m"
xmlns:mvc="sap.ui.core.mvc" xmlns:unified="sap.ui.unified" xmlns:f="sap.ui.layout.form">
<Page title="Aprovação de Férias/Ausências" enableScrolling="true">
    <Panel class="sapUiSmallMargin" width="auto">
        <PlanningCalendar id="PC1" startDate="{path: '/startDate'}" rows="{path: '/people'}" appointmentsVisualization="Filled"
            appointmentSelect="handleAppointmentSelect" showEmptyIntervalHeaders="false" viewKey="One Month">
            <toolbarContent>
                <Title text="Calendário" titleStyle="H4"/>
                <ToolbarSpacer/>
                <SearchField width="300px" placeholder="Procurar..."/>
                <Button icon="sap-icon://legend" press="handlePopoverPress"/>
            </toolbarContent>
            <rows>
                <PlanningCalendarRow icon="{pic}" title="{name}" text="{role}" appointments="{appointments}" intervalHeaders="{headers}">
                    <appointments>
                        <unified:CalendarAppointment startDate="{start}" endDate="{end}" icon="{pic}" title="{title}" text="{info}" type="{type}"
                            tentative="{tentative}"></unified:CalendarAppointment>
                    </appointments>
                    <intervalHeaders>
                        <unified:CalendarAppointment startDate="{start}" endDate="{end}" icon="{pic}" title="{title}" type="{type}"></unified:CalendarAppointment>
                    </intervalHeaders>
                </PlanningCalendarRow>
            </rows>
        </PlanningCalendar>
        <f:SimpleForm id="SimpleFormDisplay354" class="sapUiLargeMarginTop" width="auto" editable="false" layout="ResponsiveGridLayout"
            title="Informações do Colaborador" labelSpanXL="3" labelSpanL="3" labelSpanM="3" labelSpanS="12" adjustLabelSpan="false" emptySpanXL="4"
            emptySpanL="4" emptySpanM="4" emptySpanS="0" columnsXL="1" columnsL="1" columnsM="1" singleContainerFullSize="false">
            <f:content>

                <Text text="{Name}" width="100%"/>

                <Text text="{Street} {HouseNumber}" width="100%"/>

                <Text text="{ZIPCode} {City}" width="100%"/>

                <Text text="{Country}" width="100%"/></f:content>
        </f:SimpleForm>
    </Panel>

        <Toolbar>
            <Button icon="sap-icon://past" text="Meses Aprovados" type="Emphasized" press="onMessageDialogPress"/>
            <ToolbarSpacer/>
            <Button icon="sap-icon://accept" text="Aprovar" type="Accept" press="onMessageSuccessDialogPress"/>
            <Button icon="sap-icon://sys-cancel-2" text="Rejeitar" type="Reject" press="onMessageWarningDialogPress" />
        </Toolbar>

</Page>

Thanks in advance for your help.

Body:
I used the binding context of selected row and bound it to the form below and it worked.
Below is the working code and steps:

Add "Row Selection Event" to planning calender.

<PlanningCalendar id="PC1" startDate="{path: '/startDate'}" rows="{path: '/people'}"
    appointmentsVisualization="Filled"
    appointmentSelect="handleAppointmentSelect" showEmptyIntervalHeaders="false" viewKey="One Month"
    rowSelectionChange="onRowSelection">

Step 2: Find the binding Context of selected row and bind it to the form:

    onRowSelection: function(oEvent) {
        var oForm = this.byId('SimpleFormDisplay354');
        var oBindingContext = oEvent.getSource().getSelectedRows()[0].getBindingContext();
        oForm.setBindingContext(oBindingContext);
    }

Step 3: Bind correct Properties in the form:

    <f:SimpleForm id="SimpleFormDisplay354" class="sapUiLargeMarginTop" width="auto" editable="false" layout="ResponsiveGridLayout"
        title="Informações do Colaborador" labelSpanXL="3" labelSpanL="3" labelSpanM="3" labelSpanS="12" adjustLabelSpan="false" emptySpanXL="4"
        emptySpanL="4" emptySpanM="4" emptySpanS="0" columnsXL="1" columnsL="1" columnsM="1" singleContainerFullSize="false">
        <f:content>
            <Label text="Nome" width="100%" design="Bold"/>
            <Text text="{name}" width="100%"/>
            <!--Depois ir buscar estes dados à BD-->
            <Label text="Role" width="100%" design="Bold"/>
            <Text text="{role}" width="100%"/>
            </f:content>
    </f:SimpleForm>

Let me know if this works for you.


来源: stackexchange

问:
Julia: Export results to table: example code
Please point to example code and documentation on approaches to export some data and simulation results to a tidy, readable table that could easily be copy-pasted or imported into documents, particularly for post-processing with LaTeX.

My current practice is along the lines of:

```<code>using DataFrames
function show_table(mp::ModelParameters, ms::ModelSolution)
    α = mp.α; δ = ms.δ;
    d = DataFrame(Name = @data(["α"]),
                  Description = @data(["alpha"]),
                  Value = @data([α])
    )
    push!(d, @data(["δ", "delta", δ]))
    return(d)
end

    2×3 DataFrames.DataFrame
    │ Row │ Name │ Description │ Value │
    ├─────┼──────┼─────────────┼───────┤
    │ 1   │ "α"  │ "alpha"     │ 1.01  │
    │ 2   │ "δ"  │ "delta"     │ 2.02  │
</code>```

Turning the above into a LaTeX table will require some work. Any step in the right direction will be appreciated.

I have found a promising package named LaTeX.jl that does not seem to be maintained and/or has been superseded.  The dream would be to have something like stargazer  for R.

I have used unicode Greeks in my code, e.g. α, which can be compiled with XeLaTeX, but a solution where α were converted to \alpha would be welcome too. An alternative would be to manually replace the names in my convenience function show_table, which is not so bad.

答:
There may or may not be a nice package that generally exports latex tables.  What I'm saying in my comment above is that, in my experience, for any serious document, your latex tables will be complicated and best looked after individually (some may have multicolumns for instance, others might not, others might need custom spacing etc). So it may be worth having julia scripts generating those tables instead, i.e. one script per table. This enables you to then make this part of your makefile when compiling your final latex document.

E.g., using your provided example dataframe:

%% main.tex -- example bare-bones document illustrating how
 %             to import externally generated tables, without
 %             affecting the structure of your main document
 %             when those external tables get updated / replaced

\documentclass[12pt]{article}
\usepackage[utf8]{inputenc}
\usepackage[table]{xcolor}
\begin{document}
  \begin{table}[htbp]
    \centering
    \input{./table1}        % I.e. simply dump julia-generated table here
    \caption{This table was generated in Julia}
    \label{tbl:table1}
  \end{table}
\end{document}
```

<p>

<pre class="lang-julia prettyprint-override"><code>### table1.jl script
  T[:,:Name] = "\$\\" * T[:,:Description] * "\$";  # replace symbol with latex math

# Generate table header
  Table  = "\\begin{tabular}{| " * "c |" ^ (ncol(T)+1) * "}\n";
  Table *= "    \\hline\n";
  Table *= "    % Table header\n";
  Table *= "    \\rowcolor[gray]{0.9}\n";
  Table *= "  Row"; for i in 1:ncol(T); Table *= " & " * string(names(T)[i]); end; Table *= " \\\\\n";

# Generate table body (with nice alternating row colours)
  toggleRowColour(x) = x == "0.8" ? "0.7" : "0.8";
  rowcolour = toggleRowColour(0.7);

  Table *= "    % Table body\n";
  for row in 1 : nrow(T)
    Table *= "  \\rowcolor[gray]{" * (rowcolour = toggleRowColour(rowcolour); rowcolour) * "}\n";
    Table *= "  " * string(row); for col in 1 : ncol(T) Table *= " & " * string(T[row,col]); end; Table *= " \\\\\n";
    Table *= "  \\hline\n";
  end
  Table *= "\\end{tabular}\n";

# Export result to .tex file
  write("table1.tex", Table);
</code>```

In your julia REPL:

julia> using DataFrames
julia> # function show_table defined as above ...
julia> T = show_table(1.01,2.02);
julia> include("table1.jl")
```

<p>Resulting in the following <code>table1.tex</code> file:</p>

<pre class="lang-latex prettyprint-override"><code>\begin{tabular}{| c |c |c |c |}
  \hline
  % Table header
  \rowcolor[gray]{0.9}
  Row & Name & Description & Value \\
  % Table body
  \rowcolor[gray]{0.7}
  1 & $\alpha$ & alpha & 1.01 \\
  \hline
  \rowcolor[gray]{0.8}
  2 & $\delta$ & delta & 2.02 \\
  \hline
\end{tabular}
</code>```

Compiling the resulting main.tex file gives:

Now, I want to be clear what I'm saying here. I'm not saying this is the most generic, automated julia approach. Quite the opposite. This is highly specific to your file. what I am saying is that keeping a simple julia script template for generating tables like this which is suitable for your project, and adapting it for each specific latex table you require, is probably going to be a lot more straightforward in the context of writing a thesis or similar document, where you'll probably need a lot of fine-tuning and control over your tables in the long term.

So, after you've written your first table and have it as a template, this approach is fast for the subsequent tables because you just make the odd tweak here and there, while still enabling you to update your tables with new data as they arise, and allowing you to make compilation of your julia-generated tables automatic within a wider Latex Makefile compilation sequence.

This was the approach I followed with my own thesis and it saved me a lot of time.

ContentLicense: CC BY-SA 3.0

Body:
Please point to example code and documentation on approaches to export some data and simulation results to a tidy, readable table that could easily be copy-pasted or imported into documents, particularly for post-processing with LaTeX.

My current practice is along the lines of:

using DataFrames
function show_table(mp::ModelParameters, ms::ModelSolution)
    α = mp.α; δ = ms.δ;
    d = DataFrame(Name = @data(["α"]),
                  Description = @data(["alpha"]),
                  Value = @data([α])
    )
    push!(d, @data(["δ", "delta", δ]))
    return(d)
end

    2×3 DataFrames.DataFrame
    │ Row │ Name │ Description │ Value │
    ├─────┼──────┼─────────────┼───────┤
    │ 1   │ "α"  │ "alpha"     │ 1.01  │
    │ 2   │ "δ"  │ "delta"     │ 2.02  │

Turning the above into a LaTeX table will require some work. Any step in the right direction will be appreciated.

I have found a promising package named LaTeX.jl that does not seem to be maintained and/or has been superseded.  The dream would be to have something like stargazer  for R.

I have used unicode Greeks in my code, e.g. α, which can be compiled with XeLaTeX, but a solution where α were converted to \alpha would be welcome too. An alternative would be to manually replace the names in my convenience function show_table, which is not so bad.

Body:
There may or may not be a nice package that generally exports latex tables.  What I'm saying in my comment above is that, in my experience, for any serious document, your latex tables will be complicated and best looked after individually (some may have multicolumns for instance, others might not, others might need custom spacing etc). So it may be worth having julia scripts generating those tables instead, i.e. one script per table. This enables you to then make this part of your makefile when compiling your final latex document.

E.g., using your provided example dataframe:

%% main.tex -- example bare-bones document illustrating how
 %             to import externally generated tables, without
 %             affecting the structure of your main document
 %             when those external tables get updated / replaced

\documentclass[12pt]{article}
\usepackage[utf8]{inputenc}
\usepackage[table]{xcolor}
\begin{document}
  \begin{table}[htbp]
    \centering
    \input{./table1}        % I.e. simply dump julia-generated table here
    \caption{This table was generated in Julia}
    \label{tbl:table1}
  \end{table}
\end{document}

### table1.jl script
  T[:,:Name] = "\$\\" * T[:,:Description] * "\$";  # replace symbol with latex math

# Generate table header
  Table  = "\\begin{tabular}{| " * "c |" ^ (ncol(T)+1) * "}\n";
  Table *= "    \\hline\n";
  Table *= "    % Table header\n";
  Table *= "    \\rowcolor[gray]{0.9}\n";
  Table *= "  Row"; for i in 1:ncol(T); Table *= " & " * string(names(T)[i]); end; Table *= " \\\\\n";

# Generate table body (with nice alternating row colours)
  toggleRowColour(x) = x == "0.8" ? "0.7" : "0.8";
  rowcolour = toggleRowColour(0.7);

  Table *= "    % Table body\n";
  for row in 1 : nrow(T)
    Table *= "  \\rowcolor[gray]{" * (rowcolour = toggleRowColour(rowcolour); rowcolour) * "}\n";
    Table *= "  " * string(row); for col in 1 : ncol(T) Table *= " & " * string(T[row,col]); end; Table *= " \\\\\n";
    Table *= "  \\hline\n";
  end
  Table *= "\\end{tabular}\n";

# Export result to .tex file
  write("table1.tex", Table);

In your julia REPL:

julia> using DataFrames
julia> # function show_table defined as above ...
julia> T = show_table(1.01,2.02);
julia> include("table1.jl")

Resulting in the following table1.tex file:

\begin{tabular}{| c |c |c |c |}
  \hline
  % Table header
  \rowcolor[gray]{0.9}
  Row & Name & Description & Value \\
  % Table body
  \rowcolor[gray]{0.7}
  1 & $\alpha$ & alpha & 1.01 \\
  \hline
  \rowcolor[gray]{0.8}
  2 & $\delta$ & delta & 2.02 \\
  \hline
\end{tabular}

Compiling the resulting main.tex file gives:

Now, I want to be clear what I'm saying here. I'm not saying this is the most generic, automated julia approach. Quite the opposite. This is highly specific to your file. what I am saying is that keeping a simple julia script template for generating tables like this which is suitable for your project, and adapting it for each specific latex table you require, is probably going to be a lot more straightforward in the context of writing a thesis or similar document, where you'll probably need a lot of fine-tuning and control over your tables in the long term.

So, after you've written your first table and have it as a template, this approach is fast for the subsequent tables because you just make the odd tweak here and there, while still enabling you to update your tables with new data as they arise, and allowing you to make compilation of your julia-generated tables automatic within a wider Latex Makefile compilation sequence.

This was the approach I followed with my own thesis and it saved me a lot of time.


问:
pandas dataframe select row by full multiindex entry and some column entry
I have a multi indexed DataFrame in pandas and i would like to select a row by the following condition:

Let's say we have columns 'a','b','c' and indicies 'i1','i2'

```<code>print(df)

           a   b   c
i1  i2
10 2.0    10  34   ..
   2.0    11  45   ..
   2.0    12  36   ..
20 2.0    10  15   ..
   2.0    18  34   ..
   2.0    16  46   ..
</code>```

Now I would like to select for each unique muliindex entry the row where column 'a' becomes maximal. So I wrote

```<code>for entry in df.index.unique():
    max_a = df.loc[entry,'a'].max()
</code>```

and now I would like to select that row and append it to another dataframe, let's say dfout

```<code>dfout=dfout.append(df[(df.index.values == entry) & (df['fi'] == max_a)])
</code>```

This raises invalid type comparison, probably because I try to compare tuples, not sure...
Can anyone explain to me, how I would be able to select exactly that row the correct way? Maybe there is even a much nicer way to select all these max('a') rows for all unique entries of df.index.

edit:

df.index.values is of type numpy.ndarray

entry is of type tuple

Maybe this helps for answering my question.

答:
I took the example dataframe from the pandas MultiIndex documentation page and did the following

```<code>def mklbl(prefix,n):
        return ["%s%s" % (prefix,i)  for i in range(n)]

miindex = pd.MultiIndex.from_product([mklbl('A',4),
                                       mklbl('B',2),
                                       mklbl('C',4),
                                       mklbl('D',2)])

micolumns = pd.MultiIndex.from_tuples([('a','foo'),('a','bar'),
                                        ('b','foo'),('b','bah')],
                                       names=['lvl0', 'lvl1'])

dfmi = pd.DataFrame(np.arange(len(miindex)*len(micolumns)).reshape((len(miindex),len(micolumns))),
                     index=miindex,
                     columns=micolumns).sort_index().sort_index(axis=1)

dfmi.index = dfmi.index.droplevel(3)
dfmi_ = dfmi.reset_index()
dfmi_.columns = dfmi_.columns.droplevel(1)
</code>```

the dataframe should now look roughly the same as your example

```<code>>> dfmi_.head()
lvl0 level_0 level_1 level_2   a   a   b   b
0         A0      B0      C0   1   0   3   2
1         A0      B0      C0   5   4   7   6
2         A0      B0      C1   9   8  11  10
3         A0      B0      C1  13  12  15  14
4         A0      B0      C2  17  16  19  18
</code>```

now you can just do a groupby and idxmax to get the max index per group

```<code>>> idxmax = dfmi_.groupby('level_0')['a'].idxmax()
>> dfmi_.loc[idxmax]
lvl0 level_0 level_1 level_2    a    a    b    b
15        A0      B1      C3   61   60   63   62
15        A0      B1      C3   61   60   63   62
31        A1      B1      C3  125  124  127  126
31        A1      B1      C3  125  124  127  126
47        A2      B1      C3  189  188  191  190
47        A2      B1      C3  189  188  191  190
63        A3      B1      C3  253  252  255  254
63        A3      B1      C3  253  252  255  254
</code>```

Body:
I have a multi indexed DataFrame in pandas and i would like to select a row by the following condition:

Let's say we have columns 'a','b','c' and indicies 'i1','i2'

print(df)

           a   b   c
i1  i2
10 2.0    10  34   ..
   2.0    11  45   ..
   2.0    12  36   ..
20 2.0    10  15   ..
   2.0    18  34   ..
   2.0    16  46   ..

Now I would like to select for each unique muliindex entry the row where column 'a' becomes maximal. So I wrote

for entry in df.index.unique():
    max_a = df.loc[entry,'a'].max()

and now I would like to select that row and append it to another dataframe, let's say dfout

dfout=dfout.append(df[(df.index.values == entry) & (df['fi'] == max_a)])

This raises invalid type comparison, probably because I try to compare tuples, not sure...
Can anyone explain to me, how I would be able to select exactly that row the correct way? Maybe there is even a much nicer way to select all these max('a') rows for all unique entries of df.index.

edit:

df.index.values is of type numpy.ndarray

entry is of type tuple

Maybe this helps for answering my question.

Body:
I took the example dataframe from the pandas MultiIndex documentation page and did the following

def mklbl(prefix,n):
        return ["%s%s" % (prefix,i)  for i in range(n)]

miindex = pd.MultiIndex.from_product([mklbl('A',4),
                                       mklbl('B',2),
                                       mklbl('C',4),
                                       mklbl('D',2)])

micolumns = pd.MultiIndex.from_tuples([('a','foo'),('a','bar'),
                                        ('b','foo'),('b','bah')],
                                       names=['lvl0', 'lvl1'])

dfmi = pd.DataFrame(np.arange(len(miindex)*len(micolumns)).reshape((len(miindex),len(micolumns))),
                     index=miindex,
                     columns=micolumns).sort_index().sort_index(axis=1)

dfmi.index = dfmi.index.droplevel(3)
dfmi_ = dfmi.reset_index()
dfmi_.columns = dfmi_.columns.droplevel(1)

the dataframe should now look roughly the same as your example

>> dfmi_.head()
lvl0 level_0 level_1 level_2   a   a   b   b
0         A0      B0      C0   1   0   3   2
1         A0      B0      C0   5   4   7   6
2         A0      B0      C1   9   8  11  10
3         A0      B0      C1  13  12  15  14
4         A0      B0      C2  17  16  19  18

now you can just do a groupby and idxmax to get the max index per group

>> idxmax = dfmi_.groupby('level_0')['a'].idxmax()
>> dfmi_.loc[idxmax]
lvl0 level_0 level_1 level_2    a    a    b    b
15        A0      B1      C3   61   60   63   62
15        A0      B1      C3   61   60   63   62
31        A1      B1      C3  125  124  127  126
31        A1      B1      C3  125  124  127  126
47        A2      B1      C3  189  188  191  190
47        A2      B1      C3  189  188  191  190
63        A3      B1      C3  253  252  255  254
63        A3      B1      C3  253  252  255  254


问:
'Beautiful arrays' CodeChef, how to input data
Here's the problem statement:

An array a is called beautiful if for every pair of numbers ai, aj, (i
≠ j), there exists an ak such that ak = ai * aj. Note that k can be
equal to i or j too.

Find out whether the given array a is beautiful or not!

Input

First line of the input contains an integer T denoting the number of
test cases. T test cases follow.

First line of each test case contains an integer n denoting number of
elements in a.

Next line contains n space separated integers denoting the array a.
Output

For each test case, output a single line containing "yes" or "no"
(without quotes) corresponding to the answer of the problem.
Constraints

```<code>1 ≤ T ≤ 106
1 ≤ n ≤ 105
Sum of n over all the test cases ≤ 106
-109 ≤ ai ≤ 109
</code>```

Example

Input

3

2

0 1

2

1 2

2

5 6

Output:

yes

yes

no

I am new to CodeChef and can't work out how to correctly take in an input, I have some code that I am trying to use to solve the beautiful arrays problem but when I run it I get a NZEC.

```<code>from collections import Counter
numCase = int(input())
for i in range(numCase):
    length = input()
    array = Counter(input().split(''))
    answer = "no"
    for i in range(length - 1):
        if array[i] == 0 or array[i] == 1:
            answer = "yes"

    print(answer)
</code>```

When I change the inputs and manually input some data the code works for me, can anybody tell me why this code doesn't work? Thanks

答:
I think you're not checking the last element of array because of range. try this</p>

```<code>for i in range(length)
</code>```

Body:
Here's the problem statement:

An array a is called beautiful if for every pair of numbers ai, aj, (i
≠ j), there exists an ak such that ak = ai * aj. Note that k can be
equal to i or j too.

Find out whether the given array a is beautiful or not!

Input

First line of the input contains an integer T denoting the number of
test cases. T test cases follow.

First line of each test case contains an integer n denoting number of
elements in a.

Next line contains n space separated integers denoting the array a.
Output

For each test case, output a single line containing "yes" or "no"
(without quotes) corresponding to the answer of the problem.
Constraints

1 ≤ T ≤ 106
1 ≤ n ≤ 105
Sum of n over all the test cases ≤ 106
-109 ≤ ai ≤ 109

Example

Input

3

2

0 1

2

1 2

2

5 6

Output:

yes

yes

no

I am new to CodeChef and can't work out how to correctly take in an input, I have some code that I am trying to use to solve the beautiful arrays problem but when I run it I get a NZEC.

from collections import Counter
numCase = int(input())
for i in range(numCase):
    length = input()
    array = Counter(input().split(''))
    answer = "no"
    for i in range(length - 1):
        if array[i] == 0 or array[i] == 1:
            answer = "yes"

    print(answer)

When I change the inputs and manually input some data the code works for me, can anybody tell me why this code doesn't work? Thanks

Body:
I think you're not checking the last element of array because of range. try this

for i in range(length)


问:
Monkey patch XMLHTTPRequest.onreadystatechange
How would go about monkey patching the XMLHTTPRequest's onreadystatechange function. I'm trying to add a function that would be called when every ajax request made from a page come back.

I know this sounds like a terrible idea, but the use case is quite peculiar. I want to use a certain SDK with a console (jqconsole) but show status and results from ajax calls within the console without modifying the external SDK.

I've looked at this post which had great info, but nothing on monkey patching the callback which seem to exceed my JavaScript skills.

P.S Can't use jQuery since it only supports ajax calls made from jQuery not from XMLHTTPRequests directly which is the case here.

答:
you can learn from Ajax-hook written by chinese!

it is a advanced js to enable Monkey patch XMLHTTPRequest

ContentLicense: CC BY-SA 4.0


问:
openSuse and cx_Freeze 4.3.3 : ImportError: libwx_gtk2u_adv-suse.so.1: No such file or directory
I'm trying to create a binary file with cx_Freeze 4.3.3 on openSuse 42.1 (I use
wxPython3.0), but on an empty openSuse system, I can't run my program...

here is my setup.py file :

```<code>#!/usr/bin/python
# -*- coding: utf-8 -*-

import sys
from cx_Freeze import setup, Executable

path = sys.path
path += ["/usr/lib64"]

includes = []
excludes = ['PyQt4', 'PyQt5', 'Tkinter', 'FixTk', 'tcl', 'tk', '_tkinter', 'collections.abc']
packages = ['matplotlib.backends.backend_wxagg', 'numpy']

includefiles = ['./data/','./images/','./html/','./locale/','./logs/']

binpathincludes = []

if sys.platform == "linux2":
     binpathincludes += ["/usr/lib64"]
     binpathincludes += ["/usr/lib"]

base = 'Console'

options = {"path": path,
            "includes": includes,
            "excludes": excludes,
            "packages": packages,
            "include_files": includefiles,
            "bin_path_includes": binpathincludes,
            "optimize": 0,
            "silent": True
            }

executables = [
     Executable('MyProjetc.py', base=base)
]

setup(name='MyProject',
       version='1.0',
       description='My Project',
       executables=executables,
       options={'build_exe': options}
       )
</code>```

but when I try to run my binary program on an empty system opensuse (without
wxPython installed on it), I get this error :

```<code>Traceback (most recent call last):
File "/usr/lib64/python2.7/site-packages/cx_Freeze/initscripts/Console.py", line 27, in <module>
File "JustConsum.py", line 4, in <module>
File "/usr/lib64/python2.7/site-packages/wx-3.0-gtk2/wx/__init__.py", line 45, in <module>
File "/usr/lib64/python2.7/site-packages/wx-3.0-gtk2/wx/_core.py", line 4, in <module>
File "ExtensionLoader_wx__core_.py", line 22, in <module>
File "ExtensionLoader_wx__core_.py", line 14, in __bootstrap__
ImportError: libwx_gtk2u_adv-suse.so.1: cannot open shared object file: No such file or directory
</code>```

But that file "libwx_gtk2u_adv-suse.so.1" is
indeed at root of the directory containing the binaries files :

```<code>-rwxrwx--- 1 regis users  1918960 25 oct.   2015 libwx_gtk2u_adv-suse.so.1
-rwxrwx--- 1 regis users   575528 25 oct.   2015 libwx_gtk2u_aui-suse.so.1
-rwxrwx--- 1 regis users  5780640 25 oct.   2015 libwx_gtk2u_core-suse.so.1
</code>```

Any idea on what's going on ?

Thx a lot

答:
So I searched on the internet, and found out the " patchelf " command.
As my binary files (generated with cx_Freeze) were in the same directory than my executable file, I created the script :

```<code>for i in *so*
do
     patchelf --set-rpath '.' $i
done
</code>```

Since, my standalone application can be launched on an "empty" openSuse system...

Note:

this solution works with cx_Freeze 4.3.x, but don't with the 5.x versions

I successfully created standalone application (for this same program) on various other linux platform (Debian, Mint, Ubuntu, Mageia, Fedora, CentOS) without any kind of problem.

Only openSuse has needed this kind of operation so my standalone program can work out... I can't explain why.

May be this post could help some else.

Body:
I'm trying to create a binary file with cx_Freeze 4.3.3 on openSuse 42.1 (I use
wxPython3.0), but on an empty openSuse system, I can't run my program...

here is my setup.py file :

#!/usr/bin/python
# -*- coding: utf-8 -*-

import sys
from cx_Freeze import setup, Executable

path = sys.path
path += ["/usr/lib64"]

includes = []
excludes = ['PyQt4', 'PyQt5', 'Tkinter', 'FixTk', 'tcl', 'tk', '_tkinter', 'collections.abc']
packages = ['matplotlib.backends.backend_wxagg', 'numpy']

includefiles = ['./data/','./images/','./html/','./locale/','./logs/']

binpathincludes = []

if sys.platform == "linux2":
     binpathincludes += ["/usr/lib64"]
     binpathincludes += ["/usr/lib"]

base = 'Console'

options = {"path": path,
            "includes": includes,
            "excludes": excludes,
            "packages": packages,
            "include_files": includefiles,
            "bin_path_includes": binpathincludes,
            "optimize": 0,
            "silent": True
            }

executables = [
     Executable('MyProjetc.py', base=base)
]

setup(name='MyProject',
       version='1.0',
       description='My Project',
       executables=executables,
       options={'build_exe': options}
       )

but when I try to run my binary program on an empty system opensuse (without
wxPython installed on it), I get this error :

Traceback (most recent call last):
File "/usr/lib64/python2.7/site-packages/cx_Freeze/initscripts/Console.py", line 27, in <module>
File "JustConsum.py", line 4, in <module>
File "/usr/lib64/python2.7/site-packages/wx-3.0-gtk2/wx/__init__.py", line 45, in <module>
File "/usr/lib64/python2.7/site-packages/wx-3.0-gtk2/wx/_core.py", line 4, in <module>
File "ExtensionLoader_wx__core_.py", line 22, in <module>
File "ExtensionLoader_wx__core_.py", line 14, in __bootstrap__
ImportError: libwx_gtk2u_adv-suse.so.1: cannot open shared object file: No such file or directory

But that file "libwx_gtk2u_adv-suse.so.1" is
indeed at root of the directory containing the binaries files :

-rwxrwx--- 1 regis users  1918960 25 oct.   2015 libwx_gtk2u_adv-suse.so.1
-rwxrwx--- 1 regis users   575528 25 oct.   2015 libwx_gtk2u_aui-suse.so.1
-rwxrwx--- 1 regis users  5780640 25 oct.   2015 libwx_gtk2u_core-suse.so.1

Any idea on what's going on ?

Thx a lot

Body:
So I searched on the internet, and found out the " patchelf " command.
As my binary files (generated with cx_Freeze) were in the same directory than my executable file, I created the script :

for i in *so*
do
     patchelf --set-rpath '.' $i
done

Since, my standalone application can be launched on an "empty" openSuse system...

Note:

this solution works with cx_Freeze 4.3.x, but don't with the 5.x versions

I successfully created standalone application (for this same program) on various other linux platform (Debian, Mint, Ubuntu, Mageia, Fedora, CentOS) without any kind of problem.

Only openSuse has needed this kind of operation so my standalone program can work out... I can't explain why.

May be this post could help some else.


问:
Links in navbar with Rails and Bootstrap
Say I have a navbar:

```<code><ul class="nav navbar-nav">
  <li><%= link_to 'Item 1', item1_path %>
  <li><%= link_to 'Item 2', item2_path %>
  ...
</code>```

But this way current menu item is also a link. How do I make it into a span, preserving appearance? Which doesn't look like a good options, since in this case I need to duplicate bootstrap's styles. Or make it look like a menu item without it pointing to any page?

答:
A link_to method will always render an  tag, but you can render a  inside of the  tag if you use link_to ... do

This is an example taken from this documentation

```<code><%= link_to(@profile) do %>
  <strong><%= @profile.name %></strong> -- <span>Check it out!</span>
<% end %>
<!-- which renders -->
<a href="/profiles/1">
       <strong>David</strong> -- <span>Check it out!</span>
</a>
</code>```

Body:
Say I have a navbar:

<%= link_to 'Item 1', item1_path %>

<%= link_to 'Item 2', item2_path %>
  ...

But this way current menu item is also a link. How do I make it into a span, preserving appearance? Which doesn't look like a good options, since in this case I need to duplicate bootstrap's styles. Or make it look like a menu item without it pointing to any page?

Body:
A link_to method will always render an <a> tag, but you can render a <span> inside of the <a> tag if you use link_to ... do

This is an example taken from this documentation

<%= link_to(@profile) do %>
  <strong><%= @profile.name %></strong> -- <span>Check it out!</span>
<% end %>
<!-- which renders -->
<a href="/profiles/1">
       <strong>David</strong> -- <span>Check it out!</span>
</a>


问:
Get rid of warnings in List<GenericClass<T>>.toArray()
Another one of those how do I do toArray() with no warnings questions, but it's different from most of the ones posted here.

How do I rewrite the method implementation (without changing the method signature) to make it compile without warning?

The apparent difficulty here is that the Class information for T is not available during runtime. However, the return type is an erased type during runtime too, so there's no really reason that this cannot be done. So, how do I do this if want to enforce compile-time type safety?

Thank you

```<code><T> GenericClass<T>[] toGenericArray(List<GenericClass<T>> list) {
    return list.toArray(new GenericClass[0]);
}
</code>```

答:
You can't.  Because Arrays are covariant, it is impossible to have compile time safety for an array that's holding a parameterized type.  (unless you use < ? > which is legal.)

This will always be legal:

```<code>GenericClass<String>[] array = new GenericClass[1];
Object[] brokenArray = array;
brokenArray[0] = new GenericClass<Integer>();
String value = array[0].getGenericValue(); //kaboom
</code>```

Compiler is unable to protect you from that, so it forces you to acknowledge/suppress that there's a warning.

ContentLicense: CC BY-SA 2.5

Body:
Another one of those how do I do toArray() with no warnings questions, but it's different from most of the ones posted here.

How do I rewrite the method implementation (without changing the method signature) to make it compile without warning?

The apparent difficulty here is that the Class information for T is not available during runtime. However, the return type is an erased type during runtime too, so there's no really reason that this cannot be done. So, how do I do this if want to enforce compile-time type safety?

Thank you

<T> GenericClass<T>[] toGenericArray(List<GenericClass<T>> list) {
    return list.toArray(new GenericClass[0]);
}

Body:
You can't.  Because Arrays are covariant, it is impossible to have compile time safety for an array that's holding a parameterized type.  (unless you use < ? > which is legal.)

This will always be legal:

GenericClass<String>[] array = new GenericClass[1];
Object[] brokenArray = array;
brokenArray[0] = new GenericClass<Integer>();
String value = array[0].getGenericValue(); //kaboom

Compiler is unable to protect you from that, so it forces you to acknowledge/suppress that there's a warning.


问:
h2o checkpoint parameter change error - but no parameter changed??
I am trying to export the weights and biases of a "model" in which I did not originally train the model with "export_weights_and_biases = TRUE"

Therefore, I'd like to try to checkpoint the model and try to export_weights_and_biases = TRUE in a new "model2".

However, despite not changing any of the parameters - and ensuring that nfolds=10 just as in the original "model", the checkpoint model continues to return a parameter change error almost immediately (h2o version 3.10.4.6):

```<code>water.exceptions.H2OIllegalArgumentException: Cannot change parameter: '_nfolds': 10 -> 0

water.exceptions.H2OIllegalArgumentException: Cannot change parameter: '_nfolds': 10 -> 0
    at hex.deeplearning.DeepLearningModel$DeepLearningParameters$Sanity.checkIfParameterChangeAllowed(DeepLearningModel.java:2078)
    at hex.deeplearning.DeepLearning$DeepLearningDriver.buildModel(DeepLearning.java:249)
    at hex.deeplearning.DeepLearning$DeepLearningDriver.computeImpl(DeepLearning.java:211)
    at hex.ModelBuilder$Driver.compute2(ModelBuilder.java:169)
    at hex.deeplearning.DeepLearning$DeepLearningDriver.compute2(DeepLearning.java:204)
    at water.H2O$H2OCountedCompleter.compute(H2O.java:1241)
    at jsr166y.CountedCompleter.exec(CountedCompleter.java:468)
    at jsr166y.ForkJoinTask.doExec(ForkJoinTask.java:263)
    at jsr166y.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:974)
    at jsr166y.ForkJoinPool.runWorker(ForkJoinPool.java:1477)
    at jsr166y.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:104)

Error: water.exceptions.H2OIllegalArgumentException: Cannot change parameter: '_nfolds': 10 -> 0
</code>```

Any ideas how to resolve this issue? All I'm trying to do is obtain all the weights and biases of my original "model".

Thank you!

答:
I resolved this on my own:

1) Checkpoint can only be done if original model:

used no CV

or used CV but had fold assignment set to Modulo

and of course if other certain parameters are not changed such as nfolds.

2) Would still like to know how it would be possible to extract the weights and biases of my model if possible. Thank you.

Body:
I am trying to export the weights and biases of a "model" in which I did not originally train the model with "export_weights_and_biases = TRUE"

Therefore, I'd like to try to checkpoint the model and try to export_weights_and_biases = TRUE in a new "model2".

However, despite not changing any of the parameters - and ensuring that nfolds=10 just as in the original "model", the checkpoint model continues to return a parameter change error almost immediately (h2o version 3.10.4.6):

water.exceptions.H2OIllegalArgumentException: Cannot change parameter: '_nfolds': 10 -> 0

water.exceptions.H2OIllegalArgumentException: Cannot change parameter: '_nfolds': 10 -> 0
    at hex.deeplearning.DeepLearningModel$DeepLearningParameters$Sanity.checkIfParameterChangeAllowed(DeepLearningModel.java:2078)
    at hex.deeplearning.DeepLearning$DeepLearningDriver.buildModel(DeepLearning.java:249)
    at hex.deeplearning.DeepLearning$DeepLearningDriver.computeImpl(DeepLearning.java:211)
    at hex.ModelBuilder$Driver.compute2(ModelBuilder.java:169)
    at hex.deeplearning.DeepLearning$DeepLearningDriver.compute2(DeepLearning.java:204)
    at water.H2O$H2OCountedCompleter.compute(H2O.java:1241)
    at jsr166y.CountedCompleter.exec(CountedCompleter.java:468)
    at jsr166y.ForkJoinTask.doExec(ForkJoinTask.java:263)
    at jsr166y.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:974)
    at jsr166y.ForkJoinPool.runWorker(ForkJoinPool.java:1477)
    at jsr166y.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:104)

Error: water.exceptions.H2OIllegalArgumentException: Cannot change parameter: '_nfolds': 10 -> 0

Any ideas how to resolve this issue? All I'm trying to do is obtain all the weights and biases of my original "model".

Thank you!


问:
Get IndexPath of CollectionViewCell outside of Cell
First of all I am a newbie in swift, so be gentle. I have a problem fetching the indexPath of the cell outside of the cell. I want to get that index path to a function and use it to send the content to another view. The image was created programatically in the cell, it has a tap gesture recogniser sending to this function (where "myIndex" is defined as an Int : var myIndex = 0):

```<code>// tap image to go at the indexpath of the user
func imageTapped(tapGestureRecognizer: UITapGestureRecognizer) {
   print("image tapped")

    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let secondViewController = storyboard.instantiateViewController(withIdentifier: "patientProfile") as! PatientProfileVC
    secondViewController.userID = posts[myIndex].userID
    secondViewController.patientName = posts[myIndex].author

    print("Passed data to the other view")

    self.show(secondViewController, sender: self)

}
</code>```

I know that I could use didSelectItem at IndexPath where I also have the declaration of the myIndex but I have something that will be triggered from a segue there:

```<code>//standard functon for item selected
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

    //get the index of the cell
    myIndex = indexPath.row

    print("Cell is selected")

    //perform the segue
    self.performSegue(withIdentifier: "CommentsVC", sender: self)
    print(myIndex)

}
</code>```

and my perform for segue looks like this:` override

func prepare(for segue: UIStoryboardSegue, sender: Any?) {

```<code>    print("Segue Initiated")
    feed.navigationItem.title = nil

    //if segue.destination is CommentsFullVC{
        print("Comments segue initiated")
        let secondViewController = segue.destination as! CommentsFullVC
        secondViewController.questionData = posts[myIndex].postContent
        secondViewController.authorName = posts[myIndex].author
        secondViewController.date = posts[myIndex].normalDate
        secondViewController.profileImagePath = posts[myIndex].pathToImage
        secondViewController.typeOfClinic = posts[myIndex].clinic
        secondViewController.postID = posts[myIndex].postID
        secondViewController.followersForPost = posts[myIndex].followers

}
</code>```

So my question is, how do I pass those 2 fields to the other view without using prepareForSegue? I am struggling with this for 20 hours now and still can not figure it out.

```<code>secondViewController.userID = posts[myIndex].userID
secondViewController.patientName = posts[myIndex].author
</code>```

UPDATE: Got it to work thanks to Jose answer, now it looks like this... in case anybody has the same problem as I had.

```<code> // tap image to go at the indexpath of the user
func imageTapped(tapGestureRecognizer: UITapGestureRecognizer) {
   print("image tapped")

    let pointInCollectionView = tapGestureRecognizer.location(in: collectionView)
    let indexPath = collectionView?.indexPathForItem(at: pointInCollectionView)
    print(indexPath!)

    // this one works - show segue
    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let secondViewController = storyboard.instantiateViewController(withIdentifier: "patientProfile") as! PatientProfileVC
    secondViewController.userID = posts[(indexPath?.row)!].userID
    secondViewController.patientName = posts[(indexPath?.row)!].author

    print("Passed data to the other view")

    self.show(secondViewController, sender: self)

}
</code>```

答:
Get the location of the tapGestureRecognizer in the collectionView and then the indexPath at the given location

```<code>let pointInCollectionView = tapGestureRecognizer.location(in: collectionView)
let indexPath = collectionView.indexPathForItem(at: pointInCollectionView)
</code>```

Body:
First of all I am a newbie in swift, so be gentle. I have a problem fetching the indexPath of the cell outside of the cell. I want to get that index path to a function and use it to send the content to another view. The image was created programatically in the cell, it has a tap gesture recogniser sending to this function (where "myIndex" is defined as an Int : var myIndex = 0):

// tap image to go at the indexpath of the user
func imageTapped(tapGestureRecognizer: UITapGestureRecognizer) {
   print("image tapped")

    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let secondViewController = storyboard.instantiateViewController(withIdentifier: "patientProfile") as! PatientProfileVC
    secondViewController.userID = posts[myIndex].userID
    secondViewController.patientName = posts[myIndex].author

    print("Passed data to the other view")

    self.show(secondViewController, sender: self)

}

I know that I could use didSelectItem at IndexPath where I also have the declaration of the myIndex but I have something that will be triggered from a segue there:

//standard functon for item selected
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

    //get the index of the cell
    myIndex = indexPath.row

    print("Cell is selected")

    //perform the segue
    self.performSegue(withIdentifier: "CommentsVC", sender: self)
    print(myIndex)

}

and my perform for segue looks like this:` override

func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    print("Segue Initiated")
    feed.navigationItem.title = nil

    //if segue.destination is CommentsFullVC{
        print("Comments segue initiated")
        let secondViewController = segue.destination as! CommentsFullVC
        secondViewController.questionData = posts[myIndex].postContent
        secondViewController.authorName = posts[myIndex].author
        secondViewController.date = posts[myIndex].normalDate
        secondViewController.profileImagePath = posts[myIndex].pathToImage
        secondViewController.typeOfClinic = posts[myIndex].clinic
        secondViewController.postID = posts[myIndex].postID
        secondViewController.followersForPost = posts[myIndex].followers

}

So my question is, how do I pass those 2 fields to the other view without using prepareForSegue? I am struggling with this for 20 hours now and still can not figure it out.

secondViewController.userID = posts[myIndex].userID
secondViewController.patientName = posts[myIndex].author

UPDATE: Got it to work thanks to Jose answer, now it looks like this... in case anybody has the same problem as I had.

 // tap image to go at the indexpath of the user
func imageTapped(tapGestureRecognizer: UITapGestureRecognizer) {
   print("image tapped")

    let pointInCollectionView = tapGestureRecognizer.location(in: collectionView)
    let indexPath = collectionView?.indexPathForItem(at: pointInCollectionView)
    print(indexPath!)

    // this one works - show segue
    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let secondViewController = storyboard.instantiateViewController(withIdentifier: "patientProfile") as! PatientProfileVC
    secondViewController.userID = posts[(indexPath?.row)!].userID
    secondViewController.patientName = posts[(indexPath?.row)!].author

    print("Passed data to the other view")

    self.show(secondViewController, sender: self)

}

Body:
Get the location of the tapGestureRecognizer in the collectionView and then the indexPath at the given location

let pointInCollectionView = tapGestureRecognizer.location(in: collectionView)
let indexPath = collectionView.indexPathForItem(at: pointInCollectionView)


问:
Getting Max date from the given two dates in mysql
I have a table with below structure and data.

```<code>id ean           Control_date qty
1  4046228081410 26.05.2017   568
2  4046228081410 05.06.2017   900
</code>```

My expected result would be like below

```<code>2  4046228081410 05.06.2017   1468
</code>```

To acheive this i am using the below query

```<code> SELECT EAN,Control_date,SUM(Qty) AS Qty FROM mytable WHERE
(STR_TO_DATE(`Control_date`,'%d.%m.%Y') <= STR_TO_DATE('03.06.2017','%d.%m.%Y')
OR
STR_TO_DATE(`Control_date`, '%d.%m.%Y') <= DATE_ADD(STR_TO_DATE('03.06.2017', '%d.%m.%Y'), INTERVAL 7 DAY))
AND ean = 4046228081410
</code>```

Here i need to sum up the qty where control date< today date and control date > today date and should be less than todaydate + 7 days . Here 2nd control date is 05.06.2017 and greater than today date and less than (03.05.2017 +7 days)
But always i am getting where contorl date is less than today date.

```<code>1  4046228081410 26.05.2017   1468
</code>```

But i need data with control date 05.06.2017.
Any help would be greatly appreciated.

答:
You have a typo in your SQL statement, and if you do not want today's date, then use less and greater</p>

```<code>SELECT EAN,Control_date,SUM(Qty) AS Qty FROM mytable WHERE
(STR_TO_DATE(`Control_date`,'%d.%m.%Y') **<** STR_TO_DATE('03.06.2017','%d.%m.%Y')
OR
STR_TO_DATE(`Control_date`, '%d.%m.%Y') **>** DATE_ADD(STR_TO_DATE('03.06.2017', '%d.%m.%Y'), INTERVAL 7 DAY))
AND ean = 4046228081410
</code>```

Body:
I have a table with below structure and data.

id ean           Control_date qty
1  4046228081410 26.05.2017   568
2  4046228081410 05.06.2017   900

My expected result would be like below

2  4046228081410 05.06.2017   1468

To acheive this i am using the below query

 SELECT EAN,Control_date,SUM(Qty) AS Qty FROM mytable WHERE
(STR_TO_DATE(`Control_date`,'%d.%m.%Y') <= STR_TO_DATE('03.06.2017','%d.%m.%Y')
OR
STR_TO_DATE(`Control_date`, '%d.%m.%Y') <= DATE_ADD(STR_TO_DATE('03.06.2017', '%d.%m.%Y'), INTERVAL 7 DAY))
AND ean = 4046228081410

Here i need to sum up the qty where control date< today date and control date > today date and should be less than todaydate + 7 days . Here 2nd control date is 05.06.2017 and greater than today date and less than (03.05.2017 +7 days)
But always i am getting where contorl date is less than today date.

1  4046228081410 26.05.2017   1468

But i need data with control date 05.06.2017.
Any help would be greatly appreciated.

Body:
You have a typo in your SQL statement, and if you do not want today's date, then use less and greater

SELECT EAN,Control_date,SUM(Qty) AS Qty FROM mytable WHERE
(STR_TO_DATE(`Control_date`,'%d.%m.%Y') **<** STR_TO_DATE('03.06.2017','%d.%m.%Y')
OR
STR_TO_DATE(`Control_date`, '%d.%m.%Y') **>** DATE_ADD(STR_TO_DATE('03.06.2017', '%d.%m.%Y'), INTERVAL 7 DAY))
AND ean = 4046228081410


问:
Filtering out data in Spark dataframe in Scala
I have a dataframe df, which contains below data:

```<code>**customers**   **product**   **Val_id**
     1               A            1
     2               B            X
     3               C
     4               D            Z
</code>```

I have successfully filtered for data where column val_id is blank

```<code>df.where(col("val_id").isin(""))
</code>```

But I am not able to figure out a way to filter data where column val_id is not blank, i tried something like below, but did not work for me:

```<code>df.where(col("val_id").isnotin(""))
</code>```

Can anyone please help me to achieve it using Spark Scala.

答:
If column type is String:

```<code>df.where(trim(col("val_id")) != "")
</code>```

Body:
I have a dataframe df, which contains below data:

**customers**   **product**   **Val_id**
     1               A            1
     2               B            X
     3               C
     4               D            Z

I have successfully filtered for data where column val_id is blank

df.where(col("val_id").isin(""))

But I am not able to figure out a way to filter data where column val_id is not blank, i tried something like below, but did not work for me:

df.where(col("val_id").isnotin(""))

Can anyone please help me to achieve it using Spark Scala.

Body:
If column type is String:

df.where(trim(col("val_id")) != "")


问:
Wrong ruby path used in rake task executed as cron through whenever
I am trying to use the whenever gem to execute a couple of rake tasks.  It appears to set up the cron tasks correctly - info here is from the mail output that is produced. Here's an example of the command executed:

```<code>/bin/bash -l -c 'cd /path/to/deployed/app && RAILS_ENV=production
</code>```

rake clean:my:task --silent'

And here are some of the environment variables:

```<code>X-Cron-Env: <SHELL=/bin/sh>
X-Cron-Env: <PATH=/usr/bin:/bin>
</code>```

And here is the error that follows:

```<code>/bin/bash: /usr/bin/rake: /usr/bin/ruby: bad interpreter: No such file or directory
</code>```

When i'm logged in i can run these rake tasks from the same directory, but when i run

```<code>which ruby
</code>```

i get

```<code>/usr/local/bin/ruby
</code>```

There does appear to be a 'rake' in /usr/bin, but running

```<code>/usr/bin/rake -T
</code>```

gives me the same error:

```<code>-bash: /usr/bin/rake: /usr/bin/ruby: bad interpreter: No such file or directory
</code>```

What would be the best way to resolve this?

答:
Is /usr/local/bin/ in your path?  When you ran which ruby you got /usr/local/bin/ruby but when you run rake it's looking for /usr/bin/ruby

Or you could just symlink ruby like:

sudo ln -s /usr/local/bin/ruby /usr/bin/.

Body:
I am trying to use the whenever gem to execute a couple of rake tasks.  It appears to set up the cron tasks correctly - info here is from the mail output that is produced. Here's an example of the command executed:

/bin/bash -l -c 'cd /path/to/deployed/app && RAILS_ENV=production

rake clean:my:task --silent'

And here are some of the environment variables:

X-Cron-Env: <SHELL=/bin/sh>
X-Cron-Env: <PATH=/usr/bin:/bin>

And here is the error that follows:

/bin/bash: /usr/bin/rake: /usr/bin/ruby: bad interpreter: No such file or directory

When i'm logged in i can run these rake tasks from the same directory, but when i run

which ruby

i get

/usr/local/bin/ruby

There does appear to be a 'rake' in /usr/bin, but running

/usr/bin/rake -T

gives me the same error:

-bash: /usr/bin/rake: /usr/bin/ruby: bad interpreter: No such file or directory

What would be the best way to resolve this?


问:
Issues in Xunit.Assert.Collection - C#
I have a Class Library, it contains the following Model and Method

Model:

```<code>public class Employee {
    public int EmpId { get; set; }
    public string Name { get; set; }
}
</code>```

Method:

```<code>public class EmployeeService {
    public List<Employee> GetEmployee() {
        return new List<Employee>() {
            new Employee() { EmpId = 1, Name = "John" },
            new Employee() { EmpId = 2, Name = "Albert John" },
            new Employee() { EmpId = 3, Name = "Emma" },
        }.Where(m => m.Name.Contains("John")).ToList();
    }
}
</code>```

I have a Test Method

```<code>[TestMethod()]
public void GetEmployeeTest() {
    EmployeeService obj = new EmployeeService();
    var result = obj.GetEmployee();
    Xunit.Assert.Collection<Employee>(result, m => Xunit.Assert.Contains("John",m.Name));
}
</code>```

I got an Exception message

```<code>Assert.Collection() Failure
Collection: [Employee { EmpId = 1, Name = "John" }, Employee { EmpId = 2, Name = "Albert John" }]
Expected item count: 1
Actual item count:   2
</code>```

My requirement is to check all the items.Name should contain the sub string "John". Kindly assist me how to check using Xunit.Assert.Collection

答:
It appears that Assert.Collection only uses each element inspector once. So, for your test, the following works:

If the sequence result has exactly two elements:

```<code>[Fact]
public void GetEmployeeTest()
{
    EmployeeService obj = new EmployeeService();
    var result = obj.GetEmployee();

    Assert.Collection(result, item => Assert.Contains("John", item.Name),
                              item => Assert.Contains("John", item.Name));
}
</code>```

If there are many elements, changing the Assert to

Assert.All(result, item => Assert.Contains("John", item.Name));
```

should give you the result you are expecting.

Title: Issues in Xunit.Assert.Collection - C#

Body:
I have a Class Library, it contains the following Model and Method

Model:

public class Employee {
    public int EmpId { get; set; }
    public string Name { get; set; }
}

Method:

public class EmployeeService {
    public List<Employee> GetEmployee() {
        return new List<Employee>() {
            new Employee() { EmpId = 1, Name = "John" },
            new Employee() { EmpId = 2, Name = "Albert John" },
            new Employee() { EmpId = 3, Name = "Emma" },
        }.Where(m => m.Name.Contains("John")).ToList();
    }
}

I have a Test Method

[TestMethod()]
public void GetEmployeeTest() {
    EmployeeService obj = new EmployeeService();
    var result = obj.GetEmployee();
    Xunit.Assert.Collection<Employee>(result, m => Xunit.Assert.Contains("John",m.Name));
}

I got an Exception message

Assert.Collection() Failure
Collection: [Employee { EmpId = 1, Name = "John" }, Employee { EmpId = 2, Name = "Albert John" }]
Expected item count: 1
Actual item count:   2

My requirement is to check all the items.Name should contain the sub string "John". Kindly assist me how to check using Xunit.Assert.Collection

Body:
It appears that Assert.Collection only uses each element inspector once. So, for your test, the following works:

If the sequence result has exactly two elements:

[Fact]
public void GetEmployeeTest()
{
    EmployeeService obj = new EmployeeService();
    var result = obj.GetEmployee();

    Assert.Collection(result, item => Assert.Contains("John", item.Name),
                              item => Assert.Contains("John", item.Name));
}

If there are many elements, changing the Assert to

Assert.All(result, item => Assert.Contains("John", item.Name));

should give you the result you are expecting.