问:
How to Export HTML to Document without border or colored text
I want to create an editable text where you fill the contentEditable area and export the text result as document and I found a script online to that and I modify it but the problem i faced is that the contentEditable area is not visible it appears like fixed text until you click on it so I made a black border and red text for the contentEditable area so the user can see it but when I export the document it has black border and red text so How can i make them visible when you fill text and disappear when you export the document this my website that was inspired by this
 site and this the script jsfiddle

function Export2Doc(element, filename = ''){
    var preHtml = "<meta charset='utf-8'><title>Export HTML To Doc</title>";
    var postHtml = "";
    var html = preHtml+document.getElementById(element).innerHTML+postHtml;

    var blob = new Blob(['\ufeff', html], {
        type: 'application/msword'
    });

    // Specify link url
    var url = 'data:application/vnd.ms-word;charset=utf-8,' + encodeURIComponent(html);

    // Specify file name
    filename = filename?filename+'.doc':'document.doc';

    // Create download link element
    var downloadLink = document.createElement("a");

    document.body.appendChild(downloadLink);

    if(navigator.msSaveOrOpenBlob ){
        navigator.msSaveOrOpenBlob(blob, filename);
    }else{
        // Create a link to the file
        downloadLink.href = url;

        // Setting the file name
        downloadLink.download = filename;

        //triggering the function
        downloadLink.click();
    }

    document.body.removeChild(downloadLink);
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>span.a{

display:inline-block;

}</code>```

   Lorem Ipsum is simply dummy text of the printing and typesetting industry.
   Lorem Ipsum has been the industry's standard dummy text ever since the 1500s,

    when an unknown printer
     took a galley of type and scrambled it to make a type specimen book.
   It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.
   It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages,
   and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

<button onclick="Export2Doc('exportContent');">document</button>

```

答:
Remove the inline style from your editable span style="min-width:20px;border:1px solid black;color:red" and put it under the span.a selector where you set the display to inline-block.

function Export2Doc(element, filename = ''){
    var preHtml = "<meta charset='utf-8'><title>Export HTML To Doc</title>";
    var postHtml = "";
    var html = preHtml+document.getElementById(element).innerHTML+postHtml;

    var blob = new Blob(['\ufeff', html], {
        type: 'application/msword'
    });

    // Specify link url
    var url = 'data:application/vnd.ms-word;charset=utf-8,' + encodeURIComponent(html);

    // Specify file name
    filename = filename?filename+'.doc':'document.doc';

    // Create download link element
    var downloadLink = document.createElement("a");

    document.body.appendChild(downloadLink);

    if(navigator.msSaveOrOpenBlob ){
        navigator.msSaveOrOpenBlob(blob, filename);
    }else{
        // Create a link to the file
        downloadLink.href = url;

        // Setting the file name
        downloadLink.download = filename;

        //triggering the function
        downloadLink.click();
    }

    document.body.removeChild(downloadLink);
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>span.a{
    display:inline-block;
    min-width:20px;
    border:1px solid black;
    color:red;
}</code>```

   Lorem Ipsum is simply dummy text of the printing and typesetting industry.
   Lorem Ipsum has been the industry's standard dummy text ever since the 1500s,

    when an unknown printer
     took a galley of type and scrambled it to make a type specimen book.
   It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.
   It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages,
   and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

<button onclick="Export2Doc('exportContent');">document</button>

```

Body:
I want to create an editable text where you fill the contentEditable area and export the text result as document and I found a script online to that and I modify it but the problem i faced is that the contentEditable area is not visible it appears like fixed text until you click on it so I made a black border and red text for the contentEditable area so the user can see it but when I export the document it has black border and red text so How can i make them visible when you fill text and disappear when you export the document this my website that was inspired by this
 site and this the script jsfiddle

function Export2Doc(element, filename = ''){
    var preHtml = "<meta charset='utf-8'><title>Export HTML To Doc</title>";
    var postHtml = "";
    var html = preHtml+document.getElementById(element).innerHTML+postHtml;

    var blob = new Blob(['\ufeff', html], {
        type: 'application/msword'
    });

    // Specify link url
    var url = 'data:application/vnd.ms-word;charset=utf-8,' + encodeURIComponent(html);

    // Specify file name
    filename = filename?filename+'.doc':'document.doc';

    // Create download link element
    var downloadLink = document.createElement("a");

    document.body.appendChild(downloadLink);

    if(navigator.msSaveOrOpenBlob ){
        navigator.msSaveOrOpenBlob(blob, filename);
    }else{
        // Create a link to the file
        downloadLink.href = url;

        // Setting the file name
        downloadLink.download = filename;

        //triggering the function
        downloadLink.click();
    }

    document.body.removeChild(downloadLink);
}

span.a{

display:inline-block;

}

   Lorem Ipsum is simply dummy text of the printing and typesetting industry.
   Lorem Ipsum has been the industry's standard dummy text ever since the 1500s,

    when an unknown printer
     took a galley of type and scrambled it to make a type specimen book.
   It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.
   It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages,
   and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

<button onclick="Export2Doc('exportContent');">document</button>

Body:
Remove the inline style from your editable span style="min-width:20px;border:1px solid black;color:red" and put it under the span.a selector where you set the display to inline-block.

function Export2Doc(element, filename = ''){
    var preHtml = "<html xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:w='urn:schemas-microsoft-com:office:word' xmlns='http://www.w3.org/TR/REC-html40'><head><meta charset='utf-8'><title>Export HTML To Doc</title></head><body>";
    var postHtml = "</body></html>";
    var html = preHtml+document.getElementById(element).innerHTML+postHtml;

    var blob = new Blob(['\ufeff', html], {
        type: 'application/msword'
    });

    // Specify link url
    var url = 'data:application/vnd.ms-word;charset=utf-8,' + encodeURIComponent(html);

    // Specify file name
    filename = filename?filename+'.doc':'document.doc';

    // Create download link element
    var downloadLink = document.createElement("a");

    document.body.appendChild(downloadLink);

    if(navigator.msSaveOrOpenBlob ){
        navigator.msSaveOrOpenBlob(blob, filename);
    }else{
        // Create a link to the file
        downloadLink.href = url;

        // Setting the file name
        downloadLink.download = filename;

        //triggering the function
        downloadLink.click();
    }

    document.body.removeChild(downloadLink);
}

span.a{
    display:inline-block;
    min-width:20px;
    border:1px solid black;
    color:red;
}

<body>
<div id="exportContent">
   Lorem Ipsum is simply dummy text of the printing and typesetting industry.
   Lorem Ipsum has been the industry's standard dummy text ever since the 1500s,
   <span  class="a" contenteditable="true">
    when an unknown printer
    </span> took a galley of type and scrambled it to make a type specimen book.
   It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.
   It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages,
   and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</div>

<button onclick="Export2Doc('exportContent');">document</button>

</body>


来源: stackexchange

问:
ESP8266 Captive portal with pop-up
Has anyone ever succeeded in getting a captive portal to cause a pop-up for the redirected content to a specific landing page on an Arduino or ESP8266?
I've tried everything under the sun and while my android will complain about a non-connected internet and other things, it never actually requests/suggests opening a browser as I've seen done on some open-wifi hotspots with sign-in pages.
I'm trying to implement what will actually be a non-internet connected device that users would sign into at a remote location to show they had arrived, kind of like a geocache but using wifi sign in. I did the dnsServer glob (all names to local IP), I've done a number of url redirects. I've tried feeding the specific content (instead of the re-directs) but nothing pops up.

Relevant code:

```<code>#include <ESPAsyncWebServer.h>
#include <ESP8266WiFi.h>
#include <DNSServer.h>
#include <ESP8266mDNS.h>

IPAddress apIp ( 10, 10, 10, 10 );
AsyncWebServer asyncWebServer(80);
DNSServer dnsServer;
const char* captiveRedirect = "/index.htm";
String apSSID = "GeoCache";

dnsServer.setErrorReplyCode(DNSReplyCode::NoError);
dnsServer.start ( DNS_PORT, "*", apIp );

DBG_OUTPUT_PORT.println("Initializing MDNS for local hostname on AP");
if (MDNS.begin(apHostname)) {
    MDNS.addService("http", "tcp", 80);
    DBG_OUTPUT_PORT.println("MDNS responder started");
    DBG_OUTPUT_PORT.print("You can now connect to http://");
    DBG_OUTPUT_PORT.print(apHostname);
    DBG_OUTPUT_PORT.println(".local");
}

//Android captive portal. Maybe not needed. Might be handled by notFound handler.
asyncWebServer.addRewrite( new AsyncWebRewrite("/generate_204", captiveRedirect));
//asyncWebServer.on ( "/generate_204", returnOK );
//Microsoft captive portal. Maybe not needed. Might be handled by notFound handler.
asyncWebServer.addRewrite( new AsyncWebRewrite("/fwlink", captiveRedirect));
//asyncWebServer.on ( "/fwlink", returnOK );
//Microsoft windows 10
//asyncWebServer.on ( "/connecttest.txt", returnOK );
asyncWebServer.addRewrite( new AsyncWebRewrite("/connecttest.txt", captiveRedirect));
// apple devices
asyncWebServer.addRewrite( new AsyncWebRewrite("/hotspot-detect.html", captiveRedirect));
//asyncWebServer.on ( "/hotspot-detect.html", returnOK );
asyncWebServer.addRewrite( new AsyncWebRewrite("/library/test/success.html", captiveRedirect));
//asyncWebServer.on ( "/library/test/success.html", returnOK );
// kindle
asyncWebServer.addRewrite( new AsyncWebRewrite("/kindle-wifi/wifistub.html", captiveRedirect));
//asyncWebServer.on ( "/kindle-wifi/wifistub.html", returnOK );

asyncWebServer.on("/delete", HTTP_DELETE, handleDelete);
// upload a file to /upload
asyncWebServer.on("/upload", HTTP_POST, returnOK, handleUpload);
// Catch-All Handlers
asyncWebServer.onFileUpload(handleUpload);
//asyncWebServer.onRequestBody(onBody);

asyncWebServer.on("/signin", HTTP_GET, addLog);

asyncWebServer.onNotFound(handleNotFound);

asyncWebServer.begin();

WiFi.mode(WIFI_AP);
WiFi.softAPConfig ( apIp, apIp, IPAddress ( 255, 255, 255, 0 ) );
WiFi.softAP(apSSID);
</code>```

答:
In the loop(), you have to include:

```<code>dnsServer.processNextRequest();
</code>```

before

```<code>server.handleClient(); //Handling of incoming requests
</code>```

then, create a notfound router:

```<code>server.onNotFound([]() {
    char * msg = "HELLO<br>Default landing page<br>";
    server.send(200, "text/html", msg );
  });
</code>```

ContentLicense: CC BY-SA 3.0

Title: ESP8266 Captive portal with pop-up

Body:
Has anyone ever succeeded in getting a captive portal to cause a pop-up for the redirected content to a specific landing page on an Arduino or ESP8266?
I've tried everything under the sun and while my android will complain about a non-connected internet and other things, it never actually requests/suggests opening a browser as I've seen done on some open-wifi hotspots with sign-in pages.
I'm trying to implement what will actually be a non-internet connected device that users would sign into at a remote location to show they had arrived, kind of like a geocache but using wifi sign in. I did the dnsServer glob (all names to local IP), I've done a number of url redirects. I've tried feeding the specific content (instead of the re-directs) but nothing pops up.

Relevant code:

#include <ESPAsyncWebServer.h>
#include <ESP8266WiFi.h>
#include <DNSServer.h>
#include <ESP8266mDNS.h>

IPAddress apIp ( 10, 10, 10, 10 );
AsyncWebServer asyncWebServer(80);
DNSServer dnsServer;
const char* captiveRedirect = "/index.htm";
String apSSID = "GeoCache";

dnsServer.setErrorReplyCode(DNSReplyCode::NoError);
dnsServer.start ( DNS_PORT, "*", apIp );

DBG_OUTPUT_PORT.println("Initializing MDNS for local hostname on AP");
if (MDNS.begin(apHostname)) {
    MDNS.addService("http", "tcp", 80);
    DBG_OUTPUT_PORT.println("MDNS responder started");
    DBG_OUTPUT_PORT.print("You can now connect to http://");
    DBG_OUTPUT_PORT.print(apHostname);
    DBG_OUTPUT_PORT.println(".local");
}

//Android captive portal. Maybe not needed. Might be handled by notFound handler.
asyncWebServer.addRewrite( new AsyncWebRewrite("/generate_204", captiveRedirect));
//asyncWebServer.on ( "/generate_204", returnOK );
//Microsoft captive portal. Maybe not needed. Might be handled by notFound handler.
asyncWebServer.addRewrite( new AsyncWebRewrite("/fwlink", captiveRedirect));
//asyncWebServer.on ( "/fwlink", returnOK );
//Microsoft windows 10
//asyncWebServer.on ( "/connecttest.txt", returnOK );
asyncWebServer.addRewrite( new AsyncWebRewrite("/connecttest.txt", captiveRedirect));
// apple devices
asyncWebServer.addRewrite( new AsyncWebRewrite("/hotspot-detect.html", captiveRedirect));
//asyncWebServer.on ( "/hotspot-detect.html", returnOK );
asyncWebServer.addRewrite( new AsyncWebRewrite("/library/test/success.html", captiveRedirect));
//asyncWebServer.on ( "/library/test/success.html", returnOK );
// kindle
asyncWebServer.addRewrite( new AsyncWebRewrite("/kindle-wifi/wifistub.html", captiveRedirect));
//asyncWebServer.on ( "/kindle-wifi/wifistub.html", returnOK );

asyncWebServer.on("/delete", HTTP_DELETE, handleDelete);
// upload a file to /upload
asyncWebServer.on("/upload", HTTP_POST, returnOK, handleUpload);
// Catch-All Handlers
asyncWebServer.onFileUpload(handleUpload);
//asyncWebServer.onRequestBody(onBody);

asyncWebServer.on("/signin", HTTP_GET, addLog);

asyncWebServer.onNotFound(handleNotFound);

asyncWebServer.begin();

WiFi.mode(WIFI_AP);
WiFi.softAPConfig ( apIp, apIp, IPAddress ( 255, 255, 255, 0 ) );
WiFi.softAP(apSSID);

Body:
In the loop(), you have to include:

dnsServer.processNextRequest();

before

server.handleClient(); //Handling of incoming requests

then, create a notfound router:

server.onNotFound([]() {
    char * msg = "HELLO<br>Default landing page<br>";
    server.send(200, "text/html", msg );
  });

ContentLicense: CC BY-SA 4.0


问:
Why doesn't my use of "protected" work?
I have read that a protected member can be accessed from derived classes, but the following does not work.</p>

```<code>class A
{
    protected int Test;
}
class B:A
{
    A instanceOfA= new A()

    public B()
    {
        instanceOfA.Test //Not possible
    }
}
</code>```

答:
As B already inherits from A, you don't need a separate instance of A.

```<code>   public B()
   {
     this.Test = 1; //possible
   }
</code>```

Title: Why doesn't my use of "protected" work?

Body:
I have read that a protected member can be accessed from derived classes, but the following does not work.

class A
{
    protected int Test;
}
class B:A
{
    A instanceOfA= new A()

    public B()
    {
        instanceOfA.Test //Not possible
    }
}

Body:
As B already inherits from A, you don't need a separate instance of A.

   public B()
   {
     this.Test = 1; //possible
   }


问:
No suitable driver found for jdbc:mysql//localhost/sakila
I'm trying to set up JDBC but I'm getting this error.

I tried adding the dependency in pom.xml and even jar file nothing works. I tried the methods mentioned in previous questions, nothing works.

```<code>public class FilmLength {

public static void main(String[] args) throws SQLException  {
    Connection dbCon = null;
    PreparedStatement st = null;
    ResultSet rs = null;
    String url = "jdbc:mysql//localhost:3306/sakila";
    String username = "devuser";
    String password = "Demo@123";
    String query = "select * from film ";

    try {
        Class.forName("com.mysql.jdbc.Driver");
        dbCon = DriverManager.getConnection(url,username,password);
        st = dbCon.prepareStatement(query);
        rs = st.executeQuery();
        while(rs.next()) {
            String title = rs.getString(1);
            System.out.println(title);
        }
    } catch (Exception e) {

        e.printStackTrace();
    }
    finally {
        dbCon.close();
        st.close();
        rs.close();
    }

}

}
</code>```

答:
Instead of
String url = "jdbc:mysql//localhost:3306/sakila";

it should be
String url = "jdbc:mysql://localhost:3306/sakila";

Body:
I'm trying to set up JDBC but I'm getting this error.

I tried adding the dependency in pom.xml and even jar file nothing works. I tried the methods mentioned in previous questions, nothing works.

public class FilmLength {

public static void main(String[] args) throws SQLException  {
    Connection dbCon = null;
    PreparedStatement st = null;
    ResultSet rs = null;
    String url = "jdbc:mysql//localhost:3306/sakila";
    String username = "devuser";
    String password = "Demo@123";
    String query = "select * from film ";

    try {
        Class.forName("com.mysql.jdbc.Driver");
        dbCon = DriverManager.getConnection(url,username,password);
        st = dbCon.prepareStatement(query);
        rs = st.executeQuery();
        while(rs.next()) {
            String title = rs.getString(1);
            System.out.println(title);
        }
    } catch (Exception e) {

        e.printStackTrace();
    }
    finally {
        dbCon.close();
        st.close();
        rs.close();
    }

}

}


问:
Convert/cast an stdClass object to another class
I'm using a third party storage system that only returns me stdClass objects no matter what I feed in for some obscure reason. So I'm curious to know if there is a way to cast/convert an stdClass object into a full fledged object of a given type.

For instance something along the lines of:

```<code>//$stdClass is an stdClass instance
$converted = (BusinessClass) $stdClass;
</code>```

I am just casting the stdClass into an array and feed it to the BusinessClass constructor, but maybe there is a way to restore the initial class that I am not aware of.

Note: I am not interested in 'Change your storage system' type of answers since it is not the point of interest. Please consider it more an academic question on the language capacities.

Cheers

答:
Yet another approach.

The following is now possible thanks to the recent PHP 7 version.

$theStdClass = (object) [
  'a' => 'Alpha',
  'b' => 'Bravo',
  'c' => 'Charlie',
  'd' => 'Delta',
];

$foo = new class($theStdClass)  {
  public function __construct($data) {
    if (!is_array($data)) {
      $data = (array) $data;
    }

    foreach ($data as $prop => $value) {
      $this->{$prop} = $value;
    }
  }
  public function word4Letter($letter) {
    return $this->{$letter};
  }
};

print $foo->word4Letter('a') . PHP_EOL; // Alpha
print $foo->word4Letter('b') . PHP_EOL; // Bravo
print $foo->word4Letter('c') . PHP_EOL; // Charlie
print $foo->word4Letter('d') . PHP_EOL; // Delta
print $foo->word4Letter('e') . PHP_EOL; // PHP Notice:  Undefined property

```

In this example, $foo is being initialized as an anonymous class that takes one array or stdClass as only parameter for the constructor.

Eventually, we loop through the each items contained in the passed object and dynamically assign then to an object's property.

To make this approch event more generic, you can write an interface or a Trait that you will implement in any class where you want to be able to cast an stdClass.

Body:
I'm using a third party storage system that only returns me stdClass objects no matter what I feed in for some obscure reason. So I'm curious to know if there is a way to cast/convert an stdClass object into a full fledged object of a given type.

For instance something along the lines of:

//$stdClass is an stdClass instance
$converted = (BusinessClass) $stdClass;

I am just casting the stdClass into an array and feed it to the BusinessClass constructor, but maybe there is a way to restore the initial class that I am not aware of.

Note: I am not interested in 'Change your storage system' type of answers since it is not the point of interest. Please consider it more an academic question on the language capacities.

Cheers

Body:
Yet another approach.

The following is now possible thanks to the recent PHP 7 version.

$theStdClass = (object) [
  'a' => 'Alpha',
  'b' => 'Bravo',
  'c' => 'Charlie',
  'd' => 'Delta',
];

$foo = new class($theStdClass)  {
  public function __construct($data) {
    if (!is_array($data)) {
      $data = (array) $data;
    }

    foreach ($data as $prop => $value) {
      $this->{$prop} = $value;
    }
  }
  public function word4Letter($letter) {
    return $this->{$letter};
  }
};

print $foo->word4Letter('a') . PHP_EOL; // Alpha
print $foo->word4Letter('b') . PHP_EOL; // Bravo
print $foo->word4Letter('c') . PHP_EOL; // Charlie
print $foo->word4Letter('d') . PHP_EOL; // Delta
print $foo->word4Letter('e') . PHP_EOL; // PHP Notice:  Undefined property

In this example, $foo is being initialized as an anonymous class that takes one array or stdClass as only parameter for the constructor.

Eventually, we loop through the each items contained in the passed object and dynamically assign then to an object's property.

To make this approch event more generic, you can write an interface or a Trait that you will implement in any class where you want to be able to cast an stdClass.


问:
Blackberry check internet connection on device
How do I check if the Internet connection is ON or OFF on a device?</p>

答:
Here's what I use in my application, and it works just fine:</p>

```<code>protected static boolean isOutOfServiceRange() {
    return !RadioInfo.isDataServiceOperational();
}
</code>```

Body:
Here's what I use in my application, and it works just fine:

protected static boolean isOutOfServiceRange() {
    return !RadioInfo.isDataServiceOperational();
}


问:
How to use ILIKE for multiple values in single column in rails?
How to use ILIKE for multiple values in single column.

This is the solution for multiple values without using like condition:

```<code>Project.where(name: ["Arvind Oasis", "Prestige Jindal City"])
</code>```

In this example, it is taking the exact matches in my database. but i want to take similar matches for all the values.

How to use ILIKE for multiple values ["Arvind Oasis", "Rajkumar Jindal City"]

For single values i can use like this,

```<code>Project.where("name ILIKE ?", "%Prestige Kumar%")
</code>```

答:
Use: </p>

```<code>Project.where("name ILIKE ANY (array[?])", ["%Arvind Oasis%", "%Prestige Jindal City%", "%XXXX%"])
</code>```

Body:
How to use ILIKE for multiple values in single column.

This is the solution for multiple values without using like condition:

Project.where(name: ["Arvind Oasis", "Prestige Jindal City"])

In this example, it is taking the exact matches in my database. but i want to take similar matches for all the values.

How to use ILIKE for multiple values ["Arvind Oasis", "Rajkumar Jindal City"]

For single values i can use like this,

Project.where("name ILIKE ?", "%Prestige Kumar%")

Body:
Use:

Project.where("name ILIKE ANY (array[?])", ["%Arvind Oasis%", "%Prestige Jindal City%", "%XXXX%"])


问:
Hide a HTML Label in the CSS
We have a a interactive filter on our company website, used to show people based on department, without wanting to spend more money on a developer who has access to the templates, we can make CSS changes via wordpress.

Can hide the filters themselves at the moment as they seem to be contained within a style called : #Filters_Department

Label appears like this but other labels on the page we don't want to hide.

```<code><label>Department:</label>
</code>```

This Works for part of it.

```<code>#filters_department
{
display:none
}
</code>```

Have tried:

```<code>label[for="department"]
{
display:none;
}
</code>```

答:
I think you just have to add the for attribute to your label.</p>

```<code><label for="department">Department : </label>
</code>```

Title: Hide a HTML Label in the CSS

Body:
We have a a interactive filter on our company website, used to show people based on department, without wanting to spend more money on a developer who has access to the templates, we can make CSS changes via wordpress.

Can hide the filters themselves at the moment as they seem to be contained within a style called : #Filters_Department

Label appears like this but other labels on the page we don't want to hide.

Department:

This Works for part of it.

#filters_department
{
display:none
}

Have tried:

label[for="department"]
{
display:none;
}

Body:
I think you just have to add the for attribute to your label.

<label for="department">Department : </label>


问:
Message: stream_socket_enable_crypto(): Peer certificate CN=`some-address-here` did not match expected CN=`127.0.0.1'
I want to send an email using gmail but it has error as shown:

Message: stream_socket_enable_crypto(): Peer certificate CN=some-address-here did not match expected CN=`127.0.0.1'

Filename: PHPMailer-master/class.smtp.php

Message was not sentMailer Error: SMTP connect() failed.

Kindly help me. Thanks!

答: Probably, you used ssl connection on 465 port instead tls on 587.</p>


问:
How do I get the localhost name in PowerShell?
How do I get the localhost (machine) name in PowerShell? I am using PowerShell 1.0.</p>

答:
In PowerShell Core v6 (works on macOS, Linux and Windows):</p>

```<code>[Environment]::MachineName
</code>```

Body:
In PowerShell Core v6 (works on macOS, Linux and Windows):

[Environment]::MachineName


问:
Button not being positioned in React Native
My button seems to be not positioned in my react native project. The code that I have looks like this:

```<code><Button style = "centered"
      onPress = {() => {Alert.alert('Button tapped!');} }
      title = "Confirm"
    />
</code>```

Then in my style sheet I did this :

```<code> centered:{
    position: 'absolute',
    top : 350,
}
</code>```

And it did not work. Some other things that I tried:

```<code>style = {centered}
</code>```

Gives a run-time error saying can not find variable centered

```<code>class = "centered"
</code>```

Does not do anything, either.

According to suggestion, I tried creating a separate View for my button alone, but it gave an error saying JSX expressions must have one parent element. The code I tried:

```<code><View style={styles.container}>
    <Text>Select a time to be notified : </Text>
    <Picker
      style={styles.picker} itemStyle={styles.pickerItem}
      selectedValue={this.state.time}
      onValueChange={(itemValue) => this.setState({time: itemValue})}
    >
    <Picker.Item label="Now" value="now" />
      <Picker.Item label="After 1 minute" value="1min" />
      <Picker.Item label="After 5 minutes" value="5min" />
      <Picker.Item label="Custom time" value="ctime" />
    </Picker>
  </View>
  <View>
    <Button style = {{marginTop:350}}
    onPress = {() => {Alert.alert('Button tapped!');} }
    title = "Confirm"
    />
  </View>
);
</code>```

Style sheet:

```<code>const styles = StyleSheet.create({

 container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },

  picker :{
    width: 200,
    height: 44,
    backgroundColor: '#CCE6FF',
    borderColor: 'white',
    borderWidth: 1,
  },

  pickerItem :{
    width: 200,
    height: 88,
    backgroundColor: '#CCE6FF',
    borderColor: 'black',
    borderWidth: 1,
  },

  notificationButton :{
    position: 'absolute',
    top : 50,
  },
});
</code>```

答:
Add the button in a View, and style that view to center the button using alignItems and justifyContent.

```<code><View>
  <View style={styles.container}>
    <Text>Select a time to be notified : </Text>
    <Picker
      style={styles.picker}
      itemStyle={styles.pickerItem}
      selectedValue={this.state.time}
      onValueChange={itemValue => this.setState({ time: itemValue })}>
      <Picker.Item label="Now" value="now" />
      <Picker.Item label="After 1 minute" value="1min" />
      <Picker.Item label="After 5 minutes" value="5min" />
      <Picker.Item label="Custom time" value="ctime" />
    </Picker>
  </View>
  <View style={styles.confirmButton}>
    <Button
      style={{ marginTop: 350 }}
      onPress={() => {
        Alert.alert('Button tapped!');
      }}
      title="Confirm"
    />
  </View>
