问:
Child component state not updated even after data source update (Diagram Included)
I am trying to build a react grid component that has design similar to the one shown in image.

(1) Someone passes raw data to grid as props, (2) which gets converted to multiple GridData objects and stored within GRID. (3) Those objects are iterated over in render function to render grid items. (4) Now, someone performs an action outside of grid (may be in toolbar or something), that triggers property change for some/all GridData objects stored within Grid (in this case select all). (5) This results in all grid items getting updated property (in this case all items will be selected).

However, when I update the attribute of an object in Grid, the child (GridItem) does not check the checkbox. How can I fix that?

The code for the design looks something like this:

Grid.js

```<code>class Grid extends Component {
    constructor(props) {
        super(props);
        this.state = {
            gridData: props.data,
        };
    }

    componentWillReceiveProps(nextProps) {
        this.setState({
            gridData:
                typeof nextProps.gridData !== 'undefined' && nextProps.gridData
                    ? nextProps.gridData
                    : this.state.gridData,
        });
    }

    // PubSub System to receive notification
    subscriber(msg, data) {
        if(msg === 'SELECT_ALL_ITEMS'){
            this.state.gridData.forEach(gridItem => {
            gridItem.setChecked(true);
        }
    }

    renderGridItem(gridItem) {
        return (
            <GridItem
                key={gridItem.getItemId()}
                title={gridItem.getTitle()}
                isChecked={gridItem.isChecked()}
            />
        );
    }

    render() {
        return (
            <div>
            {this.state.gridData !== 'undefined' && this.state.gridData ? (
                this.state.gridData.map(gridItem => this.renderGridItem(gridItem))
            ) : (
                <div />
            )}
            </div>
        );
    }
}
</code>```

GridItem.js

```<code>class GridItem extends Component {
    constructor(props) {
        super(props);
        this.state = {
            isChecked: typeof props.isChecked !== 'undefined' && props.isChecked ? props.isChecked : false,
                title: typeof props.title !== 'undefined' && props.title ? props.title : '',
            },
        };
    }

    render() {
        const { classes } = this.props;
        return (
            <div>
                    <Checkbox
                        checked={this.state.isChecked}
                    />
                    {this.state.properties.title}
            </div>
        );
    }
}
</code>```

GridData.js

```<code>export default class GridData {
    constructor(item) {
        this._title = item.title;
        this._itemId = item.itemId;
    }

    getItemId() {
        return this._entryId;
    }

    isChecked() {
        return this._isChecked;
    }

    setChecked(isChecked) {
        this._isChecked = isChecked;
    }

    getTitle() {
        return this._title;
    }
}
</code>```

答:
I think you need to put your subscriber into componentDidMount

This method is a good place to set up any subscriptions. If you do that, don’t forget to unsubscribe in componentWillUnmount()

And you have to update state with setState in your subscriber.

Calling setState() in componentDidMount method will trigger an extra rendering

Body:
I am trying to build a react grid component that has design similar to the one shown in image.

(1) Someone passes raw data to grid as props, (2) which gets converted to multiple GridData objects and stored within GRID. (3) Those objects are iterated over in render function to render grid items. (4) Now, someone performs an action outside of grid (may be in toolbar or something), that triggers property change for some/all GridData objects stored within Grid (in this case select all). (5) This results in all grid items getting updated property (in this case all items will be selected).

However, when I update the attribute of an object in Grid, the child (GridItem) does not check the checkbox. How can I fix that?

The code for the design looks something like this:

Grid.js

class Grid extends Component {
    constructor(props) {
        super(props);
        this.state = {
            gridData: props.data,
        };
    }

    componentWillReceiveProps(nextProps) {
        this.setState({
            gridData:
                typeof nextProps.gridData !== 'undefined' && nextProps.gridData
                    ? nextProps.gridData
                    : this.state.gridData,
        });
    }

    // PubSub System to receive notification
    subscriber(msg, data) {
        if(msg === 'SELECT_ALL_ITEMS'){
            this.state.gridData.forEach(gridItem => {
            gridItem.setChecked(true);
        }
    }

    renderGridItem(gridItem) {
        return (
            <GridItem
                key={gridItem.getItemId()}
                title={gridItem.getTitle()}
                isChecked={gridItem.isChecked()}
            />
        );
    }

    render() {
        return (

            {this.state.gridData !== 'undefined' && this.state.gridData ? (
                this.state.gridData.map(gridItem => this.renderGridItem(gridItem))
            ) : (

            )}

        );
    }
}

GridItem.js

class GridItem extends Component {
    constructor(props) {
        super(props);
        this.state = {
            isChecked: typeof props.isChecked !== 'undefined' && props.isChecked ? props.isChecked : false,
                title: typeof props.title !== 'undefined' && props.title ? props.title : '',
            },
        };
    }

    render() {
        const { classes } = this.props;
        return (

                    <Checkbox
                        checked={this.state.isChecked}
                    />
                    {this.state.properties.title}

        );
    }
}

GridData.js

export default class GridData {
    constructor(item) {
        this._title = item.title;
        this._itemId = item.itemId;
    }

    getItemId() {
        return this._entryId;
    }

    isChecked() {
        return this._isChecked;
    }

    setChecked(isChecked) {
        this._isChecked = isChecked;
    }

    getTitle() {
        return this._title;
    }
}


来源: stackexchange

问:
Python 3 Unit tests with user input
I'm absolutely brand new to Python unit test. I need to use it for a project I have to submit. I sort of have an idea of where to begin, it looks like we basically put in test parameters to functions we have defined in our program and we enter the expected result. If the expected result is output, we get OK, otherwise we will get Failure, or an error.

So my problem is that I have multiple user inputs stored into variables that are within for loops or while loops. I don't know where to even begin with this to set test values in for them.

Here is all of my code:

```<code>studentTripExpenses = {}

def dictCreate(studentAmount):
    for i in range(0, studentAmount):
        studentName = input("What is the name of the student? ")
        expenseList = []
        print("Enter 'done' to move to the next student.")
        while True:
            expense = input("What is the cost of this expense? ")
            if expense.lower() == 'done':
                break
            elif (float(expense) >= 0) or (float(expense) < 0):
                expenseList.append(float(expense))
            elif not expense.isdigit():
                print("Please enter a number or enter 'done' to move on.")
        studentTripExpenses[studentName] = expenseList
    return studentTripExpenses

def studentCost(dct):
    for i in dct:
        #Variable for individual costs of student
        personalCost = 0
        #Determines the total cost for each student
        for x in dct[i]:
            personalCost = personalCost + x
        #Sets each students value to their total cost to two decimal places
        dct[i] = float("%.2f" % personalCost)
    return dct

def amountsDue(expenseLst, studentAvgPrice):
        #Runs through the dictionary of students and individual total trip costs
        for key in expenseLst:
            maxPerson = max(expenseLst, key=expenseLst.get)
            costDifference = 0
            #Determines who owes who how much money
            if max(expenseLst.values()) > expenseLst[key]:
                costDifference = studentAvgPrice-expenseLst[key]
                if (costDifference < 0):
                    costDifference = costDifference * -1
                print("%s owes %s $%.2f" % (key, maxPerson, costDifference))

def main():
    numOfStudents = int(input("How many students are going on the trip? "))
    studentCostDict = dictCreate(numOfStudents)
    studentTripExpenses = studentCost(studentCostDict)

    totalCost = 0

    #Gets the total cost for all students
    for key in (studentTripExpenses):
        totalCost = totalCost + studentTripExpenses[key]

    #Changes the total cost to 2 decimal places
    totalCost = float("%.2f" % totalCost)

    #Determines the average amount spent per student
    avgCost = float("%.2f" % (totalCost/len(studentTripExpenses)))

    amountsDue(studentTripExpenses, avgCost)

main()
</code>```

答:
You can use mocking, where you replace a function or class with a test-supplied version. You can do this with the unittest.mock() module.

In this case, you can patch the input() name in your module; instead of the built-in function, the mock object will be called:

```<code>from unittest import mock
from unittest import TestCase
import module_under_test

class DictCreateTests(TestCase):
    @mock.patch('module_under_test.input', create=True)
    def testdictCreateSimple(self, mocked_input):
        mocked_input.side_effect = ['Albert Einstein', '42.81', 'done']
        result = dictCreate(1)
        self.assertEqual(result, {'Albert Einstein': [42.81]})
</code>```

Because input doesn't exist in your module (it is a built-in function), I told the mock.patch() decorator to create the name; now this input will be used instead of the built-in function.

The side_effect attribute lets you state multiple results; each time the mock is called, it'll return the next value in that list. So the first time 'Albert Einstein' is returned, the next time '42.81', etc.

Together, this lets you simulate actual user inputs.

If you do your test right, you'll notice that there is a bug in your function; the float() call will throw a ValueError exception when anything other than done or a valid numeric value is entered. You need to rework your code to account for that. Try with mocked_input.side_effect = ['Albert Einstein', 'Not an expense', '42.81', 'done'] to trigger the bug.

ContentLicense: CC BY-SA 3.0

Title: Python 3 Unit tests with user input

Body:
I'm absolutely brand new to Python unit test. I need to use it for a project I have to submit. I sort of have an idea of where to begin, it looks like we basically put in test parameters to functions we have defined in our program and we enter the expected result. If the expected result is output, we get OK, otherwise we will get Failure, or an error.

So my problem is that I have multiple user inputs stored into variables that are within for loops or while loops. I don't know where to even begin with this to set test values in for them.

Here is all of my code:

studentTripExpenses = {}

def dictCreate(studentAmount):
    for i in range(0, studentAmount):
        studentName = input("What is the name of the student? ")
        expenseList = []
        print("Enter 'done' to move to the next student.")
        while True:
            expense = input("What is the cost of this expense? ")
            if expense.lower() == 'done':
                break
            elif (float(expense) >= 0) or (float(expense) < 0):
                expenseList.append(float(expense))
            elif not expense.isdigit():
                print("Please enter a number or enter 'done' to move on.")
        studentTripExpenses[studentName] = expenseList
    return studentTripExpenses

def studentCost(dct):
    for i in dct:
        #Variable for individual costs of student
        personalCost = 0
        #Determines the total cost for each student
        for x in dct[i]:
            personalCost = personalCost + x
        #Sets each students value to their total cost to two decimal places
        dct[i] = float("%.2f" % personalCost)
    return dct

def amountsDue(expenseLst, studentAvgPrice):
        #Runs through the dictionary of students and individual total trip costs
        for key in expenseLst:
            maxPerson = max(expenseLst, key=expenseLst.get)
            costDifference = 0
            #Determines who owes who how much money
            if max(expenseLst.values()) > expenseLst[key]:
                costDifference = studentAvgPrice-expenseLst[key]
                if (costDifference < 0):
                    costDifference = costDifference * -1
                print("%s owes %s $%.2f" % (key, maxPerson, costDifference))

def main():
    numOfStudents = int(input("How many students are going on the trip? "))
    studentCostDict = dictCreate(numOfStudents)
    studentTripExpenses = studentCost(studentCostDict)

