问:
How to appropriately use selenium and parallel processing
I am trying to scrape a bunch of urls using Selenium and BeautifulSoup. Because they are thousands and the processing that I need to do is complex and uses a lot of CPU, I need to do multiprocessing (as opposed to multithreading).

The problem right now is that I am opening and closing a Chromedriver instance once for each URL, which adds a lot of overhead and makes the process slow.

What I want to do is instead have a chromedriver instance for each subprocess, only open it once and keep it open until the subprocess finishes. However, my attempts to do it have been unsuccessful.

I tried creating the instances in the main process, dividing the set of URLS into the number of processes and sending each subprocess its subset of urls and a single driver as arguments, so that each subprocess would cycle through the urls that it got. But that didn't run at all, it did not give either results or error.

A solution similar to this with multiprocessing instead of threading got me a recursion-limit error (changing the recursion limit using sys would not help at all).

What else could I do to make this faster?

Below are the relevant parts of the code that actually works.

```<code>from bs4 import BeautifulSoup
import re
import csv
from datetime import datetime
import numpy as np
import concurrent.futures
import multiprocessing
from selenium import webdriver

options = webdriver.ChromeOptions()
options.add_argument('--headless')
options.add_argument('--window-size=1920x1080')
options.add_argument('--no-sandbox')

def runit(row):
    driver = webdriver.Chrome(chrome_options=options)
    driver.set_page_load_timeout(500)
    driver.implicitly_wait(500)
    url = row[1]
    driver.get(url)
    html_doc = driver.page_source
    driver.quit()
    soup = BeautifulSoup(html_doc, 'html.parser')

    # Some long processing code that uses the soup object and generates the result object that is returned below with what I want

    return result, row

if __name__ == '__main__':
    multiprocessing.freeze_support()
    print(datetime.now())
    # The file below has the list of all the pages that I need to process, along with some other pieces of relevant data
    # The URL is the second field in the csv file
    with open('D:\\Users\\shina\\OneDrive\\testTiles.csv') as csv_file:
        csv_reader = csv.reader(csv_file, delimiter=',')
        # I have 4 cores but Windows shows 8 logical processors, I have tried other numbers below 8, but 8 seems to bring the fastest results
        with concurrent.futures.ProcessPoolExecutor(max_workers=8) as executor:
            results = executor.map(runit, csv_reader)

        #At a later time I will code here what I will do with the results after all the processes finish.

    print(datetime.now())
</code>```

答:
At end of the day, you need more compute power to be running these types of test   i.e. multiple computers, browerstack, saucelabs etc. Also, look into Docker where you can use your grid implementation to run tests on more than one browser. </p>

<p>https://github.com/SeleniumHQ/docker-selenium </p>

Body:
I am trying to scrape a bunch of urls using Selenium and BeautifulSoup. Because they are thousands and the processing that I need to do is complex and uses a lot of CPU, I need to do multiprocessing (as opposed to multithreading).

The problem right now is that I am opening and closing a Chromedriver instance once for each URL, which adds a lot of overhead and makes the process slow.

What I want to do is instead have a chromedriver instance for each subprocess, only open it once and keep it open until the subprocess finishes. However, my attempts to do it have been unsuccessful.

I tried creating the instances in the main process, dividing the set of URLS into the number of processes and sending each subprocess its subset of urls and a single driver as arguments, so that each subprocess would cycle through the urls that it got. But that didn't run at all, it did not give either results or error.

A solution similar to this with multiprocessing instead of threading got me a recursion-limit error (changing the recursion limit using sys would not help at all).

What else could I do to make this faster?

Below are the relevant parts of the code that actually works.

from bs4 import BeautifulSoup
import re
import csv
from datetime import datetime
import numpy as np
import concurrent.futures
import multiprocessing
from selenium import webdriver

options = webdriver.ChromeOptions()
options.add_argument('--headless')
options.add_argument('--window-size=1920x1080')
options.add_argument('--no-sandbox')

def runit(row):
    driver = webdriver.Chrome(chrome_options=options)
    driver.set_page_load_timeout(500)
    driver.implicitly_wait(500)
    url = row[1]
    driver.get(url)
    html_doc = driver.page_source
    driver.quit()
    soup = BeautifulSoup(html_doc, 'html.parser')

    # Some long processing code that uses the soup object and generates the result object that is returned below with what I want

    return result, row

if __name__ == '__main__':
    multiprocessing.freeze_support()
    print(datetime.now())
    # The file below has the list of all the pages that I need to process, along with some other pieces of relevant data
    # The URL is the second field in the csv file
    with open('D:\\Users\\shina\\OneDrive\\testTiles.csv') as csv_file:
        csv_reader = csv.reader(csv_file, delimiter=',')
        # I have 4 cores but Windows shows 8 logical processors, I have tried other numbers below 8, but 8 seems to bring the fastest results
        with concurrent.futures.ProcessPoolExecutor(max_workers=8) as executor:
            results = executor.map(runit, csv_reader)

        #At a later time I will code here what I will do with the results after all the processes finish.

    print(datetime.now())

Body:
At end of the day, you need more compute power to be running these types of test   i.e. multiple computers, browerstack, saucelabs etc. Also, look into Docker where you can use your grid implementation to run tests on more than one browser.

https://github.com/SeleniumHQ/docker-selenium


来源: stackexchange

问:
How to send a Get request in iOS?
I am making a library to get response from a particular URL with specified data and method type. For this, I am making a request with url. But when I set its method type, it shows an exception of unrecognized selector send in [NSURLRequest setHTTPMethod:]
I am setting it as

```<code>[requestObject setHTTPMethod:@"GET"];
</code>```

Tell me what could be the problem. Also provide me the code if you have.

答: Make sure your requestObject is of type NSMutableURLRequest.

ContentLicense: CC BY-SA 3.0

Title: How to send a Get request in iOS?

Body:
I am making a library to get response from a particular URL with specified data and method type. For this, I am making a request with url. But when I set its method type, it shows an exception of unrecognized selector send in [NSURLRequest setHTTPMethod:]
I am setting it as

[requestObject setHTTPMethod:@"GET"];

Tell me what could be the problem. Also provide me the code if you have.


问:
Custom font on simple html website will not load
I have been following code and examples online to try and use a custom font on my very basic html website. If it matters, I am using django.

Files of note:

aurebesh_translator.html

```<code><!DOCTYPE html>
<html>
    <link rel="stylesheet" type="text/css" href="main.css">
    <p>This should be in aurebesh</p>
</html>
</code>```

main.css

```<code>@font-face {
    font-family: "aurebesh";
    src: url(aurebesh.ttf);
    font-style: normal;
    font-weight: 100;
}

p {
    font-family: aurebesh;
    font-weight: 100;
}
</code>```

These are arranged as follows:

```<code>| templates
| - ...
| - main.css
| - aurebesh_translator.html
| - fonts
| -- aurebesh.ttf

</code>```

... where the aurebesh.ttf file is the associated font file for the font I want to use.

From what I can tell online, this seems to be the way it is supposed to be formatted to use my custom font. The weird thing is, if I just copy the above files to my desktop (so that only main.css, aurebesh_translator.html, and fonts/aurebesh.ttf are present) and run the aurebesh_translator.html in a browser, it loads and uses the font successfully! This is super weird to me, because when I include these files in the context of the rest of my website's files, it somehow stops working! I have tried opening it in chrome as well as firefox and neither work (they both just load in without my custom font).

This is the error I get from my terminal running my server when I try to access the page:

```<code>[01/Jun/2020 00:08:18] "GET /articles/aurebesh_translator HTTP/1.1" 200 127
Not Found: /articles/main.css
[01/Jun/2020 00:08:18] "GET /articles/main.css HTTP/1.1" 404 4061
</code>```

How can I fix this error?

答:
In static folder add these files,

main.css

aurebesh.ttf

fonts

As you are using django, static files like css or images cannot be used directly in html. You have to load the static file in html and also change the path of the file.

<!DOCTYPE html>

{% load static %}
    <link rel="stylesheet" type="text/css" href="{% static 'main.css' %}">

This should be in aurebesh

```

ContentLicense: CC BY-SA 4.0

Body:
I have been following code and examples online to try and use a custom font on my very basic html website. If it matters, I am using django.

Files of note:

aurebesh_translator.html

<!DOCTYPE html>

    <link rel="stylesheet" type="text/css" href="main.css">

This should be in aurebesh

main.css

@font-face {
    font-family: "aurebesh";
    src: url(aurebesh.ttf);
    font-style: normal;
    font-weight: 100;
}

p {
    font-family: aurebesh;
    font-weight: 100;
}

These are arranged as follows:

| templates
| - ...
| - main.css
| - aurebesh_translator.html
| - fonts
| -- aurebesh.ttf

... where the aurebesh.ttf file is the associated font file for the font I want to use.

From what I can tell online, this seems to be the way it is supposed to be formatted to use my custom font. The weird thing is, if I just copy the above files to my desktop (so that only main.css, aurebesh_translator.html, and fonts/aurebesh.ttf are present) and run the aurebesh_translator.html in a browser, it loads and uses the font successfully! This is super weird to me, because when I include these files in the context of the rest of my website's files, it somehow stops working! I have tried opening it in chrome as well as firefox and neither work (they both just load in without my custom font).

This is the error I get from my terminal running my server when I try to access the page:

[01/Jun/2020 00:08:18] "GET /articles/aurebesh_translator HTTP/1.1" 200 127
Not Found: /articles/main.css
[01/Jun/2020 00:08:18] "GET /articles/main.css HTTP/1.1" 404 4061

How can I fix this error?

Body:
In static folder add these files,

main.css

aurebesh.ttf

fonts

As you are using django, static files like css or images cannot be used directly in html. You have to load the static file in html and also change the path of the file.

<!DOCTYPE html>
<html>
{% load static %}
    <link rel="stylesheet" type="text/css" href="{% static 'main.css' %}">
    <p>This should be in aurebesh</p>
</html>


问:
How to add quotes to gval expression
I read JSON file to get expression to evaluate by gval library. I want it to compile JSON string having values in a string slice.

```<code>func main() {
    jsonConfig := `{"exp": "\"{\" + \"\\u0022\" + fields[0] + \"\\u0022\" + \": \" + \"\\u0022\" + fields[1] + \"\\u0022\" + \"}\""}`

    m := map[string]string{}
    err := json.Unmarshal([]byte(jsonConfig), &m)

    values := []string{"fieldA", "valA"}
    res, err := gval.Evaluate(m["exp"], map[string]interface{}{"fields": values})

    if err != nil {
        fmt.Printf("failed to evaluate: %v\n", err)
        return
    }

    fmt.Printf("success: (%T) %v\n", res, res)
}
</code>```

The result is

```<code>success: (string) {"fieldA": "valA"}
</code>```

The problem is to add quotes to expression. I used \u0022 but it seems to me awkward. Is there any other way?

答:
I'm not sure the unmarshal you are doing is necessary, you should be able to just modify the config and pass it directly into gval.Evaluate - see below:

```

    main() {
        config := `"{\"" + fields[0] + "\":\" " + fields[1] + "\"}"`
        values := []string{"fieldA", "valA"}
        res, err := gval.Evaluate(config, map[string]interface{}{"fields": values})
        if err != nil {
            fmt.Printf("failed to evaluate: %v\n", err)
            return
        }
        fmt.Printf("success: (%T) %v\n", res, res)
    }

```

The result will be:

```

    success: (string) {"fieldA":" valA"}