</View>
</code>```

Button Container style

```<code>confirmButton: {
  justifyContent: 'center',
  alignItems: 'center',
  marginTop: 10,
}
</code>```

Body:
My button seems to be not positioned in my react native project. The code that I have looks like this:

<Button style = "centered"
      onPress = {() => {Alert.alert('Button tapped!');} }
      title = "Confirm"
    />

Then in my style sheet I did this :

 centered:{
    position: 'absolute',
    top : 350,
}

And it did not work. Some other things that I tried:

style = {centered}

Gives a run-time error saying can not find variable centered

class = "centered"

Does not do anything, either.

According to suggestion, I tried creating a separate View for my button alone, but it gave an error saying JSX expressions must have one parent element. The code I tried:

<View style={styles.container}>
    <Text>Select a time to be notified : </Text>
    <Picker
      style={styles.picker} itemStyle={styles.pickerItem}
      selectedValue={this.state.time}
      onValueChange={(itemValue) => this.setState({time: itemValue})}
    >
    <Picker.Item label="Now" value="now" />
      <Picker.Item label="After 1 minute" value="1min" />
      <Picker.Item label="After 5 minutes" value="5min" />
      <Picker.Item label="Custom time" value="ctime" />
    </Picker>
  </View>
  <View>
    <Button style = {{marginTop:350}}
    onPress = {() => {Alert.alert('Button tapped!');} }
    title = "Confirm"
    />
  </View>
);

Style sheet:

const styles = StyleSheet.create({

 container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },

  picker :{
    width: 200,
    height: 44,
    backgroundColor: '#CCE6FF',
    borderColor: 'white',
    borderWidth: 1,
  },

  pickerItem :{
    width: 200,
    height: 88,
    backgroundColor: '#CCE6FF',
    borderColor: 'black',
    borderWidth: 1,
  },

  notificationButton :{
    position: 'absolute',
    top : 50,
  },
});

Body:
Add the button in a View, and style that view to center the button using alignItems and justifyContent.

<View>
  <View style={styles.container}>
    <Text>Select a time to be notified : </Text>
    <Picker
      style={styles.picker}
      itemStyle={styles.pickerItem}
      selectedValue={this.state.time}
      onValueChange={itemValue => this.setState({ time: itemValue })}>
      <Picker.Item label="Now" value="now" />
      <Picker.Item label="After 1 minute" value="1min" />
      <Picker.Item label="After 5 minutes" value="5min" />
      <Picker.Item label="Custom time" value="ctime" />
    </Picker>
  </View>
  <View style={styles.confirmButton}>
    <Button
      style={{ marginTop: 350 }}
      onPress={() => {
        Alert.alert('Button tapped!');
      }}
      title="Confirm"
    />
  </View>
</View>

Button Container style

confirmButton: {
  justifyContent: 'center',
  alignItems: 'center',
  marginTop: 10,
}


问:
Only extract those words from a list that include no repeating letters, using regex
I have a large word list file with one word per line. I would like to filter out the words with repeating alphabets.

```<code>INPUT:
  abducts
  abe
  abeam
  abel
  abele

