问:
Extract e-mail with a certain domain from a semicolon-separated vector of e-mails
Consider the following vector of e-mails:

```<code>emails <- c("blah@my.blah.com;etc@etc.edu;me@me.gov",
            "yay@something.gov;yes@my.blah.com;maybe@maybe.net",
            "someemail@nothing.gov")
</code>```

Each element of the vector above is a semi-colon separated string of e-mail address for a user. In this case, for example, the first user has three e-mails: blah@my.blah.com, etc@etc.edu, and me@me.gov.

I have  a specific domain name I am interested in - let's say it's my.blah.com. I also know for a fact that, given my domain knowledge of this problem, that each user can only have one my.blah.com e-mail address, if it exists. I would like to return this e-mail address for each user as a character vector, and return NA in the cases in which a my.blah.com e-mail address does not exist.

Thus, the output should be

```<code>c("blah@my.blah.com", "yes@my.blah.com", NA)
</code>```

My best attempt at this is

```<code>emails <- c("blah@my.blah.com;etc@etc.edu;me@me.gov",
            "yay@something.gov;yes@my.blah.com;maybe@maybe.net",
            "someemail@nothing.gov")

regmatches(emails,
           regexec("+.*@my.blah.com",
                   emails))

[[1]]
[1] "blah@my.blah.com"

[[2]]
[1] "yay@something.gov;yes@my.blah.com"

[[3]]
character(0)
</code>```

which isn't a character vector, but I'm struggling to just get the RegEx right at this point, which is what I'd like to focus on.

答:
We could split the strings on ";" and then use grep with the pattern ending with "my.blah.com" and return value for those matching.

```<code>sapply(strsplit(emails, ";"), grep, pattern = "@my\\.blah\\.com$", value = TRUE)

#[[1]]
#[1] "blah@my.blah.com"

#[[2]]
#[1] "yes@my.blah.com"

#[[3]]
#character(0)
</code>```

Body:
Consider the following vector of e-mails:

emails <- c("blah@my.blah.com;etc@etc.edu;me@me.gov",
            "yay@something.gov;yes@my.blah.com;maybe@maybe.net",
            "someemail@nothing.gov")

Each element of the vector above is a semi-colon separated string of e-mail address for a user. In this case, for example, the first user has three e-mails: blah@my.blah.com, etc@etc.edu, and me@me.gov.

I have  a specific domain name I am interested in - let's say it's my.blah.com. I also know for a fact that, given my domain knowledge of this problem, that each user can only have one my.blah.com e-mail address, if it exists. I would like to return this e-mail address for each user as a character vector, and return NA in the cases in which a my.blah.com e-mail address does not exist.

Thus, the output should be

c("blah@my.blah.com", "yes@my.blah.com", NA)

My best attempt at this is

emails <- c("blah@my.blah.com;etc@etc.edu;me@me.gov",
            "yay@something.gov;yes@my.blah.com;maybe@maybe.net",
            "someemail@nothing.gov")

regmatches(emails,
           regexec("+.*@my.blah.com",
                   emails))

[[1]]
[1] "blah@my.blah.com"

[[2]]
[1] "yay@something.gov;yes@my.blah.com"

[[3]]
character(0)

which isn't a character vector, but I'm struggling to just get the RegEx right at this point, which is what I'd like to focus on.

Body:
We could split the strings on ";" and then use grep with the pattern ending with "my.blah.com" and return value for those matching.

sapply(strsplit(emails, ";"), grep, pattern = "@my\\.blah\\.com$", value = TRUE)

#[[1]]
#[1] "blah@my.blah.com"

#[[2]]
#[1] "yes@my.blah.com"

#[[3]]
#character(0)


来源: stackexchange

问:
ASP.NET unable to bind to all interfaces
I try to create an asp.net service; which works if I try to access it locally. But it is not possible to reach it from a remote location.

Below the code I use to instantiate the server:

```<code>using System;
using System.Web.Http;
using System.Web.Http.SelfHost;
using System.Configuration;

namespace RESTService
{
  public class Service : IDisposable
  {
    private HttpSelfHostServer server;

    public Service()
    {
      var config = new HttpSelfHostConfiguration($"http://*:{ConfigurationSettings.AppSettings["port"]}/");
      config.Routes.MapHttpRoute("TTS", "{controller}/{text}",
        new[] { "RESTService.Controller" });

      server = new HttpSelfHostServer(config);
    }

    public void Run()
    {
      server.OpenAsync().Wait();
    }

    public void Dispose()
    {
      server.Dispose();
    }
  }
}

</code>```

I replaced localhost with * as described in Web API self host - bind on all network interfaces. Unfortunately I get an UriFormatException with this code. How can I bind the service to all interfaces?

答:
Thanks to Lex Li; his comment pointed me into the right direction. The following code works:</p>

```<code>new HttpSelfHostConfiguration($"http://{IPAddress.Any}:{ConfigurationSettings.AppSettings["port"]}/")
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I try to create an asp.net service; which works if I try to access it locally. But it is not possible to reach it from a remote location.

Below the code I use to instantiate the server:

using System;
using System.Web.Http;
using System.Web.Http.SelfHost;
using System.Configuration;

namespace RESTService
{
  public class Service : IDisposable
  {
    private HttpSelfHostServer server;

    public Service()
    {
      var config = new HttpSelfHostConfiguration($"http://*:{ConfigurationSettings.AppSettings["port"]}/");
      config.Routes.MapHttpRoute("TTS", "{controller}/{text}",
        new[] { "RESTService.Controller" });

      server = new HttpSelfHostServer(config);
    }

    public void Run()
    {
      server.OpenAsync().Wait();
    }

    public void Dispose()
    {
      server.Dispose();
    }
  }
}

I replaced localhost with * as described in Web API self host - bind on all network interfaces. Unfortunately I get an UriFormatException with this code. How can I bind the service to all interfaces?

Body:
Thanks to Lex Li; his comment pointed me into the right direction. The following code works:

new HttpSelfHostConfiguration($"http://{IPAddress.Any}:{ConfigurationSettings.AppSettings["port"]}/")


问:
While loop that ends with a semiconlon
I have the code;

```<code>    while(nread = read(fd,&c,1)==0);
</code>```

Why is this while loop ending with a semicolon? Isn't this line going to to go through the whole fd without doing anything?

答:
well this gonna be jumping inside the loop forever until the condition is dissatisfied
so basically
here is a example for a "for" loop

for(i=0;i<10;i++);
printf("%d",i);
```

this will print 10 directly instead of the whole number series

Title: While loop that ends with a semiconlon

Body:
I have the code;

    while(nread = read(fd,&c,1)==0);

Why is this while loop ending with a semicolon? Isn't this line going to to go through the whole fd without doing anything?

Body:
well this gonna be jumping inside the loop forever until the condition is dissatisfied
so basically
here is a example for a "for" loop

for(i=0;i<10;i++);
printf("%d",i);

this will print 10 directly instead of the whole number series


问:
Select last element without a class
I'm dynamically adding and removing classes to and from elements on specific JS events. What I would like to do is select the last child element that has none these classes with CSS.

Example #1

```<code><container-element>
  <h2></h2>
  <div class='some-class'></div>
  <div></div>
  <div></div> <!-- select this div -->
</container-element>
</code>```

Example #2

```<code><container-element>
  <h2></h2>
  <div></div>
  <div></div> <!-- select this div -->
  <div class='some-class'></div>
</container-element>
</code>```

Is it possible to write a CSS selector to do this?

Something like container-element > div:not(.select):last-of-type?

答:
Of course I can do this with JS, but preferred a pure CSS solution. Supposedly a pure CSS solution is not possible, so the next best thing is an CSS solution with a little extra HTML.

The trick was to add a class, not-selected, to all of the elements, then remove this class from the element that you want to target with the CSS selector.

And the CSS selector would be div:not([class*='not-selected']).