```

Title: How to add quotes to gval expression

Body:
I read JSON file to get expression to evaluate by gval library. I want it to compile JSON string having values in a string slice.

func main() {
    jsonConfig := `{"exp": "\"{\" + \"\\u0022\" + fields[0] + \"\\u0022\" + \": \" + \"\\u0022\" + fields[1] + \"\\u0022\" + \"}\""}`

    m := map[string]string{}
    err := json.Unmarshal([]byte(jsonConfig), &m)

    values := []string{"fieldA", "valA"}
    res, err := gval.Evaluate(m["exp"], map[string]interface{}{"fields": values})

    if err != nil {
        fmt.Printf("failed to evaluate: %v\n", err)
        return
    }

    fmt.Printf("success: (%T) %v\n", res, res)
}

The result is

success: (string) {"fieldA": "valA"}

The problem is to add quotes to expression. I used \u0022 but it seems to me awkward. Is there any other way?

Body:
I'm not sure the unmarshal you are doing is necessary, you should be able to just modify the config and pass it directly into gval.Evaluate - see below:

    main() {
        config := `"{\"" + fields[0] + "\":\" " + fields[1] + "\"}"`
        values := []string{"fieldA", "valA"}
        res, err := gval.Evaluate(config, map[string]interface{}{"fields": values})
        if err != nil {
            fmt.Printf("failed to evaluate: %v\n", err)
            return
        }
        fmt.Printf("success: (%T) %v\n", res, res)
    }

The result will be:

    success: (string) {"fieldA":" valA"}


问:
How to change navbar colour after scrolling?
I am trying to chnage the colour of my navbar from transparent to black after the user scrolls down. However, my javascript does not seem to work as nothing happens. I have looked at several videos and similar questions and none have worked

HTML

        <input type="checkbox" />

Home

Submit Image

Search Image

Login/Sign up

```

<p>JS</p>

```
```

<p>CSS</p>

```.bg-transparent{
  height: 90px;
  }

.bg-transparent.scrolled{
  background: black !important;
}
```

答:
Your JavaScript code is incorrect.

Test with this code :

```<code>  window.onscroll = function () { scrollHeaderHandler() };

  function scrollHeaderHandler() {
    if (window.pageYOffset > 100) {
      $('nav').addClass('scrolled');
    } else {
      $('nav').removeClass('scrolled');
    }
  }
</code>```

Body:
I am trying to chnage the colour of my navbar from transparent to black after the user scrolls down. However, my javascript does not seem to work as nothing happens. I have looked at several videos and similar questions and none have worked

HTML

        <input type="checkbox" />

Home

Submit Image

Search Image

Login/Sign up

JS

CSS

.bg-transparent{
  height: 90px;
  }

.bg-transparent.scrolled{
  background: black !important;
}

Body:
Your JavaScript code is incorrect.

Test with this code :

  window.onscroll = function () { scrollHeaderHandler() };

  function scrollHeaderHandler() {
    if (window.pageYOffset > 100) {
      $('nav').addClass('scrolled');
    } else {
      $('nav').removeClass('scrolled');
    }
  }


问:
Elasticsearch method not being found in spring boot
I have been stuck with this issue for a while now and any assistance is appreciated. I am running Spring Boot version 2.2.0 with the ElasticSearch high-level REST Client version 6.4.3 and using version 3.2.0 for the Spring-Data-Elasticsearch version. I am getting the error below. I have tried the following attempts to fix but none do.

Change Spring Boot Version multiple times

Change ES version multiple times

I have cleared my .m2 folder and redownloaded the maven dependencies multiple times.

The issue I am getting below is

An attempt was made to call a method that does not exist. The attempt was made from the following location:

org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate.putMapping(ElasticsearchRestTemplate.java:292)

The following method did not exist:

org.elasticsearch.client.IndicesClient.putMapping(Lorg/elasticsearch/action/admin/indices/mapping/put/PutMappingRequest;Lorg/elasticsearch/client/RequestOptions;)Lorg/elasticsearch/action/support/master/AcknowledgedResponse;

The method's class, org.elasticsearch.client.IndicesClient, is available from the following locations:

jar:file:/Users/user/.m2/repository/org/elasticsearch/client/elasticsearch-rest-high-level-client/6.4.3/elasticsearch-rest-high-level-client-6.4.3.jar!/org/elasticsearch/client/IndicesClient.class

It was loaded from the following location:
    file:/Users/user/.m2/repository/org/elasticsearch/client/elasticsearch-rest-high-level-client/6.4.3/elasticsearch-rest-high-level-client-6.4.3.jar

Action:
Correct the classpath of your application so that it contains a single, compatible version of org.elasticsearch.client.IndicesClient

My POM is below

```<code>    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-elasticsearch</artifactId>
        <version>3.2.0</version>
    </dependency>
</code>```

Any help is appreciated. I am sure it has to deal with compatibility issues but not sure which. Thanks all!

Update

I was able to get it run sucessfully by changing my elasticsearch version to 6.7.0. But now I am receiving the following error

```<code>org.elasticsearch.ElasticsearchStatusException: Elasticsearch exception [type=index_not_found_exception, reason=no such index]
</code>```

My POM looks like this below now also.

```<code>    <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>6.70</version>
        </dependency>

    <dependency>
        <groupId>org.elasticsearch.client</groupId>
        <artifactId>elasticsearch-rest-high-level-client</artifactId>
        <version>6.70</version>
    </dependency>

    <dependency>
        <groupId>org.elasticsearch.client</groupId>
        <artifactId>elasticsearch-rest-client</artifactId>
        <version>6.70</version>
    </dependency>
</code>```

答:
Previous issue of method that does not exist. was resolved by changing the elasticsearch version to 6.7.0.

To avoid these incompatibility issues its always recommend to use the same version of elasticsearch server and its client.

Body:
I have been stuck with this issue for a while now and any assistance is appreciated. I am running Spring Boot version 2.2.0 with the ElasticSearch high-level REST Client version 6.4.3 and using version 3.2.0 for the Spring-Data-Elasticsearch version. I am getting the error below. I have tried the following attempts to fix but none do.

Change Spring Boot Version multiple times

Change ES version multiple times

I have cleared my .m2 folder and redownloaded the maven dependencies multiple times.

The issue I am getting below is

An attempt was made to call a method that does not exist. The attempt was made from the following location:

org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate.putMapping(ElasticsearchRestTemplate.java:292)

The following method did not exist:

org.elasticsearch.client.IndicesClient.putMapping(Lorg/elasticsearch/action/admin/indices/mapping/put/PutMappingRequest;Lorg/elasticsearch/client/RequestOptions;)Lorg/elasticsearch/action/support/master/AcknowledgedResponse;

The method's class, org.elasticsearch.client.IndicesClient, is available from the following locations:

jar:file:/Users/user/.m2/repository/org/elasticsearch/client/elasticsearch-rest-high-level-client/6.4.3/elasticsearch-rest-high-level-client-6.4.3.jar!/org/elasticsearch/client/IndicesClient.class

It was loaded from the following location:
    file:/Users/user/.m2/repository/org/elasticsearch/client/elasticsearch-rest-high-level-client/6.4.3/elasticsearch-rest-high-level-client-6.4.3.jar

Action:
Correct the classpath of your application so that it contains a single, compatible version of org.elasticsearch.client.IndicesClient

My POM is below

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-elasticsearch</artifactId>
        <version>3.2.0</version>
    </dependency>

Any help is appreciated. I am sure it has to deal with compatibility issues but not sure which. Thanks all!

Update

I was able to get it run sucessfully by changing my elasticsearch version to 6.7.0. But now I am receiving the following error

org.elasticsearch.ElasticsearchStatusException: Elasticsearch exception [type=index_not_found_exception, reason=no such index]

My POM looks like this below now also.

    <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>6.70</version>
        </dependency>

    <dependency>
        <groupId>org.elasticsearch.client</groupId>
        <artifactId>elasticsearch-rest-high-level-client</artifactId>
        <version>6.70</version>
    </dependency>

    <dependency>
        <groupId>org.elasticsearch.client</groupId>
        <artifactId>elasticsearch-rest-client</artifactId>
        <version>6.70</version>
    </dependency>


问:
return findViewById() in viewbinding
I am trying to optimize old code. And I am trying to replace findviewbyid with viewbinding.
But how do I return viewbinding id instead of findviewbyid?

```<code>private TextView getTextView(int id){
        return (TextView) findViewById(id);
}
</code>```

This is the old code. But I want to apply viewbinding. I want it to work something like this. As I have no idea how to do it.

```<code>private TextView getTextView(int id){
        return sampleViewBinding(id);
}
</code>```

How can I achieve this?

答:
If your layout file name is fragment_dashboard.xml and has within a textview with an Id userNameTvId, then you normally do this without using data binding:

```<code>val view = inflater.inflate(R.layout.fragment_dashboard, container, false)
val textview = view.findViewById(R.id.userNameTvId)
</code>```

but with viewBinding it is done by chaining. this textview is acceptable through the binding object. The above will be rewritten like this using viewBinding:

```<code>val binding = FragmentDashboardBinding.inflate(inflater)
binding.userNameTvId

// to pass a value you can just do
binding.userNameTvId = "SomeOne"

val view = binding.root
</code>```

Title: return findViewById() in viewbinding

Body:
I am trying to optimize old code. And I am trying to replace findviewbyid with viewbinding.
But how do I return viewbinding id instead of findviewbyid?

private TextView getTextView(int id){
        return (TextView) findViewById(id);
}

This is the old code. But I want to apply viewbinding. I want it to work something like this. As I have no idea how to do it.

private TextView getTextView(int id){
        return sampleViewBinding(id);
}

How can I achieve this?

Body:
If your layout file name is fragment_dashboard.xml and has within a textview with an Id userNameTvId, then you normally do this without using data binding:

val view = inflater.inflate(R.layout.fragment_dashboard, container, false)
val textview = view.findViewById(R.id.userNameTvId)

but with viewBinding it is done by chaining. this textview is acceptable through the binding object. The above will be rewritten like this using viewBinding:

val binding = FragmentDashboardBinding.inflate(inflater)
binding.userNameTvId

// to pass a value you can just do
binding.userNameTvId = "SomeOne"

val view = binding.root


问:
Python Matplotlib: How to disable Constrained Layout but keep the axes position?
I've created a (3,2) subplots and forced them in constrained_layout=True.

Then I wanted to disable the constrained_layout with .set_constrained_layout(False) due to performance issues, but I 'd like to keep the axes positions.

I tried to get the positions in constrained layout state, and then apply these positions to the axes after setting constrained_layout to False, following these instructions, but it doesn't work.

With the code below, I expected to obtain the following figure, but I ended up with the one below it.

What am I missing?

```<code>import matplotlib.pyplot as plt

fig, ax = plt.subplots(3,2,constrained_layout =True)

mng = plt.get_current_fig_manager()
mng.window.showMaximized()
fig.canvas.draw()

bounds = [ex.get_position().bounds for ex in fig.axes]

fig.set_constrained_layout(False)

for i in range(len(fig.axes)):
    fig.axes[i].set_position(bounds[i])

fig.canvas.draw()
</code>```

答:
Is it wrong to adjust the vertical and horizontal in the subplot?</p>

```<code>fig, ax = plt.subplots(3,2)
fig.subplots_adjust(wspace=0.3, hspace=0.3)
</code>```

Body:
I've created a (3,2) subplots and forced them in constrained_layout=True.

Then I wanted to disable the constrained_layout with .set_constrained_layout(False) due to performance issues, but I 'd like to keep the axes positions.