    totalCost = 0

    #Gets the total cost for all students
    for key in (studentTripExpenses):
        totalCost = totalCost + studentTripExpenses[key]

    #Changes the total cost to 2 decimal places
    totalCost = float("%.2f" % totalCost)

    #Determines the average amount spent per student
    avgCost = float("%.2f" % (totalCost/len(studentTripExpenses)))

    amountsDue(studentTripExpenses, avgCost)

main()

Body:
You can use mocking, where you replace a function or class with a test-supplied version. You can do this with the unittest.mock() module.

In this case, you can patch the input() name in your module; instead of the built-in function, the mock object will be called:

from unittest import mock
from unittest import TestCase
import module_under_test

class DictCreateTests(TestCase):
    @mock.patch('module_under_test.input', create=True)
    def testdictCreateSimple(self, mocked_input):
        mocked_input.side_effect = ['Albert Einstein', '42.81', 'done']
        result = dictCreate(1)
        self.assertEqual(result, {'Albert Einstein': [42.81]})

Because input doesn't exist in your module (it is a built-in function), I told the mock.patch() decorator to create the name; now this input will be used instead of the built-in function.

The side_effect attribute lets you state multiple results; each time the mock is called, it'll return the next value in that list. So the first time 'Albert Einstein' is returned, the next time '42.81', etc.

Together, this lets you simulate actual user inputs.

If you do your test right, you'll notice that there is a bug in your function; the float() call will throw a ValueError exception when anything other than done or a valid numeric value is entered. You need to rework your code to account for that. Try with mocked_input.side_effect = ['Albert Einstein', 'Not an expense', '42.81', 'done'] to trigger the bug.


问:
Read two bytes into an integer?
I have a byte[] that I've read from a file, and I want to get an int from two bytes in it. Here's an example:

```<code>byte[] bytes = new byte[] {(byte)0x00, (byte)0x2F, (byte)0x01, (byte)0x10, (byte)0x6F};
int value = bytes.getInt(2,4); //This method doesn't exist
</code>```

This should make value equal to 0x0110, or 272 in decimal. But obviously, byte[].getInt() doesn't exist. How can I accomplish this task?

The above array is just an example. Actual values are unknown to me.

答:
Try:

```<code>public static int getInt(byte[] arr, int off) {
  return arr[off]<<8 &0xFF00 | arr[off+1]&0xFF;
} // end of getInt
</code>```

Your question didn't indicate what the two args (2,4) meant.  2 and 4 don't make sense in your example as indices in the array to find ox01 and 0x10,  I guessed you wanted to take two consecutive element, a common thing to do, so I used off and off+1 in my method.

You can't extend the byte[] class in java, so you can't have a method bytes.getInt, so I made a static method that uses the byte[] as the first arg.

The 'trick' to the method is that you bytes are 8 bit signed integers and values over 0x80 are negative and would be sign extended (ie 0xFFFFFF80 when used as an int).  That is why the '&0xFF' masking is needed.  the '<<8' shifts the more significant byte 8 bits left.
The '|' combines the two values -- just as '+' would.  The order of the operators is important because << has highest precedence, followed by & followed by | -- thus no parentheses are needed.

Title: Read two bytes into an integer?

Body:
I have a byte[] that I've read from a file, and I want to get an int from two bytes in it. Here's an example:

byte[] bytes = new byte[] {(byte)0x00, (byte)0x2F, (byte)0x01, (byte)0x10, (byte)0x6F};
int value = bytes.getInt(2,4); //This method doesn't exist

This should make value equal to 0x0110, or 272 in decimal. But obviously, byte[].getInt() doesn't exist. How can I accomplish this task?

The above array is just an example. Actual values are unknown to me.

Body:
Try:

public static int getInt(byte[] arr, int off) {
  return arr[off]<<8 &0xFF00 | arr[off+1]&0xFF;
} // end of getInt

Your question didn't indicate what the two args (2,4) meant.  2 and 4 don't make sense in your example as indices in the array to find ox01 and 0x10,  I guessed you wanted to take two consecutive element, a common thing to do, so I used off and off+1 in my method.

You can't extend the byte[] class in java, so you can't have a method bytes.getInt, so I made a static method that uses the byte[] as the first arg.

The 'trick' to the method is that you bytes are 8 bit signed integers and values over 0x80 are negative and would be sign extended (ie 0xFFFFFF80 when used as an int).  That is why the '&0xFF' masking is needed.  the '<<8' shifts the more significant byte 8 bits left.
The '|' combines the two values -- just as '+' would.  The order of the operators is important because << has highest precedence, followed by & followed by | -- thus no parentheses are needed.

ContentLicense: CC BY-SA 2.5


问:
Special characters breaking textbox submission
Currently dealing with a bug if a user submits a special character into a textbox like '/' or '&' the information submits and displays on their profile page but on page reload all input boxes are empty and the user cannot submit any more changes. This is after a page refresh, all the fields I just filled out are now blank, and trying to submit 'test' into the bio i get this console error:

Here's the form html:

```<code><form class="login-signup-form">
    <label for="display-name">Display Name</label>
    <input id="display-name" name="display-name" type="text" placeholder="Name">
    <label for="email">Email</label>
    <input id="email" name="email" type="email" placeholder="Email">
    <label for="twitter-link">Twitter link</label>
    <input id="twitter-link" name="twitter-link" type="url" placeholder="https://">
    <label for="instagram-link">Instagram link</label>
    <input id="instagram-link" name="instagram-link" type="url" placeholder="https://">
    <label for="youtube-link">YouTube link</label>
    <input id="youtube-link" name="youtube-link" type="url" placeholder="https://">
    <label for="web-link">Website</label>
    <input id="web-link" name="web-link" type="url" placeholder="https://">
    <label for="artist-bio">Bio</label>
    <textarea id="artist-bio" name="artist-bio" type="text" rows="5" maxlength="250" placeholder="Share what you want (Max: 250 characters)"></textarea>
    <hr />
    <label for="allow-collaboration">Allow collaboration?</label>
    <input id="allow-collaboration" name="allow-collaboration" type="checkbox">
    <h5>Checking the box will display your email address on your Creator page. This indicates your interest in collaborating with other Unearth creators.</h5>
    <input type="button" value="Submit" onclick="submitAccountInfo();">
</form>
</code>```

The respective Jquery that loads the data into the input fields and update fields:

```<code>$(document).ready(function()
{
    setFormValues();
});
function setFormValues()
{
    if("@(!String.IsNullOrWhiteSpace(Model.AccountInfo.ImageURL))" == "True")
    {
        $("#profile-image").attr("src", "@Model.AccountInfo.ImageURL");
    }
    if("@(!String.IsNullOrWhiteSpace(Model.AccountInfo.DisplayName))" == "True")
    {
        $("#display-name").val("@Html.Raw(Model.AccountInfo.DisplayName)");
    }
    if("@(!String.IsNullOrWhiteSpace(Model.AspNetUser.Email))" == "True")
    {
        $("#email").val("@Html.Raw(Model.AspNetUser.Email)");
    }
    if("@(!String.IsNullOrWhiteSpace(Model.AccountInfo.TwitterURL))" == "True")
    {
        $("#twitter-link").val("@Model.AccountInfo.TwitterURL");
    }
    if("@(!String.IsNullOrWhiteSpace(Model.AccountInfo.InstagramURL))" == "True")
    {
            $("#instagram-link").val("@Model.AccountInfo.InstagramURL");
    }
    if("@(!String.IsNullOrWhiteSpace(Model.AccountInfo.YouTubeURL))" == "True")
    {
        $("#youtube-link").val("@Model.AccountInfo.YouTubeURL");
    }
    if("@(!String.IsNullOrWhiteSpace(Model.AccountInfo.WebURL))" == "True")
    {
        $("#web-link").val("@Model.AccountInfo.WebURL");
    }
    if("@(!String.IsNullOrWhiteSpace(Model.AccountInfo.Bio))" == "True")
    {
        $("#artist-bio").html("@Model.AccountInfo.Bio").text();
    }
    if("@(Model.AccountInfo.AllowCollaborationFL.HasValue ? Model.AccountInfo.AllowCollaborationFL.Value : false)" == "True")
    {
        $("#allow-collaboration").prop("checked", true);
    }
}

    function updateAspNetUserEmail()
{
    var aspNetUser = new Object();
    aspNetUser.Email = $("#email").val();
    $.ajax
    ({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        url: "@Url.Content("~/Account/SubmitEmailInfo/")",
        data: JSON.stringify(aspNetUser),
        success: function(data)
        {
            if(data == true)
            {
                location.reload(true);
            }
        },
        error: function(jqXHR, textStatus, errorThrown)
        {
            //TODO: Indicate Error
        }
        });
}

function submitAccountInfo()
{
    var accountInfo = new Object();
    accountInfo.ImageURL = $("#profile-image").attr("src");
    accountInfo.DisplayName = $("#display-name").val();
    //accountInfo.Email = $("#email").val();
    accountInfo.TwitterURL = $("#twitter-link").val();
    accountInfo.InstagramURL = $("#instagram-link").val();
    accountInfo.YouTubeURL = $("#youtube-link").val();
    accountInfo.WebURL = $("#web-link").val();
    accountInfo.Bio = $("#artist-bio").val();
    accountInfo.AllowCollaborationFL = $("#allow-collaboration").is(":checked");
    $.ajax
    ({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        url: "@Url.Content("~/Account/SubmitAccountInfo/")",
        data: JSON.stringify(accountInfo),
        success: function(data)
        {
            if(data == true)
            {
                updateAspNetUserEmail();
            }
        },
        error: function(jqXHR, textStatus, errorThrown)
        {
            //TODO: Indicate Error
        }
        });
}
</code>```

And lastly, here's my accountcontroller with the Jsonsubmits:

```<code>public JsonResult SubmitEmailInfo(AspNetUser aspNetUser)
{
    try
    {
        var userID = User.Identity.GetUserId();
        aspNetUser.Id = userID;
        var _aspNetUser = EntityDataAccess.GetAspNetUserByID(userID);
        if (_aspNetUser == null)
        {
            aspNetUser = EntityDataAccess.InsertEmailInfo(aspNetUser);
        }
        else
        {
            aspNetUser.Id = _aspNetUser.Id;
            aspNetUser.EmailConfirmed = _aspNetUser.EmailConfirmed;
            aspNetUser.PasswordHash = _aspNetUser.PasswordHash;
            aspNetUser.SecurityStamp = _aspNetUser.SecurityStamp;
            aspNetUser.PhoneNumber = _aspNetUser.PhoneNumber;
            aspNetUser.PhoneNumberConfirmed = _aspNetUser.PhoneNumberConfirmed;
            aspNetUser.TwoFactorEnabled = _aspNetUser.TwoFactorEnabled;
            aspNetUser.LockoutEnabled = _aspNetUser.LockoutEnabled;
            aspNetUser.LockoutEndDateUtc = _aspNetUser.LockoutEndDateUtc;
            aspNetUser.AccessFailedCount = _aspNetUser.AccessFailedCount;
            aspNetUser.UserName = _aspNetUser.UserName;
            aspNetUser = EntityDataAccess.UpdateEmailInfo(aspNetUser);
        }
        return Json(true);
    }
    catch (Exception ex)
    {
        return Json(ex);
    }
}

public JsonResult SubmitAccountInfo(AccountInfo accountInfo)
{
    try
    {
        var userID = User.Identity.GetUserId();
        accountInfo.UserID = userID;
        var _accountInfo = EntityDataAccess.GetAccountInfoByUserID(userID);
        if(_accountInfo == null)
        {
            accountInfo = EntityDataAccess.InsertAccountInfo(accountInfo);
        }
        else
        {
            accountInfo.AccountInfoID = _accountInfo.AccountInfoID;
            accountInfo.CreatorFL = _accountInfo.CreatorFL;
            accountInfo.NeedsVerificationFL = _accountInfo.NeedsVerificationFL;
            accountInfo.VerifiedFL = _accountInfo.VerifiedFL;
            accountInfo.AdminFL = _accountInfo.AdminFL;
            accountInfo = EntityDataAccess.UpdateAccountInfo(accountInfo);
        }
        var algoliaArtistModel = Tools.BuildAlgoliaArtistModel(accountInfo);
        var artistIndexHelper = HttpContext.Application.Get("ArtistIndexHelper") as IndexHelper<ArtistAlgoliaModel>;
        artistIndexHelper.SaveObjectAsync(algoliaArtistModel);
        var algoliaSongModels = Tools.BuildAlgoliaSongModels(accountInfo);
        var songIndexHelper = HttpContext.Application.Get("SongIndexHelper") as IndexHelper<SongAlgoliaModel>;
        songIndexHelper.SaveObjectsAsync(algoliaSongModels);
        return Json(true);
    }
    catch(Exception ex)
    {
        return Json(ex);
    }
}
</code>```

答:
do this for every input you have</p>

```<code>   <script>
      function escapeHtml(text) {
       return text
      .replace(/&/g, "&")
      .replace(/</g, "<")
      .replace(/>/g, ">")
      .replace(/"/g, "``")
      .replace(/'/g, "`");
    }
      var displayname = document.getElementById("display-name").value;
      displayname = escapeHtml(displayname);
      /* repeat for every input */
    </script>
