问:
sed: delete items between multiple pattern matches (issue with greediness)
So Ive spent a few hours looking at similar articles - helpful yes but not enough to get me over the hump.

I have a line I want to keep the beginning of and then surgically isolate matching patterns after to the end of the string.

For example heres the original line (easy to focus on just one line):

```<code>ltm pool gateway_ping { description "healthcheck pool" load-balancing-mode least-connections-node members { 10.100.100.4:icmp { address 10.100.100.4 session monitor-enabled state up } server2name:https { address 1.1.1.1 session monitor-enabled state up } } monitor Pingmonitor
</code>```

This shortens and isolates the name like Im trying:

cat config.txt | sed -e 's/^ltm \(pool .*\) { .*members { /\1 members /'

gets me this:

```<code>pool gateway_ping members 10.100.100.4:icmp { address 10.100.100.4 session monitor-enabled state up } server2name:https { address 1.1.1.1 session monitor-enabled state up } } monitor Pingmonitor
</code>```

Now to pipe the results to another sed and somehow get rid of anything between the each instance of braces

```<code>{ address 10.100.100.4 session monitor-enabled state up }
{ address 1.1.1.1 session monitor-enabled state up }
</code>```

adding this:

| sed -e 's/{ address .* } / /g'

I ended up with this haircut giving me the first match correctly but blowing out all the rest:

```<code>pool gateway_ping members 10.100.100.4:icmp monitor Pingmonitor }
</code>```

I really need the other members in there - the line should read:

```<code>pool gateway_ping members 10.100.100.4:icmp server2name:https monitor Pingmonitor }
</code>```

I can get rid of the monitor Pingmonitor }    Im just stuck on how to NOT have SED be greedy and blow out all matches to the very LAST end brace... I'd like it to stop at the first end brace... then continue on matching individually.

I think I may have murdered this by trying to describe it.   Hopefully I didnt lose the audience :-)

答:
var='ltm pool gateway_ping { description "healthcheck pool" load-balancing-mode least-connections-node members { 10.100.100.4:icmp { address 10.100.100.4 session monitor-enabled state up } server2name:https { address 1.1.1.1 session monitor-enabled state up } } monitor Pingmonitor'

# with GNU awk
awk -F' *{ *' '
    /^ltm pool/{
        $0 = gensub(/^ltm (pool \w+) .* (members) {/, "\\1 \\2", "1")
        for(i=2; i<=NF-1; i++) sub(/.* /, "", $i)
        sub(/ address.*} }/, "")
    }
    ($1=$1)
' <<<"${var}"

### output:
pool gateway_ping members 10.100.100.4:icmp server2name:https monitor Pingmonitor

# with GNU sed
sed -nE '
    s/ \{ address( \S+){5} \}//g
    s/ +\}//;s/^ltm (pool \S+) \{ .* (members) \{/\1 \2/p
' <<<"${var}"

### output:
pool gateway_ping members 10.100.100.4:icmp server2name:https monitor Pingmonitor
```

Does any of these help you out? I can come back and edit the answer with some explanation if you want.

Body:
So Ive spent a few hours looking at similar articles - helpful yes but not enough to get me over the hump.

I have a line I want to keep the beginning of and then surgically isolate matching patterns after to the end of the string.

For example heres the original line (easy to focus on just one line):

ltm pool gateway_ping { description "healthcheck pool" load-balancing-mode least-connections-node members { 10.100.100.4:icmp { address 10.100.100.4 session monitor-enabled state up } server2name:https { address 1.1.1.1 session monitor-enabled state up } } monitor Pingmonitor

This shortens and isolates the name like Im trying:

cat config.txt | sed -e 's/^ltm \(pool .*\) { .*members { /\1 members /'

gets me this:

pool gateway_ping members 10.100.100.4:icmp { address 10.100.100.4 session monitor-enabled state up } server2name:https { address 1.1.1.1 session monitor-enabled state up } } monitor Pingmonitor

Now to pipe the results to another sed and somehow get rid of anything between the each instance of braces

{ address 10.100.100.4 session monitor-enabled state up }
{ address 1.1.1.1 session monitor-enabled state up }

adding this:

| sed -e 's/{ address .* } / /g'

I ended up with this haircut giving me the first match correctly but blowing out all the rest:

pool gateway_ping members 10.100.100.4:icmp monitor Pingmonitor }

I really need the other members in there - the line should read:

pool gateway_ping members 10.100.100.4:icmp server2name:https monitor Pingmonitor }

I can get rid of the monitor Pingmonitor }    Im just stuck on how to NOT have SED be greedy and blow out all matches to the very LAST end brace... I'd like it to stop at the first end brace... then continue on matching individually.

I think I may have murdered this by trying to describe it.   Hopefully I didnt lose the audience :-)

Body:
var='ltm pool gateway_ping { description "healthcheck pool" load-balancing-mode least-connections-node members { 10.100.100.4:icmp { address 10.100.100.4 session monitor-enabled state up } server2name:https { address 1.1.1.1 session monitor-enabled state up } } monitor Pingmonitor'

# with GNU awk
awk -F' *{ *' '
    /^ltm pool/{
        $0 = gensub(/^ltm (pool \w+) .* (members) {/, "\\1 \\2", "1")
        for(i=2; i<=NF-1; i++) sub(/.* /, "", $i)
        sub(/ address.*} }/, "")
    }
    ($1=$1)
' <<<"${var}"

### output:
pool gateway_ping members 10.100.100.4:icmp server2name:https monitor Pingmonitor

# with GNU sed
sed -nE '
    s/ \{ address( \S+){5} \}//g
    s/ +\}//;s/^ltm (pool \S+) \{ .* (members) \{/\1 \2/p
' <<<"${var}"

### output:
pool gateway_ping members 10.100.100.4:icmp server2name:https monitor Pingmonitor

Does any of these help you out? I can come back and edit the answer with some explanation if you want.


来源: stackexchange

问:
How to pass environment variables to FROM statement in Dockerfile
I'm starting to use Docker and I'm creating a Dockerfile.
The image I use for the FROM statement has environment variables to configure it, but I don't know how to pass the variables to this image. To do this I just need to set the ENV in the Dockerfile?</p>

答:
Yes set the env variable using ARG NAME_OF_ENV_VARIABLE in dockerfile

and while building the docker image use --build-arg Flag.

example:

docker build -t nameOfImage --build-arg NAME_OF_ENV_VARIABLE=ADD_YOUR_VALUE_TO_PASS .

ContentLicense: CC BY-SA 4.0


问:
Android - can't access strings with R.string
I am have trouble accessing a string I stored in strings.xml and don't know why.

res/values/strings.xml

```<code>    <?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="FileBrowser">FileBrowser</string>
    <string name="menu_settings">Settings</string>
    <string name="up_one_level">..</string>
    <string name="current_dir">.</string>
</resources>
</code>```

Code

```<code>this.directoryEntries.add(getString(R.string.current_dir)); //current_dir is not being seen
</code>```

答:
Check that you did not add the following import by mistake:

```<code>import android.R
</code>```

It happened to me several times this week.

Delete this line and everything will work as expected.

ContentLicense: CC BY-SA 3.0

Body:
I am have trouble accessing a string I stored in strings.xml and don't know why.

res/values/strings.xml

    <?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="FileBrowser">FileBrowser</string>
    <string name="menu_settings">Settings</string>
    <string name="up_one_level">..</string>
    <string name="current_dir">.</string>
</resources>

Code

this.directoryEntries.add(getString(R.string.current_dir)); //current_dir is not being seen

Body:
Check that you did not add the following import by mistake:

import android.R

It happened to me several times this week.

Delete this line and everything will work as expected.


问:
Cannot read properties of undefined (reading 'name') / (reading 'location')
how to solve this error with 'Cannot read properties of undefined (reading 'name')' and the same with (reading 'location'), I don't understand.

Swagger : https://test-front.framework.team/api-docs/#/%2Flocations/locations

codesandbox: https://codesandbox.io/s/elem-1f5t5

I want the item blocks to be displayed correctly, with all the information I get from the API

```<code>import "./styles.css";
    import { useEffect, useState } from "react";

const App = () => {
  const baseURL = "https://test-front.framework.team/";
  const [items, setItems] = useState([]);
  const [authors, setAuthors] = useState([]);
  const [locations, setLocations] = useState([]);

  useEffect(() => {
    fetch("https://test-front.framework.team/paintings")
      .then((res) => res.json())
      .then(
        (result) => {
          setIsLoaded(true);
          setItems(result);
          console.log("paintings");
        }
      );
    fetch("https://test-front.framework.team/authors")
      .then((res) => res.json())
      .then(
        (result) => {
          setIsLoaded(true);
          setAuthors(result);
          console.log("authors");
        }
      );
    fetch("https://test-front.framework.team/locations")
      .then((res) => res.json())
      .then(
        (result) => {
          setIsLoaded(true);
          setLocations(result);
          console.log("locations");
        }
      );
  }, []);

  const result = items.map((elem) => {
    return {
      author: authors.find((author) => author.id === elem.authorId).name,
      created: elem.created,
      id: elem.id,
      imgUrl: elem.imgUrl,
      location: locations.find((location) => location.id === elem.locationId)
        .location,
      name: elem.name
    };
  });

  return (
    <div className="App">
      {result.map((elem) => (
        <div key={elem.id} className={"item"}>
          <img src={`${baseURL}${elem.imageUrl}`} />
          <li className={"cardInfo"}>
            <ul>{elem.name}</ul>
            <ul> {elem.author}</ul>
            <ul>{elem.created}</ul>
            <ul>{elem.location}</ul>
          </li>
        </div>
      ))}
    </div>
  );
};

export default App;
</code>```

答:
its because it renders the page before the request and the items is an empty array you can set the result inside your useEffect like this:

```<code>  useEffect(() => {
    fetch("https://test-front.framework.team/paintings")
      .then((res) => res.json())
      .then(
        (result) => {
          setIsLoaded(true);
          setItems(result);
          console.log("paintings");
        }
      );
    fetch("https://test-front.framework.team/authors")
      .then((res) => res.json())
      .then(
        (result) => {
          setIsLoaded(true);
          setAuthors(result);
          console.log("authors");
        }
      );
    fetch("https://test-front.framework.team/locations")
      .then((res) => res.json())
      .then(
        (result) => {
          setIsLoaded(true);
          setLocations(result);
          console.log("locations");
        }
      );

  const result = items.map((elem) => {
    return {
      author: authors.find((author) => author.id === elem.authorId).name,
      created: elem.created,
      id: elem.id,
      imgUrl: elem.imgUrl,
      location: locations.find((location) => location.id === elem.locationId)
        .location,
      name: elem.name
    };
  });
  }, []);