I tried to get the positions in constrained layout state, and then apply these positions to the axes after setting constrained_layout to False, following these instructions, but it doesn't work.

With the code below, I expected to obtain the following figure, but I ended up with the one below it.

What am I missing?

import matplotlib.pyplot as plt

fig, ax = plt.subplots(3,2,constrained_layout =True)

mng = plt.get_current_fig_manager()
mng.window.showMaximized()
fig.canvas.draw()

bounds = [ex.get_position().bounds for ex in fig.axes]

fig.set_constrained_layout(False)

for i in range(len(fig.axes)):
    fig.axes[i].set_position(bounds[i])

fig.canvas.draw()

Body:
Is it wrong to adjust the vertical and horizontal in the subplot?

fig, ax = plt.subplots(3,2)
fig.subplots_adjust(wspace=0.3, hspace=0.3)


问:
How to debug a Java maven spring-boot app in vs code?
I was able to debug a simple Java hello world. The first step was to "compile" with javac -g. I looked up how I would acomplish the same with maven and found http://docs.spring.io/spring-boot/docs/current/maven-plugin/examples/run-debug.html, but those instructions are for running the application and wait for a debugger to connect.

I also tried to use target/classes for classpath in  launch.json. The debugger complains that it cannot find a file in the root directory /, but it runs. Althought the debugger is running, the application is not responding to HTTP requests.

Is there a mvn command to compile the application with javac -g and produce a .class the debugger is able to run successfully?

答:
Assuming you've installed the collection package Java Extension Pack by Microsoft debugging Maven Spring Boot applications seems to work right-out-of-the-box.

Launch code from the project's root directory and "Start Debugging".  There are multiple ways to launch the debbugger -- the most straightforward is to just hit F5 and, if it asks, select Java.

Under nominal conditions this triggers the following steps:

Your application is compiled into class files

It finds and launches your application's main function -- which should include SpringApplication.run()

The application runs (with breakpoints enabled) and log output is sent to the TERMINAL panel.

Related links:

https://code.visualstudio.com/docs/java/java-spring-boot

How can I fix build failed, do you want to continue? in vscode


问:
how to Reduce load time caused by multiple requests
I am developing a news aggregator website, in have added 24 publishers in it, all the publishers data is present in xml files, so i am calling them using ajax. But it is taking 30 sec to load the page.I have four sections in my webpage(for you, technology, politics,MOvies/tv) for each i have a external JS file. These files are requesting data. PLZ help me reduce the page load time, also suggest some  stratergies.

```<code>//technology JS file code sample
  $.when($.get('https://cors-anywhere.herokuapp.com/https://feed.cnet.com/feed/topics/sci-tech'), $.get('https://cors-anywhere.herokuapp.com/https://in.mashable.com/tech.xml')).then(function(r1, r2) {
        // console.log(r1[0]);
        // console.log(r2[0]);
        // cnet article
        $(r1[0]).find('item').each(function(i, j) {
            title = $(j).find('title').text();
            description = $(j).find('description').text();
            link = $(j).find('link').text();
            thumbnail = $(j).find('[url]').attr('url');
            newsname = "Cnet";
            logo = "http://i.i.cbsi.com/cnwk.1d/i/ne/gr/prtnr/CNET_Logo_150.gif";

            articlestech(i, title, description, link, thumbnail, newsname, logo);

        });
        //Mashable articles
        $(r2[0]).find('item').each(function(i, j) {
            title = $(j).find('title').text();
            description = $(j).find('description').text();
            //pos3 = description.indexOf("</a>");
            // des = description.substring(pos3 + 2);
            // thumbnail = $(j).find('image').text();
            link = $(j).find('link').text();
            var pos2 = description.indexOf("width");
            var pos1 = description.indexOf("src=");
            thumbnail = description.substring(pos1 + 5, pos2 - 2);
            newsname = "Mashable India Tech";
            logo = "https://media.glassdoor.com/sqll/255718/mashable-squarelogo-1430326903133.png";
            des = "";
            articlestech(i, title, des, link, thumbnail, newsname, logo);

        });}) ;

//movies/tv shows code sample
 $.ajax({
            type: "GET",
            url: "https://cors-anywhere.herokuapp.com/https://www.cinemablend.com/rss/topic/reviews/movies",
            dataType: "xml",
            success: function(xml) {
                $(r1[0]).find('item').each(function(i, j) {
                    title = $(j).find('title').text();
                    description = $(j).find('description').text() + "...";
                    link = $(j).find('link').text();
                    //console.log(link);
                    thumbnail = $(j).find('enclosure').attr('url');
                    //console.log(thumbnail);
                    newsname = "Cinemablend";
                    logo = "https://s3.amazonaws.com/media.muckrack.com/groups/icons/cinemablend.jpeg";

                    articlestech(i, title, description, link, thumbnail, newsname, logo);
                });
            }
        });
        $.ajax({
            type: "GET",
            url: "https://cors-anywhere.herokuapp.com/https://www.cinejosh.com/rss-feed/1/review.html",
            dataType: "xml",
            success: function(xml) {
                $(xml).find('item').each(function(i, j) {
                    title = $(j).find('title').text();
                    //des = $(j).find('description').text();
                    link = $(j).find('link').text();
                    description = "";
                    thumbnail = $(j).find('[url]').attr('url');;
                    console.log(thumbnail);
                    newsname = "CineJosh";
                    logo = "https://www.cinejosh.com/gallereys/others/normal/cinejosh_logo_1902160805/cinejosh_logo_1902160805_01.jpg";

                    articlestech(i, title, description, link, thumbnail, newsname, logo);
                });
            }
        });
</code>```

Rest two JS files has same code structure.HOW TO REDUCE LOAD TIME.

答:
The problem is that you are waiting for all the six requests to return to start doing something with the responses. As I can see from the code snippet you provided the requests does not depend on each other, so you can do all of them separeted and as soon as the first request finishes the user will be able to see the result in the screen.

So, this:

```<code>$.when(
  $.get('https://cors-anywhere.herokuapp.com/https://feed.cnet.com/feed/topics/sci-tech'),
  $.get('https://cors-anywhere.herokuapp.com/https://in.mashable.com/tech.xml'),
  $.get('https://www.theverge.com/rss/tech/index.xml'),
  $.get('https://cors-anywhere.herokuapp.com/https://www.buzzfeed.com/tech.xml'),
  $.get('https://cors-anywhere.herokuapp.com/https://www.cnbc.com/id/19854910/device/rss/rss.html'),
  $.get('https://cors-anywhere.herokuapp.com/https://www.engadget.com/rss.xml'))
</code>```

Needs to be something like this:

```<code>$.when($.get('https://cors-anywhere.herokuapp.com/https://feed.cnet.com/feed/topics/sci-tech')).then(function(r1) {
    $(r1[0]).find('item').each(function(i, j) {
        title = $(j).find('title').text();
        description = $(j).find('description').text();
        link = $(j).find('link').text();
        thumbnail = $(j).find('[url]').attr('url');
        newsname = "Cnet";
        logo = "http://i.i.cbsi.com/cnwk.1d/i/ne/gr/prtnr/CNET_Logo_150.gif";

        articlestech(i, title, description, link, thumbnail, newsname, logo);
  });
})

$.when($.get('https://cors-anywhere.herokuapp.com/https://in.mashable.com/tech.xml')).then(function(r1) {
    $(r2[0]).find('item').each(function(i, j) {
        title = $(j).find('title').text();
        description = $(j).find('description').text();
        //pos3 = description.indexOf("</a>");
        // des = description.substring(pos3 + 2);
        // thumbnail = $(j).find('image').text();
        link = $(j).find('link').text();
        var pos2 = description.indexOf("width");
        var pos1 = description.indexOf("src=");
        thumbnail = description.substring(pos1 + 5, pos2 - 2);
        newsname = "Mashable India Tech";
        logo = "https://media.glassdoor.com/sqll/255718/mashable-squarelogo-1430326903133.png";
        des = "";
        articlestech(i, title, des, link, thumbnail, newsname, logo);
  });
})
</code>```

...

Body:
I am developing a news aggregator website, in have added 24 publishers in it, all the publishers data is present in xml files, so i am calling them using ajax. But it is taking 30 sec to load the page.I have four sections in my webpage(for you, technology, politics,MOvies/tv) for each i have a external JS file. These files are requesting data. PLZ help me reduce the page load time, also suggest some  stratergies.

//technology JS file code sample
  $.when($.get('https://cors-anywhere.herokuapp.com/https://feed.cnet.com/feed/topics/sci-tech'), $.get('https://cors-anywhere.herokuapp.com/https://in.mashable.com/tech.xml')).then(function(r1, r2) {
        // console.log(r1[0]);
        // console.log(r2[0]);
        // cnet article
        $(r1[0]).find('item').each(function(i, j) {
            title = $(j).find('title').text();
            description = $(j).find('description').text();
            link = $(j).find('link').text();
            thumbnail = $(j).find('[url]').attr('url');
            newsname = "Cnet";
            logo = "http://i.i.cbsi.com/cnwk.1d/i/ne/gr/prtnr/CNET_Logo_150.gif";

            articlestech(i, title, description, link, thumbnail, newsname, logo);

        });
        //Mashable articles
        $(r2[0]).find('item').each(function(i, j) {
            title = $(j).find('title').text();
            description = $(j).find('description').text();
            //pos3 = description.indexOf("");
            // des = description.substring(pos3 + 2);
            // thumbnail = $(j).find('image').text();
            link = $(j).find('link').text();
            var pos2 = description.indexOf("width");
            var pos1 = description.indexOf("src=");
            thumbnail = description.substring(pos1 + 5, pos2 - 2);
            newsname = "Mashable India Tech";
            logo = "https://media.glassdoor.com/sqll/255718/mashable-squarelogo-1430326903133.png";
            des = "";
            articlestech(i, title, des, link, thumbnail, newsname, logo);

        });}) ;

//movies/tv shows code sample
 $.ajax({
            type: "GET",
            url: "https://cors-anywhere.herokuapp.com/https://www.cinemablend.com/rss/topic/reviews/movies",
            dataType: "xml",
            success: function(xml) {
                $(r1[0]).find('item').each(function(i, j) {
                    title = $(j).find('title').text();
                    description = $(j).find('description').text() + "...";
                    link = $(j).find('link').text();
                    //console.log(link);
                    thumbnail = $(j).find('enclosure').attr('url');
                    //console.log(thumbnail);
                    newsname = "Cinemablend";
                    logo = "https://s3.amazonaws.com/media.muckrack.com/groups/icons/cinemablend.jpeg";

                    articlestech(i, title, description, link, thumbnail, newsname, logo);
                });
            }
        });
        $.ajax({
            type: "GET",
            url: "https://cors-anywhere.herokuapp.com/https://www.cinejosh.com/rss-feed/1/review.html",
            dataType: "xml",
            success: function(xml) {
                $(xml).find('item').each(function(i, j) {
                    title = $(j).find('title').text();
                    //des = $(j).find('description').text();
                    link = $(j).find('link').text();
                    description = "";
                    thumbnail = $(j).find('[url]').attr('url');;
                    console.log(thumbnail);
                    newsname = "CineJosh";
                    logo = "https://www.cinejosh.com/gallereys/others/normal/cinejosh_logo_1902160805/cinejosh_logo_1902160805_01.jpg";

                    articlestech(i, title, description, link, thumbnail, newsname, logo);
                });
            }
        });

