问:
301 redirects on WHMCS
I have installed WHMCS in a subdirectory, domain.com/whmcs

Now I am moving it into the main domain and I will be using custom pages. However, i don't want to have .PHP extension on the custom pages that I created. Ex. domain.com/page.php

I will need to remove .PHP extensions from specific pages and redirect these pages to non .PHP versions.

I just want to double check if this is the right 301 redirect for the search engines, before i publish it:

```<code>RewriteEngine on
RewriteRule ^mypage$ mypage.php [L]
Redirect 301 /mypage.php https: //domain.com/mypage
</code>```

It works perfectly when i type domain.com/mypage.php redirects to domain.com/mypage But i am not sure if it's the right way to do it for the search engines. Currently i use wordpress in the root domain, so basically, I want to match the same links.

Thanks!

答:
Just use this to redirect xyz.php to xyz:

```<code>Redirect 301 /xyz.php /xyz
</code>```

As far as I know about search engines, its better to use a 302 redirect to avoid a 'permanent' issue.

Make sure that /xyz actually shows a valid page. So that you do not mess up with the search engines due to a simple mistake like that.

In your example, you use both mod_rewrite and mod_alias. One of them is enough.

RewriteCond, RewriteRule... are from mod_rewrite

Redirect, RedirectMatch... are from mod_alias

Always, test it once before working on a production server.

Title: 301 redirects on WHMCS

Body:
I have installed WHMCS in a subdirectory, domain.com/whmcs

Now I am moving it into the main domain and I will be using custom pages. However, i don't want to have .PHP extension on the custom pages that I created. Ex. domain.com/page.php

I will need to remove .PHP extensions from specific pages and redirect these pages to non .PHP versions.

I just want to double check if this is the right 301 redirect for the search engines, before i publish it:

RewriteEngine on
RewriteRule ^mypage$ mypage.php [L]
Redirect 301 /mypage.php https: //domain.com/mypage

It works perfectly when i type domain.com/mypage.php redirects to domain.com/mypage But i am not sure if it's the right way to do it for the search engines. Currently i use wordpress in the root domain, so basically, I want to match the same links.

Thanks!

Body:
Just use this to redirect xyz.php to xyz:

Redirect 301 /xyz.php /xyz

As far as I know about search engines, its better to use a 302 redirect to avoid a 'permanent' issue.

Make sure that /xyz actually shows a valid page. So that you do not mess up with the search engines due to a simple mistake like that.

In your example, you use both mod_rewrite and mod_alias. One of them is enough.

RewriteCond, RewriteRule... are from mod_rewrite

Redirect, RedirectMatch... are from mod_alias

Always, test it once before working on a production server.


来源: stackexchange

问:
How to import multiple components to main.js in svelte js?
How could import an svelte component to a "target" different to body?

https://github.com/sveltejs/template/blob/master/src/main.js

I am trying the next:

```<code>import App from './App.svelte';
export default new App({ target: document.body.div});
</code>```

How could I export multiple componentes to different targets?

```<code>import App1 from './App1.svelte';
import App2 from './App2.svelte';
export default new App1({ target: document.body.div1});
export default new App2({ target: document.body.div2});
</code>```

答:
You can export a "const" object instead "default" to html element #ids with document.getElementById() or body tag names with   document.getElementsByTagName()</p>
```<code>import App1 from './App1.svelte';
import App2 from './App2.svelte';

export const app1 = new App1({ target: document.getElementById("div1") });
export const app2 = new App2({ target: document.getElementById("div2") });
</code>```

ContentLicense: CC BY-SA 4.0

Body:
How could import an svelte component to a "target" different to body?

https://github.com/sveltejs/template/blob/master/src/main.js

I am trying the next:

import App from './App.svelte';
export default new App({ target: document.body.div});

How could I export multiple componentes to different targets?

import App1 from './App1.svelte';
import App2 from './App2.svelte';
export default new App1({ target: document.body.div1});
export default new App2({ target: document.body.div2});

Body:
You can export a "const" object instead "default" to html element #ids with document.getElementById() or body tag names with   document.getElementsByTagName()

import App1 from './App1.svelte';
import App2 from './App2.svelte';

export const app1 = new App1({ target: document.getElementById("div1") });
export const app2 = new App2({ target: document.getElementById("div2") });


问:
'imgSrc' is not defined no-undef
Consider this:

```<code>useEffect(() => {
    let imageUrlRequest = axios.get(imageEndPointString).then(function (response) {
        console.log('call made')
        let imgSrc = response.data[0].data.children[0].data.url;
        console.log(imgSrc)
      })
      .catch(function (error) {
        // handle error
        console.log(error);
      })
      .then(function () {
        // always executed
      });
  },[]);

  return (
    <div className="game__image">
      <h2>IMAGE URL: {imgSrc}</h2>
      <img src={imgSrc} />
    </div>
  );
</code>```

Howcome imgSrc is undefined?

I also tried this

```<code>let imgSrc;

  useEffect(() => {
    let imageUrlRequest = axios.get(imageEndPointString).then(function (response) {
        console.log('call made')
        imgSrc = response.data[0].data.children[0].data.url;
        console.log(imgSrc)
      })
      .catch(function (error) {
        // handle error
        console.log(error);
      })
      .then(function () {
        // always executed
      });
  },[]);

  return (
    <div className="game">
      <img src={imgSrc} />
    </div>
  );
</code>```

but the image still won't come through. why?

答:
In Javascript variables that are declared inside a block can be used only in this block (local scope).
Furthermore, in React if you want to change your view based on some value you must use the setState function to allow React to know when it should re-render the view.

So in your example you need to do something like this:

```<code>const [imgSrc, setImgSrc] = useState(null);

useEffect(() => {
    let imageUrlRequest = axios.get(imageEndPointString).then(function (response) {
        console.log('call made')
        setImgSrc(response.data[0].data.children[0].data.url);
        console.log(imgSrc)
      })
      .catch(function (error) {
        // handle error
        console.log(error);
      })
      .then(function () {
        // always executed
      });   },[]);

  return (
    <div className="game__image">
      <h2>IMAGE URL: {imgSrc}</h2>
      <img src={imgSrc} />
    </div>   );
</code>```

Title: 'imgSrc' is not defined no-undef

Body:
Consider this:

useEffect(() => {
    let imageUrlRequest = axios.get(imageEndPointString).then(function (response) {
        console.log('call made')
        let imgSrc = response.data[0].data.children[0].data.url;
        console.log(imgSrc)
      })
      .catch(function (error) {
        // handle error
        console.log(error);
      })
      .then(function () {
        // always executed
      });
  },[]);

  return (

IMAGE URL: {imgSrc}

  );

Howcome imgSrc is undefined?

I also tried this

let imgSrc;

  useEffect(() => {
    let imageUrlRequest = axios.get(imageEndPointString).then(function (response) {
        console.log('call made')
        imgSrc = response.data[0].data.children[0].data.url;
        console.log(imgSrc)
      })
      .catch(function (error) {
        // handle error
        console.log(error);
      })
      .then(function () {
        // always executed
      });
  },[]);

  return (

  );

but the image still won't come through. why?

Body:
In Javascript variables that are declared inside a block can be used only in this block (local scope).
Furthermore, in React if you want to change your view based on some value you must use the setState function to allow React to know when it should re-render the view.

So in your example you need to do something like this:

const [imgSrc, setImgSrc] = useState(null);

useEffect(() => {
    let imageUrlRequest = axios.get(imageEndPointString).then(function (response) {
        console.log('call made')
        setImgSrc(response.data[0].data.children[0].data.url);
        console.log(imgSrc)
      })
      .catch(function (error) {
        // handle error
        console.log(error);
      })
      .then(function () {
        // always executed
      });   },[]);

  return (
    <div className="game__image">
      <h2>IMAGE URL: {imgSrc}</h2>
      <img src={imgSrc} />
    </div>   );


问:
remove const qualifier of vector in c++
Is it possible to remove constness of vector ? If so, how can it be achieved? For some reason, I don't have access to the main (), can I still remove the constness of arr in the following code snipet? It feels like that auto arr0 = const_cast<vector<int> & > (arr); is identical to vector<int> arr0 = arr;. I guess it is just an example of explicit vs implicit cast,which both creates a copy of original array ````arr```. Is it possible to remove constness inplace without creating a copy?

```<code>#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

vector<int> func(const vector<int>& arr){
//    vector<int> arr0 = arr;
    auto arr0 = const_cast<vector<int> & > (arr);
    sort(arr0.begin(), arr0.end());
    return arr0;
}

int main(){
    const vector<int> arr = {3,4,1,5,2};
    auto res = func(arr);
    for (auto n:res)
        cout<<n<<" ";
    return 0;

}
</code>```

答:
You can make a copy, it achieves what you're already trying to do. (You get return value optimization, too).

#include <vector>
#include <algorithm>

template <class T>
static std::vector<T> func(std::vector<T> v) {
  std::sort(v.begin(), v.end());
  return v;
}
```

Live Example

You should never attempt to modify a const variable, that's undefined behavior, it doesn't have to do anything, and whatever it does is up to the compiler.

Title: remove const qualifier of vector in c++

Body:
Is it possible to remove constness of vector ? If so, how can it be achieved? For some reason, I don't have access to the main (), can I still remove the constness of arr in the following code snipet? It feels like that auto arr0 = const_cast<vector<int> & > (arr); is identical to vector<int> arr0 = arr;. I guess it is just an example of explicit vs implicit cast,which both creates a copy of original array ````arr```. Is it possible to remove constness inplace without creating a copy?

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

vector<int> func(const vector<int>& arr){
//    vector<int> arr0 = arr;
    auto arr0 = const_cast<vector<int> & > (arr);
    sort(arr0.begin(), arr0.end());
    return arr0;
}

int main(){
    const vector<int> arr = {3,4,1,5,2};
    auto res = func(arr);
    for (auto n:res)
        cout<<n<<" ";
    return 0;

}

Body:
You can make a copy, it achieves what you're already trying to do. (You get return value optimization, too).

#include <vector>
#include <algorithm>

template <class T>
static std::vector<T> func(std::vector<T> v) {
  std::sort(v.begin(), v.end());
  return v;
}