OUTPUT:
  abducts
  abe
  abel
</code>```

I'd like to do this using Regex (grep or perl or python). Is that possible?

答:
You can't do this with Regex.  Regex is a Finite State Machine, and this would require a stack to store what letters have been seen.

I would suggest doing this with a foreach and manually check each word with code.
Something like

```<code>List chars
foreach word in list
    foreach letter in word
        if chars.contains letter then remove word from list
        else
            chars.Add letter
    chars.clear
</code>```

Body:
I have a large word list file with one word per line. I would like to filter out the words with repeating alphabets.

INPUT:
  abducts
  abe
  abeam
  abel
  abele

OUTPUT:
  abducts
  abe
  abel

I'd like to do this using Regex (grep or perl or python). Is that possible?

Body:
You can't do this with Regex.  Regex is a Finite State Machine, and this would require a stack to store what letters have been seen.

I would suggest doing this with a foreach and manually check each word with code.
Something like

List chars
foreach word in list
    foreach letter in word
        if chars.contains letter then remove word from list
        else
            chars.Add letter
    chars.clear


问:
MaterialTable - A state mutation was detected between dispatches
I have two sets of data that i want to display in table data so depending on the requirement, trying to set state of tabledata with different data.

Table Component:

```<code><Grid item xs={12} md={8}>
  {this.state.showTable && this.state.tableData !== null && (
       <MaterialTable
         title="Manage Blogs"
         columns={this.state.columns}
         data={this.state.tableData}
         actions={[
         {
           icon: "open_in_new",
           tooltip: "Open Blog",
           onClick: (blog, rowData) => {
            // Do save operation
            this.props.history.push("partner/blog/" + rowData._id);
             }
            }
          ]}
        />
  )}
</Grid>
</code>```

Following are the two places, where i am changing state of tableData:

```<code>  changeSelectedComponent = label => {
    debugger;
    if (this.state.selectedComponent.toString() !== label)
      this.setState(state => ({ selectedComponent: label }));
    if (label === "Blogs") {
      if (
        this.props.partnerBlogs === null &&
        this.props.apiCallsInProgress === 0
      ) {
        this.props.actions
          .loadPartnerBlogs(this.props.auth0UserProfile.sub)
          .catch(error => {
            alert("Loading events failed" + error);
          });
      } else if (this.props.apiCallsInProgress === 0) {
        this.setState({ tableData: this.props.partnerBlogs, showTable: true });
      }
    } else if (label === "Your Events") {
      if (
        this.props.partnerEvents === null &&
        this.props.apiCallsInProgress === 0
      ) {
        this.props.actions
          .loadPartnerEvents(this.props.auth0UserProfile.sub)
          .catch(error => {
            alert("Loading events failed" + error);
          });
      } else if (this.props.apiCallsInProgress === 0) {
        this.setState({ tableData: this.props.partnerEvents, showTable: true });
      }
    }
  };