</code>```

or you can set a boolean state when your request is done like this and then using jsx map your items:

```<code>import "./styles.css";
    import { useEffect, useState } from "react";

const App = () => {
  const baseURL = "https://test-front.framework.team/";
  const [items, setItems] = useState([]);
  const [authors, setAuthors] = useState([]);
  const [locations, setLocations] = useState([]);
  const [hasItemsArrived , SetHasItemsArrived] = usestate(false)

  useEffect(() => {
    fetch("https://test-front.framework.team/paintings")
      .then((res) => res.json())
      .then(
        (result) => {
          setIsLoaded(true);
          setItems(result);
          setHasItemsArrived(true);
          console.log("paintings");
        }
      );
    fetch("https://test-front.framework.team/authors")
      .then((res) => res.json())
      .then(
        (result) => {
          setIsLoaded(true);
          setAuthors(result);
          console.log("authors");
        }
      );
    fetch("https://test-front.framework.team/locations")
      .then((res) => res.json())
      .then(
        (result) => {
          setIsLoaded(true);
          setLocations(result);
          console.log("locations");
        }
      );
  }, []);

  return (
    <div className="App">
      {hasItemsArrived && items.map((elem) => (
        <div key={elem.id} className={"item"}>
          <img src={`${baseURL}${elem.imageUrl}`} />
          <li className={"cardInfo"}>
            <ul>{elem.name}</ul>
            <ul> {elem.author}</ul>
            <ul>{elem.created}</ul>
            <ul>{elem.location}</ul>
          </li>
        </div>
      ))}
    </div>
  );
};

export default App;

</code>```

Body:
how to solve this error with 'Cannot read properties of undefined (reading 'name')' and the same with (reading 'location'), I don't understand.

Swagger : https://test-front.framework.team/api-docs/#/%2Flocations/locations

codesandbox: https://codesandbox.io/s/elem-1f5t5

I want the item blocks to be displayed correctly, with all the information I get from the API

import "./styles.css";
    import { useEffect, useState } from "react";

const App = () => {
  const baseURL = "https://test-front.framework.team/";
  const [items, setItems] = useState([]);
  const [authors, setAuthors] = useState([]);
  const [locations, setLocations] = useState([]);

  useEffect(() => {
    fetch("https://test-front.framework.team/paintings")
      .then((res) => res.json())
      .then(
        (result) => {
          setIsLoaded(true);
          setItems(result);
          console.log("paintings");
        }
      );
    fetch("https://test-front.framework.team/authors")
      .then((res) => res.json())
      .then(
        (result) => {
          setIsLoaded(true);
          setAuthors(result);
          console.log("authors");
        }
      );
    fetch("https://test-front.framework.team/locations")
      .then((res) => res.json())
      .then(
        (result) => {
          setIsLoaded(true);
          setLocations(result);
          console.log("locations");
        }
      );
  }, []);

  const result = items.map((elem) => {
    return {
      author: authors.find((author) => author.id === elem.authorId).name,
      created: elem.created,
      id: elem.id,
      imgUrl: elem.imgUrl,
      location: locations.find((location) => location.id === elem.locationId)
        .location,
      name: elem.name
    };
  });

  return (

      {result.map((elem) => (

          <img src={`${baseURL}${elem.imageUrl}`} />

{elem.name}

 {elem.author}

{elem.created}

{elem.location}

      ))}

  );
};

export default App;

Body:
its because it renders the page before the request and the items is an empty array you can set the result inside your useEffect like this:

  useEffect(() => {
    fetch("https://test-front.framework.team/paintings")
      .then((res) => res.json())
      .then(
        (result) => {
          setIsLoaded(true);
          setItems(result);
          console.log("paintings");
        }
      );
    fetch("https://test-front.framework.team/authors")
      .then((res) => res.json())
      .then(
        (result) => {
          setIsLoaded(true);
          setAuthors(result);
          console.log("authors");
        }
      );
    fetch("https://test-front.framework.team/locations")
      .then((res) => res.json())
      .then(
        (result) => {
          setIsLoaded(true);
          setLocations(result);
          console.log("locations");
        }
      );

  const result = items.map((elem) => {
    return {
      author: authors.find((author) => author.id === elem.authorId).name,
      created: elem.created,
      id: elem.id,
      imgUrl: elem.imgUrl,
      location: locations.find((location) => location.id === elem.locationId)
        .location,
      name: elem.name
    };
  });
  }, []);

or you can set a boolean state when your request is done like this and then using jsx map your items:

import "./styles.css";
    import { useEffect, useState } from "react";

const App = () => {
  const baseURL = "https://test-front.framework.team/";
  const [items, setItems] = useState([]);
  const [authors, setAuthors] = useState([]);
  const [locations, setLocations] = useState([]);
  const [hasItemsArrived , SetHasItemsArrived] = usestate(false)

  useEffect(() => {
    fetch("https://test-front.framework.team/paintings")
      .then((res) => res.json())
      .then(
        (result) => {
          setIsLoaded(true);
          setItems(result);
          setHasItemsArrived(true);
          console.log("paintings");
        }
      );
    fetch("https://test-front.framework.team/authors")
      .then((res) => res.json())
      .then(
        (result) => {
          setIsLoaded(true);
          setAuthors(result);
          console.log("authors");
        }
      );
    fetch("https://test-front.framework.team/locations")
      .then((res) => res.json())
      .then(
        (result) => {
          setIsLoaded(true);
          setLocations(result);
          console.log("locations");
        }
      );
  }, []);

  return (
    <div className="App">
      {hasItemsArrived && items.map((elem) => (
        <div key={elem.id} className={"item"}>
          <img src={`${baseURL}${elem.imageUrl}`} />
          <li className={"cardInfo"}>
            <ul>{elem.name}</ul>
            <ul> {elem.author}</ul>
            <ul>{elem.created}</ul>
            <ul>{elem.location}</ul>
          </li>
        </div>
      ))}
    </div>
  );
};

export default App;


问:
I s there any way to extract values separately from the html code shown below
This is for a project I am working on and I want to extract the sales growth of 1 year, 3 years and 5 years separately. I tried doing it using

soap.find("div",{"class":"ratiosingle"}).find_all("span",{"class":"durationvalue"})[1].getText()
```
<p>but the above code is showing an error.</p>
<pre class="lang-html prettyprint-override"><code><div class="w-100">
    <div class="ratiosingle">
        <span class="duration">1 Year</span>
        <span class="durationvalue">-27.09%</span>
    </div>
    <div class="ratiosingle">
        <span class="duration">3 Year</span>
        <span class="durationvalue">-5.38%</span>
    </div>
    <div class="ratiosingle">
        <span class="duration">5 Year</span>
        <span class="durationvalue">1.05%</span>
    </div>
</div>
</code>```

import pandas as pd
from bs4 import BeautifulSoup
import requests

a = input("Enter symbol of the company\n")
url = "https://ticker.finology.in/company/" + a
print(url)
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
CP = soup.find("div", {"id": "mainContent_clsprice"}).find("span", {"class": "Number"}).getText()
```

答:
There are several apporaches to get the values, just come up with two of them used ticker IDEA.

Option#1
Values as list with css selectors and list comprehension:

```<code>[v.text for v in soup.select('#mainContent_divSales span.durationvalue')]

#output
['-6.8%', '14.41%', '3.08%']
</code>```

Option#2
More structured with stripped_strings as dict:

```<code>dict([v.stripped_strings for v in soup.select('#mainContent_divSales .ratiosingle')])

#output
{'1 Year': '-6.8%', '3 Year': '14.41%', '5 Year': '3.08%'}
</code>```

Body:
This is for a project I am working on and I want to extract the sales growth of 1 year, 3 years and 5 years separately. I tried doing it using

soap.find("div",{"class":"ratiosingle"}).find_all("span",{"class":"durationvalue"})[1].getText()

but the above code is showing an error.

        1 Year
        -27.09%

        3 Year
        -5.38%

        5 Year
        1.05%

import pandas as pd
from bs4 import BeautifulSoup
import requests

a = input("Enter symbol of the company\n")
url = "https://ticker.finology.in/company/" + a
print(url)
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
CP = soup.find("div", {"id": "mainContent_clsprice"}).find("span", {"class": "Number"}).getText()

Body:
There are several apporaches to get the values, just come up with two of them used ticker IDEA.

Option#1
Values as list with css selectors and list comprehension:

[v.text for v in soup.select('#mainContent_divSales span.durationvalue')]

#output
['-6.8%', '14.41%', '3.08%']

Option#2
More structured with stripped_strings as dict:

dict([v.stripped_strings for v in soup.select('#mainContent_divSales .ratiosingle')])

#output
{'1 Year': '-6.8%', '3 Year': '14.41%', '5 Year': '3.08%'}


问:
Can't run python manage.py runserver
Hello~ I have installed django-bootstrap-ui-2.0.0 and django-admin startproject, and tried both python and python3 manage.py runserver. However, it says that no such file or directory. Am I missing some functions that have to pip install? Much thanks!</p>
```<code>C:\Users\user\AppData\Local\Programs\Python\Python310\python.exe: can't open file 'C:\\
Users\\user\\PycharmProjects\\Pyshop\\manage.py': [Errno 2] No such file or directory
PS C:\Users\user\PycharmProjects\Pyshop>
</code>```

答: This could be because you haven't activated the virtual environment. The basic reason is that the system is not able to find manage.py on that location.</p>

Title: Can't run python manage.py runserver

Body:
Hello~ I have installed django-bootstrap-ui-2.0.0 and django-admin startproject, and tried both python and python3 manage.py runserver. However, it says that no such file or directory. Am I missing some functions that have to pip install? Much thanks!

C:\Users\user\AppData\Local\Programs\Python\Python310\python.exe: can't open file 'C:\\
Users\\user\\PycharmProjects\\Pyshop\\manage.py': [Errno 2] No such file or directory
PS C:\Users\user\PycharmProjects\Pyshop>


问:
Does FileInputStream incorrectly implement InputStream?
The docs for InputStream.read(bytes) say "This method blocks until input data is available, end of file is detected, or an exception is thrown."

However, java.io.FileInputStream extends java.io.InputStream
and the docs for FileInputStream.read(bytes) state no such guarantee:

```<code> * Reads up to {@code b.length} bytes of data from this input
 * stream into an array of bytes. This method blocks until some input
 * is available.
</code>```

In practice, FileInputStream can indeed return before all the input is available, so it seems both the docs and the implementation do not follow the contract of InputStream.

Is this a bug? Is it a known bug?