Live Example

You should never attempt to modify a const variable, that's undefined behavior, it doesn't have to do anything, and whatever it does is up to the compiler.


问:
Pandas apply function treating input as a series rather than a single cell in the passed series
I am working in a Jupyter notebook to do some string comparisons between two dataframes and I have run into a confusing issue.

I wrote a simple function to remove all of the stop words and punctuation from a string and when I try to apply it to a column in pandas (as in iterate over all of the indexes for a given column) it instead passes the entire column to the function and outputs garbage.

Here is the statement that is causing problems:

```<code>bank_exp['Description'] = bank_exp.apply(lambda row : preprocess_cell(bank_exp['Description'], stopwords_all), axis = 1)
</code>```

The preprocess function in pseudocode works something like:

def preprocess_cell(string, stopwords_set):
    # Remove punctuation from the string
    string = remove_punc()
    # Filter the string
    filtered_sentence = filt_str(string, stopwords_set)
    # Convert list back into string
    filtered_cell = re_format(filtered_sentence)

    return filtered_cell
```

For reference, my table looks something like this originally:
base table format

And when I run the code currently I get an output like this: partial traceback

I have been staring at this for a bit now so any ideas would be greatly appreciated.

答:
You have to pass the row, not the entire column:

```<code>bank_exp['Description'] = bank_exp.apply(lambda row : preprocess_cell(row['Description'], stopwords_all), axis = 1)
</code>```

Or run apply on the Series:

```<code>bank_exp['Description'] = bank_exp['Description'].apply(preprocess_cell, args=(stopwords_all,))
</code>```

Body:
I am working in a Jupyter notebook to do some string comparisons between two dataframes and I have run into a confusing issue.

I wrote a simple function to remove all of the stop words and punctuation from a string and when I try to apply it to a column in pandas (as in iterate over all of the indexes for a given column) it instead passes the entire column to the function and outputs garbage.

Here is the statement that is causing problems:

bank_exp['Description'] = bank_exp.apply(lambda row : preprocess_cell(bank_exp['Description'], stopwords_all), axis = 1)

The preprocess function in pseudocode works something like:

def preprocess_cell(string, stopwords_set):
    # Remove punctuation from the string
    string = remove_punc()
    # Filter the string
    filtered_sentence = filt_str(string, stopwords_set)
    # Convert list back into string
    filtered_cell = re_format(filtered_sentence)

    return filtered_cell

For reference, my table looks something like this originally:
base table format

And when I run the code currently I get an output like this: partial traceback

I have been staring at this for a bit now so any ideas would be greatly appreciated.

Body:
You have to pass the row, not the entire column:

bank_exp['Description'] = bank_exp.apply(lambda row : preprocess_cell(row['Description'], stopwords_all), axis = 1)

Or run apply on the Series:

bank_exp['Description'] = bank_exp['Description'].apply(preprocess_cell, args=(stopwords_all,))


问:
C# .NET communicate between computers over network
How should I go about making an application with C# and .NET where, say, on one computer a button is pressed that triggers an event on the other?

I saw this:

Recommended way to communicate between processes running on different computers on the same network

I've never heard of WCF, is that what I should try?

答:
Yes, I would use WCF, because I know it's pretty easy to get a simple project running with WCF, and that will give you confidence to build on it. (Having said that, I dont have much experience with any other networking technologies.)

Start with this Getting Started tutorial.

Then if you have more specific questions, ask them.

ContentLicense: CC BY-SA 3.0


问:
ESLint not working in VS Code?
ESLint is not working for me in VS Code. I have the plugin installed in VS Code, and ESLint itself as a developer dependency in my package.json, which I have installed as well.

I modified the following option in the VS Code User Settings:

```<code>{
  "eslint.options": { "configFile": "C:/mypath" }
}
</code>```

I have use the command eslint --init to add the basic .eslintrc.json to the main directory of my package.

Other people were able to get ESLint feedback from VS Code using the exact same package with the exact same ESLint config file.

I have received no feedback of any kind when directly breaking multiple rules that were all included in the recommended rule set that is by default inside of the .eslintrc.json file.

What am I missing?

Edit: I have tested using ESLint via command line, and everything worked as expected, with the errors found where they should have, however, these same errors never showed up in VS Code. The issue seems to be on VS Code's side and not ESLint.

答:
In my case, I followed https://eslint.org/docs/user-guide/getting-started#installation-and-usage to setup the es-lint. But after the installation it's wasn't working.

Fix: But just restarting the vs-code solved the problem for me.

Title: ESLint not working in VS Code?

Body:
ESLint is not working for me in VS Code. I have the plugin installed in VS Code, and ESLint itself as a developer dependency in my package.json, which I have installed as well.

I modified the following option in the VS Code User Settings:

{
  "eslint.options": { "configFile": "C:/mypath" }
}

I have use the command eslint --init to add the basic .eslintrc.json to the main directory of my package.

Other people were able to get ESLint feedback from VS Code using the exact same package with the exact same ESLint config file.

I have received no feedback of any kind when directly breaking multiple rules that were all included in the recommended rule set that is by default inside of the .eslintrc.json file.

What am I missing?

Edit: I have tested using ESLint via command line, and everything worked as expected, with the errors found where they should have, however, these same errors never showed up in VS Code. The issue seems to be on VS Code's side and not ESLint.


答:
I think its because on the first render (before the useEffect) you are trying to use the variable imgSrc as the image source, so you get an error before the useEffect executes. What you can do is using a default value on your return in case imgSrc is still undefined at that moment. Something like

```<code><img src={imgSrc || "anotherurl.com"} />
</code>```

Just use any placeholder default image url and you should get rid of your problem

Title: 'imgSrc' is not defined no-undef

Body:
I think its because on the first render (before the useEffect) you are trying to use the variable imgSrc as the image source, so you get an error before the useEffect executes. What you can do is using a default value on your return in case imgSrc is still undefined at that moment. Something like

<img src={imgSrc || "anotherurl.com"} />

Just use any placeholder default image url and you should get rid of your problem


问:
Configure ASP.NET to use x86 on x64 Windows
I am trying to deploy GAL Modifier, which is an ASP.NET website which uses Microsoft Access on a Windows 2003 x64 machine. However there is no JET driver on x64 (see here), so the change is to use change the target CPU to x86.

However as it is a web site there is no option in Visual Studio except Any CPU, so how can I change the settings to force it to use x86?

答: on iis 6.0, on your left side select "Application Pools", then (on your right side) right click on your app and click on "Advanced Settings...", on the "Enable 32-Bit Applications" option, change to True, and you're ready to go!</p>

ContentLicense: CC BY-SA 2.5


问:
mysql WHERE IN array string / username
Code:

```<code>$friendsArray = array("zac1987", "peter", "micellelimmeizheng1152013142");
$friendsArray2 = join(', ',$friendsArray);
$query120 = "SELECT picturemedium FROM users WHERE username IN ('$friendsArray2')";
echo $query120;
</code>```

This is the output :

```<code>SELECT picturemedium FROM users WHERE username IN ('zac1987, peter, micellelimmeizheng1152013142')
</code>```

It fails because usernames are not wrapped by single quotes like 'zac1987', 'peter', 'mice...'. How can each username be wrapped with single quotes?

答:
When using "IN" logical operator with strings, each string should be wrapped with quotation marks. This is not necessary if all values are numeric values.

```<code>$friendsArray = array("zac1987", "peter", "micellelimmeizheng1152013142");
$friendsArray2 = join("','",$friendsArray);
$query120 = "SELECT picturemedium FROM users WHERE username IN ('{$friendsArray2}')";
echo $query120;
</code>```

The output should be :

```<code>SELECT picturemedium FROM users WHERE username IN ('zac1987','peter','micellelimmeizheng1152013142')
</code>```

Title: mysql WHERE IN array string / username

Body:
Code:

$friendsArray = array("zac1987", "peter", "micellelimmeizheng1152013142");
$friendsArray2 = join(', ',$friendsArray);
$query120 = "SELECT picturemedium FROM users WHERE username IN ('$friendsArray2')";
echo $query120;

This is the output :

SELECT picturemedium FROM users WHERE username IN ('zac1987, peter, micellelimmeizheng1152013142')

It fails because usernames are not wrapped by single quotes like 'zac1987', 'peter', 'mice...'. How can each username be wrapped with single quotes?

Body:
When using "IN" logical operator with strings, each string should be wrapped with quotation marks. This is not necessary if all values are numeric values.

$friendsArray = array("zac1987", "peter", "micellelimmeizheng1152013142");
$friendsArray2 = join("','",$friendsArray);
$query120 = "SELECT picturemedium FROM users WHERE username IN ('{$friendsArray2}')";
echo $query120;

The output should be :

SELECT picturemedium FROM users WHERE username IN ('zac1987','peter','micellelimmeizheng1152013142')


问:
Forced Slowdown of Multiprocessing Generation vs OSError Too Many Open Files
I have the following code.  In testing, I found that when I get several hundred concurrent child processes (somewhere around 400?), I get "OSError Too Many Open Files".  Any idea why?

I can solve the problem with the time.sleep(.005) call, but I shouldn't have to.

This is a part of a larger program.  A typical call will set a server string, token string, and a list of many thousands of devices.  For the REST API call used, the server can only handle a single device at a time.  In testing, this resulted in a 20 min execution time, but indications are that using a multiprocessing approach can reduce it to around 30 sec.

```<code>import urllib, requests, json, sys, pprint, time, multiprocessing as mp

assert sys.version_info >= (3, 6), "Must use Python 3.6+"

###########################
### handler function for multiprocessing worker
###########################

def getAttributesOneDevice(server, device, token, q):
    """Handler function for getting a single device"""
    serverURL = server + "/ServicesAPI/API/V1/CMDB/Devices/Attributes"
    headers = { "Accept" : "application/json",
                "Content-Type" : "application/json",
                "token" : token }
    query = { "hostname" : device }

    response = requests.get(serverURL, headers = headers, params = query, verify = False)
    q.put(response.json())
# end getAttributesOneDevice()

