问:
Why do I return a series of a chars for a pointer return type?
I am trying my best to return a pointer with a specific value. Though, I am not understanding why I am getting more chars than usual. I asked a few people and I was told that I am getting a substring?

Problem: I type in the word hotdog.
I expect to return a pointer at the index[2]. Though instead, I get the chars dog. Why is that? How would I get just index[2]? I am thinking about dereferencing it, but I am having problems in getting the return type to work.

I cannot change the return type or parameters for my function.

```<code>#include <iostream>

char * GetValueAtIndex(char * const c, int index);
void ReadString(char * c, int length);

int main()

{
    const int size = 10;
    char ma[size];
    char * pointer = ma;

    ReadString(ma, 20);
    std::cout << GetValueAtIndex(pointer, 3) << std::endl;
    system("pause");
}

void ReadString(char * c, int length)
{
    std::cin.getline(c, length);
}

char * GetValueAtIndex(char * const c, int index)
{

    return c + index;

}
</code>```

答:
Modify your function to return a value not a pointer:

```<code>char GetValueAtIndex(char * const c, int index){
    return *(c + index);
}
</code>```

or simply dereference a pointer returned by a function:

```<code>std::cout << *GetValueAtIndex(pointer, 3);
</code>```

When you have a char* pointer like:

```<code>char* p = "Hotdog";
</code>```

and send that p to std::cout it will be treated as a pointer to (a first character of a) C style string and printed as such. C style strings end with \0. So it will print out whatever the character the p points to followed by all the remaining characters until it reaches the end of the string that is \0.
If you increment a pointer it then points at the next character etc:

```<code>char* p = "Hotdog";
p++;
std::cout << p;
p+=3;
std::cout << p;
</code>```

If you just need to print a single character the p points at then send a dereferenced pointer to std::cout:

```<code>char* p = "Hotdog";
std::cout << *p;
</code>```

Body:
I am trying my best to return a pointer with a specific value. Though, I am not understanding why I am getting more chars than usual. I asked a few people and I was told that I am getting a substring?

Problem: I type in the word hotdog.
I expect to return a pointer at the index[2]. Though instead, I get the chars dog. Why is that? How would I get just index[2]? I am thinking about dereferencing it, but I am having problems in getting the return type to work.

I cannot change the return type or parameters for my function.

#include <iostream>

char * GetValueAtIndex(char * const c, int index);
void ReadString(char * c, int length);

int main()

{
    const int size = 10;
    char ma[size];
    char * pointer = ma;

    ReadString(ma, 20);
    std::cout << GetValueAtIndex(pointer, 3) << std::endl;
    system("pause");
}

void ReadString(char * c, int length)
{
    std::cin.getline(c, length);
}

char * GetValueAtIndex(char * const c, int index)
{

    return c + index;

}

Body:
Modify your function to return a value not a pointer:

char GetValueAtIndex(char * const c, int index){
    return *(c + index);
}

or simply dereference a pointer returned by a function:

std::cout << *GetValueAtIndex(pointer, 3);

When you have a char* pointer like:

char* p = "Hotdog";

and send that p to std::cout it will be treated as a pointer to (a first character of a) C style string and printed as such. C style strings end with \0. So it will print out whatever the character the p points to followed by all the remaining characters until it reaches the end of the string that is \0.
If you increment a pointer it then points at the next character etc:

char* p = "Hotdog";
p++;
std::cout << p;
p+=3;
std::cout << p;

If you just need to print a single character the p points at then send a dereferenced pointer to std::cout:

char* p = "Hotdog";
std::cout << *p;


来源: stackexchange

问:
How to save Images to database using ASP.NET Core?
I am working on a small blog using ASP.NET Core(MVC 6) EF Visual Studio. I have trouble finding how to save images to a database. I have read about IFormfile but I do not really understand how to go about it, I am stuck. I am new to this and would love to have a little help.

I want to save the image to the post I am creating(In the same form). I, therefore, want to save it to postID. Then I need to be able to display the image, how do I do that?

答:
You can use IFormFile to save image posted from view. Below is the sample code.

```<code>public class UserProfileViewModel
    {
        public string UserName { get; set; }
        public IFormFile UploadedImage { get; set; }
        public string ImageUrl { get; set; }
    }
</code>```

In view simply bind it with IFormFile property like:

```<code><img src="@Model.ImageUrl" alt="User Logo" asp-append-version="true" />
<input type="file" asp-for="UploadedImage" />
</code>```

In your controller you just need to save file on server like:

```<code>var filename = ContentDispositionHeaderValue
                                    .Parse(user.UploadedImage.ContentDisposition)
                                    .FileName
                                    .Trim('"');
                    filename = Path.Combine(webRoot, "/Content/UserProfile/", $@"\{filename}");
                    if (Directory.Exists(webRoot + "/Content/UserProfile/"))
                    {
                        using (FileStream fs = System.IO.File.Create(filename))
                        {
                            user.UploadedImage.CopyTo(fs);
                            fs.Flush();
                        }
                    }
model.ImageURL = "~/Content/Brands/" + user.UploadedImage.FileName;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
You can use IFormFile to save image posted from view. Below is the sample code.

public class UserProfileViewModel
    {
        public string UserName { get; set; }
        public IFormFile UploadedImage { get; set; }
        public string ImageUrl { get; set; }
    }

In view simply bind it with IFormFile property like:

<img src="@Model.ImageUrl" alt="User Logo" asp-append-version="true" />
<input type="file" asp-for="UploadedImage" />

In your controller you just need to save file on server like:

var filename = ContentDispositionHeaderValue
                                    .Parse(user.UploadedImage.ContentDisposition)
                                    .FileName
                                    .Trim('"');
                    filename = Path.Combine(webRoot, "/Content/UserProfile/", $@"\{filename}");
                    if (Directory.Exists(webRoot + "/Content/UserProfile/"))
                    {
                        using (FileStream fs = System.IO.File.Create(filename))
                        {
                            user.UploadedImage.CopyTo(fs);
                            fs.Flush();
                        }
                    }
model.ImageURL = "~/Content/Brands/" + user.UploadedImage.FileName;

ContentLicense: CC BY-SA 3.0


问:
Why am I not getting data from the reducer when I click on a button?
I am using React and Redux to build a simple app. There are four buttons: up, left, down, right. If I click on "up", it moves the item up and when I click "down", the item goes down and so on. However, when I clicked on the buttons, the item does not move at all. Even worse, I did not get any error messages in the console when I clicked on them. Here is my code so far:

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import { Provider, connect } from 'react-redux';
import { createStore, combineReducers } from 'redux';
import './index.css';
import registerServiceWorker from './registerServiceWorker';

const reducers = combineReducers({
    vertical: (state={style: 40}, action) => {
        console.log("Inside the vertial reducer", action.type);
        if (action.type === "UP") {
            //Reassign outside the return statement
            state.style = state.style - 10;
            return state;
        } else if (action.type === "DOWN") {
            state.style = state.style + 10;
            return state;
        } else {
            return state;
        }
    },

    horizontal: (state={style: 40}, action) => {
        console.log("Inside the horizontal reducer", action.type);
        if (action.type === "LEFT") {
            state.style = state.style - 10;
            return state;
        } else if (action.type === "RIGHT") {
            state.style = state.style + 10;
            return state;
        } else {
            return state;
        }
    }
});

const a = state => {
    return {
        vertical: state.vertical.style,
        horizontal: state.horizontal.style
    };
};

const b = dispatcher => {
    return {
        clickUp: () => {
            dispatcher({ type: "UP" })
        },
        clickDown: () => {
            dispatcher({ type: "DOWN" })
        },
        clickLeft: () => {
            dispatcher({ type: "LEFT" })
        },
        clickRight: () => {
            dispatcher({ type: "RIGHT" })
        }
    };
};

const container = connect(a, b);

//This is my component
const C = ({ vertical, horizontal, clickUp, clickDown, clickLeft, clickRight }) => {
        console.log("this is from C", vertical);
        return (
            <div>
                <button onClick={clickUp}>Up</button>
                <button onClick={clickDown}>Down</button>
                <button onClick={clickLeft}>Left</button>
                <button onClick={clickRight}>Right</button>
                <img style={{top:vertical+"px", left:horizontal+"px", position:"absolute", width:"40px", height:"40px"}} src={"https://media.licdn.com/mpr/mpr/shrinknp_400_400/AAEAAQAAAAAAAAglAAAAJDIwYjM0NDEwLTViMTMtNGE2Yi05OGZlLTUwOGE2N2IxMjFlOQ.jpg"} alt="" />
            </div>
        );
};

const App = container(C);

const store = createStore(reducers);

ReactDOM.render(
    <Provider store={store}>
        <App />
    </Provider>, document.getElementById('root'));
registerServiceWorker();
</code>```

I console.log the type in my vertical and horizontal reducers and is giving the correct type when I clicked on the button. When I tried to console.log the vertical in my C component, I am not getting any value when I clicked on a button. It is suppose to log out a number in my console, but is not. So, it seems like my state is not being updated when I clicked on the buttons without giving me any errors in the console. I looked through my code many times and cannot find any thing. May I get advice to how to fix my code and why my code is failing silently?

答:
In your reducer, you are overwriting the previous state instead of creating a new state. Redux won't update the component state as it thinks it is still the same as the previous, and so tries to optimize the rerender process and not do so.

Update your reducers to the following, and your app should work as expected:

```<code>const reducers = combineReducers({
    vertical: (state={style: 40}, action) => {
        switch (action.type) {
            case 'UP': {
                return Object.assign({}, state, {
                    style: state.style - 10
                });
            }
            case 'DOWN': {
                return Object.assign({}, state, {
                    style: state.style + 10
                });
            }
            default: {
                return state;
            }
        }
    },

    horizontal: (state={style: 40}, action) => {
        switch (action.type) {
            case 'LEFT': {
                return Object.assign({}, state, {
                    style: state.style - 10
                });
            }
            case 'RIGHT': {
                return Object.assign({}, state, {
                    style: state.style + 10
                });
            }
            default: {
                return state;
            }
        }
    }
});
</code>```

Body:
I am using React and Redux to build a simple app. There are four buttons: up, left, down, right. If I click on "up", it moves the item up and when I click "down", the item goes down and so on. However, when I clicked on the buttons, the item does not move at all. Even worse, I did not get any error messages in the console when I clicked on them. Here is my code so far:

import React from 'react';
import ReactDOM from 'react-dom';
import { Provider, connect } from 'react-redux';
import { createStore, combineReducers } from 'redux';
import './index.css';
import registerServiceWorker from './registerServiceWorker';

const reducers = combineReducers({
    vertical: (state={style: 40}, action) => {
        console.log("Inside the vertial reducer", action.type);
        if (action.type === "UP") {
            //Reassign outside the return statement
            state.style = state.style - 10;
            return state;
        } else if (action.type === "DOWN") {
            state.style = state.style + 10;
            return state;
        } else {
            return state;
        }
    },

    horizontal: (state={style: 40}, action) => {
        console.log("Inside the horizontal reducer", action.type);
        if (action.type === "LEFT") {
            state.style = state.style - 10;
            return state;
        } else if (action.type === "RIGHT") {
            state.style = state.style + 10;
            return state;
        } else {
            return state;
        }
    }
});