</code>```

Body:
Currently dealing with a bug if a user submits a special character into a textbox like '/' or '&' the information submits and displays on their profile page but on page reload all input boxes are empty and the user cannot submit any more changes. This is after a page refresh, all the fields I just filled out are now blank, and trying to submit 'test' into the bio i get this console error:

Here's the form html:

<form class="login-signup-form">
    Display Name
    <input id="display-name" name="display-name" type="text" placeholder="Name">
    Email
    <input id="email" name="email" type="email" placeholder="Email">
    Twitter link
    <input id="twitter-link" name="twitter-link" type="url" placeholder="https://">
    Instagram link
    <input id="instagram-link" name="instagram-link" type="url" placeholder="https://">
    YouTube link
    <input id="youtube-link" name="youtube-link" type="url" placeholder="https://">
    Website
    <input id="web-link" name="web-link" type="url" placeholder="https://">
    Bio
    <textarea id="artist-bio" name="artist-bio" type="text" rows="5" maxlength="250" placeholder="Share what you want (Max: 250 characters)"></textarea>

    Allow collaboration?
    <input id="allow-collaboration" name="allow-collaboration" type="checkbox">

Checking the box will display your email address on your Creator page. This indicates your interest in collaborating with other Unearth creators.

    <input type="button" value="Submit" onclick="submitAccountInfo();">
</form>

The respective Jquery that loads the data into the input fields and update fields:

$(document).ready(function()
{
    setFormValues();
});
function setFormValues()
{
    if("@(!String.IsNullOrWhiteSpace(Model.AccountInfo.ImageURL))" == "True")
    {
        $("#profile-image").attr("src", "@Model.AccountInfo.ImageURL");
    }
    if("@(!String.IsNullOrWhiteSpace(Model.AccountInfo.DisplayName))" == "True")
    {
        $("#display-name").val("@Html.Raw(Model.AccountInfo.DisplayName)");
    }
    if("@(!String.IsNullOrWhiteSpace(Model.AspNetUser.Email))" == "True")
    {
        $("#email").val("@Html.Raw(Model.AspNetUser.Email)");
    }
    if("@(!String.IsNullOrWhiteSpace(Model.AccountInfo.TwitterURL))" == "True")
    {
        $("#twitter-link").val("@Model.AccountInfo.TwitterURL");
    }
    if("@(!String.IsNullOrWhiteSpace(Model.AccountInfo.InstagramURL))" == "True")
    {
            $("#instagram-link").val("@Model.AccountInfo.InstagramURL");
    }
    if("@(!String.IsNullOrWhiteSpace(Model.AccountInfo.YouTubeURL))" == "True")
    {
        $("#youtube-link").val("@Model.AccountInfo.YouTubeURL");
    }
    if("@(!String.IsNullOrWhiteSpace(Model.AccountInfo.WebURL))" == "True")
    {
        $("#web-link").val("@Model.AccountInfo.WebURL");
    }
    if("@(!String.IsNullOrWhiteSpace(Model.AccountInfo.Bio))" == "True")
    {
        $("#artist-bio").html("@Model.AccountInfo.Bio").text();
    }
    if("@(Model.AccountInfo.AllowCollaborationFL.HasValue ? Model.AccountInfo.AllowCollaborationFL.Value : false)" == "True")
    {
        $("#allow-collaboration").prop("checked", true);
    }
}

    function updateAspNetUserEmail()
{
    var aspNetUser = new Object();
    aspNetUser.Email = $("#email").val();
    $.ajax
    ({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        url: "@Url.Content("~/Account/SubmitEmailInfo/")",
        data: JSON.stringify(aspNetUser),
        success: function(data)
        {
            if(data == true)
            {
                location.reload(true);
            }
        },
        error: function(jqXHR, textStatus, errorThrown)
        {
            //TODO: Indicate Error
        }
        });
}

function submitAccountInfo()
{
    var accountInfo = new Object();
    accountInfo.ImageURL = $("#profile-image").attr("src");
    accountInfo.DisplayName = $("#display-name").val();
    //accountInfo.Email = $("#email").val();
    accountInfo.TwitterURL = $("#twitter-link").val();
    accountInfo.InstagramURL = $("#instagram-link").val();
    accountInfo.YouTubeURL = $("#youtube-link").val();
    accountInfo.WebURL = $("#web-link").val();
    accountInfo.Bio = $("#artist-bio").val();
    accountInfo.AllowCollaborationFL = $("#allow-collaboration").is(":checked");
    $.ajax
    ({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        url: "@Url.Content("~/Account/SubmitAccountInfo/")",
        data: JSON.stringify(accountInfo),
        success: function(data)
        {
            if(data == true)
            {
                updateAspNetUserEmail();
            }
        },
        error: function(jqXHR, textStatus, errorThrown)
        {
            //TODO: Indicate Error
        }
        });
}

And lastly, here's my accountcontroller with the Jsonsubmits:

public JsonResult SubmitEmailInfo(AspNetUser aspNetUser)
{
    try
    {
        var userID = User.Identity.GetUserId();
        aspNetUser.Id = userID;
        var _aspNetUser = EntityDataAccess.GetAspNetUserByID(userID);
        if (_aspNetUser == null)
        {
            aspNetUser = EntityDataAccess.InsertEmailInfo(aspNetUser);
        }
        else
        {
            aspNetUser.Id = _aspNetUser.Id;
            aspNetUser.EmailConfirmed = _aspNetUser.EmailConfirmed;
            aspNetUser.PasswordHash = _aspNetUser.PasswordHash;
            aspNetUser.SecurityStamp = _aspNetUser.SecurityStamp;
            aspNetUser.PhoneNumber = _aspNetUser.PhoneNumber;
            aspNetUser.PhoneNumberConfirmed = _aspNetUser.PhoneNumberConfirmed;
            aspNetUser.TwoFactorEnabled = _aspNetUser.TwoFactorEnabled;
            aspNetUser.LockoutEnabled = _aspNetUser.LockoutEnabled;
            aspNetUser.LockoutEndDateUtc = _aspNetUser.LockoutEndDateUtc;
            aspNetUser.AccessFailedCount = _aspNetUser.AccessFailedCount;
            aspNetUser.UserName = _aspNetUser.UserName;
            aspNetUser = EntityDataAccess.UpdateEmailInfo(aspNetUser);
        }
        return Json(true);
    }
    catch (Exception ex)
    {
        return Json(ex);
    }
}

public JsonResult SubmitAccountInfo(AccountInfo accountInfo)
{
    try
    {
        var userID = User.Identity.GetUserId();
        accountInfo.UserID = userID;
        var _accountInfo = EntityDataAccess.GetAccountInfoByUserID(userID);
        if(_accountInfo == null)
        {
            accountInfo = EntityDataAccess.InsertAccountInfo(accountInfo);
        }
        else
        {
            accountInfo.AccountInfoID = _accountInfo.AccountInfoID;
            accountInfo.CreatorFL = _accountInfo.CreatorFL;
            accountInfo.NeedsVerificationFL = _accountInfo.NeedsVerificationFL;
            accountInfo.VerifiedFL = _accountInfo.VerifiedFL;
            accountInfo.AdminFL = _accountInfo.AdminFL;
            accountInfo = EntityDataAccess.UpdateAccountInfo(accountInfo);
        }
        var algoliaArtistModel = Tools.BuildAlgoliaArtistModel(accountInfo);
        var artistIndexHelper = HttpContext.Application.Get("ArtistIndexHelper") as IndexHelper<ArtistAlgoliaModel>;
        artistIndexHelper.SaveObjectAsync(algoliaArtistModel);
        var algoliaSongModels = Tools.BuildAlgoliaSongModels(accountInfo);
        var songIndexHelper = HttpContext.Application.Get("SongIndexHelper") as IndexHelper<SongAlgoliaModel>;
        songIndexHelper.SaveObjectsAsync(algoliaSongModels);
        return Json(true);
    }
    catch(Exception ex)
    {
        return Json(ex);
    }
}

Body:
do this for every input you have

   <script>
      function escapeHtml(text) {
       return text
      .replace(/&/g, "&amp;")
      .replace(/</g, "&lt;")
      .replace(/>/g, "&gt;")
      .replace(/"/g, "``")
      .replace(/'/g, "`");
    }
      var displayname = document.getElementById("display-name").value;
      displayname = escapeHtml(displayname);
      /* repeat for every input */
    </script>