Rest two JS files has same code structure.HOW TO REDUCE LOAD TIME.

Body:
The problem is that you are waiting for all the six requests to return to start doing something with the responses. As I can see from the code snippet you provided the requests does not depend on each other, so you can do all of them separeted and as soon as the first request finishes the user will be able to see the result in the screen.

So, this:

$.when(
  $.get('https://cors-anywhere.herokuapp.com/https://feed.cnet.com/feed/topics/sci-tech'),
  $.get('https://cors-anywhere.herokuapp.com/https://in.mashable.com/tech.xml'),
  $.get('https://www.theverge.com/rss/tech/index.xml'),
  $.get('https://cors-anywhere.herokuapp.com/https://www.buzzfeed.com/tech.xml'),
  $.get('https://cors-anywhere.herokuapp.com/https://www.cnbc.com/id/19854910/device/rss/rss.html'),
  $.get('https://cors-anywhere.herokuapp.com/https://www.engadget.com/rss.xml'))

Needs to be something like this:

$.when($.get('https://cors-anywhere.herokuapp.com/https://feed.cnet.com/feed/topics/sci-tech')).then(function(r1) {
    $(r1[0]).find('item').each(function(i, j) {
        title = $(j).find('title').text();
        description = $(j).find('description').text();
        link = $(j).find('link').text();
        thumbnail = $(j).find('[url]').attr('url');
        newsname = "Cnet";
        logo = "http://i.i.cbsi.com/cnwk.1d/i/ne/gr/prtnr/CNET_Logo_150.gif";

        articlestech(i, title, description, link, thumbnail, newsname, logo);
  });
})

$.when($.get('https://cors-anywhere.herokuapp.com/https://in.mashable.com/tech.xml')).then(function(r1) {
    $(r2[0]).find('item').each(function(i, j) {
        title = $(j).find('title').text();
        description = $(j).find('description').text();
        //pos3 = description.indexOf("</a>");
        // des = description.substring(pos3 + 2);
        // thumbnail = $(j).find('image').text();
        link = $(j).find('link').text();
        var pos2 = description.indexOf("width");
        var pos1 = description.indexOf("src=");
        thumbnail = description.substring(pos1 + 5, pos2 - 2);
        newsname = "Mashable India Tech";
        logo = "https://media.glassdoor.com/sqll/255718/mashable-squarelogo-1430326903133.png";
        des = "";
        articlestech(i, title, des, link, thumbnail, newsname, logo);
  });
})

...


问:
EKReminder with RecurrenceRules
I was work on fetching reminder, I have no problem fetching title, last modified date, notes, etc but I only have problem is recurrenceRules. Here my code:

```<code>print(get_reminder_detail.recurrenceRules)
</code>```

And when I ran the app, it said:

[EKRecurrenceRule <0x28051c1e0> RRULE FREQ=WEEKLY;INTERVAL=1;UNTIL=20200815T061923Z]

As I see two things I am not sure how to pull information from this...first, how can I take FREQ  and INTERVAL into the string? Second, how can I pull the UNTIL into the DateComponents?

答:
Do not look at the string that is used to print out the recurrence rule in the console. Look at the properties of the recurrence rule itself.

https://developer.apple.com/documentation/eventkit/ekrecurrencerule

Everything you need is right there.

Title: EKReminder with RecurrenceRules

Body:
I was work on fetching reminder, I have no problem fetching title, last modified date, notes, etc but I only have problem is recurrenceRules. Here my code:

print(get_reminder_detail.recurrenceRules)

And when I ran the app, it said:

[EKRecurrenceRule <0x28051c1e0> RRULE FREQ=WEEKLY;INTERVAL=1;UNTIL=20200815T061923Z]

As I see two things I am not sure how to pull information from this...first, how can I take FREQ  and INTERVAL into the string? Second, how can I pull the UNTIL into the DateComponents?


问:
Deploy Individual Static Content Files to Azure App Service Via FTP Task in Azure Pipelines
I've just upgraded a Classic ASP website to an ASP.NET Core MVC Razor Page framework. I do not have a CMS system and all of my static content files (.xml), PDFs, and images are contained in my website project. To deploy my static content files, I'm using FTP tasks within Azure pipelines that are based on directory. When my release pipelines run, they delete all of the content within the designated content directory on my app service and then re-copy all of the content that was in the directory associated with the deployment. With Classic ASP, I was able to use Web Deploy to publish individual files to my on prem servers, however, Web Deploy is no longer an option due to security issues with publishing from on prem to the cloud. I'd like to deploy individual content files, instead of an entire content directory within my release pipelines. The ability to deploy deltas would be an added bonus. Is there a script or other functionality available that would allow me to deploy individual static content files to my app services? Please note I'm not able to edit the files directly within the Kudu console, due to audit standards.</p>

答:
You can use Kudu api to deploy individual content files to your azure app server.

You can try adding a script task to call kudu api in your release pipeline. For below example scripts in powershell:

```<code># User name from WebDeploy Publish Profile. Use backtick while assigning variable content
$userName = "{userName}"
# Password from WebDeploy Publish Profile
$password = "{Password}"
# Encode username and password to base64 string
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $userName, $password)))

#deploy the static files to azure app server.
$filePath = "$(system.defaultworkingdirectory)\content\staticfiles.html";
$apiUrl = "https://websitename.scm.azurewebsites.net/api/vfs/site/wwwroot/staticfiles.html";
Invoke-RestMethod -Uri $apiUrl -Headers @{Authorization=("Basic {0}" -f $base64AuthInfo)} -UserAgent $userAgent -Method PUT -InFile $filePath -ContentType "multipart/form-data";
</code>```

You can get the username and password in the Publish Profile. You can download the publish profile from the Azure Web App. And refer userName and userPWD values in the publishProfile section.

You can also get the username and password via scripts in Azure PowerShell task. See below example:

```<code>$ResGroupName = ""
$WebAppName = ""

# Get publishing profile for web application
$WebApp = Get-AzWebApp -Name $WebAppName -ResourceGroupName $ResGroupName
[xml]$publishingProfile = Get-AzWebAppPublishingProfile -WebApp $WebApp

# Create Base64 authorization header
$username = $publishingProfile.publishData.publishProfile[0].userName
$password = $publishingProfile.publishData.publishProfile[0].userPWD
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $username,$password)))

#deploy the static files to azure app server.
$filePath = "$(system.defaultworkingdirectory)\content\staticfiles.html";
$apiUrl = "https://websitename.scm.azurewebsites.net/api/vfs/site/wwwroot/staticfiles.html";
Invoke-RestMethod -Uri $apiUrl -Headers @{Authorization=("Basic {0}" -f $base64AuthInfo)} -UserAgent $userAgent -Method PUT -InFile $filePath -ContentType "multipart/form-data";
</code>```

See here for more information.

Body:
You can use Kudu api to deploy individual content files to your azure app server.

You can try adding a script task to call kudu api in your release pipeline. For below example scripts in powershell:

# User name from WebDeploy Publish Profile. Use backtick while assigning variable content
$userName = "{userName}"
# Password from WebDeploy Publish Profile
$password = "{Password}"
# Encode username and password to base64 string
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $userName, $password)))

#deploy the static files to azure app server.
$filePath = "$(system.defaultworkingdirectory)\content\staticfiles.html";
$apiUrl = "https://websitename.scm.azurewebsites.net/api/vfs/site/wwwroot/staticfiles.html";
Invoke-RestMethod -Uri $apiUrl -Headers @{Authorization=("Basic {0}" -f $base64AuthInfo)} -UserAgent $userAgent -Method PUT -InFile $filePath -ContentType "multipart/form-data";

You can get the username and password in the Publish Profile. You can download the publish profile from the Azure Web App. And refer userName and userPWD values in the publishProfile section.

You can also get the username and password via scripts in Azure PowerShell task. See below example:

$ResGroupName = ""
$WebAppName = ""

# Get publishing profile for web application
$WebApp = Get-AzWebApp -Name $WebAppName -ResourceGroupName $ResGroupName
[xml]$publishingProfile = Get-AzWebAppPublishingProfile -WebApp $WebApp

# Create Base64 authorization header
$username = $publishingProfile.publishData.publishProfile[0].userName
$password = $publishingProfile.publishData.publishProfile[0].userPWD
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $username,$password)))

#deploy the static files to azure app server.
$filePath = "$(system.defaultworkingdirectory)\content\staticfiles.html";
$apiUrl = "https://websitename.scm.azurewebsites.net/api/vfs/site/wwwroot/staticfiles.html";
Invoke-RestMethod -Uri $apiUrl -Headers @{Authorization=("Basic {0}" -f $base64AuthInfo)} -UserAgent $userAgent -Method PUT -InFile $filePath -ContentType "multipart/form-data";

See here for more information.


问:
Html tab active
I use this example code in https://www.w3schools.com/howto/howto_js_tabs.asp, i Just want that if the user click button Paris even the user refresh the page, the tab will still be in Paris

```<code><div class="tab">
  <button class="tablinks" onclick="openCity(event, 'London')" id="defaultOpen">Enrollment</button>
  <button class="tablinks" onclick="openCity(event, 'Paris')" id="secondOpen" >Student</button>
  <button class="tablinks" onclick="openCity(event, 'Tokyo')" id="thirdOpen">Parents</button>
</div>

<div id="London" class="tabcontent">
  <h3>London</h3>
  <p>London is the capital city of England.</p>
</div>

<div id="Paris" class="tabcontent">
  <h3>Paris</h3>
  <p>Paris is the capital of France.</p>
</div>

<div id="Tokyo" class="tabcontent">
  <h3>Tokyo</h3>
  <p>Tokyo is the capital of Japan.</p>
</div>

<script>
function openCity(evt, cityName) {
  var i, tabcontent, tablinks;
  tabcontent = document.getElementsByClassName("tabcontent");
  for (i = 0; i < tabcontent.length; i++) {
    tabcontent[i].style.display = "none";
  }
  tablinks = document.getElementsByClassName("tablinks");
  for (i = 0; i < tablinks.length; i++) {
    tablinks[i].className = tablinks[i].className.replace(" active", "");
  }
  document.getElementById(cityName).style.display = "block";
  evt.currentTarget.className += " active";
}
//is this right?
first = document.getElementById("defaultOpen");
second = document.getElementById("secondOpen");
third = document.getElementById("thirdOpen");
if (second == ('active')){
    document.getElementById("secondOpen").click();
}else if(third == ('active')){
    document.getElementById("thirdOpen").click();
}else{
document.getElementById("defaultOpen").click();
}
</script>
</code>```

this is the example of html, I just want that if the user click the paris, even the user refresh the page the paris will active

function openCity(evt, cityName) {
  var i, tabcontent, tablinks;
  tabcontent = document.getElementsByClassName("tabcontent");
  for (i = 0; i < tabcontent.length; i++) {
    tabcontent[i].style.display = "none";
  }
  tablinks = document.getElementsByClassName("tablinks");
  for (i = 0; i < tablinks.length; i++) {
    tablinks[i].className = tablinks[i].className.replace(" active", "");
  }
  document.getElementById(cityName).style.display = "block";
  evt.currentTarget.className += " active";
}