const a = state => {
    return {
        vertical: state.vertical.style,
        horizontal: state.horizontal.style
    };
};

const b = dispatcher => {
    return {
        clickUp: () => {
            dispatcher({ type: "UP" })
        },
        clickDown: () => {
            dispatcher({ type: "DOWN" })
        },
        clickLeft: () => {
            dispatcher({ type: "LEFT" })
        },
        clickRight: () => {
            dispatcher({ type: "RIGHT" })
        }
    };
};

const container = connect(a, b);

//This is my component
const C = ({ vertical, horizontal, clickUp, clickDown, clickLeft, clickRight }) => {
        console.log("this is from C", vertical);
        return (

                <button onClick={clickUp}>Up</button>
                <button onClick={clickDown}>Down</button>
                <button onClick={clickLeft}>Left</button>
                <button onClick={clickRight}>Right</button>

        );
};

const App = container(C);

const store = createStore(reducers);

ReactDOM.render(
    <Provider store={store}>
        <App />
    </Provider>, document.getElementById('root'));
registerServiceWorker();

I console.log the type in my vertical and horizontal reducers and is giving the correct type when I clicked on the button. When I tried to console.log the vertical in my C component, I am not getting any value when I clicked on a button. It is suppose to log out a number in my console, but is not. So, it seems like my state is not being updated when I clicked on the buttons without giving me any errors in the console. I looked through my code many times and cannot find any thing. May I get advice to how to fix my code and why my code is failing silently?

Body:
In your reducer, you are overwriting the previous state instead of creating a new state. Redux won't update the component state as it thinks it is still the same as the previous, and so tries to optimize the rerender process and not do so.

Update your reducers to the following, and your app should work as expected:

const reducers = combineReducers({
    vertical: (state={style: 40}, action) => {
        switch (action.type) {
            case 'UP': {
                return Object.assign({}, state, {
                    style: state.style - 10
                });
            }
            case 'DOWN': {
                return Object.assign({}, state, {
                    style: state.style + 10
                });
            }
            default: {
                return state;
            }
        }
    },

    horizontal: (state={style: 40}, action) => {
        switch (action.type) {
            case 'LEFT': {
                return Object.assign({}, state, {
                    style: state.style - 10
                });
            }
            case 'RIGHT': {
                return Object.assign({}, state, {
                    style: state.style + 10
                });
            }
            default: {
                return state;
            }
        }
    }
});


问:
Access Tab Control - Set Pages Visibilty based on Subform Records
I know how to do this, but wondering if I might be able to write a more elegant solution.  I have a form with a tab control.  The control has 14 pages, each one, with it's own sub form.  One of the pages (pgRequirements) has a subform of requirements, with a combo control "Requirement Type". It is a continuous form, so the user can add as many requirements as they want, for the main record.

There are 9 of those requirements, which have their own tab control page / sub form.  I want to set visibility of those tab control pages, based on this parent's sub form requirements.  So a current main record, can have multiple sub-requirement records. If any of those match e.g. requirement type A, than page A should be visible, otherwise it should not be.

I need this code to run anytime the main form is loaded, and the detail is made visible (meaning a main record has been chosen from a find form). Also anytime a requirement record is added or removed.  The below is assuming that the parent-child links on the main form to subform will limit the requirement records, to just those that are for the current main record.

Here is the simple code, that will do the job, but is probably over-written:

```<code>If Me.FKRequirementType.Column(1) = "ReqType1" Then
    Me.Parent!pgReqType1.Visible = True
Else
    Me.Parent!pgReqType1.Visible = False
End If

If Me.FKRequirementType.Column(1) = "ReqType2" Then
    Me.Parent!pgReqType2.Visible = True
Else
    Me.Parent!pgReqType2.Visible = False
End If

If Me.FKRequirementType.Column(1) = "ReqType3" Then
    Me.Parent!pgReqType3.Visible = True
Else
    Me.Parent!pgReqType3.Visible = False
End If

If Me.FKRequirementType.Column(1) = "ReqType4" Then
    Me.Parent!pgReqType4.Visible = True
Else
    Me.Parent!pgReqType4.Visible = False
End If
</code>```

Thanks!

EDIT

I turned this into a public function, so I can call it from anywhere.  One problem.  It's not working lol (small problem).  I don't get any errors, but all the tab control pages are visible.  When I add a new record, most of them should be hidden.  I have a tblReqType table, with all the requirement types.  I added a column to this, with the exact name of it's corresponding tab control page name, so I can loop through that table, for all records where that page name is not null, and set their page visible or not, based on the current main record ID having a record-requirement (cross reference table) record for each requirement type.

This is the public function I wrote.  Can anyone help me understand what I'm missing in these loops for setting the visibility true (vtrue) vs setting the visibility false (vfalse)

```<code>Public Function ShowRequirements()
    Dim db As DAO.Database
    Dim strRstVTrue As String
    Dim rstvTrue As DAO.Recordset
    Dim strRstVFalse As String
    Dim rstvFalse As DAO.Recordset
    Dim strFieldName As String

    'Setup the recordset
    Set db = CurrentDb
    strRstVTrue = "SELECT tblMRecordRequirements.ID, tblMRecordRequirements.FKMC, tblReqType.txtRequirementPage " & _
    "FROM tblMRecordRequirements LEFT JOIN tblReqType ON tblMRecordRequirements.FKRequirementType = tblReqType.ID " & _
    "WHERE tblReqType.txtRequirementPage Is Not Null AND tblMRecordRequirements.FKMC = " & Nz(Forms!frmMRecords!ID, 0)

    strRstVFalse = "SELECT tblReqType.ID, tblReqType.txtRequirementPage, tblMRecordRequirements.FKMC " & _
    "FROM tblReqType LEFT JOIN tblMRecordRequirements ON tblReqType.ID = tblMRecordRequirements.FKRequirementType " & _
    "WHERE tblReqType.txtRequirementPage Is Not Null AND tblMRecordRequirements.FKMC <> " & Nz(Forms!frmMRecords!ID, 0)

    Set rstvTrue = CurrentDb.OpenRecordset(strRstVTrue, dbOpenDynaset, dbSeeChanges)
    Set rstvFalse = CurrentDb.OpenRecordset(strRstVFalse, dbOpenDynaset, dbSeeChanges)
    strFieldName = "txtRequirementPage"
    Do While Not rstvTrue.EOF
        Forms!frmMRecords.tbMRecordSubs.Pages(rstvTrue.Fields(strFieldName)).Visible = True
    Loop
    Do While Not rstvFalse.EOF
        Forms!frmMRecords.tbMRecordSubs.Pages(rstvFalse.Fields(strFieldName)).Visible = False
    Loop
End Function
</code>```

If anyone can help me figure out my stupidity, you deserve an up vote, a check mark, and a cookie.

EDIT again

Below is updated code for the public function.  I fixed the rs for the true query, and I added in the MoveNext for the loops.

Public Function ShowRequirements()
        Dim db As DAO.Database
        Dim strRstVTrue As String
        Dim rstvTrue As DAO.Recordset
        Dim strRstVFalse As String
        Dim rstvFalse As DAO.Recordset
        Dim strFieldName As String

```<code>    'Setup the recordset
    Set db = CurrentDb
    strRstVTrue = "SELECT tblMRecordRequirements.ID, tblMRecordRequirements.FKMC, tblReqType.txtRequirementPage " & _
    "FROM tblMRecordRequirements LEFT JOIN tblReqType ON tblMRecordRequirements.FKRequirementType = tblReqType.ID " & _
    "WHERE tblReqType.txtRequirementPage Is Not Null AND tblMRecordRequirements.FKMC = " & Nz(Forms!frmMRecords!ID, 0)

    strRstVFalse = "SELECT tblReqType.ID, tblReqType.txtRequirementPage, tblMRecordRequirements.FKMC " & _
    "FROM tblReqType LEFT JOIN tblMRecordRequirements ON tblReqType.ID = tblMRecordRequirements.FKRequirementType " & _
    "WHERE tblReqType.txtRequirementPage Is Not Null AND tblMRecordRequirements.FKMC <> Is Null"

    Set rstvTrue = CurrentDb.OpenRecordset(strRstVTrue, dbOpenDynaset, dbSeeChanges)
    Set rstvFalse = CurrentDb.OpenRecordset(strRstVFalse, dbOpenDynaset, dbSeeChanges)
    strFieldName = "txtRequirementPage"
    Do While Not rstvTrue.EOF
        Forms!frmMRecords.tbMRecordSubs.Pages(rstvTrue.Fields(strFieldName)).Visible = True
    rstvTrue.MoveNext
    Loop
    Do While Not rstvFalse.EOF
        Forms!frmMRecords.tbMRecordSubs.Pages(rstvFalse.Fields(strFieldName)).Visible = False
    rstvFalse.MoveNext
    Loop
End Function
</code>```

EDIT REDUX

I think I may have it worked out, but let me know what you all think.  I really appreciate all your thoughts on this, as I know you all have a lot of experience not just in figuring out these kinds of challenges, but ensuring the code is good and not prone to issues.

Here is where I am at:

```<code>Public Function ShowRequirements()
    Dim db As DAO.Database
    Dim db2 As DAO.Database
    Dim strRstVTrue As String
    Dim rstvTrue As DAO.Recordset
    Dim strRstVFalse As String
    Dim rstvFalse As DAO.Recordset
    Dim strFieldName As String

    strFieldName = "txtRequirementPage"
    Set db = CurrentDb
    Set db2 = CurrentDb

    strRstVTrue = "SELECT tblReqType.txtRequirementPage " & _
    "FROM tblReqType LEFT JOIN tblMRecordRequirements ON tblMRecordRequirements.FKRequirementType = tblReqType.ID " & _
    "WHERE tblReqType.txtRequirementPage Is Not Null AND tblMRecordRequirements.FKMC = " & MCID

    strRstVFalse = "SELECT tblReqType.txtRequirementPage " & _
    "FROM tblReqType LEFT JOIN tblMRecordRequirements ON tblMRecordRequirements.FKRequirementType = tblReqType.ID " & _
    "WHERE tblMRecordRequirements.ID Not In (Select ID From [tblMRecordRequirements] WHERE [tblMRecordRequirements]![FKMC] = " & MCID & _
    ") AND tblReqType.txtRequirementPage Is Not Null;"

    Set rstvTrue = db.OpenRecordset(strRstVTrue, dbOpenDynaset, dbSeeChanges)
    Set rstvFalse = db2.OpenRecordset(strRstVFalse, dbOpenDynaset, dbSeeChanges)
    Do While Not rstvTrue.EOF
        Forms!frmMRecords.tbMRecordSubs.Pages(rstvTrue.Fields(strFieldName)).Visible = True
    rstvTrue.MoveNext
    Loop
    Do While Not rstvFalse.EOF
        Forms!frmMRecords.tbMRecordSubs.Pages(rstvFalse.Fields(strFieldName)).Visible = False
    rstvFalse.MoveNext
    Loop
End Function
</code>```

答:
This really goes against my better judgement of Stack Overflow principles --to not answer multi-part, continuing debugging questions-- but I really want a cookie.

How could the posted code have ever worked, since you are not moving through either recordset?  There are no MoveNext calls.  That means that both recordsets are empty or an error is being thrown that is being ignored somewhere (i.e. On Error Resume Next).  Otherwise, it should lock up Access with infinite loops.  Sometimes you can stop the code with Ctrl+Break, but not always successful in Access.