问:
How do I retrieve the remote FS root from declarative Jenkinsfile?
I have a heavyweight base project that rarely changes over time and has a lot of header files. I've set it up to be built in a custom workspace with a relative path base. So on a remote node with FS root set to C:\Jenkins, the resulting path on that particular node will be C:\Jenkins\base.
The reason for this setup is that I don't want to copy or unpack the whole base project for every dependent project to save build time. Also, I don't want to use absolute paths because I like the idea of a self-contained jenkins installation.

Now I have a second project project that uses base. I need to specify the path of base to the build system of project so that it will find the base headers it needs.

Is there any way to retrieve the remote FS root through the environment? I've tried using ${env.JENKINS_HOME} but this always resolves to the home folder of the Jenkins master. My build system expects to find the path to the base project in the PATH_TO_BASE environment variable:

```<code>pipeline {
    agent none

    stages {
        stage('Build') {
            parallel {
                stage('Build Linux x64') {
                    agent {
                        label "Debian9_x64"
                    }
                    steps {
                        withEnv(["PATH_TO_BASE=${env.JENKINS_HOME}/base"]) {
                            sh '''mkdir -p _build
                            cd _build
                            cmake ..
                            cmake --build .'''
                        }
                    }
                }
                stage('Build Windows10') {
                    agent {
                        label "Windows10"
                    }
                    steps {
                        withEnv(["PATH_TO_BASE=${env.JENKINS_HOME}/base"]) {
                            bat '''if not exist _build mkdir _build
                            cd _build
                            cmake ..
                            cmake --build .'''
                        }
                    }
                }
            }
        }
    }
}
</code>```

答:
I usually configure slave with a set of environment variables.

Go to the slave configuration

Set Environment varaible under "node properties" section.

Body:
I have a heavyweight base project that rarely changes over time and has a lot of header files. I've set it up to be built in a custom workspace with a relative path base. So on a remote node with FS root set to C:\Jenkins, the resulting path on that particular node will be C:\Jenkins\base.
The reason for this setup is that I don't want to copy or unpack the whole base project for every dependent project to save build time. Also, I don't want to use absolute paths because I like the idea of a self-contained jenkins installation.

Now I have a second project project that uses base. I need to specify the path of base to the build system of project so that it will find the base headers it needs.

Is there any way to retrieve the remote FS root through the environment? I've tried using ${env.JENKINS_HOME} but this always resolves to the home folder of the Jenkins master. My build system expects to find the path to the base project in the PATH_TO_BASE environment variable:

pipeline {
    agent none

    stages {
        stage('Build') {
            parallel {
                stage('Build Linux x64') {
                    agent {
                        label "Debian9_x64"
                    }
                    steps {
                        withEnv(["PATH_TO_BASE=${env.JENKINS_HOME}/base"]) {
                            sh '''mkdir -p _build
                            cd _build
                            cmake ..
                            cmake --build .'''
                        }
                    }
                }
                stage('Build Windows10') {
                    agent {
                        label "Windows10"
                    }
                    steps {
                        withEnv(["PATH_TO_BASE=${env.JENKINS_HOME}/base"]) {
                            bat '''if not exist _build mkdir _build
                            cd _build
                            cmake ..
                            cmake --build .'''
                        }
                    }
                }
            }
        }
    }
}


问:
Fortran choice of format to enhance code execution time
I have a code which starts with three arrays of values which are initialized in the beginning of the code. For a different runs, I have to go into the code to make an explicit changes on these initial values.
Since this is very frustrating and time consuming, I have decided to modify the code such that the code reads the initial values from a text file instead.

Although I successfully made a change, now the code runs much much slower (at least factor 20).

When I initialized the array explicitly in the code, the arrays looked something like

array1 = {0.001,0.002,0.034,...}
array2 = {42D4, 36D4, 72D4, 10D5, ...}.

and I have tried reading these array values from a text file using

Format(E8.2) or Format(D8.2) or Format(F8.2).

I am guessing that the way I read the values from the file using these format has to do with the immense reduction in the code speed?

Is this true? If not, what do I need to do?
If yes, how should I modify the format so that my code runs at a similar speed as before?

答:
It is hard to argue if the reading takes a big part of the runtime in your code. We can't know, because we can't see the code. But if yes then:

As said many, many times before, you are not going to get good performance with text files. The format you set for reading is irrelevant, the runtime library has to do a lot of processing to convert the string to a number in the computer's memory.

The way to significantly speed the I/O operations is to use unformatted (binary) data files.

Notably, formats you tried

```<code>Format(E8.2)
Format(D8.2)
Format(F8.2)
</code>```

are all completely equivalent for input. Not only their speed. Their meaning is for input completely equivalent.

Body:
It is hard to argue if the reading takes a big part of the runtime in your code. We can't know, because we can't see the code. But if yes then:

As said many, many times before, you are not going to get good performance with text files. The format you set for reading is irrelevant, the runtime library has to do a lot of processing to convert the string to a number in the computer's memory.

The way to significantly speed the I/O operations is to use unformatted (binary) data files.

Notably, formats you tried

Format(E8.2)
Format(D8.2)
Format(F8.2)

are all completely equivalent for input. Not only their speed. Their meaning is for input completely equivalent.


问:
Countdown (Cookies)
How do I make this countdown able to not reset the countdown when it is refresh? Like when I click refresh it should continue the countdown instead of resetting the countdown again, from "14d, 22h, 23m, 32s" (refresh) to continue to "14d , 22, 59m, 59s".

With some research I saw I should use Cookies but I don't know how to create one, hope you can help me create one!

function getTimeRemaining(endtime) {
  var t = Date.parse(endtime) - Date.parse(new Date());
  var seconds = Math.floor((t / 1000) % 60);
  var minutes = Math.floor((t / 1000 / 60) % 60);
  var hours = Math.floor((t / (1000 * 60 * 60)) % 24);
  var days = Math.floor(t / (1000 * 60 * 60 * 24));
  return {
    'total': t,
    'days': days,
    'hours': hours,
    'minutes': minutes,
    'seconds': seconds
  };
}

function initializeClock(id, endtime) {
  var clock = document.getElementById(id);
  var daysSpan = clock.querySelector('.days');
  var hoursSpan = clock.querySelector('.hours');
  var minutesSpan = clock.querySelector('.minutes');
  var secondsSpan = clock.querySelector('.seconds');

  function updateClock() {
    var t = getTimeRemaining(endtime);

    daysSpan.innerHTML = t.days;
    hoursSpan.innerHTML = ('0' + t.hours).slice(-2);
    minutesSpan.innerHTML = ('0' + t.minutes).slice(-2);
    secondsSpan.innerHTML = ('0' + t.seconds).slice(-2);

    if (t.total <= 0) {
      clearInterval(timeinterval);
    }
  }

  updateClock();
  var timeinterval = setInterval(updateClock, 1000);
}

var deadline = new Date(Date.parse(new Date()) + 15 * 24 * 60 * 60 * 1000);
initializeClock('clockdiv', deadline);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>@import 'https://fonts.googleapis.com/css?family=Alegreya+Sans';

@font-face {
    font-family: 'ps';
    src: url("../fonts/personalservice.ttf");
}

@font-face {
    font-family: 'afb';
    src: url("../fonts/Agency_FB.ttf");
}

@font-face {
    font-family: 'blob';
    src: url("../fonts/Blobtastics.ttf");
}

@font-face {
    font-family: 'rv';
    src: url("../fonts/roundedvale.ttf");
}

/*start loading*/

.spinner{
    width: 80px;
    height: 80px;

    border: 2px solid #f3f3f3;
    border-top:3px solid #f25a41;
    border-radius: 100%;

    position: absolute;
    top:0;
    bottom:0;
    left:0;
    right: 0;
    margin: auto;

    animation: spin 1s infinite linear;
}

@keyframes spin {
    from{
        transform: rotate(0deg);
    }to{
        transform: rotate(360deg);
    }
}

#overlay{
  height:100%;
  width:100%;
  background: #e1e1e1;
  opacity: .5;
  position:fixed;
  left:0;
  top:0;
 }

* {
    margin: 0;
    padding: 0;
    border: 0;
}

body {
    background: #e1e1e1;
    color: #67727A;
    font-family: 'Alegreya', Sans-serif;
}

#banner{
    height: 592px;
    vertical-align: center;
}

#branding{
    padding-top: 150px;
    width: 752px;
    height: 100px;
    padding-left: 400px;
}

#text{
    padding-top: 30px;
    font-family: 'ps';
    font-size: 40px;
    width: 500px;
    float: right;
}

#logo {
    float: left;
    width: 251px;
    height: 90px;
    background: url(../img/RH5.png) no-repeat center;
}

#clockdiv{
    font-family: sans-serif;
    color: #fff;
    display: inline-block;
    font-weight: 100;
    text-align: center;
    font-size: 50px;
    padding-left: 440px;
}

#clockdiv > div{
    padding: 10px;
    border-radius: 3px;
    background: #00BF96;
    display: inline-block;
}

#clockdiv div > span{
    padding: 15px;
    border-radius: 3px;
    background: #00816A;
    display: inline-block;
}

.smalltext{
    padding-top: 5px;
    font-size: 16px;
}

footer{
    background-color: #87ceeb;
    height: 70px;
}

#ig img{
    width: 49px;
    height: 49px;
    float: right;
    margin-right: 25px;
    margin-top: 10px;
    text-align: center;
}

#fb img{
    width: 49px;
    height: 49px;
    margin-top: 10px;
    margin-right: 625px;
    float: right;
    text-align: center;
    border-radius: 10px 10px 10px 10px;
}</code>```

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <meta name="description" content="FSX Repaints">
    <meta name="keywords" content="fsx, repaints, project airbus, just flight, pmdg, captainsim, premier airraft design, pad, airlines, project opensky, posky, tom's ruth">
    <meta name="author" content="Raven Lescano">
    <title>Coming Soon | Raven's Hangar</title>
    <link rel="stylesheet" href="css/countdown.css" type="text/css">
    <link href="css/font-awesome.min.css" rel="stylesheet">

coming soon

Days

Hours

Minutes

Seconds

```

答:
Please use this link to see how to create cookie in Javascript :
https://www.w3schools.com/js/js_cookies.asp</p>

Title: Countdown (Cookies)

Body:
How do I make this countdown able to not reset the countdown when it is refresh? Like when I click refresh it should continue the countdown instead of resetting the countdown again, from "14d, 22h, 23m, 32s" (refresh) to continue to "14d , 22, 59m, 59s".

With some research I saw I should use Cookies but I don't know how to create one, hope you can help me create one!

function getTimeRemaining(endtime) {
  var t = Date.parse(endtime) - Date.parse(new Date());
  var seconds = Math.floor((t / 1000) % 60);
  var minutes = Math.floor((t / 1000 / 60) % 60);
  var hours = Math.floor((t / (1000 * 60 * 60)) % 24);
  var days = Math.floor(t / (1000 * 60 * 60 * 24));
  return {
    'total': t,
    'days': days,
    'hours': hours,
    'minutes': minutes,
    'seconds': seconds
  };
}