def GetDeviceAttributes(server = "", token = "", devices = []):
    """
    See this URL for explanation of what this function does
    https://github.com/NetBrainAPI/NetBrain-REST-API-V8.02/blob/master
                      /REST APIs Documentation/Devices Management
                      /Get Device Attributes API.md

    To summarize the URL: will acquire detailed device attributes for a single
    device.

    This subroutine therefore queries for all devices provided, and assemble the
    results into a single list of dicts.

    Server queries are relatively expensive.  A single query is not a big deal,
    but accumulated across a massive device list and this can take excessive
    time to execute (20min, etc). Therefor, this procedure is parallelized
    through multi-processing to complete in a reasonable amount of time.

    'server' should be a string that is just the http(s)://<FQDN>.  Do not
    incude the trailing '/'.

    'token' should be an authentication token that was generated by
    GetLoginToken and SetWorkingDomain modules in this directory.

    'devices' should be a list of strings, where each entry is a device.

    return a single dictionary:
        "Table" a list of dicts, each dict the detailed attributes of a device
        "Missed" a list of devices that had no result

    Note that failure to capture a device is distinct from function failure.
    """

    resultsTable = []
    MissedDevices = []
    procList = []

    for dev in devices:
        q = mp.Queue()
        proc = mp.Process(target=getAttributesOneDevice,
                          args=(server, dev, token, q))
        proc.start()
        procList += [ {"proc" : proc, "dev" : dev, "queue" : q} ]

        # If I don't do this as I'm going, I *always* get "OSError too many open files"
        updatedProcList = []
        for proc in procList:
            if proc["proc"].is_alive():
                updatedProcList += [proc]
            else:
                # kill zombies
                if proc["queue"].empty():
                    MissedDevices += [ proc["dev"] ]
                else:
                    queueData = proc["queue"].get()
                    resultsTable += [ queueData ]

                while not proc["queue"].empty():
                    # drain whatever's left before we closeout the process
                    proc["queue"].get()
                proc["proc"].join()

        procList = updatedProcList

        # if I don't do this, I get "OSError too many open files" at somewhere
        # around 375-400 child processes
        time.sleep(.005)

    # I could instead embed the list comprehension in the while statement,
    # but that would hinder troubleshooting
    remainingProcs = [ 1 ]
    while len(remainingProcs) > 0:
        remainingProcs = [ proc for proc in procList if proc["proc"].is_alive()]
        time.sleep(1)

    for proc in procList:
        # kill zombies
        if proc["queue"].empty():
            MissedDevices += [ proc["dev"] ]
        else:
            queueData = proc["queue"].get()
            resultsTable += [ queueData ]

        while not proc["queue"].empty():
            # drain whatever's left before we closeout the process
            proc["queue"].get()
        proc["proc"].join()

    return { "Table" : resultsTable, "Missed" : MissedDevices }
</code>```

答:
Thank you @Booboo and @Olvin-Roght for your help.  I've marked Booboo's answer and the "accepted" answer, ultimately it was a combination of the two.  Here's what I actually ended up with, for transparency and in case it helps anyone else in the future, but I only got here with the pointers from the folks on this thread.  Thank you to everyone.</p>
```<code>import requests, json, sys, concurrent.futures

# tested on 3.6.8
assert sys.version_info >= (3, 6), "Must use Python 3.6+"

#needed to REALLY condense the letters in the function name for submit()
def get1Dev(server, device, token):
    """Handler function for getting a single device. raises an exception if
    unseccessful query, or returns the dict of the detailed attributes table."""

    serverURL = server + "/ServicesAPI/API/V1/CMDB/Devices/Attributes"
    query = { "hostname" : device }
    headers = {
        "Accept" : "application/json",
        "Content-Type" : "application/json",
        "token" : token
    }

    # ProcessPoolExecutor already handles all exceptions
    response = requests.get(serverURL,headers=headers,params=query,verify=False)
    if response.status_code is not 200:
        raise Exception(str(response.status_code) + " returned from server")

    responseStatusDescription = response.json()["statusDescription"]
    if "Success." not in responseStatusDescription:
        raise Exception(f"{responseStatusDescription} returned from server")

    return response.json()["attributes"]
# end get1Dev()

def GetDeviceAttributes(server = "", token = "", devices = []):
    """
    See this URL for explanation of what this function does
    https://github.com/NetBrainAPI/NetBrain-REST-API-V8.02/blob/master
                      /REST APIs Documentation/Devices Management
                      /Get Device Attributes API.md

    To summarize the URL: will acquire detailed device attributes for a single

    This subroutine therefore queries for all devices provided, and assemble the
    results into a single list of dicts.

    Server queries are relatively expensive.  A single query is not a big deal,
    but accumulated across a massive device list and this can take excessive
    time to execute (20min, etc). Therefor, this procedure is parallelized
    through multi-processing to complete in a reasonable amount of time.

    'server' should be a string that is just the http(s)://<FQDN>.  Do not
    incude the trailing '/'.

    'token' should be an authentication token that was generated by
    GetLoginToken and SetWorkingDomain modules in this directory.

    'devices' should be a list of strings, where each entry is a device.

    return a single dictionary:
        "Table" a list of dicts, each dict the detailed attributes of a device
        "Missed" a list of devices that had no result

    Note that failure to capture a device is distinct from function failure.
    """

    # will raise() if needed; purposefully not including in a "try" block
    inputValidate(server, token, devices)

    # remove all empty strings in 'devices'
    devices = [ dev for dev in devices if dev ]

    resultsTable = []
    MissedDevices = []

    # profiling data for max_workers, 06 Feb 2022:
    # single-threaded single-processed: 20min (ish)
    # 61 is default, took 6min
    # 10000 resulted in "too many open files" error
    # detailed analysis: "too many open files" occurs ~350-400 child procs
    # 300 took 40sec, so we'll call that the "sweet spot"
    exe = concurrent.futures.ProcessPoolExecutor(max_workers=300)

    # exe.map() is too trivial in that it halts on first exception :(
    # derived from example for ThreadPoolExecutor
    # https://docs.python.org/3/library/concurrent.futures.html
    results = {exe.submit(get1Dev, server, dev, token): dev for dev in devices}
    for result in concurrent.futures.as_completed(results, timeout=300):
        try:
            # separating calling result() from the += allows exception handling
            # without worrying about adding error result to resultsTable
            res = result.result()
            resultsTable += [ res ]

        # need to catch both exceptions
        except (Exception, concurrent.futures.TimeoutError):
            # not sure why, results[result] is related dev in devices, as desired
            MissedDevices += [ results[result] ]

    return { "Table" : resultsTable, "Missed" : MissedDevices }