// is this right?
first = document.getElementById("defaultOpen");
second = document.getElementById("secondOpen");
third = document.getElementById("thirdOpen");
if (second == ('active')){
document.getElementById("secondOpen").click();
}else if(third == ('active')){
    document.getElementById("thirdOpen").click();
}else{
document.getElementById("defaultOpen").click();
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {font-family: Arial;}

/* Style the tab */
.tab {
  overflow: hidden;
  border: 1px solid #ccc;
  background-color: #f1f1f1;
}

/* Style the buttons inside the tab */
.tab button {
  background-color: inherit;
  float: left;
  border: none;
  outline: none;
  cursor: pointer;
  padding: 14px 16px;
  transition: 0.3s;
  font-size: 17px;
}

/* Change background color of buttons on hover */
.tab button:hover {
  background-color: #ddd;
}

/* Create an active/current tablink class */
.tab button.active {
  background-color: #ccc;
}

/* Style the tab content */
.tabcontent {
  display: none;
  padding: 6px 12px;
  border: 1px solid #ccc;
  border-top: none;
}</code>```

  <button class="tablinks" onclick="openCity(event, 'London')" id="defaultOpen">London</button>
  <button class="tablinks" onclick="openCity(event, 'Paris')">Paris</button>
  <button class="tablinks" onclick="openCity(event, 'Tokyo')">Tokyo</button>

London

London is the capital city of England.

Paris

Paris is the capital of France.

Tokyo

Tokyo is the capital of Japan.

```

答:
This one works i have used local storage

Working Codepen Link

function openCity(cityName) {
  localStorage.setItem('cityName', cityName);
  var i, tabcontent, tablinks;
  tabcontent = document.getElementsByClassName("tabcontent");
  for (i = 0; i < tabcontent.length; i++) {
    tabcontent[i].style.display = "none";
  }
  tablinks = document.getElementsByClassName("tablinks");
  for (i = 0; i < tablinks.length; i++) {
    tablinks[i].className = tablinks[i].className.replace(" active", "");
  }
  document.getElementById(cityName).style.display = "block";
  document.querySelector(`[data-value=${cityName}]`).className += " active";
}
localStorage.getItem('cityName') !== null ? openCity(localStorage.getItem('cityName')) : openCity('London')```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {font-family: Arial;}

/* Style the tab */
.tab {
  overflow: hidden;
  border: 1px solid #ccc;
  background-color: #f1f1f1;
}

/* Style the buttons inside the tab */
.tab button {
  background-color: inherit;
  float: left;
  border: none;
  outline: none;
  cursor: pointer;
  padding: 14px 16px;
  transition: 0.3s;
  font-size: 17px;
}

/* Change background color of buttons on hover */
.tab button:hover {
  background-color: #ddd;
}

/* Create an active/current tablink class */
.tab button.active {
  background-color: #ccc;
}

/* Style the tab content */
.tabcontent {
  display: none;
  padding: 6px 12px;
  border: 1px solid #ccc;
  border-top: none;
}</code>```

  <button class="tablinks" data-value="London" onclick="openCity('London')">London</button>
  <button class="tablinks" data-value="Paris" onclick="openCity('Paris')">Paris</button>
  <button class="tablinks" data-value="Tokyo" onclick="openCity('Tokyo')">Tokyo</button>

London

London is the capital city of England.

Paris

Paris is the capital of France.

Tokyo

Tokyo is the capital of Japan.

```

Title: Html tab active

Body:
I use this example code in https://www.w3schools.com/howto/howto_js_tabs.asp, i Just want that if the user click button Paris even the user refresh the page, the tab will still be in Paris

  <button class="tablinks" onclick="openCity(event, 'London')" id="defaultOpen">Enrollment</button>
  <button class="tablinks" onclick="openCity(event, 'Paris')" id="secondOpen" >Student</button>
  <button class="tablinks" onclick="openCity(event, 'Tokyo')" id="thirdOpen">Parents</button>

London

London is the capital city of England.

Paris

Paris is the capital of France.

Tokyo

Tokyo is the capital of Japan.

this is the example of html, I just want that if the user click the paris, even the user refresh the page the paris will active

function openCity(evt, cityName) {
  var i, tabcontent, tablinks;
  tabcontent = document.getElementsByClassName("tabcontent");
  for (i = 0; i < tabcontent.length; i++) {
    tabcontent[i].style.display = "none";
  }
  tablinks = document.getElementsByClassName("tablinks");
  for (i = 0; i < tablinks.length; i++) {
    tablinks[i].className = tablinks[i].className.replace(" active", "");
  }
  document.getElementById(cityName).style.display = "block";
  evt.currentTarget.className += " active";
}

// is this right?
first = document.getElementById("defaultOpen");
second = document.getElementById("secondOpen");
third = document.getElementById("thirdOpen");
if (second == ('active')){
document.getElementById("secondOpen").click();
}else if(third == ('active')){
    document.getElementById("thirdOpen").click();
}else{
document.getElementById("defaultOpen").click();
}

body {font-family: Arial;}

/* Style the tab */
.tab {
  overflow: hidden;
  border: 1px solid #ccc;
  background-color: #f1f1f1;
}

/* Style the buttons inside the tab */
.tab button {
  background-color: inherit;
  float: left;
  border: none;
  outline: none;
  cursor: pointer;
  padding: 14px 16px;
  transition: 0.3s;
  font-size: 17px;
}

/* Change background color of buttons on hover */
.tab button:hover {
  background-color: #ddd;
}

/* Create an active/current tablink class */
.tab button.active {
  background-color: #ccc;
}

/* Style the tab content */
.tabcontent {
  display: none;
  padding: 6px 12px;
  border: 1px solid #ccc;
  border-top: none;
}

  <button class="tablinks" onclick="openCity(event, 'London')" id="defaultOpen">London</button>
  <button class="tablinks" onclick="openCity(event, 'Paris')">Paris</button>
  <button class="tablinks" onclick="openCity(event, 'Tokyo')">Tokyo</button>

London

London is the capital city of England.

Paris

Paris is the capital of France.

Tokyo

Tokyo is the capital of Japan.

Body:
This one works i have used local storage

Working Codepen Link

function openCity(cityName) {
  localStorage.setItem('cityName', cityName);
  var i, tabcontent, tablinks;
  tabcontent = document.getElementsByClassName("tabcontent");
  for (i = 0; i < tabcontent.length; i++) {
    tabcontent[i].style.display = "none";
  }
  tablinks = document.getElementsByClassName("tablinks");
  for (i = 0; i < tablinks.length; i++) {
    tablinks[i].className = tablinks[i].className.replace(" active", "");
  }
  document.getElementById(cityName).style.display = "block";
  document.querySelector(`[data-value=${cityName}]`).className += " active";
}
localStorage.getItem('cityName') !== null ? openCity(localStorage.getItem('cityName')) : openCity('London')

body {font-family: Arial;}

/* Style the tab */
.tab {
  overflow: hidden;
  border: 1px solid #ccc;
  background-color: #f1f1f1;
}

/* Style the buttons inside the tab */
.tab button {
  background-color: inherit;
  float: left;
  border: none;
  outline: none;
  cursor: pointer;
  padding: 14px 16px;
  transition: 0.3s;
  font-size: 17px;
}

/* Change background color of buttons on hover */
.tab button:hover {
  background-color: #ddd;
}

/* Create an active/current tablink class */
.tab button.active {
  background-color: #ccc;
}

/* Style the tab content */
.tabcontent {
  display: none;
  padding: 6px 12px;
  border: 1px solid #ccc;
  border-top: none;
}

<div class="tab">
  <button class="tablinks" data-value="London" onclick="openCity('London')">London</button>
  <button class="tablinks" data-value="Paris" onclick="openCity('Paris')">Paris</button>
  <button class="tablinks" data-value="Tokyo" onclick="openCity('Tokyo')">Tokyo</button>
</div>

<div id="London" class="tabcontent">
  <h3>London</h3>
  <p>London is the capital city of England.</p>
</div>

<div id="Paris" class="tabcontent">
  <h3>Paris</h3>
  <p>Paris is the capital of France.</p>
</div>

<div id="Tokyo" class="tabcontent">
  <h3>Tokyo</h3>
  <p>Tokyo is the capital of Japan.</p>
</div>


问:
How to get the value from a table cell
I have a table I created and am most interested in the "costs" column. I could have more than one row of data in which I would have multiple costs and I want to add those up and put the result in the table cell next to "Total." I saw a method called GetValue(); but not sure if that is what I am looking for or how to use it. My thinking is that migradoc has a method where you can get the value of a table cell in which I would store that in a variable. And where I create the "Total" row, I would use that variable to display the total. So how would I do that?

My code:

```<code>/define header of table
        Row row = table.AddRow();
        row.HeadingFormat = true;
        Cell cell = row.Cells[0];
        cell.AddParagraph("Customer Name");
        cell.Format.Font.Bold = true;

        cell = row.Cells[1];
        cell.AddParagraph("Date Created");
        cell.Format.Font.Bold = true;

        cell = row.Cells[2];
        cell.AddParagraph("Description");
        cell.Format.Font.Bold = true;

        cell = row.Cells[3];
        cell.AddParagraph("Due Date");
        cell.Format.Font.Bold = true;

        cell = row.Cells[4];
        cell.AddParagraph("Billable Hours");
        cell.Format.Font.Bold = true;

        cell = row.Cells[5];
        cell.AddParagraph("Costs");
        cell.Format.Font.Bold = true;

        //define a row of data in the table
        foreach (TicketView1 ticket in SampleTickets)
        {
            row = table.AddRow();

            cell = row.Cells[0];
            cell.AddParagraph(ticket.customer_name);

            cell = row.Cells[1];
            cell.AddParagraph(ticket.date_created.ToString("MM/dd/yyyy"));

            cell = row.Cells[2];
            cell.AddParagraph(ticket.description);

            cell = row.Cells[3];
            cell.AddParagraph(ticket.due_date.ToString("MM/dd/yyyy"));

            cell = row.Cells[4];
            cell.AddParagraph(ticket.billable_hrs.ToString());
        }

        cell = row.Cells[5];
        cell.AddParagraph("$60.00");

        //add invisible row as a space line to the table
        row = table.AddRow();
        row.Borders.Visible = false;

        //add the subtotal row
        row = table.AddRow();
        row.Cells[0].Borders.Visible = false;
        row.Cells[0].AddParagraph("Sub Total:");
        row.Cells[0].Format.Font.Bold = true;
        row.Cells[0].Format.Alignment = ParagraphAlignment.Right;
        row.Cells[0].MergeRight = 4;
        cell = row.Cells[5];

        //add tax row
        row = table.AddRow();
        row.Cells[0].Borders.Visible = false;
        row.Cells[0].AddParagraph("TAX:");
        row.Cells[0].Format.Font.Bold = true;
        row.Cells[0].Format.Alignment = ParagraphAlignment.Right;
        row.Cells[0].MergeRight = 4;

        //add total
        row = table.AddRow();
        row.Cells[0].Borders.Visible = false;
        row.Cells[0].AddParagraph("TOTAL:");
        row.Cells[0].Format.Font.Bold = true;
        row.Cells[0].Format.Alignment = ParagraphAlignment.Right;
        row.Cells[0].MergeRight = 4;

    }
</code>```

答:
I have found out the answer by simple creating a count variable and then inside my forEach loop just adding that sum plus my dummy data which would be 60. Then right where I created my "totals" row, right underneath it I added into the cell that variable which contains the count data.

My forEach loop and count variable

```<code>double sum = 0;
        foreach (TicketView1 ticket in SampleTickets)
        {
            row = table.AddRow();

            cell = row.Cells[0];
            cell.AddParagraph(ticket.customer_name);

            cell = row.Cells[1];
            cell.AddParagraph(ticket.date_created.ToString("MM/dd/yyyy"));

            cell = row.Cells[2];
            cell.AddParagraph(ticket.description);

            cell = row.Cells[3];
            cell.AddParagraph(ticket.due_date.ToString("MM/dd/yyyy"));

            cell = row.Cells[4];
            cell.AddParagraph(ticket.billable_hrs.ToString());

            cell = row.Cells[5];
            cell.AddParagraph("$60.00");
            sum = sum + 60;
        }