function initializeClock(id, endtime) {
  var clock = document.getElementById(id);
  var daysSpan = clock.querySelector('.days');
  var hoursSpan = clock.querySelector('.hours');
  var minutesSpan = clock.querySelector('.minutes');
  var secondsSpan = clock.querySelector('.seconds');

  function updateClock() {
    var t = getTimeRemaining(endtime);

    daysSpan.innerHTML = t.days;
    hoursSpan.innerHTML = ('0' + t.hours).slice(-2);
    minutesSpan.innerHTML = ('0' + t.minutes).slice(-2);
    secondsSpan.innerHTML = ('0' + t.seconds).slice(-2);

    if (t.total <= 0) {
      clearInterval(timeinterval);
    }
  }

  updateClock();
  var timeinterval = setInterval(updateClock, 1000);
}

var deadline = new Date(Date.parse(new Date()) + 15 * 24 * 60 * 60 * 1000);
initializeClock('clockdiv', deadline);

@import 'https://fonts.googleapis.com/css?family=Alegreya+Sans';

@font-face {
    font-family: 'ps';
    src: url("../fonts/personalservice.ttf");
}

@font-face {
    font-family: 'afb';
    src: url("../fonts/Agency_FB.ttf");
}

@font-face {
    font-family: 'blob';
    src: url("../fonts/Blobtastics.ttf");
}

@font-face {
    font-family: 'rv';
    src: url("../fonts/roundedvale.ttf");
}

/*start loading*/

.spinner{
    width: 80px;
    height: 80px;

    border: 2px solid #f3f3f3;
    border-top:3px solid #f25a41;
    border-radius: 100%;

    position: absolute;
    top:0;
    bottom:0;
    left:0;
    right: 0;
    margin: auto;

    animation: spin 1s infinite linear;
}

@keyframes spin {
    from{
        transform: rotate(0deg);
    }to{
        transform: rotate(360deg);
    }
}

#overlay{
  height:100%;
  width:100%;
  background: #e1e1e1;
  opacity: .5;
  position:fixed;
  left:0;
  top:0;
 }

* {
    margin: 0;
    padding: 0;
    border: 0;
}

body {
    background: #e1e1e1;
    color: #67727A;
    font-family: 'Alegreya', Sans-serif;
}

#banner{
    height: 592px;
    vertical-align: center;
}

#branding{
    padding-top: 150px;
    width: 752px;
    height: 100px;
    padding-left: 400px;
}

#text{
    padding-top: 30px;
    font-family: 'ps';
    font-size: 40px;
    width: 500px;
    float: right;
}

#logo {
    float: left;
    width: 251px;
    height: 90px;
    background: url(../img/RH5.png) no-repeat center;
}

#clockdiv{
    font-family: sans-serif;
    color: #fff;
    display: inline-block;
    font-weight: 100;
    text-align: center;
    font-size: 50px;
    padding-left: 440px;
}

#clockdiv > div{
    padding: 10px;
    border-radius: 3px;
    background: #00BF96;
    display: inline-block;
}

#clockdiv div > span{
    padding: 15px;
    border-radius: 3px;
    background: #00816A;
    display: inline-block;
}

.smalltext{
    padding-top: 5px;
    font-size: 16px;
}

footer{
    background-color: #87ceeb;
    height: 70px;
}

#ig img{
    width: 49px;
    height: 49px;
    float: right;
    margin-right: 25px;
    margin-top: 10px;
    text-align: center;
}

#fb img{
    width: 49px;
    height: 49px;
    margin-top: 10px;
    margin-right: 625px;
    float: right;
    text-align: center;
    border-radius: 10px 10px 10px 10px;
}

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <meta name="description" content="FSX Repaints">
    <meta name="keywords" content="fsx, repaints, project airbus, just flight, pmdg, captainsim, premier airraft design, pad, airlines, project opensky, posky, tom's ruth">
    <meta name="author" content="Raven Lescano">
    <title>Coming Soon | Raven's Hangar</title>
    <link rel="stylesheet" href="css/countdown.css" type="text/css">
    <link href="css/font-awesome.min.css" rel="stylesheet">

coming soon

Days

Hours

Minutes

Seconds


问:
Wordpress count results for post_title not working with foreach

I have this code:

```<code>$data = "test 1, test 2, test 3, test 4, test 5";
$verify = explode(',', $data);
 foreach($verify as $datatoverify){
   echo $wpdb->get_var("SELECT count(post_title) FROM $wpdb->posts WHERE post_title LIKE '$datatoverify'");
}
</code>```

The "test 3" and "test 5" exists in database.
With the code above it shows 00000 as output.
If i make the echo with a value (test 3 or test 5) it echos 2 that exists.

```<code>echo $wpdb->get_var("SELECT count(post_title) FROM $wpdb->posts WHERE post_title LIKE 'test 3'");
</code>```

Why isn't working with foreach? What i'm doing wrong?

UPDATE

I found what the problem was, I had to add a trim($datatoverify) to strip whitespace (or other characters) from the beginning and end of a string.

答:
```<code>$data = "test 1, test 2, test 3, test 4, test 5";
$verify = explode(', ', $data);
 foreach($verify as $datatoverify){
   echo $wpdb->get_var("SELECT count(post_title) FROM $wpdb->posts WHERE post_title LIKE '".$datatoverify."'");
}
</code>```

TRY this I hope it works :D

Body:
I have this code:

$data = "test 1, test 2, test 3, test 4, test 5";
$verify = explode(',', $data);
 foreach($verify as $datatoverify){
   echo $wpdb->get_var("SELECT count(post_title) FROM $wpdb->posts WHERE post_title LIKE '$datatoverify'");
}

The "test 3" and "test 5" exists in database.
With the code above it shows 00000 as output.
If i make the echo with a value (test 3 or test 5) it echos 2 that exists.

echo $wpdb->get_var("SELECT count(post_title) FROM $wpdb->posts WHERE post_title LIKE 'test 3'");

Why isn't working with foreach? What i'm doing wrong?

UPDATE

I found what the problem was, I had to add a trim($datatoverify) to strip whitespace (or other characters) from the beginning and end of a string.

Body:
$data = "test 1, test 2, test 3, test 4, test 5";
$verify = explode(', ', $data);
 foreach($verify as $datatoverify){
   echo $wpdb->get_var("SELECT count(post_title) FROM $wpdb->posts WHERE post_title LIKE '".$datatoverify."'");
}

TRY this I hope it works :D


问:
mongodb specific query like join
I am new in nosql and I need a query that works like join. I hope you can help me with that.
User collection which has id name
Idea collection which includes id comment user_id

one can have many comments and I would like to reach the
comments given by user
Idea.comment User.name is the result I want
I hope you can help me thx

```<code>db.ProjectIdea.aggregate([
    {
    $lookup:{
        from:"User",
        localField:"createdUser",
        foreignField:"_id",
        as:"kim"
    }
}
]).forEach(
function(u){

         print(u.kim[0].name;
    }
);
</code>```

however, some users do not have name attribute defined so i am havin error
How do I perform the SQL Join equivalent in MongoDB? i tried the thing in the link before but could not solve the whole problem

答:
I found the solution </p>

```<code>db.ProjectIdea.aggregate([
    { "$match": { projectId:ObjectId("59e72193212ef231dc5c7d7d") } },
    {
        $lookup:{
            from:"User",
            localField:"createdUser",
            foreignField:"_id",
            as:"kim"
    }
}
]).forEach(
    function(u){
        print(""+u._id+'|'+u.caption.replace("\r"," ").replace("\n","
        ")+'|'+u.idea.replace("\r"," ").replace("\n"," ")+'|'+u.kim[0].name+'
'+u.kim[0].lastName+"");
}
);
</code>```

<p>Only problem here is if the "kim" part does not have the name and lastName (eg after the comment deleting the person who gives the comment can make that part undefined) this code throws error. I will try to fix that error too. Then edit that part again. </p>

Title: mongodb specific query like join

Body:
I am new in nosql and I need a query that works like join. I hope you can help me with that.
User collection which has id name
Idea collection which includes id comment user_id

one can have many comments and I would like to reach the
comments given by user
Idea.comment User.name is the result I want
I hope you can help me thx