div:not([class*='not-selected']) {
  background: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button type='button'>
  <h2>title</h2>
  <div class='not-selected'>option one</div>
  <div>option two</div>
  <div class='not-selected'>option three</div>
</button></code>```

Title: Select last element without a class

Body:
I'm dynamically adding and removing classes to and from elements on specific JS events. What I would like to do is select the last child element that has none these classes with CSS.

Example #1

<container-element>

</container-element>

Example #2

<container-element>

</container-element>

Is it possible to write a CSS selector to do this?

Something like container-element > div:not(.select):last-of-type?

Body:
Of course I can do this with JS, but preferred a pure CSS solution. Supposedly a pure CSS solution is not possible, so the next best thing is an CSS solution with a little extra HTML.

The trick was to add a class, not-selected, to all of the elements, then remove this class from the element that you want to target with the CSS selector.

And the CSS selector would be div:not([class*='not-selected']).

div:not([class*='not-selected']) {
  background: red;
}

<button type='button'>
  <h2>title</h2>
  <div class='not-selected'>option one</div>
  <div>option two</div>
  <div class='not-selected'>option three</div>
</button>


问:
Calling a class having its name as a string
I have a string which specifies the name of the call.
How can i call the particular class by using this string.am trying this in java.
A function will return me a list of strings which are class names.now task is to make a call to a  class by using this string.</p>

答: Learn reflection. By reflection you can get class by its name.</p>

ContentLicense: CC BY-SA 3.0


问:
FTP in VBA stuck with PUT
I created a test file on my D drive.  My goal is to upload it to my website from a VBA script in Excel.  When I run the .bat file it hangs during the put.  What am I doing wrong?  I commented out the / line because that was giving me an error.

Reply when running upload.bat from command prompt

```<code>D:\>upload.bat

D:\>ftp -i -s:d:\script.dat domain.com
Connected to domain.com.
220 *** FTP Server Ready
200 UTF8 set to on
User (domain.com:(none)):
331 Password required for username

230 User username logged in
ftp> put d:\test.txt
200 PORT command successful
425 Unable to build data connection: Connection timed out
ftp> quit
221 Goodbye.
enter code here

Sub ftp()

Dim fs As Object

Set fs = CreateObject("Scripting.FileSystemObject")
    Set a = fs.CreateTextFile("d:\script.dat", True)
    a.writeline "username" 'username
    a.writeline "password" 'password
    'a.writeline "\" 'directory on FTP site
    a.writeline "put d:\test.txt" 'file to be uploaded
    a.writeline "quit"
    a.Close

    Set fs = CreateObject("Scripting.FileSystemObject")
    Set a = fs.CreateTextFile("d:\upload.bat", True)
    a.writeline "ftp -i -s:d:\script.dat domain.com" 'the ftp site
    a.Close

    dRetVal = Shell("d:\upload.bat", 0) 'upload the file

    Application.ScreenUpdating = True

End Sub
</code>```

答:
200 PORT command successful

  425 Unable to build data connection: Connection timed out

This happens usually if your are behind some firewall or device doing NAT (i.e. typical SoHo router). FTP requires a separat data connection and in active mode (as you use here) the server tries to connect to the client - which fill fail in the given scenarios either with a connection reset or with a timeout (as in your case).

You'd better use passive mode where the client will try to connect to the server for the data connections instead. Unfortunately, the builtin command line client in Windows does not seem to support passive mode so you would need to use a different client.

Title: FTP in VBA stuck with PUT

Body:
I created a test file on my D drive.  My goal is to upload it to my website from a VBA script in Excel.  When I run the .bat file it hangs during the put.  What am I doing wrong?  I commented out the / line because that was giving me an error.

Reply when running upload.bat from command prompt

D:\>upload.bat

D:\>ftp -i -s:d:\script.dat domain.com
Connected to domain.com.
220 *** FTP Server Ready
200 UTF8 set to on
User (domain.com:(none)):
331 Password required for username

230 User username logged in
ftp> put d:\test.txt
200 PORT command successful
425 Unable to build data connection: Connection timed out
ftp> quit
221 Goodbye.
enter code here

Sub ftp()

Dim fs As Object

Set fs = CreateObject("Scripting.FileSystemObject")
    Set a = fs.CreateTextFile("d:\script.dat", True)
    a.writeline "username" 'username
    a.writeline "password" 'password
    'a.writeline "\" 'directory on FTP site
    a.writeline "put d:\test.txt" 'file to be uploaded
    a.writeline "quit"
    a.Close

    Set fs = CreateObject("Scripting.FileSystemObject")
    Set a = fs.CreateTextFile("d:\upload.bat", True)
    a.writeline "ftp -i -s:d:\script.dat domain.com" 'the ftp site
    a.Close

    dRetVal = Shell("d:\upload.bat", 0) 'upload the file

    Application.ScreenUpdating = True

End Sub


问:
Using std::launder to get a pointer to an active union member from a pointer to an inactive union member?
Consider this union:

```<code>union A{
  int a;
  struct{
    int b;
    } c;
  };
</code>```

c and a are not layout-compatibles types so it is not possible to read the value of b through a:

```<code>A x;
x.c.b=10;
x.a+x.a; //undefined behaviour (UB)
</code>```

 For Trial 1 and Trial 2 see this question

Trial 3

Now let's use std::launder for what it does not seems to be intended:

```<code>A x;
x.a=10;
auto p = &x.a;                 //(1)
x.c.b=12;                      //(2)
p = std::launder(p);           //(2')
*p+*p;                         //(3)  UB?
</code>```

Could std::launder change anything? According to [ptr.launder]:

template <class T> constexpr T* launder(T* p) noexcept;

Requires: p represents the address A of a byte in memory. An object X that is within its lifetime and whose type is similar to T is located at the address A. All bytes of storage that would be reachable through the result are reachable through p (see below).

Returns: A value of type T * that points to X.

Remarks: An invocation of this function may be used in a core constant expression whenever the value of its argument may be used in a core constant expression. A byte of storage is reachable through a pointer value that points to an object Y if it is within the storage occupied by Y, an object that is pointer-interconvertible with Y, or the immediately-enclosing array object if Y is an array element. The program is ill-formed if T is a function type or cv void.

The bolded sentence emphasizes a someting that troubles me. If p is an invalid pointer value, how could any byte of storage be accessible? On the other hand with such a reading std::launder is just not usable.

Otherwise, could p's value at (2) be a pointer value that represents a region of storage as is talked about in a "Note" in [basic.life]:

If these conditions are not met, a pointer to the new object can be obtained from a pointer that represents the address of its storage by calling std::launder ([support.dynamic]).

答:
It is explicitly allowed in a note.

basic.life contains the following rule that makes std::launder unnecessary:

If, after the lifetime of an object has ended and before the storage which the object occupied is reused or released, a new object is created at the storage location which the original object occupied, a pointer that pointed to the original object, a reference that referred to the original object, or the name of the original object will automatically refer to the new object and, once the lifetime of the new object has started, can be used to manipulate the new object, if:

the storage for the new object exactly overlays the storage location which the original object occupied, and

the new object is of the same type as the original object (ignoring the top-level cv-qualifiers), and

the type of the original object is not const-qualified, and, if a class type, does not contain any non-static data member whose type is const-qualified or a reference type, and

neither the original object nor the new object is a potentially-overlapping subobject.

[ Note: If these conditions are not met, a pointer to the new object can be obtained from a pointer that represents the address of its storage by calling std::launder. — end note ]

This "new object is created at the storage location which the original object occupied" case clearly applies here because:

An object is created ... when implicitly changing the active member of a union...

All the bullet conditions are met, as "potentially overlapping subobject" refers to base class subobjects, which union members are not.  (And in the version you linked to, that bullet mentioned base class subobjects directly.)

However even if this interpretation were to change against unions, the note specifically mentions that std::launder bypasses this restriction.

Do note that older versions of the Standard excluded subobjects from this rule... but the note makes it clear that std::launder would have bypassed that problem as well.

Body:
Consider this union:

union A{
  int a;
  struct{
    int b;
    } c;
  };

c and a are not layout-compatibles types so it is not possible to read the value of b through a:

A x;
x.c.b=10;
x.a+x.a; //undefined behaviour (UB)

 For Trial 1 and Trial 2 see this question

Trial 3

Now let's use std::launder for what it does not seems to be intended:

A x;
x.a=10;
auto p = &x.a;                 //(1)
x.c.b=12;                      //(2)
p = std::launder(p);           //(2')
*p+*p;                         //(3)  UB?

Could std::launder change anything? According to [ptr.launder]:

template <class T> constexpr T* launder(T* p) noexcept;

Requires: p represents the address A of a byte in memory. An object X that is within its lifetime and whose type is similar to T is located at the address A. All bytes of storage that would be reachable through the result are reachable through p (see below).

Returns: A value of type T * that points to X.

Remarks: An invocation of this function may be used in a core constant expression whenever the value of its argument may be used in a core constant expression. A byte of storage is reachable through a pointer value that points to an object Y if it is within the storage occupied by Y, an object that is pointer-interconvertible with Y, or the immediately-enclosing array object if Y is an array element. The program is ill-formed if T is a function type or cv void.

The bolded sentence emphasizes a someting that troubles me. If p is an invalid pointer value, how could any byte of storage be accessible? On the other hand with such a reading std::launder is just not usable.

Otherwise, could p's value at (2) be a pointer value that represents a region of storage as is talked about in a "Note" in [basic.life]:

If these conditions are not met, a pointer to the new object can be obtained from a pointer that represents the address of its storage by calling std::launder ([support.dynamic]).


问:
Is there a shorthand way of doing a @media query OR a custom class?
I have a sidebar on my website that collapses into a narrower one on a smaller screen. I would like to add an option now, to be able to toggle having the narrower sidebar, even if you're on a big screen. Let's say that i do it by adding the class .compact to .

My CSS for the compact sidebar was originally inside a @media block:

    @media(min-width: 768px) and (max-width: 1200px) {
        nav {}
        nav > .nav-item {}
        /* ... */
    }
```

<p>And would now also need to be as children of <code>.compact</code>:</p>

<pre class="lang-css prettyprint-override"><code>    body.compact nav {}
    body.compact nav > .nav-item {}
    /* ... */
</code>```

Which would need me to copy/paste all of the declarations to achieve that behaviour, since @media's syntax is one of a wrapper, and cannot be a sibling of .compact's declarations.

Is there a different clever way that this can be achieved, that does NOT involve javascript?

答:
This can be achieved by using css variables:

function toggleSidebar(size) {
  let container = document.getElementById("container");
  let sibebarClass;

  switch (size) {
    case 'sm':
      sidebarClass = 'small-sidebar';
      break;
    case 'md':
      sidebarClass = 'medium-sidebar';
      break;
    case 'lg':
      sidebarClass = 'large-sidebar';
      break;
    default:
      sidebarClass = '';

  }

  container.classList.remove('large-sidebar', 'medium-sidebar', 'small-sidebar');
  container.classList.add(sidebarClass);

}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
  box-sizing: border-box;
}

html,
body {
  margin: 0;
  height: 100vh;
}

.page-container {
  width: 100%;
  height: 100%;
  display: flex;
  /* This will be default value */
  --sidebar-width: 300px;
}

.content {
  padding: 10px;
}

/* Sidebar width is defined in this block */
.page-container.large-sidebar {
  --sidebar-width: 400px;
}
.page-container.medium-sidebar {
  --sidebar-width: 300px;
}
.page-container.small-sidebar {
  --sidebar-width: 200px;
}

.sidebar {
  height: 100%;
  width: var(--sidebar-width);
  background-color: limegreen;
}</code>```

    <button class="toggleSidebar" onclick="toggleSidebar('sm');">Toggle small</button>
    <button class="toggleSidebar" onclick="toggleSidebar('md');">Toggle medium</button>
    <button class="toggleSidebar" onclick="toggleSidebar('lg');">Toggle large</button>

```

This way you only need to add new .page-container.somesize-sidebar to add new sidebar size without touching .sidebar selector.

If you want different sidebar sizes for different screens - you can put .page-container.small-sidebar and others inside @media query.

Body:
I have a sidebar on my website that collapses into a narrower one on a smaller screen. I would like to add an option now, to be able to toggle having the narrower sidebar, even if you're on a big screen. Let's say that i do it by adding the class .compact to .

My CSS for the compact sidebar was originally inside a @media block:

    @media(min-width: 768px) and (max-width: 1200px) {
        nav {}
        nav > .nav-item {}
        /* ... */
    }

And would now also need to be as children of .compact:

    body.compact nav {}
    body.compact nav > .nav-item {}
    /* ... */

Which would need me to copy/paste all of the declarations to achieve that behaviour, since @media's syntax is one of a wrapper, and cannot be a sibling of .compact's declarations.

Is there a different clever way that this can be achieved, that does NOT involve javascript?

Body:
This can be achieved by using css variables:

function toggleSidebar(size) {
  let container = document.getElementById("container");
  let sibebarClass;

  switch (size) {
    case 'sm':
      sidebarClass = 'small-sidebar';
      break;
    case 'md':
      sidebarClass = 'medium-sidebar';
      break;
    case 'lg':
      sidebarClass = 'large-sidebar';
      break;
    default:
      sidebarClass = '';

  }

  container.classList.remove('large-sidebar', 'medium-sidebar', 'small-sidebar');
  container.classList.add(sidebarClass);

}

* {
  box-sizing: border-box;
}

html,
body {
  margin: 0;
  height: 100vh;
}

.page-container {
  width: 100%;
  height: 100%;
  display: flex;
  /* This will be default value */
  --sidebar-width: 300px;
}

.content {
  padding: 10px;
}

/* Sidebar width is defined in this block */
.page-container.large-sidebar {
  --sidebar-width: 400px;
}
.page-container.medium-sidebar {
  --sidebar-width: 300px;
}
.page-container.small-sidebar {
  --sidebar-width: 200px;
}

.sidebar {
  height: 100%;
  width: var(--sidebar-width);
  background-color: limegreen;
}

<div id="container" class="page-container">
  <div class="sidebar"></div>
  <div class="content">
    <button class="toggleSidebar" onclick="toggleSidebar('sm');">Toggle small</button>
    <button class="toggleSidebar" onclick="toggleSidebar('md');">Toggle medium</button>
    <button class="toggleSidebar" onclick="toggleSidebar('lg');">Toggle large</button>
  </div>
</div>

This way you only need to add new .page-container.somesize-sidebar to add new sidebar size without touching .sidebar selector.

If you want different sidebar sizes for different screens - you can put .page-container.small-sidebar and others inside @media query.


问:
Getting "Attempt to get length of null array" error
I m getting "Attempt to get length of null array" error.
I m trying to fetch the random quotes as following from the link https://gturnquist-quoters.cfapps.io/api/random when I try to click the button :
type    "success"
value

id  7
quote   "The real benefit of Boot, however, is that it's just Spring. That means any direction the code takes, regardless of complexity, I know it's a safe bet."

MainActivity.java

```<code>public class MainActivity extends AppCompatActivity {

    Button btnCallRestApi;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btnCallRestApi = findViewById(R.id.btnCallRestApi);
        btnCallRestApi.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //call Rest Api
                new HttpReqTask().execute();

            }
        });
    }
    private class HttpReqTask extends AsyncTask<Void, Void, Value[]> {
        @Override
        protected Value[] doInBackground(Void... params){
            try{
                String apiUrl = "https://gturnquist-quoters.cfapps.io/api/random";
                RestTemplate rest = new RestTemplate();
                rest.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
                Value[] quotes = rest.getForObject(apiUrl, Value[].class);
                return quotes;
            }catch (Exception ex){
                Log.e("Could not get Quotes",ex.getMessage());
            }
            return null;
        }
        protected void onPostExecute(Value[] quotes){
            super.onPostExecute(quotes);
            for(Value v:quotes){
                Log.i("id: ", String.valueOf(v.getId()));
                Log.i("quote: ", v.getQuote());
            }
        }
    }
}
</code>```

Quote.java

```<code> public Quote() {
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public Value getValue() {
        return value;
    }

    public void setValue(Value value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return "Quote{" +
                "type='" + type + '\'' +
                ", value=" + value +
                '}';
    }
</code>```

Value.java

```<code> public Value() {
    }

    public Long getId() {
        return this.id;
    }

    public String getQuote() {
        return this.quote;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public void setQuote(String quote) {
        this.quote = quote;
    }

    @Override
    public String toString() {
        return "Value{" +
                "id=" + id +
                ", quote='" + quote + '\'' +
                '}';
    }
</code>```

答:
you are trying to do a loop on a null array , which trigger a NPE , try to handle it with a try/catch clause

```<code> protected void onPostExecute(Value[] quotes){
            super.onPostExecute(quotes);
    try {
        for(Value v:quotes){
            Log.i("id: ", String.valueOf(v.getId()));
            Log.i("quote: ", v.getQuote());
        }
    } catch (NullPointerException e) {
        System.out.print("Caught the NullPointerException");
    }
</code>```

edit for the new issue :

i think you are reading the JSON OBJECT wrongly !

Body:
I m getting "Attempt to get length of null array" error.
I m trying to fetch the random quotes as following from the link https://gturnquist-quoters.cfapps.io/api/random when I try to click the button :
type    "success"
value

id  7
quote   "The real benefit of Boot, however, is that it's just Spring. That means any direction the code takes, regardless of complexity, I know it's a safe bet."

MainActivity.java

public class MainActivity extends AppCompatActivity {

    Button btnCallRestApi;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btnCallRestApi = findViewById(R.id.btnCallRestApi);
        btnCallRestApi.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //call Rest Api
                new HttpReqTask().execute();

            }
        });
    }
    private class HttpReqTask extends AsyncTask<Void, Void, Value[]> {
        @Override
        protected Value[] doInBackground(Void... params){
            try{
                String apiUrl = "https://gturnquist-quoters.cfapps.io/api/random";
                RestTemplate rest = new RestTemplate();
                rest.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
                Value[] quotes = rest.getForObject(apiUrl, Value[].class);
                return quotes;
            }catch (Exception ex){
                Log.e("Could not get Quotes",ex.getMessage());
            }
            return null;
        }
        protected void onPostExecute(Value[] quotes){
            super.onPostExecute(quotes);
            for(Value v:quotes){
                Log.i("id: ", String.valueOf(v.getId()));
                Log.i("quote: ", v.getQuote());
            }
        }
    }
}

Quote.java

 public Quote() {
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public Value getValue() {
        return value;
    }

    public void setValue(Value value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return "Quote{" +
                "type='" + type + '\'' +
                ", value=" + value +
                '}';
    }

Value.java

 public Value() {
    }

    public Long getId() {
        return this.id;
    }

    public String getQuote() {
        return this.quote;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public void setQuote(String quote) {
        this.quote = quote;
    }

    @Override
    public String toString() {
        return "Value{" +
                "id=" + id +
                ", quote='" + quote + '\'' +
                '}';
    }

Body:
you are trying to do a loop on a null array , which trigger a NPE , try to handle it with a try/catch clause

 protected void onPostExecute(Value[] quotes){
            super.onPostExecute(quotes);
    try {
        for(Value v:quotes){
            Log.i("id: ", String.valueOf(v.getId()));
            Log.i("quote: ", v.getQuote());
        }
    } catch (NullPointerException e) {
        System.out.print("Caught the NullPointerException");
    }

edit for the new issue :

i think you are reading the JSON OBJECT wrongly !


问:
how to combine joptionpane with combobox
i want my joptionpane can combine with combobox,and the combobox data is in database, how i managed that.

i've tried change but the red code always show

```<code>  SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String wel = sdf.format(cal1.getDate());
                String NamaFile = "/report/harianMasuk.jasper";
                HashMap hash = new HashMap();
          String tak = JOptionPane.showOptionDialog(null,id.getSelectedIndex()-1,"Laporan Supplier",JOptionPane.QUESTION_MESSAGE);
     try {
                      hash.put("til", wel);
                   hash.put("rul", tak);
                   runReportDefault(NamaFile, hash);
               } catch (Exception e) {
                   JOptionPane.showMessageDialog(rootPane, e);
               }
</code>```

答:
Not exactly sure what you are trying to accomplish but it appears to be that you want to utilize a JComboBox within a JOptionPane dialog window. This ComboBox would be filled with specific data from your database. The User is to select from this ComboBox and your application continues processing based on that selection. If this is the case then you might want to try something like this:

```<code>String selectedItem = "";
int selectedItemIndex = -1;

/* Ensure dialog never hides behind anything (use if
   the keyword 'this' can not be used or there is no
   object to reference as parent for the dialog).   */
JFrame iframe = new JFrame();
iframe.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
iframe.setAlwaysOnTop(true);
// ---------------------------------------------------

int btns = JOptionPane.OK_CANCEL_OPTION;

String dialogMessage = "<html>Select the desired item from the Drop-Down "
        + "list<br>you want to work with:<br><br></html>";
String dialogTitle = "Your Fav Items";
/* Up to you to gather what you want placed into the
   JComboBox that will be displayed within the JOptionPane. */
String[] comboBoxItems = {"Your", "DB", "Items", "You", "Want", "To",
    "Add", "To", "ComboBox"};
BorderLayout layout = new BorderLayout();
JPanel topPanel = new JPanel(layout);
JLabel label = new JLabel(dialogMessage);
topPanel.add(label, BorderLayout.NORTH);
JPanel centerPanel = new JPanel(new BorderLayout(5, 5));
JComboBox cb = new JComboBox();
cb.setModel(new DefaultComboBoxModel<>(comboBoxItems));
cb.setSelectedIndex(-1);
centerPanel.add(cb, BorderLayout.CENTER);
topPanel.add(centerPanel);

// Ensure a selection or Cancel (or dialog close)
while (selectedItemIndex < 0) {
    int res = JOptionPane.showConfirmDialog(iframe, topPanel, dialogTitle, btns);
    if (res == 2) {
        selectedItem = "Selection Option Was Canceled!";
        break;
    }
    selectedItemIndex = cb.getSelectedIndex();
    if (res == JOptionPane.OK_OPTION) {
        if (selectedItemIndex == -1) {
            JOptionPane.showMessageDialog(iframe, "<html>You <b>must</b> "
                    + "select something or select <font color=red><b>Cancel</b></font>.",
                      "Invalid Selection...", JOptionPane.WARNING_MESSAGE);
        }
        else {
            selectedItem = cb.getSelectedItem().toString();
        }
    }
    iframe.dispose();
}
JOptionPane.showMessageDialog(iframe, "<html>You selected the ComboBox item:"
        + "<br><br><b><font color=blue><center>" + selectedItem + "</center>"
        + "</font></b><br></html>", "Selected Item", JOptionPane.INFORMATION_MESSAGE);
iframe.dispose();
</code>```

With the above code, the Input dialog that will be displayed would look something like this:

It is up to you to find the means to fill the comboBoxItems String Array used within the code above.

Body:
i want my joptionpane can combine with combobox,and the combobox data is in database, how i managed that.

i've tried change but the red code always show

  SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String wel = sdf.format(cal1.getDate());
                String NamaFile = "/report/harianMasuk.jasper";
                HashMap hash = new HashMap();
          String tak = JOptionPane.showOptionDialog(null,id.getSelectedIndex()-1,"Laporan Supplier",JOptionPane.QUESTION_MESSAGE);
     try {
                      hash.put("til", wel);
                   hash.put("rul", tak);
                   runReportDefault(NamaFile, hash);
               } catch (Exception e) {
                   JOptionPane.showMessageDialog(rootPane, e);
               }

Body:
Not exactly sure what you are trying to accomplish but it appears to be that you want to utilize a JComboBox within a JOptionPane dialog window. This ComboBox would be filled with specific data from your database. The User is to select from this ComboBox and your application continues processing based on that selection. If this is the case then you might want to try something like this:

String selectedItem = "";
int selectedItemIndex = -1;

/* Ensure dialog never hides behind anything (use if
   the keyword 'this' can not be used or there is no
   object to reference as parent for the dialog).   */
JFrame iframe = new JFrame();
iframe.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
iframe.setAlwaysOnTop(true);
// ---------------------------------------------------

int btns = JOptionPane.OK_CANCEL_OPTION;

String dialogMessage = "<html>Select the desired item from the Drop-Down "
        + "list<br>you want to work with:<br><br></html>";
String dialogTitle = "Your Fav Items";
/* Up to you to gather what you want placed into the
   JComboBox that will be displayed within the JOptionPane. */
String[] comboBoxItems = {"Your", "DB", "Items", "You", "Want", "To",
    "Add", "To", "ComboBox"};
BorderLayout layout = new BorderLayout();
JPanel topPanel = new JPanel(layout);
JLabel label = new JLabel(dialogMessage);
topPanel.add(label, BorderLayout.NORTH);
JPanel centerPanel = new JPanel(new BorderLayout(5, 5));
JComboBox cb = new JComboBox();
cb.setModel(new DefaultComboBoxModel<>(comboBoxItems));
cb.setSelectedIndex(-1);
centerPanel.add(cb, BorderLayout.CENTER);
topPanel.add(centerPanel);

// Ensure a selection or Cancel (or dialog close)
while (selectedItemIndex < 0) {
    int res = JOptionPane.showConfirmDialog(iframe, topPanel, dialogTitle, btns);
    if (res == 2) {
        selectedItem = "Selection Option Was Canceled!";
        break;
    }
    selectedItemIndex = cb.getSelectedIndex();
    if (res == JOptionPane.OK_OPTION) {
        if (selectedItemIndex == -1) {
            JOptionPane.showMessageDialog(iframe, "<html>You <b>must</b> "
                    + "select something or select <font color=red><b>Cancel</b></font>.",
                      "Invalid Selection...", JOptionPane.WARNING_MESSAGE);
        }
        else {
            selectedItem = cb.getSelectedItem().toString();
        }
    }
    iframe.dispose();
}
JOptionPane.showMessageDialog(iframe, "<html>You selected the ComboBox item:"
        + "<br><br><b><font color=blue><center>" + selectedItem + "</center>"
        + "</font></b><br></html>", "Selected Item", JOptionPane.INFORMATION_MESSAGE);
iframe.dispose();

With the above code, the Input dialog that will be displayed would look something like this:

It is up to you to find the means to fill the comboBoxItems String Array used within the code above.


问:
Turn your Session into FlushMode.COMMIT/AUTO or remove 'readOnly' marker from transaction definition
I am beginner in spring and in my console based project i am using spring with hibernate.I was stuck with the following error for about a day.

```<code>Exception in thread "main" org.springframework.dao.InvalidDataAccessApiUsageException: Write operations are not allowed in read-only mode (FlushMode.MANUAL): Turn your Session into FlushMode.COMMIT/AUTO or remove 'readOnly' marker from transaction definition.
at org.springframework.orm.hibernate5.HibernateTemplate.checkWriteOperationAllowed(HibernateTemplate.java:1126)
at org.springframework.orm.hibernate5.HibernateTemplate$12.doInHibernate(HibernateTemplate.java:619)
at org.springframework.orm.hibernate5.HibernateTemplate$12.doInHibernate(HibernateTemplate.java:616)
at org.springframework.orm.hibernate5.HibernateTemplate.doExecute(HibernateTemplate.java:341)
at org.springframework.orm.hibernate5.HibernateTemplate.executeWithNativeSession(HibernateTemplate.java:309)
at org.springframework.orm.hibernate5.HibernateTemplate.save(HibernateTemplate.java:616)
at com.hbtemp.dao.impl.StudentDaoImpl.insertStudent(StudentDaoImpl.java:22)
at com.hbtemp.test.TestClass.main(TestClass.java:25)
</code>```

I searched for this error in the web but i couldn't find the solution,so please help me with some concept

Model Class:Student.java

```<code>private int id;
private String firstName;
private String lastName;
private String address;
private int rollNo;

public int getId() {
    return id;
}
public void setId(int id) {
    this.id = id;
}
public String getFirstName() {
    return firstName;
}
public void setFirstName(String firstName) {
    this.firstName = firstName;
}
public String getLastName() {
    return lastName;
}
public void setLastName(String lastName) {
    this.lastName = lastName;
}
public String getAddress() {
    return address;
}
public void setAddress(String address) {
    this.address = address;
}
public int getRollNo() {
    return rollNo;
}
public void setRollNo(int rollNo) {
    this.rollNo = rollNo;
}
</code>```

StudentDaoImpl.java

```<code>public void setHibernateTemplate(HibernateTemplate hibernateTemplate){
    this.hibernateTemplate = hibernateTemplate;
}

@Override
public int insertStudent(Student student) {
    hibernateTemplate.save(student);
    return 0;
}
</code>```

ApplicationContext.xml

```<code><bean id = "dataSource" class = "org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name = "driverClassName" value = "com.mysql.jdbc.Driver"></property>
    <property name = "url" value = "jdbc:mysql://localhost:3306/spring_jdbc_template"></property>
    <property name = "username" value = "root"></property>
    <property name = "password" value = ""></property>
</bean>

<bean id = "mySessionFactory" class = "org.springframework.orm.hibernate5.LocalSessionFactoryBean">
      <property name = "dataSource" ref = "dataSource"></property>
      <property name = "mappingResources">
         <list>
             <value>student.hbm.xml</value>
         </list>
      </property>
      <property name = "hibernateProperties">
          <map>
             <entry key="hibernate.dialect" value = "org.hibernate.dialect.MySQLDialect"></entry>
             <!-- <entry key="hibernate.hbm2ddl.auto" value = "update"></entry> -->
             <entry key="hibernate.show_sql" value = "true"></entry>
             <entry key="checkWriteOperation" value = "false"></entry>
             <entry key="current_session_context_class" value = "thread"></entry>
          </map>
      </property>
</bean>

<bean id = "hibernateTemplate" class = "org.springframework.orm.hibernate5.HibernateTemplate">
     <property name = "sessionFactory" ref = "mySessionFactory"></property>
</bean>

<bean id = "studentDaoImpl" class = "com.hbtemp.dao.impl.StudentDaoImpl">
     <property name = "hibernateTemplate" ref = "hibernateTemplate"></property>
</bean>
</code>```

student.hbm.xml :

```<code><hibernate-mapping>
<class name = "com.hbtemp.model.Student" table = "student">
    <id name = "id" column = "ID">
        <generator class="identity"></generator>
    </id>

    <property name = "firstName" column = "FirstName"></property>
    <property name = "lastName" column = "LastName"></property>
    <property name = "address" column = "Address"></property>
    <property name = "rollNo" column = "Roll_NO"></property>
</class>
</code>```

TestClass.java

```<code>ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    StudentDaoImpl studentDaoImpl = (StudentDaoImpl)context.getBean("studentDaoImpl");

    Student student = new Student();
    student.setId(2);
    student.setFirstName("Prakash");
    student.setLastName("Gautam");
    student.setAddress("Bhaktapur");
    student.setRollNo(434);

    int status = studentDaoImpl.insertStudent(student);
</code>```

If i write a code hibernateTemplate.setCheckWriteOperations(false) inside insertStudent method it works fine............but my question is...is it good practice or not ? If it isn't good pratice please recommend the good pratice

答: add " "in spring configuration file, this will work for sure.</p>

Body:
I am beginner in spring and in my console based project i am using spring with hibernate.I was stuck with the following error for about a day.

Exception in thread "main" org.springframework.dao.InvalidDataAccessApiUsageException: Write operations are not allowed in read-only mode (FlushMode.MANUAL): Turn your Session into FlushMode.COMMIT/AUTO or remove 'readOnly' marker from transaction definition.
at org.springframework.orm.hibernate5.HibernateTemplate.checkWriteOperationAllowed(HibernateTemplate.java:1126)
at org.springframework.orm.hibernate5.HibernateTemplate$12.doInHibernate(HibernateTemplate.java:619)
at org.springframework.orm.hibernate5.HibernateTemplate$12.doInHibernate(HibernateTemplate.java:616)
at org.springframework.orm.hibernate5.HibernateTemplate.doExecute(HibernateTemplate.java:341)
at org.springframework.orm.hibernate5.HibernateTemplate.executeWithNativeSession(HibernateTemplate.java:309)
at org.springframework.orm.hibernate5.HibernateTemplate.save(HibernateTemplate.java:616)
at com.hbtemp.dao.impl.StudentDaoImpl.insertStudent(StudentDaoImpl.java:22)
at com.hbtemp.test.TestClass.main(TestClass.java:25)

I searched for this error in the web but i couldn't find the solution,so please help me with some concept

Model Class:Student.java

private int id;
private String firstName;
private String lastName;
private String address;
private int rollNo;

public int getId() {
    return id;
}
public void setId(int id) {
    this.id = id;
}
public String getFirstName() {
    return firstName;
}
public void setFirstName(String firstName) {
    this.firstName = firstName;
}
public String getLastName() {
    return lastName;
}
public void setLastName(String lastName) {
    this.lastName = lastName;
}
public String getAddress() {
    return address;
}
public void setAddress(String address) {
    this.address = address;
}
public int getRollNo() {
    return rollNo;
}
public void setRollNo(int rollNo) {
    this.rollNo = rollNo;
}

StudentDaoImpl.java

public void setHibernateTemplate(HibernateTemplate hibernateTemplate){
    this.hibernateTemplate = hibernateTemplate;
}

@Override
public int insertStudent(Student student) {
    hibernateTemplate.save(student);
    return 0;
}

ApplicationContext.xml

<bean id = "dataSource" class = "org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name = "driverClassName" value = "com.mysql.jdbc.Driver"></property>
    <property name = "url" value = "jdbc:mysql://localhost:3306/spring_jdbc_template"></property>
    <property name = "username" value = "root"></property>
    <property name = "password" value = ""></property>
</bean>

<bean id = "mySessionFactory" class = "org.springframework.orm.hibernate5.LocalSessionFactoryBean">
      <property name = "dataSource" ref = "dataSource"></property>
      <property name = "mappingResources">
         <list>
             <value>student.hbm.xml</value>
         </list>
      </property>
      <property name = "hibernateProperties">
          <map>
             <entry key="hibernate.dialect" value = "org.hibernate.dialect.MySQLDialect"></entry>

             <entry key="hibernate.show_sql" value = "true"></entry>
             <entry key="checkWriteOperation" value = "false"></entry>
             <entry key="current_session_context_class" value = "thread"></entry>
          </map>
      </property>
</bean>

<bean id = "hibernateTemplate" class = "org.springframework.orm.hibernate5.HibernateTemplate">
     <property name = "sessionFactory" ref = "mySessionFactory"></property>
</bean>

<bean id = "studentDaoImpl" class = "com.hbtemp.dao.impl.StudentDaoImpl">
     <property name = "hibernateTemplate" ref = "hibernateTemplate"></property>
</bean>

student.hbm.xml :

<hibernate-mapping>
<class name = "com.hbtemp.model.Student" table = "student">
    <id name = "id" column = "ID">
        <generator class="identity"></generator>
    </id>

    <property name = "firstName" column = "FirstName"></property>
    <property name = "lastName" column = "LastName"></property>
    <property name = "address" column = "Address"></property>
    <property name = "rollNo" column = "Roll_NO"></property>
</class>

TestClass.java

ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    StudentDaoImpl studentDaoImpl = (StudentDaoImpl)context.getBean("studentDaoImpl");

    Student student = new Student();
    student.setId(2);
    student.setFirstName("Prakash");
    student.setLastName("Gautam");
    student.setAddress("Bhaktapur");
    student.setRollNo(434);

    int status = studentDaoImpl.insertStudent(student);

If i write a code hibernateTemplate.setCheckWriteOperations(false) inside insertStudent method it works fine............but my question is...is it good practice or not ? If it isn't good pratice please recommend the good pratice


问:
How to make it so that after naving to a fragment, the last fragment can no longer be navigated to with the back button?
I have a nav structure like so:

```<code>StaringFragment -> nestedNavGraph
                         |
                   HomeFragment -> SecondFragment
</code>```

I need to make it so that after the user navigates away from StartingFragment to the nestedNavGraph the user can no longer hit the back button to return to the StartingFragment.

I am basically performing a permissions check, and if the check succeeds I navigate from the StartingFragment to the nestedNavGraph with this code:

findNavController(R.id.nav_host_frag).navigate(R.id.nestedNavGraph)

Then, on the action arrow between the StartingFrag -> nestedNavGraph in the nav graph editor, I set popUpTo to HomeFragment and inclusive to true. Did I misunderstand the documentation?

What's the proper way to remove the StartingFragment from the backstack as soon as I navigate away from it?

答:
As per the documentation, you set app:popUpTo to the destination you want to pop - you don't want to pop the HomeFragment, you want to pop the StartingFragment, so you should set your app:popUpTo to the ID of the StartingFragment.

Note that as per the Principles of Navigation, you should always have a fixed starting destination - you shouldn't be using the start destination for conditional navigation - many of the APIs in Navigation, such as NavigationUI, assume you're correctly following the Principles of Navigation and that the start destination of your graph remains on your back stack.

Keep in mind that Android will restore your state (including what fragment you were at) when returning to your activity (say, after the user manually revoked the permissions you asked for) - your Fragment itself (or the activity if the permission really is globally required on every single screen in your whole app) should always be checking for permission - you can't rely on your StartingFragment always being called.

Body:
I have a nav structure like so:

StaringFragment -> nestedNavGraph
                         |
                   HomeFragment -> SecondFragment

I need to make it so that after the user navigates away from StartingFragment to the nestedNavGraph the user can no longer hit the back button to return to the StartingFragment.

I am basically performing a permissions check, and if the check succeeds I navigate from the StartingFragment to the nestedNavGraph with this code:

findNavController(R.id.nav_host_frag).navigate(R.id.nestedNavGraph)

Then, on the action arrow between the StartingFrag -> nestedNavGraph in the nav graph editor, I set popUpTo to HomeFragment and inclusive to true. Did I misunderstand the documentation?

What's the proper way to remove the StartingFragment from the backstack as soon as I navigate away from it?


问:
Gracefully kill Chrome for Windows with Python
I have been trying to determine a method to close Chrome (and other processes) gracefully utilizing Python.  I have gone through a few methods but all result in Chrome displaying a message stating "Chrome didn't shut down correctly." with a Restore button.  This doesn't happen when you shut down a program from task manager in Windows. I have written a program utilizing Falcon to provide API access to shut down 'managed' programs.  The code for that isn't relevant, but here are the methods I have tried that do work to shut down Chrome that work well, but not gracefully.

```<code>def stop_app(app_exe):
    for process in psutil.process_iter():
        if process.name() == app_exe:
            process.terminate()
</code>```

Alternate:

```<code>for process in psutil.process_iter():
    if process.name() == app_exe:
        children = process.children(recursive=True)
        children.append(process)
        for p in children:
            p.send_signal(signal.CTRL_BREAK_EVENT)
</code>```

I have also tried kill() in place of terminate(), various signal types (Windows really only supports three, CTRL_BREAK_EVENT, CNTL_C_EVENT, SIGTERM).

I have also tried using the win32 library and I had the same issue. Win32 also isn't platform agnostic and I had found that win32/wmi libraries utilize a lot of system resources when looking for running windows processes.  The psutil library allows for being platform agnostic AND doesn't have the same performance issue when iterating through the Windows processes. Here is the code for that.

```<code>c = wmi.WMI()
for process in c.Win32_Process():
    if process.Name == app_exe:
        process.Terminate()
</code>```

Anyone out there try something similar and come up with a solution?

Quick solution per CristiFati recommendations.:

```<code>def enumWindowsProc(hwnd, lParam):
    if (lParam is None) or ((lParam is not None) and
          win32process.GetWindowThreadProcessId(hwnd)[1] == pid)):
        text = win32gui.GetWindowText(hwnd)
        if text:
            wStyle = win32api.GetWindowLong(hwnd, win32con.GWL_STYLE)
            if wStyle & win32con.WS_VISIBLE:
                win32api.SendMessage(hwnd, win32con.WM_CLOSE)

def stop_app(app_exe):
    for process in psutil.process_iter():
        if process.name() == app_exe:
            win32gui.EnumWindows(enumWindowsProc, process.pid)
</code>```

答:
A more generic version that sends the close message to apps, including those only visible in the system tray, with all included needed imports:

```<code>import win32con
import win32api
import win32gui
import win32process
import psutil

def enumWindowsProc(hwnd, lParam):
    if (lParam is None) or ((lParam is not None) and win32process.GetWindowThreadProcessId(hwnd)[1] == lParam):
        text = win32gui.GetWindowText(hwnd)
        if text:
            win32api.SendMessage(hwnd, win32con.WM_CLOSE)

def stop_app(app_exe):
    for process in psutil.process_iter():
        if process.name() == app_exe:
            win32gui.EnumWindows(enumWindowsProc, process.pid)

stop_app("appname.exe")
</code>```

(Based off of 'Quick solution per CristiFati recommendation' in the Question, but changes 'pid' to 'lParam', includes needed imports, and also works on apps only visible in the system tray.)

Body:
I have been trying to determine a method to close Chrome (and other processes) gracefully utilizing Python.  I have gone through a few methods but all result in Chrome displaying a message stating "Chrome didn't shut down correctly." with a Restore button.  This doesn't happen when you shut down a program from task manager in Windows. I have written a program utilizing Falcon to provide API access to shut down 'managed' programs.  The code for that isn't relevant, but here are the methods I have tried that do work to shut down Chrome that work well, but not gracefully.

def stop_app(app_exe):
    for process in psutil.process_iter():
        if process.name() == app_exe:
            process.terminate()

Alternate:

for process in psutil.process_iter():
    if process.name() == app_exe:
        children = process.children(recursive=True)
        children.append(process)
        for p in children:
            p.send_signal(signal.CTRL_BREAK_EVENT)

I have also tried kill() in place of terminate(), various signal types (Windows really only supports three, CTRL_BREAK_EVENT, CNTL_C_EVENT, SIGTERM).

I have also tried using the win32 library and I had the same issue. Win32 also isn't platform agnostic and I had found that win32/wmi libraries utilize a lot of system resources when looking for running windows processes.  The psutil library allows for being platform agnostic AND doesn't have the same performance issue when iterating through the Windows processes. Here is the code for that.

c = wmi.WMI()
for process in c.Win32_Process():
    if process.Name == app_exe:
        process.Terminate()

Anyone out there try something similar and come up with a solution?

Quick solution per CristiFati recommendations.:

def enumWindowsProc(hwnd, lParam):
    if (lParam is None) or ((lParam is not None) and
          win32process.GetWindowThreadProcessId(hwnd)[1] == pid)):
        text = win32gui.GetWindowText(hwnd)
        if text:
            wStyle = win32api.GetWindowLong(hwnd, win32con.GWL_STYLE)
            if wStyle & win32con.WS_VISIBLE:
                win32api.SendMessage(hwnd, win32con.WM_CLOSE)

def stop_app(app_exe):
    for process in psutil.process_iter():
        if process.name() == app_exe:
            win32gui.EnumWindows(enumWindowsProc, process.pid)

Body:
A more generic version that sends the close message to apps, including those only visible in the system tray, with all included needed imports:

import win32con
import win32api
import win32gui
import win32process
import psutil

def enumWindowsProc(hwnd, lParam):
    if (lParam is None) or ((lParam is not None) and win32process.GetWindowThreadProcessId(hwnd)[1] == lParam):
        text = win32gui.GetWindowText(hwnd)
        if text:
            win32api.SendMessage(hwnd, win32con.WM_CLOSE)

def stop_app(app_exe):
    for process in psutil.process_iter():
        if process.name() == app_exe:
            win32gui.EnumWindows(enumWindowsProc, process.pid)

stop_app("appname.exe")

(Based off of 'Quick solution per CristiFati recommendation' in the Question, but changes 'pid' to 'lParam', includes needed imports, and also works on apps only visible in the system tray.)


问:
C++ IsFloat function
Does anybody know of a convenient means of determining if a string value "qualifies" as a floating-point number?</p>

```<code>bool IsFloat( string MyString )
{
   ... etc ...

   return ... // true if float; false otherwise
}
</code>```

答:
I was looking for something similar, found a much simpler answer than any I've seen (Although is for floats VS. ints, would still require a typecast from string)

```<code>bool is_float(float val){
    if(val != floor(val)){
        return true;
    }
    else
        return false;
}
</code>```

or:

```<code>auto lambda_isFloat = [](float val) {return (val != floor(val)); };
</code>```

Hope this helps !

ZMazz

OwnerDisplayName: AndyUK

Title: C++ IsFloat function

Body:
Does anybody know of a convenient means of determining if a string value "qualifies" as a floating-point number?

bool IsFloat( string MyString )
{
   ... etc ...

   return ... // true if float; false otherwise
}

Body:
I was looking for something similar, found a much simpler answer than any I've seen (Although is for floats VS. ints, would still require a typecast from string)

bool is_float(float val){
    if(val != floor(val)){
        return true;
    }
    else
        return false;
}

or:

auto lambda_isFloat = [](float val) {return (val != floor(val)); };

Hope this helps !

ZMazz


答:
Here is one approach using regmatches, along the lines of what you were trying to do:

```<code>emails <- c("blah@my.blah.com;etc@etc.edu;me@me.gov",
            "yay@something.gov;yes@my.blah.com;maybe@maybe.net;stuff@my.blah.com",
            "someemail@nothing.gov")

sapply(emails, function(x) {
    m <- gregexpr("[^;]+@my\\.blah\\.com", x)
    regmatches(x, m)
})
names(matches) <- seq(1:length(matches))
matches

$`1`
[1] "blah@my.blah.com"

$`2`
[1] "yes@my.blah.com"   "stuff@my.blah.com"

$`3`
character(0)
</code>```

Title: Extract e-mail with a certain domain from a semicolon-separated vector of e-mails

Body:
Consider the following vector of e-mails:

emails <- c("blah@my.blah.com;etc@etc.edu;me@me.gov",
            "yay@something.gov;yes@my.blah.com;maybe@maybe.net",
            "someemail@nothing.gov")

Each element of the vector above is a semi-colon separated string of e-mail address for a user. In this case, for example, the first user has three e-mails: blah@my.blah.com, etc@etc.edu, and me@me.gov.

I have  a specific domain name I am interested in - let's say it's my.blah.com. I also know for a fact that, given my domain knowledge of this problem, that each user can only have one my.blah.com e-mail address, if it exists. I would like to return this e-mail address for each user as a character vector, and return NA in the cases in which a my.blah.com e-mail address does not exist.

Thus, the output should be

c("blah@my.blah.com", "yes@my.blah.com", NA)

My best attempt at this is

emails <- c("blah@my.blah.com;etc@etc.edu;me@me.gov",
            "yay@something.gov;yes@my.blah.com;maybe@maybe.net",
            "someemail@nothing.gov")

regmatches(emails,
           regexec("+.*@my.blah.com",
                   emails))

[[1]]
[1] "blah@my.blah.com"

[[2]]
[1] "yay@something.gov;yes@my.blah.com"

[[3]]
character(0)

which isn't a character vector, but I'm struggling to just get the RegEx right at this point, which is what I'd like to focus on.

Body:
Here is one approach using regmatches, along the lines of what you were trying to do:

emails <- c("blah@my.blah.com;etc@etc.edu;me@me.gov",
            "yay@something.gov;yes@my.blah.com;maybe@maybe.net;stuff@my.blah.com",
            "someemail@nothing.gov")

sapply(emails, function(x) {
    m <- gregexpr("[^;]+@my\\.blah\\.com", x)
    regmatches(x, m)
})
names(matches) <- seq(1:length(matches))
matches

$`1`
[1] "blah@my.blah.com"

$`2`
[1] "yes@my.blah.com"   "stuff@my.blah.com"

$`3`
character(0)


问:
Stop python program from closing when a directory is not found
Im creating a DOS clone with python and I have a command cd which allows you to change directory. The only problem is that if you misspell or type a non-existent directory, the program closes with a traceback error. Im basically looking for it not to completely close the program but instead print a statement like 'requested_directory' Is not a directory! and allow you to type in a different directory.

Ive tried a couple things, mainly error handling, but to no prevail. Im assuming that im still not quite understanding error handling or using it incorrectly.

Any help is much appreciated.

This is the code im using to change directories (elif because i have many more commands. cmd is a raw input.)

```<code>elif 'cd' in cmd:
        desired_directory = cmd.split(' ')[1]
        if desired_directory == "..":
            os.chdir('..')
        else:
            os.chdir(desired_directory)
</code>```

This is the output when an incorrect directory is typed in

```<code>Traceback (most recent call last):
  File "/Users/jrosmac/PycharmProjects/untitled/JDOS/SYS64/jdosos.py", line 47, in <module>
    os.chdir(desired_directory)
OSError: [Errno 2] No such file or directory: 'raw_input goes here'
</code>```

答:
I believe you need to handle the error.

try:
    os.chdir(desired_directory)
except OSError as e:
    print e.args[0]
```

Body:
Im creating a DOS clone with python and I have a command cd which allows you to change directory. The only problem is that if you misspell or type a non-existent directory, the program closes with a traceback error. Im basically looking for it not to completely close the program but instead print a statement like 'requested_directory' Is not a directory! and allow you to type in a different directory.

Ive tried a couple things, mainly error handling, but to no prevail. Im assuming that im still not quite understanding error handling or using it incorrectly.

Any help is much appreciated.

This is the code im using to change directories (elif because i have many more commands. cmd is a raw input.)

elif 'cd' in cmd:
        desired_directory = cmd.split(' ')[1]
        if desired_directory == "..":
            os.chdir('..')
        else:
            os.chdir(desired_directory)

This is the output when an incorrect directory is typed in

Traceback (most recent call last):
  File "/Users/jrosmac/PycharmProjects/untitled/JDOS/SYS64/jdosos.py", line 47, in <module>
    os.chdir(desired_directory)
OSError: [Errno 2] No such file or directory: 'raw_input goes here'


答:
Use exception handing:</p>

```<code>try:
    os.chdir(target)
except OSError as e:
    # handle the failure of the chdir call
</code>```

Title: Stop python program from closing when a directory is not found

Body:
Use exception handing:

try:
    os.chdir(target)
except OSError as e:
    # handle the failure of the chdir call


问:
how to resolve error :SDL_OpenAudio (2 channels, 44100 Hz): No such audio device
I have tried the code:

```<code>import cv2
import numpy as np
from ffpyplayer.player import MediaPlayer
video_path="/home/xxx/Desktop/videoplayback.mp4"
def PlayVideo(video_path):
    video=cv2.VideoCapture(video_path)
    player = MediaPlayer(video_path)
    while True:
        grabbed, frame=video.read()
        audio_frame, val = player.get_frame()
        if not grabbed:
            print("End of video")
            break
        if cv2.waitKey(28) & 0xFF == ord("q"):
            break
        cv2.imshow("Video", frame)
        if val != 'eof' and audio_frame is not None:
            #audio
            img, t = audio_frame
    video.release()
    cv2.destroyAllWindows()
PlayVideo(video_path)
</code>```

I'm getting following error.

SDL_OpenAudio (2 channels, 44100 Hz): No such audio device
  SDL_OpenAudio (1 channels, 44100 Hz): No such audio device
  No more channel combinations to try, audio open failed

答:
I got around this by installing the latest version of ffpyplayer on GitHub as per the project's instructions.</p>

```<code>pip install https://github.com/matham/ffpyplayer/archive/master.zip
</code>```

Body:
I have tried the code:

import cv2
import numpy as np
from ffpyplayer.player import MediaPlayer
video_path="/home/xxx/Desktop/videoplayback.mp4"
def PlayVideo(video_path):
    video=cv2.VideoCapture(video_path)
    player = MediaPlayer(video_path)
    while True:
        grabbed, frame=video.read()
        audio_frame, val = player.get_frame()
        if not grabbed:
            print("End of video")
            break
        if cv2.waitKey(28) & 0xFF == ord("q"):
            break
        cv2.imshow("Video", frame)
        if val != 'eof' and audio_frame is not None:
            #audio
            img, t = audio_frame
    video.release()
    cv2.destroyAllWindows()
PlayVideo(video_path)

I'm getting following error.

SDL_OpenAudio (2 channels, 44100 Hz): No such audio device
  SDL_OpenAudio (1 channels, 44100 Hz): No such audio device
  No more channel combinations to try, audio open failed

Body:
I got around this by installing the latest version of ffpyplayer on GitHub as per the project's instructions.

pip install https://github.com/matham/ffpyplayer/archive/master.zip


问:
Php for each data to display in a comma seperated list with no space
Currently i am displaying id's of users to display in a single line with a comma delimiter, the problem is it is having unwanted space between comma's

Showing like this
1, 6, 10

Should be like this
1,6,10

<?php foreach ( $students as $student ) {

          $process = '';
          $result = 0;
          $student = learn_press_get_user( $student->ID );
          $data = $student->get_course_data($course->get_id());
          $status = $student->get_course_status($course->get_id());
          $result = $data->get_results();
   ?>

  <?php if ( $status ) {
  $process = ( $status == 'finished' ) ? 'finished' : 'in-progress';
  } ?>

       <?php echo $student->get_id(); ?>,
        <?php } ?>

```

答:
Another solution with implode

```<code><div class="students">
  <?php
  $student_ids = array();
  foreach ( $students as $student ) {
         $process = '';
         $result = 0;
         $student = learn_press_get_user( $student->ID );
         $data = $student->get_course_data($course->get_id());
         $status = $student->get_course_status($course->get_id());
         $result = $data->get_results();
         if ( $status ) {
           $process = ( $status == 'finished' ) ? 'finished' : 'in-progress';
         }
         $student_ids[] =  $student->get_id(); // store all student id in array
    }
    echo implode(',', $student_ids);
  ?>
</div>
</code>```

Body:
Another solution with implode

<div class="students">
  <?php
  $student_ids = array();
  foreach ( $students as $student ) {
         $process = '';
         $result = 0;
         $student = learn_press_get_user( $student->ID );
         $data = $student->get_course_data($course->get_id());
         $status = $student->get_course_status($course->get_id());
         $result = $data->get_results();
         if ( $status ) {
           $process = ( $status == 'finished' ) ? 'finished' : 'in-progress';
         }
         $student_ids[] =  $student->get_id(); // store all student id in array
    }
    echo implode(',', $student_ids);
  ?>
</div>


问:
What is the most performant method to access top level props in deep children or a config file?
Currently

I have an item list built in React.

Each item has fields, and field 1 can be edited by a form.

The field 1 form allows you to link 2 items together.

The form takes in a config file that contains the list of items.

Problem

What is the most performant way to populate the config file with the list of items so that each form (when opened) can access the list of items?

My concern is that if I pass the list of items down through each item, it's a very heavy load on the app.

I have also read that declaring global variables (e.g. in window.items) is bad practice. Ref: https://stackoverflow.com/a/45081013/1730260

Architecture

答: performance wise both are same thing, Context API is just a cleaner/newer approach that people can take. Since your architecture is based on multiple and deep child tree, Redux is more viable solution for you so that you dont have to pass prop to any undesired component and just pull from App state where needed directly by using connect. If you are talking about React's own implementation then Context API for cleaner approach but again performance wise both are same.


问:
Optional vs if/else-if performance java 8
Hello i have two samples of code

if/else if/else statements

private Object getObj(message) {
        if (message.getA() != null)
            return message.getA();
        else if (message.getB() != null)
            return message.getB();
        else if (message.getC() != null)
            return message.getC();
        else return null;
}
```

<p>Optional statements</p>

<pre class="lang-java prettyprint-override"><code>private Optional<Object> wrap(Object o){
    return Optional.ofNullable(o);
}

private Object getObj(message) {
    return  wrap(message.getA())
            .orElseGet(() -> wrap(message.getB())
            .orElseGet(() -> wrap(message.getC())
            .orElse(null)));
}
</code>```

So my question is how these two compare in terms of performance (i have about 15-20 if-else statements on actual code)?

Is it worth refactoring the code readability vs performance or is a misusage of optionals?

Also what is the performance penalty in case the if/else-if statements grown to 100+?

Thanks in advance

答:
tl;dr

If your goal is condensed code, then use ternary chaining. Performance is likely identical to that of a series of if-then-else statements.

```<code>        ( this.getA() != null ) ? this.getA()
                : ( this.getB() != null ) ? this.getB()
                : ( this.getC() != null ) ? this.getC()
                : null;
</code>```

Ternary chaining

As the Answer by Lino correctly states, you are trying to take Optional beyond their original design purpose (returning values within lambdas & streams). Generally best to use Optional only with a return statement, and only then when you want to make clear that null is a valid value to be returned. See this Answer by Brian Goetz.

A ternary operator is a condensed if-then-else, combined into a one-liner.

```<code>result = test ? valueToUseIfTestIsTrue : valueToUseIfTestIsFalse
</code>```

Example:

```<code>Color color = isPrinterMonochrome ? Color.GREY : Color.GREEN ;
</code>```

Use a chain of ternary statements.

So this:

```<code>    if ( this.getA() != null )
        return this.getA();
    else if ( this.getB() != null )
        return this.getB();
    else if ( this.getC() != null )
        return this.getC();
    else return null;
</code>```

…becomes this:

```<code>    return
            ( this.getA() != null ) ? this.getA()
                    : ( this.getB() != null ) ? this.getB()
                    : ( this.getC() != null ) ? this.getC()
                    : null;
</code>```

Example code.

```<code>public String getA ()
{
    // return "A";
    return null;
}

public String getB ()
{
    // return "B";
    return null;
}

public String getC ()
{
    return "C";
    // return null;
}

public String getABC ()
{
    if ( this.getA() != null )
        return this.getA();
    else if ( this.getB() != null )
        return this.getB();
    else if ( this.getC() != null )
        return this.getC();
    else return null;
}

public String getABCTernary ()
{
    return
            ( this.getA() != null ) ? this.getA()
                    : ( this.getB() != null ) ? this.getB()
                    : ( this.getC() != null ) ? this.getC()
                    : null;
}
</code>```

Run that example code.

```<code>String s = this.getABCTernary();
System.out.println( "s: " + s );
</code>```

C

Pros and cons

The upside to the ternary chain is condensed code, collapsed into a one-liner.

The downside is that you are calling your getter method twice in this particular situation just to get a single value. Not a problem for a simple fetch-the-variable kind of getter, but impact performance if the getter is a time-consuming method such as a remote web services call. And, the cascading if-then-else has the same problem, also calling your getter twice.

Performance

how these two compare in terms of performance

The ternary operator in Java is "short-circuiting", meaning the left or right side that matches the test results is the only code called. In our code here, if getA returns a non-null value, that value is returned immediately. The further calls to getB and getC are never executed. So in this regard, the performance of the chained ternary is the same as a cascading if-then-else statement: first-match wins, no further calls.

If you mean performance as in nanoseconds of execution, I do not know. Worrying about that would be falling into the trap of premature optimization. Modern JVMs are extremely well-tuned for optimizing your code.

Body:
Hello i have two samples of code

if/else if/else statements

private Object getObj(message) {
        if (message.getA() != null)
            return message.getA();
        else if (message.getB() != null)
            return message.getB();
        else if (message.getC() != null)
            return message.getC();
        else return null;
}

Optional statements

private Optional<Object> wrap(Object o){
    return Optional.ofNullable(o);
}

private Object getObj(message) {
    return  wrap(message.getA())
            .orElseGet(() -> wrap(message.getB())
            .orElseGet(() -> wrap(message.getC())
            .orElse(null)));
}

So my question is how these two compare in terms of performance (i have about 15-20 if-else statements on actual code)?

Is it worth refactoring the code readability vs performance or is a misusage of optionals?

Also what is the performance penalty in case the if/else-if statements grown to 100+?

Thanks in advance

Body:
tl;dr

If your goal is condensed code, then use ternary chaining. Performance is likely identical to that of a series of if-then-else statements.

        ( this.getA() != null ) ? this.getA()
                : ( this.getB() != null ) ? this.getB()
                : ( this.getC() != null ) ? this.getC()
                : null;

Ternary chaining

As the Answer by Lino correctly states, you are trying to take Optional beyond their original design purpose (returning values within lambdas & streams). Generally best to use Optional only with a return statement, and only then when you want to make clear that null is a valid value to be returned. See this Answer by Brian Goetz.

A ternary operator is a condensed if-then-else, combined into a one-liner.

result = test ? valueToUseIfTestIsTrue : valueToUseIfTestIsFalse

Example:

Color color = isPrinterMonochrome ? Color.GREY : Color.GREEN ;

Use a chain of ternary statements.

So this:

    if ( this.getA() != null )
        return this.getA();
    else if ( this.getB() != null )
        return this.getB();
    else if ( this.getC() != null )
        return this.getC();
    else return null;

…becomes this:

    return
            ( this.getA() != null ) ? this.getA()
                    : ( this.getB() != null ) ? this.getB()
                    : ( this.getC() != null ) ? this.getC()
                    : null;

Example code.

public String getA ()
{
    // return "A";
    return null;
}

public String getB ()
{
    // return "B";
    return null;
}

public String getC ()
{
    return "C";
    // return null;
}

public String getABC ()
{
    if ( this.getA() != null )
        return this.getA();
    else if ( this.getB() != null )
        return this.getB();
    else if ( this.getC() != null )
        return this.getC();
    else return null;
}

public String getABCTernary ()
{
    return
            ( this.getA() != null ) ? this.getA()
                    : ( this.getB() != null ) ? this.getB()
                    : ( this.getC() != null ) ? this.getC()
                    : null;
}

Run that example code.

String s = this.getABCTernary();
System.out.println( "s: " + s );

C

Pros and cons

The upside to the ternary chain is condensed code, collapsed into a one-liner.

The downside is that you are calling your getter method twice in this particular situation just to get a single value. Not a problem for a simple fetch-the-variable kind of getter, but impact performance if the getter is a time-consuming method such as a remote web services call. And, the cascading if-then-else has the same problem, also calling your getter twice.

Performance

how these two compare in terms of performance

The ternary operator in Java is "short-circuiting", meaning the left or right side that matches the test results is the only code called. In our code here, if getA returns a non-null value, that value is returned immediately. The further calls to getB and getC are never executed. So in this regard, the performance of the chained ternary is the same as a cascading if-then-else statement: first-match wins, no further calls.

If you mean performance as in nanoseconds of execution, I do not know. Worrying about that would be falling into the trap of premature optimization. Modern JVMs are extremely well-tuned for optimizing your code.


问:
How can a local std::bernoulli_distribution create accurately distributed data?
Here, I have a class Generator that has a random number engine and a method genTrial() that's supposed to return a bool representing the "success" or "failure" outcome of an independent trial. Using the std::bernoulli_distribution, I can assign the probability of getting a "success"; notice that this variable is local to genTrial().

In the main code, I am generating 30,000 trials by repeatedly calling genTrial() with a success parameter of 25% in the loop. When the code runs, the distribution is correct.

My question is: Since the std::bernoulli_distribution variable is local, how does it know/remember the state of the distribution in order to still generate a correct data set? If a new variable is created/destroyed every iteration, there's no persistence of state and no way to know what's been done in the past, so how does it determine where to put the fed in number? Shouldn't it put the numbers in the same set?

generator.h

#ifndef GENERATOR_H
#define GENERATOR_H

#include <random>

class Generator
{
    private:
        static std::mt19937 randEngine;

    public:
        bool genTrial(double success);
};

#endif
```

<p><strong>generator.cpp</strong></p>

<pre class="lang-cpp prettyprint-override"><code>#include "generator.h"
#include <cstdlib>
#include <random>

std::mt19937 Generator::randEngine(0);

bool Generator::genTrial(double success)
{
    std::bernoulli_distribution distrib(success);
    return distrib(randEngine);
}
</code>```

main.cpp

#include "generator.h"
#include <iostream>

int main()
{
    const int NUM_SAMPLES = 30000;
    const int NUM_OF_BINARY_VALUES = 2;
    const double SUCCESS_RATE = 0.25;

    Generator gen;
    int binaryRecord[NUM_OF_BINARY_VALUES] = {0};

    // "roll the dice"
    for(int x = 0; x < NUM_SAMPLES; x++)
    {
        bool thisRoll = gen.genTrial(SUCCESS_RATE);
        if(thisRoll == true) binaryRecord[1]++;
        else binaryRecord[0]++;
    }

    // draw the results
    for(int y = 0; y < NUM_OF_BINARY_VALUES; y++)
    {
        if(y == 0) std::cout << "[F]: ";
        else std::cout << "[T]: ";

        int numActualTallies = binaryRecord[y];
        int numDisplayedTallies = numActualTallies / 1000;
        for(int i = 0; i < numDisplayedTallies; i++)
        {
            std::cout << "*";
        }
        std::cout << "\n";
    }
    return 0;
}
```

答:
std::mt19937 Generator::randEngine(0); this is your source of randomness.

Distributions extract randomness from engines and produce values.

Distributions are mostly stateless (after construction).  Their state is outsourced to the engine.

Body:
Here, I have a class Generator that has a random number engine and a method genTrial() that's supposed to return a bool representing the "success" or "failure" outcome of an independent trial. Using the std::bernoulli_distribution, I can assign the probability of getting a "success"; notice that this variable is local to genTrial().

In the main code, I am generating 30,000 trials by repeatedly calling genTrial() with a success parameter of 25% in the loop. When the code runs, the distribution is correct.

My question is: Since the std::bernoulli_distribution variable is local, how does it know/remember the state of the distribution in order to still generate a correct data set? If a new variable is created/destroyed every iteration, there's no persistence of state and no way to know what's been done in the past, so how does it determine where to put the fed in number? Shouldn't it put the numbers in the same set?

generator.h

#ifndef GENERATOR_H
#define GENERATOR_H

#include <random>

class Generator
{
    private:
        static std::mt19937 randEngine;

    public:
        bool genTrial(double success);
};

#endif

generator.cpp

#include "generator.h"
#include <cstdlib>
#include <random>

std::mt19937 Generator::randEngine(0);

bool Generator::genTrial(double success)
{
    std::bernoulli_distribution distrib(success);
    return distrib(randEngine);
}

main.cpp

#include "generator.h"
#include <iostream>

int main()
{
    const int NUM_SAMPLES = 30000;
    const int NUM_OF_BINARY_VALUES = 2;
    const double SUCCESS_RATE = 0.25;

    Generator gen;
    int binaryRecord[NUM_OF_BINARY_VALUES] = {0};

    // "roll the dice"
    for(int x = 0; x < NUM_SAMPLES; x++)
    {
        bool thisRoll = gen.genTrial(SUCCESS_RATE);
        if(thisRoll == true) binaryRecord[1]++;
        else binaryRecord[0]++;
    }

    // draw the results
    for(int y = 0; y < NUM_OF_BINARY_VALUES; y++)
    {
        if(y == 0) std::cout << "[F]: ";
        else std::cout << "[T]: ";

        int numActualTallies = binaryRecord[y];
        int numDisplayedTallies = numActualTallies / 1000;
        for(int i = 0; i < numDisplayedTallies; i++)
        {
            std::cout << "*";
        }
        std::cout << "\n";
    }
    return 0;
}


问:
remove dataframe rows where value is much lower than surrounding rows
```<code>Date          Data
2016-04-29    12
2016-04-30    13
2016-05-01    2
2016-05-02    11
2016-05-03    12
2016-05-04    3
2016-05-05    14
</code>```

In the datafrme above, I want to remove those rows where the row value dips below adjacent 2 rows by an average of 8 units e.g. the values in row corresponding to dates 2016-05-01 and 2016-05-04 are at least 8 units below immediately surrounding 2 rows. The result should look like:

```<code>Date          Data
2016-04-29    12
2016-04-30    13
2016-05-02    11
2016-05-03    12
2016-05-05    14
</code>```

答:
You should take a look at pandas.Series.diff.

I would do it like this:

```<code>>>> df
            Data
Date
2016-04-29    12
2016-04-30    13
2016-05-01     2
2016-05-02    11
2016-05-03    12
2016-05-04     3
2016-05-05    14

>>> df[(df.Data.diff().fillna(0) > -8) & (df.Data.diff(-1).fillna(0) > -8)]
            Data
Date
2016-04-29    12
2016-04-30    13
2016-05-02    11
2016-05-03    12
2016-05-05    14
</code>```

Explanation

The first expression computes row difference taking second minus first, etc. Then replacing the NaN in the first row.

The second expression computes row difference taking first minus second, etc. Replacing the NaN in the last row. I filter out rows where both expressions result in values below a given threshold.

Body:
Date          Data
2016-04-29    12
2016-04-30    13
2016-05-01    2
2016-05-02    11
2016-05-03    12
2016-05-04    3
2016-05-05    14

In the datafrme above, I want to remove those rows where the row value dips below adjacent 2 rows by an average of 8 units e.g. the values in row corresponding to dates 2016-05-01 and 2016-05-04 are at least 8 units below immediately surrounding 2 rows. The result should look like:

Date          Data
2016-04-29    12
2016-04-30    13
2016-05-02    11
2016-05-03    12
2016-05-05    14

Body:
You should take a look at pandas.Series.diff.

I would do it like this:

>>> df
            Data
Date
2016-04-29    12
2016-04-30    13
2016-05-01     2
2016-05-02    11
2016-05-03    12
2016-05-04     3
2016-05-05    14

>>> df[(df.Data.diff().fillna(0) > -8) & (df.Data.diff(-1).fillna(0) > -8)]
            Data
Date
2016-04-29    12
2016-04-30    13
2016-05-02    11
2016-05-03    12
2016-05-05    14

Explanation

The first expression computes row difference taking second minus first, etc. Then replacing the NaN in the first row.

The second expression computes row difference taking first minus second, etc. Replacing the NaN in the last row. I filter out rows where both expressions result in values below a given threshold.


问:
Understanding UIView Height When Constraints Are Set with AutoLayout/UIScrollView
I hope this  helps, but I am trying to wrap my head around a concept.  I have a UIScrollView, added to a self.view in my ViewController, with its top, leading, trailing, and bottom edges pinned to that of the self.view.  This is viewA.

I have a second UIView, viewB, with several subviews.  Each of those subviews are added to viewB with AutoLayout, and for brevity, each of those subviews have a height constraint set to a value.

I want to add viewB to viewA, with viewA able to scroll vertically.  Since viewB is undoubtedly taller than viewA, it should scroll.

I am adding viewB like so;

```<code>viewB.topAnchor.constraint(equalTo: viewA.topAnchor).isActive = true
viewB.leadingAnchor.constraint(equalTo: viewA.leadingAnchor).isActive = true
viewB.trailingAnchor.cosntraint(equalTo: viewA.trailingAnchor).isActive = true
</code>```

This is where I am stuck.  If I set a bottom anchor (viewB.bottomAnchor.constraint(equalTo: viewA.bottomAnchor).isActive = true), my UIScrollView does not scroll, and viewB is visibly cut off.

If I set a random height for viewB (using viewB.heightAnchor.constraint(equalToConstant: 2000.0).isActive = true), the UIScrollView does scroll, though this constant is far too tall.

I am confused how to get the appropriate height for viewB.  Since viewB does have an actual height (with hard-coded subviews), I see no reason that AutoLayout shouldn't be able to calculate that height of viewB, even with no bottom anchor set, but can't figure out the right code.

答:
If the height constraint is complete, you don't have to consider viewA's contentSize.
You don't need to use ViewB, subviews add to viewA, subview1's top equalTo viewA's top, set subview1 height, subview1's bottom equalTo subview2's top or offset some Height. And so on. Until the last subview, subview4's bottom equal to viewA' bottom. You can get a suitable content size without setting the height of the content.</p>

Body:
I hope this  helps, but I am trying to wrap my head around a concept.  I have a UIScrollView, added to a self.view in my ViewController, with its top, leading, trailing, and bottom edges pinned to that of the self.view.  This is viewA.

I have a second UIView, viewB, with several subviews.  Each of those subviews are added to viewB with AutoLayout, and for brevity, each of those subviews have a height constraint set to a value.

I want to add viewB to viewA, with viewA able to scroll vertically.  Since viewB is undoubtedly taller than viewA, it should scroll.

I am adding viewB like so;

viewB.topAnchor.constraint(equalTo: viewA.topAnchor).isActive = true
viewB.leadingAnchor.constraint(equalTo: viewA.leadingAnchor).isActive = true
viewB.trailingAnchor.cosntraint(equalTo: viewA.trailingAnchor).isActive = true

This is where I am stuck.  If I set a bottom anchor (viewB.bottomAnchor.constraint(equalTo: viewA.bottomAnchor).isActive = true), my UIScrollView does not scroll, and viewB is visibly cut off.

If I set a random height for viewB (using viewB.heightAnchor.constraint(equalToConstant: 2000.0).isActive = true), the UIScrollView does scroll, though this constant is far too tall.

I am confused how to get the appropriate height for viewB.  Since viewB does have an actual height (with hard-coded subviews), I see no reason that AutoLayout shouldn't be able to calculate that height of viewB, even with no bottom anchor set, but can't figure out the right code.


问:
django url doesn't work fine for me when using class based view
I am new to Django and now i am using Django2.2.
The scenario is when user click profile option on menu, and it will take user to their user profile

models.py

```<code>class UserProfile(auth.models.AbstractUser):
    image = models.ImageField(upload_to=get_image_path,
                              max_length=100,
                              blank=True,
                              null=True,
                              default='account_users/default/profile_image/default.png')

    class Meta:
        verbose_name = "account_user"
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.username
</code>```

template

```<code><ul class="dropdown-menu dropdown-menu-right" aria-labelledby="dropdownMenu1">
    <li>
        <a href="{% url 'account:user_profile_detail' username=userprofile.username %}" class="btn btn-simple">Profile</a>
    </li>
</ul>

</code>```

urls.py

```<code>urlpatterns = [
    path("profile/<str:username>/", views.UserDetail.as_view(), name="user_profile_detail"),
]

</code>```

views.py

```<code>class UserDetail(DetailView):
    model = models.UserProfile
    template_name = "userprofile_detail.html"

    def get_queryset(self):
        queryset = super().get_queryset()
        return queryset.filter(
            userprofile__username__iexact=self.kwargs.get("username")
        )
</code>```

it shows me this following error :

AttributeError at /account/profile/sm10547/
Generic detail view UserDetail must be called with either an object pk or a slug in the URLconf.
Request Method: GET
Request URL:    http://0.0.0.0:8000/account/profile/sm10547/
Django Version: 2.2.1
Exception Type: AttributeError
Exception Value:

Generic detail view UserDetail must be called with either an object pk or a slug in the URLconf.
Exception Location: /usr/local/lib/python3.7/site-packages/django/views/generic/detail.py in get_object, line 47
Python Executable:  /usr/local/bin/python
Python Version: 3.7.2

updated :  sorry i update current situation here , now the structure
  is :

models.py

```<code>class UserProfile(auth.models.AbstractUser):
    image = models.ImageField(upload_to=get_image_path,
                              max_length=100,
                              blank=True,
                              null=True,
                         default='account_users/default/profile_image/default.png')

    class Meta:
        verbose_name = "account_user"
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.username
</code>```

template

```<code><ul class="dropdown-menu dropdown-menu-right" aria-labelledby="dropdownMenu1">
    <li>
        <a href="{% url 'account:user_profile_detail' username=userprofile.username %}" class="btn btn-simple">Profile</a>
    </li>
</ul>
</code>```

url.py

```<code>urlpatterns = [
    path("profile/<slug:username>/", views.UserDetail.as_view(), name="user_profile_detail"),
]
</code>```

view.py

```<code>class UserDetail(DetailView):
    model = models.UserProfile
    template_name = "userprofile_detail.html"
    slug_url_kwarg = 'username'

    def get_queryset(self)  :
        queryset = super().get_queryset()
        return queryset.filter(username__iexact=self.kwargs.get("username"))

</code>```

then it will throw error :

```<code>Exception Value:
Cannot resolve keyword 'slug' into field. Choices are: date_joined, email, first_name, groups, id, image, is_active, is_staff, is_superuser, last_login, last_name, logentry, password, posts, user_permissions, username
</code>```

do i really need to add slug field? or any way is better for me to deal with this error? thanks all !

答:
This error throws because it expect a slug field or pk field
Change here

```<code>class UserDetail(DetailView):
    model = models.UserProfile
    template_name = "userprofile_detail.html"
    slug_url_kwarg = 'username'
</code>```

In url.py

```<code>path("profile/<slug:username>/", views.UserDetail.as_view(), name="user_profile_detail"),
</code>```

In views.py

```<code>return queryset.filter(username__iexact=self.kwargs.get("username"))
</code>```

Lean more slug_url_kwarg

Body:
I am new to Django and now i am using Django2.2.
The scenario is when user click profile option on menu, and it will take user to their user profile

models.py

class UserProfile(auth.models.AbstractUser):
    image = models.ImageField(upload_to=get_image_path,
                              max_length=100,
                              blank=True,
                              null=True,
                              default='account_users/default/profile_image/default.png')

    class Meta:
        verbose_name = "account_user"
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.username

template

        Profile

urls.py

urlpatterns = [
    path("profile/<str:username>/", views.UserDetail.as_view(), name="user_profile_detail"),
]

views.py

class UserDetail(DetailView):
    model = models.UserProfile
    template_name = "userprofile_detail.html"

    def get_queryset(self):
        queryset = super().get_queryset()
        return queryset.filter(
            userprofile__username__iexact=self.kwargs.get("username")
        )

it shows me this following error :

AttributeError at /account/profile/sm10547/
Generic detail view UserDetail must be called with either an object pk or a slug in the URLconf.
Request Method: GET
Request URL:    http://0.0.0.0:8000/account/profile/sm10547/
Django Version: 2.2.1
Exception Type: AttributeError
Exception Value:

Generic detail view UserDetail must be called with either an object pk or a slug in the URLconf.
Exception Location: /usr/local/lib/python3.7/site-packages/django/views/generic/detail.py in get_object, line 47
Python Executable:  /usr/local/bin/python
Python Version: 3.7.2

updated :  sorry i update current situation here , now the structure
  is :

models.py

class UserProfile(auth.models.AbstractUser):
    image = models.ImageField(upload_to=get_image_path,
                              max_length=100,
                              blank=True,
                              null=True,
                         default='account_users/default/profile_image/default.png')

    class Meta:
        verbose_name = "account_user"
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.username

template

        Profile

url.py

urlpatterns = [
    path("profile/<slug:username>/", views.UserDetail.as_view(), name="user_profile_detail"),
]

view.py

class UserDetail(DetailView):
    model = models.UserProfile
    template_name = "userprofile_detail.html"
    slug_url_kwarg = 'username'

    def get_queryset(self)  :
        queryset = super().get_queryset()
        return queryset.filter(username__iexact=self.kwargs.get("username"))

then it will throw error :

Exception Value:
Cannot resolve keyword 'slug' into field. Choices are: date_joined, email, first_name, groups, id, image, is_active, is_staff, is_superuser, last_login, last_name, logentry, password, posts, user_permissions, username

do i really need to add slug field? or any way is better for me to deal with this error? thanks all !

Body:
This error throws because it expect a slug field or pk field
Change here

class UserDetail(DetailView):
    model = models.UserProfile
    template_name = "userprofile_detail.html"
    slug_url_kwarg = 'username'

In url.py

path("profile/<slug:username>/", views.UserDetail.as_view(), name="user_profile_detail"),

In views.py

return queryset.filter(username__iexact=self.kwargs.get("username"))

Lean more slug_url_kwarg