UPDATE: to clarify: System.in is a FileInputStream. I am seeing System.in.read(buf) return a nonzero int that is neither all of the bytes, nor -1. If I use System.in.readNBytes(buf, 0, theNumberOfBytesIAmExpecting) then I get all the bytes the sender is sending.

答:
I think that the situation is more subtle, - InputStream.read(byte[] b) just delegates to InputStream.read(byte[] b, int off, int len)

And for read(byte[] b, int off, int len) it seems that the contract/promise broken (or at least different).

For InputStream.read(byte[] b, int off, int len) the documentation states:

The default implementation of this method blocks until the requested amount of input data len has been read, end of file is detected, or an exception is thrown. Subclasses are encouraged to provide a more efficient implementation of this method.

(and it is implemented this way: - the requested amount of data is always read)

For FileInputStream.read(byte[] b, int off, int len) - there is no such promise (and implementation may not read all the requested amount).

Many other high-level methods delegate to read(byte[] b, int off, int len) and I would consider that at least for this method the promise of InputStream (to read either the requested amount or till the end of the steam) is broken in FileInputStream and it creates confusion.

Body:
The docs for InputStream.read(bytes) say "This method blocks until input data is available, end of file is detected, or an exception is thrown."

However, java.io.FileInputStream extends java.io.InputStream
and the docs for FileInputStream.read(bytes) state no such guarantee:

 * Reads up to {@code b.length} bytes of data from this input
 * stream into an array of bytes. This method blocks until some input
 * is available.

In practice, FileInputStream can indeed return before all the input is available, so it seems both the docs and the implementation do not follow the contract of InputStream.

Is this a bug? Is it a known bug?

UPDATE: to clarify: System.in is a FileInputStream. I am seeing System.in.read(buf) return a nonzero int that is neither all of the bytes, nor -1. If I use System.in.readNBytes(buf, 0, theNumberOfBytesIAmExpecting) then I get all the bytes the sender is sending.


问:
Export converted video into stream using ffmpeg pipe option
I'm stream and successfully output converted video into mkv file.

```<code>var stream = ..incoming stream of type MemoryStream();
var process = new System.Diagnostics.Process();
process.StartInfo.Arguments = "-f mp4 -i pipe:0 -c:v libx264 -crf 20 -s 600:400 -f matroska myfile.mkv";
process.Start();
process.StandardInput.BaseStream.Write(stream.ToArray())
process.BeginOutputReadLine()
process.StandardInput.BaseStream.Close();
process.WaitForExit(1000);
</code>```