More precise table schema is required to properly interpret your data, but I'll make some assumptions.  You state that tblReqType contains all requirement types.  I'll assume that tblMRecordRequirements contains rows only for requirements which are "applied" (a.k.a. "on", "selected") for the ID value in tblMRecordRequirements.FKMC. Assuming the converse, if there are no rows in tblMRecordRequirements with ID in tblMRecordRequirements.FKMC for a given tblMRecordRequirements.FKRequirementType, then the requirement is not "applied" to that ID.

Does every row in tblReqType have a value in txtRequirementPage, or do some rows have null values?  Also, can multiple requirements have the same page specified?  Or is it a true one-to-one requirement-to-page mapping with no null values?

First of all why would the first query not be an INNER JOIN, since I assume that only records that match in both tables should be returned for the Visible = True condition?  Depending on your answers above, this would probably make the condition tblReqType.txtRequirementPage Is Not Null unnecessary in the first query.

Simply reversing a LEFT JOIN will not return what you want especially if you select all other ID values ( tblMRecordRequirements.FKMC <>  Nz(Forms!frmMRecords!ID, 0) ).  All that does is give you the requirements for every other ID values.  Not only will that be inefficient since it could return many, many irrelevant records, it could be likely that over all other ID values that every possible requirement would be applied, so that the second query will essentially cause all requirements to be invisible.

Further picky observations:

If Forms!frmMRecords!ID is null, then you might as well not even execute the queries.  You should check that value for null separately and perform appropriate actions rather than letting that specific condition fall through the other code, even if the end side effect is what you desire.  It makes the code harder to debug and interpret properly.  In other words write code that does "If ID is null, set all pages to visible = false, then exit the sub (i.e. skip other code)"

It's more efficient to get a read-only snapshot rather than an fully-updatable Dynaset recordset: Too much overhead just for looping through without data manipulation.

Proper break points, debug output and error handling code can help identify bad code.  It is worth tracing through results of recordsets manually to inspect values and proper SQL syntax.

Try this:

```<code>Public Sub ShowRequirements()
    Dim db As DAO.Database
    Dim iID As Long '? Assuming long integer
    Dim strSQL As String
    Dim rsTabs As DAO.Recordset

    On Error Resume Next
    iID = -1 '* Set to bogus value
    If Not IsNull(Forms!frmMRecords!ID) Then
      iID = Forms!frmMRecords!ID
    End If

    If iID = -1 Or Err.Number <> 0 Then
      '* Problem accessing ID control on form (empty recordset, new record row, etc.)
      '*  or it is null

      'Set all tab pages to Visible = False?
      Exit Sub
    End If

    On Error GoTo Catch
    '* Setup the recordset
    Set db = CurrentDb

    '* Use embedded query (replacable with saved query) for filtering on ID values.
    '* This is critical so that the LEFT JOIN does not return or filter records
    '* based on other ID values.
    strSQL = _
      "SELECT tblReqType.ID, tblReqType.txtRequirementPage, (IDReq.FKRequirementType Is Not Null) As ShowTab " & _
      " FROM tblReqType LEFT JOIN" & _
        " (SELECT MReq.FKRequirementType FROM tblMRecordRequirements AS MReq " & _
          " WHERE MReq.FKMC = " & iID & ") AS IDReq" & _
        " ON tblReqType.ID = IDReq.FKRequirementType" & _
        " WHERE tblReqType.txtRequirementPage Is Not Null"

    Set rsTabs = db.OpenRecordset(strRstVTrue, dbOpenSnapshot, dbReadOnly)
    Do While Not rsTabs.EOF
        Forms!frmMRecords.tbMRecordSubs.Pages(rsTabs!txtRequirementPage).Visible = rsTabs!ShowTab
        rsTabs.MoveNext '* Advance recordset.  (Avoid infinite loops.)
    Loop

CloseAll:
    On Error Resume Next
    '* Best habit to explicitly close recordsets and database connections, even when not necessary (since they'll close automatically when they go out of scope)
    If Not rsTabs Is Nothing Then
      rsTabs.Close
      Set rsTabs = Nothing
    End If
    Set db = Nothing

    Exit Sub
Catch:
    '* At least report error for development
    Debug.Print "ShowRequirements(): Error: " & Err.Number & ": " & Err.Description

    '* Show MsgBox or update form status control?
    '* Set all tab pages to Visible = False?
    '* Form state could be misleading without proper user notification and/or error handling

    Resume CloseAll
End Sub
</code>```

Body:
I know how to do this, but wondering if I might be able to write a more elegant solution.  I have a form with a tab control.  The control has 14 pages, each one, with it's own sub form.  One of the pages (pgRequirements) has a subform of requirements, with a combo control "Requirement Type". It is a continuous form, so the user can add as many requirements as they want, for the main record.

There are 9 of those requirements, which have their own tab control page / sub form.  I want to set visibility of those tab control pages, based on this parent's sub form requirements.  So a current main record, can have multiple sub-requirement records. If any of those match e.g. requirement type A, than page A should be visible, otherwise it should not be.

I need this code to run anytime the main form is loaded, and the detail is made visible (meaning a main record has been chosen from a find form). Also anytime a requirement record is added or removed.  The below is assuming that the parent-child links on the main form to subform will limit the requirement records, to just those that are for the current main record.

Here is the simple code, that will do the job, but is probably over-written:

If Me.FKRequirementType.Column(1) = "ReqType1" Then
    Me.Parent!pgReqType1.Visible = True
Else
    Me.Parent!pgReqType1.Visible = False
End If

If Me.FKRequirementType.Column(1) = "ReqType2" Then
    Me.Parent!pgReqType2.Visible = True
Else
    Me.Parent!pgReqType2.Visible = False
End If

If Me.FKRequirementType.Column(1) = "ReqType3" Then
    Me.Parent!pgReqType3.Visible = True
Else
    Me.Parent!pgReqType3.Visible = False
End If

If Me.FKRequirementType.Column(1) = "ReqType4" Then
    Me.Parent!pgReqType4.Visible = True
Else
    Me.Parent!pgReqType4.Visible = False
End If

Thanks!

EDIT

I turned this into a public function, so I can call it from anywhere.  One problem.  It's not working lol (small problem).  I don't get any errors, but all the tab control pages are visible.  When I add a new record, most of them should be hidden.  I have a tblReqType table, with all the requirement types.  I added a column to this, with the exact name of it's corresponding tab control page name, so I can loop through that table, for all records where that page name is not null, and set their page visible or not, based on the current main record ID having a record-requirement (cross reference table) record for each requirement type.

This is the public function I wrote.  Can anyone help me understand what I'm missing in these loops for setting the visibility true (vtrue) vs setting the visibility false (vfalse)

Public Function ShowRequirements()
    Dim db As DAO.Database
    Dim strRstVTrue As String
    Dim rstvTrue As DAO.Recordset
    Dim strRstVFalse As String
    Dim rstvFalse As DAO.Recordset
    Dim strFieldName As String

    'Setup the recordset
    Set db = CurrentDb
    strRstVTrue = "SELECT tblMRecordRequirements.ID, tblMRecordRequirements.FKMC, tblReqType.txtRequirementPage " & _
    "FROM tblMRecordRequirements LEFT JOIN tblReqType ON tblMRecordRequirements.FKRequirementType = tblReqType.ID " & _
    "WHERE tblReqType.txtRequirementPage Is Not Null AND tblMRecordRequirements.FKMC = " & Nz(Forms!frmMRecords!ID, 0)

    strRstVFalse = "SELECT tblReqType.ID, tblReqType.txtRequirementPage, tblMRecordRequirements.FKMC " & _
    "FROM tblReqType LEFT JOIN tblMRecordRequirements ON tblReqType.ID = tblMRecordRequirements.FKRequirementType " & _
    "WHERE tblReqType.txtRequirementPage Is Not Null AND tblMRecordRequirements.FKMC <> " & Nz(Forms!frmMRecords!ID, 0)

    Set rstvTrue = CurrentDb.OpenRecordset(strRstVTrue, dbOpenDynaset, dbSeeChanges)
    Set rstvFalse = CurrentDb.OpenRecordset(strRstVFalse, dbOpenDynaset, dbSeeChanges)
    strFieldName = "txtRequirementPage"
    Do While Not rstvTrue.EOF
        Forms!frmMRecords.tbMRecordSubs.Pages(rstvTrue.Fields(strFieldName)).Visible = True
    Loop
    Do While Not rstvFalse.EOF
        Forms!frmMRecords.tbMRecordSubs.Pages(rstvFalse.Fields(strFieldName)).Visible = False
    Loop
End Function

If anyone can help me figure out my stupidity, you deserve an up vote, a check mark, and a cookie.

EDIT again

Below is updated code for the public function.  I fixed the rs for the true query, and I added in the MoveNext for the loops.

Public Function ShowRequirements()
        Dim db As DAO.Database
        Dim strRstVTrue As String
        Dim rstvTrue As DAO.Recordset
        Dim strRstVFalse As String
        Dim rstvFalse As DAO.Recordset
        Dim strFieldName As String

    'Setup the recordset
    Set db = CurrentDb
    strRstVTrue = "SELECT tblMRecordRequirements.ID, tblMRecordRequirements.FKMC, tblReqType.txtRequirementPage " & _
    "FROM tblMRecordRequirements LEFT JOIN tblReqType ON tblMRecordRequirements.FKRequirementType = tblReqType.ID " & _
    "WHERE tblReqType.txtRequirementPage Is Not Null AND tblMRecordRequirements.FKMC = " & Nz(Forms!frmMRecords!ID, 0)

    strRstVFalse = "SELECT tblReqType.ID, tblReqType.txtRequirementPage, tblMRecordRequirements.FKMC " & _
    "FROM tblReqType LEFT JOIN tblMRecordRequirements ON tblReqType.ID = tblMRecordRequirements.FKRequirementType " & _
    "WHERE tblReqType.txtRequirementPage Is Not Null AND tblMRecordRequirements.FKMC <> Is Null"

    Set rstvTrue = CurrentDb.OpenRecordset(strRstVTrue, dbOpenDynaset, dbSeeChanges)
    Set rstvFalse = CurrentDb.OpenRecordset(strRstVFalse, dbOpenDynaset, dbSeeChanges)
    strFieldName = "txtRequirementPage"
    Do While Not rstvTrue.EOF
        Forms!frmMRecords.tbMRecordSubs.Pages(rstvTrue.Fields(strFieldName)).Visible = True
    rstvTrue.MoveNext
    Loop
    Do While Not rstvFalse.EOF
        Forms!frmMRecords.tbMRecordSubs.Pages(rstvFalse.Fields(strFieldName)).Visible = False
    rstvFalse.MoveNext
    Loop
End Function

EDIT REDUX

I think I may have it worked out, but let me know what you all think.  I really appreciate all your thoughts on this, as I know you all have a lot of experience not just in figuring out these kinds of challenges, but ensuring the code is good and not prone to issues.

Here is where I am at:

Public Function ShowRequirements()
    Dim db As DAO.Database
    Dim db2 As DAO.Database
    Dim strRstVTrue As String
    Dim rstvTrue As DAO.Recordset
    Dim strRstVFalse As String
    Dim rstvFalse As DAO.Recordset
    Dim strFieldName As String

    strFieldName = "txtRequirementPage"
    Set db = CurrentDb
    Set db2 = CurrentDb

    strRstVTrue = "SELECT tblReqType.txtRequirementPage " & _
    "FROM tblReqType LEFT JOIN tblMRecordRequirements ON tblMRecordRequirements.FKRequirementType = tblReqType.ID " & _
    "WHERE tblReqType.txtRequirementPage Is Not Null AND tblMRecordRequirements.FKMC = " & MCID

    strRstVFalse = "SELECT tblReqType.txtRequirementPage " & _
    "FROM tblReqType LEFT JOIN tblMRecordRequirements ON tblMRecordRequirements.FKRequirementType = tblReqType.ID " & _
    "WHERE tblMRecordRequirements.ID Not In (Select ID From [tblMRecordRequirements] WHERE [tblMRecordRequirements]![FKMC] = " & MCID & _
    ") AND tblReqType.txtRequirementPage Is Not Null;"

    Set rstvTrue = db.OpenRecordset(strRstVTrue, dbOpenDynaset, dbSeeChanges)
    Set rstvFalse = db2.OpenRecordset(strRstVFalse, dbOpenDynaset, dbSeeChanges)
    Do While Not rstvTrue.EOF
        Forms!frmMRecords.tbMRecordSubs.Pages(rstvTrue.Fields(strFieldName)).Visible = True
    rstvTrue.MoveNext
    Loop
    Do While Not rstvFalse.EOF
        Forms!frmMRecords.tbMRecordSubs.Pages(rstvFalse.Fields(strFieldName)).Visible = False
    rstvFalse.MoveNext
    Loop
End Function

Body:
This really goes against my better judgement of Stack Overflow principles --to not answer multi-part, continuing debugging questions-- but I really want a cookie.

How could the posted code have ever worked, since you are not moving through either recordset?  There are no MoveNext calls.  That means that both recordsets are empty or an error is being thrown that is being ignored somewhere (i.e. On Error Resume Next).  Otherwise, it should lock up Access with infinite loops.  Sometimes you can stop the code with Ctrl+Break, but not always successful in Access.

More precise table schema is required to properly interpret your data, but I'll make some assumptions.  You state that tblReqType contains all requirement types.  I'll assume that tblMRecordRequirements contains rows only for requirements which are "applied" (a.k.a. "on", "selected") for the ID value in tblMRecordRequirements.FKMC. Assuming the converse, if there are no rows in tblMRecordRequirements with ID in tblMRecordRequirements.FKMC for a given tblMRecordRequirements.FKRequirementType, then the requirement is not "applied" to that ID.

Does every row in tblReqType have a value in txtRequirementPage, or do some rows have null values?  Also, can multiple requirements have the same page specified?  Or is it a true one-to-one requirement-to-page mapping with no null values?

First of all why would the first query not be an INNER JOIN, since I assume that only records that match in both tables should be returned for the Visible = True condition?  Depending on your answers above, this would probably make the condition tblReqType.txtRequirementPage Is Not Null unnecessary in the first query.

Simply reversing a LEFT JOIN will not return what you want especially if you select all other ID values ( tblMRecordRequirements.FKMC <>  Nz(Forms!frmMRecords!ID, 0) ).  All that does is give you the requirements for every other ID values.  Not only will that be inefficient since it could return many, many irrelevant records, it could be likely that over all other ID values that every possible requirement would be applied, so that the second query will essentially cause all requirements to be invisible.

Further picky observations:

If Forms!frmMRecords!ID is null, then you might as well not even execute the queries.  You should check that value for null separately and perform appropriate actions rather than letting that specific condition fall through the other code, even if the end side effect is what you desire.  It makes the code harder to debug and interpret properly.  In other words write code that does "If ID is null, set all pages to visible = false, then exit the sub (i.e. skip other code)"

It's more efficient to get a read-only snapshot rather than an fully-updatable Dynaset recordset: Too much overhead just for looping through without data manipulation.

Proper break points, debug output and error handling code can help identify bad code.  It is worth tracing through results of recordsets manually to inspect values and proper SQL syntax.

Try this:

Public Sub ShowRequirements()
    Dim db As DAO.Database
    Dim iID As Long '? Assuming long integer
    Dim strSQL As String
    Dim rsTabs As DAO.Recordset

    On Error Resume Next
    iID = -1 '* Set to bogus value
    If Not IsNull(Forms!frmMRecords!ID) Then
      iID = Forms!frmMRecords!ID
    End If

    If iID = -1 Or Err.Number <> 0 Then
      '* Problem accessing ID control on form (empty recordset, new record row, etc.)
      '*  or it is null

      'Set all tab pages to Visible = False?
      Exit Sub
    End If

    On Error GoTo Catch
    '* Setup the recordset
    Set db = CurrentDb

    '* Use embedded query (replacable with saved query) for filtering on ID values.
    '* This is critical so that the LEFT JOIN does not return or filter records
    '* based on other ID values.
    strSQL = _
      "SELECT tblReqType.ID, tblReqType.txtRequirementPage, (IDReq.FKRequirementType Is Not Null) As ShowTab " & _
      " FROM tblReqType LEFT JOIN" & _
        " (SELECT MReq.FKRequirementType FROM tblMRecordRequirements AS MReq " & _
          " WHERE MReq.FKMC = " & iID & ") AS IDReq" & _
        " ON tblReqType.ID = IDReq.FKRequirementType" & _
        " WHERE tblReqType.txtRequirementPage Is Not Null"

    Set rsTabs = db.OpenRecordset(strRstVTrue, dbOpenSnapshot, dbReadOnly)
    Do While Not rsTabs.EOF
        Forms!frmMRecords.tbMRecordSubs.Pages(rsTabs!txtRequirementPage).Visible = rsTabs!ShowTab
        rsTabs.MoveNext '* Advance recordset.  (Avoid infinite loops.)
    Loop

CloseAll:
    On Error Resume Next
    '* Best habit to explicitly close recordsets and database connections, even when not necessary (since they'll close automatically when they go out of scope)
    If Not rsTabs Is Nothing Then
      rsTabs.Close
      Set rsTabs = Nothing
    End If
    Set db = Nothing

    Exit Sub
Catch:
    '* At least report error for development
    Debug.Print "ShowRequirements(): Error: " & Err.Number & ": " & Err.Description

    '* Show MsgBox or update form status control?
    '* Set all tab pages to Visible = False?
    '* Form state could be misleading without proper user notification and/or error handling

    Resume CloseAll
End Sub


问:
Python namespaced xml-parsing error
What's wrong with the following code? I am expecting boogie as output.</p>

```<code>import urllib.request
from html.parser import HTMLParser
import xml.etree.ElementTree as ET

html = '''<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
 xmlns="http://purl.org/rss/1.0/"
 xmlns:enc="http://purl.oclc.org/net/rss_2.0/enc#"
><foo><title>boogie</title></foo></rdf:RDF>'''

root = ET.fromstring(html)
ns = { 'default': 'http://purl.org/rss/1.0/', 'rdf': 'http://www.w3.org/1999/02/22-rdf-syntax-ns#'}

titles = root.findall("default:.//title", ns)
[print(title.text) for title in titles]
</code>```

答:
```<code>import urllib.request
from html.parser import HTMLParser
import xml.etree.ElementTree as ET

html = '''<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
 xmlns="http://purl.org/rss/1.0/"
 xmlns:enc="http://purl.oclc.org/net/rss_2.0/enc#"
 ><foo><title>boogie</title></foo></rdf:RDF>'''

root = ET.fromstring(html)
ns = '{http://purl.org/rss/1.0/}'

titles = root.findall(".//%stitle" % ns)
print titles[0].text
</code>```

This is working version

Title: Python namespaced xml-parsing error

Body:
What's wrong with the following code? I am expecting boogie as output.

import urllib.request
from html.parser import HTMLParser
import xml.etree.ElementTree as ET

html = '''<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
 xmlns="http://purl.org/rss/1.0/"
 xmlns:enc="http://purl.oclc.org/net/rss_2.0/enc#"
><foo><title>boogie</title></foo></rdf:RDF>'''

root = ET.fromstring(html)
ns = { 'default': 'http://purl.org/rss/1.0/', 'rdf': 'http://www.w3.org/1999/02/22-rdf-syntax-ns#'}

titles = root.findall("default:.//title", ns)
[print(title.text) for title in titles]

Body:
import urllib.request
from html.parser import HTMLParser
import xml.etree.ElementTree as ET

html = '''<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
 xmlns="http://purl.org/rss/1.0/"
 xmlns:enc="http://purl.oclc.org/net/rss_2.0/enc#"
 ><foo><title>boogie</title></foo></rdf:RDF>'''

root = ET.fromstring(html)
ns = '{http://purl.org/rss/1.0/}'

titles = root.findall(".//%stitle" % ns)
print titles[0].text

This is working version


问:
angular 4 http.post not sending or working
I am quite new to the latest version of Angular. http.post does not seem to work in anywhere in my application. I have tried things like:

```<code>this.http
    .post(this.bikesUrl, data, { headers: this.headers })
    .toPromise()
    .then(res => res.json().data)
    .catch(this.handleError);
</code>```

...or...

```<code>this.http.post(this.config.apiEndpoint+'/authenticate', JSON.stringify({ username: username, password: password }))
        .map((response: Response) => {
            // login successful if there's a jwt token in the response
            let token = response.json() && response.json().token;
            if (token) {
                // set token property
                this.token = token;

                // store username and jwt token in local storage to keep user logged in between page refreshes
                localStorage.setItem('currentUser', JSON.stringify({ username: username, token: token }));

                // return true to indicate successful login
                return true;
            } else {
                // return false to indicate failed login
                return false;
            }
        }).subscribe(result => {
      if (result === true) {
        // login successful
        this.router.navigate(['/']);
      } else {
        // login failed
        this.error = 'Username or password is incorrect';
        this.loading = false;
      }
    })
</code>```

...or...

```<code> var json = {var1: 'test'};
var params = 'json='+json;
let headers = new Headers();
headers.append('Content-Type', 'application/json');
http.post("http://example.com/infoarray.php", params, headers ).subscribe (re => {
  console.log(re)
})
</code>```

When I run this in the browser it is almost like the script is not there. I see no requests in the inspector. I am using Angular CLI

答:
Other mistake we generally do is we forget to import Headers from @angular/http. It will not give any error but requests will not work. Please try importing Headers as
import {Headers, Http} from '@angular/http';

Body:
I am quite new to the latest version of Angular. http.post does not seem to work in anywhere in my application. I have tried things like:

this.http
    .post(this.bikesUrl, data, { headers: this.headers })
    .toPromise()
    .then(res => res.json().data)
    .catch(this.handleError);

...or...

this.http.post(this.config.apiEndpoint+'/authenticate', JSON.stringify({ username: username, password: password }))
        .map((response: Response) => {
            // login successful if there's a jwt token in the response
            let token = response.json() && response.json().token;
            if (token) {
                // set token property
                this.token = token;

                // store username and jwt token in local storage to keep user logged in between page refreshes
                localStorage.setItem('currentUser', JSON.stringify({ username: username, token: token }));

                // return true to indicate successful login
                return true;
            } else {
                // return false to indicate failed login
                return false;
            }
        }).subscribe(result => {
      if (result === true) {
        // login successful
        this.router.navigate(['/']);
      } else {
        // login failed
        this.error = 'Username or password is incorrect';
        this.loading = false;
      }
    })