</code>```

Another place after receiving new props:

```<code>  componentWillReceiveProps(nextProps) {
    debugger;
    if (
      this.props.partnerBlogs !== nextProps.partnerBlogs &&
      nextProps.apiCallsInProgress === 0
    ) {
      this.setState({
        tableData: nextProps.partnerBlogs,
        showTable: true
      });
    }
    if (
      this.props.partnerEvents !== nextProps.partnerEvents &&
      nextProps.apiCallsInProgress === 0
    ) {
      this.setState({
        tableData: nextProps.partnerEvents,
        showTable: true
      });
    }
  }
</code>```

Initial state of tableData is null. There is no issue when i am setting state for the first time but while changing state, getting following error

A state mutation was detected between dispatches, in the path
  partnerEvents.0.tableData. This may cause incorrect behavior.
  (http://redux.js.org/docs/Troubleshooting.html#never-mutate-reducer-arguments)

Don't know what's wrong in my code, Thanks for the help

答:
materialTable mutated your data adding the object TableData that contain row 'Id' and 'checked' elements, so I recommend use this in your code if you want to avoid the mutation:

data={this.state.yourData.map(x =>Object.assign({}, x))}

Please, let me know if that avoid the mutation issues that you are having.

Best Regards

Body:
I have two sets of data that i want to display in table data so depending on the requirement, trying to set state of tabledata with different data.

Table Component:

<Grid item xs={12} md={8}>
  {this.state.showTable && this.state.tableData !== null && (
       <MaterialTable
         title="Manage Blogs"
         columns={this.state.columns}
         data={this.state.tableData}
         actions={[
         {
           icon: "open_in_new",
           tooltip: "Open Blog",
           onClick: (blog, rowData) => {
            // Do save operation
            this.props.history.push("partner/blog/" + rowData._id);
             }
            }
          ]}
        />
  )}
</Grid>

Following are the two places, where i am changing state of tableData:

  changeSelectedComponent = label => {
    debugger;
    if (this.state.selectedComponent.toString() !== label)
      this.setState(state => ({ selectedComponent: label }));
    if (label === "Blogs") {
      if (
        this.props.partnerBlogs === null &&
        this.props.apiCallsInProgress === 0
      ) {
        this.props.actions
          .loadPartnerBlogs(this.props.auth0UserProfile.sub)
          .catch(error => {
            alert("Loading events failed" + error);
          });
      } else if (this.props.apiCallsInProgress === 0) {
        this.setState({ tableData: this.props.partnerBlogs, showTable: true });
      }
    } else if (label === "Your Events") {
      if (
        this.props.partnerEvents === null &&
        this.props.apiCallsInProgress === 0
      ) {
        this.props.actions
          .loadPartnerEvents(this.props.auth0UserProfile.sub)
          .catch(error => {
            alert("Loading events failed" + error);
          });
      } else if (this.props.apiCallsInProgress === 0) {
        this.setState({ tableData: this.props.partnerEvents, showTable: true });
      }
    }
  };

Another place after receiving new props:

  componentWillReceiveProps(nextProps) {
    debugger;
    if (
      this.props.partnerBlogs !== nextProps.partnerBlogs &&
      nextProps.apiCallsInProgress === 0
    ) {
      this.setState({
        tableData: nextProps.partnerBlogs,
        showTable: true
      });
    }
    if (
      this.props.partnerEvents !== nextProps.partnerEvents &&
      nextProps.apiCallsInProgress === 0
    ) {
      this.setState({
        tableData: nextProps.partnerEvents,
        showTable: true
      });
    }
  }

Initial state of tableData is null. There is no issue when i am setting state for the first time but while changing state, getting following error

A state mutation was detected between dispatches, in the path
  partnerEvents.0.tableData. This may cause incorrect behavior.
  (http://redux.js.org/docs/Troubleshooting.html#never-mutate-reducer-arguments)

Don't know what's wrong in my code, Thanks for the help


问:
Sharing secret across namespaces
Is there a way to share secrets across namespaces in Kubernetes?

My use case is: I have the same private registry for all my namespaces and I want to avoid creating the same secret for each.

答:
kubectl get secret gitlab-registry --namespace=revsys-com --export -o yaml |\
   kubectl apply --namespace=devspectrum-dev -f -</p>

Title: Sharing secret across namespaces


问:
Is there any reason why this php / mysql behaves differently on localhost and remote server?
I have my code working well on localhost, but when loaded on the remove server it behaves differently - the id on localhost shows as it should (see image) - id is in order.

However, on the remote server it is not, yet the code is identical!!

I have tried running just the sql query in myphpadmin on the remote server and it is fine.

```<code>$con = mysqli_connect("localhost", "******", "******", "ps10");

if (mysqli_connect_errno()) {
    echo "Failed to connect to MySQL: ".mysqli_connect_error();
}

if ($_POST['selClass'] == 'All records' OR $_SESSION['selClass'] == 'All records') {
    $query_rs4 = "SELECT *
                  FROM  marker
                  INNER JOIN users ON marker.class = users.class";
} else {
    if (empty($_POST['selClass']) && empty($_SESSION['selClass'])) {
        $query_rs4 = "SELECT *
                      FROM  marker
                      INNER JOIN users ON marker.class = users.class";
    } else {
        $query_rs4 = "SELECT *
                      FROM  marker
                      INNER JOIN users ON marker.class = users.class
                      WHERE users.username='{$_SESSION['selClass']}'";
    }
}

$rs4 = mysqli_query($con, $query_rs4) or die(mysqli_error($con));
$row = mysqli_num_rows($rs4);

echo "There are ".$row." students in this class";
</code>```

答:
Besides the fact that you don't show us the code that creates the table, which is functioning differently in the two machines, remember that saying

```<code>SELECT * FROM tableA JOIN tableb
</code>```

means that since there can be fields with the same name in the two tables you cannot be sure what field gets returned.

For example, if both the tables had an id field, using that query means that you don't know if you'll get tableA.id or tableB.id...

If, instead you say:

```<code>select tableA.* from tableA join tableB
</code>```

You will be sure that the id field will come from tableA...

Also, if you want the result ordered by id, you should EXPLICTLY add an ORDER BY tableA.id clause, otherwise the server can decide to give you the records in the order it likes, even a different one each time you do the query...

Body:
I have my code working well on localhost, but when loaded on the remove server it behaves differently - the id on localhost shows as it should (see image) - id is in order.

However, on the remote server it is not, yet the code is identical!!

I have tried running just the sql query in myphpadmin on the remote server and it is fine.

$con = mysqli_connect("localhost", "******", "******", "ps10");

if (mysqli_connect_errno()) {
    echo "Failed to connect to MySQL: ".mysqli_connect_error();
}

if ($_POST['selClass'] == 'All records' OR $_SESSION['selClass'] == 'All records') {
    $query_rs4 = "SELECT *
                  FROM  marker
                  INNER JOIN users ON marker.class = users.class";
} else {
    if (empty($_POST['selClass']) && empty($_SESSION['selClass'])) {
        $query_rs4 = "SELECT *
                      FROM  marker
                      INNER JOIN users ON marker.class = users.class";
    } else {
        $query_rs4 = "SELECT *
                      FROM  marker
                      INNER JOIN users ON marker.class = users.class
                      WHERE users.username='{$_SESSION['selClass']}'";
    }
}

$rs4 = mysqli_query($con, $query_rs4) or die(mysqli_error($con));
$row = mysqli_num_rows($rs4);

echo "There are ".$row." students in this class";

Body:
Besides the fact that you don't show us the code that creates the table, which is functioning differently in the two machines, remember that saying

SELECT * FROM tableA JOIN tableb

means that since there can be fields with the same name in the two tables you cannot be sure what field gets returned.

For example, if both the tables had an id field, using that query means that you don't know if you'll get tableA.id or tableB.id...

If, instead you say:

select tableA.* from tableA join tableB

You will be sure that the id field will come from tableA...

Also, if you want the result ordered by id, you should EXPLICTLY add an ORDER BY tableA.id clause, otherwise the server can decide to give you the records in the order it likes, even a different one each time you do the query...


问:
c++ vectors and pointers
As i understand if i dont store pointers, everything in c++ gets copied, which can lead to bad performance (ignore the simplicity of my example). So i thought i store my objects as pointers instead of string object inside my vector, thats better for performance right? (assumining i have very long strings and lots of them).

The problem when i try to iterate over my vector of string pointers is i cant extract the actual value from them

```<code>string test = "my-name";
vector<string*> names(20);
names.push_back(&test);