db.ProjectIdea.aggregate([
    {
    $lookup:{
        from:"User",
        localField:"createdUser",
        foreignField:"_id",
        as:"kim"
    }
}
]).forEach(
function(u){

         print(u.kim[0].name;
    }
);

however, some users do not have name attribute defined so i am havin error
How do I perform the SQL Join equivalent in MongoDB? i tried the thing in the link before but could not solve the whole problem

Body:
I found the solution

db.ProjectIdea.aggregate([
    { "$match": { projectId:ObjectId("59e72193212ef231dc5c7d7d") } },
    {
        $lookup:{
            from:"User",
            localField:"createdUser",
            foreignField:"_id",
            as:"kim"
    }
}
]).forEach(
    function(u){
        print(""+u._id+'|'+u.caption.replace("\r"," ").replace("\n","
        ")+'|'+u.idea.replace("\r"," ").replace("\n"," ")+'|'+u.kim[0].name+'
'+u.kim[0].lastName+"");
}
);

Only problem here is if the "kim" part does not have the name and lastName (eg after the comment deleting the person who gives the comment can make that part undefined) this code throws error. I will try to fix that error too. Then edit that part again.


问:
How to get Dropdowns selected text where there are multiple dropdowns
I have multiple dropdowns like this

```<code><asp:DropDownList ID="ddl1"
        runat="server"
        DataTextField="Text"
        DataValueField="ValID"
        AutoPostBack="true"
        OnSelectedIndexChanged="ddl_SelectedIndexChanged">
</asp:DropDownList>

<asp:DropDownList ID="ddl2"
    runat="server"
    DataTextField="Text"
    DataValueField="ValID"
    AutoPostBack="true"
    OnSelectedIndexChanged="ddl_SelectedIndexChanged">
</asp:DropDownList>
</code>```

Both the dropdowns has different set of values they are unique. I did the following on ddl_SelectedIndexChanged funtion

```<code>DropDownList ddl = sender as DropDownList;
string selectedId = ddl.ID;
string selectedText = ddl.SelectedItem.Text;
</code>```

When I select values on the first dropdown I get correct selectedId  and selectedText.

My Problem:
When I select the second dropdown the selectedId is of the second dropdown but selectedText is always the first dropdowns first value and it never changes. I need selectedText to be that of the Item which I select in the second dropdown.

Any Suggestion?

答:
When binding the data to the DropDownLists, you must place them inside an IsPostBack check.

```<code>protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        ddl1.DataSource = source;
        ddl1.DataBind();

        ddl2.DataSource = source;
        ddl2.DataBind();
    }
}
</code>```

If you do not the SelectedIndexChanged will fire each time for the DropDownList because rebinding data will trigger that since the previous selecedindex is overwritten.

Body:
I have multiple dropdowns like this

<asp:DropDownList ID="ddl1"
        runat="server"
        DataTextField="Text"
        DataValueField="ValID"
        AutoPostBack="true"
        OnSelectedIndexChanged="ddl_SelectedIndexChanged">
</asp:DropDownList>

<asp:DropDownList ID="ddl2"
    runat="server"
    DataTextField="Text"
    DataValueField="ValID"
    AutoPostBack="true"
    OnSelectedIndexChanged="ddl_SelectedIndexChanged">
</asp:DropDownList>

Both the dropdowns has different set of values they are unique. I did the following on ddl_SelectedIndexChanged funtion

DropDownList ddl = sender as DropDownList;
string selectedId = ddl.ID;
string selectedText = ddl.SelectedItem.Text;

When I select values on the first dropdown I get correct selectedId  and selectedText.

My Problem:
When I select the second dropdown the selectedId is of the second dropdown but selectedText is always the first dropdowns first value and it never changes. I need selectedText to be that of the Item which I select in the second dropdown.

Any Suggestion?

Body:
When binding the data to the DropDownLists, you must place them inside an IsPostBack check.

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        ddl1.DataSource = source;
        ddl1.DataBind();

        ddl2.DataSource = source;
        ddl2.DataBind();
    }
}

If you do not the SelectedIndexChanged will fire each time for the DropDownList because rebinding data will trigger that since the previous selecedindex is overwritten.


问:
Get specific href values or link from email which is parsed as html in c#
I am processing emails in my C# service. I need to extract certain links present in the same to add to DB. I am using HtmlagilityPack. The div and p tags turn out interchangeable in the parsed email. I have to extract the links present below the tags 'Scheduler Link', 'Data Path' and 'Link' from the email. After cleaning it up, a sample data is as follows :

```<code><html>
 <body>
   ......//contains some other tags which i dont need, may include hrefs but
         //i dont need them
   <div align="justify" style="margin:0;"></div>
   <div align="justify" style="margin:0;"></div>
   <div align="justify" style="margin:0;">Scheduler link :</div>
   <div align="justify" style="margin:0;"></div>
   <div style="margin:0;"><a href="https://something.com/requests/26428">
   https://something.com/requests/26428</a>
   </div>
   <div style="margin:0;"></div>
   <div style="margin:0;"></div>
   <div style="margin:0;"></div>
   <div align="justify" style="margin:0;">Data path :</div>
   <div align="left" style="text-align:justify;margin:0;"><a
   href="file:///\\mycompany.com\ABC\OPQ1234\jui\tui245.5t_2rtfg_tyui">
   \\mycompany.com\ABC\OPQ1234\jui\tui245.5t_2rtfg_tyui</a>
   </div>
   <div align="left" style="text-align:justify;margin:0;"><a
   href="file:///\\mycompany.com\ABC\OPQ1234\tui245.5t_2rtfg_tyui">
   \\mycompany.com\ABC\OPQ1234\tui245.5t_2rtfg_tyui</a>
   </div>
   <div align="justify" style="margin:0;"></div>
   <div align="justify" style="margin:0;">Link :</div>
   <div align="justify" style="margin:0;"><a
   href="https://Thisisanotherlink.abcdef/sites/this/498592/rkjfb/3874y">
   This is some text</a></div>
   <div align="justify" style="margin:0 0 5pt 0;">This is another text</div>

   ......//contains some other tags which i dont need
 </body>
</html>
</code>```

I am looking for the div tag of 'Scheduler Link', 'Data Path' and 'Link' using regular expressions as follows :

```<code>HtmlNode schedulerLink = doc.DocumentNode.SelectSingleNode("//*[text()[contains(.,'" + Regex.Match(body, _keyValuePairs["scheduler"]).Value.ToString() + "')]]");
HtmlNode dataPath = doc.DocumentNode.SelectSingleNode("//*[text()[contains(.,'" + Regex.Match(body, _keyValuePairs["datapath"]).Value.ToString() + "')]]");
HtmlNode link = doc.DocumentNode.SelectSingleNode("//*[text()[contains(.,'" + Regex.Match(body, _keyValuePairs["link"]).Value.ToString() + "')]]");
</code>```

The div tags are returning me the respective nodes. The number of links present against the three in each email varies and so does the order of the tags. I need to capture the links against each in a list. I am using the following code :

```<code> foreach (HtmlNode link in schedulerLink.Descendants())
        {
        string hrefValue = link.GetAttributeValue("href", string.Empty);

            if (!(link.InnerText.Contains("\r\n")))
            {
                if (link.InnerText.Contains("/"))
                {
                    schedulersList.Add(link.InnerText.Trim());
                }
            }
        }
</code>```

The descendants sometimes is not returning the correct number of nodes. Also how do i get the specific links against the 3 tags in 3 different lists since descendants usually return all the nodes present below.

答:
If I understand correctly, you want to capture the content of the first href-attribute after a specific string like scheduler link. I don't know about the HtmlagilityPack, but my approach would be to just search the email body with a regex like this:

```<code>Scheduler link(?:\s|\S)*?href="([^"]+)
</code>```

This regex should capture the content of the first href-attribute after every occurence of "Scheduler link" in the mail.

You can try it here: Regex101

To find the other types of links just replace the Scheduler link part with the respective string.

I hope this is helpful.

Additional info about the regex:

Scheduler link matches the string literally

(?:\s|\S)*?href=" non-capturing group that matches any character until the first occurence of the literal string href="

([^"]+) captures everything despite the " character

Body:
I am processing emails in my C# service. I need to extract certain links present in the same to add to DB. I am using HtmlagilityPack. The div and p tags turn out interchangeable in the parsed email. I have to extract the links present below the tags 'Scheduler Link', 'Data Path' and 'Link' from the email. After cleaning it up, a sample data is as follows :

   ......//contains some other tags which i dont need, may include hrefs but
         //i dont need them

Scheduler link :

   https://something.com/requests/26428

Data path :

   \\mycompany.com\ABC\OPQ1234\jui\tui245.5t_2rtfg_tyui

   \\mycompany.com\ABC\OPQ1234\tui245.5t_2rtfg_tyui

Link :

   This is some text

This is another text

   ......//contains some other tags which i dont need

I am looking for the div tag of 'Scheduler Link', 'Data Path' and 'Link' using regular expressions as follows :

HtmlNode schedulerLink = doc.DocumentNode.SelectSingleNode("//*[text()[contains(.,'" + Regex.Match(body, _keyValuePairs["scheduler"]).Value.ToString() + "')]]");
HtmlNode dataPath = doc.DocumentNode.SelectSingleNode("//*[text()[contains(.,'" + Regex.Match(body, _keyValuePairs["datapath"]).Value.ToString() + "')]]");
HtmlNode link = doc.DocumentNode.SelectSingleNode("//*[text()[contains(.,'" + Regex.Match(body, _keyValuePairs["link"]).Value.ToString() + "')]]");

The div tags are returning me the respective nodes. The number of links present against the three in each email varies and so does the order of the tags. I need to capture the links against each in a list. I am using the following code :

 foreach (HtmlNode link in schedulerLink.Descendants())
        {
        string hrefValue = link.GetAttributeValue("href", string.Empty);

            if (!(link.InnerText.Contains("\r\n")))
            {
                if (link.InnerText.Contains("/"))
                {
                    schedulersList.Add(link.InnerText.Trim());
                }
            }
        }

The descendants sometimes is not returning the correct number of nodes. Also how do i get the specific links against the 3 tags in 3 different lists since descendants usually return all the nodes present below.

Body:
If I understand correctly, you want to capture the content of the first href-attribute after a specific string like scheduler link. I don't know about the HtmlagilityPack, but my approach would be to just search the email body with a regex like this:

Scheduler link(?:\s|\S)*?href="([^"]+)

This regex should capture the content of the first href-attribute after every occurence of "Scheduler link" in the mail.

You can try it here: Regex101

To find the other types of links just replace the Scheduler link part with the respective string.

I hope this is helpful.

Additional info about the regex:

Scheduler link matches the string literally

(?:\s|\S)*?href=" non-capturing group that matches any character until the first occurence of the literal string href="

([^"]+) captures everything despite the " character


问:
Building MySQL query with need for variable operators PHP PDO
Is there any standard or best way in PHP PDO database class to change the operator from "=" to "IS" when I don't know if the value I'm going to pass is NULL or not.  Here is an example of what I mean.

I have two variables.  I want a count of the results that match.  Sometimes one or both of the variables can be NULL.  But MySQL requires a different operator to find NULL (IS NULL).

I'm currently just creating another variable for the operator and when I build the query I inject it in as so:

```<code>  // First create a variable "=" or "is" depending on whether var1 and var2 are NULL or not
  if($var1 == NULL) $var1_operator = "IS";
  else $var1_operator = "=";
  if($var2 == NULL) $var2_operator = "IS";
  else $var2_operator = "=";

  // Build the query
  $query = 'SELECT count(*) as count FROM table
  WHERE var1 '.$var1_operator.' :var1 AND var2 '.$var2_operator.' :var2';

  //  Conduct the query
  $prepare = $db_connection->prepare($query);
  $prepare->bindValue(':var1', $var1, PDO::PARAM_STR);
  $prepare->bindValue(':var2', $var2, PDO::PARAM_STR);
  $prepare->execute();
  $results = $prepare->fetch();
</code>```

Is there another way to do this?  This works to bindValue using PARAM_STR even when the value is NULL and not really a string.  The query returns the correct value count.  Just not sure if there is better practice for doing it.

答:
As you are using mysql, you can use its spaceship operator, <=>:

```<code>$query = 'SELECT count(*) FROM table WHERE var1 <=> ? AND var2 <=> ?';
$prepare = $db_connection->prepare($query);
$prepare->execute([$var1, $var2]);
$count = $prepare->fetchColumn();
</code>```

But in general, if you need variable operators or other query parts, such a conditional query building is the only way.

A more generalized solution can be found in my article How to create a WHERE clause for PDO dynamically:

```<code>// always initialize a variable before use!
$conditions = [];
$parameters = [];

// conditional statements
if (!empty($_GET['name']))
{
    // here we are using LIKE with wildcard search
    // use it ONLY if really need it
    $conditions[] = 'name LIKE ?';
    $parameters[] = '%'.$_GET['name']."%";
}
if (!empty($_GET['sex']))
{
    // here we are using equality
    $conditions[] = 'sex = ?';
    $parameters[] = $_GET['sex'];
}
if (!empty($_GET['car']))
{
    // here we are using not equality
    $conditions[] = 'car != ?';
    $parameters[] = $_GET['car'];
}
// the main query
$sql = "SELECT * FROM users";
// a smart code to add all conditions, if any
if ($conditions)
{
    $sql .= " WHERE ".implode(" AND ", $conditions);
}
// the usual prepare/execute/fetch routine
$stmt = $pdo->prepare($sql);
$stmt->execute($parameters);
$data = $stmt->fetchAll();
</code>```

so in these conditions above whatever logic could be implemented, including operator change or anything.

Body:
Is there any standard or best way in PHP PDO database class to change the operator from "=" to "IS" when I don't know if the value I'm going to pass is NULL or not.  Here is an example of what I mean.

I have two variables.  I want a count of the results that match.  Sometimes one or both of the variables can be NULL.  But MySQL requires a different operator to find NULL (IS NULL).

I'm currently just creating another variable for the operator and when I build the query I inject it in as so:

  // First create a variable "=" or "is" depending on whether var1 and var2 are NULL or not
  if($var1 == NULL) $var1_operator = "IS";
  else $var1_operator = "=";
  if($var2 == NULL) $var2_operator = "IS";
  else $var2_operator = "=";

  // Build the query
  $query = 'SELECT count(*) as count FROM table
  WHERE var1 '.$var1_operator.' :var1 AND var2 '.$var2_operator.' :var2';

  //  Conduct the query
  $prepare = $db_connection->prepare($query);
  $prepare->bindValue(':var1', $var1, PDO::PARAM_STR);
  $prepare->bindValue(':var2', $var2, PDO::PARAM_STR);
  $prepare->execute();
  $results = $prepare->fetch();

Is there another way to do this?  This works to bindValue using PARAM_STR even when the value is NULL and not really a string.  The query returns the correct value count.  Just not sure if there is better practice for doing it.

Body:
As you are using mysql, you can use its spaceship operator, <=>:

$query = 'SELECT count(*) FROM table WHERE var1 <=> ? AND var2 <=> ?';
$prepare = $db_connection->prepare($query);
$prepare->execute([$var1, $var2]);
$count = $prepare->fetchColumn();

But in general, if you need variable operators or other query parts, such a conditional query building is the only way.

A more generalized solution can be found in my article How to create a WHERE clause for PDO dynamically:

// always initialize a variable before use!
$conditions = [];
$parameters = [];

// conditional statements
if (!empty($_GET['name']))
{
    // here we are using LIKE with wildcard search
    // use it ONLY if really need it
    $conditions[] = 'name LIKE ?';
    $parameters[] = '%'.$_GET['name']."%";
}
if (!empty($_GET['sex']))
{
    // here we are using equality
    $conditions[] = 'sex = ?';
    $parameters[] = $_GET['sex'];
}
if (!empty($_GET['car']))
{
    // here we are using not equality
    $conditions[] = 'car != ?';
    $parameters[] = $_GET['car'];
}
// the main query
$sql = "SELECT * FROM users";
// a smart code to add all conditions, if any
if ($conditions)
{
    $sql .= " WHERE ".implode(" AND ", $conditions);
}
// the usual prepare/execute/fetch routine
$stmt = $pdo->prepare($sql);
$stmt->execute($parameters);
$data = $stmt->fetchAll();

so in these conditions above whatever logic could be implemented, including operator change or anything.


问:
Change font family of object using its id
I need to change my font family of specific object using its id

Any suggestions how I do it?

```<code><script>
    var day = new Date();
    var today = day.getDate();
    var lys = today * 16;
    var heode = 505 - lys;

    if (today == 24){
    document.getElementById("chistmas").innerHTML ="Merry Christmas"
    }
    else {
        let remainingdays = 24 - today;
        document.getElementById("chistmas").innerHTML = "there are " + remainingdays + " days until christmas"
    }
    document.getElementsByClassName("light")[0].style.height=heode+"px"
</script>
</code>```

答:
If you know the selector will only match one class:

```<code>document.getElementsByClassName("className")[0].style.fontFamily = "New Font Family";
</code>```

If you need to modify multiple elements then you need to loop over the result of document.getElementsByClassName("className")

Body:
If you know the selector will only match one class:

document.getElementsByClassName("className")[0].style.fontFamily = "New Font Family";

If you need to modify multiple elements then you need to loop over the result of document.getElementsByClassName("className")


问:
how to set local time in project irrespective of server location
I have my project based in India and my hosting server located somewhere that is at a difference of -5:30 HRs from Indian time.

So my time being stored in database is coming as based on there timings. How can I rectify this in PHP so that the time actually gets stored on India.

I tried using date_default_timezone_set('Asia/Kolkata');

but still the time gets stored with a difference of -30mins to -45mins. What could be possible code fort his so that the time sets exactly according to Indian timings. Any advice will be very helpful.

答:
If you want to store the current date/time on your database and use the timezone you have. Try to use now() function.

Reference Link: https://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html#function_now


问:
C# Get Path/Filename by Handle (hWnd) 32 and 64bit
I got the following code to get path/filename by handle:

```<code>    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern int GetWindowThreadProcessId(IntPtr handle, out uint processId);

    public static string GetProcessPath(IntPtr hwnd)
    {
        uint pid = 0;
        GetWindowThreadProcessId(hwnd, out pid);
        Process proc = Process.GetProcessById((int)pid);
        return proc.MainModule.FileName.ToString();
    }
</code>```

it works perfect in 32 bit but I get error in 64bit > "Only part of the ReadProcessMemory or WriteProcessMemory request was completed."
the project is compiled as x86 (platform target x86).

How can I fix it?

~Thanks Ron

答: I'm not aware of a known problem with this, it smells environmental.  The error is very low level, probably the wow64 emulation layer.  I can only suggest you punt and use a different way to get the same info.  You can use WMI, Win32_Process class.  Run a select query on ProcessId, the ExecutablePath property gives you what you are looking for.  Use the WMI Code Creator utility to experiment, it auto-generates the C# code you need.  The odds are however not zero that this will fail the same way.</p>

Body:
I got the following code to get path/filename by handle:

    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern int GetWindowThreadProcessId(IntPtr handle, out uint processId);

    public static string GetProcessPath(IntPtr hwnd)
    {
        uint pid = 0;
        GetWindowThreadProcessId(hwnd, out pid);
        Process proc = Process.GetProcessById((int)pid);
        return proc.MainModule.FileName.ToString();
    }

it works perfect in 32 bit but I get error in 64bit > "Only part of the ReadProcessMemory or WriteProcessMemory request was completed."
the project is compiled as x86 (platform target x86).

How can I fix it?

~Thanks Ron


问:
How to readlines without having the \n at the end? (python)
As I was finishing off a game I made, I made a save button that saves to a file. When the game opens, it will then read the file and save those lines as variables. I do so, but then I see that it needs to be an integer, so I use int(). But then it does not work, because the variable is "0\n" instead of "0". I have checked many other questions, but they do not ask or answer the same question.

So I am wondering, is there a way to readlines() without the \n at the end? Or is there a way that I can backspace the variable automatically? Here is my code:

```<code>import tkinter as tk
from PIL import Image, ImageTk

# --- functions ---
def eggvalue_change():
    global eggvalue, eggvalueupgrade, money, eggz
    if money > int(round(eggvalueupgrade)):
        eggz -= eggvalueupgrade / eggvalue
        eggvalue+=0.2
        eggvalueupgrade += int(round(eggvalueupgrade + (eggvalueupgrade / 7)))
def moar_eggz():
    global eggzps, chookz
    chookz += 1
def saving():
    savedfile.write(money)
    savedfile.write(eggvalueupgrade)
    savedfile.write(eggzps)
    savedfile.write(chookz)
    savedfile.write(eggvalue)
    savedfile.write(eggz)
def main_loop():
    global eggz, eggzps, money
    eggzps = chookz / 100.0
    money = eggz * eggvalue

    try:
        openbutton2.config( text="Egg Value: " + str(eggvalue) + " --> " + str(eggvalue+0.2) + " ($" + str(eggvalueupgrade) + ")", command=eggvalue_change)
        label2.config(text="Money: $" + str(int(round(money))), font=("Terminal", 50), borderwidth=5, relief="ridge", bg="black", foreground="white",pady=10, padx=498)
        if eggzps >= 10:
            label1.config(text="| Chickens: " + str(chookz)+" | Eggs: " + str(int(round(eggz)))+" | Eggs Per Second: " + str(int(round(eggzps)))+" | Egg Value: $" + str(eggvalue) + " |", font=("Terminal", 20), borderwidth=4, relief="ridge", bg="black", foreground="red",pady=10, padx=498)
        elif eggzps < 10:
            label1.config(text="| Chickens: " + str(chookz)+" | Eggs: " + str(int(round(eggz)))+" | Eggs Per Second: " + str(eggzps)+" | Egg Value: $" + str(eggvalue)+ " |", font=("Terminal", 20), borderwidth=4, relief="ridge", bg="black", foreground="red",pady=10, padx=498)
        if money < int(round(eggvalueupgrade)):
            openbutton2.config(fg="gray")
        elif money > int(round(eggvalueupgrade)):
            openbutton2.config(fg="white")
    except Exception as e:
        print(e) # display exception to see problem
    root.after(20, main_loop)
def update_eggz():
    global eggz
    try:
        eggz += eggzps
    except Exception as e:
        print(e) # display exception to see problem

    # repeat it after 1000ms
    root.after(1000, update_eggz)

# --- main ---

root = tk.Tk()
root.title("Chicken Clicker")

savedfile = open("savedata\\mainsave.txt", "a+")
savedlines = savedfile.readlines()
print savedlines

if savedlines == []:
    eggz = 0
    eggvalue = 0.2
    chookz = 0
    eggzps = 0.0
    eggvalueupgrade = 100
    money = eggz * eggvalue

eggz = int(savedlines[0])
eggvalue = int(savedlines[1])
chookz = int(savedlines[2])
eggzps = int(savedlines[3])
eggvalueupgrade = int(savedlines[4])
money = int(savedlines[5])

savedfile.close()

# empty labels - `update_labels` will add text

label2 = tk.Label(root)
label1 = tk.Label(root)

label2.pack()
label1.pack()

chickencnv = Image.open("img\\1.png")
chicken = ImageTk.PhotoImage(chickencnv)
openbutton3 =tk.Button(root, bg="black", fg="white", font=("Terminal", 13), command=saving)
openbutton2= tk.Button(root, bg="black", fg="gray", font=("Terminal", 15))
openbutton1= tk.Button(root, image=chicken, width=500, height=500, command=moar_eggz, bg="black")

openbutton1.pack()
openbutton2.pack()
openbutton3.pack()

# run it first time at once
update_eggz()
main_loop()

root.mainloop()
</code>```

If there is no answer, I am fine with you commenting or answering that.

答:
First of all, your code have logical bug.

```<code>if savedlines == []:
    eggz = 0
    eggvalue = 0.2
    chookz = 0
    eggzps = 0.0
    eggvalueupgrade = 100
    money = eggz * eggvalue

eggz = int(savedlines[0])
eggvalue = int(savedlines[1])
chookz = int(savedlines[2])
eggzps = int(savedlines[3])
eggvalueupgrade = int(savedlines[4])
money = int(savedlines[5])
</code>```

You check wheter savedlines is empty list and set some values accordingly. But, if this is true, following lines will fail with IndexError, since your list is empty. You need to change this to:

```<code>if savedlines == []:
    eggz = 0
    eggvalue = 0.2
    chookz = 0
    eggzps = 0.0
    eggvalueupgrade = 100
    money = eggz * eggvalue
else:
    eggz = int(savedlines[0])
    eggvalue = int(savedlines[1])
    chookz = int(savedlines[2])
    eggzps = int(savedlines[3])
    eggvalueupgrade = int(savedlines[4])
    money = int(savedlines[5])
</code>```

Now, to address the question. After the line:

```<code>savedlines = savedfile.readlines()
</code>```

You should add following line which will strip \n from the end of the lines:

```<code>savedlines = [line.rstrip("\n") for line in savedlines]
</code>```

Body:
As I was finishing off a game I made, I made a save button that saves to a file. When the game opens, it will then read the file and save those lines as variables. I do so, but then I see that it needs to be an integer, so I use int(). But then it does not work, because the variable is "0\n" instead of "0". I have checked many other questions, but they do not ask or answer the same question.

So I am wondering, is there a way to readlines() without the \n at the end? Or is there a way that I can backspace the variable automatically? Here is my code:

import tkinter as tk
from PIL import Image, ImageTk

# --- functions ---
def eggvalue_change():
    global eggvalue, eggvalueupgrade, money, eggz
    if money > int(round(eggvalueupgrade)):
        eggz -= eggvalueupgrade / eggvalue
        eggvalue+=0.2
        eggvalueupgrade += int(round(eggvalueupgrade + (eggvalueupgrade / 7)))
def moar_eggz():
    global eggzps, chookz
    chookz += 1
def saving():
    savedfile.write(money)
    savedfile.write(eggvalueupgrade)
    savedfile.write(eggzps)
    savedfile.write(chookz)
    savedfile.write(eggvalue)
    savedfile.write(eggz)
def main_loop():
    global eggz, eggzps, money
    eggzps = chookz / 100.0
    money = eggz * eggvalue

    try:
        openbutton2.config( text="Egg Value: " + str(eggvalue) + " --> " + str(eggvalue+0.2) + " ($" + str(eggvalueupgrade) + ")", command=eggvalue_change)
        label2.config(text="Money: $" + str(int(round(money))), font=("Terminal", 50), borderwidth=5, relief="ridge", bg="black", foreground="white",pady=10, padx=498)
        if eggzps >= 10:
            label1.config(text="| Chickens: " + str(chookz)+" | Eggs: " + str(int(round(eggz)))+" | Eggs Per Second: " + str(int(round(eggzps)))+" | Egg Value: $" + str(eggvalue) + " |", font=("Terminal", 20), borderwidth=4, relief="ridge", bg="black", foreground="red",pady=10, padx=498)
        elif eggzps < 10:
            label1.config(text="| Chickens: " + str(chookz)+" | Eggs: " + str(int(round(eggz)))+" | Eggs Per Second: " + str(eggzps)+" | Egg Value: $" + str(eggvalue)+ " |", font=("Terminal", 20), borderwidth=4, relief="ridge", bg="black", foreground="red",pady=10, padx=498)
        if money < int(round(eggvalueupgrade)):
            openbutton2.config(fg="gray")
        elif money > int(round(eggvalueupgrade)):
            openbutton2.config(fg="white")
    except Exception as e:
        print(e) # display exception to see problem
    root.after(20, main_loop)
def update_eggz():
    global eggz
    try:
        eggz += eggzps
    except Exception as e:
        print(e) # display exception to see problem

    # repeat it after 1000ms
    root.after(1000, update_eggz)

# --- main ---

root = tk.Tk()
root.title("Chicken Clicker")

savedfile = open("savedata\\mainsave.txt", "a+")
savedlines = savedfile.readlines()
print savedlines

if savedlines == []:
    eggz = 0
    eggvalue = 0.2
    chookz = 0
    eggzps = 0.0
    eggvalueupgrade = 100
    money = eggz * eggvalue

eggz = int(savedlines[0])
eggvalue = int(savedlines[1])
chookz = int(savedlines[2])
eggzps = int(savedlines[3])
eggvalueupgrade = int(savedlines[4])
money = int(savedlines[5])

savedfile.close()

# empty labels - `update_labels` will add text

label2 = tk.Label(root)
label1 = tk.Label(root)

label2.pack()
label1.pack()

chickencnv = Image.open("img\\1.png")
chicken = ImageTk.PhotoImage(chickencnv)
openbutton3 =tk.Button(root, bg="black", fg="white", font=("Terminal", 13), command=saving)
openbutton2= tk.Button(root, bg="black", fg="gray", font=("Terminal", 15))
openbutton1= tk.Button(root, image=chicken, width=500, height=500, command=moar_eggz, bg="black")

openbutton1.pack()
openbutton2.pack()
openbutton3.pack()

# run it first time at once
update_eggz()
main_loop()

root.mainloop()

If there is no answer, I am fine with you commenting or answering that.

Body:
First of all, your code have logical bug.

if savedlines == []:
    eggz = 0
    eggvalue = 0.2
    chookz = 0
    eggzps = 0.0
    eggvalueupgrade = 100
    money = eggz * eggvalue

eggz = int(savedlines[0])
eggvalue = int(savedlines[1])
chookz = int(savedlines[2])
eggzps = int(savedlines[3])
eggvalueupgrade = int(savedlines[4])
money = int(savedlines[5])

You check wheter savedlines is empty list and set some values accordingly. But, if this is true, following lines will fail with IndexError, since your list is empty. You need to change this to:

if savedlines == []:
    eggz = 0
    eggvalue = 0.2
    chookz = 0
    eggzps = 0.0
    eggvalueupgrade = 100
    money = eggz * eggvalue
else:
    eggz = int(savedlines[0])
    eggvalue = int(savedlines[1])
    chookz = int(savedlines[2])
    eggzps = int(savedlines[3])
    eggvalueupgrade = int(savedlines[4])
    money = int(savedlines[5])

Now, to address the question. After the line:

savedlines = savedfile.readlines()

You should add following line which will strip \n from the end of the lines:

savedlines = [line.rstrip("\n") for line in savedlines]


问:
Set the first Record Value of LINQ
I have a DBSet which is db.Company and it contains 3 records like

id name is_active

```<code>1 company1 1
2 company2 1
3 company3 1
</code>```

My Created class to transfer the records:

```<code>public class CompanyFinal
    {
        public int id { get; set; }
        public string name { get; set; }
        public string selected { get; set; }
    }
</code>```

My LINQ looks like this:

```<code>(from h in db.Company where h.is_active == 1 select new CompanyFinal { id = h.id, name = h.name, selected = "false" }).ToList();
</code>```

No doubt this LINQ is working but i need to make the first record to be selected="true" which is the company 1 while doing it in LINQ.

How could i do that? Is it possible?

Thanks in advance

答:
Since you're making a list, I think that computational the fasted method, which is also the best maintainable (understood by others) would be to just assign the first element:

(Using method syntax, showing an alternative select)

```<code>var resultingList = db.Company
    .Where(company => company.is_active == 1)
    .Select(company => new CompanyFinal()
    {
        id = company.id,
        name = company.name,
        selected = "false",
    })
    .ToList();
if (resultingList.Any())
   resultingList[0].selected = true;
</code>```

If you are not sure whether you want to convert it to a list, for instance because you want to concatenate other Linq functions after it, consider using this overload of Enumerable.Select

```<code>var result = db.Company
    .Where(company => company.is_active == 1)
    .Select( (company, index) => new CompanyFinal()
    {
        id = company.id,
        name = company.name,
        selected = (index == 0) ? "true" : "false",
    });
</code>```

By the way, consider changing your CompanyFinal class such that selected is a bool instead of a string, that would make your code less error prone. For instance, after construction Selected is neither "true" nor "false". Users are able to give it a value like "TRUE" or String.Empty

If your class has users that really need a string property selected instead of a Boolean property consider keeping a get property for it:

```<code>public class CompanyFinal
{
    public int id { get; set; }
    public string name { get; set; }
    public bool Selected {get; set;}

    // for old user compatability:
    public string selected
    {
        get { return this.Selected ? "true" : "false"; }
    }
}
</code>```

The following will go wrong:

```<code>if (companyFinals[0].selected == "True") ...
</code>```

versus:

```<code> if (companyFinals[0].Selected)
</code>```

Title: Set the first Record Value of LINQ

Body:
I have a DBSet which is db.Company and it contains 3 records like

id name is_active

1 company1 1
2 company2 1
3 company3 1

My Created class to transfer the records:

public class CompanyFinal
    {
        public int id { get; set; }
        public string name { get; set; }
        public string selected { get; set; }
    }

My LINQ looks like this:

(from h in db.Company where h.is_active == 1 select new CompanyFinal { id = h.id, name = h.name, selected = "false" }).ToList();

No doubt this LINQ is working but i need to make the first record to be selected="true" which is the company 1 while doing it in LINQ.

How could i do that? Is it possible?

Thanks in advance

Body:
Since you're making a list, I think that computational the fasted method, which is also the best maintainable (understood by others) would be to just assign the first element:

(Using method syntax, showing an alternative select)

var resultingList = db.Company
    .Where(company => company.is_active == 1)
    .Select(company => new CompanyFinal()
    {
        id = company.id,
        name = company.name,
        selected = "false",
    })
    .ToList();
if (resultingList.Any())
   resultingList[0].selected = true;

If you are not sure whether you want to convert it to a list, for instance because you want to concatenate other Linq functions after it, consider using this overload of Enumerable.Select

var result = db.Company
    .Where(company => company.is_active == 1)
    .Select( (company, index) => new CompanyFinal()
    {
        id = company.id,
        name = company.name,
        selected = (index == 0) ? "true" : "false",
    });

By the way, consider changing your CompanyFinal class such that selected is a bool instead of a string, that would make your code less error prone. For instance, after construction Selected is neither "true" nor "false". Users are able to give it a value like "TRUE" or String.Empty

If your class has users that really need a string property selected instead of a Boolean property consider keeping a get property for it:

public class CompanyFinal
{
    public int id { get; set; }
    public string name { get; set; }
    public bool Selected {get; set;}

    // for old user compatability:
    public string selected
    {
        get { return this.Selected ? "true" : "false"; }
    }
}

The following will go wrong:

if (companyFinals[0].selected == "True") ...

versus:

 if (companyFinals[0].Selected)


问:
How to create AMI from VHD in AWS S3 storage
I want to create AMI instance on EC2, where my data sitting on the AWS S3 in VHD/VMDK format.
Could you please help me in how to convert VHD/VMDK to AMI through amazon SDK APIS,
and how to transfer data from AWS S3 to AMI  through amazon SDK API's</p>

答: You should use AWS VM Import/Export. You can find the steps (via CLI) in here and the API is ImportImage.</p>