</code>```

Body:
I have the following code.  In testing, I found that when I get several hundred concurrent child processes (somewhere around 400?), I get "OSError Too Many Open Files".  Any idea why?

I can solve the problem with the time.sleep(.005) call, but I shouldn't have to.

This is a part of a larger program.  A typical call will set a server string, token string, and a list of many thousands of devices.  For the REST API call used, the server can only handle a single device at a time.  In testing, this resulted in a 20 min execution time, but indications are that using a multiprocessing approach can reduce it to around 30 sec.

import urllib, requests, json, sys, pprint, time, multiprocessing as mp

assert sys.version_info >= (3, 6), "Must use Python 3.6+"

###########################
### handler function for multiprocessing worker
###########################

def getAttributesOneDevice(server, device, token, q):
    """Handler function for getting a single device"""
    serverURL = server + "/ServicesAPI/API/V1/CMDB/Devices/Attributes"
    headers = { "Accept" : "application/json",
                "Content-Type" : "application/json",
                "token" : token }
    query = { "hostname" : device }

    response = requests.get(serverURL, headers = headers, params = query, verify = False)
    q.put(response.json())
# end getAttributesOneDevice()

def GetDeviceAttributes(server = "", token = "", devices = []):
    """
    See this URL for explanation of what this function does
    https://github.com/NetBrainAPI/NetBrain-REST-API-V8.02/blob/master
                      /REST APIs Documentation/Devices Management
                      /Get Device Attributes API.md

    To summarize the URL: will acquire detailed device attributes for a single
    device.

    This subroutine therefore queries for all devices provided, and assemble the
    results into a single list of dicts.

    Server queries are relatively expensive.  A single query is not a big deal,
    but accumulated across a massive device list and this can take excessive
    time to execute (20min, etc). Therefor, this procedure is parallelized
    through multi-processing to complete in a reasonable amount of time.

    'server' should be a string that is just the http(s)://<FQDN>.  Do not
    incude the trailing '/'.

    'token' should be an authentication token that was generated by
    GetLoginToken and SetWorkingDomain modules in this directory.

    'devices' should be a list of strings, where each entry is a device.

    return a single dictionary:
        "Table" a list of dicts, each dict the detailed attributes of a device
        "Missed" a list of devices that had no result

    Note that failure to capture a device is distinct from function failure.
    """

    resultsTable = []
    MissedDevices = []
    procList = []

    for dev in devices:
        q = mp.Queue()
        proc = mp.Process(target=getAttributesOneDevice,
                          args=(server, dev, token, q))
        proc.start()
        procList += [ {"proc" : proc, "dev" : dev, "queue" : q} ]

        # If I don't do this as I'm going, I *always* get "OSError too many open files"
        updatedProcList = []
        for proc in procList:
            if proc["proc"].is_alive():
                updatedProcList += [proc]
            else:
                # kill zombies
                if proc["queue"].empty():
                    MissedDevices += [ proc["dev"] ]
                else:
                    queueData = proc["queue"].get()
                    resultsTable += [ queueData ]

                while not proc["queue"].empty():
                    # drain whatever's left before we closeout the process
                    proc["queue"].get()
                proc["proc"].join()

        procList = updatedProcList

        # if I don't do this, I get "OSError too many open files" at somewhere
        # around 375-400 child processes
        time.sleep(.005)

    # I could instead embed the list comprehension in the while statement,
    # but that would hinder troubleshooting
    remainingProcs = [ 1 ]
    while len(remainingProcs) > 0:
        remainingProcs = [ proc for proc in procList if proc["proc"].is_alive()]
        time.sleep(1)

    for proc in procList:
        # kill zombies
        if proc["queue"].empty():
            MissedDevices += [ proc["dev"] ]
        else:
            queueData = proc["queue"].get()
            resultsTable += [ queueData ]

        while not proc["queue"].empty():
            # drain whatever's left before we closeout the process
            proc["queue"].get()
        proc["proc"].join()

    return { "Table" : resultsTable, "Missed" : MissedDevices }

Body:
Thank you @Booboo and @Olvin-Roght for your help.  I've marked Booboo's answer and the "accepted" answer, ultimately it was a combination of the two.  Here's what I actually ended up with, for transparency and in case it helps anyone else in the future, but I only got here with the pointers from the folks on this thread.  Thank you to everyone.

import requests, json, sys, concurrent.futures

# tested on 3.6.8
assert sys.version_info >= (3, 6), "Must use Python 3.6+"

#needed to REALLY condense the letters in the function name for submit()
def get1Dev(server, device, token):
    """Handler function for getting a single device. raises an exception if
    unseccessful query, or returns the dict of the detailed attributes table."""

    serverURL = server + "/ServicesAPI/API/V1/CMDB/Devices/Attributes"
    query = { "hostname" : device }
    headers = {
        "Accept" : "application/json",
        "Content-Type" : "application/json",
        "token" : token
    }

    # ProcessPoolExecutor already handles all exceptions
    response = requests.get(serverURL,headers=headers,params=query,verify=False)
    if response.status_code is not 200:
        raise Exception(str(response.status_code) + " returned from server")

    responseStatusDescription = response.json()["statusDescription"]
    if "Success." not in responseStatusDescription:
        raise Exception(f"{responseStatusDescription} returned from server")

    return response.json()["attributes"]
# end get1Dev()

def GetDeviceAttributes(server = "", token = "", devices = []):
    """
    See this URL for explanation of what this function does
    https://github.com/NetBrainAPI/NetBrain-REST-API-V8.02/blob/master
                      /REST APIs Documentation/Devices Management
                      /Get Device Attributes API.md

    To summarize the URL: will acquire detailed device attributes for a single

    This subroutine therefore queries for all devices provided, and assemble the
    results into a single list of dicts.

    Server queries are relatively expensive.  A single query is not a big deal,
    but accumulated across a massive device list and this can take excessive
    time to execute (20min, etc). Therefor, this procedure is parallelized
    through multi-processing to complete in a reasonable amount of time.

    'server' should be a string that is just the http(s)://<FQDN>.  Do not
    incude the trailing '/'.

    'token' should be an authentication token that was generated by
    GetLoginToken and SetWorkingDomain modules in this directory.

    'devices' should be a list of strings, where each entry is a device.

    return a single dictionary:
        "Table" a list of dicts, each dict the detailed attributes of a device
        "Missed" a list of devices that had no result

    Note that failure to capture a device is distinct from function failure.
    """

    # will raise() if needed; purposefully not including in a "try" block
    inputValidate(server, token, devices)

    # remove all empty strings in 'devices'
    devices = [ dev for dev in devices if dev ]

    resultsTable = []
    MissedDevices = []

    # profiling data for max_workers, 06 Feb 2022:
    # single-threaded single-processed: 20min (ish)
    # 61 is default, took 6min
    # 10000 resulted in "too many open files" error
    # detailed analysis: "too many open files" occurs ~350-400 child procs
    # 300 took 40sec, so we'll call that the "sweet spot"
    exe = concurrent.futures.ProcessPoolExecutor(max_workers=300)

    # exe.map() is too trivial in that it halts on first exception :(
    # derived from example for ThreadPoolExecutor
    # https://docs.python.org/3/library/concurrent.futures.html
    results = {exe.submit(get1Dev, server, dev, token): dev for dev in devices}
    for result in concurrent.futures.as_completed(results, timeout=300):
        try:
            # separating calling result() from the += allows exception handling
            # without worrying about adding error result to resultsTable
            res = result.result()
            resultsTable += [ res ]

        # need to catch both exceptions
        except (Exception, concurrent.futures.TimeoutError):
            # not sure why, results[result] is related dev in devices, as desired
            MissedDevices += [ results[result] ]

    return { "Table" : resultsTable, "Missed" : MissedDevices }


问:
How was Grub programmed without OS? And is it possible to install only the grub bootloader in an newly assembled UEFI PC with no other OS installed?

In which platform/Environment/OS was grub bootloader programmed? Example the linux kernal was programmed on GCC compiler on MINIX OS, but how was grub made? Since grub is a bootloader (that loads the OS), how was it programmed without using an OS (Like we use IDE as a tool to make an application or any C program cannot execute without C compiler, similarly which tool was used to develop grub)

If I bought a new machine(64 bit intel system with UEFI) with no OS installed, is it possible for me to install grub bootloader (only the bootloader without any linux distro) in this machine.

If the above is possible then what are the steps to install grub directly without any os (Assume that I have an additional windows/Linux PC with me and I have the following src code of grub from here

https://git.savannah.gnu.org/git/grub.git/

https://ftp.gnu.org/gnu/grub/                 )

With this how can I install the grub bootloader in a UEFI system without no os installed and no partition created (Imagine as if the PC is assembled and no OS is still installed but it has UEFI interface).

If it is possible to install only the grub bootloader, then how can I install windows and any linux OS from the grub menu when I boot the system. (Assume that the PC that I am installing is a UEFI system and it has no OS installed on it)

答:
Now, I'm not an expert at the subject, but to my knowledge(never tried it) u might be able to do that, with something like arch linux.
U can just install grub onto the drive but there wont be a place to store the config files if u dont have a proper installed OS. So I know this answer has been vague but in general, the answer is yes but a minimal OS is needed, i have seen with metasploitable, the OS is small, vulnerable and has the grub bootloader too
maybe u could also install an OS and then change grub to not display any OS

also if I understand correctly, u do not need this, but just were wondering
Or u plan on using it with windows, which to my knowledge, should work but with limited customizability(unless u install a linux distro with it)
Thank You


问:
Python os.path.join() and "+" in string concatenation
If I want to use a path "a/b", what is the difference between
os.path.join("a/","b") and "a/"+"b"  ?

Like this:

答:
You can use os.path and its functions, which take care of OS-specific paths. Will work on Windows with backslashes '\' and Unix (including Mac OS X) with '/'.

```<code>>>> import os
>>> os.path.join('root', 'subdir', 'dir', 'filename.ext')
'root/subdir/dir/filename.ext'
</code>```

Using os.path.join makes the statement OS-agnostic. Also it makes obvious to other people reading your code that you are working with file paths. People can quickly scan through the code and discover it's a file path intrinsically.

Body:
You can use os.path and its functions, which take care of OS-specific paths. Will work on Windows with backslashes '\' and Unix (including Mac OS X) with '/'.

>>> import os
>>> os.path.join('root', 'subdir', 'dir', 'filename.ext')
'root/subdir/dir/filename.ext'

Using os.path.join makes the statement OS-agnostic. Also it makes obvious to other people reading your code that you are working with file paths. People can quickly scan through the code and discover it's a file path intrinsically.


问:
I am unable to run streamlit on pycharm and spyder. I am running the latest python version on window.When I try what the code ,it says invalid syntax
#This code is used to open streamlit in browser

import streamlit
import streamlit as st
import pandas as pd
from FPL import predict_team, get_overview_data, extract_player_roster,

extract_teams_data, extract_player_types
import matplotlib.pyplot as plt
import numpy as np
pd.options.display.float_format = "{:,.2f}".format

```<code>def get_team_limit(max_players_from_team):
    max_players_from_team['ARS'] = int(st.text_input('ARS:', 3))
    max_players_from_team['AVL'] = int(st.text_input('AVL:', 3))
    max_players_from_team['BHA'] = int(st.text_input('BHA:', 3))
    max_players_from_team['BUR'] = int(st.text_input('BUR:', 3))
    max_players_from_team['CHE'] = int(st.text_input('CHE:', 3))
    max_players_from_team['CRY'] = int(st.text_input('CRY:', 3))
    max_players_from_team['EVE'] = int(st.text_input('EVE:', 3))
    max_players_from_team['FUL'] = int(st.text_input('FUL:', 3))
    max_players_from_team['LEE'] = int(st.text_input('LEE:', 3))
    max_players_from_team['LEI'] = int(st.text_input('LEI:', 3))
    max_players_from_team['LIV'] = int(st.text_input('LIV:', 3))
    max_players_from_team['MCI'] = int(st.text_input('MCI:', 3))
    max_players_from_team['MUN'] = int(st.text_input('MUN:', 3))
    max_players_from_team['NEW'] = int(st.text_input('NEW:', 3))
    max_players_from_team['SHU'] = int(st.text_input('SHU:', 3))
    max_players_from_team['SOU'] = int(st.text_input('SOU:', 3))
    max_players_from_team['TOT'] = int(st.text_input('TOT:', 3))
    max_players_from_team['WBA'] = int(st.text_input('WBA:', 3))
    max_players_from_team['WHU'] = int(st.text_input('WHU:', 3))
    max_players_from_team['WOL'] = int(st.text_input('WOL:', 3))

    return max_players_from_team

st.markdown("<h1 style='text-align: center;'>Welcome to FPL TeamMaker</h1>", \
            unsafe_allow_html=True)
st.markdown("<h3 style='text-align: center;'>Use Data Science to build your \
            team and win!</h3>", unsafe_allow_html=True)

transfer = False
wildcard = False
gw = 1
budget = 1000
old_data_weight = 0.4
new_data_weight = 0.6
form_weight = 0.5
max_players_from_team = {}
current_team = []
num_transfers = 1

gw = int(st.text_input('Enter the Gameweek you want to make team for:', '1'))
if gw == 1:
    st.write('Starting below, please provide how many players you want from each team.\
        Use this in cases when a particular team does not have a fixture for the week.')
    max_players_from_team = get_team_limit(max_players_from_team)

