问:
Garbage value published as key in kafka topic
I am using Long serializer for the keys and String serializer for value , after posting the message to the kafka topic when we retrieved the message and along with key are seeing key as some garbage value  like below

```<code>^@^@^@^AÏÃ<9a>ò
</code>```

is there anything wrong  with kafka producer configuration ?

Update :

Below producer configuration

```<code>                    configProps.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
configProps.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, LongSerializer.class.getName());
            configProps.put(CommonClientConfigs.REQUEST_TIMEOUT_MS_CONFIG, requestTimeoutInMillis);
            configProps.put(ProducerConfig.COMPRESSION_TYPE_CONFIG, abcompressionType);

@Bean
    public ProducerFactory<Long, String> longProducerFactory() {
        return new DefaultKafkaProducerFactory<>(longProducerConfigs());
    }

@Bean
    public KafkaTemplate<Long, String> longKeyKafkaTemplate() {
        return new KafkaTemplate<>(longProducerFactory());
    }
</code>```

and below send call

```<code>longKeyKafkaTemplate.send(topicName, key, message);
</code>```

答:
when i see the key values in Kafka Tool , kafkatool.com , i found those garbage values ,

It's not "garbage" it's a Long value displayed as a String without proper deserialization.

I am not familiar with that tool or whether you can specify a deserializer for the key with it, but with the command line tool kafka-console-consumer.sh you can specify the deserializers to use.

```<code>$ kafka-console-consumer
This tool helps to read data from Kafka topics and outputs it to standard output.
Option                                   Description
------                                   -----------
--bootstrap-server <String: server to    REQUIRED: The server(s) to connect to.
  connect to>
--consumer-property <String:             A mechanism to pass user-defined
  consumer_prop>                           properties in the form key=value to
                                           the consumer.
--consumer.config <String: config file>  Consumer config properties file. Note
                                           that [consumer-property] takes
                                           precedence over this config.
--enable-systest-events                  Log lifecycle events of the consumer
                                           in addition to logging consumed
                                           messages. (This is specific for
                                           system tests.)
--formatter <String: class>              The name of a class to use for
                                           formatting kafka messages for
                                           display. (default: kafka.tools.
                                           DefaultMessageFormatter)
--from-beginning                         If the consumer does not already have
                                           an established offset to consume
                                           from, start with the earliest
                                           message present in the log rather
                                           than the latest message.
--group <String: consumer group id>      The consumer group id of the consumer.
--help                                   Print usage information.
--isolation-level <String>               Set to read_committed in order to
                                           filter out transactional messages
                                           which are not committed. Set to
                                           read_uncommitted to read all
                                           messages. (default: read_uncommitted)
--key-deserializer <String:
  deserializer for key>
--max-messages <Integer: num_messages>   The maximum number of messages to
                                           consume before exiting. If not set,
                                           consumption is continual.
--offset <String: consume offset>        The offset id to consume from (a non-
                                           negative number), or 'earliest'
                                           which means from beginning, or
                                           'latest' which means from end
                                           (default: latest)
--partition <Integer: partition>         The partition to consume from.
                                           Consumption starts from the end of
                                           the partition unless '--offset' is
                                           specified.
--property <String: prop>                The properties to initialize the
                                           message formatter. Default
                                           properties include:
                                            print.timestamp=true|false
                                            print.key=true|false
                                            print.value=true|false
                                            key.separator=<key.separator>
                                            line.separator=<line.separator>
                                            key.deserializer=<key.deserializer>
                                            value.deserializer=<value.
                                           deserializer>
                                         Users can also pass in customized
                                           properties for their formatter; more
                                           specifically, users can pass in
                                           properties keyed with 'key.
                                           deserializer.' and 'value.
                                           deserializer.' prefixes to configure
                                           their deserializers.
--skip-message-on-error                  If there is an error when processing a
                                           message, skip it instead of halt.
--timeout-ms <Integer: timeout_ms>       If specified, exit if no message is
                                           available for consumption for the
                                           specified interval.
--topic <String: topic>                  The topic id to consume on.
--value-deserializer <String:
  deserializer for values>
--version                                Display Kafka version.
--whitelist <String: whitelist>          Regular expression specifying
                                           whitelist of topics to include for
                                           consumption.
</code>```

Body:
I am using Long serializer for the keys and String serializer for value , after posting the message to the kafka topic when we retrieved the message and along with key are seeing key as some garbage value  like below

^@^@^@^AÏÃ<9a>ò

is there anything wrong  with kafka producer configuration ?

Update :

Below producer configuration

                    configProps.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
configProps.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, LongSerializer.class.getName());
            configProps.put(CommonClientConfigs.REQUEST_TIMEOUT_MS_CONFIG, requestTimeoutInMillis);
            configProps.put(ProducerConfig.COMPRESSION_TYPE_CONFIG, abcompressionType);

@Bean
    public ProducerFactory<Long, String> longProducerFactory() {
        return new DefaultKafkaProducerFactory<>(longProducerConfigs());
    }

@Bean
    public KafkaTemplate<Long, String> longKeyKafkaTemplate() {
        return new KafkaTemplate<>(longProducerFactory());
    }

and below send call

longKeyKafkaTemplate.send(topicName, key, message);

Body:
when i see the key values in Kafka Tool , kafkatool.com , i found those garbage values ,

It's not "garbage" it's a Long value displayed as a String without proper deserialization.

I am not familiar with that tool or whether you can specify a deserializer for the key with it, but with the command line tool kafka-console-consumer.sh you can specify the deserializers to use.

$ kafka-console-consumer
This tool helps to read data from Kafka topics and outputs it to standard output.
Option                                   Description
------                                   -----------
--bootstrap-server <String: server to    REQUIRED: The server(s) to connect to.
  connect to>
--consumer-property <String:             A mechanism to pass user-defined
  consumer_prop>                           properties in the form key=value to
                                           the consumer.
--consumer.config <String: config file>  Consumer config properties file. Note
                                           that [consumer-property] takes
                                           precedence over this config.
--enable-systest-events                  Log lifecycle events of the consumer
                                           in addition to logging consumed
                                           messages. (This is specific for
                                           system tests.)
--formatter <String: class>              The name of a class to use for
                                           formatting kafka messages for
                                           display. (default: kafka.tools.
                                           DefaultMessageFormatter)
--from-beginning                         If the consumer does not already have
                                           an established offset to consume
                                           from, start with the earliest
                                           message present in the log rather
                                           than the latest message.
--group <String: consumer group id>      The consumer group id of the consumer.
--help                                   Print usage information.
--isolation-level <String>               Set to read_committed in order to
                                           filter out transactional messages
                                           which are not committed. Set to
                                           read_uncommitted to read all
                                           messages. (default: read_uncommitted)
--key-deserializer <String:
  deserializer for key>
--max-messages <Integer: num_messages>   The maximum number of messages to
                                           consume before exiting. If not set,
                                           consumption is continual.
--offset <String: consume offset>        The offset id to consume from (a non-
                                           negative number), or 'earliest'
                                           which means from beginning, or
                                           'latest' which means from end
                                           (default: latest)
--partition <Integer: partition>         The partition to consume from.
                                           Consumption starts from the end of
                                           the partition unless '--offset' is
                                           specified.
--property <String: prop>                The properties to initialize the
                                           message formatter. Default
                                           properties include:
                                            print.timestamp=true|false
                                            print.key=true|false
                                            print.value=true|false
                                            key.separator=<key.separator>
                                            line.separator=<line.separator>
                                            key.deserializer=<key.deserializer>
                                            value.deserializer=<value.
                                           deserializer>
                                         Users can also pass in customized
                                           properties for their formatter; more
                                           specifically, users can pass in
                                           properties keyed with 'key.
                                           deserializer.' and 'value.
                                           deserializer.' prefixes to configure
                                           their deserializers.
--skip-message-on-error                  If there is an error when processing a
                                           message, skip it instead of halt.
--timeout-ms <Integer: timeout_ms>       If specified, exit if no message is
                                           available for consumption for the
                                           specified interval.
--topic <String: topic>                  The topic id to consume on.
--value-deserializer <String:
  deserializer for values>
--version                                Display Kafka version.
--whitelist <String: whitelist>          Regular expression specifying
                                           whitelist of topics to include for
                                           consumption.


来源: stackexchange

问:
Combining two RewriteRules is overriding the first
I am attempting to apply two RewriteRules at the same time. They both work exactly as intended independently (when the other is commented out), but when placed in the .htaccess file together, only the first rule works.

How can I use these together?

```<code>RewriteEngine On

# Redirect everything to this file
RewriteRule ^ public/index.php [QSA,L]

# Rewrite location of the storage files making them public
RewriteRule ^storage/(.*)$ app/files/public/$1 [QSA]
</code>```

答:
Thanks to help from @CBroe, here is the solution:</p>

```<code>RewriteEngine On

# Rewrite location of the storage files making them public
RewriteRule ^storage/(.*)$ app/files/public/$1 [QSA,L]

# Redirect everything to this file
RewriteRule ^ public/index.php [QSA]
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am attempting to apply two RewriteRules at the same time. They both work exactly as intended independently (when the other is commented out), but when placed in the .htaccess file together, only the first rule works.

How can I use these together?

RewriteEngine On

# Redirect everything to this file
RewriteRule ^ public/index.php [QSA,L]

# Rewrite location of the storage files making them public
RewriteRule ^storage/(.*)$ app/files/public/$1 [QSA]

Body:
Thanks to help from @CBroe, here is the solution:

RewriteEngine On

# Rewrite location of the storage files making them public
RewriteRule ^storage/(.*)$ app/files/public/$1 [QSA,L]

# Redirect everything to this file
RewriteRule ^ public/index.php [QSA]


问:
Change the font of an entire document without affecting formatting using Google Docs API
I am trying to change the font of an entire Google Doc using the API. The purpose is to let users of our application export documents with their company’s font.

This is what I am currently doing:

from googleapiclient.discovery import build

doc_service = build("docs", "v1")
document = self.doc_service.documents().get(documentId="[Document ID]").execute()
requests = []
for element in document["body"]["content"]:
    if "sectionBreak" in element:
        continue  # Trying to change the font of a section break causes an error
    requests.append(
        {
            "updateTextStyle": {
                "range": {
                    "startIndex": element["startIndex"],
                    "endIndex": element["endIndex"],
                },
                "textStyle": {
                    "weightedFontFamily": {
                        "fontFamily": "[Font name]"
                    },
                },
                "fields": "weightedFontFamily",
            }
        }
    )
doc_service.documents().batchUpdate(
    documentId=self.copy_id, body={"requests": requests}
).execute()
```