...or...

 var json = {var1: 'test'};
var params = 'json='+json;
let headers = new Headers();
headers.append('Content-Type', 'application/json');
http.post("http://example.com/infoarray.php", params, headers ).subscribe (re => {
  console.log(re)
})

When I run this in the browser it is almost like the script is not there. I see no requests in the inspector. I am using Angular CLI


问:
Why is the ?? operator not working in Moq setup method
Could someone explain to me, why this doesn't work?

```<code>builder.Setup(b => b.BuildCommand(query ?? It.IsAny<string>())).Returns(command);
</code>```

If query is null, BuildCommand will be passed null, and not It.IsAny<string>()

Instead, I have to do this:

```<code>if(query == null)
    builder.Setup(b => b.BuildCommand(It.IsAny<string>())).Returns(command);
else
    builder.Setup(b => b.BuildCommand(query)).Returns(command);
</code>```

Is it related to the delegate?

EDIT - Complete example

```<code>public static void ReturnFromBuildCommand(this Mock<IQueryCommandBuilder> builder, IQueryCommand command, string query = null)
{
    if(query == null)
        builder.Setup(b => b.BuildCommand(It.IsAny<string>())).Returns(command);
    else
        builder.Setup(b => b.BuildCommand(query)).Returns(command);
}
</code>```

Then I can call it like

```<code>var command = new Mock<IQueryCommand>();
var builder = new Mock<IQueryCommandBuilder>();
builder.ReturnFromBuildCommand(command.Object);
</code>```

Or

```<code>string query = "SELECT Name FROM Persons;";
builder.ReturnFromBuildCommand(command.Object, query);
</code>```

Depending on whether I care about the parameter or not.

答:
The Setup method of the mock takes in an expression, which the Moq framework then deconstructs to determine the method being called and the arguments to it.  It then sets up an interceptor to match the arguments.

You can see this in the Mock source:

```<code>    internal static MethodCallReturn<T, TResult> Setup<T, TResult>(
        Mock<T> mock,
        Expression<Func<T, TResult>> expression,
        Condition condition)
        where T : class
    {
        return PexProtector.Invoke(() =>
        {
            if (expression.IsProperty())
            {
                return SetupGet(mock, expression, condition);
            }

            var methodCall = expression.GetCallInfo(mock);
            var method = methodCall.Method;
            var args = methodCall.Arguments.ToArray();

            ThrowIfNotMember(expression, method);
            ThrowIfCantOverride(expression, method);
            var call = new MethodCallReturn<T, TResult>(mock, condition, expression, method, args);

            var targetInterceptor = GetInterceptor(methodCall.Object, mock);

            targetInterceptor.AddCall(call, SetupKind.Other);

            return call;
        });
    }
</code>```

Here args is of type Expression[].