elif gw > 1 and gw <= 4:
    transfer_or_wildcard = st.radio('Select your mode of team making:', ('Transfer',\
                                'New Team / Wildcard'))
    if transfer_or_wildcard == 'Transfer':
        transfer = True
    else:
        wildcard = True

    old_data_weight = float(st.text_input('Enter the weight you want to give to last \
                                season\'s  data (0-1.0):', 0.4))
    new_data_weight = float(st.text_input('Enter the weight you want to give to current \
                                season\'s  data (0-1.0):', 0.6))
    form_weight = float(st.text_input('Enter the weight you want to give to player form \
                            (0-1.0):', 0.5))
    budget = float(st.text_input('Enter your budget x 10 (For transfers, enter \
                                 the leftover budget using current team):', 1000))

    if transfer:
        num_transfers = int(st.text_input('Enter the number of transfers to be made:', 1))
        overview_data_json = get_overview_data()
        teams_df = extract_teams_data(overview_data_json)
        player_types_df = extract_player_types(overview_data_json)
        player_df = extract_player_roster(overview_data_json, player_types_df, teams_df)
        player_df = player_df[['code', 'first_name', 'second_name', 'team_code']]
        players = st.write('Please look at the list below and enter a comma \
                                 separated list of player codes you have in your team. \
                                 Note that they are ordered alphabetically by team name.', \
                                 player_df)
        try:
            current_team = st.text_input('')
            current_team = list(map(int, current_team.split(',')))
        except:
            st.error('Please enter an input above')

    else:
        st.write('Starting below, please provide how many players you want from each team.\
        Use this in cases when a particular team does not have a fixture for the week.')
        max_players_from_team = get_team_limit(max_players_from_team)

elif gw > 4 and gw <=38:
    transfer_or_wildcard = st.radio('Select your mode of team making:', ('Transfer',\
                                'New Team / Wildcard'))
    if transfer_or_wildcard == 'Transfer':
        transfer = True
    else:
        wildcard = True

    form_weight = float(st.text_input('Enter the weight you want to give to player form \
                            (0-1.0):', 0.5))
    budget = float(st.text_input('Enter your budget x 10 (For transfers, enter \
                                 the leftover budget using current team):', 1000))

    if transfer:
        num_transfers = int(st.text_input('Enter the number of transfers to be made:', 1))
        overview_data_json = get_overview_data()
        teams_df = extract_teams_data(overview_data_json)
        player_types_df = extract_player_types(overview_data_json)
        player_df = extract_player_roster(overview_data_json, player_types_df, teams_df)
        player_df = player_df[['code', 'first_name', 'second_name', 'team_code']]
        players = st.write('Please look at the list below and enter a comma \
                                 separated list of player codes you have in your team. \
                                 Note that they are ordered alphabetically by team name.', \
                                 player_df)
        try:
            current_team = st.text_input('')
            current_team = list(map(int, current_team.split(',')))
        except:
            st.error('Please enter an input above')

    else:
        st.write('Starting below, please provide how many players you want from each team.\
        Use this in cases when a particular team does not have a fixture for the week.')
        max_players_from_team = get_team_limit(max_players_from_team)

if st.button('Get Team'):

    if gw > 38:
        st.error('Enter correct GW')

    team, points, cost = predict_team(transfer, wildcard, gw, budget, old_data_weight, \
                 new_data_weight, form_weight, max_players_from_team, \
                 current_team, num_transfers)
    team['Cost'] /= 10
    team = team.rename(columns = {"First": "First Name", "Second": "Second Name"})
    if len(team) > 0:
        st.write(team)
        st.write('Total points of whole team:', points)
        st.write('Cost of the team:', cost)
    else:
        st.info('Please use this feature after GW4 has completed')

st.markdown("<h1 style='text-align: center;'>Visualization of Results</h1>", unsafe_allow_html=True)

bot101_points = np.array([0, 84, 133, 180, 222, 294, 349, 401, 470\
, 551, 593, 662, 723, 774, 866, 914, 965, 1028, 1070\
,  1151, 1196, 1268, 1352, 1403, np.nan, np.nan, np.nan, np.nan\
, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan])

average_points = np.array([0, 50, 109, 152, 200, 260, 308, 361, 416\
, 471, 515, 577, 628, 670, 730, 771, 808, 864, 894\
, 968, 1010, 1058, 1115, 1173, np.nan, np.nan, np.nan, np.nan, np.nan\
, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan])

bot101_rank = np.array([0, 0.175178, 0.881887, 0.797683, 1.412642, 1.056323, 0.915314, 1.0164, 0.785028\
, 0.378354, 0.515661, 0.522446, 0.495127, 0.426231, 0.218577, 0.226317, 0.191098, 0.204354, 0.219032\
, 0.302307, 0.318217, 0.224458, 0.183696, 0.275990, np.nan, np.nan, np.nan, np.nan, np.nan\
, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan])

bot101_gwrank = np.array([0, 0.175178, 4.534625, 1.174666, 4.348521, 1.728420, 2.062787, 3.960282, 1.105014\
, 0.247396, 2.6096, 2.559066, 1.815474, 1.603100, 0.178608, 2.406347, 0.969028, 2.743019, 1.780634\
, 2.626326, 2.934196, 0.699079, 0.497828, 5.061059, np.nan, np.nan, np.nan, np.nan, np.nan\
, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan])

bot101_gw_points = np.array([0, 84, 49, 55, 42, 72, 55, 52, 69, 81, 50, 69, 61, 51, 92, 48, 51, 63, \
42, 81, 45, 72, 88, 55, np.nan, np.nan, np.nan, np.nan, np.nan\
, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan])

bot101_gw_avg_points = np.array([0, 50, 59, 43, 48, 60, 48, 53, 55, 55, 44, 62, 51, 42, 60, 41, 37, \
56, 30, 74, 42, 48, 57, 58, np.nan, np.nan, np.nan, np.nan, np.nan\
, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan])

gameweeks = [i for i in range(0, 39)]

ax = plt.gca()
ax.set_xlim(0,39)
plt.plot(gameweeks, bot101_points, label = 'Cumulative Team Points')
plt.plot(gameweeks, average_points, label = 'Cumulative Average Points')
plt.xlabel('Gameweeks')
plt.ylabel('Total Points')
plt.title('Total Points Viewed per Week')
plt.legend()
plt.locator_params(axis="x", nbins=38)
st.pyplot()

ax = plt.gca()
ax.invert_yaxis()
ax.ticklabel_format(useOffset=False, style = 'plain')
plt.locator_params(axis="y", nbins=20)
plt.locator_params(axis="x", nbins=38)

ax.set_xlim(0,39)
plt.plot(gameweeks, bot101_rank, label = 'Overall Rank')
plt.plot(gameweeks, bot101_gwrank, label = 'GW Rank')
plt.xlabel('Gameweeks')
plt.ylabel('Ranking (in millions)')
plt.title('Overall vs GW Rank')
plt.legend()
st.pyplot()

ax = plt.gca()
ax.set_xlim(0,39)
plt.plot(gameweeks, bot101_gw_points, label = 'Team Points per Gameweek')
plt.plot(gameweeks, bot101_gw_avg_points, label = 'Average Points per Gameweek')
plt.xlabel('Gameweeks')
plt.ylabel('Points')
plt.title('Points per Week')
plt.legend()
plt.locator_params(axis="x", nbins=38)

st.pyplot()

#THIS IS HOW THE PROGRAM RESPONDS
#OUTPUT:

#Warning: to view this Streamlit app on a browser, run it with the following
  #command:

    #streamlit run C:/Users/HP/PycharmProjects/pythonProject/app.py [ARGUMENTS]