The code above changes the font, but it also removes any bold text formatting because it overrides the entire style of an element. Some options I have looked into:

DocumentStyle

Documents have a DocumentStyle property, but it does not contain any font information.

NamedStyles

Documents also have a NamedStyles property. It contains styles like NORMAL_TEXT and HEADING_1. I could loop through all these and change their textStyle.weightedFontFamily. This would be the ideal solution, because it would keep style information where it belongs. But I have not found a way to change NamedStyles using the API.

Deeper loop

I could continue with my current approach, looping through the elements list on each element, keeping everything but the font from textStyle (which contains things like bold: true). However, our current approach already takes too long to execute, and such an approach would be both slower and more brittle, so I would like to avoid this.

答:
This seems to work for me, even with section breaks in between, and at the end of the document. You might want to explore more corner cases..

This basically tries to mimic the SelectAll option

```<code>document = service.documents().get(documentId=doc_id).execute()
endIndex = sorted(document["body"]["content"], key=lambda x: x["endIndex"], reverse=True,)[0]["endIndex"]
service.documents().batchUpdate(
    documentId=doc_id,
    body={
        "requests": {
            "updateTextStyle": {
                "range": {
                    "endIndex": endIndex,
                    "startIndex": 1,
                },
                "fields": "fontSize",
                "textStyle": {"fontSize": {"magnitude": 100, "unit": "pt"}},
            }
        }
    },
).execute()
</code>```

Same should work for other fields too.

However, if you are going to just share a docx file to all the clients, you could keep a local copy of the PDF / DOCX and then modify those. It is fairly easy to work around the styles in DOCX (it is a bunch of xml files)

Use this to explore and update DOCX files OOXML Tools Chrome Extension

Similarly PDFs are key-values pairs stored as records. Check this:  ReportLab

Body:
I am trying to change the font of an entire Google Doc using the API. The purpose is to let users of our application export documents with their company’s font.

This is what I am currently doing:

from googleapiclient.discovery import build

doc_service = build("docs", "v1")
document = self.doc_service.documents().get(documentId="[Document ID]").execute()
requests = []
for element in document["body"]["content"]:
    if "sectionBreak" in element:
        continue  # Trying to change the font of a section break causes an error
    requests.append(
        {
            "updateTextStyle": {
                "range": {
                    "startIndex": element["startIndex"],
                    "endIndex": element["endIndex"],
                },
                "textStyle": {
                    "weightedFontFamily": {
                        "fontFamily": "[Font name]"
                    },
                },
                "fields": "weightedFontFamily",
            }
        }
    )
doc_service.documents().batchUpdate(
    documentId=self.copy_id, body={"requests": requests}
).execute()

The code above changes the font, but it also removes any bold text formatting because it overrides the entire style of an element. Some options I have looked into:

DocumentStyle

Documents have a DocumentStyle property, but it does not contain any font information.

NamedStyles

Documents also have a NamedStyles property. It contains styles like NORMAL_TEXT and HEADING_1. I could loop through all these and change their textStyle.weightedFontFamily. This would be the ideal solution, because it would keep style information where it belongs. But I have not found a way to change NamedStyles using the API.

Deeper loop

I could continue with my current approach, looping through the elements list on each element, keeping everything but the font from textStyle (which contains things like bold: true). However, our current approach already takes too long to execute, and such an approach would be both slower and more brittle, so I would like to avoid this.

Body:
This seems to work for me, even with section breaks in between, and at the end of the document. You might want to explore more corner cases..

This basically tries to mimic the SelectAll option

document = service.documents().get(documentId=doc_id).execute()
endIndex = sorted(document["body"]["content"], key=lambda x: x["endIndex"], reverse=True,)[0]["endIndex"]
service.documents().batchUpdate(
    documentId=doc_id,
    body={
        "requests": {
            "updateTextStyle": {
                "range": {
                    "endIndex": endIndex,
                    "startIndex": 1,
                },
                "fields": "fontSize",
                "textStyle": {"fontSize": {"magnitude": 100, "unit": "pt"}},
            }
        }
    },
).execute()

Same should work for other fields too.

However, if you are going to just share a docx file to all the clients, you could keep a local copy of the PDF / DOCX and then modify those. It is fairly easy to work around the styles in DOCX (it is a bunch of xml files)

Use this to explore and update DOCX files OOXML Tools Chrome Extension

Similarly PDFs are key-values pairs stored as records. Check this:  ReportLab


问:
I cant change text using javascript?
Im working on a simple commenting system for a website using the postmail API. The thing is that i want to give the user a better error when something goes wrong because postmail only changes the URL. For this is i check the URL of the page when the page loads and if that contains an error i want to change a element to that error. The only problem is that detecting it works fine and i can also create a alert with the error but the text wont change... Can anyone help me with this?

js:

```<code>    <script>
        function sending(){
            document.getElementById("submit_form").value = 'Sending...';
        };

        if (window.location.href.indexOf("err") != -1){
            alert("An error occured! Please make sure to check your input fields."); //this works fine
            document.getElementById("ertext").innerHTML = 'Error!'; //this doesnt
        };
    </script>
</code>```

HTML:

```<code>                <form action="https://postmail.invotes.com/send"
                    method="post" id="email_form">

                    <h2>Feedback</h2>
                    <h4>Your Email:</h4>
                    <input type="text" name="subject" placeholder="aa@aa.aa" style="width: 80%;"/><br>
                    <h6>Your Message:</h6>
                    <textarea name="text" placeholder="Give some feedback" style="resize: none; width: 80%;"></textarea>
                    <input type="hidden" name="access_token" value="--" />

                    <input type="hidden" name="success_url" value="./comments.html" />
                    <input type="hidden" name="error_url" value="./comments.html?err=1" /><br><br>

                    <input id="submit_form" type="submit" value="Send" onclick="sending();" />

                </form>
                <p id="ertext"></p>
                <br> <br>```
```

答:
The Javascript code needs to be executed after the html document is loaded. As mentioned before you can achieve this by putting the script tag somewhere below all referenced elements in your DOM.

Another possibility is to put your JavaScript into a separate file "test.js" and then include it in the head of your document:

```<code><script type="text/javascript" src="test.js" defer></script>
</code>```

Using the defer attribute makes sure the script will be executed after the page finished parsing.

Title: I cant change text using javascript?

Body:
Im working on a simple commenting system for a website using the postmail API. The thing is that i want to give the user a better error when something goes wrong because postmail only changes the URL. For this is i check the URL of the page when the page loads and if that contains an error i want to change a element to that error. The only problem is that detecting it works fine and i can also create a alert with the error but the text wont change... Can anyone help me with this?

js:

HTML:

                <form action="https://postmail.invotes.com/send"
                    method="post" id="email_form">

Feedback

Your Email:

                    <input type="text" name="subject" placeholder="aa@aa.aa" style="width: 80%;"/>

Your Message:

                    <textarea name="text" placeholder="Give some feedback" style="resize: none; width: 80%;"></textarea>
                    <input type="hidden" name="access_token" value="--" />

                    <input type="hidden" name="success_url" value="./comments.html" />
                    <input type="hidden" name="error_url" value="./comments.html?err=1" />

                    <input id="submit_form" type="submit" value="Send" onclick="sending();" />

                </form>

```

Body:
The Javascript code needs to be executed after the html document is loaded. As mentioned before you can achieve this by putting the script tag somewhere below all referenced elements in your DOM.

Another possibility is to put your JavaScript into a separate file "test.js" and then include it in the head of your document:

<script type="text/javascript" src="test.js" defer></script>

Using the defer attribute makes sure the script will be executed after the page finished parsing.


问:
How to print a specific item from within a JSON file into python
I want to print a user from a JSON list into Python that I select however I can only print all the users. How do you print a specific user? At the moment I have this which prints all the users out in a ugly format

```<code>import json

with open('Admin_sample.json') as f:
    admin_json = json.load(f)

print(admin_json['staff'])
</code>```

The JSON file looks like this

```<code>{
"staff": [
    {
        "id": "DA7153",
        "name": [
            "Fran\u00c3\u00a7ois",
            "Ullman"
        ],
        "department": {
            "name": "Admin"
        },
        "server_admin": "true"
    },
    {
        "id": "DA7356",
        "name": [
            "Bob",
            "Johnson"
        ],
        "department": {
            "name": "Admin"
        },
        "server_admin": "false"
    },
],
"assets": [
    {
        "asset_name": "ENGAGED SLOTH",
        "asset_type": "File",
        "owner": "DA8333",
        "details": {
            "security": {
                "cia": [
                    "HIGH",
                    "INTERMEDIATE",
                    "LOW"
                ],
                "data_categories": {
                    "Personal": "true",
                    "Personal Sensitive": "true",
                    "Customer Sensitive": "true"
                }
            },
            "retention": 2
        },
        "file_type": "Document",
        "server": {
            "server_name": "ISOLATED UGUISU",
            "ip": [
                10,
                234,
                148,
                52
            ]
        }
    },
    {
        "asset_name": "ISOLATED VIPER",
        "asset_type": "File",
        "owner": "DA8262",
        "details": {
            "security": {
                "cia": [
                    "LOW",
                    "HIGH",
                    "LOW"
                ],
                "data_categories": {
                    "Personal": "false",
                    "Personal Sensitive": "false",
                    "Customer Sensitive": "true"
                }
            },
            "retention": 2
        },
    },
]
</code>```

I just can't work it out. Any help would be appreciated.

Thanks.

答:
You have two lists in this JSON file. When you try to parse it, you'll be reach a list. For example getting the first staff id:

```<code>print(admin_json['staff'][0]['id'])
</code>```

This will print:

```<code>DA7153
</code>```

When you use "json.loads" this will simply converts JSON file to the Python dictionary. For further info:
https://docs.python.org/3/tutorial/datastructures.html#dictionaries

Body:
I want to print a user from a JSON list into Python that I select however I can only print all the users. How do you print a specific user? At the moment I have this which prints all the users out in a ugly format

import json

with open('Admin_sample.json') as f:
    admin_json = json.load(f)

print(admin_json['staff'])

The JSON file looks like this