</code>```

Where I added the total row and appended the data to the totals cell:

```<code>//add total
        row = table.AddRow();
        row.Cells[0].Borders.Visible = false;
        row.Cells[0].AddParagraph("TOTAL:");
        row.Cells[0].Format.Font.Bold = true;
        row.Cells[0].Format.Alignment = ParagraphAlignment.Right;
        row.Cells[0].MergeRight = 4;

        row.Cells[5].AddParagraph(sum.ToString("$0.00"));
</code>```

Title: How to get the value from a table cell

Body:
I have a table I created and am most interested in the "costs" column. I could have more than one row of data in which I would have multiple costs and I want to add those up and put the result in the table cell next to "Total." I saw a method called GetValue(); but not sure if that is what I am looking for or how to use it. My thinking is that migradoc has a method where you can get the value of a table cell in which I would store that in a variable. And where I create the "Total" row, I would use that variable to display the total. So how would I do that?

My code:

/define header of table
        Row row = table.AddRow();
        row.HeadingFormat = true;
        Cell cell = row.Cells[0];
        cell.AddParagraph("Customer Name");
        cell.Format.Font.Bold = true;

        cell = row.Cells[1];
        cell.AddParagraph("Date Created");
        cell.Format.Font.Bold = true;

        cell = row.Cells[2];
        cell.AddParagraph("Description");
        cell.Format.Font.Bold = true;

        cell = row.Cells[3];
        cell.AddParagraph("Due Date");
        cell.Format.Font.Bold = true;

        cell = row.Cells[4];
        cell.AddParagraph("Billable Hours");
        cell.Format.Font.Bold = true;

        cell = row.Cells[5];
        cell.AddParagraph("Costs");
        cell.Format.Font.Bold = true;

        //define a row of data in the table
        foreach (TicketView1 ticket in SampleTickets)
        {
            row = table.AddRow();

            cell = row.Cells[0];
            cell.AddParagraph(ticket.customer_name);

            cell = row.Cells[1];
            cell.AddParagraph(ticket.date_created.ToString("MM/dd/yyyy"));

            cell = row.Cells[2];
            cell.AddParagraph(ticket.description);

            cell = row.Cells[3];
            cell.AddParagraph(ticket.due_date.ToString("MM/dd/yyyy"));

            cell = row.Cells[4];
            cell.AddParagraph(ticket.billable_hrs.ToString());
        }

        cell = row.Cells[5];
        cell.AddParagraph("$60.00");

        //add invisible row as a space line to the table
        row = table.AddRow();
        row.Borders.Visible = false;

        //add the subtotal row
        row = table.AddRow();
        row.Cells[0].Borders.Visible = false;
        row.Cells[0].AddParagraph("Sub Total:");
        row.Cells[0].Format.Font.Bold = true;
        row.Cells[0].Format.Alignment = ParagraphAlignment.Right;
        row.Cells[0].MergeRight = 4;
        cell = row.Cells[5];

        //add tax row
        row = table.AddRow();
        row.Cells[0].Borders.Visible = false;
        row.Cells[0].AddParagraph("TAX:");
        row.Cells[0].Format.Font.Bold = true;
        row.Cells[0].Format.Alignment = ParagraphAlignment.Right;
        row.Cells[0].MergeRight = 4;

        //add total
        row = table.AddRow();
        row.Cells[0].Borders.Visible = false;
        row.Cells[0].AddParagraph("TOTAL:");
        row.Cells[0].Format.Font.Bold = true;
        row.Cells[0].Format.Alignment = ParagraphAlignment.Right;
        row.Cells[0].MergeRight = 4;

    }

Body:
I have found out the answer by simple creating a count variable and then inside my forEach loop just adding that sum plus my dummy data which would be 60. Then right where I created my "totals" row, right underneath it I added into the cell that variable which contains the count data.

My forEach loop and count variable

double sum = 0;
        foreach (TicketView1 ticket in SampleTickets)
        {
            row = table.AddRow();

            cell = row.Cells[0];
            cell.AddParagraph(ticket.customer_name);

            cell = row.Cells[1];
            cell.AddParagraph(ticket.date_created.ToString("MM/dd/yyyy"));

            cell = row.Cells[2];
            cell.AddParagraph(ticket.description);

            cell = row.Cells[3];
            cell.AddParagraph(ticket.due_date.ToString("MM/dd/yyyy"));

            cell = row.Cells[4];
            cell.AddParagraph(ticket.billable_hrs.ToString());

            cell = row.Cells[5];
            cell.AddParagraph("$60.00");
            sum = sum + 60;
        }

Where I added the total row and appended the data to the totals cell:

//add total
        row = table.AddRow();
        row.Cells[0].Borders.Visible = false;
        row.Cells[0].AddParagraph("TOTAL:");
        row.Cells[0].Format.Font.Bold = true;
        row.Cells[0].Format.Alignment = ParagraphAlignment.Right;
        row.Cells[0].MergeRight = 4;

        row.Cells[5].AddParagraph(sum.ToString("$0.00"));


问:
Efficiently Join Two Tables with Several WHEREs
I meet a problem when I try to join two large tables and select entries with WHERE...OR clause:

```<code>SELECT A.a, B.b
FROM A JOIN B
ON A.equal = B.equal
WHERE A.condition1 > 100 OR B.condition2 > 200
</code>```

Here A and B are very very large tables, and the entries need to match the WHERE...OR conditions in different tables. May I ask if there are any approaches I can optimize this clause?

Thx in advance.

答:
OR conditions are usually performance killer.

If your query is running slow, one alternative approach that you can try is to union two subqueries, like:

```<code>SELECT A.a, B.b
FROM A JOIN B ON A.equal = B.equal
WHERE A.condition1 > 100
UNION
SELECT A.a, B.b
FROM A JOIN B ON A.equal = B.equal
WHERE B.condition2 > 100
</code>```

You want indexes on A(condition1, equal) and B(condition2, equal) for performance.

If you can guarantee that there is no overlap between the resultset of the subqueries (ie there is no row where both conditions are true at the same time), then you can change UNION to UNIN ALL: it is far more efficient, since the database does not need to look for duplicates across the resultsets.

Body:
I meet a problem when I try to join two large tables and select entries with WHERE...OR clause:

SELECT A.a, B.b
FROM A JOIN B
ON A.equal = B.equal
WHERE A.condition1 > 100 OR B.condition2 > 200

Here A and B are very very large tables, and the entries need to match the WHERE...OR conditions in different tables. May I ask if there are any approaches I can optimize this clause?

Thx in advance.

Body:
OR conditions are usually performance killer.

If your query is running slow, one alternative approach that you can try is to union two subqueries, like:

SELECT A.a, B.b
FROM A JOIN B ON A.equal = B.equal
WHERE A.condition1 > 100
UNION
SELECT A.a, B.b
FROM A JOIN B ON A.equal = B.equal
WHERE B.condition2 > 100

You want indexes on A(condition1, equal) and B(condition2, equal) for performance.

If you can guarantee that there is no overlap between the resultset of the subqueries (ie there is no row where both conditions are true at the same time), then you can change UNION to UNIN ALL: it is far more efficient, since the database does not need to look for duplicates across the resultsets.


问:
Regex Python french accent
I use this code: b = re.sub('[^A-Za-z]+', ' ', a). Nevertheless i need to take account of the french accents: àâéèêëïîôùûç. Can you please help me? :)

Thanks.

答:
If you're like to replace all the letters, taking into account unicode, do the following:

```<code>text = "àâéèêëïîôùûç"
re.sub('\w+', ' ', text, re.UNICODE)
</code>```

Please note that the re.UNICODE is not needed in python3, as it does unicode matching by default.

Title: Regex Python french accent

Body:
If you're like to replace all the letters, taking into account unicode, do the following:

text = "àâéèêëïîôùûç"
re.sub('\w+', ' ', text, re.UNICODE)

Please note that the re.UNICODE is not needed in python3, as it does unicode matching by default.


问:
Unable to have PERT graph result - AnyChart JS
I am working on a university project in order to convert a file into a PERT diagram.
I get this specific example to convert to PERT diagram, Which translates to AnyChart JS in this way :

var data = [
  {id: "1", duration: 2, name: "Task 1"},
  {id: "2", duration: 2, name: "Task 2",dependsOn: ["1"]},
  {id: "3", duration: 1, name: "Task 3",dependsOn: ["2"]},
  {id: "4", duration: 3, name: "Task 4",dependsOn: ["3"]},
  {id: "5", duration: 3, name: "Task 5",dependsOn: ["4"]},
  {id: "6", duration: 1, name: "Task 6",dependsOn: ["5"]},
  {id: "7", duration: 1, name: "Task 7",dependsOn: ["5"]},
  {id: "8", duration: 2, name: "Task 8",dependsOn: ["7"]},
  {id: "9", duration: 1, name: "Task 9",dependsOn: ["6", "8"]},
  {id: "10", duration: 1, name: "Task 10",dependsOn: ["6", "8"]},
  {id: "11", duration: 2, name: "Task 11",dependsOn: ["6", "8"]},
  {id: "12", duration: 1, name: "Task 12",dependsOn: ["9", "10"]},
  {id: "13", duration: 2, name: "Task 13",dependsOn: ["9", "10"]},
  {id: "14", duration: 2, name: "Task 14",dependsOn: ["12", "13"]},
  {id: "15", duration: 1, name: "Task 15",dependsOn: ["14"]}
];
```

<p><strong>HTML</strong></p>

<pre class="lang-html prettyprint-override"><code><div id="container"></div>
</code>```

CSS

html, body, #container {
    width: 100%;
    height: 100%;
    margin: 0;
    padding: 0;
}
```

<p><strong>JAVASCRIPT</strong></p>