</code>```

答: run this command : streamlit run app.py</p>

Body:
#This code is used to open streamlit in browser

import streamlit
import streamlit as st
import pandas as pd
from FPL import predict_team, get_overview_data, extract_player_roster,

extract_teams_data, extract_player_types
import matplotlib.pyplot as plt
import numpy as np
pd.options.display.float_format = "{:,.2f}".format

def get_team_limit(max_players_from_team):
    max_players_from_team['ARS'] = int(st.text_input('ARS:', 3))
    max_players_from_team['AVL'] = int(st.text_input('AVL:', 3))
    max_players_from_team['BHA'] = int(st.text_input('BHA:', 3))
    max_players_from_team['BUR'] = int(st.text_input('BUR:', 3))
    max_players_from_team['CHE'] = int(st.text_input('CHE:', 3))
    max_players_from_team['CRY'] = int(st.text_input('CRY:', 3))
    max_players_from_team['EVE'] = int(st.text_input('EVE:', 3))
    max_players_from_team['FUL'] = int(st.text_input('FUL:', 3))
    max_players_from_team['LEE'] = int(st.text_input('LEE:', 3))
    max_players_from_team['LEI'] = int(st.text_input('LEI:', 3))
    max_players_from_team['LIV'] = int(st.text_input('LIV:', 3))
    max_players_from_team['MCI'] = int(st.text_input('MCI:', 3))
    max_players_from_team['MUN'] = int(st.text_input('MUN:', 3))
    max_players_from_team['NEW'] = int(st.text_input('NEW:', 3))
    max_players_from_team['SHU'] = int(st.text_input('SHU:', 3))
    max_players_from_team['SOU'] = int(st.text_input('SOU:', 3))
    max_players_from_team['TOT'] = int(st.text_input('TOT:', 3))
    max_players_from_team['WBA'] = int(st.text_input('WBA:', 3))
    max_players_from_team['WHU'] = int(st.text_input('WHU:', 3))
    max_players_from_team['WOL'] = int(st.text_input('WOL:', 3))

    return max_players_from_team

st.markdown("
Welcome to FPL TeamMaker
", \
            unsafe_allow_html=True)
st.markdown("
Use Data Science to build your \
            team and win!
", unsafe_allow_html=True)

transfer = False
wildcard = False
gw = 1
budget = 1000
old_data_weight = 0.4
new_data_weight = 0.6
form_weight = 0.5
max_players_from_team = {}
current_team = []
num_transfers = 1

gw = int(st.text_input('Enter the Gameweek you want to make team for:', '1'))
if gw == 1:
    st.write('Starting below, please provide how many players you want from each team.\
        Use this in cases when a particular team does not have a fixture for the week.')
    max_players_from_team = get_team_limit(max_players_from_team)

elif gw > 1 and gw <= 4:
    transfer_or_wildcard = st.radio('Select your mode of team making:', ('Transfer',\
                                'New Team / Wildcard'))
    if transfer_or_wildcard == 'Transfer':
        transfer = True
    else:
        wildcard = True

    old_data_weight = float(st.text_input('Enter the weight you want to give to last \
                                season\'s  data (0-1.0):', 0.4))
    new_data_weight = float(st.text_input('Enter the weight you want to give to current \
                                season\'s  data (0-1.0):', 0.6))
    form_weight = float(st.text_input('Enter the weight you want to give to player form \
                            (0-1.0):', 0.5))
    budget = float(st.text_input('Enter your budget x 10 (For transfers, enter \
                                 the leftover budget using current team):', 1000))

    if transfer:
        num_transfers = int(st.text_input('Enter the number of transfers to be made:', 1))
        overview_data_json = get_overview_data()
        teams_df = extract_teams_data(overview_data_json)
        player_types_df = extract_player_types(overview_data_json)
        player_df = extract_player_roster(overview_data_json, player_types_df, teams_df)
        player_df = player_df[['code', 'first_name', 'second_name', 'team_code']]
        players = st.write('Please look at the list below and enter a comma \
                                 separated list of player codes you have in your team. \
                                 Note that they are ordered alphabetically by team name.', \
                                 player_df)
        try:
            current_team = st.text_input('')
            current_team = list(map(int, current_team.split(',')))
        except:
            st.error('Please enter an input above')

    else:
        st.write('Starting below, please provide how many players you want from each team.\
        Use this in cases when a particular team does not have a fixture for the week.')
        max_players_from_team = get_team_limit(max_players_from_team)

elif gw > 4 and gw <=38:
    transfer_or_wildcard = st.radio('Select your mode of team making:', ('Transfer',\
                                'New Team / Wildcard'))
    if transfer_or_wildcard == 'Transfer':
        transfer = True
    else:
        wildcard = True

    form_weight = float(st.text_input('Enter the weight you want to give to player form \
                            (0-1.0):', 0.5))
    budget = float(st.text_input('Enter your budget x 10 (For transfers, enter \
                                 the leftover budget using current team):', 1000))

    if transfer:
        num_transfers = int(st.text_input('Enter the number of transfers to be made:', 1))
        overview_data_json = get_overview_data()
        teams_df = extract_teams_data(overview_data_json)
        player_types_df = extract_player_types(overview_data_json)
        player_df = extract_player_roster(overview_data_json, player_types_df, teams_df)
        player_df = player_df[['code', 'first_name', 'second_name', 'team_code']]
        players = st.write('Please look at the list below and enter a comma \
                                 separated list of player codes you have in your team. \
                                 Note that they are ordered alphabetically by team name.', \
                                 player_df)
        try:
            current_team = st.text_input('')
            current_team = list(map(int, current_team.split(',')))
        except:
            st.error('Please enter an input above')

    else:
        st.write('Starting below, please provide how many players you want from each team.\
        Use this in cases when a particular team does not have a fixture for the week.')
        max_players_from_team = get_team_limit(max_players_from_team)

if st.button('Get Team'):

    if gw > 38:
        st.error('Enter correct GW')

    team, points, cost = predict_team(transfer, wildcard, gw, budget, old_data_weight, \
                 new_data_weight, form_weight, max_players_from_team, \
                 current_team, num_transfers)
    team['Cost'] /= 10
    team = team.rename(columns = {"First": "First Name", "Second": "Second Name"})
    if len(team) > 0:
        st.write(team)
        st.write('Total points of whole team:', points)
        st.write('Cost of the team:', cost)
    else:
        st.info('Please use this feature after GW4 has completed')

st.markdown("
Visualization of Results
", unsafe_allow_html=True)

bot101_points = np.array([0, 84, 133, 180, 222, 294, 349, 401, 470\
, 551, 593, 662, 723, 774, 866, 914, 965, 1028, 1070\
,  1151, 1196, 1268, 1352, 1403, np.nan, np.nan, np.nan, np.nan\
, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan])

average_points = np.array([0, 50, 109, 152, 200, 260, 308, 361, 416\
, 471, 515, 577, 628, 670, 730, 771, 808, 864, 894\
, 968, 1010, 1058, 1115, 1173, np.nan, np.nan, np.nan, np.nan, np.nan\
, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan])

bot101_rank = np.array([0, 0.175178, 0.881887, 0.797683, 1.412642, 1.056323, 0.915314, 1.0164, 0.785028\
, 0.378354, 0.515661, 0.522446, 0.495127, 0.426231, 0.218577, 0.226317, 0.191098, 0.204354, 0.219032\
, 0.302307, 0.318217, 0.224458, 0.183696, 0.275990, np.nan, np.nan, np.nan, np.nan, np.nan\
, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan])

bot101_gwrank = np.array([0, 0.175178, 4.534625, 1.174666, 4.348521, 1.728420, 2.062787, 3.960282, 1.105014\
, 0.247396, 2.6096, 2.559066, 1.815474, 1.603100, 0.178608, 2.406347, 0.969028, 2.743019, 1.780634\
, 2.626326, 2.934196, 0.699079, 0.497828, 5.061059, np.nan, np.nan, np.nan, np.nan, np.nan\
, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan])

bot101_gw_points = np.array([0, 84, 49, 55, 42, 72, 55, 52, 69, 81, 50, 69, 61, 51, 92, 48, 51, 63, \
42, 81, 45, 72, 88, 55, np.nan, np.nan, np.nan, np.nan, np.nan\
, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan])

bot101_gw_avg_points = np.array([0, 50, 59, 43, 48, 60, 48, 53, 55, 55, 44, 62, 51, 42, 60, 41, 37, \
56, 30, 74, 42, 48, 57, 58, np.nan, np.nan, np.nan, np.nan, np.nan\
, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan])

gameweeks = [i for i in range(0, 39)]

ax = plt.gca()
ax.set_xlim(0,39)
plt.plot(gameweeks, bot101_points, label = 'Cumulative Team Points')
plt.plot(gameweeks, average_points, label = 'Cumulative Average Points')
plt.xlabel('Gameweeks')
plt.ylabel('Total Points')
plt.title('Total Points Viewed per Week')
plt.legend()
plt.locator_params(axis="x", nbins=38)
st.pyplot()

ax = plt.gca()
ax.invert_yaxis()
ax.ticklabel_format(useOffset=False, style = 'plain')
plt.locator_params(axis="y", nbins=20)
plt.locator_params(axis="x", nbins=38)

ax.set_xlim(0,39)
plt.plot(gameweeks, bot101_rank, label = 'Overall Rank')
plt.plot(gameweeks, bot101_gwrank, label = 'GW Rank')
plt.xlabel('Gameweeks')
plt.ylabel('Ranking (in millions)')
plt.title('Overall vs GW Rank')
plt.legend()
st.pyplot()

ax = plt.gca()
ax.set_xlim(0,39)
plt.plot(gameweeks, bot101_gw_points, label = 'Team Points per Gameweek')
plt.plot(gameweeks, bot101_gw_avg_points, label = 'Average Points per Gameweek')
plt.xlabel('Gameweeks')
plt.ylabel('Points')
plt.title('Points per Week')
plt.legend()
plt.locator_params(axis="x", nbins=38)

st.pyplot()

#THIS IS HOW THE PROGRAM RESPONDS
#OUTPUT:

#Warning: to view this Streamlit app on a browser, run it with the following
  #command:

    #streamlit run C:/Users/HP/PycharmProjects/pythonProject/app.py [ARGUMENTS]

Body: run this command : streamlit run app.py


问:
Using Null variables in conditions in T-Sql
Is there a way to use a variable in the following manner?

```<code>DECLARE @ID int;
SET @ID = NULL;
SELECT *
FROM Market market
WHERE market.ID IS @ID
</code>```

Or is there another way to do this?

Thanks.

答:
You need to do

```<code>SELECT *
FROM Market market
WHERE market.ID = @ID OR (@ID IS NULL AND market.ID IS NULL)
</code>```

Just for completeness at the moment it is still possible to do

```<code>SET ANSI_NULLS OFF

SELECT *
FROM Market market
WHERE market.ID = @ID
</code>```

but you shouldn't. This option is deprecated. Quite an interesting related blog post

Body:
Is there a way to use a variable in the following manner?

DECLARE @ID int;
SET @ID = NULL;
SELECT *
FROM Market market
WHERE market.ID IS @ID

Or is there another way to do this?

Thanks.

Body:
You need to do

SELECT *
FROM Market market
WHERE market.ID = @ID OR (@ID IS NULL AND market.ID IS NULL)

Just for completeness at the moment it is still possible to do

SET ANSI_NULLS OFF

SELECT *
FROM Market market
WHERE market.ID = @ID

but you shouldn't. This option is deprecated. Quite an interesting related blog post


问:
RISC - V : Is there any way to parse a word to a float?
I am trying to divide a float to a word

```<code>  fmul.s f8, f2, s5
</code>```

every time I try to run it an error pops up mentioning
Too few or incorrectly formatted operands. Expected: fmul.d f1, f2, f3, dyn

答:
You'll need to first convert the word value into a float with an fcvt instruction:

```<code>fcvt.s.w  f1, x5
</code>```

then you can use a normal floating point fmul or fdiv instruction

Body:
I am trying to divide a float to a word

  fmul.s f8, f2, s5

every time I try to run it an error pops up mentioning
Too few or incorrectly formatted operands. Expected: fmul.d f1, f2, f3, dyn

Body:
You'll need to first convert the word value into a float with an fcvt instruction:

fcvt.s.w  f1, x5

then you can use a normal floating point fmul or fdiv instruction


问:
Text column in R - Trying to count the keywords sequentially
I am working on a dataset that has a text column. The text has many sentences separated by a semi-colon ';'. I am trying to get a word count in a new column in dataframe for words that match my keyword. However, in one sentence, if there are repeated keywords, they should be considered only once.

For instance -

The section 201 solar trade case on cells and modules; Issues relating to section 201 tariffs on imported goods

Solar panels, Tawian tariffs, trade

Trade issues impacting the solar industry

are the text in one column of the dataframe.
My keywords include solar, solar panels, section 201

I want to count the words in each sentence that match my keywords but if both or all words are there in the sentence, then it is counted only once. Word counts should only consider keywords in different sentences. If one sentence doesn't have a specific keyword, then move towards finding the second keyword.

My output should be -
word_count
2 (as section 201 is mentioned in both sentences, we do not search for solar because the first word in the keyword list matched)
1 (as only solar word is there)
1 (as only solar word is there)

Please suggest a way to resolve this issue. It is a crucial part of my research work. Thanks.

Kind Regards,
Preety

答:
If the list of keywords is not too long (say 10 or 20 words), then you can look at the count of all the keywords for each text string. I am adding ; at the end of each text string so that a sentence always ends with a ;. The pattern paste0("[^;]*", key, "[^;]*;") identifies any sentence containing the word (stored in) key.

```<code>txt <- c("The section 201 solar trade case on cells and modules; Issues relating to section 201 tariffs on imported goods",
         "Solar panels, Tawian tariffs, trade",
         "Trade issues impacting the solar industry")