(reference: https://github.com/moq/moq4/blob/master/Source/Mock.cs#L463)

This args array is passed into the constructor for the Moq type MethodCallReturn as the parameter arguments.  That constructor (via the base class MethodCall) generates an argument matcher using MatcherFactory.Create. (reference: https://github.com/moq/moq4/blob/master/Source/MethodCall.cs#L148)

This is where things start to get interesting!
In the MatcherFactory.Create method, it tries to determine the type of the argument's Expression by looking that the Expression.NodeType and/or checking it against known types, such as MatchExpression (which is what something like Is.Any<string>() would be).
(reference: https://github.com/moq/moq4/blob/master/Source/MatcherFactory.cs#L54)

So let's take a step back. In your specific case, the code query ?? Is.Any<string>() is compiled down to an expression itself -- something like this ugly mess (as generated by the dotPeek decompiler):

```<code>(Expression) Expression.Coalesce((Expression) Expression.Field((Expression) Expression.Constant((object) cDisplayClass00, typeof (Extension.\u003C\u003Ec__DisplayClass0_0)),
 FieldInfo.GetFieldFromHandle(__fieldref (Extension.\u003C\u003Ec__DisplayClass0_0.query))),
(Expression) Expression.Call((Expression) null, (MethodInfo) MethodBase.GetMethodFromHandle(__methodref (It.IsAny)), new Expression[0]))
</code>```

And that's what the first argument looks like. You can rewrite your code to better express what Moq sees, like this:

```<code>    public static void ReturnFromBuildCommand(this Mock<IQueryCommandBuilder> builder, IQueryCommand command, string query = null)
    {
        Expression<Func<IQueryCommandBuilder, IQueryCommand>> expressOfFunc = commandBuilder => (commandBuilder.BuildCommand(query ?? It.IsAny<string>()));

        var methodCall = expressOfFunc.Body as MethodCallExpression;
        var args = methodCall.Arguments.ToArray();
        var nodeType = args[0].NodeType;

        builder.Setup(expressOfFunc)
            .Returns(command);

    }
</code>```

If you place a breakpoint, you can see that the value of nodeType is Coalesce.  Now, go back and change it to just use query, and nodeType becomes MemberAccess. Use It.IsAny<string>(), and nodeType is Call.

This explains the differences between the three approaches and why it's not acting like you expected.  As for why it triggers on null is not clear to me, to be honest, but whatever matcher comes out of MatcherFactory.CreateMatcher seems to think null is a valid value for your mock configuration.

Body:
Could someone explain to me, why this doesn't work?

builder.Setup(b => b.BuildCommand(query ?? It.IsAny<string>())).Returns(command);

If query is null, BuildCommand will be passed null, and not It.IsAny<string>()

Instead, I have to do this:

if(query == null)
    builder.Setup(b => b.BuildCommand(It.IsAny<string>())).Returns(command);
else
    builder.Setup(b => b.BuildCommand(query)).Returns(command);

Is it related to the delegate?

EDIT - Complete example

public static void ReturnFromBuildCommand(this Mock<IQueryCommandBuilder> builder, IQueryCommand command, string query = null)
{
    if(query == null)
        builder.Setup(b => b.BuildCommand(It.IsAny<string>())).Returns(command);
    else
        builder.Setup(b => b.BuildCommand(query)).Returns(command);
}

Then I can call it like

var command = new Mock<IQueryCommand>();
var builder = new Mock<IQueryCommandBuilder>();
builder.ReturnFromBuildCommand(command.Object);

Or

string query = "SELECT Name FROM Persons;";
builder.ReturnFromBuildCommand(command.Object, query);

Depending on whether I care about the parameter or not.

Body:
The Setup method of the mock takes in an expression, which the Moq framework then deconstructs to determine the method being called and the arguments to it.  It then sets up an interceptor to match the arguments.

You can see this in the Mock source:

    internal static MethodCallReturn<T, TResult> Setup<T, TResult>(
        Mock<T> mock,
        Expression<Func<T, TResult>> expression,
        Condition condition)
        where T : class
    {
        return PexProtector.Invoke(() =>
        {
            if (expression.IsProperty())
            {
                return SetupGet(mock, expression, condition);
            }

            var methodCall = expression.GetCallInfo(mock);
            var method = methodCall.Method;
            var args = methodCall.Arguments.ToArray();

            ThrowIfNotMember(expression, method);
            ThrowIfCantOverride(expression, method);
            var call = new MethodCallReturn<T, TResult>(mock, condition, expression, method, args);

            var targetInterceptor = GetInterceptor(methodCall.Object, mock);

            targetInterceptor.AddCall(call, SetupKind.Other);

            return call;
        });
    }

Here args is of type Expression[].

(reference: https://github.com/moq/moq4/blob/master/Source/Mock.cs#L463)

This args array is passed into the constructor for the Moq type MethodCallReturn as the parameter arguments.  That constructor (via the base class MethodCall) generates an argument matcher using MatcherFactory.Create. (reference: https://github.com/moq/moq4/blob/master/Source/MethodCall.cs#L148)

This is where things start to get interesting!
In the MatcherFactory.Create method, it tries to determine the type of the argument's Expression by looking that the Expression.NodeType and/or checking it against known types, such as MatchExpression (which is what something like Is.Any<string>() would be).
(reference: https://github.com/moq/moq4/blob/master/Source/MatcherFactory.cs#L54)

So let's take a step back. In your specific case, the code query ?? Is.Any<string>() is compiled down to an expression itself -- something like this ugly mess (as generated by the dotPeek decompiler):

(Expression) Expression.Coalesce((Expression) Expression.Field((Expression) Expression.Constant((object) cDisplayClass00, typeof (Extension.\u003C\u003Ec__DisplayClass0_0)),
 FieldInfo.GetFieldFromHandle(__fieldref (Extension.\u003C\u003Ec__DisplayClass0_0.query))),
(Expression) Expression.Call((Expression) null, (MethodInfo) MethodBase.GetMethodFromHandle(__methodref (It.IsAny)), new Expression[0]))

And that's what the first argument looks like. You can rewrite your code to better express what Moq sees, like this:

    public static void ReturnFromBuildCommand(this Mock<IQueryCommandBuilder> builder, IQueryCommand command, string query = null)
    {
        Expression<Func<IQueryCommandBuilder, IQueryCommand>> expressOfFunc = commandBuilder => (commandBuilder.BuildCommand(query ?? It.IsAny<string>()));

        var methodCall = expressOfFunc.Body as MethodCallExpression;
        var args = methodCall.Arguments.ToArray();
        var nodeType = args[0].NodeType;

        builder.Setup(expressOfFunc)
            .Returns(command);

    }

If you place a breakpoint, you can see that the value of nodeType is Coalesce.  Now, go back and change it to just use query, and nodeType becomes MemberAccess. Use It.IsAny<string>(), and nodeType is Call.

This explains the differences between the three approaches and why it's not acting like you expected.  As for why it triggers on null is not clear to me, to be honest, but whatever matcher comes out of MatcherFactory.CreateMatcher seems to think null is a valid value for your mock configuration.


问:
How many CPU cycles are needed for each assembly instruction?
I heard there is Intel book online which describes the CPU cycles needed for a specific assembly instruction, but I can not find it out (after trying hard). Could anyone show me how to find CPU cycle please?

Here is an example, in the below code, mov/lock is 1 CPU cycle, and xchg is 3 CPU cycles.

```<code>// This part is Platform dependent!
#ifdef WIN32
inline int CPP_SpinLock::TestAndSet(int* pTargetAddress,
                                              int nValue)
{
    __asm
    {
        mov edx, dword ptr [pTargetAddress]
        mov eax, nValue
        lock xchg eax, dword ptr [edx]
    }
    // mov = 1 CPU cycle
    // lock = 1 CPU cycle
    // xchg = 3 CPU cycles
}

#endif // WIN32
</code>```

BTW: here is the URL for the code I posted: http://www.codeproject.com/KB/threads/spinlocks.aspx

答:
Modern CPUs are complex beasts, using pipelining, superscalar execution, and out-of-order execution among other techniques which make performance analysis difficult... but not impossible!

While you can no longer simply add together the latencies of a stream of instructions to get the total runtime, you can still get a (often) highly accurate analysis of the behavior of some piece of code (especially a loop) as described below and in other linked resources.

Instruction Timings

First, you need the actual timings. These vary by CPU architecture, but the best resource currently for x86 timings is Agner Fog's instruction tables. Covering no less than thirty different microarchitecures, these tables list the instruction latency, which is the minimum/typical time that an instruction takes from inputs ready to output available. In Agner's words:

Latency:  This is the delay that the instruction generates in a
  dependency chain. The numbers are minimum values. Cache misses,
  misalignment, and exceptions may increase the clock counts
  considerably. Where hyperthreading is enabled, the use of the same
  execution units in the other thread leads to inferior performance.
  Denormal numbers, NAN's and infinity do not increase the latency. The
  time unit used is core clock cycles, not the reference clock cycles
  given by the time stamp counter.

So, for example, the add instruction has a latency of one cycle, so a series of dependent add instructions, as shown, will have a latency of 1 cycle per add:

```<code>add eax, eax
add eax, eax
add eax, eax
add eax, eax  # total latency of 4 cycles for these 4 adds
</code>```

Note that this doesn't mean that add instructions will only take 1 cycle each. For example, if the add instructions were not dependent, it is possible that on modern chips all 4 add instructions can execute independently in the same cycle:

```<code>add eax, eax
add ebx, ebx
add ecx, ecx
add edx, edx # these 4 instructions might all execute, in parallel in a single cycle
</code>```

Agner provides a metric which captures some of this potential parallelism, called reciprocal throughput:

Reciprocal throughput:    The average number of core clock cycles per instruction for a series of independent instructions of the same kind
  in the same thread.

For add this is listed as 0.25 meaning that up to 4 add instructions can execute every cycle (giving a reciprocal throughput of 1 / 4 = 0.25).

The reciprocal throughput number also gives a hint at the pipelining capability of an instruction. For example, on most recent x86 chips, the common forms of the imul instruction have a latency of 3 cycles, and internally only one execution unit can handle them (unlike add which usually has four add-capable units). Yet the observed throughput for a long series of independent imul instructions is 1/cycle, not 1 every 3 cycles as you might expect given the latency of 3. The reason is that the imul unit is pipelined: it can start a new imul every cycle, even while the previous multiplication hasn't completed.

This means a series of independent imul instructions can run at up to 1 per cycle, but a series of dependent imul instructions will run at only 1 every 3 cycles (since the next imul can't start until the result from the prior one is ready).

So with this information, you can start to see how to analyze instruction timings on modern CPUs.

Detailed Analysis

Still, the above is only scratching the surface. You now have multiple ways of looking at a series of instructions (latency or throughput) and it may not be clear which to use.

Furthermore, there are other limits not captured by the above numbers, such as the fact that certain instructions compete for the same resources within the CPU, and restrictions in other parts of the CPU pipeline (such as instruction decoding) which may result in a lower overall throughput than you'd calculate just by looking at latency and throughput. Beyond that, you have factors "beyond the ALUs" such as memory access and branch prediction: entire topics unto themselves - you can mostly model these well, but it takes work. For example here's a recent post where the answer covers in some detail most of the relevant factors.

Covering all the details would increase the size of this already long answer by a factor of 10 or more, so I'll just point you to the best resources. Agner Fog has an Optimizing Asembly guide that covers in detail the precise analysis of a loop with a dozen or so instructions. See "12.7 An example of analysis for bottlenecks in vector loops" which starts on page 95 in the current version of the PDF.

The basic idea is that you create a table, with one row per instruction and mark the execution resources each uses. This lets you see any throughput bottlenecks. In addition, you need to examine the loop for carried dependencies, to see if any of those limit the throughput (see "12.16 Analyzing dependencies" for a complex case).

If you don't want to do it by hand, Intel has released the Intel Architecture Code Analyzer, which is a tool that automates this analysis. It currently hasn't been updated beyond Skylake, but the results are still largely reasonable for Kaby Lake since the microarchitecture hasn't changed much and therefore the timings remain comparable. This answer goes into a lot of detail and provides example output, and the user's guide isn't half bad (although it is out of date with respect to the newest versions).

Other sources

Agner usually provides timings for new architectures shortly after they are released, but you can also check out instlatx64 for similarly organized timings in the InstLatX86 and InstLatX64 results. The results cover a lot of interesting old chips, and new chips usually show up fairly quickly. The results are mostly consistent with Agner's, with a few exceptions here and there. You can also find memory latency and other values on this page.

You can even get the timing results directly from Intel in their IA32 and Intel 64 optimization manual in Appendix C: INSTRUCTION LATENCY AND THROUGHPUT. Personally I prefer Agner's version because they are more complete, often arrive before the Intel manual is updated, and are easier to use as they provide a spreadsheet and PDF version.

Finally, the x86 tag wiki has a wealth of resources on x86 optimization, including links to other examples of how to do a cycle accurate analysis of code sequences.

If you want a deeper look into the type of "dataflow analysis" described above, I would recommend A Whirlwind Introduction to Data Flow Graphs.

Body:
I heard there is Intel book online which describes the CPU cycles needed for a specific assembly instruction, but I can not find it out (after trying hard). Could anyone show me how to find CPU cycle please?

Here is an example, in the below code, mov/lock is 1 CPU cycle, and xchg is 3 CPU cycles.

// This part is Platform dependent!
#ifdef WIN32
inline int CPP_SpinLock::TestAndSet(int* pTargetAddress,
                                              int nValue)
{
    __asm
    {
        mov edx, dword ptr [pTargetAddress]
        mov eax, nValue
        lock xchg eax, dword ptr [edx]
    }
    // mov = 1 CPU cycle
    // lock = 1 CPU cycle
    // xchg = 3 CPU cycles
}

#endif // WIN32

BTW: here is the URL for the code I posted: http://www.codeproject.com/KB/threads/spinlocks.aspx

LastEditorDisplayName: Assaf

Body:
Modern CPUs are complex beasts, using pipelining, superscalar execution, and out-of-order execution among other techniques which make performance analysis difficult... but not impossible!

While you can no longer simply add together the latencies of a stream of instructions to get the total runtime, you can still get a (often) highly accurate analysis of the behavior of some piece of code (especially a loop) as described below and in other linked resources.

Instruction Timings

First, you need the actual timings. These vary by CPU architecture, but the best resource currently for x86 timings is Agner Fog's instruction tables. Covering no less than thirty different microarchitecures, these tables list the instruction latency, which is the minimum/typical time that an instruction takes from inputs ready to output available. In Agner's words:

Latency:  This is the delay that the instruction generates in a
  dependency chain. The numbers are minimum values. Cache misses,
  misalignment, and exceptions may increase the clock counts
  considerably. Where hyperthreading is enabled, the use of the same
  execution units in the other thread leads to inferior performance.
  Denormal numbers, NAN's and infinity do not increase the latency. The
  time unit used is core clock cycles, not the reference clock cycles
  given by the time stamp counter.

So, for example, the add instruction has a latency of one cycle, so a series of dependent add instructions, as shown, will have a latency of 1 cycle per add:

add eax, eax
add eax, eax
add eax, eax
add eax, eax  # total latency of 4 cycles for these 4 adds

Note that this doesn't mean that add instructions will only take 1 cycle each. For example, if the add instructions were not dependent, it is possible that on modern chips all 4 add instructions can execute independently in the same cycle:

add eax, eax
add ebx, ebx
add ecx, ecx
add edx, edx # these 4 instructions might all execute, in parallel in a single cycle

Agner provides a metric which captures some of this potential parallelism, called reciprocal throughput:

Reciprocal throughput:    The average number of core clock cycles per instruction for a series of independent instructions of the same kind
  in the same thread.

For add this is listed as 0.25 meaning that up to 4 add instructions can execute every cycle (giving a reciprocal throughput of 1 / 4 = 0.25).

The reciprocal throughput number also gives a hint at the pipelining capability of an instruction. For example, on most recent x86 chips, the common forms of the imul instruction have a latency of 3 cycles, and internally only one execution unit can handle them (unlike add which usually has four add-capable units). Yet the observed throughput for a long series of independent imul instructions is 1/cycle, not 1 every 3 cycles as you might expect given the latency of 3. The reason is that the imul unit is pipelined: it can start a new imul every cycle, even while the previous multiplication hasn't completed.

This means a series of independent imul instructions can run at up to 1 per cycle, but a series of dependent imul instructions will run at only 1 every 3 cycles (since the next imul can't start until the result from the prior one is ready).

So with this information, you can start to see how to analyze instruction timings on modern CPUs.

Detailed Analysis

Still, the above is only scratching the surface. You now have multiple ways of looking at a series of instructions (latency or throughput) and it may not be clear which to use.

Furthermore, there are other limits not captured by the above numbers, such as the fact that certain instructions compete for the same resources within the CPU, and restrictions in other parts of the CPU pipeline (such as instruction decoding) which may result in a lower overall throughput than you'd calculate just by looking at latency and throughput. Beyond that, you have factors "beyond the ALUs" such as memory access and branch prediction: entire topics unto themselves - you can mostly model these well, but it takes work. For example here's a recent post where the answer covers in some detail most of the relevant factors.

Covering all the details would increase the size of this already long answer by a factor of 10 or more, so I'll just point you to the best resources. Agner Fog has an Optimizing Asembly guide that covers in detail the precise analysis of a loop with a dozen or so instructions. See "12.7 An example of analysis for bottlenecks in vector loops" which starts on page 95 in the current version of the PDF.

The basic idea is that you create a table, with one row per instruction and mark the execution resources each uses. This lets you see any throughput bottlenecks. In addition, you need to examine the loop for carried dependencies, to see if any of those limit the throughput (see "12.16 Analyzing dependencies" for a complex case).

If you don't want to do it by hand, Intel has released the Intel Architecture Code Analyzer, which is a tool that automates this analysis. It currently hasn't been updated beyond Skylake, but the results are still largely reasonable for Kaby Lake since the microarchitecture hasn't changed much and therefore the timings remain comparable. This answer goes into a lot of detail and provides example output, and the user's guide isn't half bad (although it is out of date with respect to the newest versions).

Other sources

Agner usually provides timings for new architectures shortly after they are released, but you can also check out instlatx64 for similarly organized timings in the InstLatX86 and InstLatX64 results. The results cover a lot of interesting old chips, and new chips usually show up fairly quickly. The results are mostly consistent with Agner's, with a few exceptions here and there. You can also find memory latency and other values on this page.

You can even get the timing results directly from Intel in their IA32 and Intel 64 optimization manual in Appendix C: INSTRUCTION LATENCY AND THROUGHPUT. Personally I prefer Agner's version because they are more complete, often arrive before the Intel manual is updated, and are easier to use as they provide a spreadsheet and PDF version.

Finally, the x86 tag wiki has a wealth of resources on x86 optimization, including links to other examples of how to do a cycle accurate analysis of code sequences.

If you want a deeper look into the type of "dataflow analysis" described above, I would recommend A Whirlwind Introduction to Data Flow Graphs.


问:
Exception while running number of queries concurrently on DB2
We are testing an application specific Design where we need to show progressive counts after firing many queries simultaneously.

When we are firing a single query, we are successfully able to get Results Asynchronously.

But, when we are firing 3-4 queries simultaneously, after a significant amount of time & after getting some records for each query
we are getting an exception which states

“com.ibm.db2.jcc.c.SqlException: DB2 SQL error: SQLCODE: -1218, SQLSTATE: 57011, SQLERRMC: 4099”

Because of this, all the queries fired do not get executed completely.

There is no problem if these queries are fired one by one. (query2 starts executing after query1 completes & so on)

After looking for this SQLCODE in Control Center we found out the details which are,

SQL1218N  There are no pages currently available in bufferpool

```<code>  "<buffpool-num>".
</code>```

Explanation:

All of the pages in the bufferpool are currently being used. A request
to use another page failed.

The statement may be successful if executed again. If this error occurs
frequently, some or all of the following actions may prevent further
failures:

increase the bufferpool size

decrease the maximum number of database agents and/or connections

decrease the maximum degree of parallelism

decrease the prefetch size for table spaces that are in this

bufferpool

move some table spaces into other bufferpools.

sqlcode: -1218

sqlstate: 57011

On our DB instance, we already had a buffer pool of 32K page size & even after creating another buffer pool
of 32K, the problem persists.

Can anyone kindly help us in solving the problem.

Thanks & Regards,

Ravindra Jain

答:
The most likely cause is your transactions are not issueing "commits" so there is buildup of uncommited data in the buffer pools.

Also 32K seems very small for current hardware ( Since DB2 can handle CLOBs and BLOBs of several megabytes) 32MB or more would be more appropriate for a bufferpool size.

OwnerDisplayName: Ravindra Jain

ContentLicense: CC BY-SA 2.5

Body:
We are testing an application specific Design where we need to show progressive counts after firing many queries simultaneously.

When we are firing a single query, we are successfully able to get Results Asynchronously.

But, when we are firing 3-4 queries simultaneously, after a significant amount of time & after getting some records for each query
we are getting an exception which states

“com.ibm.db2.jcc.c.SqlException: DB2 SQL error: SQLCODE: -1218, SQLSTATE: 57011, SQLERRMC: 4099”

Because of this, all the queries fired do not get executed completely.

There is no problem if these queries are fired one by one. (query2 starts executing after query1 completes & so on)

After looking for this SQLCODE in Control Center we found out the details which are,

SQL1218N  There are no pages currently available in bufferpool

  "<buffpool-num>".

Explanation:

All of the pages in the bufferpool are currently being used. A request
to use another page failed.

The statement may be successful if executed again. If this error occurs
frequently, some or all of the following actions may prevent further
failures:

increase the bufferpool size

decrease the maximum number of database agents and/or connections

decrease the maximum degree of parallelism

decrease the prefetch size for table spaces that are in this

bufferpool

move some table spaces into other bufferpools.

sqlcode: -1218

sqlstate: 57011

On our DB instance, we already had a buffer pool of 32K page size & even after creating another buffer pool
of 32K, the problem persists.

Can anyone kindly help us in solving the problem.

Thanks & Regards,

Ravindra Jain

OwnerDisplayName: James Anderson


问:
Trying to send a post request with PHP from swift
I'm trying to send a user's input (done through a UISearchBar) to my PHP file to search through a database of store names. However, it seems like my $_POST variable $searchWord is empty.

My swift code:

```<code>func searchBarSearchButtonClicked(_ searchBar: UISearchBar)
{
if(searchBar.text!.isEmpty)
{
    return
}
searchBar.resignFirstResponder()
doSearch(searchWord: searchBar.text!, searchbar: searchBar )

}
func doSearch(searchWord: String, searchbar: UISearchBar){

mysearchBar = searchbar

mysearchBar.resignFirstResponder()

let myURL = NSURL(string: "http://localhost:8080/searchStore.php")

var request = URLRequest(url:myURL! as URL)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")

print("name=\(searchWord)")

let postString = "name=\(searchWord)"
request.httpBody = postString.data(using: String.Encoding.utf8)
request.addValue("application/json", forHTTPHeaderField: "Accept")

let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in

    DispatchQueue.main.async() {

        if error != nil{
            self.displayAlertMessage(userMessage: (error?.localizedDescription)!)
            return
        }
        do{
            var _: Error?
            //STOPPED HERE AS OF NOW
            let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary

            self.results.removeAll(keepingCapacity: false)
            self.tableView.reloadData()

            if let parseJSON = json{
                print("json")
                if let stores = parseJSON["stores"] as? [AnyObject]{
                    print("stores")

                    for storeOjb in stores{
                        let name = (storeOjb["name"] as! String)
                        self.results.append(name)
                    }

                    self.tableView.reloadData()

                }else if(parseJSON["message"] != nil){
                    print("message")

                    let errorMessage = parseJSON["message"] as? String
                    if(errorMessage != nil){
                        self.displayAlertMessage(userMessage: errorMessage!)

                    }
                }
            }
        } catch {
            print(error)
        }
    }

}

task.resume()
}

func displayAlertMessage(userMessage: String)
{
    let myAlert = UIAlertController(title: "Alert", message: userMessage, preferredStyle: UIAlertControllerStyle.alert);
let okAction =  UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil)
myAlert.addAction(okAction);
self.present(myAlert, animated: true, completion: nil)
}
</code>```

My php file

```<code><?php
require("Conn.php");
require("MySQLDao.php");

$returnValue = array();

if(empty($_POST["name"])){
    $returnValue["message"]= "Missing required field";
    echo json_encode($returnValue);
    return;
}

$searchWord =htmlentities($_POST["name"]);

$dao = new MySQLDao(Conn::$dbhost, Conn::$dbuser, Conn::$dbpass,
Conn::$dbname);
$dao->openConnection();

$storeNames = $dao->searchStore($name);
$dao->closeConnection();

$returnValue["stores"]=$storeNames;
echo json_encode($returnValue);
?>
</code>```

class MySQLDao
    {

```<code>var $dbhost = null;
var $dbuser = null;
var $dbpass = null;
var $conn = null;
var $dbname = null;
var $result = null;
function __construct($dbhost, $dbuser, $dbpassword, $dbname) {
    $this->dbhost = $dbhost;
    $this->dbuser = $dbuser;
    $this->dbpass = $dbpassword;
    $this->dbname = $dbname;
}

public function openConnection() {
    $this->conn = new mysqli($this->dbhost, $this->dbuser, $this->dbpass,
$this->dbname);
    if (mysqli_connect_errno())
        throw new Exception("Could not establish connection with database");
    $this->conn->set_charset("utf8");
}

public function closeConnection() {
    if ($this->conn != null)
        $this->conn->close();
}

public function searchStore($name){
    $returnValue =  array();
    $sql  = "SELECT * FROM stores s WHERE s.name LIKE ? ";
    $statement = $this->conn->prepare($sql);
    if(!$statement)
    throw new Exception($statement->error);
    $name = '%' .$name. "%";
    $result->bind_param("s", $name);
    $result->execute();
    $result = $statement->get_result();

while($myrow = $result->fetch_object())
{
    $returnValue[] = $myrow;
}

return $returnValue;
}

}
?>
</code>```

And Conn.php included MySQL connection details.

PostString in the swift code displays the users input correctly (I was able to figure it out by using breakpoints). However, whenever I search anything I would get an alert message saying that "Missing required field" indicating that my $_POST variable $searchWord is empty. Does anyone know how to solve this issue?

答:
The PHP $_POST array is only populated when the the request content type is of x-www-form-urlencoded.

If you are POSTing application/json from your Swift application, then you will need to parse the request body from the php input stream: php://input or you can use the STDIN constant.

However, it looks to me like you are actually intending to send x-www-form-urlencoded data, so change your content type appropriately.

Body:
I'm trying to send a user's input (done through a UISearchBar) to my PHP file to search through a database of store names. However, it seems like my $_POST variable $searchWord is empty.

My swift code:

func searchBarSearchButtonClicked(_ searchBar: UISearchBar)
{
if(searchBar.text!.isEmpty)
{
    return
}
searchBar.resignFirstResponder()
doSearch(searchWord: searchBar.text!, searchbar: searchBar )

}
func doSearch(searchWord: String, searchbar: UISearchBar){

mysearchBar = searchbar

mysearchBar.resignFirstResponder()

let myURL = NSURL(string: "http://localhost:8080/searchStore.php")

var request = URLRequest(url:myURL! as URL)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")

print("name=\(searchWord)")

let postString = "name=\(searchWord)"
request.httpBody = postString.data(using: String.Encoding.utf8)
request.addValue("application/json", forHTTPHeaderField: "Accept")

let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in

    DispatchQueue.main.async() {

        if error != nil{
            self.displayAlertMessage(userMessage: (error?.localizedDescription)!)
            return
        }
        do{
            var _: Error?
            //STOPPED HERE AS OF NOW
            let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary

            self.results.removeAll(keepingCapacity: false)
            self.tableView.reloadData()

            if let parseJSON = json{
                print("json")
                if let stores = parseJSON["stores"] as? [AnyObject]{
                    print("stores")

                    for storeOjb in stores{
                        let name = (storeOjb["name"] as! String)
                        self.results.append(name)
                    }

                    self.tableView.reloadData()

                }else if(parseJSON["message"] != nil){
                    print("message")

                    let errorMessage = parseJSON["message"] as? String
                    if(errorMessage != nil){
                        self.displayAlertMessage(userMessage: errorMessage!)

                    }
                }
            }
        } catch {
            print(error)
        }
    }

}

task.resume()
}

func displayAlertMessage(userMessage: String)
{
    let myAlert = UIAlertController(title: "Alert", message: userMessage, preferredStyle: UIAlertControllerStyle.alert);
let okAction =  UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil)
myAlert.addAction(okAction);
self.present(myAlert, animated: true, completion: nil)
}

My php file

<?php
require("Conn.php");
require("MySQLDao.php");

$returnValue = array();

if(empty($_POST["name"])){
    $returnValue["message"]= "Missing required field";
    echo json_encode($returnValue);
    return;
}

$searchWord =htmlentities($_POST["name"]);

$dao = new MySQLDao(Conn::$dbhost, Conn::$dbuser, Conn::$dbpass,
Conn::$dbname);
$dao->openConnection();

$storeNames = $dao->searchStore($name);
$dao->closeConnection();

$returnValue["stores"]=$storeNames;
echo json_encode($returnValue);
?>

class MySQLDao
    {

var $dbhost = null;
var $dbuser = null;
var $dbpass = null;
var $conn = null;
var $dbname = null;
var $result = null;
function __construct($dbhost, $dbuser, $dbpassword, $dbname) {
    $this->dbhost = $dbhost;
    $this->dbuser = $dbuser;
    $this->dbpass = $dbpassword;
    $this->dbname = $dbname;
}

public function openConnection() {
    $this->conn = new mysqli($this->dbhost, $this->dbuser, $this->dbpass,
$this->dbname);
    if (mysqli_connect_errno())
        throw new Exception("Could not establish connection with database");
    $this->conn->set_charset("utf8");
}

public function closeConnection() {
    if ($this->conn != null)
        $this->conn->close();
}

public function searchStore($name){
    $returnValue =  array();
    $sql  = "SELECT * FROM stores s WHERE s.name LIKE ? ";
    $statement = $this->conn->prepare($sql);
    if(!$statement)
    throw new Exception($statement->error);
    $name = '%' .$name. "%";
    $result->bind_param("s", $name);
    $result->execute();
    $result = $statement->get_result();

while($myrow = $result->fetch_object())
{
    $returnValue[] = $myrow;
}

return $returnValue;
}

}
?>

And Conn.php included MySQL connection details.

PostString in the swift code displays the users input correctly (I was able to figure it out by using breakpoints). However, whenever I search anything I would get an alert message saying that "Missing required field" indicating that my $_POST variable $searchWord is empty. Does anyone know how to solve this issue?


问:
Dynamically added view has no style function React Native
I'm using carousel in my app (taken from here https://github.com/nick/react-native-carousel)

I'm trying to add a view each time a user swipe to the right.

That is the code I'm using:

```<code>export default class AllRand extends Component
{

  constructor(props)
  {
    super(props);
    this.state =
    {
      myArr: ['Page numebr: ', 'Page numebr: ']
    };
  }

  _onPageSwitchAnimateEnd()
  {
    this.state.myArr.push('Page numebr: ')
    this.setState({
        myArr: this.state.myArr
    })
  }

  render()
  {
    let Arr = this.state.myArr.map((text, index) => {
      return <View key={ index } style={ styles.shit1 }><Text>asdasd { index }</Text></View>
    })

    return (
      <Carousel animate={false} hideIndicators={false} onPageChange={() => this._onPressOut()}>
        { Arr }
      </Carousel>
    );
  }
}
</code>```

I succeed adding a View but it is not with the style, text 'Page number: ' and index...

UPDATE:

changed my code but still doesn't work...

```<code>'use strict';

import React, { Component } from 'react';

import {
  AppRegistry,
  StyleSheet,
  Text,
  View
} from 'react-native';

import Carousel from 'react-native-carousel';
import FactsApiFetcher from './facts-api-handler/facts-api-fetcher'

export default class AllRand extends Component
{

  constructor(props)
  {
    const InitialnumberOfPages = 2;

    super(props);
    this.state =
    {
      numberOfPages: InitialnumberOfPages,
      Pages: this._setInitialPages(InitialnumberOfPages)
    };
  }

  _onPageSwitchAnimateEnd()
  {
    let updatedNumberOfPages = this.state.numberOfPages + 1;
    let newArr = this._addPage(updatedNumberOfPages);

    this.setState({
        numberOfPages: updatedNumberOfPages,
        Pages: newArr
    });
  }

  render()
  {
    return (
      <Carousel animate={false} hideIndicators={false} onPageChange={() => this._onPageSwitchAnimateEnd()}>
        { this.state.Pages }
      </Carousel>
    );
  }

  _setInitialPages(numberOfPages)
  {
    let tempArr = [];

    for(let i = 0; i < numberOfPages; i++)
    {
      tempArr.push(<View key={ i } style={ styles.shit1 }><FactsApiFetcher/></View>);
    }

    return tempArr;
  }

  _addPage(updatedNumberOfPages)
  {
    return this.state.Pages.concat([<View key={ updatedNumberOfPages - 1 } style={ styles.shit1 }><FactsApiFetcher/></View>]);
  }
}

const styles = StyleSheet.create({
  shit1: {
    alignSelf: 'stretch',
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#FFFF00'
  }
});

AppRegistry.registerComponent('AllRand', () => AllRand);
</code>```

答:
So eventually the problem was because there is a bug in the Carousel library I used ( https://github.com/nick/react-native-carousel). From some reason, the callback function that adds the pages is messing up the pages array (don't know why...).]

When I tried using another Carousel library the function worked.

My only advice I can give following this experience is that when you think you tried all the possibilities in order the fix your bug, try changing the libraries you are using (to another same functionality library).

Body:
I'm using carousel in my app (taken from here https://github.com/nick/react-native-carousel)

I'm trying to add a view each time a user swipe to the right.

That is the code I'm using:

export default class AllRand extends Component
{

  constructor(props)
  {
    super(props);
    this.state =
    {
      myArr: ['Page numebr: ', 'Page numebr: ']
    };
  }

  _onPageSwitchAnimateEnd()
  {
    this.state.myArr.push('Page numebr: ')
    this.setState({
        myArr: this.state.myArr
    })
  }

  render()
  {
    let Arr = this.state.myArr.map((text, index) => {
      return <View key={ index } style={ styles.shit1 }><Text>asdasd { index }</Text></View>
    })

    return (
      <Carousel animate={false} hideIndicators={false} onPageChange={() => this._onPressOut()}>
        { Arr }
      </Carousel>
    );
  }
}

I succeed adding a View but it is not with the style, text 'Page number: ' and index...

UPDATE:

changed my code but still doesn't work...

'use strict';

import React, { Component } from 'react';

import {
  AppRegistry,
  StyleSheet,
  Text,
  View
} from 'react-native';

import Carousel from 'react-native-carousel';
import FactsApiFetcher from './facts-api-handler/facts-api-fetcher'

export default class AllRand extends Component
{

  constructor(props)
  {
    const InitialnumberOfPages = 2;

    super(props);
    this.state =
    {
      numberOfPages: InitialnumberOfPages,
      Pages: this._setInitialPages(InitialnumberOfPages)
    };
  }

  _onPageSwitchAnimateEnd()
  {
    let updatedNumberOfPages = this.state.numberOfPages + 1;
    let newArr = this._addPage(updatedNumberOfPages);

    this.setState({
        numberOfPages: updatedNumberOfPages,
        Pages: newArr
    });
  }

  render()
  {
    return (
      <Carousel animate={false} hideIndicators={false} onPageChange={() => this._onPageSwitchAnimateEnd()}>
        { this.state.Pages }
      </Carousel>
    );
  }

  _setInitialPages(numberOfPages)
  {
    let tempArr = [];

    for(let i = 0; i < numberOfPages; i++)
    {
      tempArr.push(<View key={ i } style={ styles.shit1 }><FactsApiFetcher/></View>);
    }

    return tempArr;
  }

  _addPage(updatedNumberOfPages)
  {
    return this.state.Pages.concat([<View key={ updatedNumberOfPages - 1 } style={ styles.shit1 }><FactsApiFetcher/></View>]);
  }
}

const styles = StyleSheet.create({
  shit1: {
    alignSelf: 'stretch',
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#FFFF00'
  }
});

AppRegistry.registerComponent('AllRand', () => AllRand);


问:
Extend Angular Component method with injected services
I have to handle Angular component's destruction event in my external module providing decorating function. Unfortunately I am unable to override ngOnDestroy() method when it contains references to injected services... How can I go over it or achieve the same effect other way?

Plnkr: https://plnkr.co/edit/YtczREB91A3t6rJ1uKks (error in ngOnDestroy() shouldn't be thrown)

If anyone would be interested in this, here is the working version thanks to @estus'es proposition with Symbol(): https://plnkr.co/edit/nnxLswhPUGZR3ycBWojg

答:
ngOnDestroy method is overridden with listed decorator. The actual problem with it is that wrong context is applied to originalFunction in

```<code>originalFunction.apply(target, arguments);
</code>```

In case of method/property decorators target argument is class prototype for instance properties/methods:

```<code>export const ON_DESTROY_SYMBOL = Symbol();

export function Decorator() {
  return (target: any, propertyName: string) => {
    target[ON_DESTROY_SYMBOL] = target.ngOnDestroy;
    target.ngOnDestroy = function() {
      this[ON_DESTROY_SYMBOL]();
      console.log('Component destroy event successfully handled!');
    }
  }
}
</code>```

If ngOnDestroy method doesn't necessarily exist but the decorator should be applied any way, it can be class decorator instead, where target is class constructor:

```<code>export function Decorator() {
  return (target: any, propertyName: string) => {
    target.prototype[ON_DESTROY_SYMBOL] = target.prototype.ngOnDestroy || () => {};
    target.prototype.ngOnDestroy = function() {
      this[ON_DESTROY_SYMBOL]();
      console.log('Component destroy event successfully handled!');
    }
  }
}

...
Decorator()
Component(...)
class ...
</code>```

Body:
ngOnDestroy method is overridden with listed decorator. The actual problem with it is that wrong context is applied to originalFunction in

originalFunction.apply(target, arguments);

In case of method/property decorators target argument is class prototype for instance properties/methods:

export const ON_DESTROY_SYMBOL = Symbol();

export function Decorator() {
  return (target: any, propertyName: string) => {
    target[ON_DESTROY_SYMBOL] = target.ngOnDestroy;
    target.ngOnDestroy = function() {
      this[ON_DESTROY_SYMBOL]();
      console.log('Component destroy event successfully handled!');
    }
  }
}

If ngOnDestroy method doesn't necessarily exist but the decorator should be applied any way, it can be class decorator instead, where target is class constructor:

export function Decorator() {
  return (target: any, propertyName: string) => {
    target.prototype[ON_DESTROY_SYMBOL] = target.prototype.ngOnDestroy || () => {};
    target.prototype.ngOnDestroy = function() {
      this[ON_DESTROY_SYMBOL]();
      console.log('Component destroy event successfully handled!');
    }
  }
}

...
Decorator()
Component(...)
class ...


问:
What is the equivalent of Java's Stream#Peek method in Linq C#?
I have been used to using Java's Stream#Peek method so much as it's a useful method to debug intermediate stream operation. For those of you who are not familiar with the Stream#Peek method, below shows the definition of it:

Stream<T> peek(Consumer<? super T> action)

Returns a stream consisting of the elements of this stream,
  additionally performing the provided action on each element as
  elements are consumed from the resulting stream. This is an
  intermediate operation.

Consider this simple example below:

```<code>List<Integer> integerList = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
List<Integer> result = integerList.stream()
                                  .filter(i -> i % 2 == 0)
                                  .peek(System.out::println)
                                  .collect(Collectors.toList());
</code>```

With the Stream#Peek method, this should basically allow me to print all the even numbers to the console so that I can test to see if that's what I would expect.

I have tried to find an answer to the question at hand but can't seem to find a similar method in C#, does anyone know the equivalent of Java's Stream#Peek or some other method with similar behavior?

答:
You can use a Select with a Statement Lambda for this.  Consider:

```<code>var integerList = new List<int> {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
var result = integerList
    .Where(i => i % 2 == 0)

    // this select uses a statement lambda
    .Select(i =>
    {
        Console.WriteLine(i);
        return i;
    })

    .Whatever(...);
</code>```

Body:
I have been used to using Java's Stream#Peek method so much as it's a useful method to debug intermediate stream operation. For those of you who are not familiar with the Stream#Peek method, below shows the definition of it:

Stream<T> peek(Consumer<? super T> action)

Returns a stream consisting of the elements of this stream,
  additionally performing the provided action on each element as
  elements are consumed from the resulting stream. This is an
  intermediate operation.

Consider this simple example below:

List<Integer> integerList = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
List<Integer> result = integerList.stream()
                                  .filter(i -> i % 2 == 0)
                                  .peek(System.out::println)
                                  .collect(Collectors.toList());

With the Stream#Peek method, this should basically allow me to print all the even numbers to the console so that I can test to see if that's what I would expect.

I have tried to find an answer to the question at hand but can't seem to find a similar method in C#, does anyone know the equivalent of Java's Stream#Peek or some other method with similar behavior?

Body:
You can use a Select with a Statement Lambda for this.  Consider:

var integerList = new List<int> {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
var result = integerList
    .Where(i => i % 2 == 0)

    // this select uses a statement lambda
    .Select(i =>
    {
        Console.WriteLine(i);
        return i;
    })

    .Whatever(...);