<pre class="lang-js prettyprint-override"><code>anychart.onDocumentReady(function () {
  // create data
  var data = [
    {id: "1", duration: 2, name: "Task 1"},
    {id: "2", duration: 2, name: "Task 2",dependsOn: ["1"]},
    {id: "3", duration: 1, name: "Task 3",dependsOn: ["2"]},
    {id: "4", duration: 3, name: "Task 4",dependsOn: ["3"]},
    {id: "5", duration: 3, name: "Task 5",dependsOn: ["4"]},
    {id: "6", duration: 1, name: "Task 6",dependsOn: ["5"]},
    {id: "7", duration: 1, name: "Task 7",dependsOn: ["5"]},
    {id: "8", duration: 2, name: "Task 8",dependsOn: ["7"]},
    {id: "9", duration: 1, name: "Task 9",dependsOn: ["6", "8"]},
    {id: "10", duration: 1, name: "Task 10",dependsOn: ["6", "8"]},
    {id: "11", duration: 2, name: "Task 11",dependsOn: ["6", "8"]},
    {id: "12", duration: 1, name: "Task 12",dependsOn: ["9", "10"]},
    {id: "13", duration: 2, name: "Task 13",dependsOn: ["9", "10"]},
    {id: "14", duration: 2, name: "Task 14",dependsOn: ["12", "13"]},
    {id: "15", duration: 1, name: "Task 15",dependsOn: ["14"]}
  ];

  // create a chart
  var chart = anychart.pert();

  // milestones size
  chart.milestones().size(50);

  // set chart data
  chart.data(data, "as-table");

  // set the title of the chart
  chart.title("PERT Chart");

  // set the container id for the chart
  chart.container("container");

  // initiate drawing the chart
  chart.draw();
});
</code>```

Code link https://playground.anychart.com/zoAA9JIO/3

Any idea how to fix this? or any JS libraries suggestions to draw pert diagram?

答: Your data is not compatible with the current version of the AnyChart PERT chart (8.8.0 version). It supports only planar data (without intersected tasks). Your data requires drawing a chart with tasks that intersect each other multiple times. Tasks 10, 11, 13 require intersections to be drawn.</p>

Body:
I am working on a university project in order to convert a file into a PERT diagram.
I get this specific example to convert to PERT diagram, Which translates to AnyChart JS in this way :

var data = [
  {id: "1", duration: 2, name: "Task 1"},
  {id: "2", duration: 2, name: "Task 2",dependsOn: ["1"]},
  {id: "3", duration: 1, name: "Task 3",dependsOn: ["2"]},
  {id: "4", duration: 3, name: "Task 4",dependsOn: ["3"]},
  {id: "5", duration: 3, name: "Task 5",dependsOn: ["4"]},
  {id: "6", duration: 1, name: "Task 6",dependsOn: ["5"]},
  {id: "7", duration: 1, name: "Task 7",dependsOn: ["5"]},
  {id: "8", duration: 2, name: "Task 8",dependsOn: ["7"]},
  {id: "9", duration: 1, name: "Task 9",dependsOn: ["6", "8"]},
  {id: "10", duration: 1, name: "Task 10",dependsOn: ["6", "8"]},
  {id: "11", duration: 2, name: "Task 11",dependsOn: ["6", "8"]},
  {id: "12", duration: 1, name: "Task 12",dependsOn: ["9", "10"]},
  {id: "13", duration: 2, name: "Task 13",dependsOn: ["9", "10"]},
  {id: "14", duration: 2, name: "Task 14",dependsOn: ["12", "13"]},
  {id: "15", duration: 1, name: "Task 15",dependsOn: ["14"]}
];

HTML

CSS

html, body, #container {
    width: 100%;
    height: 100%;
    margin: 0;
    padding: 0;
}

JAVASCRIPT

anychart.onDocumentReady(function () {
  // create data
  var data = [
    {id: "1", duration: 2, name: "Task 1"},
    {id: "2", duration: 2, name: "Task 2",dependsOn: ["1"]},
    {id: "3", duration: 1, name: "Task 3",dependsOn: ["2"]},
    {id: "4", duration: 3, name: "Task 4",dependsOn: ["3"]},
    {id: "5", duration: 3, name: "Task 5",dependsOn: ["4"]},
    {id: "6", duration: 1, name: "Task 6",dependsOn: ["5"]},
    {id: "7", duration: 1, name: "Task 7",dependsOn: ["5"]},
    {id: "8", duration: 2, name: "Task 8",dependsOn: ["7"]},
    {id: "9", duration: 1, name: "Task 9",dependsOn: ["6", "8"]},
    {id: "10", duration: 1, name: "Task 10",dependsOn: ["6", "8"]},
    {id: "11", duration: 2, name: "Task 11",dependsOn: ["6", "8"]},
    {id: "12", duration: 1, name: "Task 12",dependsOn: ["9", "10"]},
    {id: "13", duration: 2, name: "Task 13",dependsOn: ["9", "10"]},
    {id: "14", duration: 2, name: "Task 14",dependsOn: ["12", "13"]},
    {id: "15", duration: 1, name: "Task 15",dependsOn: ["14"]}
  ];

  // create a chart
  var chart = anychart.pert();

  // milestones size
  chart.milestones().size(50);

  // set chart data
  chart.data(data, "as-table");

  // set the title of the chart
  chart.title("PERT Chart");

  // set the container id for the chart
  chart.container("container");

  // initiate drawing the chart
  chart.draw();
});

Code link https://playground.anychart.com/zoAA9JIO/3

Any idea how to fix this? or any JS libraries suggestions to draw pert diagram?


问:
Get email subject and sender using imaplib?
I am getting the following response after executing the code shown below the response. How can I parse through this response to get the sender (John Smith) and the subject (test)?

```<code>[('13010 (BODY[HEADER.FIELDS (SUBJECT FROM)] {57}', 'From: John Smith <jsmith@gmail.com>\r\nSubject: test\r\n\r\n'), ')']
</code>```

-

```<code>conn.fetch(message, '(BODY[HEADER.FIELDS (SUBJECT FROM)])')
</code>```

答:
You can try this to fetch the header information of all the mails.

```<code>import imaplib
import email

obj = imaplib.IMAP4_SSL('imap.gmail.com', 993)
obj.login('username', 'password')
obj.select('folder_name')
resp, data = obj.uid('FETCH', ','.join(map(str,uidl_list)) , '(BODY.PEEK[HEADER.FIELDS (From Subject)] RFC822.SIZE)')
</code>```

Note: Here 'uidl_list' is the list of uid of mails whose subject u want.

Body:
I am getting the following response after executing the code shown below the response. How can I parse through this response to get the sender (John Smith) and the subject (test)?

[('13010 (BODY[HEADER.FIELDS (SUBJECT FROM)] {57}', 'From: John Smith <jsmith@gmail.com>\r\nSubject: test\r\n\r\n'), ')']

-

conn.fetch(message, '(BODY[HEADER.FIELDS (SUBJECT FROM)])')

Body:
You can try this to fetch the header information of all the mails.

import imaplib
import email

obj = imaplib.IMAP4_SSL('imap.gmail.com', 993)
obj.login('username', 'password')
obj.select('folder_name')
resp, data = obj.uid('FETCH', ','.join(map(str,uidl_list)) , '(BODY.PEEK[HEADER.FIELDS (From Subject)] RFC822.SIZE)')

Note: Here 'uidl_list' is the list of uid of mails whose subject u want.


问:
Beginner Javascript errors 'Line is longer than 80 characters', 'unexpected var' and 'use space not tabs'
Having trouble with a combined file of html, CSS and javascript  that is giving me an undisclosed error, used JSLint to check for errors but the only errors I were given were 'Line is longer than 80 characters', 'use spaces not tabs' and 'unexpected var'. Could someone please give me some help I'm real stuck.</p>

```<code>"use strict";

//validate form inputs from payment.html
function validate() {

    var errMsg = "";
    var result = true;      //assumes no errors

    //assign elements to variables
    var mastercard_check = document.getElementById("mastercard").checked;
    var visa_check = document.getElementById("visa").checked;
    var express_check = document.getElementById("express").checked;
    var credit_name = document.getElementById("credit_name").value;
    var credit_number = document.getElementById("credit_number").value;
    var credit_expiry = document.getElementById("credit_expiry").value;
    var credit_vv = document.getElementById("credit_vv").value;

    //validations for form
    if (!(mastercard_check || visa_check || express_check)) {
        errMsg += "Please choose a card type\n";
        result = false;
    }

    if (credit_name.length > 40) {
        errMsg += "Please enter a name for your credit card between 1-40 characters\n";
        result = false;
    }
    else if (!credit_name.match(/^[a-zA-Z ]+$/)) {
        errMsg += "Credit card name can only contain alpha characters\n";
        result = false;
    }

    if (isNaN(credit_number)) {
        errMsg = errMsg + "Credit card number must contain digits only\n";
        result = false;
    }
    else if (credit_number.length < 15 || credit_number.length > 16){
        errMsg = errMsg + "Credit card number must contian either 15 or 16 digits\n";
        result = false;
    }
    else {
        var tempMsg = checkCardNumber(credit_number);
        if (tempMsg != "") {
            errMsg += tempMsg;
            result = false;
        }
    }

    if (!credit_expiry.match(/^\d{2}-\d{2}$/)) {
        errMsg = errMsg + "Credit Card expiry must follow the format mm-yy\n";
        result = false;
    }

    if (!credit_vv) {
        errMsg = errMsg + "Please enter a Credit Card Verification Value\n";
        result = false;
    }

    if (errMsg != "") {
        alert(errMsg);
    }

    return result;
}

//obtain the credit card type
function getCardType() {

    var cardType = "Unknown";
    var cardArray = document.getElementById("credit_type").getElementsByTagName("input");

    for(var i = 0; i < cardArray.length; i++) {
        if (cardArray[i].checked) {
            cardType = cardArray[i].value;
        }
    }
    return cardType

}

//check hte card number matches the chosen card type
function checkCardNumber(credit_number) {
    var errMsg = "";
    var card = getCardType();
    switch(card) {
        case "visa":
            if (!(credit_number.length == 16)) {
                errMsg = "Visa number must contian 16 digits\n";
            }
            else if (!credit_number.match(/^(4).*$/)) {
                errMsg = "Visa number must start with a 4. \n";
            }
            break;
        case "mastercard":
            if (!(credit_number.length == 16)) {
                errMsg = "Mastercard number must contian 16 digits\n";
            }
            else if (!credit_number.match(/^(51|52|53|54|55).*$/)) {
                errMsg = "Mastercard number must start with digits 51 through 55. \n";
            }
            break;
        case "express":
            if (!(credit_number.length == 15)) {
                errMsg = "American Express number must contian 15 digits\n";
            }
            else if (!credit_number.match(/^(34|37).*$/)) {
                errMsg = "American Express number must start with 34 or 37. \n";
            }
            break;
    }
    return errMsg;
}

//calculate total cost using the meal size and quantity chosen
function calcCost(size, quantity){
    var cost = 0;
    if (size.search("three") != -1) cost = 100;
    if (size.search("four")!= -1) cost += 150;
    if (size.search("five")!= -1) cost += 200;
}
//get the stored values
function getInfo(){
    var cost = 0;
    if(sessionStorage.firstname != undefined){
        document.getElementById("confirm_name").textContent = sessionStorage.firstname + " " + sessionStorage.lastname;

    document.getElementById("confirm_address").textContent = sessionStorage.address + " " + sessionStorage.suburb + " " + sessionStorage.state + " " + sessionStorage.postcode;

    document.getElementById("confirm_details").textContent = sessionStorage.email + " " + sessionStorage.phone;

    document.getElementById("confirm_preferred").textContent = sessionStorage.preferred;

    document.getElementById("confirm_package").textContent = sessionStorage.package;

    document.getElementById("confirm_size").textContent = sessionStorage.size;

    document.getElementById("confirm_quantity").textContent = sessionStorage.quantity;
        cost = calcCost(sessionStorage.size, sessionStorage.quantity);

        document.getElementById("firstname").value = sessionStorage.firstname;
    document.getElementById("lastname").value = sessionStorage.lastname;
    document.getElementById("street").value = sessionStorage.street;
      document.getElementById("suburb").value = sessionStorage.suburb;
      document.getElementById("state").value = sessionStorage.state;
      document.getElementById("postcode").value = sessionStorage.postcode;
      document.getElementById("phone").value = sessionStorage.phone;
      document.getElementById("email").value = sessionStorage.email;
      document.getElementById("preferred").value = sessionStorage.preferred;
      document.getElementById("deal").value = sessionStorage.deal;
      document.getElementById("quality").value = sessionStorage.quality;
      document.getElementById("quantity").value = sessionStorage.quantity;
      document.getElementById("extrabags").value = sessionStorage.extrabags;
      document.getElementById("accomodation").value = sessionStorage.accomodation;
      document.getElementById("travel").value = sessionStorage.travel;
    document.getElementById("prohibiteditems").value = sessionStorage.prohibiteditems;
    document.getElementById("disabilityprecaution").value = sessionStorage.disabilityprecaution;
    }

}