keys <- c("section 201", "solar panels", "solar")
counts <- sapply(keys, function(key) stringr::str_count(paste0(txt, ";"), regex(paste0("[^;]*", key, "[^;]*;"), ignore_case = T)))
</code>```

Next you can go over each row of counts and look at the first non-zero element which should be the value you are looking for.

```<code>sapply(1:nrow(counts), function(i) {
  a <- counts[i, ]
  a[a != 0][1]
})
</code>```

Body:
If the list of keywords is not too long (say 10 or 20 words), then you can look at the count of all the keywords for each text string. I am adding ; at the end of each text string so that a sentence always ends with a ;. The pattern paste0("[^;]*", key, "[^;]*;") identifies any sentence containing the word (stored in) key.

txt <- c("The section 201 solar trade case on cells and modules; Issues relating to section 201 tariffs on imported goods",
         "Solar panels, Tawian tariffs, trade",
         "Trade issues impacting the solar industry")

keys <- c("section 201", "solar panels", "solar")
counts <- sapply(keys, function(key) stringr::str_count(paste0(txt, ";"), regex(paste0("[^;]*", key, "[^;]*;"), ignore_case = T)))

Next you can go over each row of counts and look at the first non-zero element which should be the value you are looking for.

sapply(1:nrow(counts), function(i) {
  a <- counts[i, ]
  a[a != 0][1]
})


问:
Multiply string - [Leetcode] Problem with Java
Question is:

Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string.

Note: You must not use any built-in BigInteger library or convert the inputs to integer directly.

Code:

```<code>class Solution {
    public String multiply(String num1, String num2) {
        long n1=0, n2=0, res;
        n1 =  Long.parseLong(num1);
        n2 =  Long.parseLong(num2);
        res = n1 * n2;
        String str = Long.toString(res);
        return str;
    }
}
</code>```

Question is:

Its working properly when I give smaller number is like:

Input :40,
90

Output:3600

Input :100,
2099

Output:209900

If i give input like this:

Input :498828660196, 840477629533

Output:"-3269442614257959980"

But the Actual output is : 419254329864656431168468. I don't know why answer coming like this. am also using long datatype. Anyone explain me and give solution for this problem.

答: Because you are storing it in Long and the range of long is up to 10^18 sort of but the answer which will come is of 10^23 range so it is throwing some garbage value as it is out of its range of storing, that is why you have return type of string as you can store it in string not in a long datatype.</p>

Body:
Question is:

Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string.

Note: You must not use any built-in BigInteger library or convert the inputs to integer directly.

Code:

class Solution {
    public String multiply(String num1, String num2) {
        long n1=0, n2=0, res;
        n1 =  Long.parseLong(num1);
        n2 =  Long.parseLong(num2);
        res = n1 * n2;
        String str = Long.toString(res);
        return str;
    }
}

Question is:

Its working properly when I give smaller number is like:

Input :40,
90

Output:3600

Input :100,
2099

Output:209900

If i give input like this:

Input :498828660196, 840477629533

Output:"-3269442614257959980"

But the Actual output is : 419254329864656431168468. I don't know why answer coming like this. am also using long datatype. Anyone explain me and give solution for this problem.


问:
How to create a custom HTTP status code between 110 - 150 in action result?
I want to add a custom error code like 110, 108 with some message like "Invalid Id". Please suggest how to break the default HTTP status code in ASP.NET </p>

答:
For example :</p>
```<code>public ActionResult TestError(string id) // id = error code
{
    Response.StatusCode = 400; // Replace .AddHeader
    var error = new Error();  // Create class Error() w/ prop
    error.ErrorID = 123;
    error.Level = 2;
    error.Message = "You broke the Internet!";

    return Json(error, JsonRequestBehavior.AllowGet);
}
</code>```

Body:
For example :

public ActionResult TestError(string id) // id = error code
{
    Response.StatusCode = 400; // Replace .AddHeader
    var error = new Error();  // Create class Error() w/ prop
    error.ErrorID = 123;
    error.Level = 2;
    error.Message = "You broke the Internet!";

    return Json(error, JsonRequestBehavior.AllowGet);
}


问:
Unable to Install Pillow for Tkinter via PIP
I tried to install Pillow library for my Tkinter project but when I try to install it, it gives me the following error.

Fatal error in launcher: Unable to create process using "C:\Python310\python.exe"  "C:\Python310\Scripts\pip.exe" install Pillow : The system cannot find the file specified.

I have the latest Python version from the official website and I also have pip manually installed during my Win7 days. Even debugging ain't helping. It gives the same error.

答:
are you using "pip" or "conda"?

try

```<code>conda install pillow
</code>```

or

```<code>pip install pillow
</code>```

Body:
are you using "pip" or "conda"?

try

conda install pillow

or

pip install pillow


问:
State not getting updated when calling the related setState in React
I am trying to fetch images from an Unsplash API, and then trying to update the images data using useState in the following code.

```<code>const [images, setImages] = useState([]);

  useEffect(() => {
    Axios.get(
      "https://api.unsplash.com/photos/?client_id=l2U-D_PXXujBJoRiCCMCL2ifi_5ZJcK4AC0WH-A2lKk"
    )
      .then((res) => {
        //res.data is printing correct/expected value
        console.log(res.data);

        setImages(res.data);
        console.log("lul");

        //but images array is still empty
        console.log("images: ", [images]); // []
      })
      .catch((err) => console.error(err));
  }, []);
</code>```

If I put the images array in the dependency array, then I am able to update the image array, but then fetching is occurring infinitely.

Why this is happening?

答:
What you are doing wrong is that you are trying to console.log before React has re-rendered. Updating a state through the related setState is not instantaneous as the doc says:

The set function only updates the state variable for the next render. If you read the state variable after calling the set function, you will still get the old value that was on the screen before your call.

One way to log changes in your state is to add a console.log() just after defining it:

const [images, setImages] = useState([]);
// It logs [] the first time and then the fetched data
console.log(images);

useEffect(() => {
  Axios.get(
    "https://api.unsplash.com/photos/?client_id=l2U-D_PXXujBJoRiCCMCL2ifi_5ZJcK4AC0WH-A2lKk"
    )
    .then((res) => {
      setImages(res.data);
    })
    .catch((err) => console.error(err));
}, []);
```

Body:
I am trying to fetch images from an Unsplash API, and then trying to update the images data using useState in the following code.

const [images, setImages] = useState([]);

  useEffect(() => {
    Axios.get(
      "https://api.unsplash.com/photos/?client_id=l2U-D_PXXujBJoRiCCMCL2ifi_5ZJcK4AC0WH-A2lKk"
    )
      .then((res) => {
        //res.data is printing correct/expected value
        console.log(res.data);

        setImages(res.data);
        console.log("lul");

        //but images array is still empty
        console.log("images: ", [images]); // []
      })
      .catch((err) => console.error(err));
  }, []);

If I put the images array in the dependency array, then I am able to update the image array, but then fetching is occurring infinitely.

Why this is happening?


问:
TemplateDoesNotExist-Already added the templates dir in settings and created inside project
I have created a project "ProTwo" and app as "appTwo" added the templates dir in the project settings and created templates folder in the project.When I render the views index.html its showing error

app/views.py

```<code>from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.

def index(request):
    help_dict={'help_me':"HELP PAGE"}
    return render(request,'appTwo/help.html',context=help_dict)
</code>```

app/urls.py

```<code>from django.urls import path
from appTwo import views

urlpatterns = [
    path('',views.index,name="index"),
]
</code>```

Project/settings.py

```<code>import os
from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
TEMPLATES_DIR=os.path.join(BASE_DIR,"templates")

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-0m6xzby50vk61zdun2g%oq^nkr2v0=_7il#z#qnx)=7=6q_e^p'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'appTwo',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'ProTwo.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [TEMPLATES_DIR,],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'ProTwo.wsgi.application'

# Database
# https://docs.djangoproject.com/en/4.0/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}

# Password validation
# https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
# https://docs.djangoproject.com/en/4.0/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

enter code here

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.0/howto/static-files/

STATIC_URL = 'static/'

# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
</code>```

project/urls.py

```<code>from django.contrib import admin
from django.urls import path,include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('appTwo/',include('appTwo.urls')),
]
</code>```

project/templates/appTwo/index.html

```<code><!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title>appTwo</title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="">
    </head>
    <body>
        {{ help_me }}
        <script src="" async defer></script>
    </body>
</html>
</code>```

答:
You are rendering  return render(request,'appTwo/help.html',context=help_dict)
and the template name is "help.html" while your html file is named "index.html". Just change the names and it will be fixed!

Body:
I have created a project "ProTwo" and app as "appTwo" added the templates dir in the project settings and created templates folder in the project.When I render the views index.html its showing error

app/views.py

from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.

def index(request):
    help_dict={'help_me':"HELP PAGE"}
    return render(request,'appTwo/help.html',context=help_dict)

app/urls.py

from django.urls import path
from appTwo import views

urlpatterns = [
    path('',views.index,name="index"),
]

Project/settings.py

