问:
Using Redux-Form for search filters, how can I "reset" and re-submit the form?

Update: Here is an example Pen

https://codepen.io/anon/pen/vwzGYY?editors=0011

Preface

Based on my research, it seems like I need a completely different approach. Maybe you can suggest one?

Context

I'm using a Redux-Form (technically an older version, but the API's
in question seem really stable. We can burn that bridge when we get there.) to set some "filters" for a sort of search results list.

In particular, since I want the pages to be link-able, I'm also setting the form content in the URL query params, via React-Router, or initially setting it on page load via similar mechanism.

The only field so far is "organization_name", a text field, used to set the query param value, and trigger an API request for /endpoint?name={some_name}.

E.g.,

<Field
  name="organization_name"
  component="input"
  type="text"
  placeholder="Organization Name"
  value={value}
/>
```

<p>I've tried several things, but here's a recent shot: </p>

<p>I'm grabbing <code>reset</code>, <code>change</code>, and other things from default props. I'm passing in a <code>handleSubmit</code> as required. </p>

<p><code>handleSubmit</code> works correctly, to do some state updating, set/push the URL query params with React Router, and then make a new API call/update display of new results! Woot! </p>

<h2>What I want / expect</h2>

<p>In the long run, I would like a "reset filters" button that sets all filter values back to defaults (e.g., set the "name" value to empty string), and <em>re-submits</em> the form (thus triggering handleSubmit). </p>

<p>What I first tried to implement was a button, as such: </p>

<pre class="lang-html prettyprint-override"><code><button
  name="reset_filters_button"
  type="button"
  onClick={resetAndSubmit}
  disabled={pristine || submitting}
  >
    Clear Search
</button>
</code>```

Where resetAndSubmit is defined on the form container as such:

```<code>const resetAndSubmit = event => {
  reset();
  handleSubmit();
};
</code>```

What actually happens... (submit takes precedence over dispatched events?)

Using the Chrome dev tools debugger, I can clearly see that the reset method is called, and returns it's dispatch(...)'d event. However, the form and state values are not updated before handleSubmit() runs and submits the form.

I think this might have to do with the submit event taking priority?

I have also tried something janky, like importing change (default prop for the container) and defining the reset button thus:

<button
  name="reset_filters_button"
  type="button"
  onClick={() => {
    change('organization_name', '');
    methodThatDispatchesSubmitAction();
  }}
  disabled={pristine || submitting}
>
  Clear Search
</button>
```

<p>Which (if I remove <code>methodThatDispatchesSubmitAction()</code>) works correctly to set the field value back to blank, making the form technically "pristine" again as well. </p>

<p><code>methodThatDispatchesSubmitAction()</code> (if it's not obvious) is bound on the parent via <code>dispatchToProps</code>, and passed in to the form container, where it uses the "remote submit" suggestion, e.g, </p>

```// organization_list_filter == name of the Redux-Form to submit.
dispatch(submit('organization_list_filter'));
```

TL;DR and final question:

How does one properly reset a form and submit its' default/empty values?

Every time I dispatch or directly call Redux Form 'submit', it ends up submitting the form before clearing values from state, or the UI. I have walked through this with a debugger and it's not skipping my call to reset or change. It's like an async/race issue, but I admit I am out of my league in this particular case for sure.

Am I just Straight Up Doing It Wrong?

答:
It is most definitely a race condition issue (or since we aren't actually dealing with threads, an order of events issue).

The reason using a methodThatDispatchesSubmitAction works when your current example does not, is because a dispatched action has the benefit of reading data directly from the redux store. Your example is not reading from the redux store, it's reading from a property that is passed in. Yes, this property comes from the redux store, but the problem you are seeing is that it hasn't been updated in your component yet.

Bear with me as this next piece is not going to be entirely accurate but it should suffice to explain what you are seeing.

```<code>Submit is clicked
    -> Reset action is dispatched
       -> Reducer receives action and returns updated state
    -> Handle submit is fired using values prop (old state data still)
Component is updated with new props from redux state
</code>```

As you can see, the order of events don't allow for an updated state to be given to the property until our click code has finished running. If you've ever watched a video on the JS Event Loop (I highly recommend it), you'll know that our onClick handle will run in full before any other async operations (or sync operations that come after our click) have a chance to run.

There are good reasons why Components aren't given updated props right away but the primary one is performance. You can see that this order is in fact the problem by wrapping the handleSubmit in an async event that fires immediately (it doesn't actually fire immediately, all other sync/async operations queued before it will finish).

```<code>const resetAndSubmit = (event) => {
  reset();
  setImmediate(() => handleSubmit());
}
</code>```

This changes the order of events as follows:

```<code>Submit is clicked
    -> Reset action is dispatched
       -> Reducer receives action and returns updated state
    -> Handle submit is queued on the event loop (not run yet)
Component is updated with new props from redux state
Event loop reaches queued code and runs is
    -> Handle submit is fired using values prop (new state data)
</code>```

Hopefully, this helps you understand why the problem is occurring. As for solutions to fix it. Obviously, you can queue the handle submit as I've shown above. Another option would the one you've described as using a dispatch to perform the submit. A third option would be to use something a bit heavier like redux-thunk or redux-sagas that tie the resetAndSubmit action into a single dispatch. Although honestly, this is the same as option two, just reduced into a single dispatch. Option four, don't use redux for all your data. Obviously, this fourth option comes with trade-offs but my point being, just because you are using redux in a project doesn't mean every single piece of data needs to be in redux. Though it completely defeats the purpose of redux-forms.

I should also add, you are not alone in being confused by this. When you introduce redux, it messes with how you traditionally think about working with code. Normally you think, I do A then B. But with redux, you do A, wait for A's changes to make it through the system, and then you do B. That's where Sagas or Thunks can be nice. You move more logic to the store to act on the dispatch rather than wait for it to all make its way back down to a component via props.

Body:
Update: Here is an example Pen

https://codepen.io/anon/pen/vwzGYY?editors=0011

Preface

Based on my research, it seems like I need a completely different approach. Maybe you can suggest one?

Context

I'm using a Redux-Form (technically an older version, but the API's
in question seem really stable. We can burn that bridge when we get there.) to set some "filters" for a sort of search results list.

In particular, since I want the pages to be link-able, I'm also setting the form content in the URL query params, via React-Router, or initially setting it on page load via similar mechanism.

The only field so far is "organization_name", a text field, used to set the query param value, and trigger an API request for /endpoint?name={some_name}.

E.g.,

<Field
  name="organization_name"
  component="input"
  type="text"
  placeholder="Organization Name"
  value={value}
/>

I've tried several things, but here's a recent shot:

I'm grabbing reset, change, and other things from default props. I'm passing in a handleSubmit as required.

handleSubmit works correctly, to do some state updating, set/push the URL query params with React Router, and then make a new API call/update display of new results! Woot!

What I want / expect

In the long run, I would like a "reset filters" button that sets all filter values back to defaults (e.g., set the "name" value to empty string), and re-submits the form (thus triggering handleSubmit).

What I first tried to implement was a button, as such:

<button
  name="reset_filters_button"
  type="button"
  onClick={resetAndSubmit}
  disabled={pristine || submitting}
  >
    Clear Search
</button>

Where resetAndSubmit is defined on the form container as such:

const resetAndSubmit = event => {
  reset();
  handleSubmit();
};

What actually happens... (submit takes precedence over dispatched events?)

Using the Chrome dev tools debugger, I can clearly see that the reset method is called, and returns it's dispatch(...)'d event. However, the form and state values are not updated before handleSubmit() runs and submits the form.

I think this might have to do with the submit event taking priority?

I have also tried something janky, like importing change (default prop for the container) and defining the reset button thus:

<button
  name="reset_filters_button"
  type="button"
  onClick={() => {
    change('organization_name', '');
    methodThatDispatchesSubmitAction();
  }}
  disabled={pristine || submitting}
>
  Clear Search
</button>

Which (if I remove methodThatDispatchesSubmitAction()) works correctly to set the field value back to blank, making the form technically "pristine" again as well.

methodThatDispatchesSubmitAction() (if it's not obvious) is bound on the parent via dispatchToProps, and passed in to the form container, where it uses the "remote submit" suggestion, e.g,

// organization_list_filter == name of the Redux-Form to submit.
dispatch(submit('organization_list_filter'));

TL;DR and final question:

How does one properly reset a form and submit its' default/empty values?

Every time I dispatch or directly call Redux Form 'submit', it ends up submitting the form before clearing values from state, or the UI. I have walked through this with a debugger and it's not skipping my call to reset or change. It's like an async/race issue, but I admit I am out of my league in this particular case for sure.

Am I just Straight Up Doing It Wrong?

Body:
It is most definitely a race condition issue (or since we aren't actually dealing with threads, an order of events issue).

The reason using a methodThatDispatchesSubmitAction works when your current example does not, is because a dispatched action has the benefit of reading data directly from the redux store. Your example is not reading from the redux store, it's reading from a property that is passed in. Yes, this property comes from the redux store, but the problem you are seeing is that it hasn't been updated in your component yet.

Bear with me as this next piece is not going to be entirely accurate but it should suffice to explain what you are seeing.

Submit is clicked
    -> Reset action is dispatched
       -> Reducer receives action and returns updated state
    -> Handle submit is fired using values prop (old state data still)
Component is updated with new props from redux state

As you can see, the order of events don't allow for an updated state to be given to the property until our click code has finished running. If you've ever watched a video on the JS Event Loop (I highly recommend it), you'll know that our onClick handle will run in full before any other async operations (or sync operations that come after our click) have a chance to run.

There are good reasons why Components aren't given updated props right away but the primary one is performance. You can see that this order is in fact the problem by wrapping the handleSubmit in an async event that fires immediately (it doesn't actually fire immediately, all other sync/async operations queued before it will finish).

const resetAndSubmit = (event) => {
  reset();
  setImmediate(() => handleSubmit());
}

This changes the order of events as follows:

Submit is clicked
    -> Reset action is dispatched
       -> Reducer receives action and returns updated state
    -> Handle submit is queued on the event loop (not run yet)
Component is updated with new props from redux state
Event loop reaches queued code and runs is
    -> Handle submit is fired using values prop (new state data)

Hopefully, this helps you understand why the problem is occurring. As for solutions to fix it. Obviously, you can queue the handle submit as I've shown above. Another option would the one you've described as using a dispatch to perform the submit. A third option would be to use something a bit heavier like redux-thunk or redux-sagas that tie the resetAndSubmit action into a single dispatch. Although honestly, this is the same as option two, just reduced into a single dispatch. Option four, don't use redux for all your data. Obviously, this fourth option comes with trade-offs but my point being, just because you are using redux in a project doesn't mean every single piece of data needs to be in redux. Though it completely defeats the purpose of redux-forms.

I should also add, you are not alone in being confused by this. When you introduce redux, it messes with how you traditionally think about working with code. Normally you think, I do A then B. But with redux, you do A, wait for A's changes to make it through the system, and then you do B. That's where Sagas or Thunks can be nice. You move more logic to the store to act on the dispatch rather than wait for it to all make its way back down to a component via props.


来源: stackexchange

问:
speed up mysql query with multiple subqueries
I'm wondering if there's a way to speed up a mysql query which is ordered by multiple subqueries.

On a music related site users can like different things like artists, songs, albums etc. These "likes" are all stored in the same table. Now I want to show a list of artists ordered by the number of "likes" by the users friends and all users. I want to show all artists, also those who have no likes at all.

I have the following query:

```<code>SELECT `artists`.*,

    // friend likes
    (SELECT COUNT(*)
     FROM `likes`
     WHERE like_type = 'artist'
     AND like_id = artists.id
     AND user_id IN (1,2,3,4, etc) // ids of friends
     GROUP BY like_id
    ) AS `friend_likes`,

    // all likes
    (SELECT COUNT(*)
     FROM `likes`
     WHERE like_type = 'artist'
     AND like_id = artists.id
     GROUP BY like_id
    ) AS `all_likes`

