问:
How do I implement a infinite list in Flex (hero)
I'm new to Flex/ActionScript (.NET/Java has been my main playground so far).
I'm trying to build a Flex app that has a list that is meant to look and behave like an infinite list (of items - which can be any object). The idea is that the user should be able to scroll up or down and never reach the end of the list in either direction.

An example would be a list of numbers. Scrolling up will show negative numbers; scrolling down will show positive ones. Now, my list is a simple Flex Spark list (using Flex Hero).
It is bound to a data provider that is an ArrayList.

My initial idea was to listen to the scroll event and add/remove items as needed. However, in the current build of Flex Hero, there is a bug that doesn't raise scroll events for vertical scrollbars sometimes (http://bugs.adobe.com/jira/browse/SDK-26533).

So, I'm using the workaround suggested in the link above (i.e listening to the  propertyChanged event of the list's scroller's viewport. The event though only gives me the current verticalScrollPosition.

And it looks like the default spark list supports smooth scrolling and raises the event many times before the list scrolling comes to a standstill (it is a nice visual effect).

Now, I need to :

Figure out whether it is scrolling up or down (how do I do that?)

Figure out which items are visible. I can get this from:

list.dataGroup.getItemIndicesInView()

Add/remove items as needed, so that the user can scroll up and down forever, never reaching the end of the list in either direction.

I've tried the following code but it doesn't work. (comments in code).

Any Flex experts out there? Please help.

```<code>        import mx.collections.ArrayList;
        import mx.core.INavigatorContent;
        import mx.events.FlexEvent;
        import mx.events.PropertyChangeEvent;

        var listData:ArrayList;
        var firstItemInView:int = 0;
        var lastItemInView:int = 0;
        var count = 0;

                    //gets the currently visible item indices (first and last)
        private function getVisibleIndices():Vector.<int> {
            var ind:Vector.<int> = new Vector.<int>(2, true);
            ind[0] = firstItemInView;
            ind[1] = lastItemInView;
            return ind;
        }

        protected function view_creationCompleteHandler(event:FlexEvent):void {

                            //create an initialise list data
            listData = new ArrayList();
            for(var i:int = 0; i < 6; i++){
                listData.addItemAt(i, i);
            }
            infiniteList.dataProvider = listData;

            updateIndices();

            infiniteList.scroller.viewport.addEventListener(PropertyChangeEvent.PROPERTY_CHANGE, infiniteList_VerticalScroll_PropertyChanged);
        }

                    //get the indices visible from the list's data group
        private function getNewIndices():Vector.<int> {
            var indices:Vector.<int> = new Vector.<int>(2, true);
            var indicesInView:Vector.<int> = infiniteList.dataGroup.getItemIndicesInView();
            if (indicesInView.length > 0){
                indices[0] = indicesInView[0];
            }
            if (indicesInView.length > 1){
                indices[1] = indicesInView[indicesInView.length - 1];
            }
            return indices;
        }

        private function updateIndices():void {
            var indices:Vector.<int> = getNewIndices();
            if (indices.length > 0){
                firstItemInView = indices[0];
                if (indices.length > 1){
                    lastItemInView = indices[1];
                }
            }
        }

        protected function leftCalendar_VerticalScroll_PropertyChanged(event:PropertyChangeEvent):void {

            switch (event.property){
                case "verticalScrollPosition":

                    var indices:Vector.<int> = getNewIndices();
                    var oldIndices:Vector.<int> = getVisibleIndices();

                    var newNum:Number;

                    if (indices[1] - indices[0] == 2 && (oldIndices[0] != indices[0] && oldIndices[1] != indices[1])){
                        //a new item is in view. did we scroll up or down?
                        if (oldIndices[0] < indices[0]){
                            count++;
                            trace(count + " up : old[" + oldIndices[0] + "," + oldIndices[1] + "], new[" + indices[0] + "," + indices[1] + "]");
                            //newNum = Number(listData.getItemAt(listData.length - 1)) + 1;
                            //trace("new number to add: " + newNum);
                            //trace("todo remove: " + listData.getItemAt(0));
                            fixItems({ addAt : "top", removeAt : "bottom", newValue : newNum});

                        } else {
                            trace("down : old[" + oldIndices[0] + "," + oldIndices[1] + "], new[" + indices[0] + "," + indices[1] + "]");
                            fixItems({ addAt : "bottom", removeAt : "top", newValue : newNum});
                        }

                        //update indices:
                        updateIndices();
                        var newOnes = getVisibleIndices(); //seems to be getting the new ones, but the next occurance of this event handler doesn't pick up the new values! why?
                        trace(count + " current[" + newOnes[0] + ", " + newOnes[1] + "]");
                    }

                    break;
            }
        }

        protected function fixItems(data:Object):void {
            var item:Object;

            //add a new item
            if (data.addAt == "top"){
                listData.addItemAt(data.newValue, 0);
            } else {
                listData.addItem(data.newValue);
            }

            //remove one of the existing ones
            if (data.removeAt == "top"){
                item = listData.getItemAt(0);
                trace("removing " + item);
                listData.removeItemAt(0);
            } else {
                item = listData.getItemAt(listData.length - 1);
                trace("removing " + item);
                listData.removeItemAt(listData.length - 1);
            }
            updateIndices();
        }
</code>```

答:
I think you need to create your custom List control, which circulate arraycollection/arraylist item for UI,
ArrayCollection/Array/ArrayList should only be use to hold data like liner list of items, and list Control should display items in circular fashion

EDITED
I am trying to ans your question modifying data in list and direction of scroll
hopefully this will help

```<code><?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
    <mx:Script>
        <![CDATA[
            import mx.controls.Alert;
            import mx.events.ScrollEvent;

            [Bindable]
            private var arr:Array = new Array(0,1,2,3,4,5);

            private var lastScrollPostion:int =0;
            private var isScrollingUp:Boolean = false;
            private function ltClicked(event:MouseEvent):void
            {
                arr.unshift(arr[0]-1);
                lst.dataProvider = arr;
            }
            private function rtClicked(event:MouseEvent):void
            {
                arr.push(arr[arr.length-1] +1);
                lst.dataProvider = arr;
            }

            private function scrolled(event:ScrollEvent):void
            {
                if (lastScrollPostion < event.position)
                {
                    isScrollingUp = false;
                }
                else
                {
                    isScrollingUp = true;
                }
                lastScrollPostion = event.position;
                Alert.show("isScrollingUp : "+isScrollingUp.toString());
            }

        ]]>
    </mx:Script>
    <mx:VBox>
        <mx:List
            id="lst"
            width="100%"
            dataProvider="{arr}"
            scroll="{scrolled(event)}"
            />
        <mx:HBox>
            <mx:Button id="lt" label="<<" click="{ltClicked(event)}"/>
            <mx:Button id="rt" label=">>" click="{rtClicked(event)}"/>
        </mx:HBox>

    </mx:VBox>

</mx:Application>
</code>```

NOTE
Function ltClicked and rtClicked are modifying List data
and scrolled is used get to direction

I think better way of doing this is extend List control to get direction and scroll position
and manipulate Array to add or remove items in list

Body:
I'm new to Flex/ActionScript (.NET/Java has been my main playground so far).
I'm trying to build a Flex app that has a list that is meant to look and behave like an infinite list (of items - which can be any object). The idea is that the user should be able to scroll up or down and never reach the end of the list in either direction.

An example would be a list of numbers. Scrolling up will show negative numbers; scrolling down will show positive ones. Now, my list is a simple Flex Spark list (using Flex Hero).
It is bound to a data provider that is an ArrayList.

My initial idea was to listen to the scroll event and add/remove items as needed. However, in the current build of Flex Hero, there is a bug that doesn't raise scroll events for vertical scrollbars sometimes (http://bugs.adobe.com/jira/browse/SDK-26533).

So, I'm using the workaround suggested in the link above (i.e listening to the  propertyChanged event of the list's scroller's viewport. The event though only gives me the current verticalScrollPosition.

And it looks like the default spark list supports smooth scrolling and raises the event many times before the list scrolling comes to a standstill (it is a nice visual effect).

Now, I need to :

Figure out whether it is scrolling up or down (how do I do that?)

Figure out which items are visible. I can get this from:

list.dataGroup.getItemIndicesInView()

Add/remove items as needed, so that the user can scroll up and down forever, never reaching the end of the list in either direction.

I've tried the following code but it doesn't work. (comments in code).

Any Flex experts out there? Please help.

        import mx.collections.ArrayList;
        import mx.core.INavigatorContent;
        import mx.events.FlexEvent;
        import mx.events.PropertyChangeEvent;

        var listData:ArrayList;
        var firstItemInView:int = 0;
        var lastItemInView:int = 0;
        var count = 0;

                    //gets the currently visible item indices (first and last)
        private function getVisibleIndices():Vector.<int> {
            var ind:Vector.<int> = new Vector.<int>(2, true);
            ind[0] = firstItemInView;
            ind[1] = lastItemInView;
            return ind;
        }

        protected function view_creationCompleteHandler(event:FlexEvent):void {

                            //create an initialise list data
            listData = new ArrayList();
            for(var i:int = 0; i < 6; i++){
                listData.addItemAt(i, i);
            }
            infiniteList.dataProvider = listData;

            updateIndices();

            infiniteList.scroller.viewport.addEventListener(PropertyChangeEvent.PROPERTY_CHANGE, infiniteList_VerticalScroll_PropertyChanged);
        }

                    //get the indices visible from the list's data group
        private function getNewIndices():Vector.<int> {
            var indices:Vector.<int> = new Vector.<int>(2, true);
            var indicesInView:Vector.<int> = infiniteList.dataGroup.getItemIndicesInView();
            if (indicesInView.length > 0){
                indices[0] = indicesInView[0];
            }
            if (indicesInView.length > 1){
                indices[1] = indicesInView[indicesInView.length - 1];
            }
            return indices;
        }

        private function updateIndices():void {
            var indices:Vector.<int> = getNewIndices();
            if (indices.length > 0){
                firstItemInView = indices[0];
                if (indices.length > 1){
                    lastItemInView = indices[1];
                }
            }
        }

        protected function leftCalendar_VerticalScroll_PropertyChanged(event:PropertyChangeEvent):void {

            switch (event.property){
                case "verticalScrollPosition":

                    var indices:Vector.<int> = getNewIndices();
                    var oldIndices:Vector.<int> = getVisibleIndices();

                    var newNum:Number;

                    if (indices[1] - indices[0] == 2 && (oldIndices[0] != indices[0] && oldIndices[1] != indices[1])){
                        //a new item is in view. did we scroll up or down?
                        if (oldIndices[0] < indices[0]){
                            count++;
                            trace(count + " up : old[" + oldIndices[0] + "," + oldIndices[1] + "], new[" + indices[0] + "," + indices[1] + "]");
                            //newNum = Number(listData.getItemAt(listData.length - 1)) + 1;
                            //trace("new number to add: " + newNum);
                            //trace("todo remove: " + listData.getItemAt(0));
                            fixItems({ addAt : "top", removeAt : "bottom", newValue : newNum});

                        } else {
                            trace("down : old[" + oldIndices[0] + "," + oldIndices[1] + "], new[" + indices[0] + "," + indices[1] + "]");
                            fixItems({ addAt : "bottom", removeAt : "top", newValue : newNum});
                        }

                        //update indices:
                        updateIndices();
                        var newOnes = getVisibleIndices(); //seems to be getting the new ones, but the next occurance of this event handler doesn't pick up the new values! why?
                        trace(count + " current[" + newOnes[0] + ", " + newOnes[1] + "]");
                    }

                    break;
            }
        }

        protected function fixItems(data:Object):void {
            var item:Object;

            //add a new item
            if (data.addAt == "top"){
                listData.addItemAt(data.newValue, 0);
            } else {
                listData.addItem(data.newValue);
            }

            //remove one of the existing ones
            if (data.removeAt == "top"){
                item = listData.getItemAt(0);
                trace("removing " + item);
                listData.removeItemAt(0);
            } else {
                item = listData.getItemAt(listData.length - 1);
                trace("removing " + item);
                listData.removeItemAt(listData.length - 1);
            }
            updateIndices();
        }