import os
from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
TEMPLATES_DIR=os.path.join(BASE_DIR,"templates")

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-0m6xzby50vk61zdun2g%oq^nkr2v0=_7il#z#qnx)=7=6q_e^p'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'appTwo',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'ProTwo.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [TEMPLATES_DIR,],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'ProTwo.wsgi.application'

# Database
# https://docs.djangoproject.com/en/4.0/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}

# Password validation
# https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
# https://docs.djangoproject.com/en/4.0/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

enter code here

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.0/howto/static-files/

STATIC_URL = 'static/'

# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

project/urls.py

from django.contrib import admin
from django.urls import path,include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('appTwo/',include('appTwo.urls')),
]

project/templates/appTwo/index.html

<!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title>appTwo</title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="">

        {{ help_me }}


问:
Run faye server on production server
I want to use Faye on production server. how can I start faye server automatically or as a daemon process.

Because when I start faye server using SSH it shutdown as i close ssh connection. Please guide me its really urgent.

I can run faye server on local but how I can rub this on live site.

答:
It gets stopped probably because you're running it in your session, and once that session is closed it receives a SIGHUP signal and quits.

A quick test to determine if that's really your problem is to log in, execute

```<code>nohup your_server_startup_command > /dev/null 2>&1 &
</code>```

logout, and see if the server still runs.  THIS IS NOT A PERMANENT SOLUTION THOUGH!

The normal way for a server is to create a management script in init.d, and then use the service management app of your Linux distro to have the service started in the appropriate runlevels.  In OpenSUSE you'll use YAST for that, in Ubuntu there's sysvconfig.

There are subtle differences between Linux distros, have a look here to get a general idea of how an init.d script is supposed to look, or here for an absolute bare-bones example.

Title: Run faye server on production server

Body:
It gets stopped probably because you're running it in your session, and once that session is closed it receives a SIGHUP signal and quits.

A quick test to determine if that's really your problem is to log in, execute

nohup your_server_startup_command > /dev/null 2>&1 &

logout, and see if the server still runs.  THIS IS NOT A PERMANENT SOLUTION THOUGH!

The normal way for a server is to create a management script in init.d, and then use the service management app of your Linux distro to have the service started in the appropriate runlevels.  In OpenSUSE you'll use YAST for that, in Ubuntu there's sysvconfig.

There are subtle differences between Linux distros, have a look here to get a general idea of how an init.d script is supposed to look, or here for an absolute bare-bones example.


问:
How to get HTML leaderboard into discord channel that auto updates
Is there anyway I can make this leaderboard show in a discord channel as as embedded or parae it to look directly like that, but show in a channel a dn auto update?

I’ve been trying all day and all I can do it get texts files to show on discord or a slipper sloppy website parse. Please Somone else , I just want to top 5-10 leaderboards user and for it to auto-update maybe every hour

enter image description here

答:
Have you tried using Webhooks?

This Reddit post explains the process in detail

A Discord Bot might also be usable in this case


问:
What is the difference between sending data using streams in node using 'data' event and 'open' event?
I have been trying to figure out the difference in the following two code snippets in node. On making the request from the browser both the code files shows transfer-encoding to be chunked. So, are these two methods same and if not what is the drawback of one over the other.

Method-1 :

```<code>const http = require("http");
const fs = require("fs");

const server = http.createServer((req, res) => {
  const stream = fs.createReadStream("./bigFile.txt");
  stream.on("open", () => {
    stream.pipe(res);
  });
});

server.listen(3000, () => {
  console.log("server started");
});
</code>```

Method-2 :

```<code>const http = require("http");
const fs = require("fs");

const server = http.createServer((req, res) => {
  const stream = fs.createReadStream("./bigFile.txt");
  stream.on("data", () => {
    stream.pipe(res);
  });
});

server.listen(3000, () => {
  console.log("server started");
});
</code>```

答:
So, you don't have to wait for either event before piping the stream.  The stream and the pipe operation will handle all that for you.  So, you can just do this:

```<code>const stream = fs.createReadStream("./bigFile.txt");
stream.pipe(res);
</code>```

The pipe operation will register itself for the data event and as data arrives on the readstream, it will write it out to the res stream.  So, you don't need to do either of your options.

I would guess that this option:

```<code>stream.on("data", () => {
  stream.pipe(res);
 });
</code>```

can actually cause a problem because the data event can occur more than once and then you'll be trying to call .pipe() more than once.  You would not have that issue with the open event, though as I said above, you don't need to hook into either event yourself as .pipe() will do that for you

Body:
I have been trying to figure out the difference in the following two code snippets in node. On making the request from the browser both the code files shows transfer-encoding to be chunked. So, are these two methods same and if not what is the drawback of one over the other.

Method-1 :

const http = require("http");
const fs = require("fs");

const server = http.createServer((req, res) => {
  const stream = fs.createReadStream("./bigFile.txt");
  stream.on("open", () => {
    stream.pipe(res);
  });
});

server.listen(3000, () => {
  console.log("server started");
});

Method-2 :

const http = require("http");
const fs = require("fs");

const server = http.createServer((req, res) => {
  const stream = fs.createReadStream("./bigFile.txt");
  stream.on("data", () => {
    stream.pipe(res);
  });
});

server.listen(3000, () => {
  console.log("server started");
});

Body:
So, you don't have to wait for either event before piping the stream.  The stream and the pipe operation will handle all that for you.  So, you can just do this:

const stream = fs.createReadStream("./bigFile.txt");
stream.pipe(res);

The pipe operation will register itself for the data event and as data arrives on the readstream, it will write it out to the res stream.  So, you don't need to do either of your options.

I would guess that this option:

stream.on("data", () => {
  stream.pipe(res);
 });

can actually cause a problem because the data event can occur more than once and then you'll be trying to call .pipe() more than once.  You would not have that issue with the open event, though as I said above, you don't need to hook into either event yourself as .pipe() will do that for you


问:
FFMPEG - How to add a language tag to a stream without changing anything else?
I have been experimenting with ffmpeg and trying to learn how to use it better - it is extremely powerful and there seem to be so many options, so I figured I would just try to do some things to learn amount mappings and tags etc.

There is nothing special about the file - it is just a small test MKV file that I can run through quickly when trying things.

Currently, I am trying to add a language tag to the video stream within the MKV file, but it is not working as expected (to me at least!)

The file (input.mkv) has four streams:

Stream #0:0: Video: h264 (Main)

Stream #0:1(eng): Audio: ac3

Stream #0:2(eng): Subtitle

Stream #0:3(eng): Subtitle

As you can see, three of the streams are tagged as Eng(lish), but the video stream is not.  I realise that video is probably not often tagged with a language, but I am just trying to understand how this all works.

This is the command I am using:

ffmpeg -i input.mkv -metadata:s:v:0 language=eng -codec copy mkv.ext

What I thought this meant, was just to set the language tag = 'eng' to the first video stream (0:0), which it does, but for some reason it also deletes (or omits) the second subtitle stream (0:3) from the output.mkv file so that what I get in the output.mkv is:

Stream #0:0(eng): Video: h264 (Main)

Stream #0:1(eng): Audio: ac3

Stream #0:2(eng): Subtitle

so that we have successfully added the 'eng' tag to the video stream, but somehow lost the second subtitle stream along the way.

Questions:

What would be the correct command to achieve what I wanted?

Please help me understand what I am missing that leads to the deletion of the second subtitle stream?

Thanks,

Alan.

答:
Add -map 0 to include all streams from input 0 in the output.

Read http://ffmpeg.org/ffmpeg.html#Stream-selection, especially the section on automatic stream selection for details on how ffmpeg selects streams.


问:
Slack: change browser to open links from desktop app
I use two browsers on my laptop - Brave for my personal stuff (Facebook, personal email, interesting things I want to read) and Firefox for my work browsing (work email, internal webpages, work communication). Normally I like having my default browser for the computer set to Brave (personal), since most of the time I use the laptop outside of work.

I now have the Slack desktop app to keep in better communication with folks at work. But when I click on links from there, it goes to Brave where I am not logged-in to anything work related.

Is there a way to change the browser that Slack opens without changin my system wide default browser?

I'm on a Mac, Mojave, if that helps.

答:
Default Browser for certain application

The above answer by @maxim deals with how to set default browser per app, and fortunately, it uses slack as the example.


问:
When a file is "opened with" a winforms application how do I get the application to use that file's directory?
I am able to set my .mdb files to "open with" my winforms application, but that only opens the winforms application without loading the file. Is there any event that is triggered upon opening the application through a file that will allow me to grab the filename/file-directory to load it into my app?

Update:

apparently this can be done for "Windows Store Apps": File "Open with" my Windows Store App

But it seems as though my winforms project lacks a package.appxmanifest to edit these settings from, nor does my project have access to the Windows.ApplicationModel.Activation.FileActivatedEventArgs and Windows.UI.Xaml.Application.OnFileActivated
APIs needed for this method.

答:
When you double-click an mdb file, your application will be executed with mdb file argument. Similar to calling your app from command line:

```<code>> your-app.exe "test.mdb"
</code>```

You should use the args in the Main method.

```<code>class Program
{
    static void Main(string[] args)
    {
        // check that user provided a file to open
        if (args != null && args.Length > 0)
        {
            var mdbFilePath = args[0];
            // TODO: read the file
        }

        // ...
</code>```

Body:
When you double-click an mdb file, your application will be executed with mdb file argument. Similar to calling your app from command line:

> your-app.exe "test.mdb"

You should use the args in the Main method.

class Program
{
    static void Main(string[] args)
    {
        // check that user provided a file to open
        if (args != null && args.Length > 0)
        {
            var mdbFilePath = args[0];
            // TODO: read the file
        }

        // ...


答:
setState is invoked asynchronous (though is doesn't return a promise so you can't await it).

Keep your useEffect as it is now, and in order to print the new value whenever the images changes, you can use another useEffect:

```<code>  useEffect(() => {
    console.log("images: ", [images]); // []
  }, [images]);
</code>```

Title: State not getting updated when calling the related setState in React

Body:
setState is invoked asynchronous (though is doesn't return a promise so you can't await it).

Keep your useEffect as it is now, and in order to print the new value whenever the images changes, you can use another useEffect:

  useEffect(() => {
    console.log("images: ", [images]); // []
  }, [images]);