function cancelBooking() {
window.location = "index.html"
}

function init() {

    getInfo();
    var payment = document.getElementById("payment");
    payment.onsubmit = function() {validate()};
    var cancel = document.getElementById("cancel");
    cancel.onclick = function cancelBooking()

}

window.onload = init;

</code>```

答:
The problem is inside your init() function. I have corrected it please try using this. You were calling the function cancelBooking() like this function cancelBooking() which was giving error.

```<code>function init() {

    getInfo();
    var payment = document.getElementById("payment");
    payment.onsubmit = function() {validate()};
    var cancel = document.getElementById("cancel");
    cancel.onclick = cancelBooking()

}
</code>```

Body:
Having trouble with a combined file of html, CSS and javascript  that is giving me an undisclosed error, used JSLint to check for errors but the only errors I were given were 'Line is longer than 80 characters', 'use spaces not tabs' and 'unexpected var'. Could someone please give me some help I'm real stuck.

"use strict";

//validate form inputs from payment.html
function validate() {

    var errMsg = "";
    var result = true;      //assumes no errors

    //assign elements to variables
    var mastercard_check = document.getElementById("mastercard").checked;
    var visa_check = document.getElementById("visa").checked;
    var express_check = document.getElementById("express").checked;
    var credit_name = document.getElementById("credit_name").value;
    var credit_number = document.getElementById("credit_number").value;
    var credit_expiry = document.getElementById("credit_expiry").value;
    var credit_vv = document.getElementById("credit_vv").value;

    //validations for form
    if (!(mastercard_check || visa_check || express_check)) {
        errMsg += "Please choose a card type\n";
        result = false;
    }

    if (credit_name.length > 40) {
        errMsg += "Please enter a name for your credit card between 1-40 characters\n";
        result = false;
    }
    else if (!credit_name.match(/^[a-zA-Z ]+$/)) {
        errMsg += "Credit card name can only contain alpha characters\n";
        result = false;
    }

    if (isNaN(credit_number)) {
        errMsg = errMsg + "Credit card number must contain digits only\n";
        result = false;
    }
    else if (credit_number.length < 15 || credit_number.length > 16){
        errMsg = errMsg + "Credit card number must contian either 15 or 16 digits\n";
        result = false;
    }
    else {
        var tempMsg = checkCardNumber(credit_number);
        if (tempMsg != "") {
            errMsg += tempMsg;
            result = false;
        }
    }

    if (!credit_expiry.match(/^\d{2}-\d{2}$/)) {
        errMsg = errMsg + "Credit Card expiry must follow the format mm-yy\n";
        result = false;
    }

    if (!credit_vv) {
        errMsg = errMsg + "Please enter a Credit Card Verification Value\n";
        result = false;
    }

    if (errMsg != "") {
        alert(errMsg);
    }

    return result;
}

//obtain the credit card type
function getCardType() {

    var cardType = "Unknown";
    var cardArray = document.getElementById("credit_type").getElementsByTagName("input");

    for(var i = 0; i < cardArray.length; i++) {
        if (cardArray[i].checked) {
            cardType = cardArray[i].value;
        }
    }
    return cardType

}

//check hte card number matches the chosen card type
function checkCardNumber(credit_number) {
    var errMsg = "";
    var card = getCardType();
    switch(card) {
        case "visa":
            if (!(credit_number.length == 16)) {
                errMsg = "Visa number must contian 16 digits\n";
            }
            else if (!credit_number.match(/^(4).*$/)) {
                errMsg = "Visa number must start with a 4. \n";
            }
            break;
        case "mastercard":
            if (!(credit_number.length == 16)) {
                errMsg = "Mastercard number must contian 16 digits\n";
            }
            else if (!credit_number.match(/^(51|52|53|54|55).*$/)) {
                errMsg = "Mastercard number must start with digits 51 through 55. \n";
            }
            break;
        case "express":
            if (!(credit_number.length == 15)) {
                errMsg = "American Express number must contian 15 digits\n";
            }
            else if (!credit_number.match(/^(34|37).*$/)) {
                errMsg = "American Express number must start with 34 or 37. \n";
            }
            break;
    }
    return errMsg;
}

//calculate total cost using the meal size and quantity chosen
function calcCost(size, quantity){
    var cost = 0;
    if (size.search("three") != -1) cost = 100;
    if (size.search("four")!= -1) cost += 150;
    if (size.search("five")!= -1) cost += 200;
}
//get the stored values
function getInfo(){
    var cost = 0;
    if(sessionStorage.firstname != undefined){
        document.getElementById("confirm_name").textContent = sessionStorage.firstname + " " + sessionStorage.lastname;

    document.getElementById("confirm_address").textContent = sessionStorage.address + " " + sessionStorage.suburb + " " + sessionStorage.state + " " + sessionStorage.postcode;

    document.getElementById("confirm_details").textContent = sessionStorage.email + " " + sessionStorage.phone;

    document.getElementById("confirm_preferred").textContent = sessionStorage.preferred;

    document.getElementById("confirm_package").textContent = sessionStorage.package;

    document.getElementById("confirm_size").textContent = sessionStorage.size;

    document.getElementById("confirm_quantity").textContent = sessionStorage.quantity;
        cost = calcCost(sessionStorage.size, sessionStorage.quantity);

        document.getElementById("firstname").value = sessionStorage.firstname;
    document.getElementById("lastname").value = sessionStorage.lastname;
    document.getElementById("street").value = sessionStorage.street;
      document.getElementById("suburb").value = sessionStorage.suburb;
      document.getElementById("state").value = sessionStorage.state;
      document.getElementById("postcode").value = sessionStorage.postcode;
      document.getElementById("phone").value = sessionStorage.phone;
      document.getElementById("email").value = sessionStorage.email;
      document.getElementById("preferred").value = sessionStorage.preferred;
      document.getElementById("deal").value = sessionStorage.deal;
      document.getElementById("quality").value = sessionStorage.quality;
      document.getElementById("quantity").value = sessionStorage.quantity;
      document.getElementById("extrabags").value = sessionStorage.extrabags;
      document.getElementById("accomodation").value = sessionStorage.accomodation;
      document.getElementById("travel").value = sessionStorage.travel;
    document.getElementById("prohibiteditems").value = sessionStorage.prohibiteditems;
    document.getElementById("disabilityprecaution").value = sessionStorage.disabilityprecaution;
    }

}

function cancelBooking() {
window.location = "index.html"
}

function init() {

    getInfo();
    var payment = document.getElementById("payment");
    payment.onsubmit = function() {validate()};
    var cancel = document.getElementById("cancel");
    cancel.onclick = function cancelBooking()

}

window.onload = init;

Body:
The problem is inside your init() function. I have corrected it please try using this. You were calling the function cancelBooking() like this function cancelBooking() which was giving error.

function init() {

    getInfo();
    var payment = document.getElementById("payment");
    payment.onsubmit = function() {validate()};
    var cancel = document.getElementById("cancel");
    cancel.onclick = cancelBooking()

}


答:
I just realized it, I found the resolved. Here the codes:

```<code>if let getrecurrence = get_reminder_detail.recurrenceRules?.first {
   if getrecurrence.frequency == .daily {print("Daily!")}
   if getrecurrence.frequency == .monthly {print("Monthly!")}
   if getrecurrence.frequency == .weekly {print("Weekly!")}
   if getrecurrence.frequency == .yearly {print("Yearly!")}
}
</code>```

I guess I ask question too early

Title: EKReminder with RecurrenceRules

Body:
I just realized it, I found the resolved. Here the codes:

if let getrecurrence = get_reminder_detail.recurrenceRules?.first {
   if getrecurrence.frequency == .daily {print("Daily!")}
   if getrecurrence.frequency == .monthly {print("Monthly!")}
   if getrecurrence.frequency == .weekly {print("Weekly!")}
   if getrecurrence.frequency == .yearly {print("Yearly!")}
}

I guess I ask question too early


问:
Is there any syntax in Python to check whether an integer input by the user contains a specific digit in it?
So I basically want to know whether there is any syntax that can recognize if the integer entered by the user contains some specified digit

For example: 23 has the digit 3.

答:
Convert the digit to a string, then check if the digit is in the string.

For example, I want to check if 9 is in the number.

```<code>x = str(50192301)
if '9' in x:
    return True
</code>```

Body:
Convert the digit to a string, then check if the digit is in the string.

For example, I want to check if 9 is in the number.

x = str(50192301)
if '9' in x:
    return True


问:
Dotted border around ASP.NET Button

I have a problem with asp:button styling. I added following style:

```<code>.myAspButton    {
        background-image: url("image for button");
        width: 110px;
        height: 25px;
        color: white;
        font-weight: bold;
        vertical-align: middle;
    }
<asp:Button ID="btnAsp" runat="server" Text="hhh" CssClass="myAspButton" BackColor="Transparent" BorderStyle="None" />
</code>```

Problem is when I press button it gets that dotted border around how to remove this?

And also what property to use to change button style when button is pressed down?

答:
```<code>outline: 0;
</code>```

Title: Dotted border around ASP.NET Button

Body:
I have a problem with asp:button styling. I added following style:

.myAspButton    {
        background-image: url("image for button");
        width: 110px;
        height: 25px;
        color: white;
        font-weight: bold;
        vertical-align: middle;
    }
<asp:Button ID="btnAsp" runat="server" Text="hhh" CssClass="myAspButton" BackColor="Transparent" BorderStyle="None" />

Problem is when I press button it gets that dotted border around how to remove this?

And also what property to use to change button style when button is pressed down?

Body: outline: 0;


问:
I keep being rejected by CLI - how to continue using node 8.x.x with Ionic 3 and Cordova 9?
Our project setup is Ionic 3 version, with Cordova 9, and 8.x.x Node.JS.

Everything was relatively fine, until recently, when I started getting this error from command line:

ERR: Your Node.js version is v8.11.3. Node.js 8 reached end-of-life on
  2019-12-31 and is no longer supported. Please update to the latest
  Node LTS version.

Usually I am getting it only when I try to build iOS app using Cordova, but sometimes it pops up even when I try to serve locally web app.

It doesn't start any process, the message pops immediately after I try to run a command, and that's it.

I am getting it ONLY on Mac machine, on Windows it works fine. It works fine also from other team members' Mac machines.

Does anyone has any idea how to get rid of it, or go around it? Upgrading Node.js is not an option atm. When I try running Node outside of Ionic project, it works perfectly. It seems that something inside out project refuse to work with 8.x.x Node.

答:
The culprit is ionic and not node.js. I had new version of ionic installed which didn't support the old node.js version.

first, remove installed ionic version from your system

```<code>npm uninstall -g ionic
</code>```

if the command doesn't work remove ionic manually from your .nvm directory or installed global node_module directory also remove ionic CLI executable from /bin directory.

then install ionic 3 using the command.

```<code>npm install -g ionic@3.2.0
</code>```

Body:
The culprit is ionic and not node.js. I had new version of ionic installed which didn't support the old node.js version.

first, remove installed ionic version from your system

npm uninstall -g ionic

if the command doesn't work remove ionic manually from your .nvm directory or installed global node_module directory also remove ionic CLI executable from /bin directory.

then install ionic 3 using the command.

npm install -g ionic@3.2.0