My question is: how can I change the implementation (command and StandardOutput.BaseStream in order to export results into memory stream and not file (like it's in the above example).

答:
What you were doing in the just deleted question was correct,

```<code>-f mp4 -i pipe:0 -c:v libx264 -crf 20 -s 600:400 -f matroska pipe:1
</code>```

let you write the output to a pipe. But you'll likely experience a deadlock because FFmpeg would not read the entire content of stream.ToArray() at once. It only reads what it needs to produce the next output data frame.

So, you need to run at least 2 threads on your program, one to write to FFmpeg and another to read from FFmpeg. Unfortunately, I'm not familiar with .net so I cannot help you with actual how to, but hopefully this answer points you a right direction.

Body:
I'm stream and successfully output converted video into mkv file.

var stream = ..incoming stream of type MemoryStream();
var process = new System.Diagnostics.Process();
process.StartInfo.Arguments = "-f mp4 -i pipe:0 -c:v libx264 -crf 20 -s 600:400 -f matroska myfile.mkv";
process.Start();
process.StandardInput.BaseStream.Write(stream.ToArray())
process.BeginOutputReadLine()
process.StandardInput.BaseStream.Close();
process.WaitForExit(1000);

My question is: how can I change the implementation (command and StandardOutput.BaseStream in order to export results into memory stream and not file (like it's in the above example).

Body:
What you were doing in the just deleted question was correct,

-f mp4 -i pipe:0 -c:v libx264 -crf 20 -s 600:400 -f matroska pipe:1

let you write the output to a pipe. But you'll likely experience a deadlock because FFmpeg would not read the entire content of stream.ToArray() at once. It only reads what it needs to produce the next output data frame.

So, you need to run at least 2 threads on your program, one to write to FFmpeg and another to read from FFmpeg. Unfortunately, I'm not familiar with .net so I cannot help you with actual how to, but hopefully this answer points you a right direction.


问:
How to solve local variable error with forloop in django?
Info: I want to get data from context. The context data is coming from for loop function.

Problem: I am getting this UnboundLocalError local variable 'context' referenced before assignment

```<code>def CurrentMatch(request, match_id):
    match = Match.objects.get(id=match_id)
    match_additional = MatchAdditional.objects.get(match=match)
    innings = match_additional.current_innings

    recent = Score.objects.filter(match=match).filter(innings=innings).order_by('over_number')[::-1][:1]

    for score in recent:
        context = {
            "ball_number": score.ball_number,
            "over_number": score.over_number,
        }

    return HttpResponse(json.dumps(context))
</code>```

答:
it happened because recent queryset is emtpy. use this snippet:

def CurrentMatch(request, match_id):
    match = Match.objects.get(id=match_id)
    match_additional = MatchAdditional.objects.get(match=match)
    innings = match_additional.current_innings

    recent = Score.objects.filter(match=match).filter(innings=innings).order_by('over_number')[::-1][:1]
    if len(recent) > 0:
        for score in recent:
            context = {
                "ball_number": score.ball_number,
                "over_number": score.over_number,
            }
        return HttpResponse(json.dumps(context))
    else:
        return HttpResponse(json.dumps({}))
```

with this part of code len(recent) you can check whether the queryset has objects or not.

Body:
Info: I want to get data from context. The context data is coming from for loop function.

Problem: I am getting this UnboundLocalError local variable 'context' referenced before assignment

def CurrentMatch(request, match_id):
    match = Match.objects.get(id=match_id)
    match_additional = MatchAdditional.objects.get(match=match)
    innings = match_additional.current_innings

    recent = Score.objects.filter(match=match).filter(innings=innings).order_by('over_number')[::-1][:1]

    for score in recent:
        context = {
            "ball_number": score.ball_number,
            "over_number": score.over_number,
        }

    return HttpResponse(json.dumps(context))

Body:
it happened because recent queryset is emtpy. use this snippet:

def CurrentMatch(request, match_id):
    match = Match.objects.get(id=match_id)
    match_additional = MatchAdditional.objects.get(match=match)
    innings = match_additional.current_innings

    recent = Score.objects.filter(match=match).filter(innings=innings).order_by('over_number')[::-1][:1]
    if len(recent) > 0:
        for score in recent:
            context = {
                "ball_number": score.ball_number,
                "over_number": score.over_number,
            }
        return HttpResponse(json.dumps(context))
    else:
        return HttpResponse(json.dumps({}))

with this part of code len(recent) you can check whether the queryset has objects or not.


问:
LightFace modal plug-in and width & height issue
i am working with LightFace and it is working fine. i am fetching data from server side and assign data into LightFace  dialog but the problem is dialog's height and width is not getting bigger according to the content size. so please guide me what i need to rectify in the code. i have given little part of my code. i need that the dialog should grow & shrink according to the content size. please guide me with little code. thanks</p>

```<code> var modal = "";
    var sHtml = "";

    jQuery.noConflict();
    jQuery(document).ready(function () {
        jQuery("#btnFeedback1").click(function () {
            var modal = new LightFace({
                draggable: true,
                height: 200,
                width: 300,
                title: 'My Profile',
                content: '<div class="BusyStyles"><div>',
                buttons: [
                { title: 'OK', event: function () {
                    if (Validate()) {
                        if (Save()) {
                            this.close();
                        }
                    }
                }
                },
                { title: 'Close', event: function () { this.close(); } }
            ]
            }).open();

            jQuery.ajax({
                type: "POST",
                url: "Dialog_LightFace.aspx/GetHtml",
                data: {},
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data) {
                    sHtml = data.d;
                    modal.load(jQuery(sHtml).find('#frm').html())
                    //modal.load('<div css="BusyStyles"><img src="images/fbloader.gif" border="0" /><div>');
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    alert(textStatus);
                }

            });

            return false;
        });
    });
</code>```

答:
If you could, please try to make a JSFiddle with some sample code. It's easier for us to debug.

I think the problem is that you already open the dialogbox before you load in any content. Therefore, the dialogbox gets set on a width and height, before the content is determined.

Try this:

Remove .open(); after making the var modal instance

Put this in jQuery.ajax.success:

```<code>success: function (data) {
  sHtml = data.d;
  modal.load(jQuery(sHtml).find('#frm').html()).open();
}
</code>```

If this is not helping, try to set width and height to 'auto' and see what happens.

Edit

Setting width and height programmatically:

```<code>jQuery.ajax({
   type: "POST",
   url: "Dialog_LightFace.aspx/GetHtml",
   data: {},
   contentType: "application/json; charset=utf-8",
   dataType: "json",
   success: function (data) {
     var sHtml = data.d;

     // Get the element and dimensions
     var element = jQuery(sHtml).find('#frm');
     var width = element.width();
     var height = element.height();

     var modal = new LightFace({
       // all other options plus:
       width: width,
       height: height
     });
     modal.load(element.html()).open();
   },
   error: function (XMLHttpRequest, textStatus, errorThrown) {
     alert(textStatus);
   }
});
</code>```

This code might need a little tweaking, because I'm writing this directly, but this illustrates how it should be able to work.

Body:
i am working with LightFace and it is working fine. i am fetching data from server side and assign data into LightFace  dialog but the problem is dialog's height and width is not getting bigger according to the content size. so please guide me what i need to rectify in the code. i have given little part of my code. i need that the dialog should grow & shrink according to the content size. please guide me with little code. thanks

 var modal = "";
    var sHtml = "";

    jQuery.noConflict();
    jQuery(document).ready(function () {
        jQuery("#btnFeedback1").click(function () {
            var modal = new LightFace({
                draggable: true,
                height: 200,
                width: 300,
                title: 'My Profile',
                content: '

',
                buttons: [
                { title: 'OK', event: function () {
                    if (Validate()) {
                        if (Save()) {
                            this.close();
                        }
                    }
                }
                },
                { title: 'Close', event: function () { this.close(); } }
            ]
            }).open();

            jQuery.ajax({
                type: "POST",
                url: "Dialog_LightFace.aspx/GetHtml",
                data: {},
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data) {
                    sHtml = data.d;
                    modal.load(jQuery(sHtml).find('#frm').html())
                    //modal.load('

');
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    alert(textStatus);
                }

            });

            return false;
        });
    });

Body:
If you could, please try to make a JSFiddle with some sample code. It's easier for us to debug.

I think the problem is that you already open the dialogbox before you load in any content. Therefore, the dialogbox gets set on a width and height, before the content is determined.

Try this:

Remove .open(); after making the var modal instance

Put this in jQuery.ajax.success:

success: function (data) {
  sHtml = data.d;
  modal.load(jQuery(sHtml).find('#frm').html()).open();
}

If this is not helping, try to set width and height to 'auto' and see what happens.

Edit

Setting width and height programmatically:

jQuery.ajax({
   type: "POST",
   url: "Dialog_LightFace.aspx/GetHtml",
   data: {},
   contentType: "application/json; charset=utf-8",
   dataType: "json",
   success: function (data) {
     var sHtml = data.d;

     // Get the element and dimensions
     var element = jQuery(sHtml).find('#frm');
     var width = element.width();
     var height = element.height();

     var modal = new LightFace({
       // all other options plus:
       width: width,
       height: height
     });
     modal.load(element.html()).open();
   },
   error: function (XMLHttpRequest, textStatus, errorThrown) {
     alert(textStatus);
   }
});

This code might need a little tweaking, because I'm writing this directly, but this illustrates how it should be able to work.


问:
Creating an empty Asp.NET MVC project in Visual Studio 2022
I was trying to create an empty MVC project in VS 2022 but I couldn't find true project type. When I chose "Asp.NET Web Application (Model-View-Controller)", it wasn't empty. When I chose "Asp.NET Web Application", it wasn't a MVC project. Which project type should I  choose to create an empty MVC project?</p>

答:
In Visual Studio 2022 Installer, below the ".NET Framework 4.8 targeting pack", there is a component named ".NET Framework project and item templates" and by default, this component was not selected.
selected and installed it.</p>


问:
Gradle - no main manifest attribute
I'm building a JAR file with Gradle. When I try to run it I get the following error

no main manifest attribute, in RxJavaDemo.jar

I tried manipulating the manifest property but I think I'm forgetting to add the dependencies or something to it. What exactly am I doing wrong?

```<code>apply plugin: 'java'
apply plugin: 'application'

mainClassName = 'demo.MainDashboard'

dependencies {
    compile files ("H:/Processes/Development/libraries/hikari-cp/HikariCP-2.4.1.jar")
    compile files ("H:/Processes/Development/libraries/controls-fx/controlsfx.jar")
    compile files ("H:/Processes/Development/libraries/database_connections/sqlite-jdbc-3.8.6.jar")
    compile files ("H:/Processes/Development/libraries/guava/guava-18.0.jar")
    compile files ("H:/Processes/Development/libraries/rxjava/rxjava-1.0.12.jar")
    compile files ("H:/Processes/Development/libraries/rxjava-extras/rxjava-extras-0.5.15.jar")
    compile files ("H:/Processes/Development/libraries/rxjavafx/RxJavaFX-1.0.0-RC1-SNAPSHOT.jar")
    compile files ("H:/Processes/Development/libraries/rxjavaguava/rxjava-guava-1.0.3.jar")
    compile files ("H:/Processes/Development/libraries/rxjava-jdbc/rxjava-jdbc-0.6.3.jar")
    compile files ("H:/Processes/Development/libraries/slf4j/slf4j-api-1.7.12.jar")
    compile files ("H:/Processes/Development/libraries/tom-commons/tom-commons.jar")
}

sourceSets {
    main.java.srcDir "src/main/java"
    main.resources.srcDir "src/main/resources"
}

jar {
    manifest {
    attributes(
        "Class-Path": configurations.compile.collect { it.getName() }.join(' '))
    }
    from configurations.compile.collect { entry -> zipTree(entry) }
}
</code>```

答:
To complement Denis Zavedeev answer, here are more ways for Kotlin DSL (build.gradle.kts):

tasks.jar {
    manifest.attributes["Main-Class"] = "com.example.MyMainClass"
}
```
<p>Another notation:</p>
<pre class="lang-kotlin prettyprint-override"><code>tasks.jar {
    manifest {
        attributes["Main-Class"] = "com.example.MyMainClass"
    }
}
</code>```

Side note: to create a runnable fat JAR (also called uber JAR), see this post.

Title: Gradle - no main manifest attribute

Body:
I'm building a JAR file with Gradle. When I try to run it I get the following error

no main manifest attribute, in RxJavaDemo.jar

I tried manipulating the manifest property but I think I'm forgetting to add the dependencies or something to it. What exactly am I doing wrong?

apply plugin: 'java'
apply plugin: 'application'

mainClassName = 'demo.MainDashboard'

dependencies {
    compile files ("H:/Processes/Development/libraries/hikari-cp/HikariCP-2.4.1.jar")
    compile files ("H:/Processes/Development/libraries/controls-fx/controlsfx.jar")
    compile files ("H:/Processes/Development/libraries/database_connections/sqlite-jdbc-3.8.6.jar")
    compile files ("H:/Processes/Development/libraries/guava/guava-18.0.jar")
    compile files ("H:/Processes/Development/libraries/rxjava/rxjava-1.0.12.jar")
    compile files ("H:/Processes/Development/libraries/rxjava-extras/rxjava-extras-0.5.15.jar")
    compile files ("H:/Processes/Development/libraries/rxjavafx/RxJavaFX-1.0.0-RC1-SNAPSHOT.jar")
    compile files ("H:/Processes/Development/libraries/rxjavaguava/rxjava-guava-1.0.3.jar")
    compile files ("H:/Processes/Development/libraries/rxjava-jdbc/rxjava-jdbc-0.6.3.jar")
    compile files ("H:/Processes/Development/libraries/slf4j/slf4j-api-1.7.12.jar")
    compile files ("H:/Processes/Development/libraries/tom-commons/tom-commons.jar")
}

sourceSets {
    main.java.srcDir "src/main/java"
    main.resources.srcDir "src/main/resources"
}

jar {
    manifest {
    attributes(
        "Class-Path": configurations.compile.collect { it.getName() }.join(' '))
    }
    from configurations.compile.collect { entry -> zipTree(entry) }
}

Body:
To complement Denis Zavedeev answer, here are more ways for Kotlin DSL (build.gradle.kts):

tasks.jar {
    manifest.attributes["Main-Class"] = "com.example.MyMainClass"
}

Another notation:

tasks.jar {
    manifest {
        attributes["Main-Class"] = "com.example.MyMainClass"
    }
}

Side note: to create a runnable fat JAR (also called uber JAR), see this post.


问:
Can't find Oracle Database Driver in Eclipse JAVA Program
I am trying to connect to an oracle database in eclipse. I have ojdbc14.jar in a lib folder in the same project and i added it to the build path of my project, so it also resides in the Referenced Libraries directory, but yet i still get an output to the console of "Could not find the database driver"

Myself and another student employee have been trying to get this figured out for the past day and a half, and no one else in our department is experienced in Java and JSP so i thought StackOverflow would be our best bet =)

```<code>try {
            // Load the JDBC driver
            String driverName = "oracle.jdbc.driver.OracleDriver";
            System.out.println("Attempting to load the driver...");
            Class.forName(driverName);
            System.out.print("Loaded the driver");

            // Create a connection to the database
            String serverName = " ;) ";
            String portNumber = " ;) ";
            String sid = " ;) ";
            String url = "jdbc:oracle:thin:@" + serverName + ":"
                    + portNumber + ":" + sid;
            String username = "kenne13";
            String password = "**********";
            connection = DriverManager.getConnection(url, username, password);
            if (connection != null) {
                return true;
            }

        } catch (ClassNotFoundException e) {
            // Could not find the database driver
            System.out.println("Could not find the database driver");
            connected = false;
        } catch (SQLException e) {
            // Could not connect to the database
            System.out.println("Could not connect to the database");
            connected = false;
        }
</code>```

Here is the output in the console:

```<code>    Aug 18, 2011 10:07:50 AM org.apache.catalina.startup.Catalina start
    INFO: Server startup in 382 ms
    Attempting to load the driver...
    Could not find the database driver
</code>```

Here is a screen capture of the code, the error, and my project directories.

答: I'm quite sure now that the class name of the driver is oracle.jdbc.OracleDriver and not oracle.jdbc.driver.OracleDriver.

Body:
I am trying to connect to an oracle database in eclipse. I have ojdbc14.jar in a lib folder in the same project and i added it to the build path of my project, so it also resides in the Referenced Libraries directory, but yet i still get an output to the console of "Could not find the database driver"

Myself and another student employee have been trying to get this figured out for the past day and a half, and no one else in our department is experienced in Java and JSP so i thought StackOverflow would be our best bet =)

try {
            // Load the JDBC driver
            String driverName = "oracle.jdbc.driver.OracleDriver";
            System.out.println("Attempting to load the driver...");
            Class.forName(driverName);
            System.out.print("Loaded the driver");

            // Create a connection to the database
            String serverName = " ;) ";
            String portNumber = " ;) ";
            String sid = " ;) ";
            String url = "jdbc:oracle:thin:@" + serverName + ":"
                    + portNumber + ":" + sid;
            String username = "kenne13";
            String password = "**********";
            connection = DriverManager.getConnection(url, username, password);
            if (connection != null) {
                return true;
            }

        } catch (ClassNotFoundException e) {
            // Could not find the database driver
            System.out.println("Could not find the database driver");
            connected = false;
        } catch (SQLException e) {
            // Could not connect to the database
            System.out.println("Could not connect to the database");
            connected = false;
        }

Here is the output in the console:

    Aug 18, 2011 10:07:50 AM org.apache.catalina.startup.Catalina start
    INFO: Server startup in 382 ms
    Attempting to load the driver...
    Could not find the database driver

Here is a screen capture of the code, the error, and my project directories.


问:
Android Studio Mediaplayer
I am a completely begginer guy in Android Studio and mobile apps in general. I used to create websites on Wordpress and i don't have so much experience on coding. Recently i started experimenting with mobile apps and mostly Android Studio. I bought a template for a Logo Quiz game and i managed to make it run without errors and publish it in Play Store as my first game. The player can see a part of the logo and guess the brand name using the given letters

But i would like to use the same template with new graphics and create a music quiz.

Instead of the logo guess game, the player will be able to listen a part of a song and guess the song's title.

The current project is getting the file names from a database stored in assets/databases folder.

So i managed to add start, pause and stop buttons in my activity_play.xml and succesfully created a mediaplayer in activityPlay.java file like:

```<code>public void music(View view) {
        switch (view.getId()){
            case R.id.button:
                // Check if mediaPlayer is null. If true, we'll instantiate the MediaPlayer object
                if(mediaPlayer == null){
                    mediaPlayer = MediaPlayer.create(this, R.raw.music);
                }
                // Then, register OnCompletionListener that calls a user supplied callback method onCompletion() when
                // looping mode was set to false to indicate playback is completed.
                mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                    @Override
                    public void onCompletion(MediaPlayer mediaPlayer) {
                        // Here, call a method to release the MediaPlayer object and to set it to null.
                        stopMusic();
                    }
                });
                // Next, call start() method on mediaPlayer to start playing the music.
                mediaPlayer.start();
                break;
            case R.id.button2:
                if(mediaPlayer != null) {
                    // Here, call pause() method on mediaPlayer to pause the music.
                    mediaPlayer.pause();
                }
                break;
            case R.id.button3:
                if(mediaPlayer != null){
                    // Here, call stop() method on mediaPlayer to stop the music.
                    mediaPlayer.stop();
                    // Call stopMusic() method
                    stopMusic();
                }
                break;
        }
    }

    private void stopMusic() {
        mediaPlayer.release();
        mediaPlayer = null;
    }

    // Call stopMusic() in onStop() overridden method as well.
    @Override
    protected void onStop() {
        super.onStop();
        stopMusic();
    }
</code>```

The above code can succesfully play the music.mp3 file located in raw folder. The app i bought is using the following code to load the images and display them for each level:

```<code>        String image_a = listDataBase.get(1);
        String image_q = listDataBase.get(2);

        if (isTrue == 1) {
            String imgPath;
            if (numImage == 0) {
                imgPath = "file:///android_asset/logos/" + image_a;
            } else {
                imgPath = "file:///android_asset/logos/" + image_q;
            }
            Picasso.get().load(imgPath).into(imageView);
            linearLayoutNullClick.setVisibility(View.VISIBLE);
            recyclerViewKeys.setVisibility(View.GONE);
            trueLogo = 2;
        } else {
            String imgPath = "file:///android_asset/logos/" + image_q;
            Picasso.get().load(imgPath).into(imageView);
            recyclerViewKeys.setVisibility(View.VISIBLE);
            recyclerViewLogoKeys.setVisibility(View.VISIBLE);
        }
</code>```

So is it possible to use the same code and load the imgPath into mediaPlayer = MediaPlayer.create(this, R.raw.music);

I tried loading imgPath directly to mediaplayer like this but didn't work:

```<code>mediaPlayer = MediaPlayer.create(this, imgPath);
</code>```

Then i tried:

```<code>private String audioPath;
audioPath = imgPath;
mediaPlayer = MediaPlayer.create(this, audioPath);
</code>```

but also didn't work.
Tried many more methods i found on the web, but always i am missing something

As i said before i am a newbie in coding and programming so the solution probably will be very easy .
Anyone can help please?

答:
If you change the value in the database of pic_1.png with audio_1.mp3
then path will start like:

```<code>"file:///android_asset/logos/" + YOUR_AUDIO;
</code>```

So are you sure audio exists in this path?

Title: Android Studio Mediaplayer

Body:
I am a completely begginer guy in Android Studio and mobile apps in general. I used to create websites on Wordpress and i don't have so much experience on coding. Recently i started experimenting with mobile apps and mostly Android Studio. I bought a template for a Logo Quiz game and i managed to make it run without errors and publish it in Play Store as my first game. The player can see a part of the logo and guess the brand name using the given letters

But i would like to use the same template with new graphics and create a music quiz.

Instead of the logo guess game, the player will be able to listen a part of a song and guess the song's title.

The current project is getting the file names from a database stored in assets/databases folder.

So i managed to add start, pause and stop buttons in my activity_play.xml and succesfully created a mediaplayer in activityPlay.java file like:

public void music(View view) {
        switch (view.getId()){
            case R.id.button:
                // Check if mediaPlayer is null. If true, we'll instantiate the MediaPlayer object
                if(mediaPlayer == null){
                    mediaPlayer = MediaPlayer.create(this, R.raw.music);
                }
                // Then, register OnCompletionListener that calls a user supplied callback method onCompletion() when
                // looping mode was set to false to indicate playback is completed.
                mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                    @Override
                    public void onCompletion(MediaPlayer mediaPlayer) {
                        // Here, call a method to release the MediaPlayer object and to set it to null.
                        stopMusic();
                    }
                });
                // Next, call start() method on mediaPlayer to start playing the music.
                mediaPlayer.start();
                break;
            case R.id.button2:
                if(mediaPlayer != null) {
                    // Here, call pause() method on mediaPlayer to pause the music.
                    mediaPlayer.pause();
                }
                break;
            case R.id.button3:
                if(mediaPlayer != null){
                    // Here, call stop() method on mediaPlayer to stop the music.
                    mediaPlayer.stop();
                    // Call stopMusic() method
                    stopMusic();
                }
                break;
        }
    }

    private void stopMusic() {
        mediaPlayer.release();
        mediaPlayer = null;
    }

    // Call stopMusic() in onStop() overridden method as well.
    @Override
    protected void onStop() {
        super.onStop();
        stopMusic();
    }

The above code can succesfully play the music.mp3 file located in raw folder. The app i bought is using the following code to load the images and display them for each level:

        String image_a = listDataBase.get(1);
        String image_q = listDataBase.get(2);

        if (isTrue == 1) {
            String imgPath;
            if (numImage == 0) {
                imgPath = "file:///android_asset/logos/" + image_a;
            } else {
                imgPath = "file:///android_asset/logos/" + image_q;
            }
            Picasso.get().load(imgPath).into(imageView);
            linearLayoutNullClick.setVisibility(View.VISIBLE);
            recyclerViewKeys.setVisibility(View.GONE);
            trueLogo = 2;
        } else {
            String imgPath = "file:///android_asset/logos/" + image_q;
            Picasso.get().load(imgPath).into(imageView);
            recyclerViewKeys.setVisibility(View.VISIBLE);
            recyclerViewLogoKeys.setVisibility(View.VISIBLE);
        }

So is it possible to use the same code and load the imgPath into mediaPlayer = MediaPlayer.create(this, R.raw.music);

I tried loading imgPath directly to mediaplayer like this but didn't work:

mediaPlayer = MediaPlayer.create(this, imgPath);

Then i tried:

private String audioPath;
audioPath = imgPath;
mediaPlayer = MediaPlayer.create(this, audioPath);

but also didn't work.
Tried many more methods i found on the web, but always i am missing something

As i said before i am a newbie in coding and programming so the solution probably will be very easy .
Anyone can help please?

Body:
If you change the value in the database of pic_1.png with audio_1.mp3
then path will start like:

"file:///android_asset/logos/" + YOUR_AUDIO;

So are you sure audio exists in this path?


问:
How to make my selenium script run forever on heroku
I have created an selenium bot that posts every 20 minutes on Instagram
I deployed my project to heroku and everything but i don't know how to make it run forever
I tried heroku run python mycode.py in the command promt but the program would stop working if i close command prompt

答:
heroku run is for ad hoc interactive stuff.

For a long-running background process you should define a worker process in your Procfile:

```<code>worker: python mycode.py
</code>```

Commit that change and redeploy. Then scale up a dyno to run it:

```<code>heroku ps:scale worker=1
</code>```

This will either consume free dyno hours or, if you are using paid dynos, incur costs.

Body:
heroku run is for ad hoc interactive stuff.

For a long-running background process you should define a worker process in your Procfile:

worker: python mycode.py

Commit that change and redeploy. Then scale up a dyno to run it:

heroku ps:scale worker=1

This will either consume free dyno hours or, if you are using paid dynos, incur costs.


问:
Windows : How to hide a folder with a specific path in Python
Basically, What I am trying to do is, whenever the assistant is given command that 'hide all the files', it should all the files if a file or folder is open. But, the problem is that if no folder is open, it will hide the current working folder. I want it to search if a folder is open, if not then ask which folder to hide.
Please help me to figure this out.
Thank You in advance.

The code I am currently using is as following:-

```<code>elif "hide all files" in query or "hide this folder" in query:
        try:
            os.system("attrib +h /s /d")
            speak("Sir, all the files in this folder are now hidden")
        except:
            speak("No directory found.")
</code>```

答:
Here is the solution for this:-</p>
```<code>import os
import plyer
from pathlib import Path
from win32con import FILE_ATTRIBUTE_HIDDEN
from win32api import SetFileAttributes

current_dir = Path().resolve()

def takefolder():  #Takes Folder Input
    while True:
        selected_folder = str(plyer.filechooser.choose_dir())
        selected_folder = selected_folder.replace("[", "")
        selected_folder = selected_folder.replace("]", "")
        selected_folder = selected_folder.replace("'", "")
        selected_folder = " ".join(selected_folder.split())
        if selected_folder=="":
            print("Please select a folder.")
        else:
            break
    return selected_folder

file_path = "Folder_path"
folder_path = os.path.join(current_dir, file_path)

if os.path.isdir(folder_path):
    final_path = folder_path
else:
    print("Please select the folder you want to hide!")
    final_path = takefolder()

try:
    SetFileAttributes(final_path, FILE_ATTRIBUTE_HIDDEN)
    print("The folder is now hidden!")
except:
    print("No directory found.")
</code>```

Body:
Basically, What I am trying to do is, whenever the assistant is given command that 'hide all the files', it should all the files if a file or folder is open. But, the problem is that if no folder is open, it will hide the current working folder. I want it to search if a folder is open, if not then ask which folder to hide.
Please help me to figure this out.
Thank You in advance.

The code I am currently using is as following:-

elif "hide all files" in query or "hide this folder" in query:
        try:
            os.system("attrib +h /s /d")
            speak("Sir, all the files in this folder are now hidden")
        except:
            speak("No directory found.")

Body:
Here is the solution for this:-

import os
import plyer
from pathlib import Path
from win32con import FILE_ATTRIBUTE_HIDDEN
from win32api import SetFileAttributes

current_dir = Path().resolve()

def takefolder():  #Takes Folder Input
    while True:
        selected_folder = str(plyer.filechooser.choose_dir())
        selected_folder = selected_folder.replace("[", "")
        selected_folder = selected_folder.replace("]", "")
        selected_folder = selected_folder.replace("'", "")
        selected_folder = " ".join(selected_folder.split())
        if selected_folder=="":
            print("Please select a folder.")
        else:
            break
    return selected_folder

file_path = "Folder_path"
folder_path = os.path.join(current_dir, file_path)

if os.path.isdir(folder_path):
    final_path = folder_path
else:
    print("Please select the folder you want to hide!")
    final_path = takefolder()

try:
    SetFileAttributes(final_path, FILE_ATTRIBUTE_HIDDEN)
    print("The folder is now hidden!")
except:
    print("No directory found.")


问:
How to check if Kafka instance is up
I'm working on a Spring Boot project where I consume messages from Kafka topics using the spring-kafka dependency.

This is my listener and it works fine:

```<code>@KafkaListener(topics = "${mytopic.name}",  containerFactory = "kafkaEventListenerObjectContainerFactory")
public void listenTopic(ConsumerRecord<String, KafkaEvent> cr,
                       @Payload KafkaEvent kafkaEvent) throws JsonProcessingException {

// my code here...

}
</code>```

My issue is that I want to check if the Kafka instance is up. I want to develop a REST API that connects to my Kafka instance, if the connection is not OK, I want to send an alert via email.

Is my idea right, or is there another clean way to check if Kafka is up?

Do you have any good idea to achieve this? I plan to execute my check every 15 minutes to get the status.

答:
There is the out of the box solution from Spring.

Building a RESTful Web Service with Spring Boot Actuator

Add the dependency for spring-boot-starter-actuator add some additional configs to your application.properties or yaml file e.g. management.server.port=8443 or you can ommit and it uses your web server port. in addition you might want to add additional management.endpoint.xxx configs (Enabling Production-ready Features).
Add a StreamsHealthIndicator class to your project and then you can call the actuator from outside e.g. http://localhost:8443/actuator/health and will include the result from your StreamsHealthIndicator. Depending on the setting management.endpoint.health.show-details=ALWAYS it will also include all the details from the HealthIndicator like threads, tasks, etc.

An example for a StreamsHealthIndicator can be found here example

Title: How to check if Kafka instance is up

Body:
I'm working on a Spring Boot project where I consume messages from Kafka topics using the spring-kafka dependency.

This is my listener and it works fine:

@KafkaListener(topics = "${mytopic.name}",  containerFactory = "kafkaEventListenerObjectContainerFactory")
public void listenTopic(ConsumerRecord<String, KafkaEvent> cr,
                       @Payload KafkaEvent kafkaEvent) throws JsonProcessingException {

// my code here...

}

My issue is that I want to check if the Kafka instance is up. I want to develop a REST API that connects to my Kafka instance, if the connection is not OK, I want to send an alert via email.

Is my idea right, or is there another clean way to check if Kafka is up?

Do you have any good idea to achieve this? I plan to execute my check every 15 minutes to get the status.


问:
when subsetting with and without .loc[ ] in python?
I was doing a Python exercises and I got the wrong answer (in red). I'm a bit confused about subsetting with and without loc[ ]. Please enlighten me. Thank you.

答:
The df.loc[:, ['alignment', 'character']] itself is a dataframe. What you're doing wrong is passing it inside df.

I suggest you to look around at the related pandas documentation.


问:
Google API Client returning 404 not fund
I am trying to get the best searches from google, using keyword, and GoogleAPI, but It is always returning "System.Net.WebException: 'The remote server returned an error: (404) Not Found.'"

Am I doing anything wrong, or is it that GoogleAPI is outdated? Last time I checked and downloaded the .dll file was from 2010...

code:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.IO;
using System.Security.Cryptography;
using System.Text.RegularExpressions;
using System.Threading;
using System.Diagnostics;
using System.Collections;
using Microsoft.Win32;
using System.Web;
using System.Net.Mail;
using System.Net.Mime;
using System.ComponentModel;
using System.Net;
using System.Windows;
using Google.Apis.Services;
using Google.Apis.CustomSearchAPI.v1;

//Ignore most using statements, It was imported from my previous code.

namespace TYZDsag
{

    internal class Program
    {
        static void Main(string[] args)
        {
            var client = new Google.API.Search.GwebSearchClient("https://www.google.com/");
            var results = client.Search("uhuhuh", 12);
            foreach (var webResult in results)
            {
                Console.WriteLine("{0}, {1}, {2}", webResult.Title, webResult.Url, webResult.Content);
                //listBox1.Items.Add(webResult.ToString());
            }

        }
    }
}

</code>```

答:
That's not  how you initialize a service object using an api key.

```<code>using System;
using System.Threading.Tasks;
using Google.Apis.CustomSearchAPI.v1;
using Google.Apis.Services;

namespace customsearch
{
    class Program
    {
        static async Task Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            var service = new CustomSearchAPIService(new BaseClientService.Initializer()
            {
                ApiKey = "XXX",
                ApplicationName = "xyz",

            });

            var result = await service.Cse.List().ExecuteAsync();

        }
    }
}
</code>```

Method: cse.list

How to create an api key

Body:
I am trying to get the best searches from google, using keyword, and GoogleAPI, but It is always returning "System.Net.WebException: 'The remote server returned an error: (404) Not Found.'"

Am I doing anything wrong, or is it that GoogleAPI is outdated? Last time I checked and downloaded the .dll file was from 2010...

code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.IO;
using System.Security.Cryptography;
using System.Text.RegularExpressions;
using System.Threading;
using System.Diagnostics;
using System.Collections;
using Microsoft.Win32;
using System.Web;
using System.Net.Mail;
using System.Net.Mime;
using System.ComponentModel;
using System.Net;
using System.Windows;
using Google.Apis.Services;
using Google.Apis.CustomSearchAPI.v1;

//Ignore most using statements, It was imported from my previous code.

namespace TYZDsag
{

    internal class Program
    {
        static void Main(string[] args)
        {
            var client = new Google.API.Search.GwebSearchClient("https://www.google.com/");
            var results = client.Search("uhuhuh", 12);
            foreach (var webResult in results)
            {
                Console.WriteLine("{0}, {1}, {2}", webResult.Title, webResult.Url, webResult.Content);
                //listBox1.Items.Add(webResult.ToString());
            }

        }
    }
}

Body:
That's not  how you initialize a service object using an api key.

using System;
using System.Threading.Tasks;
using Google.Apis.CustomSearchAPI.v1;
using Google.Apis.Services;

namespace customsearch
{
    class Program
    {
        static async Task Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            var service = new CustomSearchAPIService(new BaseClientService.Initializer()
            {
                ApiKey = "XXX",
                ApplicationName = "xyz",

            });

            var result = await service.Cse.List().ExecuteAsync();

        }
    }
}