vector<string*>::iterator iterator = names.begin();
while (iterator != names.end())
{
    std::cout << (*iterator) << ":" << std::endl;
    // std::cout << *(*iterator); // fails

    iterator++;
}
</code>```

See the commented line, i have no problem in receiving the string pointer. But when i try to get the string pointers value i get an error (i couldnt find what excatly the error is but the program just fails).

I also tried storing (iterator) in a new string variable and but it didnt help?

答: Your code looks like you're storing a pointer to a stack-based variable into a vector. As soon as the function where your string is declared returns, that string becomes garbage and the pointer is invalid. If you're going to store pointers into a vector, you probably need to allocate your strings dynamically (using new).</p>

Title: c++ vectors and pointers

Body:
As i understand if i dont store pointers, everything in c++ gets copied, which can lead to bad performance (ignore the simplicity of my example). So i thought i store my objects as pointers instead of string object inside my vector, thats better for performance right? (assumining i have very long strings and lots of them).

The problem when i try to iterate over my vector of string pointers is i cant extract the actual value from them

string test = "my-name";
vector<string*> names(20);
names.push_back(&test);

vector<string*>::iterator iterator = names.begin();
while (iterator != names.end())
{
    std::cout << (*iterator) << ":" << std::endl;
    // std::cout << *(*iterator); // fails

    iterator++;
}

See the commented line, i have no problem in receiving the string pointer. But when i try to get the string pointers value i get an error (i couldnt find what excatly the error is but the program just fails).

I also tried storing (iterator) in a new string variable and but it didnt help?


问:
How to fix redirect to trailing slash with nginx and php backend
Like in this thread i run into the same problem with trailing slashes.

Directory /var/www/services contains several backend services.
For example, i'm requesting GET /customer?arg1=1&arg2=2 nginx will always redirects me to /customer/?arg1=1&arg2=2.

Nginx log output:

```<code>172.18.0.6 - - [29/May/2019:14:47:32 +0000] "GET /customer?limit=1&filter%5Bemail%5D=somemail%40gmail.com&filter%5BwebsiteId%5D=1 HTTP/1.1" 301 170 "-" "GuzzleHttp/6.3.3 curl/7.29.0 PHP/7.0.33"
172.18.0.6 - - [29/May/2019:14:47:32 +0000] "GET /customer/?limit=1&filter%5Bemail%5D=somemail%40gmail.com&filter%5BwebsiteId%5D=1 HTTP/1.1" 200 12 "-" "GuzzleHttp/6.3.3 curl/7.29.0 PHP/7.0.33"
</code>```

All other requests, like customer/count works as expected.

How can i avoid such undesired behaviour?

Configuration is below:

```<code>server {
        listen 80;
        listen 443 ssl;
        server_name api.local;
        root /var/www/services;

        ssl_certificate  /etc/ssl/certs/optimax.crt;
        ssl_certificate_key /etc/ssl/certs/optimax.key;
        ssl_dhparam /etc/ssl/certs/optimax.pem;

        location ~ ^/(?<ms_dir>[^/]+)/(.*)$ {
                root /var/www/services/$ms_dir/public;
                set $ms_request $2;
                try_files $uri /index.php$is_args$args;
        }

        location ~ /index\.php(/|$) {
                fastcgi_pass php72:9001;
                fastcgi_split_path_info ^(.+\.php)(/.+)$;
                include fastcgi_params;
                fastcgi_param REQUEST_URI $ms_request;
                fastcgi_param SCRIPT_FILENAME $realpath_root/$ms_dir/public$fastcgi_script_name;
                fastcgi_param DOCUMENT_ROOT $realpath_root/$ms_dir/public;
        }

        access_log /dev/stdout;
        error_log /dev/stderr;
        rewrite_log on;
}
</code>```

答:
The Richard Smith's suggestion works perfect.

Updated config below:

```<code>server {
        listen 80;
        listen 443 ssl;
        server_name api.local;
        root /var/www/services;

        ssl_certificate  /etc/ssl/certs/optimax.crt;
        ssl_certificate_key /etc/ssl/certs/optimax.key;
        ssl_dhparam /etc/ssl/certs/optimax.pem;

        location ~ /index\.php(/|$) {
                fastcgi_pass php72:9001;
                fastcgi_split_path_info ^(.+\.php)(/.+)$;
                include fastcgi_params;
                fastcgi_param REQUEST_URI $ms_request;
                fastcgi_param SCRIPT_FILENAME $realpath_root/$ms_dir/public$fastcgi_script_name;
                fastcgi_param DOCUMENT_ROOT $realpath_root/$ms_dir/public;
        }

        location ~ ^/(?<ms_dir>[^/]+)(?:/(.*))$ {
                root /var/www/services/$ms_dir/public;
                set $ms_request $2;
                try_files $uri /index.php$is_args$args;
        }

        access_log /dev/stdout;
        error_log /dev/stderr;
        rewrite_log on;
}
</code>```

Body:
Like in this thread i run into the same problem with trailing slashes.

Directory /var/www/services contains several backend services.
For example, i'm requesting GET /customer?arg1=1&arg2=2 nginx will always redirects me to /customer/?arg1=1&arg2=2.

Nginx log output:

172.18.0.6 - - [29/May/2019:14:47:32 +0000] "GET /customer?limit=1&filter%5Bemail%5D=somemail%40gmail.com&filter%5BwebsiteId%5D=1 HTTP/1.1" 301 170 "-" "GuzzleHttp/6.3.3 curl/7.29.0 PHP/7.0.33"
172.18.0.6 - - [29/May/2019:14:47:32 +0000] "GET /customer/?limit=1&filter%5Bemail%5D=somemail%40gmail.com&filter%5BwebsiteId%5D=1 HTTP/1.1" 200 12 "-" "GuzzleHttp/6.3.3 curl/7.29.0 PHP/7.0.33"

All other requests, like customer/count works as expected.

How can i avoid such undesired behaviour?

Configuration is below:

server {
        listen 80;
        listen 443 ssl;
        server_name api.local;
        root /var/www/services;

        ssl_certificate  /etc/ssl/certs/optimax.crt;
        ssl_certificate_key /etc/ssl/certs/optimax.key;
        ssl_dhparam /etc/ssl/certs/optimax.pem;

        location ~ ^/(?<ms_dir>[^/]+)/(.*)$ {
                root /var/www/services/$ms_dir/public;
                set $ms_request $2;
                try_files $uri /index.php$is_args$args;
        }

        location ~ /index\.php(/|$) {
                fastcgi_pass php72:9001;
                fastcgi_split_path_info ^(.+\.php)(/.+)$;
                include fastcgi_params;
                fastcgi_param REQUEST_URI $ms_request;
                fastcgi_param SCRIPT_FILENAME $realpath_root/$ms_dir/public$fastcgi_script_name;
                fastcgi_param DOCUMENT_ROOT $realpath_root/$ms_dir/public;
        }

        access_log /dev/stdout;
        error_log /dev/stderr;
        rewrite_log on;
}

Body:
The Richard Smith's suggestion works perfect.

Updated config below:

server {
        listen 80;
        listen 443 ssl;
        server_name api.local;
        root /var/www/services;

        ssl_certificate  /etc/ssl/certs/optimax.crt;
        ssl_certificate_key /etc/ssl/certs/optimax.key;
        ssl_dhparam /etc/ssl/certs/optimax.pem;

        location ~ /index\.php(/|$) {
                fastcgi_pass php72:9001;
                fastcgi_split_path_info ^(.+\.php)(/.+)$;
                include fastcgi_params;
                fastcgi_param REQUEST_URI $ms_request;
                fastcgi_param SCRIPT_FILENAME $realpath_root/$ms_dir/public$fastcgi_script_name;
                fastcgi_param DOCUMENT_ROOT $realpath_root/$ms_dir/public;
        }

        location ~ ^/(?<ms_dir>[^/]+)(?:/(.*))$ {
                root /var/www/services/$ms_dir/public;
                set $ms_request $2;
                try_files $uri /index.php$is_args$args;
        }

        access_log /dev/stdout;
        error_log /dev/stderr;
        rewrite_log on;
}


答:
Why don't you try adding a class to the label and targeting it that way? </p>

```<code><label class="hidden">Hidden label</label>

.hidden { display: none;}
</code>```

Title: Hide a HTML Label in the CSS

Body:
Why don't you try adding a class to the label and targeting it that way?

<label class="hidden">Hidden label</label>

.hidden { display: none;}


问:
Python: List index out of range for hash table program
Not sure if this code works and it shows index out of range which I don't know how to solve

```<code>class Hash():

    def __init__(self, user):
        self.max = user
        self.table = []

    def isFull(self):
        if len(self.table) == self.max:
            return True
        else:
            return False
    def insert(self,item):
        if self.isFull():
            print('Hash table is full')
        else:
            hashing = self.index(item)
            if self.table[hashing] == None:
                self.table[hashing] = item
            else:
                for a in range(len(self.table)):
                    if self.table[a] == None:
                        self.table[a] = item
        return self.table

    def index(self,item):
        hashval = int(item) % self.max
        return hashval

    def searching(self,item):
        pass

user = int(input('Enter a number for the maximum number of items that can be stored in the hash table: '))
</code>```

It says index is out of range due to -> if self.table[hashing] == None:

答:
You are using list instead of dict. You should replace self.table = [] with self.table = {}

if self.table[hashing] == None: will raise an error if hashing not in self.table. You should replace it with: if hashing not in self.table:

for a in range(len(self.table)): will not iterate through self.table because it is not a list. for a in self.table: will work.

Here is the correct code:

```<code>class Hash():

    def __init__(self, user):
        self.max = user
        self.table = {}

    def isFull(self):
        if len(self.table) == self.max:
            return True
        else:
            return False
    def insert(self,item):
        if self.isFull():
            print('Hash table is full')
        else:
            hashing = self.index(item)
            if hashing not in self.table:
                self.table[hashing] = item
            else:
                for a in self.table:
                    if self.table[a] == None:
                        self.table[a] = item
        return self.table

    def index(self,item):
        hashval = int(item) % self.max
        return hashval

    def searching(self,item):
        pass