{
"staff": [
    {
        "id": "DA7153",
        "name": [
            "Fran\u00c3\u00a7ois",
            "Ullman"
        ],
        "department": {
            "name": "Admin"
        },
        "server_admin": "true"
    },
    {
        "id": "DA7356",
        "name": [
            "Bob",
            "Johnson"
        ],
        "department": {
            "name": "Admin"
        },
        "server_admin": "false"
    },
],
"assets": [
    {
        "asset_name": "ENGAGED SLOTH",
        "asset_type": "File",
        "owner": "DA8333",
        "details": {
            "security": {
                "cia": [
                    "HIGH",
                    "INTERMEDIATE",
                    "LOW"
                ],
                "data_categories": {
                    "Personal": "true",
                    "Personal Sensitive": "true",
                    "Customer Sensitive": "true"
                }
            },
            "retention": 2
        },
        "file_type": "Document",
        "server": {
            "server_name": "ISOLATED UGUISU",
            "ip": [
                10,
                234,
                148,
                52
            ]
        }
    },
    {
        "asset_name": "ISOLATED VIPER",
        "asset_type": "File",
        "owner": "DA8262",
        "details": {
            "security": {
                "cia": [
                    "LOW",
                    "HIGH",
                    "LOW"
                ],
                "data_categories": {
                    "Personal": "false",
                    "Personal Sensitive": "false",
                    "Customer Sensitive": "true"
                }
            },
            "retention": 2
        },
    },
]

I just can't work it out. Any help would be appreciated.

Thanks.

Body:
You have two lists in this JSON file. When you try to parse it, you'll be reach a list. For example getting the first staff id:

print(admin_json['staff'][0]['id'])

This will print:

DA7153

When you use "json.loads" this will simply converts JSON file to the Python dictionary. For further info:
https://docs.python.org/3/tutorial/datastructures.html#dictionaries


问:
How can I wait for an item to become visible, then disappear?
I need to write a pure JavaScript function (no jQuery) that will:
1. Wait for a DOC element to become visible.
2. Wait for the same element to then become invisible.
Here is my current attempt:

```<code>var checkVisible = setInterval(function() {
    var el = document.getElementById('submitBusy');
    var style = window.getComputedStyle(el);
    /* See if element is visible. */
    if (style.display !== 'none') {
        clearInterval(checkVisible);

        var checkInvisible = setInterval(function() {
            var el = document.getElementById('submitBusy');
            var style = window.getComputedStyle(el);
            /* See if element is visible. */
            if (style.display === 'none') {
                clearInterval(checkInvisible);
            }
        }, 50);
    }
}, 50);
</code>```

On the page, when a certain button is clicked to load a table on the page, the following function is called:

```<code>function searchStart() {
    $("#submitBusy").css("display", "inline-block");
}
</code>```

once the page's contents are pulled from the server, the following is called:

```<code>function searchDone() {
    $("#submitBusy").css("display", "none");
}
</code>```

Once the "submitBusy" element is shown and then disappears, I then want to walk through all rows in the newly generated table so I need to know where to put that code.

Thanks for your help.

答:
It seems like it would be much easier to add the code into your searchDone function...but if there is some reason why you must watch for the element to be shown and then hidden, the most efficient way would be to use an IntersectionObserver.

Detecting when elements "intersect" with the current viewport (or other elements) is what it's for, and of course this includes things like scrolling into view or changing the display of the element.

But even though it would theoretically work, you'd be much better off using a custom event as @cat suggested, or even just a regular function call in searchDone.

let observer = new IntersectionObserver(callback);
let hasShown = false;
let hasHidden = false;
function callback(entries) {
  entries.forEach(e => {
    if (e.isIntersecting) hasShown = true;
    else if (hasShown) hasHidden = true;
    if (hasShown &&  hasHidden) console.log('shown and hidden, do something!');
  });
}

let target = document.querySelector('#submitBusy');
observer.observe(target);

setTimeout(() => {
  target.style.display = 'block';
}, 500);

setTimeout(() => {
  target.style.display = 'none';
}, 1500);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id='submitBusy' style="display:none;">please wait...</div></code>```

You'd want to check browser support to verify it's acceptable to you. Coverage is currently 92.8%.

Body:
I need to write a pure JavaScript function (no jQuery) that will:
1. Wait for a DOC element to become visible.
2. Wait for the same element to then become invisible.
Here is my current attempt:

var checkVisible = setInterval(function() {
    var el = document.getElementById('submitBusy');
    var style = window.getComputedStyle(el);
    /* See if element is visible. */
    if (style.display !== 'none') {
        clearInterval(checkVisible);

        var checkInvisible = setInterval(function() {
            var el = document.getElementById('submitBusy');
            var style = window.getComputedStyle(el);
            /* See if element is visible. */
            if (style.display === 'none') {
                clearInterval(checkInvisible);
            }
        }, 50);
    }
}, 50);

On the page, when a certain button is clicked to load a table on the page, the following function is called:

function searchStart() {
    $("#submitBusy").css("display", "inline-block");
}

once the page's contents are pulled from the server, the following is called:

function searchDone() {
    $("#submitBusy").css("display", "none");
}

Once the "submitBusy" element is shown and then disappears, I then want to walk through all rows in the newly generated table so I need to know where to put that code.

Thanks for your help.

Body:
It seems like it would be much easier to add the code into your searchDone function...but if there is some reason why you must watch for the element to be shown and then hidden, the most efficient way would be to use an IntersectionObserver.

Detecting when elements "intersect" with the current viewport (or other elements) is what it's for, and of course this includes things like scrolling into view or changing the display of the element.

But even though it would theoretically work, you'd be much better off using a custom event as @cat suggested, or even just a regular function call in searchDone.

let observer = new IntersectionObserver(callback);
let hasShown = false;
let hasHidden = false;
function callback(entries) {
  entries.forEach(e => {
    if (e.isIntersecting) hasShown = true;
    else if (hasShown) hasHidden = true;
    if (hasShown &&  hasHidden) console.log('shown and hidden, do something!');
  });
}

let target = document.querySelector('#submitBusy');
observer.observe(target);

setTimeout(() => {
  target.style.display = 'block';
}, 500);

setTimeout(() => {
  target.style.display = 'none';
}, 1500);

<div id='submitBusy' style="display:none;">please wait...</div>

You'd want to check browser support to verify it's acceptable to you. Coverage is currently 92.8%.


问:
Hashed password update with mongoose express
I have reviewed many discussions on this matter but none seems helpful to me.

I am using mongoose 5.5 to save user data as shown below:

My schema looks like this:

```<code>const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const bcrypt = require("bcryptjs");

const userSchema = Schema({

  userName: {
    type: String
  },
  firstName: {
    type: String
  },
  surName: {
    type: String
  },
  password: {
    type: String,
    required: true
  }
});

userSchema.pre('save', async function(next){

try {
  if(!this.isModified('password')){
      return next();
  }
  const hashed = await bcrypt.hash(this.password, 10);
  this.password = hashed;

} catch (err) {
    return next(err);
  }
});

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

My registration code looks like this:

```<code>exports.register = async (req, res, next) => {

try {
    const user = await db.user.create(req.body);
    const {id, username} = user;
    res.status(201).json({user});

} catch (err) {
    if(err.code === 11000){
        err.message ='Sorry, details already taken';
    }
    next(err);
  }
};
</code>```

Login code looks like this:

```<code>exports.login = async (req, res, next) => {

try {
    const user = await db.user.findOne({username: req.body.username});
    const valid = await user.comparePasswords(req.body.password);

    if(valid){

        const token = jwt.sign({id, username}, process.env.SECRET);
        res.json({id, username, token});
    }
    else{
        throw new Error();
    }

} catch (err) {
    err.message = 'Invalid username/password';
    next(err);
  }
};
</code>```

Registration and login works well, my challenge is updating a password. I would like to compare current password with what user provides (like in login), if it is valid then update new password.

something like this:

```<code>exports.changepass = async (req, res, next) => {
    const user = await db.user.findOne({username: req.body.username});
    const valid = await user.comparePasswords(req.body.password);

    if(valid){

           " ?? update password and hash ?? "
    }
    else{
        throw new Error();
    }

}
</code>```

答:
If you're using findOneAndUpdate() to update, try using the pre("findOneAndUpdate") middleware to modify the password similar to your pre("save"). The pre("findOneAndUpdate") middleware will be called every time you use Model.findOndAndUpate() to update your models.

You can do the same with updateOne() with pre("updateOne")

Sample:

```<code>// userSchema--------------------
...
userSchema.pre('save', async function (next) {
    try {
        if (!this.isModified('password')) {
            return next();
        }
        const hashed = await bcrypt.hash(this.password, 10);
        this.password = hashed;
    } catch (err) {
        return next(err);
    }
});

userSchema.pre('findOneAndUpdate', async function (next) {
    try {
        if (this._update.password) {
            const hashed = await bcrypt.hash(this._update.password, 10)
            this._update.password = hashed;
        }
        next();
    } catch (err) {
        return next(err);
    }
});

// changepass--------------------
...
if(valid){

    //" ?? update password and hash ?? "
    const result = await db.user.findOneAndUpdate(
        { username: req.body.username },
        { password: req.body.newPassword },
        { useFindAndModify: false }
    );
}
</code>```

Body:
I have reviewed many discussions on this matter but none seems helpful to me.

I am using mongoose 5.5 to save user data as shown below:

My schema looks like this:

const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const bcrypt = require("bcryptjs");

const userSchema = Schema({

  userName: {
    type: String
  },
  firstName: {
    type: String
  },
  surName: {
    type: String
  },
  password: {
    type: String,
    required: true
  }
});

userSchema.pre('save', async function(next){

try {
  if(!this.isModified('password')){
      return next();
  }
  const hashed = await bcrypt.hash(this.password, 10);
  this.password = hashed;

} catch (err) {
    return next(err);
  }
});

module.exports = user;

My registration code looks like this:

exports.register = async (req, res, next) => {

try {
    const user = await db.user.create(req.body);
    const {id, username} = user;
    res.status(201).json({user});

} catch (err) {
    if(err.code === 11000){
        err.message ='Sorry, details already taken';
    }
    next(err);
  }
};

Login code looks like this:

exports.login = async (req, res, next) => {

try {
    const user = await db.user.findOne({username: req.body.username});
    const valid = await user.comparePasswords(req.body.password);

    if(valid){

        const token = jwt.sign({id, username}, process.env.SECRET);
        res.json({id, username, token});
    }
    else{
        throw new Error();
    }

} catch (err) {
    err.message = 'Invalid username/password';
    next(err);
  }
};

Registration and login works well, my challenge is updating a password. I would like to compare current password with what user provides (like in login), if it is valid then update new password.

something like this:

exports.changepass = async (req, res, next) => {
    const user = await db.user.findOne({username: req.body.username});
    const valid = await user.comparePasswords(req.body.password);

    if(valid){

           " ?? update password and hash ?? "
    }
    else{
        throw new Error();
    }

}

Body:
If you're using findOneAndUpdate() to update, try using the pre("findOneAndUpdate") middleware to modify the password similar to your pre("save"). The pre("findOneAndUpdate") middleware will be called every time you use Model.findOndAndUpate() to update your models.

You can do the same with updateOne() with pre("updateOne")

Sample:

// userSchema--------------------
...
userSchema.pre('save', async function (next) {
    try {
        if (!this.isModified('password')) {
            return next();
        }
        const hashed = await bcrypt.hash(this.password, 10);
        this.password = hashed;
    } catch (err) {
        return next(err);
    }
});

userSchema.pre('findOneAndUpdate', async function (next) {
    try {
        if (this._update.password) {
            const hashed = await bcrypt.hash(this._update.password, 10)
            this._update.password = hashed;
        }
        next();
    } catch (err) {
        return next(err);
    }
});

// changepass--------------------
...
if(valid){

    //" ?? update password and hash ?? "
    const result = await db.user.findOneAndUpdate(
        { username: req.body.username },
        { password: req.body.newPassword },
        { useFindAndModify: false }
    );
}


问:
Why npm start is throwing events.js:187 throw er; // Unhandled 'error' event in my react project?
While starting the server for the first time just after the code checkout
    , my react js project is throwing error "events.js:187
      throw er; // Unhandled 'error' event" . I have node 12.13.0 and npm
    6.12.0 . Log file attached log file</p>

```<code>events.js:187
      throw er; // Unhandled 'error' event
      ^

    Error: spawn cmd ENOENT
        at Process.ChildProcess._handle.onexit
       (internal/child_process.js:264:19)
       at onErrorNT (internal/child_process.js:456:16)
       at processTicksAndRejections (internal/process/task_queues.js:80:21)
    Emitted 'error' event on ChildProcess instance at:
       at Process.ChildProcess._handle.onexit (internal/child_process.js:270:12)
       at onErrorNT (internal/child_process.js:456:16)
       at processTicksAndRejections (internal/process/task_queues.js:80:21) {
    errno: 'ENOENT',
    code: 'ENOENT',
    syscall: 'spawn cmd',
    path: 'cmd',
    spawnargs: [ '/c', 'start', '""', '/b', 'http://localhost:3000/' ]
}
</code>```

答: If you are experiencing this error on ubuntu simply prepend "sudo" to the npm start command. That is sudo npm start

Body:
While starting the server for the first time just after the code checkout
    , my react js project is throwing error "events.js:187
      throw er; // Unhandled 'error' event" . I have node 12.13.0 and npm
    6.12.0 . Log file attached log file

events.js:187
      throw er; // Unhandled 'error' event
      ^

    Error: spawn cmd ENOENT
        at Process.ChildProcess._handle.onexit
       (internal/child_process.js:264:19)
       at onErrorNT (internal/child_process.js:456:16)
       at processTicksAndRejections (internal/process/task_queues.js:80:21)
    Emitted 'error' event on ChildProcess instance at:
       at Process.ChildProcess._handle.onexit (internal/child_process.js:270:12)
       at onErrorNT (internal/child_process.js:456:16)
       at processTicksAndRejections (internal/process/task_queues.js:80:21) {
    errno: 'ENOENT',
    code: 'ENOENT',
    syscall: 'spawn cmd',
    path: 'cmd',
    spawnargs: [ '/c', 'start', '""', '/b', 'http://localhost:3000/' ]
}


问:
Does the LastModifiedDate gets updates on SFDC Object record if the Formula behind formula field in the object is updated?
Does the LastModifiedDate gets updated on SFDC Object record if the Formula behind formula field in the object is updated?</p>

答:
No. You're changing metadata. Think like adding new column to table in database - it's different type of operation, no data is modified, triggers don't run...
Formulas are like views - calculated at runtime, the moment you view the record on a page or in a report.
There are ways to see who changed what (setup audit trail, tooling API can tell you who & when modified field definition, in REST API there's a call that will tell whether anything changed since X) but that's separate from actual records stored in table.</p>


问:
`var` comes as undefined but can't understand why
I have been trying to understand why my js code which was inside the HTML is not working now that it is in an external file. English is not my first language which makes me even harder to understand (and spanish results haven't been quite productive as I hoped).

I literally copy-paste the code to the other file and placed  to get the js loaded but both Firefox and Chrome keep telling me "TypeError: eng is undefined" when it is.

Before anyone tells me, it was already responded to in other questions, yes, I saw it was. But I don't understand anything so if anyone could explain me like "JS for dummies" would be REALLY appreciated.

The code is:

```<code>//SETS "LOCALE" "EN" TO REDIRECT TO ENGLISH
(function (){
  'use strict';

 var eng = document.querySelector('.eng')

  function setLocalStorage(){
     eng.addEventListener('click', () => {
      localStorage.setItem('locale','en')
    })
  }
  setLocalStorage()

}());

//SETS "LOCALE" "ES" TO REDIRECT TO SPANISH
(function (){
  'use strict';

  var esp = document.querySelector('.esp')

  function setLocalStorage(){
     esp.addEventListener('click', () => {
      localStorage.setItem('locale','es')
    })
  }
  setLocalStorage()

}());

//GETS THE "LOCALE" AND REDIRECT
(function () {
  'use strict';

  const locale = localStorage.getItem('locale');

  if (locale === 'en') {
    window.location = 'eng.html';

  } else if (locale === 'es') {
    window.location = 'esp.html';

  } else {
    // first visit:
    document
      .querySelector('.eng')
      .addEventListener('click', () => {
        localStorage.setItem('locale', 'en')
      });

    document
      .querySelector('.esp')
      .addEventListener('click', () => {
        localStorage.setItem('locale', 'es')
      });
  }

}());
</code>```

答:
This line of JavaScript:

```<code>var eng = document.querySelector('.eng')
</code>```

is trying to access an element on the HTML page, which probably looks like this:

```<code><div class="eng">english text here</div>
</code>```

In order for the JavaScript code to find that HTML element, the page must already be loaded before the JavaScript line of code runs. If not, the document.querySelector('.eng') expression will return null.

To improve the chances that the HTML will be loaded and available before the JavaScript runs, it is a good practice to put your scripts at the bottom of the  element. Something like this:

english text

```

<p>But that's not a complete guarantee. To further improve your chances, you can add the <code>defer</code> attribute to the script tag, which prevents the script from running until after the page has loaded.</p>

```
```

<hr>

<p><strong>Issue #2 - Hoisting</strong></p>

<p>There's a further problem with the JavaScript code that can cause an error. This has to do with "hoisting", where variables and function declarations are "hoisted" to the top of their blocks.</p>

<p>This JavaScript involves some hoisting:</p>

<pre class="lang-js prettyprint-override"><code>function () {
  'use strict';

  var eng = document.querySelector('.eng');

  function setLocalStorage () {
    eng.addEventListener('click', () => {
      localStorage.setItem('locale', 'en');
    });
  }

  setLocalStorage();

}
</code>```

Because of hoisting, it's actually doing this:

function () {

  // declare 'eng' as undefined
  var eng;

  // declare setLocalStorage
  function setLocalStorage () {

    // JavaScript interpreter says during declaration:
    // "TypeError: I don't know what 'eng.addEventListener' is"

    eng.addEventListener('click', () => {
      localStorage.setItem('locale', 'en');
    });
  }

  // set 'eng'
  eng = document.querySelector('.eng');

  // now that 'eng' is set, call setLocalStorage
  setLocalStorage();

}
```

<p>The fix - don't use an unset variable in a hoisted function. This code does the same thing, without any hoisting problems:</p>

<pre class="lang-js prettyprint-override"><code>(function () {
  var eng = document.querySelector('.eng');

  eng.addEventListener('click', () => {
      localStorage.setItem('locale', 'en');
    });
})();
</code>```

Body:
I have been trying to understand why my js code which was inside the HTML is not working now that it is in an external file. English is not my first language which makes me even harder to understand (and spanish results haven't been quite productive as I hoped).

I literally copy-paste the code to the other file and placed  to get the js loaded but both Firefox and Chrome keep telling me "TypeError: eng is undefined" when it is.

Before anyone tells me, it was already responded to in other questions, yes, I saw it was. But I don't understand anything so if anyone could explain me like "JS for dummies" would be REALLY appreciated.

The code is:

//SETS "LOCALE" "EN" TO REDIRECT TO ENGLISH
(function (){
  'use strict';

 var eng = document.querySelector('.eng')

  function setLocalStorage(){
     eng.addEventListener('click', () => {
      localStorage.setItem('locale','en')
    })
  }
  setLocalStorage()

}());

//SETS "LOCALE" "ES" TO REDIRECT TO SPANISH
(function (){
  'use strict';

  var esp = document.querySelector('.esp')

  function setLocalStorage(){
     esp.addEventListener('click', () => {
      localStorage.setItem('locale','es')
    })
  }
  setLocalStorage()

}());

//GETS THE "LOCALE" AND REDIRECT
(function () {
  'use strict';

  const locale = localStorage.getItem('locale');

  if (locale === 'en') {
    window.location = 'eng.html';

  } else if (locale === 'es') {
    window.location = 'esp.html';

  } else {
    // first visit:
    document
      .querySelector('.eng')
      .addEventListener('click', () => {
        localStorage.setItem('locale', 'en')
      });

    document
      .querySelector('.esp')
      .addEventListener('click', () => {
        localStorage.setItem('locale', 'es')
      });
  }

}());

Body:
This line of JavaScript:

var eng = document.querySelector('.eng')

is trying to access an element on the HTML page, which probably looks like this:

<div class="eng">english text here</div>

In order for the JavaScript code to find that HTML element, the page must already be loaded before the JavaScript line of code runs. If not, the document.querySelector('.eng') expression will return null.

To improve the chances that the HTML will be loaded and available before the JavaScript runs, it is a good practice to put your scripts at the bottom of the <body> element. Something like this:

<body>
  <div class="eng">english text</div>
  <script src="myjavascript.js"></script>
<body>

But that's not a complete guarantee. To further improve your chances, you can add the defer attribute to the script tag, which prevents the script from running until after the page has loaded.

<script src="myjavascript.js" defer></script>

Issue #2 - Hoisting

There's a further problem with the JavaScript code that can cause an error. This has to do with "hoisting", where variables and function declarations are "hoisted" to the top of their blocks.

This JavaScript involves some hoisting:

function () {
  'use strict';

  var eng = document.querySelector('.eng');

  function setLocalStorage () {
    eng.addEventListener('click', () => {
      localStorage.setItem('locale', 'en');
    });
  }

  setLocalStorage();

}

Because of hoisting, it's actually doing this:

function () {

  // declare 'eng' as undefined
  var eng;

  // declare setLocalStorage
  function setLocalStorage () {

    // JavaScript interpreter says during declaration:
    // "TypeError: I don't know what 'eng.addEventListener' is"

    eng.addEventListener('click', () => {
      localStorage.setItem('locale', 'en');
    });
  }

  // set 'eng'
  eng = document.querySelector('.eng');

  // now that 'eng' is set, call setLocalStorage
  setLocalStorage();

}

The fix - don't use an unset variable in a hoisted function. This code does the same thing, without any hoisting problems:

(function () {
  var eng = document.querySelector('.eng');

  eng.addEventListener('click', () => {
      localStorage.setItem('locale', 'en');
    });
})();


问:
fetch in git doesn't get all branches
I have cloned a repository, after which somebody else has created a new branch, which I'd like to start working on.  I read the manual, and it seems dead straight easy.  Strangely it's not working, and all the posts I've found suggest I'm doing the right thing.  So I'll subject myself to the lambasting, because there must be something obviously wrong with this:

The correct action seems to be

```<code>git fetch
git branch -a
* master
  remotes/origin/HEAD --> origin/master
  remotes/origin/master
git checkout -b dev-gml origin/dev-gml
</code>```

At this point there is a problem, for some reason after git fetch I can't see the dev-gml remote branch.  Why not?  If I clone the repository freshly, it's there, so certainly the remote branch exists:

```<code>$ mkdir ../gitest
$ cd ../gitest
$ git clone https://github.com/example/proj.git
Cloning into proj...
remote: Counting objects: 1155, done.
remote: Compressing objects: 100% (383/383), done.
remote: Total 1155 (delta 741), reused 1155 (delta 741)
Receiving objects: 100% (1155/1155), 477.22 KiB | 877 KiB/s, done.
Resolving deltas: 100% (741/741), done.
$ cd projdir
$ git branch -a
* master
  remotes/origin/HEAD -> origin/master
  remotes/origin/dev-gml
  remotes/origin/master
</code>```

I've tried git update, git pull, git fetch --all, git pretty-please in all possible permutations...

答:
Had the same problem today setting up my repo from scratch. I tried everything, nothing worked except removing the origin and re-adding it back again.</p>

```<code>git remote rm origin
git remote add origin git@github.com:web3coach/the-blockchain-bar-newsletter-edition.git

git fetch --all
// Ta daaa all branches fetched
</code>```

Title: fetch in git doesn't get all branches

Body:
I have cloned a repository, after which somebody else has created a new branch, which I'd like to start working on.  I read the manual, and it seems dead straight easy.  Strangely it's not working, and all the posts I've found suggest I'm doing the right thing.  So I'll subject myself to the lambasting, because there must be something obviously wrong with this:

The correct action seems to be

git fetch
git branch -a
* master
  remotes/origin/HEAD --> origin/master
  remotes/origin/master
git checkout -b dev-gml origin/dev-gml

At this point there is a problem, for some reason after git fetch I can't see the dev-gml remote branch.  Why not?  If I clone the repository freshly, it's there, so certainly the remote branch exists:

$ mkdir ../gitest
$ cd ../gitest
$ git clone https://github.com/example/proj.git
Cloning into proj...
remote: Counting objects: 1155, done.
remote: Compressing objects: 100% (383/383), done.
remote: Total 1155 (delta 741), reused 1155 (delta 741)
Receiving objects: 100% (1155/1155), 477.22 KiB | 877 KiB/s, done.
Resolving deltas: 100% (741/741), done.
$ cd projdir
$ git branch -a
* master
  remotes/origin/HEAD -> origin/master
  remotes/origin/dev-gml
  remotes/origin/master

I've tried git update, git pull, git fetch --all, git pretty-please in all possible permutations...

Body:
Had the same problem today setting up my repo from scratch. I tried everything, nothing worked except removing the origin and re-adding it back again.

git remote rm origin
git remote add origin git@github.com:web3coach/the-blockchain-bar-newsletter-edition.git

git fetch --all
// Ta daaa all branches fetched


问:
How to add mappings by namespace in Fluent NHibernate
In my application, I need to talk to multiple databases. I am handling this in NHibernate by creating one SessionFactory per database (I assume this is the correct thing to do). So I have two sets of models (one per database), and two sets of Fluent NHibernate ClassMap<> mappings. Both are in the same project (separated by namespace) and I'd like to keep it that way.

The problem comes when creating the SessionFactory. As far as I can see, Fluent NHibernate has basically two methods for adding mappings:

```<code>    .Mappings(m => m.FluentMappings.AddFromAssemblyOf<UserClassMap>())
    .Mappings(m => m.FluentMappings.Add<UserClassMap>()
</code>```

If I use the first overload, then my session factories get all the mappings for both databases. If I use the second, I have to specify each individual ClassMap. I'd like something like FluentMappings.AddFromNamespace(). Is there a way to do this?

答:
It's odd that FluentNHibernate supports this type of filtering for automapping, but not for ClassMaps.  It shouldn't be too hard to add this feature yourself, though, via the magic of extension methods.  Try this:

```<code>public static FluentMappingsContainer AddFromAssemblyOf<T>(
    this FluentMappingsContainer mappings,
    Predicate<Type> where)
{
    if (where == null)
        return mappings.AddFromAssemblyOf<T>();

    var mappingClasses = typeof(T).Assembly.GetExportedTypes()
        .Where(x => (typeof(IMappingProvider).IsAssignableFrom(x)
                || typeof(IExternalComponentMappingProvider).IsAssignableFrom(x))
            && where(x));

    foreach (var type in mappingClasses)
    {
        mappings.Add(type);
    }

    return mappings;
}
</code>```

... and use it like this:

```<code>m.FluentMappings.AddFromAssemblyOf<UserClassMap>(t => t.Namespace.StartsWith("One.Of.The.Two.Namespaces"));
</code>```

ContentLicense: CC BY-SA 3.0

Body:
In my application, I need to talk to multiple databases. I am handling this in NHibernate by creating one SessionFactory per database (I assume this is the correct thing to do). So I have two sets of models (one per database), and two sets of Fluent NHibernate ClassMap<> mappings. Both are in the same project (separated by namespace) and I'd like to keep it that way.

The problem comes when creating the SessionFactory. As far as I can see, Fluent NHibernate has basically two methods for adding mappings:

    .Mappings(m => m.FluentMappings.AddFromAssemblyOf<UserClassMap>())
    .Mappings(m => m.FluentMappings.Add<UserClassMap>()

If I use the first overload, then my session factories get all the mappings for both databases. If I use the second, I have to specify each individual ClassMap. I'd like something like FluentMappings.AddFromNamespace(). Is there a way to do this?

Body:
It's odd that FluentNHibernate supports this type of filtering for automapping, but not for ClassMaps.  It shouldn't be too hard to add this feature yourself, though, via the magic of extension methods.  Try this:

public static FluentMappingsContainer AddFromAssemblyOf<T>(
    this FluentMappingsContainer mappings,
    Predicate<Type> where)
{
    if (where == null)
        return mappings.AddFromAssemblyOf<T>();

    var mappingClasses = typeof(T).Assembly.GetExportedTypes()
        .Where(x => (typeof(IMappingProvider).IsAssignableFrom(x)
                || typeof(IExternalComponentMappingProvider).IsAssignableFrom(x))
            && where(x));

    foreach (var type in mappingClasses)
    {
        mappings.Add(type);
    }

    return mappings;
}

... and use it like this:

m.FluentMappings.AddFromAssemblyOf<UserClassMap>(t => t.Namespace.StartsWith("One.Of.The.Two.Namespaces"));


答:
Actually according to your code you are accessing the DOM element and further you are calling them to do some task. But suppose you are trying to access some unavailable DOM content and then telling them to do something. In that case if you are trying to access some DOM but javascript couldn't find that it will return undefined. That's why you'll get undefined. (i'm trying to explain it easily)

Please make sure you have some elements with the class name eng and esp.

So, to overcome this case you need to check if you can access them and then give some task to do.

Suppose i'm checking here if eng is present there and then assigning some task to it.

```<code>eng && eng.addEventListener('click', () => {
    localStorage.setItem('locale','en')
})
</code>```

Full Code is here.

```<code>//SETS "LOCALE" "EN" TO REDIRECT TO ENGLISH
(

    function (){
      'use strict';

     var eng = document.querySelector('.eng')

      function setLocalStorage(){
         eng && eng.addEventListener('click', () => {
          localStorage.setItem('locale','en')
        })
      }
      setLocalStorage()

    }());

    //SETS "LOCALE" "ES" TO REDIRECT TO SPANISH
    (function (){
      'use strict';

      var esp = document.querySelector('.esp')

      function setLocalStorage(){
         esp && esp.addEventListener('click', () => {
          localStorage.setItem('locale','es')
        })
      }
      setLocalStorage()

    }());

    //GETS THE "LOCALE" AND REDIRECT
    (function () {
      'use strict';

      const locale = localStorage.getItem('locale');

      if (locale === 'en') {
        window.location = 'eng.html';

      } else if (locale === 'es') {
        window.location = 'esp.html';

      } else {
        // first visit:
        document
          .querySelector('.eng')
          .addEventListener('click', () => {
            localStorage.setItem('locale', 'en')
          });

        document
          .querySelector('.esp')
          .addEventListener('click', () => {
            localStorage.setItem('locale', 'es')
          });
      }

    }());
</code>```

Title: `var` comes as undefined but can't understand why

Body:
Actually according to your code you are accessing the DOM element and further you are calling them to do some task. But suppose you are trying to access some unavailable DOM content and then telling them to do something. In that case if you are trying to access some DOM but javascript couldn't find that it will return undefined. That's why you'll get undefined. (i'm trying to explain it easily)

Please make sure you have some elements with the class name eng and esp.

So, to overcome this case you need to check if you can access them and then give some task to do.

Suppose i'm checking here if eng is present there and then assigning some task to it.

eng && eng.addEventListener('click', () => {
    localStorage.setItem('locale','en')
})

Full Code is here.

//SETS "LOCALE" "EN" TO REDIRECT TO ENGLISH
(

    function (){
      'use strict';

     var eng = document.querySelector('.eng')

      function setLocalStorage(){
         eng && eng.addEventListener('click', () => {
          localStorage.setItem('locale','en')
        })
      }
      setLocalStorage()

    }());

    //SETS "LOCALE" "ES" TO REDIRECT TO SPANISH
    (function (){
      'use strict';

      var esp = document.querySelector('.esp')

      function setLocalStorage(){
         esp && esp.addEventListener('click', () => {
          localStorage.setItem('locale','es')
        })
      }
      setLocalStorage()

    }());

    //GETS THE "LOCALE" AND REDIRECT
    (function () {
      'use strict';

      const locale = localStorage.getItem('locale');

      if (locale === 'en') {
        window.location = 'eng.html';

      } else if (locale === 'es') {
        window.location = 'esp.html';

      } else {
        // first visit:
        document
          .querySelector('.eng')
          .addEventListener('click', () => {
            localStorage.setItem('locale', 'en')
          });

        document
          .querySelector('.esp')
          .addEventListener('click', () => {
            localStorage.setItem('locale', 'es')
          });
      }

    }());


问:
Angular 2 cli - ng serve gives 'EIO: i/o error'
I'm working on building a portfolio website using Angular 2. I know there's simpler ways to go about it, but this is also a refresher for me as it's been a while since I've used Angular 2.

When I try to use 'ng serve' to run my project, it crashes and gives this:
'''"An unhandled exception occurred: EIO: i/o error, read
See "C:\Users...\angular-errors.log" for further details."'''

The error log just looks like any other error in code:

```<code>[error] Error: EIO: i/o error, read
at Object.readSync (fs.js:506:3)
at tryReadSync (fs.js:331:20)
at Object.readFileSync (fs.js:360:19)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:994:22)
at Module.load (internal/modules/cjs/loader.js:815:32)
at Function.Module._load (internal/modules/cjs/loader.js:727:14)
at Module.require (internal/modules/cjs/loader.js:852:19)
at require (internal/modules/cjs/helpers.js:74:18)
at Object.<anonymous> (D:\...\portfolio-website\node_modules\webpack-dev-server\node_modules \braces\lib\utils.js:13:19)
at Module._compile (internal/modules/cjs/loader.js:959:30)
</code>```

This error started happening when I reset my PC yesterday but kept my files. I still had to reinstall node and angular because windows lost the path keys (or environment variables or whatever lol)

I opened up an administrator command prompt and tried from that, and it woks fine. Is there an ownership issue with the files?

I've searched for a couple of hours and nothing is for this error, and nothing suggested is either relevant or works. Everything I'm using is up to date (unless maybe I don't realize I'm using it? I only started a few days ago)

Versions:
Angular: 8.3.21
Node: 12.14.0
npm: 6.13.4

答: I had the same issue while using angular 6 cli. Before getting this error I placed an image in the assets folder but it was still throwing 404 not found. I deleted that image and surprisingly the error was gone.</p>

Body:
I'm working on building a portfolio website using Angular 2. I know there's simpler ways to go about it, but this is also a refresher for me as it's been a while since I've used Angular 2.

When I try to use 'ng serve' to run my project, it crashes and gives this:
'''"An unhandled exception occurred: EIO: i/o error, read
See "C:\Users...\angular-errors.log" for further details."'''

The error log just looks like any other error in code:

[error] Error: EIO: i/o error, read
at Object.readSync (fs.js:506:3)
at tryReadSync (fs.js:331:20)
at Object.readFileSync (fs.js:360:19)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:994:22)
at Module.load (internal/modules/cjs/loader.js:815:32)
at Function.Module._load (internal/modules/cjs/loader.js:727:14)
at Module.require (internal/modules/cjs/loader.js:852:19)
at require (internal/modules/cjs/helpers.js:74:18)
at Object.<anonymous> (D:\...\portfolio-website\node_modules\webpack-dev-server\node_modules \braces\lib\utils.js:13:19)
at Module._compile (internal/modules/cjs/loader.js:959:30)

This error started happening when I reset my PC yesterday but kept my files. I still had to reinstall node and angular because windows lost the path keys (or environment variables or whatever lol)

I opened up an administrator command prompt and tried from that, and it woks fine. Is there an ownership issue with the files?

I've searched for a couple of hours and nothing is for this error, and nothing suggested is either relevant or works. Everything I'm using is up to date (unless maybe I don't realize I'm using it? I only started a few days ago)

Versions:
Angular: 8.3.21
Node: 12.14.0
npm: 6.13.4


问:
Gravity Forms: Dynamically create set of fields
I want to allow users to select a custom post type from a dropdown field and add some extra data to it.

For example: The user could select a movie from a list. For that movie he can add an amount of copies and till when he wants to borrow it.

So I have three fields in total:

Dropdown field with movies

Number field

Date field

I now want to add this fieldset for every movie in WordPress (Custom Post Type).
Because I don't know how many movies we have in WordPress, I want to generate the fields on the dynamically.

Fortunately I fount the Repeater (beta) field from Gravity Forms.
With that field, the user could add/remove movies as he wants.

Demo and Docs: https://docs.gravityforms.com/repeater-fields/

The problem is, that I need to populate the first field (Dropdown) with the movies CPT in WordPress.

Here's my current code to generate the repeater field in the form:

```<code>// Adjust your form ID
add_filter( 'gform_form_post_get_meta_5', 'add_my_field' );
function add_my_field( $form ) {
    $movie_sku = GF_Fields::create( array(
        'type'   => 'text',
        'id'     => 1002, // The Field ID must be unique on the form
        'formId' => $form['id'],
        'required' => true,
        'label'  => 'Movie',
        'class'  => 'col-md-4',
        'pageNumber'  => 1, // Ensure this is correct
    ) );
    $movie_amount = GF_Fields::create( array(
        'type'   => 'text',
        'id'     => 1007, // The Field ID must be unique on the form
        'formId' => $form['id'],
        'required' => true,
        'label'  => 'Amount',
        'pageNumber'  => 1, // Ensure this is correct
    ) );
    $movie_date = GF_Fields::create( array(
        'type'   => 'text',
        'id'     => 1001, // The Field ID must be unique on the form
        'formId' => $form['id'],
        'required' => true,
        'label'  => 'Date',
        'pageNumber'  => 1, // Ensure this is correct
    ) );

    $movie = GF_Fields::create( array(
        'type'             => 'repeater',
        'required'          => true,
        'id'               => 1000, // The Field ID must be unique on the form
        'formId'           => $form['id'],
        'label'            => 'Add movie',
        'addButtonText'    => 'Add Another movie',
        'removeButtonText'=> 'Remove movie',
        'pageNumber'       => 1, // Ensure this is correct
        'fields'           => array( $movie_sku,$movie_amount, $movie_date), // Add the fields here.
    ) );

    $form['fields'][] = $movie;

    return $form;
}

// Remove the field before the form is saved. Adjust your form ID
add_filter( 'gform_form_update_meta_5', 'remove_my_field', 10, 3 );
function remove_my_field( $form_meta, $form_id, $meta_name ) {

    if ( $meta_name == 'display_meta' ) {
        // Remove the Repeater field: ID 1000
        $form_meta['fields'] = wp_list_filter( $form_meta['fields'], array( 'id' => 1000 ), 'NOT' );
    }

    return $form_meta;
}
</code>```

And here's my code to populate a field with the movies (Custom Post Type) in WordPress:

```<code>add_filter( 'gform_pre_render_5', 'populate_posts' );
add_filter( 'gform_pre_validation_5', 'populate_posts' );
add_filter( 'gform_pre_submission_filter_5', 'populate_posts' );
add_filter( 'gform_admin_pre_render_5', 'populate_posts' );
function populate_posts( $form ) {

    foreach ( $form['fields'] as &$field ) {

        if ( $field->type != 'select' || strpos( $field->cssClass, 'populate-movie' ) === false ) {
            continue;
        }

        // you can add additional parameters here to alter the posts that are retrieved
        // more info: http://codex.wordpress.org/Template_Tags/get_posts

        $args = array(
        'orderby'       =>  'title',
        'order'         =>  'ASC',
        'numberposts'   => -1,
        'post_type'     => 'movie',
        'post_status'   => array('publish'),

        );

        $posts = get_posts( $args );

        $choices = array();

        foreach ( $posts as $post ) {

            $choices[] = array(
                'text'  => $post->post_title,
                'value' => $post->post_title
            );
        }

        // update 'Select a Post' to whatever you'd like the instructive option to be
        $field->placeholder = 'Select movie';
        $field->choices = $choices;

    }

    return $form;
}
</code>```

But how can I combine these two functions and dynamically populate the Dropdown field with the movies?

答:
I guess I found a solution:

Before the first GF_Fields::create I have to copy the following code from my second function:

```<code>$args = array(
        'orderby'       =>  'title',
        'order'         =>  'ASC',
        'numberposts'   => -1,
        'post_type'     => 'movie',
        'post_status'   => array('publish'),

        );

        $posts = get_posts( $args );

        $choices = array();

        foreach ( $posts as $post ) {

            $choices[] = array(
                'text'  => $post->post_title,
                'value' => $post->post_title
            );
        }
</code>```

Then I have to edit the first GF_Fields::create like this:

```<code>$movie_sku = GF_Fields::create( array(
    'type'   => 'select',
    'id'     => 1002, // The Field ID must be unique on the form
    'formId' => $form['id'],
    'required' => true,
    'label'  => 'Movie',
    'choices'  => $choices,
    'pageNumber'  => 1, // Ensure this is correct
) );
</code>```

The new part is the 'choices'  => $choices, which gets it's data from the code above. And of course I had to change the input type to select: 'type'   => 'select',.

Body:
I want to allow users to select a custom post type from a dropdown field and add some extra data to it.

For example: The user could select a movie from a list. For that movie he can add an amount of copies and till when he wants to borrow it.

So I have three fields in total:

Dropdown field with movies

Number field

Date field

I now want to add this fieldset for every movie in WordPress (Custom Post Type).
Because I don't know how many movies we have in WordPress, I want to generate the fields on the dynamically.

Fortunately I fount the Repeater (beta) field from Gravity Forms.
With that field, the user could add/remove movies as he wants.

Demo and Docs: https://docs.gravityforms.com/repeater-fields/

The problem is, that I need to populate the first field (Dropdown) with the movies CPT in WordPress.

Here's my current code to generate the repeater field in the form:

// Adjust your form ID
add_filter( 'gform_form_post_get_meta_5', 'add_my_field' );
function add_my_field( $form ) {
    $movie_sku = GF_Fields::create( array(
        'type'   => 'text',
        'id'     => 1002, // The Field ID must be unique on the form
        'formId' => $form['id'],
        'required' => true,
        'label'  => 'Movie',
        'class'  => 'col-md-4',
        'pageNumber'  => 1, // Ensure this is correct
    ) );
    $movie_amount = GF_Fields::create( array(
        'type'   => 'text',
        'id'     => 1007, // The Field ID must be unique on the form
        'formId' => $form['id'],
        'required' => true,
        'label'  => 'Amount',
        'pageNumber'  => 1, // Ensure this is correct
    ) );
    $movie_date = GF_Fields::create( array(
        'type'   => 'text',
        'id'     => 1001, // The Field ID must be unique on the form
        'formId' => $form['id'],
        'required' => true,
        'label'  => 'Date',
        'pageNumber'  => 1, // Ensure this is correct
    ) );

    $movie = GF_Fields::create( array(
        'type'             => 'repeater',
        'required'          => true,
        'id'               => 1000, // The Field ID must be unique on the form
        'formId'           => $form['id'],
        'label'            => 'Add movie',
        'addButtonText'    => 'Add Another movie',
        'removeButtonText'=> 'Remove movie',
        'pageNumber'       => 1, // Ensure this is correct
        'fields'           => array( $movie_sku,$movie_amount, $movie_date), // Add the fields here.
    ) );

    $form['fields'][] = $movie;

    return $form;
}

// Remove the field before the form is saved. Adjust your form ID
add_filter( 'gform_form_update_meta_5', 'remove_my_field', 10, 3 );
function remove_my_field( $form_meta, $form_id, $meta_name ) {

    if ( $meta_name == 'display_meta' ) {
        // Remove the Repeater field: ID 1000
        $form_meta['fields'] = wp_list_filter( $form_meta['fields'], array( 'id' => 1000 ), 'NOT' );
    }

    return $form_meta;
}

And here's my code to populate a field with the movies (Custom Post Type) in WordPress:

add_filter( 'gform_pre_render_5', 'populate_posts' );
add_filter( 'gform_pre_validation_5', 'populate_posts' );
add_filter( 'gform_pre_submission_filter_5', 'populate_posts' );
add_filter( 'gform_admin_pre_render_5', 'populate_posts' );
function populate_posts( $form ) {

    foreach ( $form['fields'] as &$field ) {

        if ( $field->type != 'select' || strpos( $field->cssClass, 'populate-movie' ) === false ) {
            continue;
        }

        // you can add additional parameters here to alter the posts that are retrieved
        // more info: http://codex.wordpress.org/Template_Tags/get_posts

        $args = array(
        'orderby'       =>  'title',
        'order'         =>  'ASC',
        'numberposts'   => -1,
        'post_type'     => 'movie',
        'post_status'   => array('publish'),

        );

        $posts = get_posts( $args );

        $choices = array();

        foreach ( $posts as $post ) {

            $choices[] = array(
                'text'  => $post->post_title,
                'value' => $post->post_title
            );
        }

        // update 'Select a Post' to whatever you'd like the instructive option to be
        $field->placeholder = 'Select movie';
        $field->choices = $choices;

    }

    return $form;
}

But how can I combine these two functions and dynamically populate the Dropdown field with the movies?

Body:
I guess I found a solution:

Before the first GF_Fields::create I have to copy the following code from my second function:

$args = array(
        'orderby'       =>  'title',
        'order'         =>  'ASC',
        'numberposts'   => -1,
        'post_type'     => 'movie',
        'post_status'   => array('publish'),

        );

        $posts = get_posts( $args );

        $choices = array();

        foreach ( $posts as $post ) {

            $choices[] = array(
                'text'  => $post->post_title,
                'value' => $post->post_title
            );
        }

Then I have to edit the first GF_Fields::create like this:

$movie_sku = GF_Fields::create( array(
    'type'   => 'select',
    'id'     => 1002, // The Field ID must be unique on the form
    'formId' => $form['id'],
    'required' => true,
    'label'  => 'Movie',
    'choices'  => $choices,
    'pageNumber'  => 1, // Ensure this is correct
) );

The new part is the 'choices'  => $choices, which gets it's data from the code above. And of course I had to change the input type to select: 'type'   => 'select',.


问:
How do I configure Amplify to to use multiple AppSync endpoints?
I need to support authenticated and unauthenticated AppSync requests in a React Native app. Since AppSync only allows one authorization type per API, I am setting up two APIs: one for authenticated users (Cognito User Pools), and one for guests (API Key).

I think to make this work I need to have two distinct AWSAppSyncClient configs in the same app.

```<code>  // authenticated user
  const appSyncAuthenticatedClient = new AWSAppSyncClient({
    url: Config.APPSYNC_AUTHENTICATED_ENDPOINT,
    region: Config.APPSYNC_REGION,
    auth: {
      type: 'AMAZON_COGNITO_USER_POOLS',
      jwtToken: async () =>
        (await Auth.currentSession()).getAccessToken().getJwtToken()
    }
  });

  // guest
  const appSyncUnauthenticatedClient = new AWSAppSyncClient({
    url: Config.APPSYNC_UNAUTHENTICATED_ENDPOINT,
    region: Config.APPSYNC_REGION,
    auth: {
      type: 'API_KEY',
      apiKey: Config.APPSYNC_API_ID
    }
  });
</code>```

and then determine which to use based on whether or not they are logged in

```<code>    Auth.currentAuthenticatedUser()
      .then(user => this.appSyncRunningClient = appSyncAuthenticatedClient)
      .catch(err => this.appSyncRunningClient = appSyncUnauthenticatedClient);

    const App = props => {
      return (
        <ApolloProvider client={this.appSyncRunningClient}>
          <Rehydrated>
              <RootStack/>
            </Root>
          </Rehydrated>
        </ApolloProvider>
      );
    };

    export default App;
</code>```

This fails because currentAuthenticatedUser returns a promise, and I'm stuck at how to resolve a promise at this top level instantiation of the app. I'll also need to swap out this config during auth events.

In what way can I dynamically select and change the ApolloProvider config at startup and authentication events?

答:
This is currently not possible. Until top-level await is officially supported you should create two Apollo clients one for the API and one for the Cognito.

for example: in your App.js

```<code>export default function App(props) {
  const [client, setClient] = useState(null);

  useEffect(() => {
   checkAuth()
  }, []);

  function checkAuth() {
    Auth.currentSession().then(session => {
      const token = session.getIdToken();
      const jwtToken = token.getJwtToken();
      if (typeof jwtToken == "string") {
        const authClientConfig = {
          url: awsmobile.aws_appsync_graphqlEndpoint,
          region: awsmobile.aws_appsync_region,
          disableOffline: true,
          auth: {
            type: AUTH_TYPE.AMAZON_COGNITO_USER_POOLS,
            jwtToken: jwtToken
          }
        }
        const link = ApolloLink.from([createAuthLink(authClientConfig), createSubscriptionHandshakeLink(authClientConfig)]);
        const authClient = new ApolloClient({ link, cache: new InMemoryCache({ addTypename: false }) });
        setClient(authClient);
      } else {
        throw "error";
      }
    }).catch(e => {
      console.log(e);
      const config = {
        url: awsmobile.aws_appsync_graphqlEndpoint,
        region: awsmobile.aws_appsync_region,
        disableOffline: true,
        auth: {
          type: AUTH_TYPE.API_KEY,
          apiKey: awsmobile.aws_appsync_apiKey
        }
      }
      const link = ApolloLink.from([createAuthLink(config), createSubscriptionHandshakeLink(config)]);
      const authClient = new ApolloClient({ link, cache: new InMemoryCache({ addTypename: false }) });
        setClient(authClient);
    })
  }

    if (!client) {
      return "Loading..."
    }

    return (
      <ApolloProvider client={client}>
          ...
      </ApolloProvider>
    );
}`
</code>```

Body:
I need to support authenticated and unauthenticated AppSync requests in a React Native app. Since AppSync only allows one authorization type per API, I am setting up two APIs: one for authenticated users (Cognito User Pools), and one for guests (API Key).

I think to make this work I need to have two distinct AWSAppSyncClient configs in the same app.

  // authenticated user
  const appSyncAuthenticatedClient = new AWSAppSyncClient({
    url: Config.APPSYNC_AUTHENTICATED_ENDPOINT,
    region: Config.APPSYNC_REGION,
    auth: {
      type: 'AMAZON_COGNITO_USER_POOLS',
      jwtToken: async () =>
        (await Auth.currentSession()).getAccessToken().getJwtToken()
    }
  });

  // guest
  const appSyncUnauthenticatedClient = new AWSAppSyncClient({
    url: Config.APPSYNC_UNAUTHENTICATED_ENDPOINT,
    region: Config.APPSYNC_REGION,
    auth: {
      type: 'API_KEY',
      apiKey: Config.APPSYNC_API_ID
    }
  });

and then determine which to use based on whether or not they are logged in

    Auth.currentAuthenticatedUser()
      .then(user => this.appSyncRunningClient = appSyncAuthenticatedClient)
      .catch(err => this.appSyncRunningClient = appSyncUnauthenticatedClient);

    const App = props => {
      return (
        <ApolloProvider client={this.appSyncRunningClient}>
          <Rehydrated>
              <RootStack/>
            </Root>
          </Rehydrated>
        </ApolloProvider>
      );
    };

    export default App;

This fails because currentAuthenticatedUser returns a promise, and I'm stuck at how to resolve a promise at this top level instantiation of the app. I'll also need to swap out this config during auth events.

In what way can I dynamically select and change the ApolloProvider config at startup and authentication events?

Body:
This is currently not possible. Until top-level await is officially supported you should create two Apollo clients one for the API and one for the Cognito.

for example: in your App.js

export default function App(props) {
  const [client, setClient] = useState(null);

  useEffect(() => {
   checkAuth()
  }, []);

  function checkAuth() {
    Auth.currentSession().then(session => {
      const token = session.getIdToken();
      const jwtToken = token.getJwtToken();
      if (typeof jwtToken == "string") {
        const authClientConfig = {
          url: awsmobile.aws_appsync_graphqlEndpoint,
          region: awsmobile.aws_appsync_region,
          disableOffline: true,
          auth: {
            type: AUTH_TYPE.AMAZON_COGNITO_USER_POOLS,
            jwtToken: jwtToken
          }
        }
        const link = ApolloLink.from([createAuthLink(authClientConfig), createSubscriptionHandshakeLink(authClientConfig)]);
        const authClient = new ApolloClient({ link, cache: new InMemoryCache({ addTypename: false }) });
        setClient(authClient);
      } else {
        throw "error";
      }
    }).catch(e => {
      console.log(e);
      const config = {
        url: awsmobile.aws_appsync_graphqlEndpoint,
        region: awsmobile.aws_appsync_region,
        disableOffline: true,
        auth: {
          type: AUTH_TYPE.API_KEY,
          apiKey: awsmobile.aws_appsync_apiKey
        }
      }
      const link = ApolloLink.from([createAuthLink(config), createSubscriptionHandshakeLink(config)]);
      const authClient = new ApolloClient({ link, cache: new InMemoryCache({ addTypename: false }) });
        setClient(authClient);
    })
  }

    if (!client) {
      return "Loading..."
    }

    return (
      <ApolloProvider client={client}>
          ...
      </ApolloProvider>
    );
}`


问:
Suddenly having sql_error_code = 42601 STATEMENT: SET statement_timeout TO ? in logs
So no scripts were running at this point and no where in our app are we setting a timeout. Started happening 2 hours ago, any clue/idea on why/how this happened? Also checked heroku status and no luck either

[AMBER] [10-1] sql_error_code = 42601 ERROR:  syntax error at or near "?" at character 26

[AMBER] [10-2]  sql_error_code = 42601 STATEMENT: SET statement_timeout TO ?

答: We also saw these errors, across all our apps, from 7:19 to 9:45 am.  It seems most likely to be a Heroku thing, although the Heroku status page has not yet reported anything, but then again, it's not an outage so it might never.</p>


问:
Can I use double equal in JavaScript if one of the elements is a string?
I'm newbie in JS, I know that == double comparation for equality and === triple one for equality and type. My teacher says that I should use always triple. However, I don't see any down effect if I use double equal when one of the elements is a string.

'' == 0 // true
'10' == 10 // true
'dog' == 'cat' // false
```

So, I'm using always double equal when some of the element is a string (avoiding this 'false' == false) and triple when I'm detecting null or undefined.

Is there any down side for my approach?

I checked this previous answer: Which equals operator (== vs ===) should be used in JavaScript comparisons?

答:
If you read the linked answer, you also read this chunk of code involving strings:

```<code>'' == '0'           // false
0 == ''             // true
0 == '0'            // true

false == 'false'    // false
false == '0'        // true
</code>```

Those are string, but still the behaviour is not exactly what you may expect. Indeed using === can make your life easier as your teacher said :)

Body:
I'm newbie in JS, I know that == double comparation for equality and === triple one for equality and type. My teacher says that I should use always triple. However, I don't see any down effect if I use double equal when one of the elements is a string.

'' == 0 // true
'10' == 10 // true
'dog' == 'cat' // false

So, I'm using always double equal when some of the element is a string (avoiding this 'false' == false) and triple when I'm detecting null or undefined.

Is there any down side for my approach?

I checked this previous answer: Which equals operator (== vs ===) should be used in JavaScript comparisons?

Body:
If you read the linked answer, you also read this chunk of code involving strings:

'' == '0'           // false
0 == ''             // true
0 == '0'            // true

false == 'false'    // false
false == '0'        // true

Those are string, but still the behaviour is not exactly what you may expect. Indeed using === can make your life easier as your teacher said :)


问:
Adding a watermark to a listview
Is it possible to have a watermark background for a listview control in Android? Basically I want a stationary background image with a listview on top of the image. When I scroll, I want the listview to scroll like normal, but the image stay stationary. Since there doesn't seem to be any z-order in Android, I'm wondering if this is possible.</p>

答:
Have you tried ListView.setBackgroundResource(int resId)?

Or for the whole screen use...

```<code>getWindow().getDecorView().setBackgroundResource(int resId)
</code>```

You'll need to use setCacheColorHint(0) to prevent 'blackouts' when scrolling the list though.

Title: Adding a watermark to a listview

Body:
Have you tried ListView.setBackgroundResource(int resId)?

Or for the whole screen use...

getWindow().getDecorView().setBackgroundResource(int resId)

You'll need to use setCacheColorHint(0) to prevent 'blackouts' when scrolling the list though.


问:
remove special char from rows in pandas python
I have the following dataframe...unable to remove the "-" char and trim it to the right "int" number for the cell:

```<code>    Branch   Market Company     Brand Name  MRP 2020-05-15 2020-05-19 2020-05-22 2020-05-26
1      USA      abc     xqz           A     165    180-190    170-180        170        170
2      USA      abc     xqz           B     165    180-190    170-180        170        170
3      USA      abc     xqz           C     100        120    110-120        120        120
4      USA      abc     xqz           D      95        110        100        100        110
5      USA      abc     xqz           E      59         70         70         70         70

</code>```

want the following dataframe to plot a scatter plot with brand name in x-axis and MRP in y axis.

```<code>    Branch   Market Company     Brand Name  MRP 2020-05-15 2020-05-19 2020-05-22 2020-05-26
1      USA      abc     xqz           A     165        185        175        170        170
2      USA      abc     xqz           B     165        185        175        170        170
3      USA      abc     xqz           C     100        120        115        120        120
4      USA      abc     xqz           D      95        110        100        100        110
5      USA      abc     xqz           E      59         70         70         70         70

</code>```

can you plz help. tried many codes, but unable to get the desired result/df.

Body:
I have the following dataframe...unable to remove the "-" char and trim it to the right "int" number for the cell:

    Branch   Market Company     Brand Name  MRP 2020-05-15 2020-05-19 2020-05-22 2020-05-26
1      USA      abc     xqz           A     165    180-190    170-180        170        170
2      USA      abc     xqz           B     165    180-190    170-180        170        170
3      USA      abc     xqz           C     100        120    110-120        120        120
4      USA      abc     xqz           D      95        110        100        100        110
5      USA      abc     xqz           E      59         70         70         70         70

want the following dataframe to plot a scatter plot with brand name in x-axis and MRP in y axis.

    Branch   Market Company     Brand Name  MRP 2020-05-15 2020-05-19 2020-05-22 2020-05-26
1      USA      abc     xqz           A     165        185        175        170        170
2      USA      abc     xqz           B     165        185        175        170        170
3      USA      abc     xqz           C     100        120        115        120        120
4      USA      abc     xqz           D      95        110        100        100        110
5      USA      abc     xqz           E      59         70         70         70         70

can you plz help. tried many codes, but unable to get the desired result/df.

Body:
with np.where and str.split:

df['2020-05-15'] = np.where((df['2020-05-15'].str.contains('-')),
                            (df['2020-05-15'].str.split('-').str[0].astype(float) + df['2020-05-15'].str.split('-').str[1].astype(float)) / 2,
                            df['2020-05-15'])
df['2020-05-19'] = np.where((df['2020-05-19'].str.contains('-')),
                            (df['2020-05-19'].str.split('-').str[0].astype(float) + df['2020-05-19'].str.split('-').str[1].astype(float)) / 2,
                            df['2020-05-19'])
df


问:
name 'doc2vec' is not defined
I am trying to use doc2vec for text classification but after importing when i am trying to use it inside a function its says doc2vec in not defined. Please help me to identify which all libraries should I be installing to use doc2vec.

here I have 2 columns called Action(Text or sentences) and Category(actual tags)

```<code>from gensim.models import Doc2Vec
import gensim
from gensim.models.doc2vec import TaggedDocument
def label_sentences(corpus, label_type):
    labeled = []
    for i, v in enumerate(corpus):
        label = label_type + '_' + str(i)
        labeled.append(doc2vec.TaggedDocument(v.split(), [label]))
    return labeled
X_train, X_test, y_train, y_test = train_test_split(df.Action, df.Category, random_state=0, test_size=0.3)
X_train = label_sentences(X_train, 'Train')

Error
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-66-d20e5f21684d> in <module>
----> 1 X_train = label_sentences(X_train, 'Train')

<ipython-input-53-bca3c695cfb6> in label_sentences(corpus, label_type)
      8     for i, v in enumerate(corpus):
      9         label = label_type + '_' + str(i)
---> 10         labeled.append(doc2vec.TaggedDocument(v.split(), [label]))
     11     return labeled

NameError: name 'doc2vec' is not defined
</code>```

答:
```<code>def label_sentences(corpus, label_type):
    labeled = []
    for i, v in enumerate(corpus):
        label = label_type + '_' + str(i)
        labeled.append(TaggedDocument(v.split(), [label]))
    return labeled
</code>```

Title: name 'doc2vec' is not defined

Body:
I am trying to use doc2vec for text classification but after importing when i am trying to use it inside a function its says doc2vec in not defined. Please help me to identify which all libraries should I be installing to use doc2vec.

here I have 2 columns called Action(Text or sentences) and Category(actual tags)

from gensim.models import Doc2Vec
import gensim
from gensim.models.doc2vec import TaggedDocument
def label_sentences(corpus, label_type):
    labeled = []
    for i, v in enumerate(corpus):
        label = label_type + '_' + str(i)
        labeled.append(doc2vec.TaggedDocument(v.split(), [label]))
    return labeled
X_train, X_test, y_train, y_test = train_test_split(df.Action, df.Category, random_state=0, test_size=0.3)
X_train = label_sentences(X_train, 'Train')

Error
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-66-d20e5f21684d> in <module>
----> 1 X_train = label_sentences(X_train, 'Train')

<ipython-input-53-bca3c695cfb6> in label_sentences(corpus, label_type)
      8     for i, v in enumerate(corpus):
      9         label = label_type + '_' + str(i)
---> 10         labeled.append(doc2vec.TaggedDocument(v.split(), [label]))
     11     return labeled

NameError: name 'doc2vec' is not defined