Method: cse.list

How to create an api key


问:
IE problems with Media Queries
OK, this script checks the media type using css media queries. The idea is that I create a div (pre-DOM) and a style element with media queries, and if the style is applied then the media query was true. This works in Firefox 5, but not in IE 9.

```<code>/** Detect Browser Media **/
if(!window.mediaQuery){
    window.mediaQuery = function(query){
    var boolean = 0;

    style = document.createElement('style');
    style.media = query;
    style.innerHTML = '#mediaQuery{width:5px;}';
    document.head.appendChild(style);

    div = document.createElement('div');
    div.id = 'mediaQuery';
    document.documentElement.appendChild(div);

    if(div.offsetWidth == 5){boolean = 1;}
    console.log(div.offsetWidth," ",boolean);

    return { match:boolean };
    }
}
</code>```

This returns "5 1" in FF 5 and in Chrome console, but it returns "919 0" in IE 9. What is IE doing here? How can I work around?

Here is an example of the function call:
mediaQuery('screen and (min-width: 480px)').match

After some testing I have found that the width matches 100% of the screen width.
Why isn't the media query working in IE, it works in FF and Chrome...
Maybe IE is just not processing the CSS before I test the width in javascript?

答:
I figured this out.

IE only applies css to elements in the body, in order to get it to use the css you have to place the div within a fake body (because the real body hasn't loaded yet). Here is the finished script:

```<code>/** Detect Browser Media **/
if(!window.mediaQuery){
    window.mediaQuery = function(query){
    var boolean = 0;

    var style = document.createElement('style');
    style.type="text/css";
    style.media = query;
    if(style.styleSheet){style.styleSheet.cssText='#mediaQuery{width:30px;}';}else{
        var MyCssText=document.createTextNode("#mediaQuery{width:30px;}");
        style.appendChild(MyCssText);
    }

    document.head.appendChild(style);

    bod = document.createElement('body');
    bod.id="fakeBody";
    div = document.createElement('div');
    div.id = 'mediaQuery';
    document.documentElement.appendChild(bod);
    bod.appendChild(div);

    if(div.offsetWidth == 30){boolean = 1;}
    console.log(div.offsetWidth," ",boolean);

    return { match:boolean };
    }
}
</code>```

Title: IE problems with Media Queries

Body:
OK, this script checks the media type using css media queries. The idea is that I create a div (pre-DOM) and a style element with media queries, and if the style is applied then the media query was true. This works in Firefox 5, but not in IE 9.

/** Detect Browser Media **/
if(!window.mediaQuery){
    window.mediaQuery = function(query){
    var boolean = 0;

    style = document.createElement('style');
    style.media = query;
    style.innerHTML = '#mediaQuery{width:5px;}';
    document.head.appendChild(style);

    div = document.createElement('div');
    div.id = 'mediaQuery';
    document.documentElement.appendChild(div);

    if(div.offsetWidth == 5){boolean = 1;}
    console.log(div.offsetWidth," ",boolean);

    return { match:boolean };
    }
}

This returns "5 1" in FF 5 and in Chrome console, but it returns "919 0" in IE 9. What is IE doing here? How can I work around?

Here is an example of the function call:
mediaQuery('screen and (min-width: 480px)').match

After some testing I have found that the width matches 100% of the screen width.
Why isn't the media query working in IE, it works in FF and Chrome...
Maybe IE is just not processing the CSS before I test the width in javascript?

Body:
I figured this out.

IE only applies css to elements in the body, in order to get it to use the css you have to place the div within a fake body (because the real body hasn't loaded yet). Here is the finished script:

/** Detect Browser Media **/
if(!window.mediaQuery){
    window.mediaQuery = function(query){
    var boolean = 0;

    var style = document.createElement('style');
    style.type="text/css";
    style.media = query;
    if(style.styleSheet){style.styleSheet.cssText='#mediaQuery{width:30px;}';}else{
        var MyCssText=document.createTextNode("#mediaQuery{width:30px;}");
        style.appendChild(MyCssText);
    }

    document.head.appendChild(style);

    bod = document.createElement('body');
    bod.id="fakeBody";
    div = document.createElement('div');
    div.id = 'mediaQuery';
    document.documentElement.appendChild(bod);
    bod.appendChild(div);

    if(div.offsetWidth == 30){boolean = 1;}
    console.log(div.offsetWidth," ",boolean);

    return { match:boolean };
    }
}


问:
java split with unknown result
for the following code,

why there is empty string in position 2,3,5,6,8?

then why "b", ":andf", "1" has no empty string behind?

```<code>    String[] splitStrs = "booo:and:fooo1o".split("o", -1);
    System.out.println(splitStrs.length);
    for (int i=0; i<splitStrs.length; i++) {
        System.out.println("\"" + splitStrs[i]+ "\"");
    }
</code>```

output is:

8

"b"

""

""

":and:f"

""

""

"1"

""

答:
The split method will find all occurances where is wanted character (in your example "o"), put a new (sub)string between current "o" and next "o", without the "o" character, in array, and continue for the whole string.

When you have, for an example "oo", it will be "" since there is nothing between those 2 "o" characters.

Let's take an example. You have a string "Oh, hello Anna! I havent seen you since 2010s!" and split this string on every place where is "a" character.

First, start from the first character, then find where is next letter "a", which is found on 14th index. Take part of the string from start to that place where is "a" and add it into an array. First element of an array will look like "Oh, hello Ann" ("A" and "a" are different characters). Then start from that "a" where I have found (14th index) and find next "a" , which is in 20th index in our example. Take part of the string from first and second "a" and copy it in an array. Then the procedure goes on until the end of the string.

Result will be:

```<code>"Oh, hello Ann"
"! I h"
"vent seen you since 2010s!"
</code>```

If we split our same string on every "n", by using same logic, we will get:

```<code>"Oh, hello A"
""
"a! I have"
"t see"
" you si"
"ce 2010s"
</code>```

Reason why I get an empty string on second part is because in "...Anna...", there is nothing between those 2 "n" characters

Some examples can be found on: https://www.geeksforgeeks.org/split-string-java-examples/

Title: java split with unknown result

Body:
for the following code,

why there is empty string in position 2,3,5,6,8?

then why "b", ":andf", "1" has no empty string behind?

    String[] splitStrs = "booo:and:fooo1o".split("o", -1);
    System.out.println(splitStrs.length);
    for (int i=0; i<splitStrs.length; i++) {
        System.out.println("\"" + splitStrs[i]+ "\"");
    }

output is:

8

"b"

""

""

":and:f"

""

""

"1"

""

Body:
The split method will find all occurances where is wanted character (in your example "o"), put a new (sub)string between current "o" and next "o", without the "o" character, in array, and continue for the whole string.

When you have, for an example "oo", it will be "" since there is nothing between those 2 "o" characters.

Let's take an example. You have a string "Oh, hello Anna! I havent seen you since 2010s!" and split this string on every place where is "a" character.

First, start from the first character, then find where is next letter "a", which is found on 14th index. Take part of the string from start to that place where is "a" and add it into an array. First element of an array will look like "Oh, hello Ann" ("A" and "a" are different characters). Then start from that "a" where I have found (14th index) and find next "a" , which is in 20th index in our example. Take part of the string from first and second "a" and copy it in an array. Then the procedure goes on until the end of the string.

Result will be:

"Oh, hello Ann"
"! I h"
"vent seen you since 2010s!"

If we split our same string on every "n", by using same logic, we will get:

"Oh, hello A"
""
"a! I have"
"t see"
" you si"
"ce 2010s"

Reason why I get an empty string on second part is because in "...Anna...", there is nothing between those 2 "n" characters

Some examples can be found on: https://www.geeksforgeeks.org/split-string-java-examples/


问:
Where should I keep data to continuously use in server?
Currently, I'm trying to build a dating app(server part).

I'm going to store each user's profile data like videos, photos, profile messages to AWS S3.

And I have user info including location(longitude, latitude) in my database server.

If you've ever used this kind of app, you might easily understand how it works.

First, whenever a user opens this app, the user gets to see the profile of other users one at a time based on the current location.

Second, the user gives like or dislike to the current profile and gets to the next profile.

So, in order to implement the first step, I'm going to search other users in a certain distance from the user's current location in the database, but here I'm only going to get unique user ID values from database. This only happens once when a user opens the app.

Now that I have other users' id values like [id1, id2, id3, id4...] I can load each user's profile data from AWS S3 with each unique id value one by one whenever the user needs to see the next profile.

Here my question comes. To build the recommendation logic like that, where should I keep the id values??

Thanks in advance.

答: Use a in memory cache like Redis/memcache (both provided by AWS). Also your cahce should get updated as and when data in AWS S3 profile updates because only then you will have latest data.</p>


问:
Focus language grammar
I need to extract some info from a list of mainframe scripts written in focus language.
I'm trying to write a java program for parsing source code. Due to the name of the language it is difficult to find any useful information on the internet. Maybe someone know if exist a grammar for this language on internet(for example for antlr4) or maybe an implemented lexer.
Thanks in advance for any response!</p>

答:
There is a curated list of ANTLR grammars here.  Unfortunately, there is no grammar for the focus product.

Not all authors make their grammars available at the above link, you might try searching github and other code repositories.

Title: Focus language grammar


问:
Azure Data Explorer Syslog virtual machine
sorry for the basic question but I am totally new to this technology and would like to ask some questions to all of you expert and amazing people.

I have a windows virtual machine that receives a lot of syslogs on port 3014. So far I have been using Elasticsearch, logstash and Grafana to collect those data and visualise them.

But I would like to take a different approach and move everything directly to azure portal, so I came across azure data explorer.

Can any one direct me a good documentation (because I couldn't find any) how to send directly those syslogs from my vm to data explorer to analyse them and visualise them?

Please if my request is not 100% clear, just ask for more details.

Thank you very much for your time and help

答:
The solution you need has two parts: 1. Listening on the syslog port (3014) and 2. pushing the data to Azure Data Explorer (Kusto)

You need a component that has the syslog listening capability and the output to Azure Data Explorer.

You can definitely continue to use Logstash and leverage the Logstash Azure Data Explorer plugin (https://learn.microsoft.com/en-us/azure/data-explorer/ingest-data-logstash) to send the data.
But you can also use a Telegraf agent with the Azure Data Explorer output plugin (https://techcommunity.microsoft.com/t5/azure-data-explorer-blog/new-azure-data-explorer-output-plugin-for-telegraf-enables-sql/ba-p/2829444) or FluentBit (https://azure.microsoft.com/en-us/updates/fluent-bit-connector-for-azure-storage-to-support-azure-data-explorer/)

You can also add another hop and leverage Azure Event Hub to aggregate the data. Most syslog listeners can send data to event hubs via the Kafka head it exposes. Then Azure Data Explorer can listen on the Event Hub.


问:
Switch from PHP to Java or .Net
I currently run a website on LAMP, I am currently in the process of refactoring my code from normal php to Zend framework with Doctrine. I am happy with setup but often find function not found errors on live site cause I have renamed function. Which is frustrating as most of time is wasted is patching these errors.
So I have decided to switch from php to java as the code gets compiled, so just error will not go to live site. With java netbeans will work better.

But as I have not been in touch to j2ee for many years. What is the best replacement for my above setup in java?

Option 1. Jsf 2 with Hibernate

Option 2. Seam

Option 3. Spring

Option 4. Struts with Hibernate

My server has 24 gig ram and 2 core i7 processor and ssd drive on raid 0

Will my server handle the same amount of visitors if java was used without any performance issues?

I like the way I can update my site without losing live sessions(logged-in users). Can I do the same in Java? from my experience each update to site will redeploy the App which resets all the Active Sessions.

I love to consider .Net but from what I have read on most forums, no one recommends it?

Kind regards

Zerone

答:
Java has a large variety of solutions to the same problem.  Currently, the mainline Java solution to presenting items on the web is Java Server Faces.

Older (which doesn't always mean worse) solutions include Struts, Apache Tapestry, (parts of) Spring, etc.  These solutions benefit from maturity, having an established following, etc.  Basically they are good solutions because people already know the points where they fail, and already know how to work around them.  The new solutions attempt to remove these pain points, and thus suffer from new pain points.  Think of it as not noticing your headache until after you fix your broken arm.

Java will perform much better because the code that delivers the web pages is already in memory, so it avoids a number of items that take time (process spawning, disk access, webserver to language engine communications, etc).  There are other PHP solutions which also attempt to solve similar problems using similar techniques; however, PHP has a different coding background and style.  For example, Java doesn't need to discard any state between web page requests, something that PHP does (and often uses a number of libraries and workarounds to mitigate).

My recommendation is to use Java, but realize that a direct port will incur a lot of unnecessary expense.  Choose a web facing toolkit (JavaServerFaces is the newest and part of the Java EE standard), and start off by porting the static portions of the HTML web pages.  Organize your requests by scope (how long the side effect of the request should persist), and use the Servlet standard to store the artifacts generated by the request in the appropriate application, session, request, etc scope.

On the database side of things, there are many standards and solutions to pick from too.  Personally, as you don't have a lot of legacy concerns, I would go with JPA.  While it is not really a 100% complete solution, it will push you to use an interface which can be replaced by better implementations over time, without the need to recode your application.  By stating it isn't 100% complete, I mean that you need to select a JPA provider as the default provider probably won't meet your real-world production needs.  That said, the default provider should sustain development oriented work, and JPA's standards should protect you from unexpected differences when you run the code against different environments.

Whether you wish to fully restructure you code into a Java EE multi-tier architecture, of if you just want to embed a large Servlet (server faces is a type of servlet solution) that does everything is more of a function of how much you wish to architect your code.  It is not a porting problem.  That said, the biggest benefits of a typical Java solution over a typical PHP solution is that the Java architecture is designed to work faster and provide more features out-of-the-box.  If you intend to do a port with no rearchitecting, you might be better off just finding out the bottlenecks in the PHP code and fixing them.

Title: Switch from PHP to Java or .Net


问:
stopping a Qthread with a QTimer
I am starting a Qthread in my GUI to perform an optimization function. I want to include a stopping function that can interrupt the Qthread, and end the optimization function immediately.

I read that using Qthread.terminate() is not recommended; Using a stopping flag is not possible because the nature of the function is not a loop.

I thought about using a QTimer in the QThread (a watchdog timer) that periodically checks a stopping flag, and if it is triggered, just end the optimization function, but I can not really imagine how such an idea can be written.

any Ideas?

```<code>class Worker(QObject):
    finished = pyqtSignal()
    def run(self):
        # implement a QTimer here that will somehow interrupt the minimize function
        # minimize is an arbitrary function that takes too long to run, and uses child processes to do so
        result = minimize(something)

FROM_Optimization_Process,_ = loadUiType(os.path.join(os.path.dirname(__file__),"ui_files/Optimization_process_window.ui"))

class Optimization_process_window(QDialog, FROM_Optimization_Process):
    def __init__(self, parent=None):
        # first UI
        super(Optimization_process_window, self).__init__(parent)
        self.setupUi(self)

    def start_solving_thread(self):
        self.thread = QThread()
        self.thread.daemon = True
        self.worker = Worker()
        self.worker.moveToThread(self.thread)
        self.thread.started.connect(self.worker.run)
        self.worker.finished.connect(self.thread.quit)
        self.worker.finished.connect(self.worker.deleteLater)
        self.thread.finished.connect(self.thread.deleteLater)
        self.thread.start()

    def stop_solving(self):
        # implement an interrupt function here
        self.thread.quit()
        self.thread.wait()

</code>```

答:
You misunderstand how timers work. They cannot "interrupt" a code running in a thread in any way. Timers only can work when event loop in the thread is idle and ready to process the timer events and signal. And that event loop is blocked if some code is running in that thread.

In other words, QTimer in your thread will not work unless you unblock the event loop time to time to process the timer signal. But from what I see, you probably do some intensive work in your minimize(something) function. And it blocks the event loop completely.

If you want to be able to implement worker/thread interruption, the only way is to implement interruptions into your minimize(something) function by periodical polling. You need to split the work in this function into certain blocks and after each block is done, you check if the worker/thread is supposed to be stopped.

QThread has a helper functions for this. It is QThread.requestInterruption() and QThread.isInterruptionRequested(), these functions are thread safe. And you can access the thread instance from your worker by calling QObject.thread(). But it is you responsibility to check QThread.isInterruptionRequested() frequently enough in the code after each block of work is done.

Of course you can develop your own methods for aborting the work, possibly guarded by mutexes... Nevertheless you must check it periodically. There is no way around it.

```<code>def minimize(self, something): # a method of Worker class
  for i in range(1000000):
    if i % 1000 == 0: # this is just to represent a block of work
      if self.thread().isInterruptionRequested():
        return
    self.minimize_next_part(something)
  self.finished.emit()
</code>```

The stopper function should then be:

```<code>def stop_solving(self):
  self.thread.requestInterruption() # this will unblock the event loop in just a moment
  self.thread.quit() # this ends event loop and will emit thread's finished signal
  # self.thread.wait() # you do not need this probbaly, it depends...
</code>```

(I am sorry for potential syntax errors, I am C++ programmer, not Pythonista)

I know this looks stupid, but really there is no other miraculous mechanism for interrupting threads. You simply need periodical polling.

PS: instead of

```<code>self.worker.finished.connect(self.worker.deleteLater)
</code>```

you should use

```<code>self.thread.finished.connect(self.worker.deleteLater)
</code>```

otherwise the worker will not be deleted if the thread gets interrupted because then Worker.finished signal gets never called.

Title: stopping a Qthread with a QTimer

Body:
I am starting a Qthread in my GUI to perform an optimization function. I want to include a stopping function that can interrupt the Qthread, and end the optimization function immediately.

I read that using Qthread.terminate() is not recommended; Using a stopping flag is not possible because the nature of the function is not a loop.

I thought about using a QTimer in the QThread (a watchdog timer) that periodically checks a stopping flag, and if it is triggered, just end the optimization function, but I can not really imagine how such an idea can be written.

any Ideas?

class Worker(QObject):
    finished = pyqtSignal()
    def run(self):
        # implement a QTimer here that will somehow interrupt the minimize function
        # minimize is an arbitrary function that takes too long to run, and uses child processes to do so
        result = minimize(something)

FROM_Optimization_Process,_ = loadUiType(os.path.join(os.path.dirname(__file__),"ui_files/Optimization_process_window.ui"))

class Optimization_process_window(QDialog, FROM_Optimization_Process):
    def __init__(self, parent=None):
        # first UI
        super(Optimization_process_window, self).__init__(parent)
        self.setupUi(self)

    def start_solving_thread(self):
        self.thread = QThread()
        self.thread.daemon = True
        self.worker = Worker()
        self.worker.moveToThread(self.thread)
        self.thread.started.connect(self.worker.run)
        self.worker.finished.connect(self.thread.quit)
        self.worker.finished.connect(self.worker.deleteLater)
        self.thread.finished.connect(self.thread.deleteLater)
        self.thread.start()

    def stop_solving(self):
        # implement an interrupt function here
        self.thread.quit()
        self.thread.wait()

Body:
You misunderstand how timers work. They cannot "interrupt" a code running in a thread in any way. Timers only can work when event loop in the thread is idle and ready to process the timer events and signal. And that event loop is blocked if some code is running in that thread.

In other words, QTimer in your thread will not work unless you unblock the event loop time to time to process the timer signal. But from what I see, you probably do some intensive work in your minimize(something) function. And it blocks the event loop completely.

If you want to be able to implement worker/thread interruption, the only way is to implement interruptions into your minimize(something) function by periodical polling. You need to split the work in this function into certain blocks and after each block is done, you check if the worker/thread is supposed to be stopped.

QThread has a helper functions for this. It is QThread.requestInterruption() and QThread.isInterruptionRequested(), these functions are thread safe. And you can access the thread instance from your worker by calling QObject.thread(). But it is you responsibility to check QThread.isInterruptionRequested() frequently enough in the code after each block of work is done.

Of course you can develop your own methods for aborting the work, possibly guarded by mutexes... Nevertheless you must check it periodically. There is no way around it.

def minimize(self, something): # a method of Worker class
  for i in range(1000000):
    if i % 1000 == 0: # this is just to represent a block of work
      if self.thread().isInterruptionRequested():
        return
    self.minimize_next_part(something)
  self.finished.emit()

The stopper function should then be:

def stop_solving(self):
  self.thread.requestInterruption() # this will unblock the event loop in just a moment
  self.thread.quit() # this ends event loop and will emit thread's finished signal
  # self.thread.wait() # you do not need this probbaly, it depends...

(I am sorry for potential syntax errors, I am C++ programmer, not Pythonista)

I know this looks stupid, but really there is no other miraculous mechanism for interrupting threads. You simply need periodical polling.

PS: instead of

self.worker.finished.connect(self.worker.deleteLater)

you should use

self.thread.finished.connect(self.worker.deleteLater)

otherwise the worker will not be deleted if the thread gets interrupted because then Worker.finished signal gets never called.


问:
How to import android project as library and NOT compile it as apk (Android studio 1.0)
I tried to import a project(projLib) as dependency for another project(projAPK).

projAPK gradle has this :

```<code>dependencies {
    compile project(':libs:NewsAPI')
    compile project(':projLib')
}
</code>```

but when i sync the gradle it gives this error:

Error:Dependency Android_2015:projLib:unspecified on project projAPK resolves to an APK archive which is not supported as a compilation dependency. File: /Users/myname/Documents/Development/Android_2015/libs/projAPK/build/outputs/apk/projLib-release-unsigned.apk

so I guess there are two solution to this:

somehow make gradle think that projLib is a library that shouldn't be compiled to apk

somehow make gradle NOT compile the projLib explicitly

The problem is, I couldn't find how to do any of that.
Would be awesome if you guys can help :)

答:
For Kotlin DSL (build.gradle.kts), use this notation:

plugins {
    id("com.android.library")
    // ...
}
```

Body:
I tried to import a project(projLib) as dependency for another project(projAPK).

projAPK gradle has this :

dependencies {
    compile project(':libs:NewsAPI')
    compile project(':projLib')
}

but when i sync the gradle it gives this error:

Error:Dependency Android_2015:projLib:unspecified on project projAPK resolves to an APK archive which is not supported as a compilation dependency. File: /Users/myname/Documents/Development/Android_2015/libs/projAPK/build/outputs/apk/projLib-release-unsigned.apk

so I guess there are two solution to this:

somehow make gradle think that projLib is a library that shouldn't be compiled to apk

somehow make gradle NOT compile the projLib explicitly

The problem is, I couldn't find how to do any of that.
Would be awesome if you guys can help :)


问:
Localhost - .net6 api project returning empty payload, although I'm getting a 200 OK response status
On a small project developed with React (running locally on localhost:3000), when doing a fetch to my local API(.net6 project), I'm getting a 200 response:

However the response comes totally blank:

If I run the same call from swagger on the API Project I get the response just fine.

My controller currently is using a mediator so it looks like this:

```<code>[AllowAnonymous]
[HttpPost("Authenticate")]
[ProducesResponseType(Microsoft.AspNetCore.Http.StatusCodes.Status200OK)]
[ProducesResponseType(Microsoft.AspNetCore.Http.StatusCodes.Status400BadRequest)]
[ApiConventionMethod(typeof(DefaultApiConventions), nameof(DefaultApiConventions.Post))]
public async Task<TokenResponse> AuthenticateAsync([FromBody] Authenticate.AuthenticateCommand command)
{
    var response = await _mediator.Send(command);
    return response.Resource;
}
</code>```

So maybe there is something there not working?

Because if I replace the controller response like this:

```<code>public async Task<JsonResult> AuthenticateAsync([FromBody] Authenticate.AuthenticateCommand command)
{
    return new JsonResult(new { response = "OK" });
}
</code>```

I'm getting it just fine:

Something suspicious that I don't get when shooting with Swagger is this on the Chrome network tool:

That message "Caution: request is not finished yet!", not sure what it means.

Any help is welcome and appreciated! Thanks!!

答:
Using fiddler I got to see that the response was coming with all the values I've needed.

To finish the flow and get the response in Chrome, after the fetch I've needed to do:

```<code>.then((response) => response.json())
.then((value) => value);
</code>```

In the javascript side of the thing and that finished the flow.

Thanks!!!

Body:
On a small project developed with React (running locally on localhost:3000), when doing a fetch to my local API(.net6 project), I'm getting a 200 response:

However the response comes totally blank:

If I run the same call from swagger on the API Project I get the response just fine.

My controller currently is using a mediator so it looks like this:

[AllowAnonymous]
[HttpPost("Authenticate")]
[ProducesResponseType(Microsoft.AspNetCore.Http.StatusCodes.Status200OK)]
[ProducesResponseType(Microsoft.AspNetCore.Http.StatusCodes.Status400BadRequest)]
[ApiConventionMethod(typeof(DefaultApiConventions), nameof(DefaultApiConventions.Post))]
public async Task<TokenResponse> AuthenticateAsync([FromBody] Authenticate.AuthenticateCommand command)
{
    var response = await _mediator.Send(command);
    return response.Resource;
}

So maybe there is something there not working?

Because if I replace the controller response like this:

public async Task<JsonResult> AuthenticateAsync([FromBody] Authenticate.AuthenticateCommand command)
{
    return new JsonResult(new { response = "OK" });
}

I'm getting it just fine:

Something suspicious that I don't get when shooting with Swagger is this on the Chrome network tool:

That message "Caution: request is not finished yet!", not sure what it means.

Any help is welcome and appreciated! Thanks!!

Body:
Using fiddler I got to see that the response was coming with all the values I've needed.

To finish the flow and get the response in Chrome, after the fetch I've needed to do:

.then((response) => response.json())
.then((value) => value);

In the javascript side of the thing and that finished the flow.

Thanks!!!