user = int(input('Enter a number for the maximum number of items that can be stored in the hash table: '))
h = Hash(user)
h.insert(5)
h.insert(6)
</code>```

Body:
Not sure if this code works and it shows index out of range which I don't know how to solve

class Hash():

    def __init__(self, user):
        self.max = user
        self.table = []

    def isFull(self):
        if len(self.table) == self.max:
            return True
        else:
            return False
    def insert(self,item):
        if self.isFull():
            print('Hash table is full')
        else:
            hashing = self.index(item)
            if self.table[hashing] == None:
                self.table[hashing] = item
            else:
                for a in range(len(self.table)):
                    if self.table[a] == None:
                        self.table[a] = item
        return self.table

    def index(self,item):
        hashval = int(item) % self.max
        return hashval

    def searching(self,item):
        pass

user = int(input('Enter a number for the maximum number of items that can be stored in the hash table: '))

It says index is out of range due to -> if self.table[hashing] == None:

Body:
You are using list instead of dict. You should replace self.table = [] with self.table = {}

if self.table[hashing] == None: will raise an error if hashing not in self.table. You should replace it with: if hashing not in self.table:

for a in range(len(self.table)): will not iterate through self.table because it is not a list. for a in self.table: will work.

Here is the correct code:

class Hash():

    def __init__(self, user):
        self.max = user
        self.table = {}

    def isFull(self):
        if len(self.table) == self.max:
            return True
        else:
            return False
    def insert(self,item):
        if self.isFull():
            print('Hash table is full')
        else:
            hashing = self.index(item)
            if hashing not in self.table:
                self.table[hashing] = item
            else:
                for a in self.table:
                    if self.table[a] == None:
                        self.table[a] = item
        return self.table

    def index(self,item):
        hashval = int(item) % self.max
        return hashval

    def searching(self,item):
        pass

user = int(input('Enter a number for the maximum number of items that can be stored in the hash table: '))
h = Hash(user)
h.insert(5)
h.insert(6)


问:
Why isn't CSS loading consistently in my printing iframe?
So, my page has a div that I want to print. It uses bootstrap and fontawesome to look good. To print it, I have a button to create an iframe, copy the outerHTML into its body and some css and js to its head, make some modifications to fit the A4 paper, print it and then remove it. The thing is that the first time I click the button it shows chrome's print page beautifully, exactly the way I want, but when I click the button again it looses some of the styling.

I noticed on the network tab of chrome's devtools that the js and css files load just fine the first time but after that it shows as pending when the printing window is shown, only loading after I close it.

This is the function called by the button:

```<code>function print1(elem)
{
    $('<iframe>', {
        id: 'printFrame',
        name: 'printFrame',
        class: 'printFrame',
        style: 'display: none'
    }).appendTo('body').contents()

    .find('head')
        .append('<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />')
        .append('<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.3.1/css/all.css" integrity="sha384-mzrmE5qonljUremFsqc01SB46JvROS7bZs3IO2EmfFsd15uHvIt+Y8vEf7N7fWAU" crossorigin="anonymous">')
        .append('<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto|Roboto+Condensed">')
        .append('<link rel="stylesheet" href="/css/wscustom.css" type="text/css">')
        .append('<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js" />')
        .append('<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" />')
        .append($('style')[0].outerHTML)
        .parent()

    .find('body')
        .css('font-family', 'Roboto, sans-serif')
        .css('font-size', '14px')
        .css('line-height', '1.428571429')
        .css('color', '#333')
        .css('box-sizing', 'border-box')
        .append('<div class="container">')
        .find('.container')
        .append($('#' + elem).clone())

    .find('div.col-xs-12.col-md-6.col-lg-4')
        .removeClass('col-xs-12').removeClass('col-md-6').removeClass('col-lg-4').addClass('col-4')
        .css('width', '31.7%')
        .css('margin', '5px')
        .css('height', '514px')
        .css('float', 'left')
        .css('position', 'relative')
        .find('.fa-redo').hide();

    window.frames['printFrame'].focus();
    window.frames['printFrame'].print();
    $("#printFrame").remove();
}
</code>```

Like I mentioned above, I suspect it has something to do with the js and css files that are hanging on "pending" while the print window is open.

Besides a lot of bootstrap styling missing, one detail that shows when it works (the first time I click the button) are fontawesome stars in blue and gray. After the first click it sometimes shows in black and sometimes doesn't show at all.

Any insights would be much appreciated.

答:
It's probably printing before everything is loaded. Put your print action in the iframe, not the parent page, and wrap it in a READY handler.</p>

```<code>$(document).ready(function() { window.print(); }
</code>```

Body:
So, my page has a div that I want to print. It uses bootstrap and fontawesome to look good. To print it, I have a button to create an iframe, copy the outerHTML into its body and some css and js to its head, make some modifications to fit the A4 paper, print it and then remove it. The thing is that the first time I click the button it shows chrome's print page beautifully, exactly the way I want, but when I click the button again it looses some of the styling.

I noticed on the network tab of chrome's devtools that the js and css files load just fine the first time but after that it shows as pending when the printing window is shown, only loading after I close it.

This is the function called by the button:

function print1(elem)
{
    $('', {
        id: 'printFrame',
        name: 'printFrame',
        class: 'printFrame',
        style: 'display: none'
    }).appendTo('body').contents()

    .find('head')
        .append('<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />')
        .append('<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.3.1/css/all.css" integrity="sha384-mzrmE5qonljUremFsqc01SB46JvROS7bZs3IO2EmfFsd15uHvIt+Y8vEf7N7fWAU" crossorigin="anonymous">')
        .append('<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto|Roboto+Condensed">')
        .append('<link rel="stylesheet" href="/css/wscustom.css" type="text/css">')
        .append('

Body:
It's probably printing before everything is loaded. Put your print action in the iframe, not the parent page, and wrap it in a READY handler.

$(document).ready(function() { window.print(); }


问:
Best way to store laravel API tokens?
I'm currently setting up a new project in Laravel.

Upon logging in I want to store the logged in user's token. so, I can make other API request in other controllers using this format,

Code:

```<code>$response = $client->request('POST', '/api/user', [
'headers' => [
    'Authorization' => 'Bearer '.$token,
    'Accept' => 'application/json',
],]);
</code>```

I'm not quite sure, how I will store $token so it can be accessed in all controllers.

答:
Normally, APIs that use token based authentication require the token to be sent with each request as the APIs are, hopefully, stateless. This means that whatever controller of yours is handling the user request will also have the token to perform other requests in the background. In your controller, you should be able to retrieve the token like so:

```<code>class MyController
{
    public function index(Request $request)
    {
        $authorization = $request->header('Authorization');
        $token = null;
        if (substr($authorization, 0, 7) === "Bearer ") {
            $token = substr($authorization, 7);
        }

        // in theory, this is obsolete as your controller should only
        // be called if there is a valid token present on the request
        if ($token === null) {
            abort(403); // or whatever
        }

        $client = ...; // initialize the client
        $response = $client->request('POST', '/api/user', [
            'headers' => [
                'Authorization' => 'Bearer '.$token,
                'Accept' => 'application/json',
            ],
        ]);

        // return some response to the user
    }
}
</code>```

Obviously it makes sense to extract the token parsing into its own function which lives in a base controller that all other controllers inherit from. In your concrete example you could also simply use ['headers' => ['Authorization' => $request->header('Authorization')]] as you only want to forward the header.

Old answer which doesn't make any sense:

Store the token in the session data of the user:

```<code>session(['token' => $token]);
</code>```

The array indicates that you set data in the session. Retrieving the token is even easier:

```<code>$token = session('token');
</code>```

Title: Best way to store laravel API tokens?

Body:
I'm currently setting up a new project in Laravel.

Upon logging in I want to store the logged in user's token. so, I can make other API request in other controllers using this format,

Code:

$response = $client->request('POST', '/api/user', [
'headers' => [
    'Authorization' => 'Bearer '.$token,
    'Accept' => 'application/json',
],]);

I'm not quite sure, how I will store $token so it can be accessed in all controllers.

Body:
Normally, APIs that use token based authentication require the token to be sent with each request as the APIs are, hopefully, stateless. This means that whatever controller of yours is handling the user request will also have the token to perform other requests in the background. In your controller, you should be able to retrieve the token like so:

class MyController
{
    public function index(Request $request)
    {
        $authorization = $request->header('Authorization');
        $token = null;
        if (substr($authorization, 0, 7) === "Bearer ") {
            $token = substr($authorization, 7);
        }

        // in theory, this is obsolete as your controller should only
        // be called if there is a valid token present on the request
        if ($token === null) {
            abort(403); // or whatever
        }

        $client = ...; // initialize the client
        $response = $client->request('POST', '/api/user', [
            'headers' => [
                'Authorization' => 'Bearer '.$token,
                'Accept' => 'application/json',
            ],
        ]);

        // return some response to the user
    }
}

Obviously it makes sense to extract the token parsing into its own function which lives in a base controller that all other controllers inherit from. In your concrete example you could also simply use ['headers' => ['Authorization' => $request->header('Authorization')]] as you only want to forward the header.

Old answer which doesn't make any sense:

Store the token in the session data of the user:

session(['token' => $token]);

The array indicates that you set data in the session. Retrieving the token is even easier:

$token = session('token');


问:
How to generate promo code for android app subscription?
I want to generate promo code for my app subscription, but when i
         go to promotion on google play console and trying to add/GET, it
         just give a message

This product is not available for promotion.

Please help me if any one have any solution.

答:
In the "create promotions" Google support page:

https://support.google.com/googleplay/android-developer/answer/6321495

it specifically states:

"For subscription promotions, you can create up to 10,000 promo codes per quarter per subscription product. This does not count towards the limit of promo codes for managed products."


问:
How to use customjs to update dropdown menu choices dynamically in Bokeh
I am trying to update a dropdown menu depending on the choice made by the user in a previous dropdown menu by using customjs callbacks in Bokeh. In the example below, the user can either create a basic graph based on selecting a common_name OR by selecting a quadrat. But I would like the user to be able to first choose a common_name, and then choose a quadrat based on the data available for that common_name (i.e based on the common_name first selected). Any ideas ?</p>

```<code>from bokeh.models import CustomJS, ColumnDataSource, MultiSelect, Column

from bokeh.plotting import figure, show
from bokeh.layouts import row, column
import pandas as pd

# data
data = dict(common_name = ['A','A','B','C','B','B','A','C','C','B','A','B','C'],
length = [10, 20, 10, 20, 30, 20, 20, 30, 20, 30, 30, 20, 30],
weight = [100, 200, 100, 300, 100, 400, 100, 300, 100, 400, 500, 600, 450],
quadrat = ['N', 'N', 'N', 'N', 'M', 'M', 'M', 'M', 'O', 'O', 'M', 'N', 'O'])

data = pd.DataFrame(data)

data_source = ColumnDataSource(data)

# Empty source so the plot is empty before data is selected
source = ColumnDataSource(dict(length = [], weight = []))

plot = figure()

plot.circle(x = 'length', y = 'weight', source = source)

# Select species
available_species = list(set(data['common_name']))
available_species.sort()

species_callback = CustomJS(args = {'source': source, 'data_source': data_source},
code = """
var data = data_source.data;
var source_data = source.data;
var common_name = data['common_name'];
var selected_species = cb_obj.value;
var length_data = data['length'];
var weight_data = data['weight'];
var length = source_data['length'];
length.length = 0;
var weight = source_data['weight'];
weight.length = 0;
 for (var i = 0; i < length_data.length; i++) {
  if (selected_species.indexOf(common_name[i]) >= 0) {
   length.push(length_data[i]);
   weight.push(weight_data[i]);
    }
  }
  source.change.emit();
  """)

multiselect_species = MultiSelect(title = 'Species:', value = [], options = available_species, width = 240)

# Select quadrat
available_quadrat = list(set(data['quadrat']))
available_quadrat.sort()

quadrat_callback = CustomJS(args = {'source': source, 'data_source': data_source},
code = """
var data = data_source.data;
var source_data = source.data;
var quadrat = data['quadrat'];
var selected_quadrat = cb_obj.value;
var length_data = data['length'];
var weight_data = data['weight'];
var length = source_data['length'];
length.length = 0;
  var weight = source_data['weight'];
  weight.length = 0;
  for (var i = 0; i < length_data.length; i++) {
    if (selected_quadrat.indexOf(quadrat[i]) >= 0) {
      length.push(length_data[i]);
      weight.push(weight_data[i]);
    }
  }
  source.change.emit();
  """)

multiselect_quadrat = MultiSelect(title = 'Set:', value = [], options = available_quadrat, width = 240)
multiselect_quadrat.js_on_change('value', quadrat_callback)

multiselect_species.js_on_change('value', species_callback, CustomJS(args = dict(multiselect_quadrat = multiselect_quadrat,
                                                                                available_quadrat = available_quadrat),
code="""
const available_quadrat = %s
multiselect_quadrat.options = "available_quadrat[cb_obj.value]"
""" % available_quadrat))

  # Set up widgets layout
widgets_layout = column(multiselect_species, multiselect_quadrat)

page_layout = row(widgets_layout, plot)

show(page_layout)

</code>```

答:
Here is a complete example that updates a MultiSelect based on a CustomJS callback for another widget:

```<code>from bokeh.io import show
from bokeh.layouts import column
from bokeh.models import RadioButtonGroup, CustomJS, MultiSelect

opts = {
    0: ["foo", "bar"],
    1: ["baz", "quux"],
}

bg = RadioButtonGroup(labels=["Stuff", "Things"], active=0)

ms = MultiSelect(options=opts[0])

bg.js_on_change('active', CustomJS(args=dict(ms=ms), code="""
    const opts = %s
    ms.options = opts[cb_obj.active]
""" % opts))

show(column(bg, ms)
</code>```

Body:
I am trying to update a dropdown menu depending on the choice made by the user in a previous dropdown menu by using customjs callbacks in Bokeh. In the example below, the user can either create a basic graph based on selecting a common_name OR by selecting a quadrat. But I would like the user to be able to first choose a common_name, and then choose a quadrat based on the data available for that common_name (i.e based on the common_name first selected). Any ideas ?

from bokeh.models import CustomJS, ColumnDataSource, MultiSelect, Column

from bokeh.plotting import figure, show
from bokeh.layouts import row, column
import pandas as pd

# data
data = dict(common_name = ['A','A','B','C','B','B','A','C','C','B','A','B','C'],
length = [10, 20, 10, 20, 30, 20, 20, 30, 20, 30, 30, 20, 30],
weight = [100, 200, 100, 300, 100, 400, 100, 300, 100, 400, 500, 600, 450],
quadrat = ['N', 'N', 'N', 'N', 'M', 'M', 'M', 'M', 'O', 'O', 'M', 'N', 'O'])

data = pd.DataFrame(data)

data_source = ColumnDataSource(data)

# Empty source so the plot is empty before data is selected
source = ColumnDataSource(dict(length = [], weight = []))

plot = figure()

plot.circle(x = 'length', y = 'weight', source = source)

# Select species
available_species = list(set(data['common_name']))
available_species.sort()

species_callback = CustomJS(args = {'source': source, 'data_source': data_source},
code = """
var data = data_source.data;
var source_data = source.data;
var common_name = data['common_name'];
var selected_species = cb_obj.value;
var length_data = data['length'];
var weight_data = data['weight'];
var length = source_data['length'];
length.length = 0;
var weight = source_data['weight'];
weight.length = 0;
 for (var i = 0; i < length_data.length; i++) {
  if (selected_species.indexOf(common_name[i]) >= 0) {
   length.push(length_data[i]);
   weight.push(weight_data[i]);
    }
  }
  source.change.emit();
  """)

multiselect_species = MultiSelect(title = 'Species:', value = [], options = available_species, width = 240)

# Select quadrat
available_quadrat = list(set(data['quadrat']))
available_quadrat.sort()

quadrat_callback = CustomJS(args = {'source': source, 'data_source': data_source},
code = """
var data = data_source.data;
var source_data = source.data;
var quadrat = data['quadrat'];
var selected_quadrat = cb_obj.value;
var length_data = data['length'];
var weight_data = data['weight'];
var length = source_data['length'];
length.length = 0;
  var weight = source_data['weight'];
  weight.length = 0;
  for (var i = 0; i < length_data.length; i++) {
    if (selected_quadrat.indexOf(quadrat[i]) >= 0) {
      length.push(length_data[i]);
      weight.push(weight_data[i]);
    }
  }
  source.change.emit();
  """)

multiselect_quadrat = MultiSelect(title = 'Set:', value = [], options = available_quadrat, width = 240)
multiselect_quadrat.js_on_change('value', quadrat_callback)

multiselect_species.js_on_change('value', species_callback, CustomJS(args = dict(multiselect_quadrat = multiselect_quadrat,
                                                                                available_quadrat = available_quadrat),
code="""
const available_quadrat = %s
multiselect_quadrat.options = "available_quadrat[cb_obj.value]"
""" % available_quadrat))

  # Set up widgets layout
widgets_layout = column(multiselect_species, multiselect_quadrat)

page_layout = row(widgets_layout, plot)

show(page_layout)

Body:
Here is a complete example that updates a MultiSelect based on a CustomJS callback for another widget:

from bokeh.io import show
from bokeh.layouts import column
from bokeh.models import RadioButtonGroup, CustomJS, MultiSelect

opts = {
    0: ["foo", "bar"],
    1: ["baz", "quux"],
}

bg = RadioButtonGroup(labels=["Stuff", "Things"], active=0)

ms = MultiSelect(options=opts[0])

bg.js_on_change('active', CustomJS(args=dict(ms=ms), code="""
    const opts = %s
    ms.options = opts[cb_obj.active]
""" % opts))

show(column(bg, ms)


问:
Javascript / Nodejs use await on top level in nodejs module
I tried finding the solution to my problem, but couldnt find it, and was looking for some "best practice examples". I have a nodejs express application and my functions are split in files. For example I have this controller (oktacontroller.js):

```<code>var okta_api_key = <here some await data, getting from db>;

const OKTA_ORG_URL = '<here too>';

exports.createUser = async (req, res) => {

    console.log(okta_api_key);
}

exports.getGroups = async (req, res) => {
    console.log(okta_api_key);
}
</code>```

In both exported functions (which are express routes) I need the var okta_api_key. I know I can get them by querying them in both functions, because they are async functions and I can use await there, but it feels dumb to query this every time (because it wont ever change).

How can I manage this? I know I can do this:

var okta_api_key;
(async () => {
    okta_api_key = await <getting key async>
})()
```

But this feels off as well..

Is there any way too make some sort of large function, which is async, and exports the two functions? In other words: How do I use await on the top level of a file (module). It doesnt need to be on top level (its impossible), but some sort of method to have my "top level" variables exposed to my exported functions.

EDIT: Some other usecase, because I got the suggestion of putting it in a config file. Yes, for this one it is possible, but for example: I have some other api key which gets his access token from the service itself, on every startup (because it expires). That token cannot be stored in the config file, so I need some async work to get the value. I know top-level-await is not working (or even not desirable), but I just want an example of how you guys would do this if it were your project :)

答:
You are close:

```<code> var okta_api_key = (async () => {
    return  await <getting key async>
 })();
</code>```

Create a promise, then  await that promise whenever you want to use it.

How do I use await on the top level of a file (module).

Top level await might look great: You just add one await and then you can access the variable synchronously. But that simplifies things too much: It will stop all modules depending on that module from executing. In most cases you don't want that¹. Instead create a promise of the async task, then await it when needed. That way you limit the asynchronous execution to the code pieces that actually need it.

¹ Those rare cases are:

1) Loading some global config, that you have to access everywhere in your code, so it makes no sense to start the service if the config isn't ready.