Body:
I think you need to create your custom List control, which circulate arraycollection/arraylist item for UI,
ArrayCollection/Array/ArrayList should only be use to hold data like liner list of items, and list Control should display items in circular fashion

EDITED
I am trying to ans your question modifying data in list and direction of scroll
hopefully this will help

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
    <mx:Script>
        <![CDATA[
            import mx.controls.Alert;
            import mx.events.ScrollEvent;

            [Bindable]
            private var arr:Array = new Array(0,1,2,3,4,5);

            private var lastScrollPostion:int =0;
            private var isScrollingUp:Boolean = false;
            private function ltClicked(event:MouseEvent):void
            {
                arr.unshift(arr[0]-1);
                lst.dataProvider = arr;
            }
            private function rtClicked(event:MouseEvent):void
            {
                arr.push(arr[arr.length-1] +1);
                lst.dataProvider = arr;
            }

            private function scrolled(event:ScrollEvent):void
            {
                if (lastScrollPostion < event.position)
                {
                    isScrollingUp = false;
                }
                else
                {
                    isScrollingUp = true;
                }
                lastScrollPostion = event.position;
                Alert.show("isScrollingUp : "+isScrollingUp.toString());
            }

        ]]>
    </mx:Script>
    <mx:VBox>
        <mx:List
            id="lst"
            width="100%"
            dataProvider="{arr}"
            scroll="{scrolled(event)}"
            />
        <mx:HBox>
            <mx:Button id="lt" label="&lt;&lt;" click="{ltClicked(event)}"/>
            <mx:Button id="rt" label="&gt;&gt;" click="{rtClicked(event)}"/>
        </mx:HBox>

    </mx:VBox>

</mx:Application>

NOTE
Function ltClicked and rtClicked are modifying List data
and scrolled is used get to direction

I think better way of doing this is extend List control to get direction and scroll position
and manipulate Array to add or remove items in list


来源: stackexchange

问:
%MessageID% different from BTS.MessageID
I am trying to identify the messages I am saving in a folder using MessageID property. However the MessageID values are different from the values I get when I use BTS.MessageID. Why?

In my orchestration I receive a message "myMsg" from a receive port (with receive pipeline: XML Receive). After that I check myMsg(BTS.MessageID) value with

```<code>System.Diagnostics.EventLog.WriteEntry("MessageID", System.String.Format("The Value = {0}", myMsg(BTS.MessageID)));
</code>```

and I get for example this value: c9953bec-72a8-4274-9ea3-d7770c52d4ab

Then I send my message through a send port (with send pipeline: PassThruTransmit)

When the message is saved, the name is: {EE2AB9A1-FA3C-4737-BB02-6AC0C0EA5EBC}.xml

Why are they different? I thought they would be the same.

答:
Each message is unique. Assume you have 2 send ports where that orchestration message would go to. Would you expect it to have the same message id as the one from the orchestration? I hope not, because you would have 2 instances of a message with the same message id. (Actually 3 because you should also count your orchestration message is).

I guess what you're looking for is the InterchangeID, this one stays the same.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to identify the messages I am saving in a folder using MessageID property. However the MessageID values are different from the values I get when I use BTS.MessageID. Why?

In my orchestration I receive a message "myMsg" from a receive port (with receive pipeline: XML Receive). After that I check myMsg(BTS.MessageID) value with

System.Diagnostics.EventLog.WriteEntry("MessageID", System.String.Format("The Value = {0}", myMsg(BTS.MessageID)));

and I get for example this value: c9953bec-72a8-4274-9ea3-d7770c52d4ab

Then I send my message through a send port (with send pipeline: PassThruTransmit)

When the message is saved, the name is: {EE2AB9A1-FA3C-4737-BB02-6AC0C0EA5EBC}.xml

Why are they different? I thought they would be the same.


问:
After changing the value in input tag auto simulate Enter Key
I am entering data into a hidden input tag in HTML using JavaScript. I am able to do that but I need to simulate ENTER Key on keyboard to pass data into database, but the Problem in could not simulate the Enter key. I have tried bunch of solutions on events, listener and DOM, but none of them worked for me.

I am using DynamoDB to so it doesn't matter what type of data we enter or how; some of the code I have tried is:

```<code>function enter1() {
  var keyboardEvent = document.createEvent('KeyboardEvent');
  delete keyboardEvent.which;
  var initMethod = typeof keyboardEvent.initKeyboardEvent !== 'undefined' ? 'initKeyboardEvent' : 'initKeyEvent';
  keyboardEvent[initMethod](
    'keydown', // event type : keydown, keyup, keypress
    true, // bubbles
    true, // cancelable
    window, // viewArg: should be window
    false, // ctrlKeyArg
    false, // altKeyArg
    false, // shiftKeyArg
    false, // metaKeyArg
    13, // keyCodeArg : unsigned long the virtual key code, else 0
    13 // charCodeArgs : unsigned long the Unicode character associated with the depressed key, else 0
  );
  document.getElementById('newdata').dispatchEvent(keyboardEvent);
}
</code>```

I have tried various solutions provided using JavaScript, JQuery, events etc.
but none of them work.

```<code><input  className="new" placeholder="add data " type="hidden"
id = "newdata" value="need to add to data base"  />
</code>```

```<code>Wholevalue = " result1 = " + result1 + " Result2 = " + ressult2 + " result3 = " + result3 + "\n";
    alert(wholevalue);
    document.getElementById("newdata").setAttribute("value", wholevalue);
</code>```

I look for a way when data is change /input into the value field via script, it detects ENTER key, so it passes the data.

答:
You will have to trigger the change event yourself everytime you change the value. Once the change notification is received, you can dispatch a keypress for the Enter key.

I have given the code snippet below that triggers a value change event, which in turn triggers a keypress event.

Hope that helps.

$('#hiddenValue').change(TriggerValueChanged);
$('#hiddenValue').keypress(HandleKeyPress);

$('#hiddenValue').val("value change 1").trigger('change');
$('#hiddenValue').val("value change 2").trigger('change');

function TriggerValueChanged(element) {
  var event = $.Event( "keypress", { which: 13 } );
  $('#hiddenValue').trigger(event);
}