FROM artists
ORDER BY
    friend_likes DESC,
    all_likes DESC,
    artists.name ASC
</code>```

The query takes ± 1.5 seconds on an artist table with 2000 rows. I'm afraid that this takes longer and longer as the table gets bigger and bigger. I tried using JOINS by can't seem to get this working because the subqueries contain WHERE statements.

Any ideas in the right direction would be greatly appreciated!

答:
try rolling up into a query using inline IF() and go through the table/join ONCE</p>

```<code>SELECT STRAIGHT_JOIN
  artists.*
  , LikeCounts.AllCount
  , LikeCounts.FriendLikeCount
FROM
  (SELECT
    like_id
    , count(*) AllCount
    , sum( If( User_id in ( 1, 2, 3, 4 ), 1, 0 ) as FriendLikeCount
  FROM
    friend_likes
  WHERE
    like_type = 'artist'
  GROUP BY
    like_id ) LikeCounts
JOIN artists ON LikeCounts.like_id = artists.id
ORDER BY
  LikeCounts.FriendLikeCount DESC
  , LikeCounts.AllCount DESC
  , artists.name ASC
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm wondering if there's a way to speed up a mysql query which is ordered by multiple subqueries.

On a music related site users can like different things like artists, songs, albums etc. These "likes" are all stored in the same table. Now I want to show a list of artists ordered by the number of "likes" by the users friends and all users. I want to show all artists, also those who have no likes at all.

I have the following query:

SELECT `artists`.*,

    // friend likes
    (SELECT COUNT(*)
     FROM `likes`
     WHERE like_type = 'artist'
     AND like_id = artists.id
     AND user_id IN (1,2,3,4, etc) // ids of friends
     GROUP BY like_id
    ) AS `friend_likes`,

    // all likes
    (SELECT COUNT(*)
     FROM `likes`
     WHERE like_type = 'artist'
     AND like_id = artists.id
     GROUP BY like_id
    ) AS `all_likes`

FROM artists
ORDER BY
    friend_likes DESC,
    all_likes DESC,
    artists.name ASC

The query takes ± 1.5 seconds on an artist table with 2000 rows. I'm afraid that this takes longer and longer as the table gets bigger and bigger. I tried using JOINS by can't seem to get this working because the subqueries contain WHERE statements.

Any ideas in the right direction would be greatly appreciated!

Body:
try rolling up into a query using inline IF() and go through the table/join ONCE

SELECT STRAIGHT_JOIN
  artists.*
  , LikeCounts.AllCount
  , LikeCounts.FriendLikeCount
FROM
  (SELECT
    like_id
    , count(*) AllCount
    , sum( If( User_id in ( 1, 2, 3, 4 ), 1, 0 ) as FriendLikeCount
  FROM
    friend_likes
  WHERE
    like_type = 'artist'
  GROUP BY
    like_id ) LikeCounts
JOIN artists ON LikeCounts.like_id = artists.id
ORDER BY
  LikeCounts.FriendLikeCount DESC
  , LikeCounts.AllCount DESC
  , artists.name ASC


问:
React Native SectionList Rendering Incorreclty
I'm attempting to bind an array of objects to a SelectionList, it appears to be binding but its rendering each character as an individual list item rather than a single item.

Here is my code:

r: GetRecipesResponse is a list of objects that I am then converting to an array, this is visible to the left of the above, the rendering issue is apparent on the right.

```<code>interface States {
    response: GetRecipesResponse;
    globalItems: any[];
    isModalVisible: boolean;
    selectedItem: any;
    selectedItemUnit: any;
}

export class MatrixScreen extends BaseNetworkScreen<GetRecipesResponse, Props, States> {

    itemWidth: number = 100;
    itemMargin: number = 3;
    selectedItemsArray: any[];

    constructor(props: Props) {
        super(props);

        this.selectedItemsArray = [];

        this.state = {
            isLoading: false,
            response: null,
            globalItems: this.selectedItemsArray,
            isModalVisible: false,
            selectedItem: null,
            selectedItemUnit: null
        };
    }
}

renderSelectLists(r: GetRecipesResponse): any {

    var arr = [];
    for (var key in r.data.recipe) {
      arr.push(r.data.recipe[key].name);
    }

    let sections = []
    for (const key in this.state.globalItems) {
        if (this.state.globalItems.hasOwnProperty(key)) {
            sections.push({
                data: this.state.globalItems[key],
                key: key,
                unit: this.state.selectedItemUnit
            })
        }
    }

    return (
        <View style={{ flex: 1, flexDirection: 'row' }}>
            <View style={styles.addContainer}>

                <Text>Press To Add Item</Text>

                <SectionList

                    sections={[{ data: arr }]}
                    renderItem={({ item }) => <Text style={styles.SectionListItemS} onPress={this.loadMatrixModal.bind(this, item)}> {item} </Text>}
                    keyExtractor={(item, index: any) => index}
                />
            </View>
            <View style={styles.removeContainer}>
                <Text>Press To Remove Item</Text>
                <SectionList
                    sections={sections}
                    renderItem={({ item, index }) => <Text style={styles.SectionListItemS} onPress={this.removeSectionListItem.bind(this, index)}> {item} </Text>}
                    keyExtractor={(item, index: any) => item}
                />
            </View>
        </View>
    );
}
</code>```

Logging out "sections" to the console after it's been defined returns the following:

Update:

If I add renderItem={({ item, index }) => <Text style={styles.SectionListItemS} onPress={this.removeSectionListItem.bind(this, index)}> {console.log(item)} {item} </Text>}

Interestingly it outputs the following to the console,

答:
So I had to build my object like so:

```<code>var data = {name: item, qty: unit};
var builtObject = {data: [data]};
</code>```

Then I can push the object to an array and set the state of globalItems to the array.

ContentLicense: CC BY-SA 4.0

Body:
I'm attempting to bind an array of objects to a SelectionList, it appears to be binding but its rendering each character as an individual list item rather than a single item.

Here is my code:

r: GetRecipesResponse is a list of objects that I am then converting to an array, this is visible to the left of the above, the rendering issue is apparent on the right.

interface States {
    response: GetRecipesResponse;
    globalItems: any[];
    isModalVisible: boolean;
    selectedItem: any;
    selectedItemUnit: any;
}

export class MatrixScreen extends BaseNetworkScreen<GetRecipesResponse, Props, States> {

    itemWidth: number = 100;
    itemMargin: number = 3;
    selectedItemsArray: any[];

    constructor(props: Props) {
        super(props);

        this.selectedItemsArray = [];

        this.state = {
            isLoading: false,
            response: null,
            globalItems: this.selectedItemsArray,
            isModalVisible: false,
            selectedItem: null,
            selectedItemUnit: null
        };
    }
}

renderSelectLists(r: GetRecipesResponse): any {

    var arr = [];
    for (var key in r.data.recipe) {
      arr.push(r.data.recipe[key].name);
    }

    let sections = []
    for (const key in this.state.globalItems) {
        if (this.state.globalItems.hasOwnProperty(key)) {
            sections.push({
                data: this.state.globalItems[key],
                key: key,
                unit: this.state.selectedItemUnit
            })
        }
    }

    return (
        <View style={{ flex: 1, flexDirection: 'row' }}>
            <View style={styles.addContainer}>

                <Text>Press To Add Item</Text>

                <SectionList

                    sections={[{ data: arr }]}
                    renderItem={({ item }) => <Text style={styles.SectionListItemS} onPress={this.loadMatrixModal.bind(this, item)}> {item} </Text>}
                    keyExtractor={(item, index: any) => index}
                />
            </View>
            <View style={styles.removeContainer}>
                <Text>Press To Remove Item</Text>
                <SectionList
                    sections={sections}
                    renderItem={({ item, index }) => <Text style={styles.SectionListItemS} onPress={this.removeSectionListItem.bind(this, index)}> {item} </Text>}
                    keyExtractor={(item, index: any) => item}
                />
            </View>
        </View>
    );
}

Logging out "sections" to the console after it's been defined returns the following:

Update:

If I add renderItem={({ item, index }) => <Text style={styles.SectionListItemS} onPress={this.removeSectionListItem.bind(this, index)}> {console.log(item)} {item} </Text>}

Interestingly it outputs the following to the console,

Body:
So I had to build my object like so:

var data = {name: item, qty: unit};
var builtObject = {data: [data]};

Then I can push the object to an array and set the state of globalItems to the array.


问:
view.findViewById() returns null in one function but works fine in other one
I am trying to get a TextView object using view.findViewById() in a function which is called when a button is clicked. In the onClickButton() null is returned whereas in other function setDefaultValues() it works fine.

Activity1.java

```<code>public class Activity1 extends AppCompatActivity {
    private final Double TIP = 10.0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_1);
        setDefaultValues();
    }

    private void setDefaultValues() {
        TextView tipView = findViewById(R.id.tipView);
       tipView.setText(getString(R.string.main_msg_tip,Double.toString(TIP)));
    }

    public void onClickToggleButton(View view){
        TextView tipView = view.findViewById(R.id.tipView);
        switch (view.getId()) {
            case (R.id.toggleButtonBad):
                tipView.setText(getString(R.string.main_msg_tip, Double.toString(BAD)));
                break;
        }
}

</code>```

When testing the app the following error message was shown:

```<code>java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object referenceat com.example.chandan.learning.Activity1.onClickToggleButton
</code>```

Edit : The activity_1.xml file does contain the TextView with tipView id so the theory that element is not present in the XML file is out of the window.

答:
You are trying to find view from inside clicked view (Ex. Button), while the "tipView" is in main view container. So update your method "onClickToggleButton" as below:</p>

```<code>    public void onClickToggleButton(View view) {
        TextView tipView = findViewById(R.id.tipView);
        switch (view.getId()) {
            case (R.id.toggleButtonBad):
             tipView.setText(getString(R.string.main_msg_tip, Double.toString(BAD)));
            break;
        }
    }
</code>```

Body:
I am trying to get a TextView object using view.findViewById() in a function which is called when a button is clicked. In the onClickButton() null is returned whereas in other function setDefaultValues() it works fine.

Activity1.java

public class Activity1 extends AppCompatActivity {
    private final Double TIP = 10.0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_1);
        setDefaultValues();
    }

    private void setDefaultValues() {
        TextView tipView = findViewById(R.id.tipView);
       tipView.setText(getString(R.string.main_msg_tip,Double.toString(TIP)));
    }

    public void onClickToggleButton(View view){
        TextView tipView = view.findViewById(R.id.tipView);
        switch (view.getId()) {
            case (R.id.toggleButtonBad):
                tipView.setText(getString(R.string.main_msg_tip, Double.toString(BAD)));
                break;
        }
}

When testing the app the following error message was shown:

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object referenceat com.example.chandan.learning.Activity1.onClickToggleButton

Edit : The activity_1.xml file does contain the TextView with tipView id so the theory that element is not present in the XML file is out of the window.

Body:
You are trying to find view from inside clicked view (Ex. Button), while the "tipView" is in main view container. So update your method "onClickToggleButton" as below:

    public void onClickToggleButton(View view) {
        TextView tipView = findViewById(R.id.tipView);
        switch (view.getId()) {
            case (R.id.toggleButtonBad):
             tipView.setText(getString(R.string.main_msg_tip, Double.toString(BAD)));
            break;
        }
    }


问:
Error when scheduling python script: fcron[12036]: Couldn't exec '/usr/bin/sendmail': No such file or directory
I have a python script that I would like to schedule with fcrontab. This script sends emails based on the status field set in one of the columns. The script executes in the expected manner when I invoke the following:

```<code>python2 mail.py
</code>```

This results in the following and expected output:

```<code>Successfully sent email...
Update sent status on EdPost...  xxxxxx
Update sent status on EdPost...  xxxxxx
Update sent status on EdPost...  xxxxxx
Update sent status on EdPost...  xxxxxx
Update sent status on EdPost...  xxxxxx
Update sent status on EdPost...  xxxxxx
Update sent status on EdPost...  xxxxxx
Update sent status on EdPost...  xxxxxx
</code>```

However when I try to run this script as a cron job, I end up with the mentioned error.

Cron:

```<code>0 15 * * * /home/x/JobParse/mail.py >> /home/x/JobParse/mailer.log
</code>```

Error:

```<code>fcron[23191]: Couldn't exec '/usr/bin/sendmail': No such file or directory
</code>```

I have another python script scheduled in a similar fashion that runs just fine with the #!/usr/bin/env python2 shebang. That script does not use the smtplib library though.

The script I'm trying to schedule is below:

mail.py

#!/usr/bin/python2
import smtplib
from db import get_records,update_sent_status
import traceback
import datetime
configs = [line.rstrip('\n') for line in open('configs')]
usr = configs[0]
pwd = configs[1]
rcvr = configs[2]
receivers = [rcvr]
date = datetime.datetime.now().date()
posts = []
edpost_tbl_rows= ""
appli_tbl_rows= ""

ed_posts = get_records(0) # * non-appli and  unsent
ed_posts_ids = [row[0] for row in ed_posts]
ed_posts_sent = get_records(1) # post_id

uniq_appli = get_records(2) # unique unsent appli
uniq_appli_ids = [row[0] for row in uniq_appli]

all_appli_sent = [row[0] for row in get_records(4)] # all app_id sent
all_appli_unsent = [row[0] for row in get_records(5)] # all app_id unsent

# No jobs to send so exit
if len(all_appli_unsent) == 0 and len(ed_posts) == 0:
    print "Exit: No new unique posts.."
    exit()

# Transform db data into html table row format
for row in ed_posts:
    edpost_tbl_rows += \
            "
"\
            +str(row[0])\
            +"	"\
            +row[4]\
            +"	"\
            +row[5]\
            +"	"\
            +row[6]\
            +"
"

# Transform applitrack posts into html table
for row in uniq_appli:
    # check if sent before - app_id not unique on edpost
    if row[3] not in all_appli_sent:
        print "New unique & unsent applitrack post... ",row[3]
        appli_tbl_rows += \
            "
"\
            +str(row[0])\
            +"	"\
            +str(row[3])\
            +"	"\
            +row[4]\
            +"	"\
            +row[5]\
            +"	"\
            +row[6]\
            +"
"
    else:
        print "Skipping applitrack post... ",row[3]

message = """From: JobUpdates <{usr}>
To: xxxx <{rcvr}>
MIME-Version: 1.0
Content-type: text/html; charset=utf-8
Subject: New Job Postings: {date}

Check out these postings you may have not have seen yet :)

Searched: words

Jobs With Applitrack

        EdPost ID
        AppliTrack ID
        Description
        Post DT
        Exp DT

    {appli_tbl_rows}

Jobs Without Applitrack

        EdPost ID
        Description
        Post DT
        Exp DT

    {edpost_tbl_rows}

""".format(usr=usr,rcvr=rcvr,date=date,edpost_tbl_rows=edpost_tbl_rows,appli_tbl_rows=appli_tbl_rows)

try:
    smtpObj = smtplib.SMTP('localhost',1025)
    smtpObj.login(usr,pwd)
    smtpObj.sendmail(usr, rcvr, message)
    print "Successfully sent email... "
    for post_id in ed_posts_ids:
        print "Update sent status on EdPost... ",post_id
        update_sent_status(post_id)

    for app_id in all_appli_unsent:
        print "Update sent status on Appli... ",app_id
        update_sent_status(app_id,1)

except smtplib.SMTPException:
    print "ERROR: unable to send email... "
    print traceback.format_exc()
```

I've tried this with the #!/usr/bin/env python2 shebang as well to no avail.

答:
I was able to resolve the issue without installing sendmail. This was done by moving the Python path into the script at the start of it as follows:

import os
abspath = os.path.abspath(__file__)
dname = os.path.dirname(abspath)
os.chdir(dname)
```

See Pitto's answer here.

I'm guessing updating the path variable for cron's environment from crontab itself would be a viable solution as well.

Body:
I have a python script that I would like to schedule with fcrontab. This script sends emails based on the status field set in one of the columns. The script executes in the expected manner when I invoke the following:

python2 mail.py

This results in the following and expected output:

Successfully sent email...
Update sent status on EdPost...  xxxxxx
Update sent status on EdPost...  xxxxxx
Update sent status on EdPost...  xxxxxx
Update sent status on EdPost...  xxxxxx
Update sent status on EdPost...  xxxxxx
Update sent status on EdPost...  xxxxxx
Update sent status on EdPost...  xxxxxx
Update sent status on EdPost...  xxxxxx

However when I try to run this script as a cron job, I end up with the mentioned error.

Cron:

0 15 * * * /home/x/JobParse/mail.py >> /home/x/JobParse/mailer.log

Error:

fcron[23191]: Couldn't exec '/usr/bin/sendmail': No such file or directory

I have another python script scheduled in a similar fashion that runs just fine with the #!/usr/bin/env python2 shebang. That script does not use the smtplib library though.

The script I'm trying to schedule is below:

mail.py

#!/usr/bin/python2
import smtplib
from db import get_records,update_sent_status
import traceback
import datetime
configs = [line.rstrip('\n') for line in open('configs')]
usr = configs[0]
pwd = configs[1]
rcvr = configs[2]
receivers = [rcvr]
date = datetime.datetime.now().date()
posts = []
edpost_tbl_rows= ""
appli_tbl_rows= ""

ed_posts = get_records(0) # * non-appli and  unsent
ed_posts_ids = [row[0] for row in ed_posts]
ed_posts_sent = get_records(1) # post_id

uniq_appli = get_records(2) # unique unsent appli
uniq_appli_ids = [row[0] for row in uniq_appli]

all_appli_sent = [row[0] for row in get_records(4)] # all app_id sent
all_appli_unsent = [row[0] for row in get_records(5)] # all app_id unsent

# No jobs to send so exit
if len(all_appli_unsent) == 0 and len(ed_posts) == 0:
    print "Exit: No new unique posts.."
    exit()

# Transform db data into html table row format
for row in ed_posts:
    edpost_tbl_rows += \
            "
"\
            +str(row[0])\
            +"	"\
            +row[4]\
            +"	"\
            +row[5]\
            +"	"\
            +row[6]\
            +"
"

# Transform applitrack posts into html table
for row in uniq_appli:
    # check if sent before - app_id not unique on edpost
    if row[3] not in all_appli_sent:
        print "New unique & unsent applitrack post... ",row[3]
        appli_tbl_rows += \
            "
"\
            +str(row[0])\
            +"	"\
            +str(row[3])\
            +"	"\
            +row[4]\
            +"	"\
            +row[5]\
            +"	"\
            +row[6]\
            +"
"
    else:
        print "Skipping applitrack post... ",row[3]

message = """From: JobUpdates <{usr}>
To: xxxx <{rcvr}>
MIME-Version: 1.0
Content-type: text/html; charset=utf-8
Subject: New Job Postings: {date}

Check out these postings you may have not have seen yet :)

Searched: words

Jobs With Applitrack

        EdPost ID
        AppliTrack ID
        Description
        Post DT
        Exp DT

    {appli_tbl_rows}

Jobs Without Applitrack

        EdPost ID
        Description
        Post DT
        Exp DT

    {edpost_tbl_rows}

""".format(usr=usr,rcvr=rcvr,date=date,edpost_tbl_rows=edpost_tbl_rows,appli_tbl_rows=appli_tbl_rows)

try:
    smtpObj = smtplib.SMTP('localhost',1025)
    smtpObj.login(usr,pwd)
    smtpObj.sendmail(usr, rcvr, message)
    print "Successfully sent email... "
    for post_id in ed_posts_ids:
        print "Update sent status on EdPost... ",post_id
        update_sent_status(post_id)

    for app_id in all_appli_unsent:
        print "Update sent status on Appli... ",app_id
        update_sent_status(app_id,1)

except smtplib.SMTPException:
    print "ERROR: unable to send email... "
    print traceback.format_exc()

I've tried this with the #!/usr/bin/env python2 shebang as well to no avail.

Body:
I was able to resolve the issue without installing sendmail. This was done by moving the Python path into the script at the start of it as follows:

import os
abspath = os.path.abspath(__file__)
dname = os.path.dirname(abspath)
os.chdir(dname)

See Pitto's answer here.

I'm guessing updating the path variable for cron's environment from crontab itself would be a viable solution as well.


问:
confd configuration with HashiCorp Vault KV v2
I'm creating a Vault Dev Server with sudo vault server -dev and putting a simple KV v2 secret with:

```<code>vault kv put secret/database url=db.example.com
</code>```

I wish confd pick that value whenever value is changed in KV store in Vault. But I'm getting the error:

```<code>FATAL template: env.tmpl:2:9: executing "env.tmpl" at <getv "database/url">: error calling getv: key does not exist: database/url
</code>```

When I run:

```<code>sudo confd --onetime --log-level debug --backend vault --auth-type token --auth-token s.ossadqwsssssssafadsd --node http://127.0.0.1:8200 -prefix='/secret'
</code>```

My /etc/confd/templates/env.tmpl is:

```<code>[myconfig]
url = {{ getv "database/url" }}
</code>```

and /etc/confd/conf.d/myconfig.toml is

```<code>[template]
src = "env.tmpl"
dest = "env.conf"
keys = [
   "secret/database"
]
</code>```

Any help would be appreciated.

答: KV v2 has data in a /data prefix. You need to change your path to be getv "data/database/url" in the config template or change prefix to /secret/data in the flag.

Body:
I'm creating a Vault Dev Server with sudo vault server -dev and putting a simple KV v2 secret with:

vault kv put secret/database url=db.example.com

I wish confd pick that value whenever value is changed in KV store in Vault. But I'm getting the error:

FATAL template: env.tmpl:2:9: executing "env.tmpl" at <getv "database/url">: error calling getv: key does not exist: database/url

When I run:

sudo confd --onetime --log-level debug --backend vault --auth-type token --auth-token s.ossadqwsssssssafadsd --node http://127.0.0.1:8200 -prefix='/secret'

My /etc/confd/templates/env.tmpl is:

[myconfig]
url = {{ getv "database/url" }}

and /etc/confd/conf.d/myconfig.toml is

[template]
src = "env.tmpl"
dest = "env.conf"
keys = [
   "secret/database"
]

Any help would be appreciated.


问:
php large xml parse it with paging
I have a large XML file with 22000 records that I have to import in my DB.

I am looking how to parse the xml with paging, meaning

```<code>parse.php?start=0; //this script get the 0-500 firt records of file
parse.php?start=500 //this script get the 500-1000 records of file
</code>```

This way I can bypass memory problems.

My problem is how to point at record 500 when load the xml file

My code is simple

```<code>$data=simplexml_load_file($xmlFile);

foreach ($data->product as $product) {
   foreach($product->children() as $section) {
       addToDB($section);
   }
}
</code>```

The code above works fine for 1000-2000 records but I want to modify as mentioned to work with large XMLs

答:
SimpleXML is a DOM parser which means that it must load the whole document into memory to be able to build an in-memory representation of the whole XML dataset. Chunking the data does not work with this type of parser.

To load XML datasets that large you must switch to so called pull parser*s such as the XMLReader for example or the very low-level XML Parser extension. Pull parsers work by traversing the XML document element by element and allow you, the developer, to react according to the currently parsed element. That reduces memory footprint because only small fragments of the data have to be loaded into memory at one time. Using pull parsers is a little bit uncommon and not as intuitive as the familiar DOM parsers (DOM and SimpleXML).

Title: php large xml parse it with paging

Body:
I have a large XML file with 22000 records that I have to import in my DB.

I am looking how to parse the xml with paging, meaning

parse.php?start=0; //this script get the 0-500 firt records of file
parse.php?start=500 //this script get the 500-1000 records of file

This way I can bypass memory problems.

My problem is how to point at record 500 when load the xml file

My code is simple

$data=simplexml_load_file($xmlFile);

foreach ($data->product as $product) {
   foreach($product->children() as $section) {
       addToDB($section);
   }
}

The code above works fine for 1000-2000 records but I want to modify as mentioned to work with large XMLs


问:
How to make optional parameter value in ActionResult method in Asp.Net MVC?
When user click the button, it will redirect to another controller action method with or without parameter value

```<code><button type="button" onclick="location.href='http://localhost/ProjectName/Customer/Details'" >Go to Details</button>

<button type="button" onclick="location.href='http://localhost/ProjectName/Customer/Details?name=xxx'" >View Details</button>
</code>```

CustomerController

```<code>    public ActionResult Details()   // i don't know how to pass optional parameter value
    {
        // some code ...
        return View();
    }
</code>```

答:
Or you may use this Initializing parameter with empty value,

`

```<code> public ActionResult Details(string Name = string.Empty)
  {
    return View();
  }
</code>```

`

Body:
When user click the button, it will redirect to another controller action method with or without parameter value

<button type="button" onclick="location.href='http://localhost/ProjectName/Customer/Details'" >Go to Details</button>

<button type="button" onclick="location.href='http://localhost/ProjectName/Customer/Details?name=xxx'" >View Details</button>

CustomerController

    public ActionResult Details()   // i don't know how to pass optional parameter value
    {
        // some code ...
        return View();
    }

Body:
Or you may use this Initializing parameter with empty value,

`

 public ActionResult Details(string Name = string.Empty)
  {
    return View();
  }

`


问:
React Router - How to redirect user if logged in?
I'm using react-router-dom to manage my routes:

```<code>const Routes = () => {
  return (
    <BrowserRouter>
      <div>
        <Route path="/" component={Navbar} />
        <Switch>
          <Route exact path="/" component={Main} />
          <Route path="/signin" component={SignIn} />
          <Route path="/signup" component={SignUp} />
          <PrivateRoute path="/dashboard" component={DashboardRoutes} />
          <Route path="*" component={() => <h1>Page not found</h1>} />
        </Switch>
      </div>
      <div>
        <Route path="/" component={Footer} />
      </div>
    </BrowserRouter>
  );
};
</code>```

I want only to render the Navbar if the user is not authenticated. If the user is authenticated, I don't want to render the Navbar and I want to redirect him to dashboard.

I tried with inline conditioning:

```<code>const Routes = () => {
  return (
    <BrowserRouter>
      <div>
        {!isAuthenticated() && <Route path="/" component={Navbar} />}
        <Switch>
          <Route exact path="/" component={Main} />
          <Route path="/signin" component={SignIn} />
          <Route path="/signup" component={SignUp} />
          <PrivateRoute path="/dashboard" component={DashboardRoutes} />
          <Route path="*" component={() => <h1>Page not found</h1>} />
        </Switch>
      </div>
      <div>
        <Route path="/" component={Footer} />
      </div>
    </BrowserRouter>
  );
};
</code>```

However, when I'm not logged in, and then sign in, the Navbar persists, because it was rendered when isAuthenticated was false.

How can I achieve this?

Thanks!

PS: I already have a isAuthenticated function.

答:
A better way to handle this would be in your Navbar component itself.

In your Navbar component, setup componentDidMount() to check if the user isAuthenticated and just redirect them.

```<code>componentDidMount(){
    if(isAuthenticated()){
        this.props.history.push("/dashboard")
    }
}
</code>```

And in the render(), just use the isAuthenticated() method you set up to determine if you should return anything.

```<code>render(){
   if(!isAuthenticated()){
     return(
        ...your navbar markup
     ) else {
        return null
     }
   }
}
</code>```

Body:
I'm using react-router-dom to manage my routes:

const Routes = () => {
  return (
    <BrowserRouter>

        <Route path="/" component={Navbar} />
        <Switch>
          <Route exact path="/" component={Main} />
          <Route path="/signin" component={SignIn} />
          <Route path="/signup" component={SignUp} />
          <PrivateRoute path="/dashboard" component={DashboardRoutes} />
          <Route path="*" component={() =>
Page not found
} />
        </Switch>

        <Route path="/" component={Footer} />

    </BrowserRouter>
  );
};

I want only to render the Navbar if the user is not authenticated. If the user is authenticated, I don't want to render the Navbar and I want to redirect him to dashboard.

I tried with inline conditioning:

const Routes = () => {
  return (
    <BrowserRouter>

        {!isAuthenticated() && <Route path="/" component={Navbar} />}
        <Switch>
          <Route exact path="/" component={Main} />
          <Route path="/signin" component={SignIn} />
          <Route path="/signup" component={SignUp} />
          <PrivateRoute path="/dashboard" component={DashboardRoutes} />
          <Route path="*" component={() =>
Page not found
} />
        </Switch>

        <Route path="/" component={Footer} />

    </BrowserRouter>
  );
};

However, when I'm not logged in, and then sign in, the Navbar persists, because it was rendered when isAuthenticated was false.

How can I achieve this?

Thanks!

PS: I already have a isAuthenticated function.

Body:
A better way to handle this would be in your Navbar component itself.

In your Navbar component, setup componentDidMount() to check if the user isAuthenticated and just redirect them.

componentDidMount(){
    if(isAuthenticated()){
        this.props.history.push("/dashboard")
    }
}

And in the render(), just use the isAuthenticated() method you set up to determine if you should return anything.

render(){
   if(!isAuthenticated()){
     return(
        ...your navbar markup
     ) else {
        return null
     }
   }
}


问:
Constraint on a related table
I have 2 tables (ItemType and Item). ItemType has a boolean hasSize, and the Item table has a size column.

I'd like to enforce that size is only set if the hasSize boolean = true.

I've seen solutions discussed which use triggers for validation. However, that doesn't provide the same robustness as a constraint.

Is this a problem of non-ideal schema design, or are there appropriate solutions for this?

答:
Check constraints cannot refer to other tables in the database & a trigger is a valid strategy around this limitation. I don't think your schema design is bad. Certain types of items are sizeable, and that information belong in the item_type table.

Here is an alternate solution not using triggers, where I impose a check constraint on an UPDATABLE VIEW to prevent data modification in the underlying tables, using the WITH CHECK OPTION modifier. note that this will only validate if data inserted or updated through the view. You must grant appropriate permissions so that the application role cannot modify the item table directly, but can through the UPDATABLE VIEW

Here's a self-contained script with sample data & examples insert that fails & insert that succeeds

```<code>-- set up dummy `item_type` table
CREATE TABLE item_type (
id int primary key generated by default as identity,
has_size bool,
name text not null unique
);
INSERT INTO item_type
  (has_size, name)
VALUES
  (true, 'sizable type')
, (false, 'unisize');

-- set up dummy `item` table
CREATE TABLE item (
id int primary key generated by default as identity,
type_id int references item_type(id),
name text NOT NULL,
size text
);

INSERT INTO item
  (type_id, name, size)
VALUES
  (1, 'worlds best dad tee shirt', 'M')
, (2, 'usb key', NULL);

-- create updatable check view.
CREATE VIEW item_view AS
SELECT item.*
FROM item
WHERE EXISTS (
SELECT
FROM item_type
WHERE item.type_id = item_type.id
  AND (item.size IS NOT NULL) = item_type.has_size
)
WITH CASCADED CHECK OPTION;
--    ^^^
-- i could have alternately used local
-- instead of cascaded
</code>```

This insert will fail

```<code>INSERT INTO item_view
  (type_id, name, size)
VALUES
  (2, 'dad socks', 'M');
</code>```

It generates the following error:

```<code>ERROR:  new row violates check option for view "item_view"
DETAIL:  Failing row contains (3, 2, dad socks, M).
</code>```

This insert will succeed

```<code>INSERT INTO item_view
  (type_id, name, size)
VALUES
  (2, 'dad socks', NULL);
</code>```

SELECT * FROM item returns the following result as expected

```<code> id | type_id |           name            | size
----+---------+---------------------------+------
  1 |       1 | worlds best dad tee shirt | M
  2 |       2 | usb key                   |
  4 |       2 | dad socks                 |
</code>```

Title: Constraint on a related table

Body:
Check constraints cannot refer to other tables in the database & a trigger is a valid strategy around this limitation. I don't think your schema design is bad. Certain types of items are sizeable, and that information belong in the item_type table.

Here is an alternate solution not using triggers, where I impose a check constraint on an UPDATABLE VIEW to prevent data modification in the underlying tables, using the WITH CHECK OPTION modifier. note that this will only validate if data inserted or updated through the view. You must grant appropriate permissions so that the application role cannot modify the item table directly, but can through the UPDATABLE VIEW

Here's a self-contained script with sample data & examples insert that fails & insert that succeeds

-- set up dummy `item_type` table
CREATE TABLE item_type (
id int primary key generated by default as identity,
has_size bool,
name text not null unique
);
INSERT INTO item_type
  (has_size, name)
VALUES
  (true, 'sizable type')
, (false, 'unisize');

-- set up dummy `item` table
CREATE TABLE item (
id int primary key generated by default as identity,
type_id int references item_type(id),
name text NOT NULL,
size text
);

INSERT INTO item
  (type_id, name, size)
VALUES
  (1, 'worlds best dad tee shirt', 'M')
, (2, 'usb key', NULL);

-- create updatable check view.
CREATE VIEW item_view AS
SELECT item.*
FROM item
WHERE EXISTS (
SELECT
FROM item_type
WHERE item.type_id = item_type.id
  AND (item.size IS NOT NULL) = item_type.has_size
)
WITH CASCADED CHECK OPTION;
--    ^^^
-- i could have alternately used local
-- instead of cascaded

This insert will fail

INSERT INTO item_view
  (type_id, name, size)
VALUES
  (2, 'dad socks', 'M');

It generates the following error:

ERROR:  new row violates check option for view "item_view"
DETAIL:  Failing row contains (3, 2, dad socks, M).

This insert will succeed

INSERT INTO item_view
  (type_id, name, size)
VALUES
  (2, 'dad socks', NULL);

SELECT * FROM item returns the following result as expected

 id | type_id |           name            | size
----+---------+---------------------------+------
  1 |       1 | worlds best dad tee shirt | M
  2 |       2 | usb key                   |
  4 |       2 | dad socks                 |


问:
What is the meaning of "UPDATE table SET column1 = value AND column2 value WHERE condition" in SQL?
If the "," in an UPDATE statement is replaced with AND, what the meaning in SQL?

Normal Update Statement :

```<code>UPDATE table
SET column1 = value ,
    column2 = value
WHERE condition
</code>```

My question statement :

```<code>UPDATE table
SET column1 = value AND column2 = value
WHERE condition
</code>```

The affected rows seem to be different, so I want to know what my question statement mean in SQL?

Original test Data

After inserting query(from original)  : Update testing set column1 = 2 , column2 =5

Normal Update

After inserting query(from original) : Update testing set column1 = 2 AND column2 =5

My Question Statement

if I insert the query(from original) :Update testing set column1 = 2 AND  =4

the output

答:
We can see from this simple experiment...

https://www.db-fiddle.com/f/3KawkrD8QfjJu6YyfuzB7U/0

...that ...

```<code>UPDATE my_table SET c = 2 AND b = 1;
</code>```

... is interpreted as...

```<code>UPDATE my_table SET c ........ = 1;
</code>```

Body:
If the "," in an UPDATE statement is replaced with AND, what the meaning in SQL?

Normal Update Statement :

UPDATE table
SET column1 = value ,
    column2 = value
WHERE condition

My question statement :

UPDATE table
SET column1 = value AND column2 = value
WHERE condition

The affected rows seem to be different, so I want to know what my question statement mean in SQL?

Original test Data

After inserting query(from original)  : Update testing set column1 = 2 , column2 =5

Normal Update

After inserting query(from original) : Update testing set column1 = 2 AND column2 =5

My Question Statement

if I insert the query(from original) :Update testing set column1 = 2 AND  =4

the output

Body:
We can see from this simple experiment...

https://www.db-fiddle.com/f/3KawkrD8QfjJu6YyfuzB7U/0

...that ...

UPDATE my_table SET c = 2 AND b = 1;

... is interpreted as...

UPDATE my_table SET c ........ = 1;


答:
As string is nullable itself, so you can use it in parameter and it will be optional, then you will only check for null values within it. For example:

```<code>public ActionResult Details(string optionalParameter)
{
     //Check it now for value
     if(string.IsNullOrEmpty(optionalParameter))
     {
        //some code if it is empty
     }
     else
     {
        //some code if it is not empty
     }

    // some code ...
    return View();
}
</code>```

Title: How to make optional parameter value in ActionResult method in Asp.Net MVC?

Body:
As string is nullable itself, so you can use it in parameter and it will be optional, then you will only check for null values within it. For example:

public ActionResult Details(string optionalParameter)
{
     //Check it now for value
     if(string.IsNullOrEmpty(optionalParameter))
     {
        //some code if it is empty
     }
     else
     {
        //some code if it is not empty
     }

    // some code ...
    return View();
}


问:
Flex 4: VideoDisplay can play MP3 files?
Is it possible to play MP3 files using the VideoDisplay or VideoPlayer components?

Thank you.

答:
Why would you use a video component to play a sound file?  Either way, you should probably google before posting here.  This is how you do it:

```<code>var snd:Sound = new Sound(new URLRequest("smallSound.mp3"));
snd.play();
</code>```

Body:
Why would you use a video component to play a sound file?  Either way, you should probably google before posting here.  This is how you do it:

var snd:Sound = new Sound(new URLRequest("smallSound.mp3"));
snd.play();


问:
How to display every image inside an image folder in react
I have an image folder in my create-react-app project with a bunch of images. I want to display every single image in the components.

```<code>├── Components
│   ├── Icons
│   │   ├── Icon.jsx (I want to display every single icon)
│
│
├── Images
│   ├── Icons
│   │   ├── ... (over 100 SVG icons)
</code>```

In my .jsx file, I want to loop over every image/icon and display it.

Icons.jsx

```<code>import React, { Component } from 'react';
import Icons from '../../Images/Icons';

class Icons extends Component {
  render() {
    return (
      //Loop over every icon and display it
    );
  }
}
</code>```

答:
I had the same scenario where I have to pick images or SVGs from the folder and display it. Below is the process I followed :

Folder structure

```<code>  -public
   -src
     |-component
     |-images
        |-1.png
        |-2.png
        |-3.png
        .
        .
        |-some x number.png
</code>```

In component where ever you want to consume the image there, you have to do this:

```<code>export default App;
import React from 'react';
import ReactDOM from 'react-dom';
var listOfImages =[];

class App extends React.Component{
    importAll(r) {
        return r.keys().map(r);
    }
    componentWillMount() {
        listOfImages = this.importAll(require.context('./images/', false, /\.(png|jpe?g|svg)$/));
    }
    render(){
        return(
          <div>
              {
                    listOfImages.map(
                      (image, index) =>    <img key={index} src={image} alt="info"></img>
                    )
              }
          </div>
        )
    }
}
</code>```

It worked for me; Give it a try.

Body:
I have an image folder in my create-react-app project with a bunch of images. I want to display every single image in the components.

├── Components
│   ├── Icons
│   │   ├── Icon.jsx (I want to display every single icon)
│
│
├── Images
│   ├── Icons
│   │   ├── ... (over 100 SVG icons)

In my .jsx file, I want to loop over every image/icon and display it.

Icons.jsx

import React, { Component } from 'react';
import Icons from '../../Images/Icons';

class Icons extends Component {
  render() {
    return (
      //Loop over every icon and display it
    );
  }
}

Body:
I had the same scenario where I have to pick images or SVGs from the folder and display it. Below is the process I followed :

Folder structure

  -public
   -src
     |-component
     |-images
        |-1.png
        |-2.png
        |-3.png
        .
        .
        |-some x number.png

In component where ever you want to consume the image there, you have to do this:

export default App;
import React from 'react';
import ReactDOM from 'react-dom';
var listOfImages =[];

class App extends React.Component{
    importAll(r) {
        return r.keys().map(r);
    }
    componentWillMount() {
        listOfImages = this.importAll(require.context('./images/', false, /\.(png|jpe?g|svg)$/));
    }
    render(){
        return(
          <div>
              {
                    listOfImages.map(
                      (image, index) =>    <img key={index} src={image} alt="info"></img>
                    )
              }
          </div>
        )
    }
}

It worked for me; Give it a try.


问:
Reset select value to default
I have select box

```<code><select id="my_select">
    <option value="a">a</option>
    <option value="b" selected="selected">b</option>
    <option value="c">c</option>
</select>

<div id="reset">
    reset
</div>
</code>```

I have also reset button, here default (selected) value is "b", suppose I select "c" and after I need resert select box value to default, how to make this using jquery?

```<code>$("#reset").on("click", function () {
    // What do here?
});
</code>```

jsfiddle: http://jsfiddle.net/T8sCf/1/

答:
```<code><select id="my_select">
    <option value="a">a</option>
    <option value="b" selected="selected">b</option>
    <option value="c">c</option>
</select>

<div id="reset">
    reset
</div>

$("#reset").on("click", function () {
    $('#my_select').prop('selectedIndex',0);
});
</code>```

This is a simple way for your question. only one line answer.

Title: Reset select value to default

Body:
I have select box

<select id="my_select">
    <option value="a">a</option>
    <option value="b" selected="selected">b</option>
    <option value="c">c</option>
</select>

    reset

I have also reset button, here default (selected) value is "b", suppose I select "c" and after I need resert select box value to default, how to make this using jquery?

$("#reset").on("click", function () {
    // What do here?
});

jsfiddle: http://jsfiddle.net/T8sCf/1/

Body:
<select id="my_select">
    <option value="a">a</option>
    <option value="b" selected="selected">b</option>
    <option value="c">c</option>
</select>

<div id="reset">
    reset
</div>

$("#reset").on("click", function () {
    $('#my_select').prop('selectedIndex',0);
});

This is a simple way for your question. only one line answer.


问:
How to combine two layers in Keras? One with embedding, one with "other" feature
I am trying to combine an embedding layer with a numeric feature layer. I did like:

```<code>tensor_feature = Input(shape=(MAX_LENGTH, 3))
tensor_embed = Input(shape=(MAX_LENGTH, ))
tensor_embed = Embedding(len(word2index), 128)(tensor_embed)

merged_tensor = concatenate([tensor_embed, tensor_feature])
model = Bidirectional(LSTM(256, return_sequences=True))(merged_tensor)
model = Bidirectional(LSTM(128, return_sequences=True))(model)
model = TimeDistributed(Dense(len(tag2index)))(model)
model = Activation('softmax')(model)
model = Model(inputs=[tensor_embed,tensor_feature],outputs=model)
</code>```

Noted that MAX_LENGTH is 82.
Unfortunately, I got an error like this:

ValueError: Graph disconnected: cannot obtain value for tensor
  Tensor("input_2:0", shape=(?, 82), dtype=float32) at layer "input_2".
  The following previous layers were accessed without issue: []

while combining input and output. Please help.

答:
You are overwriting tensor_embed which is an input layer to embedding output and using same again as input in the model.  Change your code to

```<code>tensor_feature = Input(shape=(MAX_LENGTH, 3))
tensor_embed_feature = Input(shape=(MAX_LENGTH, ))
tensor_embed = Embedding(len(word2index), 128)(tensor_embed_feature)

merged_tensor = concatenate([tensor_embed, tensor_feature])
model = Bidirectional(LSTM(256, return_sequences=True))(merged_tensor)
model = Bidirectional(LSTM(128, return_sequences=True))(model)
model = TimeDistributed(Dense(len(tag2index)))(model)
model = Activation('softmax')(model)
model = Model(inputs=[tensor_embed_feature,tensor_feature],outputs=model)
</code>```

Body:
I am trying to combine an embedding layer with a numeric feature layer. I did like:

tensor_feature = Input(shape=(MAX_LENGTH, 3))
tensor_embed = Input(shape=(MAX_LENGTH, ))
tensor_embed = Embedding(len(word2index), 128)(tensor_embed)

merged_tensor = concatenate([tensor_embed, tensor_feature])
model = Bidirectional(LSTM(256, return_sequences=True))(merged_tensor)
model = Bidirectional(LSTM(128, return_sequences=True))(model)
model = TimeDistributed(Dense(len(tag2index)))(model)
model = Activation('softmax')(model)
model = Model(inputs=[tensor_embed,tensor_feature],outputs=model)

Noted that MAX_LENGTH is 82.
Unfortunately, I got an error like this:

ValueError: Graph disconnected: cannot obtain value for tensor
  Tensor("input_2:0", shape=(?, 82), dtype=float32) at layer "input_2".
  The following previous layers were accessed without issue: []

while combining input and output. Please help.

Body:
You are overwriting tensor_embed which is an input layer to embedding output and using same again as input in the model.  Change your code to

tensor_feature = Input(shape=(MAX_LENGTH, 3))
tensor_embed_feature = Input(shape=(MAX_LENGTH, ))
tensor_embed = Embedding(len(word2index), 128)(tensor_embed_feature)

merged_tensor = concatenate([tensor_embed, tensor_feature])
model = Bidirectional(LSTM(256, return_sequences=True))(merged_tensor)
model = Bidirectional(LSTM(128, return_sequences=True))(model)
model = TimeDistributed(Dense(len(tag2index)))(model)
model = Activation('softmax')(model)
model = Model(inputs=[tensor_embed_feature,tensor_feature],outputs=model)


问:
return data as SqlDataReader
I am working on an ASP.NET project. I have a stored procedure in SQL Server which returns a list of data to show in a chart. This stored procedure works fine. I need the return data to be a SqlDataReader object to pass into the Chart.DataBindTable.

I call the stored procedure like this:

```<code>string spName = "spFetchDetails";
DbCommand dbCommand = this.ObjDatabase.GetStoredProcCommand(spName);
this.ObjDatabase.AddInParameter(dbCommand, "@Company", DbType.Int32, Company);
this.ObjDatabase.AddInParameter(dbCommand, "@Title", DbType.String, Title);
this.ObjDatabase.AddInParameter(dbCommand, "@DateRange", DbType.String, DateRange);

DataTable dt = new DataTable();
dt = this.ObjDatabase.ExecuteDataSet(dbCommand).Tables[0];
</code>```

Here the code is returning the stored procedure result as a DataTable, I want to call ExecuteReader() method, but I am not sure how to do that.

```<code>Chart.DataBindTable(dt, "Example");
</code>```

This is the code to render the chart.

Below is how I do in another chart and it is working.

```<code>SqlCommand cmd = new SqlCommand(
  "Select ai.ItemDescription, ai.ItemRate, los.sellingprice, los.mrp from aitem ai inner join losShopItemShipmentDetail los on los.itemid = ai.itemid", con);
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();

Chart.DataBindTable(rdr, "ItemDescription");
</code>```

How do I call a stored procedure this way? or is there a way to pass the DataTable into DataBindTable function?

```<code>public void DataBindTable (System.Collections.IEnumerable dataSource, string xField);
</code>```

答:
you can call the stored procedure as below.

```<code>SqlCommand cmd = new SqlCommand("<SqlProcedureName>", con)
cmd.CommandType = CommandType.StoredProcedure;
</code>```

But in place of assigning datareader to chart control. Find another way to set the data only

Title: return data as SqlDataReader

Body:
I am working on an ASP.NET project. I have a stored procedure in SQL Server which returns a list of data to show in a chart. This stored procedure works fine. I need the return data to be a SqlDataReader object to pass into the Chart.DataBindTable.

I call the stored procedure like this:

string spName = "spFetchDetails";
DbCommand dbCommand = this.ObjDatabase.GetStoredProcCommand(spName);
this.ObjDatabase.AddInParameter(dbCommand, "@Company", DbType.Int32, Company);
this.ObjDatabase.AddInParameter(dbCommand, "@Title", DbType.String, Title);
this.ObjDatabase.AddInParameter(dbCommand, "@DateRange", DbType.String, DateRange);

DataTable dt = new DataTable();
dt = this.ObjDatabase.ExecuteDataSet(dbCommand).Tables[0];

Here the code is returning the stored procedure result as a DataTable, I want to call ExecuteReader() method, but I am not sure how to do that.

Chart.DataBindTable(dt, "Example");

This is the code to render the chart.

Below is how I do in another chart and it is working.

SqlCommand cmd = new SqlCommand(
  "Select ai.ItemDescription, ai.ItemRate, los.sellingprice, los.mrp from aitem ai inner join losShopItemShipmentDetail los on los.itemid = ai.itemid", con);
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();

Chart.DataBindTable(rdr, "ItemDescription");

How do I call a stored procedure this way? or is there a way to pass the DataTable into DataBindTable function?

public void DataBindTable (System.Collections.IEnumerable dataSource, string xField);

Body:
you can call the stored procedure as below.

SqlCommand cmd = new SqlCommand("<SqlProcedureName>", con)
cmd.CommandType = CommandType.StoredProcedure;

But in place of assigning datareader to chart control. Find another way to set the data only


问:
How to navigate back in angular2 apps?
I'm building a single page application with multiple views served by a router.

Most of the info I have read says to inject location:Location as a service, then use (click)='location.back' to go back a view.

This doesn't work for me as if you start on a certain view and click back, you end up exiting the app and going to the previous website. I also get frequent page reloads when using this as a navigation method. Is there a history API, or some other way to handle navigation in an ng2 application?

答:
On ionic 4 this worked for me:</p>

```<code>import { Location } from '@angular/common';

...
constructor(private location: Location) {}

back() {
  this.location.back();
}
...
</code>```

Title: How to navigate back in angular2 apps?

Body:
On ionic 4 this worked for me:

import { Location } from '@angular/common';

...
constructor(private location: Location) {}

back() {
  this.location.back();
}
...


问:
A non-null String must be provided to a Text widget
I'm trying to add the option for the quantity to be adjusted but I get an error saying "A non-null String must be provided to a Text widget"
How do I provide this, to this code?

```<code> trailing: Container(
        height: 60,
        width: 60,
        padding: EdgeInsets.only(left: 10),
        child: Column(
          children: <Widget>[
            new GestureDetector(child: Icon(Icons.arrow_drop_up), onTap: () {}),
            new Text(cart_prod_qty),
            new GestureDetector(child: Icon(Icons.arrow_drop_down), onTap: () {})
          ],
        ),
</code>```

答:
Just check for null and give a default

```<code>Text(cart_prod_qty!=null?cart_prod_qty:'default value'),
</code>```

You can keep it empty if you wish

```<code>Text(cart_prod_qty!=null?cart_prod_qty:''),
</code>```

Or else you can make text widget optional

```<code>cart_prod_qty!=null? Text(cart_prod_qty): Container()
</code>```

Body:
I'm trying to add the option for the quantity to be adjusted but I get an error saying "A non-null String must be provided to a Text widget"
How do I provide this, to this code?

 trailing: Container(
        height: 60,
        width: 60,
        padding: EdgeInsets.only(left: 10),
        child: Column(
          children: <Widget>[
            new GestureDetector(child: Icon(Icons.arrow_drop_up), onTap: () {}),
            new Text(cart_prod_qty),
            new GestureDetector(child: Icon(Icons.arrow_drop_down), onTap: () {})
          ],
        ),

Body:
Just check for null and give a default

Text(cart_prod_qty!=null?cart_prod_qty:'default value'),

You can keep it empty if you wish

Text(cart_prod_qty!=null?cart_prod_qty:''),

Or else you can make text widget optional

cart_prod_qty!=null? Text(cart_prod_qty): Container()


问:
Windows form UI freezing and unable to execute user action when too much data is coming in
Created a simple window form to receive and process data from serial port
also logging the data in textfile and displaying in the rich-text box.

For some reason, it is going into unresponsive state and not able to execute user action and freeze.

According to my understanding, earlier code was using two threads one UI and another one for data received event. Is this correct

But now as i am using background worker, it should create anther thread to process and append in the log and richtext box. Is this correct?

This is my first project in c# so pardon me if it is already answered somewhere else as i am unable to correlate this situation with the given answers and not able to implement them.

Is it a good idea to background worker if not then how can i solve this problem.

Thanks in advance.

Earlier the entire application was running on UI thread. Now i have tried to use background to create a new thread to store data receiving from serial port and processing inside that thread

```<code>//earlier code
void DataReceived_Event(object sender, SerialDataReceivedEventArgs e)
{
    if (Port.IsOpen)
    {
        int bytes = Port.BytesToRead;
        byte[] buffer = new byte[bytes];
        Port.Read(buffer, 0, bytes);
        receivedBytes.AddRange(buffer);
        ProcessRecievedBytes(null);
    }
}

//latest code with background worker
void DataReceived_Event(object sender, SerialDataReceivedEventArgs e)
{
    if (Port.IsOpen)
    {
        int bytes = Port.BytesToRead;
        byte[] buffer = new byte[bytes];

        Port.Read(buffer, 0, bytes);
        receivingBytes.AddRange(buffer);

        if (!essentialBgWorker.IsBusy)
        {
            receivedBytes.AddRange(receivingBytes);
            receivingBytes.Clear();
            essentialBgWorker.RunWorkerAsync();
        }
    }
 }

private void essentialBgWorker_DoWork(object sender, DoWorkEventArgs e)
{
    foreach (byte hexByte in receivedBytes)
    {
        //color = Color.Gray;
        if ((Config.Data.Serial_DisplayLevel == GLOBAL.HEX_LEVEL_NONE))
        {
            if ((hexByte == '\n') || ((hexByte >= 0x20) && (hexByte <= 0x7E)))
            {
                String tmpString = new String((char)hexByte, 1);
                //essentialBgWorker.ReportProgress(0, tmpString);
                //in here i am putting in the log file and appending in the richtext box
                PreprocessAppend(tmpString, Color.Black, false);
            }
        }
    }

    process.ProcessData(receivedBytes);//in here i am processing the data
    receivedBytes.Clear();
}

private void essentialBgWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    string str = e.UserState.ToString();
    logWriter.Write(str);
    logWriter.Flush();

    if (e.ProgressPercentage == 0)
    {
        AppendSerial(str, Color.Black, false);
    }
    else if (e.ProgressPercentage == 1)
    {
        AppendSerial(str, Color.Black, false);
    }
}

SerialTab.SerialPort.AppendSerial += delegate (string data, Color txtColor, bool newLineCheck)
{
    this.BeginInvoke((MethodInvoker)(delegate ()
    {
        if (newLineCheck && (serialTextBox.Text != "") && (serialTextBox.Text[serialTextBox.TextLength - 1] != '\r') && (serialTextBox.Text[serialTextBox.TextLength - 1] != '\n'))
        {
            data = "\n" + data;
        }

        AppendTextbox(serialTextBox, data, txtColor);
    }));
};

void AppendTextbox(RichTextBox tb, string data, Color txtColor)
{
    if (data == null)
    {
        return;
    }

    int start = tb.TextLength;
    tb.AppendText(data);
    int end = tb.TextLength;

    // Textbox may transform chars, so (end-start) != text.Length
    tb.Select(start, end - start);
    tb.SelectionColor = txtColor;

    //reset color to defaults
    tb.SelectionLength = 0;
    tb.SelectionColor = serialTextBox.ForeColor;

    //move caret to bottom of page
    ScrollToBottom(tb);

    //ensure text buffer stays below 15000 characters
    checkTextBoxLength(tb);
}

void checkTextBoxLength(RichTextBox box)
{
    //ensure text buffer in text box gets too large
    if (box.Text.Length > 15000)
    {
        box.ReadOnly = false;
        box.SelectionStart = 0;
        box.SelectionLength = box.TextLength - 10000;
        box.SelectedText = "";
        box.ReadOnly = true;
    }
}
</code>```

答:
Don't access windows controls from any thread other than the one that created them. When using a BackgroundWorker:

add the backgroundworker to the form designer

set its ReportsProgress property to true

attach an event handler to DoWork and another to ProgressChanged

in the DoWork event, do your background work such as reading from the serial port. Any time you want to update a windows control, call the backgroundworker ReportProgress() method with an object argument for the user state that contains some data you want to use in the control

I tend to use the progress int to also specify something, such as running a switch statement to chose one of several text boxes to update

The background worker will correctly ensure the ProgressChanged event is executed by the UI thread, meaning you can update controls from within it

Looking at your code, it seems you were going along these lines because I can see a commented out ReportProgress call. Show the contents of your ProgressChanged event handler. Make absolutely sure the only time you ever access any windows control (read or write any property or call any method) is in ProgressChanged, NOT DoWork

Edit/Update

Now I can see more of your code, it looks like you've embarked on a path of making it all way too complicated. I'll make another answer

Body:
Created a simple window form to receive and process data from serial port
also logging the data in textfile and displaying in the rich-text box.

For some reason, it is going into unresponsive state and not able to execute user action and freeze.

According to my understanding, earlier code was using two threads one UI and another one for data received event. Is this correct

But now as i am using background worker, it should create anther thread to process and append in the log and richtext box. Is this correct?

This is my first project in c# so pardon me if it is already answered somewhere else as i am unable to correlate this situation with the given answers and not able to implement them.

Is it a good idea to background worker if not then how can i solve this problem.

Thanks in advance.

Earlier the entire application was running on UI thread. Now i have tried to use background to create a new thread to store data receiving from serial port and processing inside that thread

//earlier code
void DataReceived_Event(object sender, SerialDataReceivedEventArgs e)
{
    if (Port.IsOpen)
    {
        int bytes = Port.BytesToRead;
        byte[] buffer = new byte[bytes];
        Port.Read(buffer, 0, bytes);
        receivedBytes.AddRange(buffer);
        ProcessRecievedBytes(null);
    }
}

//latest code with background worker
void DataReceived_Event(object sender, SerialDataReceivedEventArgs e)
{
    if (Port.IsOpen)
    {
        int bytes = Port.BytesToRead;
        byte[] buffer = new byte[bytes];

        Port.Read(buffer, 0, bytes);
        receivingBytes.AddRange(buffer);

        if (!essentialBgWorker.IsBusy)
        {
            receivedBytes.AddRange(receivingBytes);
            receivingBytes.Clear();
            essentialBgWorker.RunWorkerAsync();
        }
    }
 }

private void essentialBgWorker_DoWork(object sender, DoWorkEventArgs e)
{
    foreach (byte hexByte in receivedBytes)
    {
        //color = Color.Gray;
        if ((Config.Data.Serial_DisplayLevel == GLOBAL.HEX_LEVEL_NONE))
        {
            if ((hexByte == '\n') || ((hexByte >= 0x20) && (hexByte <= 0x7E)))
            {
                String tmpString = new String((char)hexByte, 1);
                //essentialBgWorker.ReportProgress(0, tmpString);
                //in here i am putting in the log file and appending in the richtext box
                PreprocessAppend(tmpString, Color.Black, false);
            }
        }
    }

    process.ProcessData(receivedBytes);//in here i am processing the data
    receivedBytes.Clear();
}

private void essentialBgWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    string str = e.UserState.ToString();
    logWriter.Write(str);
    logWriter.Flush();

    if (e.ProgressPercentage == 0)
    {
        AppendSerial(str, Color.Black, false);
    }
    else if (e.ProgressPercentage == 1)
    {
        AppendSerial(str, Color.Black, false);
    }
}

SerialTab.SerialPort.AppendSerial += delegate (string data, Color txtColor, bool newLineCheck)
{
    this.BeginInvoke((MethodInvoker)(delegate ()
    {
        if (newLineCheck && (serialTextBox.Text != "") && (serialTextBox.Text[serialTextBox.TextLength - 1] != '\r') && (serialTextBox.Text[serialTextBox.TextLength - 1] != '\n'))
        {
            data = "\n" + data;
        }

        AppendTextbox(serialTextBox, data, txtColor);
    }));
};

void AppendTextbox(RichTextBox tb, string data, Color txtColor)
{
    if (data == null)
    {
        return;
    }

    int start = tb.TextLength;
    tb.AppendText(data);
    int end = tb.TextLength;

    // Textbox may transform chars, so (end-start) != text.Length
    tb.Select(start, end - start);
    tb.SelectionColor = txtColor;

    //reset color to defaults
    tb.SelectionLength = 0;
    tb.SelectionColor = serialTextBox.ForeColor;

    //move caret to bottom of page
    ScrollToBottom(tb);

    //ensure text buffer stays below 15000 characters
    checkTextBoxLength(tb);
}

void checkTextBoxLength(RichTextBox box)
{
    //ensure text buffer in text box gets too large
    if (box.Text.Length > 15000)
    {
        box.ReadOnly = false;
        box.SelectionStart = 0;
        box.SelectionLength = box.TextLength - 10000;
        box.SelectedText = "";
        box.ReadOnly = true;
    }
}


问:
How to navigate from one screen to another screen
How to navigate from one Activity screen to another Activity screen? In the first screen I'm having one button if I click the button it has to move to another Activity screen.</p>

答:
You can navigate to the next screen using these code snippets:

Kotlin

```<code>startActivity(Intent(this, LoginActivity::class.java))
</code>```

Java

```<code>startActivity(new Intent(this, LoginActivity.class))
</code>```

Here's a reference: Android Developers - Starting another activity

Body:
You can navigate to the next screen using these code snippets:

Kotlin

startActivity(Intent(this, LoginActivity::class.java))

Java

startActivity(new Intent(this, LoginActivity.class))

Here's a reference: Android Developers - Starting another activity


问:
Access to IBM Weather API with PHP works, but with JS it does not work
I access to IBM Weather API in my application.

When I try to access with PHP:

```<code>$auth = base64_encode("<username>:<password>");
$context = stream_context_create([
"http" => [
    "header" => "Authorization: Basic $auth"
]]);
$homepage = file_get_contents("https://twcservice.eu-gb.mybluemix.net/api/weather/v1/geocode/49.14/15.00/forecast/daily/3day.json?language=en-US&units=m", false, $context );
echo($homepage);
</code>```

It works.

But when I try to access with Javascript:

```<code>let headers = new Headers();
headers.append("Content-Type", "application/json");
headers.append("Authorization", "Basic " + btoa("<username>" + ":" + "<password>"));
fetch("https://twcservice.eu-gb.mybluemix.net/api/weather/v1/geocode/"+lat.toFixed(2)+"/"+lng.toFixed(2)+"/forecast/daily/3day.json?language=en-US&units=m", {headers: headers})
.then(function(response) {
    console.log(response);
    return response.json();
})
.then(function(json) {
    for(let i = 0; i <= 3; i++) {
        console.log(json['forecasts'][i]['dow']+" - "+json['forecasts'][i]['narrative']);
    }
});
</code>```

It gives me the CORS error message.

```<code>Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://twcservice.eu-gb.mybluemix.net/api/weather/v1/geocode/49.14/15.00/forecast/daily/3day.json?language=en-US&units=m. (Reason: CORS header ‘Access-Control-Allow-Origin’ does not match ‘https://*.ibm.com, https://*.ibmcloud.com’).
</code>```

I don't understand why.

Thanks for help!

If the IBM Weather API is scared about stealing its content, why does it work with PHP?

I don't get it.

答:
@John Doe

This is CORS issue. Servers can be configured to not allow browsers to make requests from different domains. The Mozilla document about CORS is a great read if you're unfamiliar with the topic.

Note that you'll only hit CORS errors if you're doing something through a browser. So attempting to redo the same API call in a terminal with curl will often still work. Making things even more confusing!

Was your PHP script run locally, through a terminal?

If you're tinkering around, there are proxy services that bypass CORS, like CORS-anywhere. Try hitting https://cors-anywhere.herokuapp.com/https://twcservice.eu-gb.mybluemix.net instead of the API you currently have. Note that this isn't meant for anything production worthy. Just trying to help you get a little farther along.

Body:
I access to IBM Weather API in my application.

When I try to access with PHP:

$auth = base64_encode("<username>:<password>");
$context = stream_context_create([
"http" => [
    "header" => "Authorization: Basic $auth"
]]);
$homepage = file_get_contents("https://twcservice.eu-gb.mybluemix.net/api/weather/v1/geocode/49.14/15.00/forecast/daily/3day.json?language=en-US&units=m", false, $context );
echo($homepage);

It works.

But when I try to access with Javascript:

let headers = new Headers();
headers.append("Content-Type", "application/json");
headers.append("Authorization", "Basic " + btoa("<username>" + ":" + "<password>"));
fetch("https://twcservice.eu-gb.mybluemix.net/api/weather/v1/geocode/"+lat.toFixed(2)+"/"+lng.toFixed(2)+"/forecast/daily/3day.json?language=en-US&units=m", {headers: headers})
.then(function(response) {
    console.log(response);
    return response.json();
})
.then(function(json) {
    for(let i = 0; i <= 3; i++) {
        console.log(json['forecasts'][i]['dow']+" - "+json['forecasts'][i]['narrative']);
    }
});

It gives me the CORS error message.

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://twcservice.eu-gb.mybluemix.net/api/weather/v1/geocode/49.14/15.00/forecast/daily/3day.json?language=en-US&units=m. (Reason: CORS header ‘Access-Control-Allow-Origin’ does not match ‘https://*.ibm.com, https://*.ibmcloud.com’).

I don't understand why.

Thanks for help!

If the IBM Weather API is scared about stealing its content, why does it work with PHP?

I don't get it.


问:
sort list of custom objects based on enum in kotlin
I have a list of custom object and an Enum class. I have to sort the list based on the enum properties. For example:

My list:

```<code>val list = listOf(Item(1,Severity.CRITICAL), Item(3, Severity.LOW), Item(2, Severity.SEVERE))
</code>```

My enum class:

```<code>enum class Severity{
 CRITICAL, SEVERE, MODERATE, LOW
}
</code>```

My sorted list should be:

```<code>listOf(Item(1,Severity.CRITICAL), Item(2, Severity.SEVERE), Item(3, Severity.LOW))
</code>```

Ordering is done as per the order in enum class. How can I achieve this?

答:
Since enum is a comparable,an object of enum can be sorted by extracting the enum value
from the object, and use compareBy

```<code>val sortedList = list.sortedWith(compareBy { it.severity })
</code>```

Edit:
If the ordering of the item is a 'natural' part of it, consider implements Comparable interface
So it will be like

```<code>data class Item(val index: Int, val severity: Severity) : Comparable<Item> {
    override fun compareTo(other: Item): Int {
        return this.severity.compareTo(other.severity)
    }

}
val sortedList= list.sorted()
</code>```

Body:
I have a list of custom object and an Enum class. I have to sort the list based on the enum properties. For example:

My list:

val list = listOf(Item(1,Severity.CRITICAL), Item(3, Severity.LOW), Item(2, Severity.SEVERE))

My enum class:

enum class Severity{
 CRITICAL, SEVERE, MODERATE, LOW
}

My sorted list should be:

listOf(Item(1,Severity.CRITICAL), Item(2, Severity.SEVERE), Item(3, Severity.LOW))

Ordering is done as per the order in enum class. How can I achieve this?

Body:
Since enum is a comparable,an object of enum can be sorted by extracting the enum value
from the object, and use compareBy

val sortedList = list.sortedWith(compareBy { it.severity })

Edit:
If the ordering of the item is a 'natural' part of it, consider implements Comparable interface
So it will be like

data class Item(val index: Int, val severity: Severity) : Comparable<Item> {
    override fun compareTo(other: Item): Int {
        return this.severity.compareTo(other.severity)
    }

}
val sortedList= list.sorted()


问:
Why doesn't the values stored in my json file change?
I have buttons that are connected to keys in my json file. Using kivy's Clock module I check the value connected to the button and changes its colors. When the button turns red I want it's score value to turn 0 and be stored in the json file. When I have multiple buttons saved in the json file the score doesn't turn zero until I press one of the buttons and when I do press the button all the values except the first button turn 0, this is not what I want.

```<code>class MainApp(App):
    def build(self):  # build() returns an instance
        self.store = JsonStore("streak.json")  # file that stores the streaks:
        Clock.schedule_interval(self.check_streak, 1 / 30.)

        return presentation

    def check_streak(self, dt):

        for child in reversed(self.root.screen_two.ids.streak_zone.children):
            name = child.text

            with open("streak.json", "r") as read_file:
                data = json.load(read_file)

            for key in data.keys():
                if key == name:
                    delay = data.get(key, {}).get('delay')  # get value of nested key 'delay'
                    self.honey = data[key]['delta']
                    float(self.honey)

                if delay > time.time() < self.honey:  # early (yellow)
                    child.background_normal = ''
                    child.background_color = [1, 1, 0, 1]
                    child.unbind(on_press=self.add_score)
                    child.bind(on_press=self.early_click)

                elif delay > time.time() > self.honey:  # on time (green)
                    child.background_normal = ''
                    child.background_color = [0, 1, 0, 1]
                    child.unbind(on_press=self.early_click)
                    child.bind(on_press=self.add_score)

                elif delay < time.time() > self.honey:  # late (red)
                    child.background_normal = ''
                    child.background_color = [1, 0, 0, 1]
                    child.unbind(on_press=self.add_score)
                    child.unbind(on_press=self.early_click)

                    with open("streak.json", "r+") as f:
                        files = json.load(f)
                        files[child.text]['score'] = 0
                        f.seek(0)
                        json.dump(files, f, indent=4)
                        f.truncate()
</code>```

json file:

```<code>{
    "One": {
        "action": "One",
        "delay": 1558740875.58999,
        "seconds": 60,
        "score": 3,
        "delta": 1558740815.58999,
        "grace_sec": 120
    },
    "Two": {
        "action": "Two",
        "delay": 1558740752.0085213,
        "seconds": 60,
        "score": 0,
        "delta": 1558740692.0085213,
        "grace_sec": 120
    },
    "Three": {
        "action": "Three",
        "delay": 1558746820.4364505,
        "seconds": 60,
        "score": 0,
        "delta": 1558740820.4364505,
        "grace_sec": 6060
    }
}
</code>```

I want only the button that is red to change its score to 0 but both Two and Three change, even though only Two was red. Also, the score only changes when I press a green button, in this case, it was One. This is not what I want. I want the score to update its self using the Clock module.

答:
created a separate function that uses clock to update the json file.</p>

```<code># change score to 0 and stores in json file
    def score_gone(self, dt):
        for child in self.root.screen_two.ids.streak_zone.children:
            name = child.text
            color = child.background_color

            with open("streak.json", "r") as file:
                read = json.load(file)

            if color == [1, 0, 0, .95]: # red

                if read[name]['score'] != 0: #stops slow down from Clock
                    with open("streak.json", "r+") as f: # fix score not reseting to 0
                            data = json.load(f)
                            data[name]['score'] = 0
                            f.seek(0)
                            json.dump(data, f, indent=4)
                            f.truncate()

                elif read[name]['score'] == 0: #stops slow down from Clock
                        pass
</code>```

Body:
I have buttons that are connected to keys in my json file. Using kivy's Clock module I check the value connected to the button and changes its colors. When the button turns red I want it's score value to turn 0 and be stored in the json file. When I have multiple buttons saved in the json file the score doesn't turn zero until I press one of the buttons and when I do press the button all the values except the first button turn 0, this is not what I want.

class MainApp(App):
    def build(self):  # build() returns an instance
        self.store = JsonStore("streak.json")  # file that stores the streaks:
        Clock.schedule_interval(self.check_streak, 1 / 30.)

        return presentation

    def check_streak(self, dt):

        for child in reversed(self.root.screen_two.ids.streak_zone.children):
            name = child.text

            with open("streak.json", "r") as read_file:
                data = json.load(read_file)

            for key in data.keys():
                if key == name:
                    delay = data.get(key, {}).get('delay')  # get value of nested key 'delay'
                    self.honey = data[key]['delta']
                    float(self.honey)

                if delay > time.time() < self.honey:  # early (yellow)
                    child.background_normal = ''
                    child.background_color = [1, 1, 0, 1]
                    child.unbind(on_press=self.add_score)
                    child.bind(on_press=self.early_click)

                elif delay > time.time() > self.honey:  # on time (green)
                    child.background_normal = ''
                    child.background_color = [0, 1, 0, 1]
                    child.unbind(on_press=self.early_click)
                    child.bind(on_press=self.add_score)

                elif delay < time.time() > self.honey:  # late (red)
                    child.background_normal = ''
                    child.background_color = [1, 0, 0, 1]
                    child.unbind(on_press=self.add_score)
                    child.unbind(on_press=self.early_click)

                    with open("streak.json", "r+") as f:
                        files = json.load(f)
                        files[child.text]['score'] = 0
                        f.seek(0)
                        json.dump(files, f, indent=4)
                        f.truncate()

json file:

{
    "One": {
        "action": "One",
        "delay": 1558740875.58999,
        "seconds": 60,
        "score": 3,
        "delta": 1558740815.58999,
        "grace_sec": 120
    },
    "Two": {
        "action": "Two",
        "delay": 1558740752.0085213,
        "seconds": 60,
        "score": 0,
        "delta": 1558740692.0085213,
        "grace_sec": 120
    },
    "Three": {
        "action": "Three",
        "delay": 1558746820.4364505,
        "seconds": 60,
        "score": 0,
        "delta": 1558740820.4364505,
        "grace_sec": 6060
    }
}

I want only the button that is red to change its score to 0 but both Two and Three change, even though only Two was red. Also, the score only changes when I press a green button, in this case, it was One. This is not what I want. I want the score to update its self using the Clock module.

Body:
created a separate function that uses clock to update the json file.

# change score to 0 and stores in json file
    def score_gone(self, dt):
        for child in self.root.screen_two.ids.streak_zone.children:
            name = child.text
            color = child.background_color

            with open("streak.json", "r") as file:
                read = json.load(file)

            if color == [1, 0, 0, .95]: # red

                if read[name]['score'] != 0: #stops slow down from Clock
                    with open("streak.json", "r+") as f: # fix score not reseting to 0
                            data = json.load(f)
                            data[name]['score'] = 0
                            f.seek(0)
                            json.dump(data, f, indent=4)
                            f.truncate()

                elif read[name]['score'] == 0: #stops slow down from Clock
                        pass


问:
What Is the most popular combination of technologies used to building Reactjs web apps
I'm mid PHP/Laravel developer with some exp in jQuery and Vue.js
I want to start self-learning in reactive JS frameworks (for example ReactJS), because I see is the near future in web development.

I checked the [React + redux] is the most popular technology working on browser side, but what about back-end ?
Secured API to PHP/MySQL? or maybe run apps directly on NodeJS server ? if nodejs env. then where will be storing the data ? SQL? NoSQL?

Tell me please what back-end stack is the most popular? or what stack is the near future ?

What about PWA with ReactJS ?

Thank You!

答:
Hi with my previous experience

ReactJs + Redux + fire base
this is very good technical combination you can use
reactJs , redux , meterilaUI,Sementic UI,ant design for front end.
and fire base can easily connected with your application.
advantage of this architecture the app will real time data application , no end point integration , quickly development , easy to authenticate

sample project

ReactJs + Redux + REST + Spring-boot in this project back end service developed using java spring-boot and it possible for connect any relational data bases such as Oracle , MYSql, NoSql , even any kind of Data bases using Spting-Data-JPA or Hibernate , JPA.

But authentication and state management not much easy. need to implement JWT to any  state management method because REST is stateless.
advantage is good for micro services architecture , easy to build react app inside spring boot (packaging as .jar .war) and deployee j2EE server.

sample project

i have already developed project based on these 2 technologies stacks both are worked as my different requirements.


问:
How do I check whether a checkbox is checked in jQuery?
I need to check the checked property of a checkbox and perform an action based on the checked property using jQuery.

For example, if the age checkbox is checked, then I need to show a textbox to enter age, else hide the textbox.

But the following code returns false by default:

if ($('#isAgeSelected').attr('checked')) {
  $("#txtAge").show();
} else {
  $("#txtAge").hide();
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="isAgeSelected"/>
<div id="txtAge" style="display:none">
  Age is selected
</div></code>```

How do I successfully query the checked property?

答:
Please try below code to check checkbox is checked or not

```<code>$(document).ready(function(){

    $("#isAgeSelected").on('change',function(){

    if($("#isAgeSelected").is(':checked'))
        $("#txtAge").show();  // checked
    else{
        $("#txtAge").hide();  // unchecked
    }

   });

});
</code>```

Body:
I need to check the checked property of a checkbox and perform an action based on the checked property using jQuery.

For example, if the age checkbox is checked, then I need to show a textbox to enter age, else hide the textbox.

But the following code returns false by default:

if ($('#isAgeSelected').attr('checked')) {
  $("#txtAge").show();
} else {
  $("#txtAge").hide();
}

<input type="checkbox" id="isAgeSelected"/>

  Age is selected

How do I successfully query the checked property?

Body:
Please try below code to check checkbox is checked or not

$(document).ready(function(){

    $("#isAgeSelected").on('change',function(){

    if($("#isAgeSelected").is(':checked'))
        $("#txtAge").show();  // checked
    else{
        $("#txtAge").hide();  // unchecked
    }

   });

});