2) awaiting in the top level file of your service: As no module depends on it, this won't cause any problems.

Side note: Top level await is not yet specified, and the NodeJS support is also not there yet. To use it in production you have to wait a few months (?).

Body:
I tried finding the solution to my problem, but couldnt find it, and was looking for some "best practice examples". I have a nodejs express application and my functions are split in files. For example I have this controller (oktacontroller.js):

var okta_api_key = <here some await data, getting from db>;

const OKTA_ORG_URL = '<here too>';

exports.createUser = async (req, res) => {

    console.log(okta_api_key);
}

exports.getGroups = async (req, res) => {
    console.log(okta_api_key);
}

In both exported functions (which are express routes) I need the var okta_api_key. I know I can get them by querying them in both functions, because they are async functions and I can use await there, but it feels dumb to query this every time (because it wont ever change).

How can I manage this? I know I can do this:

var okta_api_key;
(async () => {
    okta_api_key = await <getting key async>
})()

But this feels off as well..

Is there any way too make some sort of large function, which is async, and exports the two functions? In other words: How do I use await on the top level of a file (module). It doesnt need to be on top level (its impossible), but some sort of method to have my "top level" variables exposed to my exported functions.

EDIT: Some other usecase, because I got the suggestion of putting it in a config file. Yes, for this one it is possible, but for example: I have some other api key which gets his access token from the service itself, on every startup (because it expires). That token cannot be stored in the config file, so I need some async work to get the value. I know top-level-await is not working (or even not desirable), but I just want an example of how you guys would do this if it were your project :)

Body:
You are close:

 var okta_api_key = (async () => {
    return  await <getting key async>
 })();

Create a promise, then  await that promise whenever you want to use it.

How do I use await on the top level of a file (module).

Top level await might look great: You just add one await and then you can access the variable synchronously. But that simplifies things too much: It will stop all modules depending on that module from executing. In most cases you don't want that¹. Instead create a promise of the async task, then await it when needed. That way you limit the asynchronous execution to the code pieces that actually need it.

¹ Those rare cases are:

1) Loading some global config, that you have to access everywhere in your code, so it makes no sense to start the service if the config isn't ready.

2) awaiting in the top level file of your service: As no module depends on it, this won't cause any problems.

Side note: Top level await is not yet specified, and the NodeJS support is also not there yet. To use it in production you have to wait a few months (?).


问: How can I plot this kind of smoothed probability distribution in Matlab?

答:
If you have the equation to the PDF, you can simply plot it for specified values of x. For example,

Normal distribution

```<code>pNormal=@(x)1/sqrt(2*pi)*exp(-(x.^2)/2);
x=linspace(-4,4,1e3);
plot(x,pNormal(x));
</code>```

Log-Normal distribution

```<code>pLogNormal=@(mu,sigma,x)1./(x*sigma*sqrt(2*pi)).*exp(-((log(x)-mu)./(sqrt(2)*sigma)).^2);
x=linspace(0,10,1e3);
mu=0;sigma=1;
plot(x,pLogNormal(mu,sigma,x));
</code>```

You can vary sigma, mu and x according to your needs. The log-normal distribution is defined for x>0.

Body:
If you have the equation to the PDF, you can simply plot it for specified values of x. For example,

Normal distribution

pNormal=@(x)1/sqrt(2*pi)*exp(-(x.^2)/2);
x=linspace(-4,4,1e3);
plot(x,pNormal(x));

Log-Normal distribution

pLogNormal=@(mu,sigma,x)1./(x*sigma*sqrt(2*pi)).*exp(-((log(x)-mu)./(sqrt(2)*sigma)).^2);
x=linspace(0,10,1e3);
mu=0;sigma=1;
plot(x,pLogNormal(mu,sigma,x));

You can vary sigma, mu and x according to your needs. The log-normal distribution is defined for x>0.


答:
We can use any in filter after grouping by 'grp'

```<code>library(dplyr)
dat %>%
    group_by(grp) %>%
    filter(any(var2 >= 14))
# A tibble: 4 x 3
# Groups:   grp [2]
#  date         grp  var2
#  <fct>      <dbl> <dbl>
#1 2017-02-15     6    18
#2 2017-02-05     7    15
#3 2018-05-23     7    25
#4 2018-02-22     7     5
</code>```

Or with all on reverse logic

```<code>dat %>%
   group_by(grp) %>%
   filter(!all(var2 < 14))
</code>```

In base R, this can be done with ave to create a logical vector for subsetting the rows

```<code>dat[with(dat, ave(var2 >= 14, grp, FUN = any)),]
</code>```

Title: Select all rows by group with condition

Body:
I have this data frame:

`dat <- data.frame(date = c("2017-02-23", "2017-02-22", "2017-02-15", "2017-02-05","2018-05-23", "2018-02-22"), grp = c(1,1,6,7,7,7),
var2 = c(1,3,18,15,25,5))`

I would like to have all the rows of each group (grp) when value of var2>=14

Expected results:

    dat <- data.frame(date = c("2017-02-15", "2017-02-05","2018-05-23",
"2018-02-22"), grp = c(6,7,7,7), var2 = c(18,15,25,5))

Body:
We can use any in filter after grouping by 'grp'

library(dplyr)
dat %>%
    group_by(grp) %>%
    filter(any(var2 >= 14))
# A tibble: 4 x 3
# Groups:   grp [2]
#  date         grp  var2
#  <fct>      <dbl> <dbl>
#1 2017-02-15     6    18
#2 2017-02-05     7    15
#3 2018-05-23     7    25
#4 2018-02-22     7     5

Or with all on reverse logic

dat %>%
   group_by(grp) %>%
   filter(!all(var2 < 14))

In base R, this can be done with ave to create a logical vector for subsetting the rows

dat[with(dat, ave(var2 >= 14, grp, FUN = any)),]


问:
Visual Studio: how to ignore known exceptions when debugging?
I'm debugging with Visual Studio Code Version 1.34.

I've setup a breakpoint that is not reached because of exceptions that are not critical.

How do I stop that behaviur? I'm coping the configuration file for debugging with Django in VSC.

launch.json

```<code>{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "type": "extensionHost",
            "request": "launch",
            "name": "Launch Extension",
            "runtimeExecutable": "${execPath}",
            "args": [
                "--extensionDevelopmentPath=${workspaceFolder}"
            ],
            "outFiles": [
                "${workspaceFolder}/out/**/*.js"
            ],
            "preLaunchTask": "npm"
        },
        {
            "name": "Python: Django",
            "type": "python",
            "request": "launch",
            "program": "${workspaceFolder}\\manage.py",
            "args": [
                "runserver",
                "--noreload",
                "--nothreading"
            ],
            "django": true
        }
    ]
}
</code>```

答:
In python you can use a try and except