function HandleKeyPress(event) {
  if(event.which == 13) {
    alert(`KeyPress Detected. Event.Which: ${event.which}`);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="hidden" id="hiddenValue" value="" /></code>```

Body:
I am entering data into a hidden input tag in HTML using JavaScript. I am able to do that but I need to simulate ENTER Key on keyboard to pass data into database, but the Problem in could not simulate the Enter key. I have tried bunch of solutions on events, listener and DOM, but none of them worked for me.

I am using DynamoDB to so it doesn't matter what type of data we enter or how; some of the code I have tried is:

function enter1() {
  var keyboardEvent = document.createEvent('KeyboardEvent');
  delete keyboardEvent.which;
  var initMethod = typeof keyboardEvent.initKeyboardEvent !== 'undefined' ? 'initKeyboardEvent' : 'initKeyEvent';
  keyboardEvent[initMethod](
    'keydown', // event type : keydown, keyup, keypress
    true, // bubbles
    true, // cancelable
    window, // viewArg: should be window
    false, // ctrlKeyArg
    false, // altKeyArg
    false, // shiftKeyArg
    false, // metaKeyArg
    13, // keyCodeArg : unsigned long the virtual key code, else 0
    13 // charCodeArgs : unsigned long the Unicode character associated with the depressed key, else 0
  );
  document.getElementById('newdata').dispatchEvent(keyboardEvent);
}

I have tried various solutions provided using JavaScript, JQuery, events etc.
but none of them work.

<input  className="new" placeholder="add data " type="hidden"
id = "newdata" value="need to add to data base"  />

Wholevalue = " result1 = " + result1 + " Result2 = " + ressult2 + " result3 = " + result3 + "\n";
    alert(wholevalue);
    document.getElementById("newdata").setAttribute("value", wholevalue);

I look for a way when data is change /input into the value field via script, it detects ENTER key, so it passes the data.

Body:
You will have to trigger the change event yourself everytime you change the value. Once the change notification is received, you can dispatch a keypress for the Enter key.

I have given the code snippet below that triggers a value change event, which in turn triggers a keypress event.

Hope that helps.

$('#hiddenValue').change(TriggerValueChanged);
$('#hiddenValue').keypress(HandleKeyPress);

$('#hiddenValue').val("value change 1").trigger('change');
$('#hiddenValue').val("value change 2").trigger('change');

function TriggerValueChanged(element) {
  var event = $.Event( "keypress", { which: 13 } );
  $('#hiddenValue').trigger(event);
}

function HandleKeyPress(event) {
  if(event.which == 13) {
    alert(`KeyPress Detected. Event.Which: ${event.which}`);
  }
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="hidden" id="hiddenValue" value="" />


问:
IndProp: ev_plus_plus
```<code>(** **** Exercise: 3 stars, standard, optional (ev_plus_plus)

    This exercise just requires applying existing lemmas.  No
    induction or even case analysis is needed, though some of the
    rewriting may be tedious. *)

Theorem ev_plus_plus : forall n m p,
  even (n+m) -> even (n+p) -> even (m+p).
Proof.
  intros n m p H1 H2.
</code>```

Here is what I got:

```<code>1 subgoal (ID 89)

n, m, p : nat
H1 : even (n + m)
H2 : even (n + p)
============================
even (m + p)
</code>```

I have proven the previous theorem:

```<code>Theorem ev_ev__ev : forall n m,
  even (n+m) -> even n -> even m.
</code>```

And wanted to apply it to H1, but

```<code>apply ev_ev__ev in H1.
</code>```

gives an error:

```<code>Error: Unable to find an instance for the variable m.
</code>```

Why can't it find "m" in the expression even (n + m)? How to fix?

Update

```<code>apply ev_ev__ev with (m:=m) in H1.
</code>```

gives a very strange result:

```<code>2 subgoals (ID 90)

n, m, p : nat
H1 : even m
H2 : even (n + p)
============================
even (m + p)

subgoal 2 (ID 92) is:
 even (n + m + m)
</code>```

I thought that it will transform H1 to 2 hypothesis:

```<code>H11 : even n
H12 : even m
</code>```

But instead it gave 2 subgoals, the second that we need to prove is more complicated than the initial one:

```<code>even (n + m + m)
</code>```

What's happening here?

答:
The thing that is happening is that Coq unifies H1 with the even n argument of ev_ev__ev instead of the even (n+m).

You can tell Coq exactly where you want H1 to go, and use _ wildcards for the places where you let Coq work out the details.

You probably wanted this the term ev_ev__ev n m H1 with type even n -> even m but your apply produced the term ev_ev__ev (n+m) m _ H1  which also left you with some more stuff to prove.  To take a look at the proof context, do

```<code>Check ev_ev__ev (n+m) m _ H1.
</code>```

Title: IndProp: ev_plus_plus

Body:
(** **** Exercise: 3 stars, standard, optional (ev_plus_plus)

    This exercise just requires applying existing lemmas.  No
    induction or even case analysis is needed, though some of the
    rewriting may be tedious. *)

Theorem ev_plus_plus : forall n m p,
  even (n+m) -> even (n+p) -> even (m+p).
Proof.
  intros n m p H1 H2.

Here is what I got:

1 subgoal (ID 89)

n, m, p : nat
H1 : even (n + m)
H2 : even (n + p)
============================
even (m + p)

I have proven the previous theorem:

Theorem ev_ev__ev : forall n m,
  even (n+m) -> even n -> even m.

And wanted to apply it to H1, but

apply ev_ev__ev in H1.

gives an error:

Error: Unable to find an instance for the variable m.

Why can't it find "m" in the expression even (n + m)? How to fix?

Update

apply ev_ev__ev with (m:=m) in H1.

gives a very strange result:

2 subgoals (ID 90)

n, m, p : nat
H1 : even m
H2 : even (n + p)
============================
even (m + p)

subgoal 2 (ID 92) is:
 even (n + m + m)

I thought that it will transform H1 to 2 hypothesis:

H11 : even n
H12 : even m

But instead it gave 2 subgoals, the second that we need to prove is more complicated than the initial one:

even (n + m + m)

What's happening here?

Body:
The thing that is happening is that Coq unifies H1 with the even n argument of ev_ev__ev instead of the even (n+m).

You can tell Coq exactly where you want H1 to go, and use _ wildcards for the places where you let Coq work out the details.

You probably wanted this the term ev_ev__ev n m H1 with type even n -> even m but your apply produced the term ev_ev__ev (n+m) m _ H1  which also left you with some more stuff to prove.  To take a look at the proof context, do

Check ev_ev__ev (n+m) m _ H1.


问:
Windows 7 - 'make' is not recognized as an internal or external command, operable program or batch file
I have Windows 7 and tried to use the 'make' command but 'make' is not recognized as an internal or external command.

I did Start -> cmd -> run -> make, which outputs:

'make' is not recognized as an internal or external command,operable program or batch file.

Then I typed 'mingw32-make' instead of 'make' (Start -> cmd -> run -> mingw32-make) and I get the same output:

'mingw32-make' is not recognized as an internal or external command,operable program or batch file.

What shall I do next in order to fix this problem?

答:
This is an old question, but none of the answers here provide enough context for a beginner to choose which one to pick.

What is make?

make is a traditional Unix utility which reads a Makefile to decide what programs to run to reach a particular goal. Typically, that goal is to build a piece of software from a set of source files and libraries; but make is general enough to be used for various other tasks, too, like assembling a PDF from a collection of TeX source files, or retrieving the newest versions of each of a list of web pages.

Besides encapsulating the steps to reach an individual target, make reduces processing time by avoiding to re-execute steps which are already complete. It does this by comparing time stamps between dependencies; if A depends on B but A already exists and is newer than B, there is no need to make A. Of course, in order for this to work properly, the Makefile needs to document all such dependencies.

```<code>A: B
    commands to produce A from B
</code>```

Notice that the indentation needs to consist of a literal tab character. This is a common beginner mistake.

Common Versions of make

The original make was rather pedestrian. Its lineage continues to this day into BSD make, from which nmake is derived. Roughly speaking, this version provides the make functionality defined by POSIX, with a few minor enhancements and variations.

GNU make, by contrast, significantly extends the formalism, to the point where a GNU Makefile is unlikely to work with other versions (or occasionally even older versions of GNU make). There is a convention to call such files GNUmakefile instead of Makefile, but this convention is widely ignored, especially on platforms like Linux where GNU make is the de facto standard make.

Telltale signs that a Makefile uses GNU make conventions are the use of := instead of = for variable assignments (though this is not exclusively a GNU feature) and a plethora of functions like $(shell ...), $(foreach ...), $(patsubst ...) etc.

So Which Do I Need?

Well, it really depends on what you are hoping to accomplish.

If the software you are hoping to build has a vcproj file or similar, you probably want to use that instead, and not try to use make at all.

In the general case, MinGW make is a Windows port of GNU make for Windows, It should generally cope with any Makefile you throw at it.

If you know the software was written to use nmake and you already have it installed, or it is easy for you to obtain, maybe go with that.

You should understand that if the software was not written for, or explicitly ported to, Windows, it is unlikely to compile without significant modifications. In this scenario, getting make to run is the least of your problems, and you will need a good understanding of the differences between the original platform and Windows to have a chance of pulling it off yourself.

In some more detail, if the Makefile contains Unix commands like grep or curl or yacc then your system needs to have those commands installed, too. But quite apart from that, C or C++ (or more generally, source code in any language) which was written for a different platform might simply not work - at all, or as expected (which is often worse) - on Windows.

Body:
This is an old question, but none of the answers here provide enough context for a beginner to choose which one to pick.

What is make?

make is a traditional Unix utility which reads a Makefile to decide what programs to run to reach a particular goal. Typically, that goal is to build a piece of software from a set of source files and libraries; but make is general enough to be used for various other tasks, too, like assembling a PDF from a collection of TeX source files, or retrieving the newest versions of each of a list of web pages.

Besides encapsulating the steps to reach an individual target, make reduces processing time by avoiding to re-execute steps which are already complete. It does this by comparing time stamps between dependencies; if A depends on B but A already exists and is newer than B, there is no need to make A. Of course, in order for this to work properly, the Makefile needs to document all such dependencies.

A: B
    commands to produce A from B

Notice that the indentation needs to consist of a literal tab character. This is a common beginner mistake.

Common Versions of make

The original make was rather pedestrian. Its lineage continues to this day into BSD make, from which nmake is derived. Roughly speaking, this version provides the make functionality defined by POSIX, with a few minor enhancements and variations.

GNU make, by contrast, significantly extends the formalism, to the point where a GNU Makefile is unlikely to work with other versions (or occasionally even older versions of GNU make). There is a convention to call such files GNUmakefile instead of Makefile, but this convention is widely ignored, especially on platforms like Linux where GNU make is the de facto standard make.

Telltale signs that a Makefile uses GNU make conventions are the use of := instead of = for variable assignments (though this is not exclusively a GNU feature) and a plethora of functions like $(shell ...), $(foreach ...), $(patsubst ...) etc.

So Which Do I Need?

Well, it really depends on what you are hoping to accomplish.

If the software you are hoping to build has a vcproj file or similar, you probably want to use that instead, and not try to use make at all.

In the general case, MinGW make is a Windows port of GNU make for Windows, It should generally cope with any Makefile you throw at it.

If you know the software was written to use nmake and you already have it installed, or it is easy for you to obtain, maybe go with that.

You should understand that if the software was not written for, or explicitly ported to, Windows, it is unlikely to compile without significant modifications. In this scenario, getting make to run is the least of your problems, and you will need a good understanding of the differences between the original platform and Windows to have a chance of pulling it off yourself.

In some more detail, if the Makefile contains Unix commands like grep or curl or yacc then your system needs to have those commands installed, too. But quite apart from that, C or C++ (or more generally, source code in any language) which was written for a different platform might simply not work - at all, or as expected (which is often worse) - on Windows.


问:
AWS lambda not working with Log4j 2 appender
I am trying to write a java based lambda function. Everything works fine except the logging. I have the log4j2.xml file in classpath.

I have also followed the instruction laid down in AWS Lambda LOgging in Java to the word.

I get this in the log when I trigger the Lambda function.

log4j:WARN No appenders could be found for logger (com.amazonaws.AmazonWebServiceClient).
  log4j:WARN Please initialize the log4j system properly.
  log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.

I use maven to package the jar. The pom.xml has the following dependencies.

```<code><dependencies>
<dependency>
  <groupId>junit</groupId>
  <artifactId>junit</artifactId>
  <version>3.8.1</version>
  <scope>test</scope>
</dependency>
<dependency>
  <groupId>com.amazon.alexa</groupId>
  <artifactId>alexa-skills-kit</artifactId>
  <version>${alexa.version}</version>
</dependency>

<dependency>
  <groupId>org.apache.commons</groupId>
  <artifactId>commons-lang3</artifactId>
  <version>3.4</version>
  <scope>compile</scope>
</dependency>
<dependency>
  <groupId>org.apache.directory.studio</groupId>
  <artifactId>org.apache.commons.io</artifactId>
  <version>2.4</version>
  <scope>compile</scope>
</dependency>
<dependency>
  <groupId>com.amazonaws</groupId>
  <artifactId>aws-lambda-java-core</artifactId>
  <version>1.0.0</version>
  <scope>compile</scope>
</dependency>
<dependency>
  <groupId>com.amazonaws</groupId>
  <artifactId>aws-java-sdk-dynamodb</artifactId>
  <version>1.9.40</version>
</dependency>
<dependency>
  <groupId>com.amazonaws</groupId>
  <artifactId>aws-lambda-java-log4j2</artifactId>
  <version>1.0.0</version>
</dependency>
<dependency>
  <groupId>org.apache.logging.log4j</groupId>
  <artifactId>log4j-core</artifactId>
  <version>2.8.2</version>
</dependency>
<dependency>
  <groupId>org.apache.logging.log4j</groupId>
  <artifactId>log4j-api</artifactId>
  <version>2.8.2</version>
</dependency>
</code>```

I am not sure what else I must do to make this work.

答:
Logging reference

When creating an Alexa Skill - its dependencies already contain log4j components, but laking the Log4j appender. Add aws-lambda-java-log4j2 to dependencies:

Maven

```<code><dependency>
    <groupId>com.amazonaws</groupId>
    <artifactId>aws-lambda-java-log4j2</artifactId>
    <version>1.1.0</version>
</dependency>
</code>```

Gradle:

```<code>dependencies {
    compile 'com.amazonaws:aws-lambda-java-log4j2:1.1.0'
}
</code>```

Error variants

No log4j2 configuration file found. Using default configuration: logging only errors to the console. Set system property 'org.apache.logging.log4j.simplelog.StatusLogger.level' to TRACE to show Log4j2 internal initialization logging.

Add:
log4j2.xml  (described in Logging reference) to src/main/resources

StatusLogger Log4j2 could not find a logging implementation. Please add log4j-core to the classpath. Using SimpleLogger to log to the console

Add (same version as in existing dependencies):

```<code>   dependencies {
    compile 'com.amazonaws:aws-lambda-java-core:1.2.0'
       compile 'org.apache.logging.log4j:log4j-core:2.8.2’
   }
</code>```

No log4j2 configuration file found. Using default configuration: logging only errors to the console. Set system property 'org.apache.logging.log4j.simplelog.StatusLogger.level' to TRACE to show Log4j2 internal initialization logging.

Add:
log4j2.xml  (described above) to src/main/resources

Error processing element Lambda ([Appenders: null]): CLASS_NOT_FOUND
Unable to locate appender "Lambda" for logger config "root"

Add:

```<code>dependencies {
   compile 'com.amazonaws:aws-lambda-java-log4j2:1.1.0'
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to write a java based lambda function. Everything works fine except the logging. I have the log4j2.xml file in classpath.

I have also followed the instruction laid down in AWS Lambda LOgging in Java to the word.

I get this in the log when I trigger the Lambda function.

log4j:WARN No appenders could be found for logger (com.amazonaws.AmazonWebServiceClient).
  log4j:WARN Please initialize the log4j system properly.
  log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.

I use maven to package the jar. The pom.xml has the following dependencies.

<dependencies>
<dependency>
  <groupId>junit</groupId>
  <artifactId>junit</artifactId>
  <version>3.8.1</version>
  <scope>test</scope>
</dependency>
<dependency>
  <groupId>com.amazon.alexa</groupId>
  <artifactId>alexa-skills-kit</artifactId>
  <version>${alexa.version}</version>
</dependency>

<dependency>
  <groupId>org.apache.commons</groupId>
  <artifactId>commons-lang3</artifactId>
  <version>3.4</version>
  <scope>compile</scope>
</dependency>
<dependency>
  <groupId>org.apache.directory.studio</groupId>
  <artifactId>org.apache.commons.io</artifactId>
  <version>2.4</version>
  <scope>compile</scope>
</dependency>
<dependency>
  <groupId>com.amazonaws</groupId>
  <artifactId>aws-lambda-java-core</artifactId>
  <version>1.0.0</version>
  <scope>compile</scope>
</dependency>
<dependency>
  <groupId>com.amazonaws</groupId>
  <artifactId>aws-java-sdk-dynamodb</artifactId>
  <version>1.9.40</version>
</dependency>
<dependency>
  <groupId>com.amazonaws</groupId>
  <artifactId>aws-lambda-java-log4j2</artifactId>
  <version>1.0.0</version>
</dependency>
<dependency>
  <groupId>org.apache.logging.log4j</groupId>
  <artifactId>log4j-core</artifactId>
  <version>2.8.2</version>
</dependency>
<dependency>
  <groupId>org.apache.logging.log4j</groupId>
  <artifactId>log4j-api</artifactId>
  <version>2.8.2</version>
</dependency>

I am not sure what else I must do to make this work.

Body:
Logging reference

When creating an Alexa Skill - its dependencies already contain log4j components, but laking the Log4j appender. Add aws-lambda-java-log4j2 to dependencies:

Maven

<dependency>
    <groupId>com.amazonaws</groupId>
    <artifactId>aws-lambda-java-log4j2</artifactId>
    <version>1.1.0</version>
</dependency>

Gradle:

dependencies {
    compile 'com.amazonaws:aws-lambda-java-log4j2:1.1.0'
}

Error variants

No log4j2 configuration file found. Using default configuration: logging only errors to the console. Set system property 'org.apache.logging.log4j.simplelog.StatusLogger.level' to TRACE to show Log4j2 internal initialization logging.

Add:
log4j2.xml  (described in Logging reference) to src/main/resources

StatusLogger Log4j2 could not find a logging implementation. Please add log4j-core to the classpath. Using SimpleLogger to log to the console

Add (same version as in existing dependencies):

   dependencies {
    compile 'com.amazonaws:aws-lambda-java-core:1.2.0'
       compile 'org.apache.logging.log4j:log4j-core:2.8.2’
   }

No log4j2 configuration file found. Using default configuration: logging only errors to the console. Set system property 'org.apache.logging.log4j.simplelog.StatusLogger.level' to TRACE to show Log4j2 internal initialization logging.

Add:
log4j2.xml  (described above) to src/main/resources

Error processing element Lambda ([Appenders: null]): CLASS_NOT_FOUND
Unable to locate appender "Lambda" for logger config "root"

Add:

dependencies {
   compile 'com.amazonaws:aws-lambda-java-log4j2:1.1.0'
}


问:
jQuery UI Dialog and Textarea Focus Issue
I'm working on a modal comment system using jQuery and jQuery UI, but I'm having some issues with focus. I have a series of divs inside the modal to switch between Login and Add comment, as below:

```<code><div id="modal" title="Loading">
 <div id="modalContent"></div>

 <div id="modalLogin">
  <div class="loginBox"></div>
  <div class="addCommentBox"></div>
  <div class="commentReview"></div>
 </div>
</div>
</code>```

Inside of the addCommentBox div, I've got the comment code:

```<code> <form action="/comments/add" class="addCommentForm" name="addCommentForm" method="post">
  <textarea name="content" class="addCommentContent"></textarea>
  <button value="Add Comment" type="submit" class="commentPost"/>
  <button value="Clear Comment" type="submit" id="clearComment"/>
 </form>
</code>```

The issue is that about half the time after opening the dialog the textarea inside the addCommentBox div doesn't react to keyboard inputs when selected. The mouse works correctly and will allow text to be selected, but keyboard control does nothing.

I have no event listeners on the textarea. I've got some on the buttons, but they are targeting only the buttons.

The only thing that happens in the HTML seems to be the fact that every time I click on the modal, the z-index increases for the overall modal div. I have set the addCommentBox div to have a z-index of 9999, greater than the z-index of the modal.

Any suggestions or directions to research would be greatly appreciated. Thanks!

答:
How are you hiding loginBox and commentReview? If you're using opacity it may be that something you can't see is sitting on top of the textarea.

You won't see elements with opacity of 0, but they're still there in every other respect. They will accept mouse events, stopping you from clicking on the textarea.

If you can see the textarea, then it doesn't sound like a z-index issue to me.

ContentLicense: CC BY-SA 2.5

Body:
I'm working on a modal comment system using jQuery and jQuery UI, but I'm having some issues with focus. I have a series of divs inside the modal to switch between Login and Add comment, as below:

Inside of the addCommentBox div, I've got the comment code:

 <form action="/comments/add" class="addCommentForm" name="addCommentForm" method="post">
  <textarea name="content" class="addCommentContent"></textarea>
  <button value="Add Comment" type="submit" class="commentPost"/>
  <button value="Clear Comment" type="submit" id="clearComment"/>
 </form>

The issue is that about half the time after opening the dialog the textarea inside the addCommentBox div doesn't react to keyboard inputs when selected. The mouse works correctly and will allow text to be selected, but keyboard control does nothing.

I have no event listeners on the textarea. I've got some on the buttons, but they are targeting only the buttons.

The only thing that happens in the HTML seems to be the fact that every time I click on the modal, the z-index increases for the overall modal div. I have set the addCommentBox div to have a z-index of 9999, greater than the z-index of the modal.

Any suggestions or directions to research would be greatly appreciated. Thanks!


问:
Reverse factorial fun won't go beyond 170
I am a beginner at pyhon and I'm trying to reverse the factorial function.
The factorial of 5 is 120
And I want my code to take input 120 and be able to return 5
Here's my present code:

```<code>`from math import factorial
    def rf(f):
        d=2
        while f/factorial(d) != 1:
            if f/factorial(d) <= 1:
                 print("Entered number is not a factorial")
                 return
            d += 1
        return int(d)`
</code>```

It can reverse the factorial upto 170.But when I enter the factorial of 171 the code gets into OverFlowError.
Is there a solution to my code?
or, a more reliable code to reverse factorial.

答:
Though @NPE's solution is much cleaner and more efficient, you could use your original code with a small change to make it work: use floor division //, that returns integers, instead of normal division /:

```<code>from math import factorial

def rf(f):
    d=2
    while f//factorial(d) != 1:
        if f//factorial(d) <= 1:
            print("Entered number is not a factorial")
            return
        d += 1
    return int(d)

rf(factorial(171))
# 171
</code>```

Body:
I am a beginner at pyhon and I'm trying to reverse the factorial function.
The factorial of 5 is 120
And I want my code to take input 120 and be able to return 5
Here's my present code:

`from math import factorial
    def rf(f):
        d=2
        while f/factorial(d) != 1:
            if f/factorial(d) <= 1:
                 print("Entered number is not a factorial")
                 return
            d += 1
        return int(d)`

It can reverse the factorial upto 170.But when I enter the factorial of 171 the code gets into OverFlowError.
Is there a solution to my code?
or, a more reliable code to reverse factorial.

Body:
Though @NPE's solution is much cleaner and more efficient, you could use your original code with a small change to make it work: use floor division //, that returns integers, instead of normal division /:

from math import factorial

def rf(f):
    d=2
    while f//factorial(d) != 1:
        if f//factorial(d) <= 1:
            print("Entered number is not a factorial")
            return
        d += 1
    return int(d)

rf(factorial(171))
# 171


问:
react-native nativeBase Tabs initialPage change to 3 but still start at tab 0
here is the code: (PAY ATTENTION AT COMMENT IN CODE)

```<code>import React, { Component } from 'react';
import {Container, Tab, Tabs, TabHeading, Icon, Text } from 'native-base';
import style from './../styles/compoCss' ;
import NewDB from './../database/NewDB';
import Category from "../lists/Category";
import HomePage from  './../tabs/HomePage'

export default class TabHome extends Component {
render() {
    return (
        <Container>
            <Tabs initialPage={3} > //THIS CODE DOESN'T WORK :(
                <Tab heading={
                    <TabHeading style={style.footerTabHome}>
                        <Icon name="md-aperture" style={style.iconFooter} />
                        <Text style={style.textFooter}>New</Text>
                    </TabHeading>}>
                    <NewDB/>
                </Tab>
                <Tab heading={
                    <TabHeading style={style.footerTabHome}>
                        <Icon name="md-bookmark" style={style.iconFooter} />
                        <Text style={style.textFooter}>Bookmark</Text>
                    </TabHeading>}>

                </Tab>
                <Tab heading={
                    <TabHeading style={style.footerTabHome}>
                        <Icon active name="md-apps" style={style.iconFooter}  />
                        <Text style={style.textFooter}>Catalog</Text>
                    </TabHeading>}>
                    <Category/>
                </Tab>
                <Tab heading={
                    <TabHeading style={style.footerTabHome}>
                        <Icon name="md-home" style={style.iconFooter} />
                        <Text style={style.textFooter}>Home</Text>
                    </TabHeading>} >
                    <HomePage/>
                </Tab>
            </Tabs>
        </Container>
    );
  }
}
</code>```

and when I build the app or refresh it , default tab is the 3 (Home) and I think it's correct but don't show the Home page contents and when i scroll I find out that it is stack in tab 0 (new)...
I search all of the forums and I can't solve my problem. please help thanks!
(this problem is in android device)

答:
I am also facing this issue and resolved it by below sample code.

```<code>constructor(props) {
    super(props);
    this.state = {
      initialPage: 1,
      activeTab: 0
    };  }

componentDidMount() {
  setTimeout(() => {
      this.setState({ activeTab: 1 });
    }, 0);
}

render(){
  return ...
    <Tabs
        locked
        initialPage={this.state.initialPage}
        page={this.state.activeTab}
      >
}
</code>```

Body:
here is the code: (PAY ATTENTION AT COMMENT IN CODE)

import React, { Component } from 'react';
import {Container, Tab, Tabs, TabHeading, Icon, Text } from 'native-base';
import style from './../styles/compoCss' ;
import NewDB from './../database/NewDB';
import Category from "../lists/Category";
import HomePage from  './../tabs/HomePage'

export default class TabHome extends Component {
render() {
    return (
        <Container>
            <Tabs initialPage={3} > //THIS CODE DOESN'T WORK :(
                <Tab heading={
                    <TabHeading style={style.footerTabHome}>
                        <Icon name="md-aperture" style={style.iconFooter} />
                        <Text style={style.textFooter}>New</Text>
                    </TabHeading>}>
                    <NewDB/>
                </Tab>
                <Tab heading={
                    <TabHeading style={style.footerTabHome}>
                        <Icon name="md-bookmark" style={style.iconFooter} />
                        <Text style={style.textFooter}>Bookmark</Text>
                    </TabHeading>}>

                </Tab>
                <Tab heading={
                    <TabHeading style={style.footerTabHome}>
                        <Icon active name="md-apps" style={style.iconFooter}  />
                        <Text style={style.textFooter}>Catalog</Text>
                    </TabHeading>}>
                    <Category/>
                </Tab>
                <Tab heading={
                    <TabHeading style={style.footerTabHome}>
                        <Icon name="md-home" style={style.iconFooter} />
                        <Text style={style.textFooter}>Home</Text>
                    </TabHeading>} >
                    <HomePage/>
                </Tab>
            </Tabs>
        </Container>
    );
  }
}

and when I build the app or refresh it , default tab is the 3 (Home) and I think it's correct but don't show the Home page contents and when i scroll I find out that it is stack in tab 0 (new)...
I search all of the forums and I can't solve my problem. please help thanks!
(this problem is in android device)

Body:
I am also facing this issue and resolved it by below sample code.

constructor(props) {
    super(props);
    this.state = {
      initialPage: 1,
      activeTab: 0
    };  }

componentDidMount() {
  setTimeout(() => {
      this.setState({ activeTab: 1 });
    }, 0);
}

render(){
  return ...
    <Tabs
        locked
        initialPage={this.state.initialPage}
        page={this.state.activeTab}
      >
}


问:
Replacing elements in an array from index array
I have two 2D arrays like:

```<code>A=array[[4,5,6],
        [0,7,8],
        [0,9,0]]

B = array[[11,12,13],
          [14,15,16],
          [17,18,19]]
</code>```

In array A where element value is 0 i want to replace same value in array B by 0 and store the changed matrix in a new variable and retain the old B matrix.

Thanks in advance.

答:
```<code>import numpy as np
A=np.array([[4,5,6],
    [0,7,8],
    [0,9,0]])

B =np.array([[11,12,13],
      [14,15,16],
      [17,18,19]])
C = B.copy()
B[A == 0] = 0
C, B = B, C
</code>```

The line B[A == 0] basically first gets all the the values where the array A is 0 by the line A == 0 . It return a boolean array with true at the position where value is zero in array A. This boolean array is then used to mask the array B and assigns 0 to indices the boolean values is True.

Body:
I have two 2D arrays like:

A=array[[4,5,6],
        [0,7,8],
        [0,9,0]]

B = array[[11,12,13],
          [14,15,16],
          [17,18,19]]

In array A where element value is 0 i want to replace same value in array B by 0 and store the changed matrix in a new variable and retain the old B matrix.

Thanks in advance.

Body:
import numpy as np
A=np.array([[4,5,6],
    [0,7,8],
    [0,9,0]])

B =np.array([[11,12,13],
      [14,15,16],
      [17,18,19]])
C = B.copy()
B[A == 0] = 0
C, B = B, C

The line B[A == 0] basically first gets all the the values where the array A is 0 by the line A == 0 . It return a boolean array with true at the position where value is zero in array A. This boolean array is then used to mask the array B and assigns 0 to indices the boolean values is True.


问:
Efficiently/elegantly apply a method to, or get property from, numpy ndarray of objects
In a python script, have 2 numpy ndarrays filled with objects, let's call them inA and inB (same shape). The objects are all of the same type and have a method calculate() and a property size.

I'd like to apply the method to each, and save the result in a new array, and I'd also like to get the property from each element and save the result in a new array.

Note: I have found ways to achieve all of this, but I think they could be improved. I just don't know how.

Getting property or applying method without arguments

If the method takes no arguments, or non-array arguments, I have found a way to apply it to each element, like so:

```<code>f = lambda x: x.calculate()
outA = np.vectorize(f)(inA)
</code>```

The same goes for getting the property:

```<code>f = lambda x: x.size
outA = np.vectorize(f)(inA)
</code>```

This is working, but it's ugly (imho), and the fact that x in the lambda function is unknown to the IDE makes me having to write the function 'blindly', without help from intellisense (or it's Spyder equivalent).

Pairwise application of method

If the method takes another object as its argument, and I'd like to apply it to each element in inA and use the corresponding element in inB as its argument, the only thing I can come up with is a dreaded loop:

```<code>out = np.ndarray(inA.shape)
for index, iA in np.ndenumerate(inA):
    out[index] = iA.calculate(inB[index])
</code>```

I refuse to believe there is no better way to achieve this.

Hence my question: is there a way to improve on these two methods (no pun intended) of applying a method to elements or pairs of elements in an ndarray?

答:
For applying a method, I found I can do

```<code>outA = np.vectorize(className.calculate)(inA)
</code>```

and for the paiwise application of a method, I found that I can do

```<code>out = np.vectorize(className.calculate)(inA, inB)
</code>```

as the first argument of the methods is self.

Especially for the latter, this is a lot cleaner.

I haven't found a way to ge the property without a lambda function, I guess this

```<code>outA = np.vectorize(lambda x: x.size)(inA)
</code>```

is the easiest/best way to do it in a oneliner.

Body:
In a python script, have 2 numpy ndarrays filled with objects, let's call them inA and inB (same shape). The objects are all of the same type and have a method calculate() and a property size.

I'd like to apply the method to each, and save the result in a new array, and I'd also like to get the property from each element and save the result in a new array.

Note: I have found ways to achieve all of this, but I think they could be improved. I just don't know how.

Getting property or applying method without arguments

If the method takes no arguments, or non-array arguments, I have found a way to apply it to each element, like so:

f = lambda x: x.calculate()
outA = np.vectorize(f)(inA)

The same goes for getting the property:

f = lambda x: x.size
outA = np.vectorize(f)(inA)

This is working, but it's ugly (imho), and the fact that x in the lambda function is unknown to the IDE makes me having to write the function 'blindly', without help from intellisense (or it's Spyder equivalent).

Pairwise application of method

If the method takes another object as its argument, and I'd like to apply it to each element in inA and use the corresponding element in inB as its argument, the only thing I can come up with is a dreaded loop:

out = np.ndarray(inA.shape)
for index, iA in np.ndenumerate(inA):
    out[index] = iA.calculate(inB[index])

I refuse to believe there is no better way to achieve this.

Hence my question: is there a way to improve on these two methods (no pun intended) of applying a method to elements or pairs of elements in an ndarray?

Body:
For applying a method, I found I can do

outA = np.vectorize(className.calculate)(inA)

and for the paiwise application of a method, I found that I can do

out = np.vectorize(className.calculate)(inA, inB)

as the first argument of the methods is self.

Especially for the latter, this is a lot cleaner.

I haven't found a way to ge the property without a lambda function, I guess this

outA = np.vectorize(lambda x: x.size)(inA)

is the easiest/best way to do it in a oneliner.


问:
Callback function is not working - Codeigniter3 HMVC
m getting form validation error while using callback function in HMVC CI...i didn't understant the problme...my validation code is -

```<code>$this->form_validation->set_rules('username', 'Email', 'trim|required|valid_email|callback_IsEmail_exist');

function IsEmail_exist() {
        $existing_email = $this->db->where("email", $this->input->post('username'))->get('tbl_user')->num_rows();//p($existing_email);echo $this->db->last_query();die;
        if ($existing_email != "0") {
            $this->form_validation->set_message('email', 'Email ID already Exist.');
            return false;
        }
    }
</code>```

The following code is in Custom_Form_validation.php:

```<code>
/* custom function by Pikachu */

class Custom_Form_validation extends CI_Form_validation {

    public $CI;

    function run($module = '', $group = '') {
        (is_object($module)) AND $this->CI = &$module;
        return parent::run($group);
    }

}
</code>```

and in my controller:

```<code>function __construct() {
        parent::__construct();
        $this->load->library('form_validation');
        $this->load->library(array('Custom_Form_validation'));
        $this->form_validation->CI =& $this;
        $this->load->model('custom_model', 'custom');
    }
</code>```

still getting "email is required" error msg in view form. Kindly help to resolve this issue.

答:
Hi @pikachu instead of doing this -

```<code>$this->form_validation->set_rules('username', 'Email', 'trim|required|valid_email|callback_IsEmail_exist');
</code>```

use the piped elements separate into individual parameters like -

```<code>$this->form_validation->set_rules('username', 'Email', 'required', 'callback_IsEmail_exist');
</code>```

this may be help you.

Body:
m getting form validation error while using callback function in HMVC CI...i didn't understant the problme...my validation code is -

$this->form_validation->set_rules('username', 'Email', 'trim|required|valid_email|callback_IsEmail_exist');

function IsEmail_exist() {
        $existing_email = $this->db->where("email", $this->input->post('username'))->get('tbl_user')->num_rows();//p($existing_email);echo $this->db->last_query();die;
        if ($existing_email != "0") {
            $this->form_validation->set_message('email', 'Email ID already Exist.');
            return false;
        }
    }

The following code is in Custom_Form_validation.php:

/* custom function by Pikachu */

class Custom_Form_validation extends CI_Form_validation {

    public $CI;

    function run($module = '', $group = '') {
        (is_object($module)) AND $this->CI = &$module;
        return parent::run($group);
    }

}

and in my controller:

function __construct() {
        parent::__construct();
        $this->load->library('form_validation');
        $this->load->library(array('Custom_Form_validation'));
        $this->form_validation->CI =& $this;
        $this->load->model('custom_model', 'custom');
    }

still getting "email is required" error msg in view form. Kindly help to resolve this issue.

Body:
Hi @pikachu instead of doing this -

$this->form_validation->set_rules('username', 'Email', 'trim|required|valid_email|callback_IsEmail_exist');

use the piped elements separate into individual parameters like -

$this->form_validation->set_rules('username', 'Email', 'required', 'callback_IsEmail_exist');

this may be help you.


问:
io.sockets.on not working inside a route in Node.js
I'm trying to use io.sockets.on inside a route in a Node.js and Express app. I have been following what is said here: https://stackoverflow.com/a/31277123/8271839

I can successfully send io.sockets.emit events, but I cannot receive events with io.sockets.on.

Here is my code:

index.js:

```<code>const cors = require('cors');
const express = require('express');
const app = express();
const server = require('http').Server(app);
const io = require('socket.io')(server);
const taskRequest = require('./routes/taskRequest');

app.use(cors())
app.use(express.json());
app.use('/api/taskRequest', taskRequest);

app.set('socketio', io);

server.listen(4002);

io.sockets.on("connection",function(socket){
    console.log("connected");
    socket.on("connected", function (data) {
        console.log("hello");
    })
});
</code>```

routes/taskRequest.js:

```<code>const express = require('express');
const router = express.Router();

router.post('/', async (req, res) => {

    var io = req.app.get('socketio');

    //pickedUser is one of the connected client
    var pickedUser = "JZLpeA4pBECwbc5IAAAA";

    //we only send the emit event to the pickedUser
    io.to(pickedUser).emit('taskRequest', req.body);

    io.on('connection', function (socket) {
        console.log('connected 2');
        socket.on('taskResponse', function () {
            console.log('hello 2');
        });
    });

});

module.exports = router;
</code>```

When a client is connected, I get the "connected" message in console, but not the "connected 2" message.

Also, when client emits "connected" message, I get "hello" in console, but when clients emits "taskResponse" message, I don't get "hello 2" in console.

Though when io.to(pickedUser).emit('taskRequest', req.body); is called, it works, client receives the "taskRequest" message.

Why is .emit() working inside my route but not .on() ?

答:
I mark TRomesh answer as the right answer, since indeed you can only have one io.on('connection', function (socket) {}) in your code.

Now here is what I have done to make it work for me: the issue was that if you place io.on('connection', function (socket) {}) within your router.post('/', async (req, res) => {}), it will only be triggered when you call your endpoint. In my case, I had some sockets events that I wanted to be called at anytime, not only when the endpoint is called. So I had to place the io.on('connection', function (socket) {}) outside of my router.post('/', async (req, res) => {}). Thus I couldn't use var io = req.app.get('socketio'); inside the router. Here is what I have done instead:

index.js:

```<code>const cors = require('cors');
const express = require('express');
const app = express();
const server = require('http').Server(app);
const io = require('socket.io')(server);
const taskRequest = require('./routes/taskRequest')(io);

app.use(cors())
app.use(express.json());
app.use('/api/taskRequest', taskRequest);

server.listen(4002);
</code>```

routes/taskRequest.js

```<code>const express = require('express');
const router = express.Router();

module.exports = function(io) {

    //we define the variables
    var sendResponse = function () {};

    io.sockets.on("connection",function(socket){
        // Everytime a client logs in, display a connected message
        console.log("Server-Client Connected!");

        socket.on('connected', function(data) {
            //listen to event at anytime (not only when endpoint is called)
            //execute some code here
        });

        socket.on('taskResponse', data => {
            //calling a function which is inside the router so we can send a res back
            sendResponse(data);
        })
    });

    router.post('/', async (req, res) => {

        //pickedUser is one of the connected client
        var pickedUser = "JZLpeA4pBECwbc5IAAAA";
        io.to(pickedUser).emit('taskRequest', req.body);

        sendResponse = function (data) {
            return res.status(200).json({"text": "Success", "response": data.data});
        }

    });

    return router;

};
</code>```

Body:
I'm trying to use io.sockets.on inside a route in a Node.js and Express app. I have been following what is said here: https://stackoverflow.com/a/31277123/8271839

I can successfully send io.sockets.emit events, but I cannot receive events with io.sockets.on.

Here is my code:

index.js:

const cors = require('cors');
const express = require('express');
const app = express();
const server = require('http').Server(app);
const io = require('socket.io')(server);
const taskRequest = require('./routes/taskRequest');

app.use(cors())
app.use(express.json());
app.use('/api/taskRequest', taskRequest);

app.set('socketio', io);

server.listen(4002);

io.sockets.on("connection",function(socket){
    console.log("connected");
    socket.on("connected", function (data) {
        console.log("hello");
    })
});

routes/taskRequest.js:

const express = require('express');
const router = express.Router();

router.post('/', async (req, res) => {

    var io = req.app.get('socketio');

    //pickedUser is one of the connected client
    var pickedUser = "JZLpeA4pBECwbc5IAAAA";

    //we only send the emit event to the pickedUser
    io.to(pickedUser).emit('taskRequest', req.body);

    io.on('connection', function (socket) {
        console.log('connected 2');
        socket.on('taskResponse', function () {
            console.log('hello 2');
        });
    });

});

module.exports = router;

When a client is connected, I get the "connected" message in console, but not the "connected 2" message.

Also, when client emits "connected" message, I get "hello" in console, but when clients emits "taskResponse" message, I don't get "hello 2" in console.

Though when io.to(pickedUser).emit('taskRequest', req.body); is called, it works, client receives the "taskRequest" message.

Why is .emit() working inside my route but not .on() ?

Body:
I mark TRomesh answer as the right answer, since indeed you can only have one io.on('connection', function (socket) {}) in your code.

Now here is what I have done to make it work for me: the issue was that if you place io.on('connection', function (socket) {}) within your router.post('/', async (req, res) => {}), it will only be triggered when you call your endpoint. In my case, I had some sockets events that I wanted to be called at anytime, not only when the endpoint is called. So I had to place the io.on('connection', function (socket) {}) outside of my router.post('/', async (req, res) => {}). Thus I couldn't use var io = req.app.get('socketio'); inside the router. Here is what I have done instead:

index.js:

const cors = require('cors');
const express = require('express');
const app = express();
const server = require('http').Server(app);
const io = require('socket.io')(server);
const taskRequest = require('./routes/taskRequest')(io);

app.use(cors())
app.use(express.json());
app.use('/api/taskRequest', taskRequest);

server.listen(4002);

routes/taskRequest.js

const express = require('express');
const router = express.Router();

module.exports = function(io) {

    //we define the variables
    var sendResponse = function () {};

    io.sockets.on("connection",function(socket){
        // Everytime a client logs in, display a connected message
        console.log("Server-Client Connected!");

        socket.on('connected', function(data) {
            //listen to event at anytime (not only when endpoint is called)
            //execute some code here
        });

        socket.on('taskResponse', data => {
            //calling a function which is inside the router so we can send a res back
            sendResponse(data);
        })
    });

    router.post('/', async (req, res) => {

        //pickedUser is one of the connected client
        var pickedUser = "JZLpeA4pBECwbc5IAAAA";
        io.to(pickedUser).emit('taskRequest', req.body);

        sendResponse = function (data) {
            return res.status(200).json({"text": "Success", "response": data.data});
        }

    });

    return router;

};


问:
Error loading MySQLdb Module 'Did you install mysqlclient or MySQL-python?'
I am using windows 10 command line for a django project using python34 however, I am facing difficulties with SQL.

I have already installed mysqlclient using pip install mysqlclient==1.3.5 and located the file to make sure I was not delusional. I then ran python manage.py migrate to migrate the tables to the SQL database (I am using phpmyadmin). However when the command returned with...

```<code> File "C:\Users\user\env\lib\site-packages\django\db\backends\mysql\base.py", line 30, in <module>
    'Did you install mysqlclient or MySQL-python?' % e
django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named 'MySQLdb'.
Did you install mysqlclient or MySQL-python?
</code>```

I am aware that questions like these already exist, but not one solution seems to have made any impact on attempts.

答:
For pip

```<code>pip install pymysql
</code>```

For pip3 you should use

```<code>python3 -m pip install PyMySQL
</code>```

Then, edit the init.py file in your project origin directory (the same as settings.py). Add:

```<code>import pymysql

pymysql.install_as_MySQLdb()
</code>```

Body:
I am using windows 10 command line for a django project using python34 however, I am facing difficulties with SQL.

I have already installed mysqlclient using pip install mysqlclient==1.3.5 and located the file to make sure I was not delusional. I then ran python manage.py migrate to migrate the tables to the SQL database (I am using phpmyadmin). However when the command returned with...

 File "C:\Users\user\env\lib\site-packages\django\db\backends\mysql\base.py", line 30, in <module>
    'Did you install mysqlclient or MySQL-python?' % e
django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named 'MySQLdb'.
Did you install mysqlclient or MySQL-python?

I am aware that questions like these already exist, but not one solution seems to have made any impact on attempts.

Body:
For pip

pip install pymysql

For pip3 you should use

python3 -m pip install PyMySQL

Then, edit the init.py file in your project origin directory (the same as settings.py). Add:

import pymysql

pymysql.install_as_MySQLdb()


问:
Should Feature Selection be done before Train-Test Split or after?
Actually, there is a contradiction of 2 facts that are the possible answers to the question:

The conventional answer is to do it after splitting as there can be information leakage, if done before, from the Test-Set.

The contradicting answer is that, if only the Training Set chosen from the whole dataset is used for Feature Selection, then the feature selection or feature importance score orders is likely to be dynamically changed with change in random_state of the Train_Test_Split. And if the feature selection for any particular work changes, then no Generalization of Feature Importance can be done, which is not desirable. Secondly, if only Training Set is used for feature selection, then the test set may contain certain set of instances that defies/contradicts the feature selection done only on the Training Set as the overall historical data is not analyzed. Moreover, feature importance scores can only be evaluated when, given a set of instances rather than a single test/unknown instance.

答:
The conventional answer #1 is correct here; the arguments in the contradicting answer #2 do not actually hold.

When having such doubts, it is useful to imagine that you simply do not have any access in any test set during the model fitting process (which includes feature importance); you should treat the test set as literally unseen data (and, since unseen, they could not have been used for feature importance scores).

Hastie & Tibshirani have clearly argued long ago about the correct & wrong way to perform such processes; I have summarized the issue in a blog post, How NOT to perform feature selection! - and although the discussion is about cross-validation, it can be easily seen that the arguments hold for the case of train/test split, too.

The only argument that actually holds in your contradicting answer #2 is that

the overall historical data is not analyzed

Nevertheless, this is the necessary price to pay in order to have an independent test set for performance assessment, otherwise, with the same logic, we should use the test set for training, too, shouldn't we?

Wrap up: the test set is there solely for performance assessment of your model, and it should not be used in any stage of model building, including feature selection.

UPDATE (after comments):

the trends in the Test Set may be different

A standard (but often implicit) assumption here is that the training & test sets are qualitatively similar; it is exactly due to this assumption that we feel OK to just use simple random splits to get them. If we have reasons to believe that our data change in significant ways (not only between train & test, but during model deployment, too), the whole rationale breaks down, and completely different approaches are required.

Also, on doing so, there can be a high probability of Over-fitting

The only certain way of overfitting is to use the test set in any way during the pipeline (including for feature selection, as you suggest). Arguably, the linked blog post has enough arguments (including quotes & links) to be convincing. Classic example, the testimony in The Dangers of Overfitting or How to Drop 50 spots in 1 minute:

as the competition went on, I began to use much more feature selection and preprocessing. However, I made the classic mistake in my cross-validation method by not including this in the cross-validation folds (for more on this mistake, see this short description or section 7.10.2 in The Elements of Statistical Learning). This lead to increasingly optimistic cross-validation estimates.

As I have already said, although the discussion here is about cross-validation, it should not be difficult to convince yourself that it perfectly applies to the train/test case, too.

feature selection should be done in such a way that Model Performance is enhanced

Well, nobody can argue with this, of course! The catch is - which exact performance are we talking about? Because the Kaggler quoted above was indeed getting better "performance" as he was going along (applying a mistaken procedure), until his model was faced with real unseen data (the moment of truth!), and it unsurprisingly flopped.

Admittedly, this is not trivial stuff, and it may take some time until you internalize them (it's no coincidence that, as Hastie & Tibshirani demonstrate, there are even research papers where the procedure is performed wrongly). Until then, my advice to keep you safe, is: during all stages of model building (including feature selection), pretend that you don't have access to the test set at all, and that it becomes available only when you need to assess the performance of your final model.


问:
How to insert 3 php Array values as 3 MYSQL Columns
I need to insert array values in php as Columns in a MYSQL table.

```<code>$new_user = array(

        "Nom"  => $_POST['Nom'],

        "EmailID"     => $_POST['EmailID'],

        "localité"  => $_POST['localité']
    );

    $table = "memfis";
    $columnNames = implode(", ", array_keys($new_user));
    $columnPlaceholders = "'" . implode("', '", array_keys($new_user)) . "'";
    $sqld = "INSERT INTO $table ($columnNames) VALUES ($columnPlaceholders);";
    var_dump($sqld); exit;
    $stmt = $pdo->prepare($sqld);
    foreach ($columnNames as $name) {
    $placeholder = "'" . $name;
    $stmt->bindParam($placeholder, $new_user[$name]);
    }
    $connection->execute($sqld);
     echo "New record created successfully";
</code>```

It should have displayed " New row added succesfully " and the row should have been  added in the table.

答:
I tested the following with the original field names - specifically making note of the acute accent on the e and it failed - when I removed the accent and replaced with a standard letter e it worked fine

```<code><?php

    /* PDO dbo */
    $dbport =   3306;
    $dbhost =   'localhost';
    $dbuser =   'root';
    $dbpwd  =   'xxx';
    $dbname =   'xxx';

    $options=array(
        PDO::ATTR_CURSOR                    =>  PDO::CURSOR_SCROLL,
        PDO::ATTR_PERSISTENT                =>  false,
        PDO::MYSQL_ATTR_USE_BUFFERED_QUERY  =>  true,
        PDO::ATTR_EMULATE_PREPARES          =>  true,
        PDO::MYSQL_ATTR_INIT_COMMAND        =>  'SET NAMES \'utf8mb4\' COLLATE \'utf8mb4_general_ci\', @@sql_mode = STRICT_ALL_TABLES, @@foreign_key_checks = 1'
    );
    $dsn = 'mysql:host='.$dbhost.';port='.$dbport.';dbname='.$dbname.';charset=UTF8';
    $db = new PDO( $dsn, $dbuser, $dbpwd, $options );

    /* Emulate POST form submission */
    $_POST=[
        'Nom'       =>  'fred flintstone',
        'EmailID'   =>  'fred@bedrock.com',
        'localite'  =>  'Bedrock'
    ];

    $table='memfis';

    /* prepare field names */
    $fields = sprintf( '`%s`', implode( '`,`', array_keys( $_POST ) ) );

    /* placeholder arrays */
    $args = [];
    $vals = [];

    /* create placeholder variable names */
    foreach( $_POST as $field => $value ) {
        $args[]=sprintf( ':%s', strtolower( $field ) );
        $vals[ sprintf( ':%s', strtolower( $field ) ) ]=$value;
    }

    /* create the sql statement */
    $sql=sprintf(
        'insert into `%s` ( %s ) values ( %s );',
        $table,
        $fields,
        implode( ', ', $args )
    );

    $stmt = $db->prepare( $sql );
    if( $stmt ){

        # debug info
        printf("```%s\n%s```", $sql, print_r( $vals, true ) );

        # execute the statement
        $res=$stmt->execute( $vals );

        # did it or did it not work?
        if( $res ){
            echo "OK!";
        } else {
            echo "Bogus!";
        }
    }
?>
</code>```

The resultant output to screen of the above is:

```<code>insert into `memfis` ( `Nom`,`EmailID`,`localite` ) values ( :nom, :emailid, :localite );
Array
(
    [:nom] => fred flintstone
    [:emailid] => fred@bedrock.com
    [:localite] => Bedrock
)
OK!
</code>```

When using the original fieldname localité the following error occurs:

Warning: PDOStatement::execute() [pdostatement.execute.html]:
  SQLSTATE[HY093]: Invalid parameter number: parameter was not defined
  in .....

Body:
I need to insert array values in php as Columns in a MYSQL table.

$new_user = array(

        "Nom"  => $_POST['Nom'],

        "EmailID"     => $_POST['EmailID'],

        "localité"  => $_POST['localité']
    );

    $table = "memfis";
    $columnNames = implode(", ", array_keys($new_user));
    $columnPlaceholders = "'" . implode("', '", array_keys($new_user)) . "'";
    $sqld = "INSERT INTO $table ($columnNames) VALUES ($columnPlaceholders);";
    var_dump($sqld); exit;
    $stmt = $pdo->prepare($sqld);
    foreach ($columnNames as $name) {
    $placeholder = "'" . $name;
    $stmt->bindParam($placeholder, $new_user[$name]);
    }
    $connection->execute($sqld);
     echo "New record created successfully";

It should have displayed " New row added succesfully " and the row should have been  added in the table.

Body:
I tested the following with the original field names - specifically making note of the acute accent on the e and it failed - when I removed the accent and replaced with a standard letter e it worked fine

<?php

    /* PDO dbo */
    $dbport =   3306;
    $dbhost =   'localhost';
    $dbuser =   'root';
    $dbpwd  =   'xxx';
    $dbname =   'xxx';

    $options=array(
        PDO::ATTR_CURSOR                    =>  PDO::CURSOR_SCROLL,
        PDO::ATTR_PERSISTENT                =>  false,
        PDO::MYSQL_ATTR_USE_BUFFERED_QUERY  =>  true,
        PDO::ATTR_EMULATE_PREPARES          =>  true,
        PDO::MYSQL_ATTR_INIT_COMMAND        =>  'SET NAMES \'utf8mb4\' COLLATE \'utf8mb4_general_ci\', @@sql_mode = STRICT_ALL_TABLES, @@foreign_key_checks = 1'
    );
    $dsn = 'mysql:host='.$dbhost.';port='.$dbport.';dbname='.$dbname.';charset=UTF8';
    $db = new PDO( $dsn, $dbuser, $dbpwd, $options );

    /* Emulate POST form submission */
    $_POST=[
        'Nom'       =>  'fred flintstone',
        'EmailID'   =>  'fred@bedrock.com',
        'localite'  =>  'Bedrock'
    ];

    $table='memfis';

    /* prepare field names */
    $fields = sprintf( '`%s`', implode( '`,`', array_keys( $_POST ) ) );

    /* placeholder arrays */
    $args = [];
    $vals = [];

    /* create placeholder variable names */
    foreach( $_POST as $field => $value ) {
        $args[]=sprintf( ':%s', strtolower( $field ) );
        $vals[ sprintf( ':%s', strtolower( $field ) ) ]=$value;
    }

    /* create the sql statement */
    $sql=sprintf(
        'insert into `%s` ( %s ) values ( %s );',
        $table,
        $fields,
        implode( ', ', $args )
    );

    $stmt = $db->prepare( $sql );
    if( $stmt ){

        # debug info
        printf("<pre>%s\n%s</pre>", $sql, print_r( $vals, true ) );

        # execute the statement
        $res=$stmt->execute( $vals );

        # did it or did it not work?
        if( $res ){
            echo "OK!";
        } else {
            echo "Bogus!";
        }
    }
?>

The resultant output to screen of the above is:

insert into `memfis` ( `Nom`,`EmailID`,`localite` ) values ( :nom, :emailid, :localite );
Array
(
    [:nom] => fred flintstone
    [:emailid] => fred@bedrock.com
    [:localite] => Bedrock
)
OK!

When using the original fieldname localité the following error occurs:

Warning: PDOStatement::execute() [pdostatement.execute.html]:
  SQLSTATE[HY093]: Invalid parameter number: parameter was not defined
  in .....


问:
Handling non-default nested Json Reads
So I have following JSON:

```<code>{
  "senderEmail" : "sender@email.com",
  "recipientEmails" : ["first@email.com", "second@email.com"]
}
</code>```

and would like to map it to case class:

```<code>case class Payload (senderEmail: String, recipientEmails: Seq[String])
</code>```

using Play's Json Reads with email validator.

While it's trivial for a senderEmail, I'm having trouble with recipientEmails since it's both Seq and email so this will not work:

```<code>implicit val payloadRead: Reads[Payload] = (
    (JsPath \ "senderEmail").read[String](Reads.email) and
    (JsPath \ "recipientEmails").read[Seq[String]](Reads.seq))(Payload.apply _)
</code>```

I'm getting overloaded method value read with alternatives.

So how can I combine both Reads.seq and Reads.email?

答:
Just keep it simple ...

scala> import play.api.libs.json._

scala> import play.api.libs.functional.syntax._

scala> case class Payload (senderEmail: String, recipientEmails: Seq[String])
defined class Payload

scala> implicit val reads: Reads[Payload] = (
     |   (JsPath \ "senderEmail").read(Reads.email) and
     |   (JsPath \ "recipientEmails").read(Reads.seq(Reads.email))
     | )(Payload.apply _)
reads: play.api.libs.json.Reads[Payload] = play.api.libs.json.Reads$$...

scala> Json.parse("""{
     |   "senderEmail" : "sender@email.com",
     |   "recipientEmails" : ["first@email.com", "second@email.com"]
     | }""").validate[Payload]
res0: play.api.libs.json.JsResult[Payload] = JsSuccess(Payload(sender@email.com,Vector(first@email.com, second@email.com)),)
```

Title: Handling non-default nested Json Reads

Body:
So I have following JSON:

{
  "senderEmail" : "sender@email.com",
  "recipientEmails" : ["first@email.com", "second@email.com"]
}

and would like to map it to case class:

case class Payload (senderEmail: String, recipientEmails: Seq[String])

using Play's Json Reads with email validator.

While it's trivial for a senderEmail, I'm having trouble with recipientEmails since it's both Seq and email so this will not work:

implicit val payloadRead: Reads[Payload] = (
    (JsPath \ "senderEmail").read[String](Reads.email) and
    (JsPath \ "recipientEmails").read[Seq[String]](Reads.seq))(Payload.apply _)

I'm getting overloaded method value read with alternatives.

So how can I combine both Reads.seq and Reads.email?


问:
Not able to access nginx from outside world
Not able to access nginx from outside the server

I have used ansible role written by me to download nginx on linux machines. But i'm not bale to access that nginx service outside of the server (the one on which it is installed)

https://github.com/kishanagarwal/ansible_poc/tree/master/roles/nginx

You can access the code from above url

I am able to get a welcome page of nginx service running on Centos machines, but can't get anything when i tried to access ip address of machine running on ubuntu 14.04 and having nginx installed on it.

答:
Its simply means nginx port is not opened.
steps to follows:

login to your machine which is trying to access nginx.
if it is windows ,open  DOS prompt OR if it is linux, open terminal.
run following command :
telnet

Based on output , if port is not open, you can refer following guide to open port:

https://www.cyberciti.biz/faq/howto-rhel-linux-open-port-using-iptables/


问:
Should I protect a struct object with mutex?
I use 4 go routines to assign different member variables of a struct instance. Each member variable is only accessed by one go routine.

Do I need to add mutex when accessing the struct instance?

I am not sure if the 4 go routines access the same memory. I feel I should be cause all of them accesses the holder.

This code demonstrates what I'm doing.

```<code>package main

import (
    "fmt"
    "sync"
)

func main() {
    var wg sync.WaitGroup
    var res Response

    var mu sync.Mutex

    wg.Add(1)
    go func() {

        defer wg.Done()
        mu.Lock()
        defer mu.Unlock()
        res.A = []string{"a"}
    }()

    wg.Add(1)
    go func() {
        defer wg.Done()
        mu.Lock()
        defer mu.Unlock()
        res.B = "b"
    }()

    wg.Add(1)
    go func() {
        defer wg.Done()
        mu.Lock()
        defer mu.Unlock()
        res.C = 100
    }()

    wg.Add(1)
    go func() {
        defer wg.Done()
        mu.Lock()
        defer mu.Unlock()
        res.D = map[string]string{
            "d": "dd",
        }
    }()

    wg.Wait()

    fmt.Println(res)

}

type Response struct {
    A []string
    B string
    C int
    D map[string]string
}
</code>```

答:
You do not need a mutex for this program. As far as the Go memory model is concerned, separate fields of a struct are separate variables. Since the four goroutines are accessing four separate (sub-)variables, there is no data race, even without the mutex.

You can verify this by removing the mutex and running your program with the race detector enabled: https://golang.org/doc/articles/race_detector.html

Body:
I use 4 go routines to assign different member variables of a struct instance. Each member variable is only accessed by one go routine.

Do I need to add mutex when accessing the struct instance?

I am not sure if the 4 go routines access the same memory. I feel I should be cause all of them accesses the holder.

This code demonstrates what I'm doing.

package main

import (
    "fmt"
    "sync"
)

func main() {
    var wg sync.WaitGroup
    var res Response

    var mu sync.Mutex

    wg.Add(1)
    go func() {

        defer wg.Done()
        mu.Lock()
        defer mu.Unlock()
        res.A = []string{"a"}
    }()

    wg.Add(1)
    go func() {
        defer wg.Done()
        mu.Lock()
        defer mu.Unlock()
        res.B = "b"
    }()

    wg.Add(1)
    go func() {
        defer wg.Done()
        mu.Lock()
        defer mu.Unlock()
        res.C = 100
    }()

    wg.Add(1)
    go func() {
        defer wg.Done()
        mu.Lock()
        defer mu.Unlock()
        res.D = map[string]string{
            "d": "dd",
        }
    }()

    wg.Wait()

    fmt.Println(res)

}

type Response struct {
    A []string
    B string
    C int
    D map[string]string
}


问:
Binding Collection in wpf comboBox with mvvm (C#)
I am trying to using mvvm pattern with wpf to create an interface for a project previously did in win form.
In this project i have an object that contains some List<> that i have to show in real time on my interface with a combobox, the problem is that combobox don't change his values. I'm using the dll of mvvm fundation for implement NotifyPropertyChanged. I think to make some mistake but i don'y know where is it.

I've tried to do a simple code with only one list in viewmodel and without a model but the result doesn't change.

<Window x:Class="ProvaComboBox.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:ProvaComboBox"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <Grid.DataContext>
            <local:ViewModel />
        </Grid.DataContext>
        <Button Content="Generate" Command="{Binding Generate}"/>
        <Button Content="Clear" Command="{Binding Clear}"/>
        <ComboBox ItemsSource="{Binding Path=Word, Mode=OneWay}" />
    </Grid>
</Window>
```

```//view Model
    class ViewModel:ObservableObject
    {
        private List<string> _word;

        public List<string> Word
        {
            get { return _word; }
        }
        public ViewModel()
        {
            _word = new List<string>();
        }
        public ICommand Generate

        { get { return new RelayCommand(GenerateExecute); } }

        void GenerateExecute()
        {
            _prova.Add("pippo");
            _prova.Add("pluto");
            RaisePropertyChanged("Word");
        }
        public ICommand Clear
        { get { return new RelayCommand(ClearExecute); } }

        void ClearExecute()
        {
            _prova.Clear();
            RaisePropertyChanged("Word");
        }
    }

```

<pre class="lang-cs prettyprint-override"><code>//View:
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
    }
</code>```

I think that the problem it's RaisePropertyChanged, but it work correctly with normal variables.
I've tryed also using ObservableCollection and it work, but i can't use it with real project.

(p.s. Its my first question in stack overflow, sorry if i did some mistake!)

答:
use ObservableCollection like that

```<code>public ObservableCollection<string> Word
        {
            get => _word;
            set
            {
                _word= value;
                RaisePropertyChanged("Word");
            }
        }
</code>```

and change the binding mode in your combobox xaml code from OneWay to TwoWay or just remove it to be something like

```<code><ComboBox ItemsSource="{Binding Path=Word}" />
</code>```

Body:
I am trying to using mvvm pattern with wpf to create an interface for a project previously did in win form.
In this project i have an object that contains some List<> that i have to show in real time on my interface with a combobox, the problem is that combobox don't change his values. I'm using the dll of mvvm fundation for implement NotifyPropertyChanged. I think to make some mistake but i don'y know where is it.

I've tried to do a simple code with only one list in viewmodel and without a model but the result doesn't change.

<Window x:Class="ProvaComboBox.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:ProvaComboBox"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <Grid.DataContext>
            <local:ViewModel />
        </Grid.DataContext>
        <Button Content="Generate" Command="{Binding Generate}"/>
        <Button Content="Clear" Command="{Binding Clear}"/>
        <ComboBox ItemsSource="{Binding Path=Word, Mode=OneWay}" />
    </Grid>
</Window>

//view Model
    class ViewModel:ObservableObject
    {
        private List<string> _word;

        public List<string> Word
        {
            get { return _word; }
        }
        public ViewModel()
        {
            _word = new List<string>();
        }
        public ICommand Generate

        { get { return new RelayCommand(GenerateExecute); } }

        void GenerateExecute()
        {
            _prova.Add("pippo");
            _prova.Add("pluto");
            RaisePropertyChanged("Word");
        }
        public ICommand Clear
        { get { return new RelayCommand(ClearExecute); } }

        void ClearExecute()
        {
            _prova.Clear();
            RaisePropertyChanged("Word");
        }
    }

//View:
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
    }

I think that the problem it's RaisePropertyChanged, but it work correctly with normal variables.
I've tryed also using ObservableCollection and it work, but i can't use it with real project.

(p.s. Its my first question in stack overflow, sorry if i did some mistake!)

Body:
use ObservableCollection like that

public ObservableCollection<string> Word
        {
            get => _word;
            set
            {
                _word= value;
                RaisePropertyChanged("Word");
            }
        }

and change the binding mode in your combobox xaml code from OneWay to TwoWay or just remove it to be something like

<ComboBox ItemsSource="{Binding Path=Word}" />