If you know the exception that is being thrown:

```<code>try:
    with open('file.txt') as file:
        read_data = file.read()
except FileNotFoundError as fnf_error:
    print(fnf_error)

print('this will still be executed')
</code>```

If you don't know what type of exception is thrown:

```<code>try:
    function_that_throws()
except:
    print('caught exception')

print('this is still executed')
</code>```

Body:
I'm debugging with Visual Studio Code Version 1.34.

I've setup a breakpoint that is not reached because of exceptions that are not critical.

How do I stop that behaviur? I'm coping the configuration file for debugging with Django in VSC.

launch.json

{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "type": "extensionHost",
            "request": "launch",
            "name": "Launch Extension",
            "runtimeExecutable": "${execPath}",
            "args": [
                "--extensionDevelopmentPath=${workspaceFolder}"
            ],
            "outFiles": [
                "${workspaceFolder}/out/**/*.js"
            ],
            "preLaunchTask": "npm"
        },
        {
            "name": "Python: Django",
            "type": "python",
            "request": "launch",
            "program": "${workspaceFolder}\\manage.py",
            "args": [
                "runserver",
                "--noreload",
                "--nothreading"
            ],
            "django": true
        }
    ]
}

Body:
In python you can use a try and except

If you know the exception that is being thrown:

try:
    with open('file.txt') as file:
        read_data = file.read()
except FileNotFoundError as fnf_error:
    print(fnf_error)

print('this will still be executed')

If you don't know what type of exception is thrown:

try:
    function_that_throws()
except:
    print('caught exception')

print('this is still executed')


问:
How to deal with "Android license status unknown."
I just tried the following methods, however, it doesn't work anyway.

```<code>flutter doctor --android-licenses
</code>```

will return

```<code>A newer version of the Android SDK is required. To update, run:
D:\software\sdk_now\android-sdk-windows\tools\bin\sdkmanager --update
</code>```

and then I tried

```<code>D:\tools\flutter\flutter>D:\software\sdk_now\android-sdk-windows\tools\bin\sdkmanager --update
Warning: java.net.ConnectException: Connection timed out: connect
Warning: Failed to download any source lists!
done
</code>```

I have tried to close my firewall, but nothing help....

答:
Finlly, I change nothing and it works now.
Maybe for Chinese learners who are looking for answer of this question same with me, just try running your project again and again.
And miracles happen.</p>

Body:
I just tried the following methods, however, it doesn't work anyway.

flutter doctor --android-licenses

will return

A newer version of the Android SDK is required. To update, run:
D:\software\sdk_now\android-sdk-windows\tools\bin\sdkmanager --update

and then I tried

D:\tools\flutter\flutter>D:\software\sdk_now\android-sdk-windows\tools\bin\sdkmanager --update
Warning: java.net.ConnectException: Connection timed out: connect
Warning: Failed to download any source lists!
done

I have tried to close my firewall, but nothing help....


问:
Delete or reset a browser cookie via Javascript
HTML links:

Logout

Logout

Logout

Logout

Logout

Logout

Javascript:

function delete_cookie(rememberKeepMeLoggedIn) {

    var cookie_date = new Date ( );

    cookie_date.setTime ( cookie_date.getTime() - 1 );

    document.cookie = rememberKeepMeLoggedIn += "=; expires=" + cookie_date.toGMTString();

  }

function del_cookie(name) {
  document.cookie = 'acceptsCookies=; expires=Thu, 01 Jan 1970 00:00:00 GMT;';
 window.location = "http://www.smugmug.com/logout.mg?goTo=#"

  }

function eraseCookie(name) {
  var cookies = document.cookie.split(";");

  for (var i = 0; i < cookies.length; i++)

  eraseCookies(cookies[i].split("=")[0]);

  }

How can I delete or reset a cookie with the name "UP-759283"?

Does the syntax below look good?

Here's my javascript function:

function del_cookie() {

  document.cookie = UP-759283 +'=; expires=Thu, 01-Jan-70 00:00:01 GMT;';

  }

The HTML URL callout

Logout

答:
Does the syntax below look good?

No; just run your code through JSLint and you'll see. Change

```<code>document.cookie = UP-759283 +'=; expires=Thu, 01-Jan-70 00:00:01 GMT;';
</code>```

to

```<code>document.cookie = 'UP-759283=; expires=Thu, 01-Jan-70 00:00:01 GMT;';
</code>```

As per the MDC document.cookie docs, cookies are deleted by setting the expiration time to zero:

```<code>document.cookie = 'UP-759283=; expires=Thu, 01 Jan 1970 00:00:00 GMT;';
</code>```

Other reference: cookies @ quirksmode
.

Body:
Does the syntax below look good?

No; just run your code through JSLint and you'll see. Change

document.cookie = UP-759283 +'=; expires=Thu, 01-Jan-70 00:00:01 GMT;';

to

document.cookie = 'UP-759283=; expires=Thu, 01-Jan-70 00:00:01 GMT;';

As per the MDC document.cookie docs, cookies are deleted by setting the expiration time to zero:

document.cookie = 'UP-759283=; expires=Thu, 01 Jan 1970 00:00:00 GMT;';

Other reference: cookies @ quirksmode
.


问:
What do these numbers mean on the network tab?
In the network tab, under the list of all the HTTP requests, I see a summary. For example:

213 requests

2.5 MB transferred

7.2 MB resources

Finish: 2.1 Min

DOMContentLoaded: 1.23 s

Load: 3.17 s

Chrome's documentation has an extensive article about this tab, but it doesn't describe these summary data.

Some of these are self-explanatory. 213 Total HTTP requests have been sent, and it took 1.23 seconds from the first request until the document.DOMContentLoaded event was fired. The big value for finished value actually makes sense because this page has a repeating 'ping' event for click tracking. However, the other values are a bit confusing.

Why are there two very different numbers for transferred and resources — i.e. what the difference between a transferred byte and a resource byte? Also, what does the "Load" time represent exactly — is that the time until window.load event or something else?

答:
The DevTools documentation points to MDN's load event page to describe the "Load" number. So yes, "Load" is the time from navigation until window.load.

"Transferred" refers to bytes across the wire. "Resources" refers to the weight of those files once they're downloaded and un-compressed, as shown in the DevTools reference.

Downloading jQuery from its CDN illustrates the difference. The DevTools reference points out that the smaller number in the requests table represents the compressed size.


问:
DataView RowFilter with TimeSpan DataType
I try to use the DataView RowFilter for a column with DataType "TimeSpan" as following:

```<code>dv.RowFilter = ("Convert([time],System.String) LIKE '17:12:00'")
</code>```

I've found that the search Parameter "%17% or %12%, for the double Zeros i have to use a single one: %0%, works fine, now im not sure about the Convert(timespan, System.String) Format... .
I know that the TimeSpan have a Special Format like (17,12,0) or {17}{12}{0} but as a not specified convert to string it should be: hh:mm:ss like timespan.ToString() - but with the DataView's RowFilter i can't get this to work!

I'm using Visual Studio 2008 Pro with .NET 3.5.

答:
To put it all together, you may use the following approach to filter columns of type TimeSpan in a DataTable for certain values. The idea behind is to convert the stored TimeSpan on the fly into its "database" string representation which in turn enables you to perform a string comparison with a TimeSpan value of your choice right after converting it into its "database" string representation.

Creation of the "database" string representation of a TimeSpan value requires special attention to time segments having zero values. It's specification could be described by the following pattern:

```<code>PT[<hours>H][<minutes>M]<seconds>[.<fraction>]S
</code>```

where <fraction> refers to the ten-millionths of a second, see "Custom TimeSpan Format Strings" of the MSDN documentation. Time segments having zero values need to be omitted, except for the seconds. Also the fraction part is expected to not contain any trailing zero digit. Finally, the string is enclosed by a prefix PT and a postfix S.

This leads to the following format string to create a correct "database" string representation:

```<code>TimeSpan oTimeSpan;  // TimeSpan value of your choice
string strTimeSpan =
    string.Format("PT{0}{1}{2}{3}S",
        (oTimeSpan.Hours == 0
            ? ""
            : string.Format("{0:%h}H", oTimeSpan)),
        (oTimeSpan.Minutes == 0
            ? ""
            : string.Format("{0:%m}M", oTimeSpan)),
        string.Format("{0:%s}", oTimeSpan),
        string.Format(".{0:fffffff}", oTimeSpan).TrimEnd('0', '.'))
</code>```

The expression to filter columns of type TimeSpan in a DataTable for certain values could be now:

```<code>string strExpr =
    "Convert([ColumnName], '" + typeof(string).ToString() + "')"
    + "='" + strTimeSpan + "'";
</code>```

where ColumnName refers to the name of the DataTable column containing the TimeSpan values.

Note that this approach is based on a string comparison, thus, only compare for equality would provide reliable results. Other compare operations like "greater than" or "less than" will most likely produce unexpected results.

Body:
I try to use the DataView RowFilter for a column with DataType "TimeSpan" as following:

dv.RowFilter = ("Convert([time],System.String) LIKE '17:12:00'")

I've found that the search Parameter "%17% or %12%, for the double Zeros i have to use a single one: %0%, works fine, now im not sure about the Convert(timespan, System.String) Format... .
I know that the TimeSpan have a Special Format like (17,12,0) or {17}{12}{0} but as a not specified convert to string it should be: hh:mm:ss like timespan.ToString() - but with the DataView's RowFilter i can't get this to work!

I'm using Visual Studio 2008 Pro with .NET 3.5.

Body:
To put it all together, you may use the following approach to filter columns of type TimeSpan in a DataTable for certain values. The idea behind is to convert the stored TimeSpan on the fly into its "database" string representation which in turn enables you to perform a string comparison with a TimeSpan value of your choice right after converting it into its "database" string representation.

Creation of the "database" string representation of a TimeSpan value requires special attention to time segments having zero values. It's specification could be described by the following pattern:

PT[<hours>H][<minutes>M]<seconds>[.<fraction>]S

where <fraction> refers to the ten-millionths of a second, see "Custom TimeSpan Format Strings" of the MSDN documentation. Time segments having zero values need to be omitted, except for the seconds. Also the fraction part is expected to not contain any trailing zero digit. Finally, the string is enclosed by a prefix PT and a postfix S.

This leads to the following format string to create a correct "database" string representation:

TimeSpan oTimeSpan;  // TimeSpan value of your choice
string strTimeSpan =
    string.Format("PT{0}{1}{2}{3}S",
        (oTimeSpan.Hours == 0
            ? ""
            : string.Format("{0:%h}H", oTimeSpan)),
        (oTimeSpan.Minutes == 0
            ? ""
            : string.Format("{0:%m}M", oTimeSpan)),
        string.Format("{0:%s}", oTimeSpan),
        string.Format(".{0:fffffff}", oTimeSpan).TrimEnd('0', '.'))

The expression to filter columns of type TimeSpan in a DataTable for certain values could be now:

string strExpr =
    "Convert([ColumnName], '" + typeof(string).ToString() + "')"
    + "='" + strTimeSpan + "'";

where ColumnName refers to the name of the DataTable column containing the TimeSpan values.

Note that this approach is based on a string comparison, thus, only compare for equality would provide reliable results. Other compare operations like "greater than" or "less than" will most likely produce unexpected results.