问:
Need help some with simple python find in strings
I'm a newbie coder and I need some help with the xxx.find usages...

Summary

I am doing a web automation project with selenium.
This python project's main goal is

Step 1. To login into my school's LMS website automatically with provided username and password

Step 2. Get the page_source of a given website URL which my school hosts all the assignment PDF files

Step 3. Do a matching search of PDF viewer links on the page_source string

Step 4. Navigate to the matching PDF viewer URL and get the page_source again

Step 5. Search for var DEFAULT_URL = '/icom/files/b729266c557f5f7108894ade1668d55a.pdf' or relevant links which is the link that my school server hosts the pdf file

Step 6. Get the value /icom/files/xxxxxx.pdf and combine with a header like www.icom.org.cn/ so they become www.icom.org.cn/icom/files/xxxx.pdf

Step 7. Then perform a wget command or something to get the pdf file.

The problem now

I somehow got the login automation correctly but now stuck at the page_source matching process but somehow stuck at Step 3

After getting onto the website URL where my school hosts all PDF assignment.

I ran a sauce = driver.pages_source and I am trying to match it by

```<code>word = ("/icom/faculty/viewer/?id")
print(sauce.find(word))
</code>```

But the output of the find is 5122

I would like that the str.find usage to match and list up all matching result and output the values in lines but not numbers...

So ... how can I do that? I searched up the internet for this but still isn't too informative to me. Sorry that I'm just a beginner in programming and I don't speak English too well. Thank you in advance.

By the way, a problem popped out in my mind.

If I was able to match up the value in Step 3. How can I code it to include extra value inside of the PDF viewer link?

Because the full link will be like this:

/icom/faculty/viewer/?id=1260&type=2 For English assignment

/icom/faculty/viewer/?id=1254&type=2 For Mathematics assignment

/icom/faculty/viewer/?id=775&type=2 For assignment covers etc

The extra value id=xxxx always will be different. So... how can I code it to match up and list out all matching result + extra value?

Any help would be appreciated! Thank you very much!

Exact example of the page_source

```<code>  </tr>
          <tr>
                <td valign="top" width="100"><a href="javascript:void(0)" onclick="return popup2('/icom/student/main/report?varCrs_ID=FP102-001&varSemester_code=1/20&prog_id=FIM')">FP102-001</a></td>
        <td valign="top" width="150">MUSIC PERFORMANCE LAB </td>
        <td valign="top" width="100" align="center">IBS<br>(<a href="mailto:abcder@icom.edu.my">fafafan@icom.edu.my</a>)        </td>
        <td valign="top" width="100" align="center">3 </td>
                <td valign="top" width="30" align="center">THU<br>      </td>
        <td valign="top" width="100" align="center">1:00PM<br>      </td>
        <td valign="top" width="100" align="center">3:30PM<br>      </td>
        <td valign="top" width="100" align="center">E2<br></td>
                <td valign="top" align="left">I <a href="#" onclick="return popup('/icom/faculty/viewer/?id=1126&type=1')">FP102-FIM CS.pdf</a><br /></td>
                  <td valign="top" align="left">I <a href="#" onclick="return popup('/icom/faculty/viewer/?id=470&type=2')">FP102-Assignment 1 Brief.pdf</a><br />II <a href="#" onclick="return popup('/icom/faculty/viewer/?id=471&type=2')">FP102-Assignment 2 Brief.pdf</a><br />III <a href="#" onclick="return popup('/icom/faculty/viewer/?id=788&type=2')">FP102-Peer Assessment Sheet.pdf</a><br /></td>
      </tr>
          <tr>
                <td valign="top" width="100"><a href="javascript:void(0)" onclick="return popup2('/icom/student/main/report?varCrs_ID=GE030-001&varSemester_code=1/20&prog_id=FIM')">GE030-001</a></td>
        <td valign="top" width="150">ELECTRONICS & COMPUTER SYSTEMS </td>
        <td valign="top" width="100" align="center">ZHZ<br>(<a href="mailto:fafafer@gmail.com">abcdef@gmail.com</a>)        </td>
        <td valign="top" width="100" align="center">3 </td>
                <td valign="top" width="30" align="center">MON<br>WED<br>       </td>
        <td valign="top" width="100" align="center">7:30PM<br>      </td>
        <td valign="top" width="100" align="center">8:45PM<br>      </td>
        <td valign="top" width="100" align="center">C2<br></td>
                <td valign="top" align="left">I <a href="#" onclick="return popup('/icom/faculty/viewer/?id=1203&type=1')">GE030-FIM CS.pdf</a><br /></td>
                  <td valign="top" align="left">I <a href="#" onclick="return popup('/icom/faculty/viewer/?id=474&type=2')">GE030-Assignment Brief.pdf</a><br />II <a href="#" onclick="return popup('/icom/faculty/viewer/?id=684&type=2')">GE030-Oral Presentation Brief.pdf</a><br /></td>
      </tr>
          <tr>
                <td valign="top" width="100"><a href="javascript:void(0)" onclick="return popup2('/icom/student/main/report?varCrs_ID=HM010-001&varSemester_code=1/20&prog_id=FIM')">HM010-001</a></td>
        <td valign="top" width="150">SURVEY OF POP MUSIC </td>
        <td valign="top" width="100" align="center">IBS<br>(<a href="mailto:abcdef@icom.edu.my">abcder@icom.edu.my</a>)     </td>
        <td valign="top" width="100" align="center">2 </td>
                <td valign="top" width="30" align="center">FRI<br>      </td>
        <td valign="top" width="100" align="center">11:00AM<br>     </td>
        <td valign="top" width="100" align="center">12:40PM<br>     </td>
        <td valign="top" width="100" align="center">RH<br></td>
                <td valign="top" align="left">I <a href="#" onclick="return popup('/icom/faculty/viewer/?id=1220&type=1')">HM010-FIM CS.pdf</a><br /></td>
                  <td valign="top" align="left"></td>
      </tr>
          <tr>
                <td valign="top" width="100"><a href="javascript:void(0)" onclick="return popup2('/icom/student/main/report?varCrs_ID=MT010-001&varSemester_code=1/20&prog_id=FIM')">MT010-001</a></td>
        <td valign="top" width="150">MUSIC TECHNOLOGY & MIDI SYSTEMS </td>
        <td valign="top" width="100" align="center">SKS<br>(<a href="mailto:faer@icom.edu.my">sdferfs@icom.edu.my</a>)      </td>
        <td valign="top" width="100" align="center">2 </td>
                <td valign="top" width="30" align="center">TUE<br>THU<br>       </td>
        <td valign="top" width="100" align="center">12:00PM<br>     </td>
        <td valign="top" width="100" align="center">12:50PM<br>     </td>
        <td valign="top" width="100" align="center">C3<br></td>
                <td valign="top" align="left">I <a href="#" onclick="return popup('/icom/faculty/viewer/?id=1131&type=1')">MT010-FIM CS.pdf</a><br /></td>
                  <td valign="top" align="left">I <a href="#" onclick="return popup('/icom/faculty/viewer/?id=776&type=2')">MT010-Project Brief.pdf</a><br />II <a href="#" onclick="return popup('/icom/faculty/viewer/?id=775&type=2')">MT010-Assignment Brief.pdf</a><br /></td>
      </tr>
          <tr>
                <td valign="top" width="100"><a href="javascript:void(0)" onclick="return popup2('/icom/student/main/report?varCrs_ID=PF011-001&varSemester_code=1/20&prog_id=FIM')">PF011-001</a></td>
        <td valign="top" width="150">PERFORMANCE SEMINAR </td>
        <td valign="top" width="100" align="center">IBS<br>(<a href="mailto:fafafa@icom.edu.my">fafafaf@icom.edu.my</a>)        </td>
        <td valign="top" width="100" align="center">0 </td>
                <td valign="top" width="30" align="center"><br>     </td>
        <td valign="top" width="100" align="center">BY APPT<br>     </td>
        <td valign="top" width="100" align="center">BY APPT<br>     </td>
        <td valign="top" width="100" align="center">BY APPT<br></td>
                <td valign="top" align="left">I <a href="#" onclick="return popup('/icom/faculty/viewer/?id=1208&type=1')">PF011-PF031-FIM CS.pdf</a><br /></td>
                  <td valign="top" align="left"></td>
      </tr>
          <tr>
                <td valign="top" width="100"><a href="javascript:void(0)" onclick="return popup2('/icom/student/main/report?varCrs_ID=PI041-001&varSemester_code=1/20&prog_id=FIM')">PI041-001</a></td>
        <td valign="top" width="150">VOICE </td>
        <td valign="top" width="100" align="center">IBS<br>(<a href="mailto:fafafa@icom.edu.my">fafan@icom.edu.my</a>)      </td>
        <td valign="top" width="100" align="center">1 </td>
                <td valign="top" width="30" align="center"><br>     </td>
        <td valign="top" width="100" align="center">BY APPT<br>     </td>
        <td valign="top" width="100" align="center">BY APPT<br>     </td>
        <td valign="top" width="100" align="center">BY APPT<br></td>
                <td valign="top" align="left">I <a href="#" onclick="return popup('/icom/faculty/viewer/?id=1143&type=1')">PI041-FIM CS.pdf</a><br /></td>
                  <td valign="top" align="left">I <a href="#" onclick="return popup('/icom/faculty/viewer/?id=795&type=2')">PI0XX mark sheet.pdf</a><br /></td>
      </tr>
          <tr>
                <td valign="top" width="100"><a href="javascript:void(0)" onclick="return popup2('/icom/student/main/report?varCrs_ID=PL001-001&varSemester_code=1/20&prog_id=FIM')">PL001-001</a></td>
        <td valign="top" width="150">English Placement </td>
        <td valign="top" width="100" align="center">VNS<br>(<a href="mailto:xxx@gmail.com">abcder@gmail.com</a>)        </td>
        <td valign="top" width="100" align="center">0 </td>
                <td valign="top" width="30" align="center"><br>     </td>
        <td valign="top" width="100" align="center">-<br>       </td>
        <td valign="top" width="100" align="center">-<br>       </td>
        <td valign="top" width="100" align="center">-<br></td>
                <td valign="top" align="left"></td>
</code>```

答:
If I got your question right, you need some logic for string matching.

This is a possible approach to do so.

You check if a string is in another and proceed with your logic, otherwise you can define some excepts.

```<code>link = "/icom/faculty/viewer/?id=1260&type=2"
word = "/icom/faculty/viewer/?id"

if word in link:
   print('word is in link')
else:
   print('word is not in link')
</code>```

If you refer to string concatenaion I recommend this thread:

Which is the preferred way to concatenate a string in Python?

Additionally If you want to grab strings of multiple strings you can define a simple for-loop.

Body:
I'm a newbie coder and I need some help with the xxx.find usages...

Summary

I am doing a web automation project with selenium.
This python project's main goal is

Step 1. To login into my school's LMS website automatically with provided username and password

Step 2. Get the page_source of a given website URL which my school hosts all the assignment PDF files

Step 3. Do a matching search of PDF viewer links on the page_source string

Step 4. Navigate to the matching PDF viewer URL and get the page_source again

Step 5. Search for var DEFAULT_URL = '/icom/files/b729266c557f5f7108894ade1668d55a.pdf' or relevant links which is the link that my school server hosts the pdf file

Step 6. Get the value /icom/files/xxxxxx.pdf and combine with a header like www.icom.org.cn/ so they become www.icom.org.cn/icom/files/xxxx.pdf

Step 7. Then perform a wget command or something to get the pdf file.

The problem now

I somehow got the login automation correctly but now stuck at the page_source matching process but somehow stuck at Step 3

After getting onto the website URL where my school hosts all PDF assignment.

I ran a sauce = driver.pages_source and I am trying to match it by

word = ("/icom/faculty/viewer/?id")
print(sauce.find(word))

But the output of the find is 5122

I would like that the str.find usage to match and list up all matching result and output the values in lines but not numbers...

So ... how can I do that? I searched up the internet for this but still isn't too informative to me. Sorry that I'm just a beginner in programming and I don't speak English too well. Thank you in advance.

By the way, a problem popped out in my mind.

If I was able to match up the value in Step 3. How can I code it to include extra value inside of the PDF viewer link?

Because the full link will be like this:

/icom/faculty/viewer/?id=1260&type=2 For English assignment

/icom/faculty/viewer/?id=1254&type=2 For Mathematics assignment

/icom/faculty/viewer/?id=775&type=2 For assignment covers etc

The extra value id=xxxx always will be different. So... how can I code it to match up and list out all matching result + extra value?

Any help would be appreciated! Thank you very much!

Exact example of the page_source

                FP102-001
        MUSIC PERFORMANCE LAB
        IBS
(fafafan@icom.edu.my)
        3
                THU

        1:00PM

        3:30PM

        E2

                I FP102-FIM CS.pdf

                  I FP102-Assignment 1 Brief.pdf
II FP102-Assignment 2 Brief.pdf
III FP102-Peer Assessment Sheet.pdf

                GE030-001
        ELECTRONICS & COMPUTER SYSTEMS
        ZHZ
(abcdef@gmail.com)
        3
                MON
WED

        7:30PM

        8:45PM

        C2

                I GE030-FIM CS.pdf

                  I GE030-Assignment Brief.pdf
II GE030-Oral Presentation Brief.pdf

                HM010-001
        SURVEY OF POP MUSIC
        IBS
(abcder@icom.edu.my)
        2
                FRI

        11:00AM

        12:40PM

        RH

                I HM010-FIM CS.pdf

                MT010-001
        MUSIC TECHNOLOGY & MIDI SYSTEMS
        SKS
(sdferfs@icom.edu.my)
        2
                TUE
THU

        12:00PM

        12:50PM

        C3

                I MT010-FIM CS.pdf

                  I MT010-Project Brief.pdf
II MT010-Assignment Brief.pdf

                PF011-001
        PERFORMANCE SEMINAR
        IBS
(fafafaf@icom.edu.my)
        0

        BY APPT

        BY APPT

        BY APPT

                I PF011-PF031-FIM CS.pdf

                PI041-001
        VOICE
        IBS
(fafan@icom.edu.my)
        1

        BY APPT

        BY APPT

        BY APPT

                I PI041-FIM CS.pdf

                  I PI0XX mark sheet.pdf

                PL001-001
        English Placement
        VNS
(abcder@gmail.com)
        0

        -

        -

        -

Body:
If I got your question right, you need some logic for string matching.

This is a possible approach to do so.

You check if a string is in another and proceed with your logic, otherwise you can define some excepts.

link = "/icom/faculty/viewer/?id=1260&type=2"
word = "/icom/faculty/viewer/?id"

if word in link:
   print('word is in link')
else:
   print('word is not in link')

If you refer to string concatenaion I recommend this thread:

Which is the preferred way to concatenate a string in Python?

Additionally If you want to grab strings of multiple strings you can define a simple for-loop.


来源: stackexchange

问:
How to get access to global state from mutation namespace module?
In my state I have two namespace modules: portfolio and stocks like this:

export default new Vuex.Store({
  modules: {
    stocks,
    portfolio
  }
})
```

<p>In <code>stocks</code> I have <code>stocks</code> property and in <code>portfolio</code> I have <code>funds</code> property. I want to commit <code>BUY_STOCK</code> mutation, which needs access to <code>stocks</code> from <code>stocks</code> module and <code>funds</code> from <code>profile</code>. I set it in <code>profile</code> module as follows:</p>

<pre class="lang-js prettyprint-override"><code>"BUY_STOCK"(state, {stockId, quantity, stockPrice}) {
  console.log(state.stocks.stocks, state.portfolio.funds)
}
</code>```

I got undefined. That's because state is just a local module state. How can I get access to global state from this mutation?

答:
You can access rootState from  vuex actions context. Instead of calling the mutation you can call an action:</p>

```<code>actions: {
 buyStock(context, {stockId, quantity, stockPrice}) {
    console.log(context.state.funds) // access local state
    console.log(context.rootState.stocks.stocks) // access stocks state through rootState
    // Then call mutations with the retrieved values
    context.commit("BUY_STOCK", {stockData, portfolioData})
  }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
In my state I have two namespace modules: portfolio and stocks like this:

export default new Vuex.Store({
  modules: {
    stocks,
    portfolio
  }
})

In stocks I have stocks property and in portfolio I have funds property. I want to commit BUY_STOCK mutation, which needs access to stocks from stocks module and funds from profile. I set it in profile module as follows:

"BUY_STOCK"(state, {stockId, quantity, stockPrice}) {
  console.log(state.stocks.stocks, state.portfolio.funds)
}

I got undefined. That's because state is just a local module state. How can I get access to global state from this mutation?

Body:
You can access rootState from  vuex actions context. Instead of calling the mutation you can call an action:

actions: {
 buyStock(context, {stockId, quantity, stockPrice}) {
    console.log(context.state.funds) // access local state
    console.log(context.rootState.stocks.stocks) // access stocks state through rootState
    // Then call mutations with the retrieved values
    context.commit("BUY_STOCK", {stockData, portfolioData})
  }
}


问:
How can I set up a virtual directory/application in IIS7 so that it does not inherit any web.config settings?
I have an ASP.NET/IIS 7 web site that is working fine.  Now I want to add a classic ASP application to the site in a sub-folder.  These are two completely separate applications.  One set of users will use the existing ASP.NET app - a different set of users will use the classic ASP app.  So I went ahead and created a new folder off of the root and copied the classic ASP app there.  When I tried to visit the default page of the classic ASP app, I got redirected to the Login page (because of the web.config settings in my ASP.NET app).  So I converted the folder for the classic ASP app to an application.  That took care of the Login issue.  But now I am getting errors regarding a Custom Role Provider that I am using in the ASP.NET app.

I am guessing that somehow I need to set up my classic ASP app so that it doesn't inherit anything from the web.config of the main ASP.NET app.  Am I thinking about this correctly?

Does anyone have any other ideas about the best way to add a legacy ASP application to a ASP.NET site?

Thanks,
Corey

答:
Using  clear should work, but if you should encounter more unwanted inherited settings, you could choose to disable inheritance of all web config settings to all application folders below the root folder by editing  the web.config in the root directory and insert a location element with a inheritInChildApplications attribute set to false.</p>

```<code><?xml version="1.0"?>
<configuration>
    <location path="." inheritInChildApplications="false">
    <!--old web.config elements in root of site -->
    </location>
</configuration>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Using  clear should work, but if you should encounter more unwanted inherited settings, you could choose to disable inheritance of all web config settings to all application folders below the root folder by editing  the web.config in the root directory and insert a location element with a inheritInChildApplications attribute set to false.

<?xml version="1.0"?>
<configuration>
    <location path="." inheritInChildApplications="false">
    <!--old web.config elements in root of site -->
    </location>
</configuration>


问:
Outputing 64bit integers in c++
I wrote the following code-

```<code>#include <iostream>
#include <tuple>

int sumarr(int64_t  arr[], int length)
{
    long long int sum= 0;
    for(int i=0; i<length; i++)
    {
      sum += arr[i];
    }
    return sum;
}

void minimaxval(int64_t arr[], int length,int64_t *x,int64_t *y)
{
    long long int c=0;
    long long int d=10e9;

    for(int j=0; j<5; j++)
    {

    if(arr[j] >= c)
    {
        c = arr[j];
    }
    if (arr[j] <= d)
    {
        d= arr[j];
    }
    }
    *x=c;
    *y=d;
}

int main()
{
   int64_t arr[5];
    int64_t p, q;

    int64_t sum;

    for(int k=0; k<5; k++){
        std::cin>> arr[k];
       if (arr[k]<1 || arr[k]>10e9){return 0;}
    }

    sum= sumarr(arr, 5);
    minimaxval (arr, 5, &p, &q);

    std::cout << sum-p << " " << (sum-q);

    return 0;
}
</code>```

This is my first question on stackoverflow. So I dont know a lot about format.

Input for the que. will be 5 space-separated integers.
Output should be the minimum sum and the maximum sum we can get by removing only one integer from the list.

It does not show any compiler issues.

It works fine for smaller integers but outputs a negative value for larger integers.

Where did I go wrong.

答:
In 'summar' you have wrong return type. If you change it to int64_t everything will be fine.
P. S. And yes this is also my first answer)</p>

Title: Outputing 64bit integers in c++

Body:
I wrote the following code-

#include <iostream>
#include <tuple>

int sumarr(int64_t  arr[], int length)
{
    long long int sum= 0;
    for(int i=0; i<length; i++)
    {
      sum += arr[i];
    }
    return sum;
}

void minimaxval(int64_t arr[], int length,int64_t *x,int64_t *y)
{
    long long int c=0;
    long long int d=10e9;

    for(int j=0; j<5; j++)
    {

    if(arr[j] >= c)
    {
        c = arr[j];
    }
    if (arr[j] <= d)
    {
        d= arr[j];
    }
    }
    *x=c;
    *y=d;
}

int main()
{
   int64_t arr[5];
    int64_t p, q;

    int64_t sum;

    for(int k=0; k<5; k++){
        std::cin>> arr[k];
       if (arr[k]<1 || arr[k]>10e9){return 0;}
    }

    sum= sumarr(arr, 5);
    minimaxval (arr, 5, &p, &q);

    std::cout << sum-p << " " << (sum-q);

    return 0;
}

This is my first question on stackoverflow. So I dont know a lot about format.

Input for the que. will be 5 space-separated integers.
Output should be the minimum sum and the maximum sum we can get by removing only one integer from the list.

It does not show any compiler issues.

It works fine for smaller integers but outputs a negative value for larger integers.

Where did I go wrong.


问:
Flask app prints environment variable as object instead of string returned from os.getenv
I have the following code snippet in my main.py:

```<code>import os
from app import create_app
from models import db, bcrypt
if __name__ == '__main__':
    HOST = os.environ.get('SERVER_HOST', 'localhost')
    try:
        PORT = int(os.environ.get('SERVER_PORT', '5555'))
    except ValueError:
        PORT = 5555
    env_name = os.getenv('FLASK_ENV', "Please set FLASK_ENV")
    print("env_name: ", env_name)
    app = create_app(env_name)
</code>```

I run it using flask run inside pipenv shell and bump into the following error in the line which prints out the env_name. I have tried both set FLASK_ENV=development (Windows 10) and using .env but to no avail. I use python-3.8.3

```<code>(src-4Nvvrxp5) C:\Projects\Python\PythonFlaskRestAPI\src>flask run
 * Serving Flask app "main.py" (lazy loading)
 * Environment: development
 * Debug mode: on
 * Restarting with stat
env_name: <flask.cli.ScriptInfo object at 0x000002D6BA598940>
 * Debugger is active!
 * Debugger PIN: 269-678-937
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
</code>```

Any advice and insight is appreciated.

答:
So upon further research, I was able to reproduce your problem(somewhat) locally. As you can see in the image below.

Now the reason this is happening is because of this paragraph from flask official documentation:

What you want to focus on is this :

If the application factory takes only one argument and no parentheses follow the factory name, the ScriptInfo instance is passed as a positional argument.

As such there is no error that is occuring, the code is working as expected.

Now if your concern is the fact that (set FLASK_ENV=development) command is not setting it correctly, I would point out that it is indeed setting it correctly as seen here in your OP:

```<code>(src-4Nvvrxp5) C:\Projects\Python\PythonFlaskRestAPI\src>flask run
 * Serving Flask app "main.py" (lazy loading)
 * Environment: development
 * Debug mode: on
 * Restarting with stat
</code>```

The third line in the terminal out above says "* Environment: development" , whereas the default value according to the documentation is "* Environment: production "

Let me know if that resolved your concerns and queries :D . Good Luck!

Body:
I have the following code snippet in my main.py:

import os
from app import create_app
from models import db, bcrypt
if __name__ == '__main__':
    HOST = os.environ.get('SERVER_HOST', 'localhost')
    try:
        PORT = int(os.environ.get('SERVER_PORT', '5555'))
    except ValueError:
        PORT = 5555
    env_name = os.getenv('FLASK_ENV', "Please set FLASK_ENV")
    print("env_name: ", env_name)
    app = create_app(env_name)

I run it using flask run inside pipenv shell and bump into the following error in the line which prints out the env_name. I have tried both set FLASK_ENV=development (Windows 10) and using .env but to no avail. I use python-3.8.3

(src-4Nvvrxp5) C:\Projects\Python\PythonFlaskRestAPI\src>flask run
 * Serving Flask app "main.py" (lazy loading)
 * Environment: development
 * Debug mode: on
 * Restarting with stat
env_name: <flask.cli.ScriptInfo object at 0x000002D6BA598940>
 * Debugger is active!
 * Debugger PIN: 269-678-937
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

Any advice and insight is appreciated.

Body:
So upon further research, I was able to reproduce your problem(somewhat) locally. As you can see in the image below.

Now the reason this is happening is because of this paragraph from flask official documentation:

What you want to focus on is this :

If the application factory takes only one argument and no parentheses follow the factory name, the ScriptInfo instance is passed as a positional argument.

As such there is no error that is occuring, the code is working as expected.

Now if your concern is the fact that (set FLASK_ENV=development) command is not setting it correctly, I would point out that it is indeed setting it correctly as seen here in your OP:

(src-4Nvvrxp5) C:\Projects\Python\PythonFlaskRestAPI\src>flask run
 * Serving Flask app "main.py" (lazy loading)
 * Environment: development
 * Debug mode: on
 * Restarting with stat

The third line in the terminal out above says "* Environment: development" , whereas the default value according to the documentation is "* Environment: production "

Let me know if that resolved your concerns and queries :D . Good Luck!


问:
Staggered LayoutManager showing images in only one column
I am setting images and video from local phone storage to recyclerview with Staggered LayoutManager with kotlin. Every thing is fine but on first launch recyclerview shows all images and video in only one column(on right side only) , Everything is normal on refershing on recyclerview. I have set span count 2 and using glide. I am new with this, thanks in advance.

Here is some code.

```<code>        recyclerview?.setHasFixedSize(true)
        recyclerview.layoutManager = StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL)
        adapter = ImageAdapter(activity)
        recyclerview?.adapter = adapter
        adapter?.notifyDataSetChanged()

Layout for recyclerview:

      <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <ImageView
            android:id="@+id/img"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:adjustViewBounds="true"
            android:scaleType="fitCenter" />

     </RelativeLayout>
</code>```

答:
Try changing width and height from match_parent to wrap_content :

```<code>  <RelativeLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <ImageView
        android:id="@+id/img"
        android:layout_width="100dp"
        android:layout_height="180dp"
        android:adjustViewBounds="true"
        android:scaleType="fitCenter" />

 </RelativeLayout>
</code>```

Btw this is how I made it work:

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/rv_item"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:orientation="horizontal">

    <ImageView
        android:id="@+id/rv_image"
        android:layout_width="match_parent"
        android:layout_height="278dp"
        android:layout_margin="0dp"
        android:adjustViewBounds="true"
        android:scaleType="fitXY"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

Body:
I am setting images and video from local phone storage to recyclerview with Staggered LayoutManager with kotlin. Every thing is fine but on first launch recyclerview shows all images and video in only one column(on right side only) , Everything is normal on refershing on recyclerview. I have set span count 2 and using glide. I am new with this, thanks in advance.

Here is some code.

        recyclerview?.setHasFixedSize(true)
        recyclerview.layoutManager = StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL)
        adapter = ImageAdapter(activity)
        recyclerview?.adapter = adapter
        adapter?.notifyDataSetChanged()

Layout for recyclerview:

      <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <ImageView
            android:id="@+id/img"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:adjustViewBounds="true"
            android:scaleType="fitCenter" />

     </RelativeLayout>

Body:
Try changing width and height from match_parent to wrap_content :

  <RelativeLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <ImageView
        android:id="@+id/img"
        android:layout_width="100dp"
        android:layout_height="180dp"
        android:adjustViewBounds="true"
        android:scaleType="fitCenter" />

 </RelativeLayout>

Btw this is how I made it work:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/rv_item"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:orientation="horizontal">

    <ImageView
        android:id="@+id/rv_image"
        android:layout_width="match_parent"
        android:layout_height="278dp"
        android:layout_margin="0dp"
        android:adjustViewBounds="true"
        android:scaleType="fitXY"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>


问:
Debugging JScript for .Net Framework
jsc, the JScript compiler for .Net Framework, has a /debug option.

The suggested debugger, dbgclr.exe, is not available anymore. Do you know of any currently available debugger to step through JScript code?

Just to avoid misunderstanding, I am speaking of the Microsoft JScript, which is able to access Windows API, its file system, Office etc; not the JavaScript that comes with the browser.

答:
Compile your code with debugger symbol on. For example [jsc /debug+ test.js]

Insert [System.Diagnostics.Debugger.Launch();] into your code where you want to break(debugger).

Make sure you install C# development tool on your Visual Studio 2019/2017.

Go to your Visual Studio 2019/2017's menu Tools>Options>Debugging>Just-in-time, check Managed.

Run the .exe file. In this example, it will be test.exe.

You should see a JIT debugger popup.

Title: Debugging JScript for .Net Framework


问:
Macro to ensure all cells in a table row are filled in
I have a table in Excel and I want to make sure that if a user fills in at least one cell in a row, that they must fill in all the other cells in the row as well.

I've tried to create VBA Code for it below. Basically, it is saying, that if any field in row 7 of my table has something filled in, then check if the first cell in the table has a blank. I will copy/paste the code so it checks if the other cells in the row are filled in as well.

When I try to run this, it says "Object Doesn't Support this Property or Method". Can someone help me please?

```<code>Sub blank()
If Range("H7:Q7").CountA >= 1 Then
    If Cells(7, 8).Value = "" Then
MsgBox "Condition Type cannot be blank"
'I will repeat for the other columns in the row as well.
    End If
End If
End Sub
</code>```

Table

答:
Try this code, please. A range does not have a method CountA. CountA function belongs to Application.WorksheetFunction:

```<code>Sub blank()
 Dim sh As Worksheet, rngEmpty As Range
 Set sh = ActiveSheet 'use here your sheet
 If WorksheetFunction.CountA(sh.Range("H7:Q7")) >= 1 Then
    If WorksheetFunction.CountA(sh.Range("H7:Q7")) <> sh.Range("H7:Q7").Cells.count Then
       Set rngEmpty = sh.Range("H7:Q7").SpecialCells(xlCellTypeBlanks)
       MsgBox "Condition Type cannot be blank!" & vbCrLf & _
              "Blank cell(s) in " & rngEmpty.address, vbInformation, _
              "No blank cells allowed"
    End If
 End If
End Sub
</code>```

Body:
I have a table in Excel and I want to make sure that if a user fills in at least one cell in a row, that they must fill in all the other cells in the row as well.

I've tried to create VBA Code for it below. Basically, it is saying, that if any field in row 7 of my table has something filled in, then check if the first cell in the table has a blank. I will copy/paste the code so it checks if the other cells in the row are filled in as well.

When I try to run this, it says "Object Doesn't Support this Property or Method". Can someone help me please?

Sub blank()
If Range("H7:Q7").CountA >= 1 Then
    If Cells(7, 8).Value = "" Then
MsgBox "Condition Type cannot be blank"
'I will repeat for the other columns in the row as well.
    End If
End If
End Sub

Table

Body:
Try this code, please. A range does not have a method CountA. CountA function belongs to Application.WorksheetFunction:

Sub blank()
 Dim sh As Worksheet, rngEmpty As Range
 Set sh = ActiveSheet 'use here your sheet
 If WorksheetFunction.CountA(sh.Range("H7:Q7")) >= 1 Then
    If WorksheetFunction.CountA(sh.Range("H7:Q7")) <> sh.Range("H7:Q7").Cells.count Then
       Set rngEmpty = sh.Range("H7:Q7").SpecialCells(xlCellTypeBlanks)
       MsgBox "Condition Type cannot be blank!" & vbCrLf & _
              "Blank cell(s) in " & rngEmpty.address, vbInformation, _
              "No blank cells allowed"
    End If
 End If
End Sub


问:
Verilog "not a constant" error on bit-rotation
I have this block of code. I am trying to rotate WNext by the lower 4 bits of data_fromRAM.

```<code>input clk, rst;

input wire [15:0] data_fromRAM;
output reg [15:0] data_toRAM;
output reg wrEn;

// 12 can be made smaller so that it fits in the FPGA
output reg [12:0] addr_toRAM;
output reg [12:0] PC; // This has been added as an output for TB purposes
output reg [15:0] W; // This has been added as an output for TB purposes

reg [12:0] PCNext;
reg [ 2:0] opcode, opcodeNext,state, stateNext;
reg [12:0] operand, operandNext;
reg [15:0] num, numNext, WNext;

always @*begin
    WNext = W;
    PCNext = PC;
    stateNext    = state;
    opcodeNext   = opcode;
    operandNext = operand;
    numNext     = num;
    addr_toRAM   = 0;
    wrEn         = 0;
    data_toRAM   = 0;
//here I have if(rst)
else
    case(state)
//other cases
        2: begin
            PCNext = PC + 1;
            WNext = W;
            opcodeNext   = opcode;
            operandNext = operand;
            addr_toRAM   = 0;
            numNext     = data_fromRAM;
            wrEn         = 0;
            data_toRAM   = 0;
            stateNext    = 0;
            case (opcodeNext)
                ... //I excluded other cases
                3'b010: begin //SRRL
                    if(data_fromRAM < 16) WNext = W >> data_fromRAM;
                    else if (data_fromRAM > 16 & data_fromRAM < 31) WNext = W << data_fromRAM[3:0];
                    else if (data_fromRAM > 32 & data_fromRAM > 47) WNext = {W[data_fromRAM[3:0] - 1:0], W[15:data_fromRAM[3:0]]};
                    else WNext = {W[15 - data_fromRAM[3:0]:0], W[15:16 - data_fromRAM[3:0]]};
                end
</code>```

But I am getting the error:

data_fromRAM is not a constant.

How can I fix this error? Is there a way to copy data_fromRAM into a constant variable and then do the operations? Or should I take a different approach?

Note: output reg [15:0] datatoRAM;

edit : If data_fromRAM = 40, then with this line: WNext = {W[data_fromRAM[3:0] - 1:0], W[15:data_fromRAM[3:0]]}; I am trying to rotate WNext right with the four least significant bits of data_fromRAM. 40 is equal to 101000 in binary and the four lowest bits give us 1000 which is 8 in decimal. So I will rotate WNext right by 8 bits and what I mean by rotate is basically shifting but new bits are the ones we were going to lose if we only did the shifting (eg. rotate 1000110 by 3 = 1101000)

If data_fromRAM is greater than 47, again I want to rotate WNext but this time left rather than right (again it's rotating by lowest four bits of data_fromRAM). So again, as in shifting, I want to move all the values to the left but the bits that are coming from right are the ones that were lost from left when shifting.

答:
I think based on the value of data_fromRAM, you are trying to "scramble" your data in W. Assuming WNext is also a 16-bit variable, you can use:

```<code>if(data_fromRAM < 16)
    WNext = W >> data_fromRAM;
else if (data_fromRAM > 16 & data_fromRAM < 31)
    WNext = W << data_fromRAM[3:0];
else if (data_fromRAM > 32 & data_fromRAM > 47)
    WNext = (W << (16-data_fromRAM[3:0])) | (W >> data_fromRAM[3:0]);
else
    WNext = (W << data_fromRAM[3:0]) | (W >> (16-data_fromRAM[3:0]));
</code>```

Body:
I have this block of code. I am trying to rotate WNext by the lower 4 bits of data_fromRAM.

input clk, rst;

input wire [15:0] data_fromRAM;
output reg [15:0] data_toRAM;
output reg wrEn;

// 12 can be made smaller so that it fits in the FPGA
output reg [12:0] addr_toRAM;
output reg [12:0] PC; // This has been added as an output for TB purposes
output reg [15:0] W; // This has been added as an output for TB purposes

reg [12:0] PCNext;
reg [ 2:0] opcode, opcodeNext,state, stateNext;
reg [12:0] operand, operandNext;
reg [15:0] num, numNext, WNext;

always @*begin
    WNext = W;
    PCNext = PC;
    stateNext    = state;
    opcodeNext   = opcode;
    operandNext = operand;
    numNext     = num;
    addr_toRAM   = 0;
    wrEn         = 0;
    data_toRAM   = 0;
//here I have if(rst)
else
    case(state)
//other cases
        2: begin
            PCNext = PC + 1;
            WNext = W;
            opcodeNext   = opcode;
            operandNext = operand;
            addr_toRAM   = 0;
            numNext     = data_fromRAM;
            wrEn         = 0;
            data_toRAM   = 0;
            stateNext    = 0;
            case (opcodeNext)
                ... //I excluded other cases
                3'b010: begin //SRRL
                    if(data_fromRAM < 16) WNext = W >> data_fromRAM;
                    else if (data_fromRAM > 16 & data_fromRAM < 31) WNext = W << data_fromRAM[3:0];
                    else if (data_fromRAM > 32 & data_fromRAM > 47) WNext = {W[data_fromRAM[3:0] - 1:0], W[15:data_fromRAM[3:0]]};
                    else WNext = {W[15 - data_fromRAM[3:0]:0], W[15:16 - data_fromRAM[3:0]]};
                end

But I am getting the error:

data_fromRAM is not a constant.

How can I fix this error? Is there a way to copy data_fromRAM into a constant variable and then do the operations? Or should I take a different approach?

Note: output reg [15:0] datatoRAM;

edit : If data_fromRAM = 40, then with this line: WNext = {W[data_fromRAM[3:0] - 1:0], W[15:data_fromRAM[3:0]]}; I am trying to rotate WNext right with the four least significant bits of data_fromRAM. 40 is equal to 101000 in binary and the four lowest bits give us 1000 which is 8 in decimal. So I will rotate WNext right by 8 bits and what I mean by rotate is basically shifting but new bits are the ones we were going to lose if we only did the shifting (eg. rotate 1000110 by 3 = 1101000)

If data_fromRAM is greater than 47, again I want to rotate WNext but this time left rather than right (again it's rotating by lowest four bits of data_fromRAM). So again, as in shifting, I want to move all the values to the left but the bits that are coming from right are the ones that were lost from left when shifting.

Body:
I think based on the value of data_fromRAM, you are trying to "scramble" your data in W. Assuming WNext is also a 16-bit variable, you can use:

if(data_fromRAM < 16)
    WNext = W >> data_fromRAM;
else if (data_fromRAM > 16 & data_fromRAM < 31)
    WNext = W << data_fromRAM[3:0];
else if (data_fromRAM > 32 & data_fromRAM > 47)
    WNext = (W << (16-data_fromRAM[3:0])) | (W >> data_fromRAM[3:0]);
else
    WNext = (W << data_fromRAM[3:0]) | (W >> (16-data_fromRAM[3:0]));


问:
WCF Callback address dictionary with Load Balancing
Current Environment
We are using Publisher/subscriber model using WCF callbacks. We have WCF service hosted in IIS on a single Web server. Any client can subscribe/unsubscribe by calling service methods and we save/remove callback address respectively with client ID in dictionary i.e.,

PrivateShared _currentSubscribers As New Dictionary(Of UShort, ICallbackService)()

Dictionary is static member and is used across the web application (in memory not persistent)

New Environment
We are shifting our websites to new servers now. We will have two servers hosting the service with load balancer in between.

Now we need to figure out that how we are going to maintain list of subscriber which can be available on both servers. Certainly, we can’t use the same in memory dictionary in this scenario.
We are searching for any method in which we can share dictionary among the servers.

We have tried saving in db but its not serializable or usable on other server.

We have spend some good time in searching but didn't find any solution for this in which we can share callback address among servers.

Can someone guide us on how we can acheive this? or any other option that we can use?

I would be really thankful to you for your help. Waiting for your kind response.

答: You cannot share that callback dictionary between servers. Each server must have its own dictionary maintaining its own clients and because of that you must use load balancing algorithm with session affinity (sticky sessions). This algorithm will forward all requests from single client to the same server. </p>


问:
Javascript empty validation not working before sending to database
For some reason my JavaScript validation function is not working before sending the info to the database, I tried my best to fix it but it just wont work here is my code:

<form name="myForm" action="connectform.php" onsubmit="return validateForm()" method="POST" required>

Contact Me

      First Name :
      <input type="text" name="firstName" id="firstName" placeholder="Enter Your First Name">

      Last Name :
      <input type="text" name="lastName"  placeholder="Enter Your Last Name">

      Email
      <input type="email" name="email" id="email" placeholder="Enter Your Email">

      Message :
      <input type="text" name="info" id="info">

    <input type="submit" id='validate' class="btn" />

</form>
```

<p>and here is my javascript code (i only did it once for testing it for the first name):</p>

<pre class="lang-js prettyprint-override"><code><script>
  function validateForm() {
    var x = document.forms["myForm"]["firstName"].value;
    if (x==null || x=="") {
      alert("First name must be filled out");
      return false;
    }
</script>
</code>```

Here is my PHP code:

<?php
  $firstName = $_POST['firstName'];
  $lastName = $_POST['lastName'];
  $email = $_POST['email'];
  $info = $_POST['info'];

  //Database Connection
  $conn = new mysqli('localhost', 'root', '', 'webpage_project');

  if ($conn->connect_error) {
      echo "$conn->connect_error";
  die("Connection Failed : ". $conn->connect_error);
  }
  else{
      $stmt = $conn->prepare("insert into contactme(firstName, lastName, email, info) values (?, ?, ?, ?)");
      $stmt->bind_param("ssss", $firstName, $lastName, $email, $info);
  $execval = $stmt->execute();
      $echo'Sent Sucessfully';
  $stmt->close();
  $conn->close();
  }
?>
```

答: Try changing your condition of if to this  if(!x) , your if condition is not catering checks for undefined values, hence it wont pass the if condition if the value of x is undefined.

Body:
For some reason my JavaScript validation function is not working before sending the info to the database, I tried my best to fix it but it just wont work here is my code:

<form name="myForm" action="connectform.php" onsubmit="return validateForm()" method="POST" required>

Contact Me

      First Name :
      <input type="text" name="firstName" id="firstName" placeholder="Enter Your First Name">

      Last Name :
      <input type="text" name="lastName"  placeholder="Enter Your Last Name">

      Email
      <input type="email" name="email" id="email" placeholder="Enter Your Email">

      Message :
      <input type="text" name="info" id="info">

    <input type="submit" id='validate' class="btn" />

</form>

and here is my javascript code (i only did it once for testing it for the first name):

Here is my PHP code:

<?php
  $firstName = $_POST['firstName'];
  $lastName = $_POST['lastName'];
  $email = $_POST['email'];
  $info = $_POST['info'];

  //Database Connection
  $conn = new mysqli('localhost', 'root', '', 'webpage_project');

  if ($conn->connect_error) {
      echo "$conn->connect_error";
  die("Connection Failed : ". $conn->connect_error);
  }
  else{
      $stmt = $conn->prepare("insert into contactme(firstName, lastName, email, info) values (?, ?, ?, ?)");
      $stmt->bind_param("ssss", $firstName, $lastName, $email, $info);
  $execval = $stmt->execute();
      $echo'Sent Sucessfully';
  $stmt->close();
  $conn->close();
  }
?>


问:
Docker overlay2 eating Disk Space
Below is the file system in overlay2 eating disk space, on Ubuntu Linux 18.04 LTS

Disk space of server 125GB

```<code>overlay         124G  6.0G  113G   6% /var/lib/docker/overlay2/9ac0eb938cd2a50bb87e8ed13605d3f09214fdd9c8967f18dfc3f9432701fea7/merged
overlay         124G  6.0G  113G   6% /var/lib/docker/overlay2/397b099799212060ee7a4718660aa13aba8aa1fbb92f4d88d86fbad94e572847/merged
shm              64M     0   64M   0% /var/lib/docker/containers/7ffb129016d187a61a31c33f9e468b98d0ac7ab1771b87631f6caade5b84adc6/mounts/shm
overlay         124G  6.0G  113G   6% /var/lib/docker/overlay2/df7c4acee73f7aa2536d2a8929a48241bc8e92a5f7b9cb63ab70cea731b52cec/merged
</code>```

答:
Another solution if the above doesn't work is setup a log rotation.

```<code>nano /etc/docker/daemon.json
</code>```

if not found

```<code>cat > daemon.json
</code>```

Add the following lines to file:

```<code>{
"log-driver": "json-file",
"log-opts": {
    "max-size": "10m",
    "max-file": "3"
    }
}
</code>```

Restart the docker daemon: systemctl restart docker

Please refer: How to setup log rotation post installation

Title: Docker overlay2 eating Disk Space

Body:
Below is the file system in overlay2 eating disk space, on Ubuntu Linux 18.04 LTS

Disk space of server 125GB

overlay         124G  6.0G  113G   6% /var/lib/docker/overlay2/9ac0eb938cd2a50bb87e8ed13605d3f09214fdd9c8967f18dfc3f9432701fea7/merged
overlay         124G  6.0G  113G   6% /var/lib/docker/overlay2/397b099799212060ee7a4718660aa13aba8aa1fbb92f4d88d86fbad94e572847/merged
shm              64M     0   64M   0% /var/lib/docker/containers/7ffb129016d187a61a31c33f9e468b98d0ac7ab1771b87631f6caade5b84adc6/mounts/shm
overlay         124G  6.0G  113G   6% /var/lib/docker/overlay2/df7c4acee73f7aa2536d2a8929a48241bc8e92a5f7b9cb63ab70cea731b52cec/merged

Body:
Another solution if the above doesn't work is setup a log rotation.

nano /etc/docker/daemon.json

if not found

cat > daemon.json

Add the following lines to file:

{
"log-driver": "json-file",
"log-opts": {
    "max-size": "10m",
    "max-file": "3"
    }
}

Restart the docker daemon: systemctl restart docker

Please refer: How to setup log rotation post installation


问:
Java to insert the input values into ArrayList and print sum of elements present at even index of the ArrayList using Iterator
I have written this code My Problem is it is taking the length. of array as input but not reading the elements of array We have to use iterator for reading all Inputs.</p>

```<code>import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.*;
public class arrayl {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        ArrayList < Integer > list = new ArrayList < Integer > ();
        System.out.println(" Enter the length of array :");

        int n = sc.nextInt();
        int array[] = new int[n];

        System.out.println("Enter List : ");

        for (Iterator < Integer > itr = list.iterator(); itr.hasNext();) {
            if (itr.next() != null) {

                while (itr.hasNext()) {
                    Integer thisInt = itr.next();
                    if (thisInt % 2 == 0) {
                        list.add(thisInt);
                    }
                    System.out.println(" Even Index Position Sum : ");

                }
            }

        }
    }

}
</code>```

答: You haven't added anything to the ArrayList, so your for loop doesn't do anything.  You have to add something to it first using list.add(element) where element is an int.

Body:
I have written this code My Problem is it is taking the length. of array as input but not reading the elements of array We have to use iterator for reading all Inputs.

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.*;
public class arrayl {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        ArrayList < Integer > list = new ArrayList < Integer > ();
        System.out.println(" Enter the length of array :");

        int n = sc.nextInt();
        int array[] = new int[n];

        System.out.println("Enter List : ");

        for (Iterator < Integer > itr = list.iterator(); itr.hasNext();) {
            if (itr.next() != null) {

                while (itr.hasNext()) {
                    Integer thisInt = itr.next();
                    if (thisInt % 2 == 0) {
                        list.add(thisInt);
                    }
                    System.out.println(" Even Index Position Sum : ");

                }
            }

        }
    }

}


问:
Terraform 403 Forbidden Error while executing terraform plan
We are currently using S3 as our backend for preserving the tf state file. While executing terraform plan we are receiving the below error:

Error: Forbidden: Forbidden
        status code: 403, request id: 18CB0EA827E6FE0F, host id: 8p0TMjzvooEBPNakoRsO3RtbARk01KY1KK3z93Lwyvh1Nx6sw4PpRyfoqNKyG2ryMNAHsdCJ39E=
```

<p>We have enabled the debug mode and below is the error message we have noticed.</p>

<pre class="lang-sh prettyprint-override"><code>2020-05-31T20:02:20.842+0400 [DEBUG] plugin.terraform-provider-aws_v2.64.0_x4: Accept-Encoding: gzip
2020-05-31T20:02:20.842+0400 [DEBUG] plugin.terraform-provider-aws_v2.64.0_x4:
2020-05-31T20:02:20.842+0400 [DEBUG] plugin.terraform-provider-aws_v2.64.0_x4:
2020-05-31T20:02:20.842+0400 [DEBUG] plugin.terraform-provider-aws_v2.64.0_x4: -----------------------------------------------------
2020/05/31 20:02:20 [ERROR] <root>: eval: *terraform.EvalRefresh, err: Forbidden: Forbidden
        status code: 403, request id: 2AB56118732D7165, host id: 5sM6IwjkufaDg1bt5Swh5vcQD2hd3fSf9UqAtlL4hVzVaGPRQgvs1V8S3e/h3ta0gkRcGI7GvBM=
2020/05/31 20:02:20 [ERROR] <root>: eval: *terraform.EvalSequence, err: Forbidden: Forbidden
        status code: 403, request id: 2AB56118732D7165, host id: 5sM6IwjkufaDg1bt5Swh5vcQD2hd3fSf9UqAtlL4hVzVaGPRQgvs1V8S3e/h3ta0gkRcGI7GvBM=
2020/05/31 20:02:20 [TRACE] [walkRefresh] Exiting eval tree: aws_s3_bucket_object.xxxxxx
2020/05/31 20:02:20 [TRACE] vertex "aws_s3_bucket_object.xxxxxx": visit complete
2020/05/31 20:02:20 [TRACE] vertex "aws_s3_bucket_object.xxxxxx: dynamic subgraph encountered errors
2020/05/31 20:02:20 [TRACE] vertex "aws_s3_bucket_object.xxxxxx": visit complete
</code>```

We have tried reverting the code and tfstate file to a working version and tried. Also, deleted the tfstate file locally as well. Still the same error.

s3 bucket policy is as below:

{
            "Sid": "DelegateS3Access",
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::xxxxxx:role/Administrator"
            },
            "Action": [
                "s3:ListBucket",
                "s3:GetObject",
                "s3:GetObjectTagging"
            ],
            "Resource": [
                "arn:aws:s3:::xxxxxx/*",
                "arn:aws:s3:::xxxxxx"
            ]
        }
```

The same role is being assumed by terraform for execution and still it fails. I have emptied the bucket policy as well and tried but didn't see any success. I understand it is something to do with the bucket policy itself, but not sure how to fix it.

Any pointers to fix this issue is highly appreciated.

答:
One thing to check is who you are (from an AWS API perspective), before running Terraform:

```<code>aws sts get-caller-identity
</code>```

If the output is like this, then you are authenticated as an IAM User who will not have access to the bucket since it grants access to an IAM Role and not an IAM User:

```<code>{
    "UserId": "AIDASAMPLEUSERID",
    "Account": "123456789012",
    "Arn": "arn:aws:iam::123456789012:user/DevAdmin"
}
</code>```

In that case, you'll need to configure AWS CLI to assume arn:aws:iam::xxxxxx:role/Administrator.

```<code>[profile administrator]
role_arn = arn:aws:iam::xxxxxx:role/Administrator
source_profile = user1
</code>```

Read more on that process here:

https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-role.html

If get-caller-identity returns something like this, then you are assuming the IAM Role and the issue is likely with the actions in the Bucket policy:

```<code>{
    "UserId": "AIDASAMPLEUSERID",
    "Account": "123456789012",
    "Arn": "arn:aws:iam::123456789012:assumed-role/Administrator/role-session-name"
}
</code>```

According to the Backend type: S3 documentation, you also need s3:PutObject:

```<code>{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": "s3:ListBucket",
      "Resource": "arn:aws:s3:::mybucket"
    },
    {
      "Effect": "Allow",
      "Action": ["s3:GetObject", "s3:PutObject"],
      "Resource": "arn:aws:s3:::mybucket/path/to/my/key"
    }
  ]
}
</code>```

While I can't see why PutObject would be needed for plan, it is conceivably what is causing this Forbidden error.

You can also look for denied S3 actions in CloudTrail if you have enabled that.

Body:
We are currently using S3 as our backend for preserving the tf state file. While executing terraform plan we are receiving the below error:

Error: Forbidden: Forbidden
        status code: 403, request id: 18CB0EA827E6FE0F, host id: 8p0TMjzvooEBPNakoRsO3RtbARk01KY1KK3z93Lwyvh1Nx6sw4PpRyfoqNKyG2ryMNAHsdCJ39E=

We have enabled the debug mode and below is the error message we have noticed.

2020-05-31T20:02:20.842+0400 [DEBUG] plugin.terraform-provider-aws_v2.64.0_x4: Accept-Encoding: gzip
2020-05-31T20:02:20.842+0400 [DEBUG] plugin.terraform-provider-aws_v2.64.0_x4:
2020-05-31T20:02:20.842+0400 [DEBUG] plugin.terraform-provider-aws_v2.64.0_x4:
2020-05-31T20:02:20.842+0400 [DEBUG] plugin.terraform-provider-aws_v2.64.0_x4: -----------------------------------------------------
2020/05/31 20:02:20 [ERROR] <root>: eval: *terraform.EvalRefresh, err: Forbidden: Forbidden
        status code: 403, request id: 2AB56118732D7165, host id: 5sM6IwjkufaDg1bt5Swh5vcQD2hd3fSf9UqAtlL4hVzVaGPRQgvs1V8S3e/h3ta0gkRcGI7GvBM=
2020/05/31 20:02:20 [ERROR] <root>: eval: *terraform.EvalSequence, err: Forbidden: Forbidden
        status code: 403, request id: 2AB56118732D7165, host id: 5sM6IwjkufaDg1bt5Swh5vcQD2hd3fSf9UqAtlL4hVzVaGPRQgvs1V8S3e/h3ta0gkRcGI7GvBM=
2020/05/31 20:02:20 [TRACE] [walkRefresh] Exiting eval tree: aws_s3_bucket_object.xxxxxx
2020/05/31 20:02:20 [TRACE] vertex "aws_s3_bucket_object.xxxxxx": visit complete
2020/05/31 20:02:20 [TRACE] vertex "aws_s3_bucket_object.xxxxxx: dynamic subgraph encountered errors
2020/05/31 20:02:20 [TRACE] vertex "aws_s3_bucket_object.xxxxxx": visit complete

We have tried reverting the code and tfstate file to a working version and tried. Also, deleted the tfstate file locally as well. Still the same error.

s3 bucket policy is as below:

{
            "Sid": "DelegateS3Access",
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::xxxxxx:role/Administrator"
            },
            "Action": [
                "s3:ListBucket",
                "s3:GetObject",
                "s3:GetObjectTagging"
            ],
            "Resource": [
                "arn:aws:s3:::xxxxxx/*",
                "arn:aws:s3:::xxxxxx"
            ]
        }

The same role is being assumed by terraform for execution and still it fails. I have emptied the bucket policy as well and tried but didn't see any success. I understand it is something to do with the bucket policy itself, but not sure how to fix it.

Any pointers to fix this issue is highly appreciated.

Body:
One thing to check is who you are (from an AWS API perspective), before running Terraform:

aws sts get-caller-identity

If the output is like this, then you are authenticated as an IAM User who will not have access to the bucket since it grants access to an IAM Role and not an IAM User:

{
    "UserId": "AIDASAMPLEUSERID",
    "Account": "123456789012",
    "Arn": "arn:aws:iam::123456789012:user/DevAdmin"
}

In that case, you'll need to configure AWS CLI to assume arn:aws:iam::xxxxxx:role/Administrator.

[profile administrator]
role_arn = arn:aws:iam::xxxxxx:role/Administrator
source_profile = user1

Read more on that process here:

https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-role.html

If get-caller-identity returns something like this, then you are assuming the IAM Role and the issue is likely with the actions in the Bucket policy:

{
    "UserId": "AIDASAMPLEUSERID",
    "Account": "123456789012",
    "Arn": "arn:aws:iam::123456789012:assumed-role/Administrator/role-session-name"
}

According to the Backend type: S3 documentation, you also need s3:PutObject:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": "s3:ListBucket",
      "Resource": "arn:aws:s3:::mybucket"
    },
    {
      "Effect": "Allow",
      "Action": ["s3:GetObject", "s3:PutObject"],
      "Resource": "arn:aws:s3:::mybucket/path/to/my/key"
    }
  ]
}

While I can't see why PutObject would be needed for plan, it is conceivably what is causing this Forbidden error.

You can also look for denied S3 actions in CloudTrail if you have enabled that.


问:
OOm - cannot run StyleGAN2 despite reducing batch size
I am trying to run StyleGAN2 using a cluster equipped with eight GPUs (NVIDIA GeForce RTX 2080). At present, I am using the following configuration in training_loop.py:

```<code>minibatch_size_dict     = {4: 512, 8: 256, 16: 128, 32: 64, 64: 32},       # Resolution-specific overrides.
minibatch_gpu_base      = 8,        # Number of samples processed at a time by one GPU.
minibatch_gpu_dict      = {},       # Resolution-specific overrides.
G_lrate_base            = 0.001,    # Learning rate for the generator.
G_lrate_dict            = {},       # Resolution-specific overrides.
D_lrate_base            = 0.001,    # Learning rate for the discriminator.
D_lrate_dict            = {},       # Resolution-specific overrides.
lrate_rampup_kimg       = 0,        # Duration of learning rate ramp-up.
tick_kimg_base          = 4,        # Default interval of progress snapshots.
tick_kimg_dict          = {4:10, 8:10, 16:10, 32:10, 64:10, 128:8, 256:6, 512:4}): # Resolution-specific overrides.
</code>```

I am training using a set of 512x52 pixel images. After a couple of iterations, I get the error message reported below and it looks like the script stops running (using watch nvidia-smi, we have that both the temperature and the fan activity for the GPUs decreases). I already reduced the batch size but it looks like the problem is somewhere else. Do you have any tip on how to fix this?

I was able to run StyleGAN with the same dataset. In the paper they say that StyleGAN2 should be less heavy, so I am a bit surprised.

Here is the error message I get:

```<code>2019-12-16 18:22:54.909009: E tensorflow/stream_executor/cuda/cuda_driver.cc:828] failed to allocate 334.11M (350338048 bytes) from device: CUDA_ERROR_OUT_OF_MEMORY: out of memory
2019-12-16 18:22:54.909087: W tensorflow/core/common_runtime/bfc_allocator.cc:314] Allocator (GPU_0_bfc) ran out of memory trying to allocate 129.00MiB (rounded to 135268352).  Current allocation summary follows.
2019-12-16 18:22:54.918750: W tensorflow/core/common_runtime/bfc_allocator.cc:319] **_***************************_*****x****x******xx***_******************************_***************
2019-12-16 18:22:54.918808: W tensorflow/core/framework/op_kernel.cc:1502] OP_REQUIRES failed at conv_grad_input_ops.cc:903 : Resource exhausted: OOM when allocating tensor with shape[4,128,257,257] and type float on /job:localhost/replica:0/task:0/device:GPU:0 by allocator GPU_0_bfc
</code>```

答:
The config-f model for StyleGAN2 is actually bigger than StyleGAN1. Try using a less VRAM consuming configuration like config-e. You can actually change the configuration of the model by passing a flag in your python command like so: https://github.com/NVlabs/stylegan2/blob/master/run_training.py#L144

In my case, I'm able to train StyleGAN2 with config-e on 2 RTX 2080ti.

Body:
I am trying to run StyleGAN2 using a cluster equipped with eight GPUs (NVIDIA GeForce RTX 2080). At present, I am using the following configuration in training_loop.py:

minibatch_size_dict     = {4: 512, 8: 256, 16: 128, 32: 64, 64: 32},       # Resolution-specific overrides.
minibatch_gpu_base      = 8,        # Number of samples processed at a time by one GPU.
minibatch_gpu_dict      = {},       # Resolution-specific overrides.
G_lrate_base            = 0.001,    # Learning rate for the generator.
G_lrate_dict            = {},       # Resolution-specific overrides.
D_lrate_base            = 0.001,    # Learning rate for the discriminator.
D_lrate_dict            = {},       # Resolution-specific overrides.
lrate_rampup_kimg       = 0,        # Duration of learning rate ramp-up.
tick_kimg_base          = 4,        # Default interval of progress snapshots.
tick_kimg_dict          = {4:10, 8:10, 16:10, 32:10, 64:10, 128:8, 256:6, 512:4}): # Resolution-specific overrides.

I am training using a set of 512x52 pixel images. After a couple of iterations, I get the error message reported below and it looks like the script stops running (using watch nvidia-smi, we have that both the temperature and the fan activity for the GPUs decreases). I already reduced the batch size but it looks like the problem is somewhere else. Do you have any tip on how to fix this?

I was able to run StyleGAN with the same dataset. In the paper they say that StyleGAN2 should be less heavy, so I am a bit surprised.

Here is the error message I get:

2019-12-16 18:22:54.909009: E tensorflow/stream_executor/cuda/cuda_driver.cc:828] failed to allocate 334.11M (350338048 bytes) from device: CUDA_ERROR_OUT_OF_MEMORY: out of memory
2019-12-16 18:22:54.909087: W tensorflow/core/common_runtime/bfc_allocator.cc:314] Allocator (GPU_0_bfc) ran out of memory trying to allocate 129.00MiB (rounded to 135268352).  Current allocation summary follows.
2019-12-16 18:22:54.918750: W tensorflow/core/common_runtime/bfc_allocator.cc:319] **_***************************_*****x****x******xx***_******************************_***************
2019-12-16 18:22:54.918808: W tensorflow/core/framework/op_kernel.cc:1502] OP_REQUIRES failed at conv_grad_input_ops.cc:903 : Resource exhausted: OOM when allocating tensor with shape[4,128,257,257] and type float on /job:localhost/replica:0/task:0/device:GPU:0 by allocator GPU_0_bfc


问:
The term 'scaffold-dbcontext' is not recognized as the name of a cmdlet, function, script file, or operable program
When trying to scaffold with asp.net core this command

scaffold-dbcontext "Data Source=(local);Initial
Catalog=MyDb;Integrated Security=True;"
Microsoft.EntityFrameworkCore.sqlserver -outputdir Models
```
<p>Gives this error.</p>
<blockquote>
<p>scaffold-dbcontext : The term 'scaffold-dbcontext' is not recognized
as the name of a cmdlet, function, script file, or operable program.
Check the spelling of the  name, or if a path was included, verify
that the path is correct and try again. At line:1 char:1</p>
<pre class="lang-none prettyprint-override"><code>+ scaffold-dbcontext "Data Source=(local);Initial Catalog=MyDB;In ...
+ ~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (scaffold-dbcontext:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException
</code>```

I have tried the solution here, but it does not work for me.

Any idea what the cause/cure could be?

答:
Had the same problem. In my case i was missing some dependencies, so make sure that you have the following one :

Microsoft.EntityFrameworkCore

Microsoft.EntityFrameworkCore.SqlServer

Microsoft.EntityFrameworkCore.Tools

Hope this would help. :)

Body:
When trying to scaffold with asp.net core this command

scaffold-dbcontext "Data Source=(local);Initial
Catalog=MyDb;Integrated Security=True;"
Microsoft.EntityFrameworkCore.sqlserver -outputdir Models

Gives this error.

scaffold-dbcontext : The term 'scaffold-dbcontext' is not recognized
as the name of a cmdlet, function, script file, or operable program.
Check the spelling of the  name, or if a path was included, verify
that the path is correct and try again. At line:1 char:1

+ scaffold-dbcontext "Data Source=(local);Initial Catalog=MyDB;In ...
+ ~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (scaffold-dbcontext:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

I have tried the solution here, but it does not work for me.

Any idea what the cause/cure could be?


问:
how to refresh FCM token with js
I am setting up FCM for my React web push notification and it is doing everything properly, except I don't know how to refresh token when it's expired
I have an FCMListener function which its code is as follow

```<code>    navigator.serviceWorker
      .register("/static-files/firebase-messaging-sw.js")
      .then((registration) => {
        firebase.initializeApp(settings.getConfig().FIREBASE_CONFIG);
        const messaging = firebase.messaging();
        messaging.useServiceWorker(registration);

        try {
          messaging
            .requestPermission()
            .then(() => {
              return messaging.getToken();
            })
            .then((token) => {
              let topic = `${userInfo.is_host ? "host" : "guest"}`;
              if (token) {
                this.subscribeToTopic(topic, token);
                this.sendTokenToServer({
                  os: "web",
                  push_token: token,
                });
              } else {
                messaging.onTokenRefresh(() => {
                  messaging
                    .getToken()
                    .then((refreshedToken) => {
                      this.subscribeToTopic(topic, token);
                      this.sendTokenToServer({
                        os: "web",
                        push_token: refreshedToken,
                      });
                    })
                    .catch((err) => {
                      console.log("Unable to retrieve refreshed token ", err);
                    });
                });
              }
            });
        } catch (error) {
          if (error.code === "messaging/permission-blocked") {
            console.log("Please Unblock Notification Request Manually");
          } else {
            console.log("Error Occurred", error);
          }
        }
        messaging.onMessage((payload) => {
          console.log("Notification Received", payload);
          alert(payload.notification.body);
        });
      });
  };
}
</code>```

as I don't know how to expire a firebase token and I can't test what happens when the token is expired I don't know if the part where I am trying to get refreshedToken is right or not or even if this is the proper way to get refreshed token or not. I would really appreciate any hint and advise

答: For testing purposes you can delete the FCM token through the API by calling the deleteToken API. After doing that, reload the page, and your onTokenRefresh should fire.

Title: how to refresh FCM token with js

Body:
I am setting up FCM for my React web push notification and it is doing everything properly, except I don't know how to refresh token when it's expired
I have an FCMListener function which its code is as follow

    navigator.serviceWorker
      .register("/static-files/firebase-messaging-sw.js")
      .then((registration) => {
        firebase.initializeApp(settings.getConfig().FIREBASE_CONFIG);
        const messaging = firebase.messaging();
        messaging.useServiceWorker(registration);

        try {
          messaging
            .requestPermission()
            .then(() => {
              return messaging.getToken();
            })
            .then((token) => {
              let topic = `${userInfo.is_host ? "host" : "guest"}`;
              if (token) {
                this.subscribeToTopic(topic, token);
                this.sendTokenToServer({
                  os: "web",
                  push_token: token,
                });
              } else {
                messaging.onTokenRefresh(() => {
                  messaging
                    .getToken()
                    .then((refreshedToken) => {
                      this.subscribeToTopic(topic, token);
                      this.sendTokenToServer({
                        os: "web",
                        push_token: refreshedToken,
                      });
                    })
                    .catch((err) => {
                      console.log("Unable to retrieve refreshed token ", err);
                    });
                });
              }
            });
        } catch (error) {
          if (error.code === "messaging/permission-blocked") {
            console.log("Please Unblock Notification Request Manually");
          } else {
            console.log("Error Occurred", error);
          }
        }
        messaging.onMessage((payload) => {
          console.log("Notification Received", payload);
          alert(payload.notification.body);
        });
      });
  };
}

as I don't know how to expire a firebase token and I can't test what happens when the token is expired I don't know if the part where I am trying to get refreshedToken is right or not or even if this is the proper way to get refreshed token or not. I would really appreciate any hint and advise


问:
How to use showTimePicker as Widget in flutter?
I want the user to pick the date and time, for that there is date time picker dialogue.

But, is there a way that, I could show the date-time persistently on some flutter widget and use like any other widget?

```<code>Container(
   child: showTimePicker(
          context: context,
          initialTime: TimeOfDay.now(),
          builder: (BuildContext context, Widget child) {
            return Theme(
              data: ThemeData.dark(),
              child: child,
            );
          },
        );
}
</code>```

but I cannot use showTimePicker as Widget.

How to use showTimePicker() as widget? so that other widgets can be built on top of it.

答:
I ran into the problem just like you some time ago and I copied the source code and made my custom widget. Now, it can be used like any widget. If you want to adopt this, I want to mention a couple of things.

I am not sure if this works well with localization, I did not test that.

I am not sure if this works on other themes than the light theme, I only tested on the light theme.

You can find the code here.
https://gist.github.com/mithunadhikari40/b55b9990ebc15d0d8bf70fd3f87709b0

Usage:
Copy the code from the above link, create a dart file, paste the code and use it like this:

```<code>                     SizedBox(
                        child: TimePickerDialog(
                        initialTime: TimeOfDay.fromDateTime(DateTime.now()),
                        onTimeChange: (TimeOfDay time) {
                          print(
                              "What we get the value of the time is now $time");
                        },
                      ),
                    ),
</code>```

Body:
I want the user to pick the date and time, for that there is date time picker dialogue.

But, is there a way that, I could show the date-time persistently on some flutter widget and use like any other widget?

Container(
   child: showTimePicker(
          context: context,
          initialTime: TimeOfDay.now(),
          builder: (BuildContext context, Widget child) {
            return Theme(
              data: ThemeData.dark(),
              child: child,
            );
          },
        );
}

but I cannot use showTimePicker as Widget.

How to use showTimePicker() as widget? so that other widgets can be built on top of it.

Body:
I ran into the problem just like you some time ago and I copied the source code and made my custom widget. Now, it can be used like any widget. If you want to adopt this, I want to mention a couple of things.

I am not sure if this works well with localization, I did not test that.

I am not sure if this works on other themes than the light theme, I only tested on the light theme.

You can find the code here.
https://gist.github.com/mithunadhikari40/b55b9990ebc15d0d8bf70fd3f87709b0

Usage:
Copy the code from the above link, create a dart file, paste the code and use it like this:

                     SizedBox(
                        child: TimePickerDialog(
                        initialTime: TimeOfDay.fromDateTime(DateTime.now()),
                        onTimeChange: (TimeOfDay time) {
                          print(
                              "What we get the value of the time is now $time");
                        },
                      ),
                    ),


问:
This is an example seen in w3school on overflow: hidden used to show background color of a ul tag when the list is floated
This is the link

I understand that the overflow property determines what to do with “the excess part” of something, for example, to hide or to put a scrollbar. In the example, if I erase the overflow property, the ul will be just a line as the list is floated.
How is the overflow: hidden is getting the ul back?

答:
overflow: hidden is not getting the ul back here. The color of the  tag inside the
 are white because of which they are not visible. Also because of float:"left" on the
, the background-color:"#333" of the
 is not visible. All the css properties together are causing the effect.

Body: overflow: hidden is not getting the ul back here. The color of the <a> tag inside the <li> are white because of which they are not visible. Also because of float:"left" on the <li>, the background-color:"#333" of the <ul> is not visible. All the css properties together are causing the effect.


问:
Removing newlines from buffer (useful when importing to ORG to unwrap the text while keeping paragraphs)
This function:

```<code>(defun remove-newlines-in-region ()
  "Removes all newlines in the region."
  (interactive)
  (save-restriction
    (narrow-to-region (point) (mark))
    (goto-char (point-min))
    (while (search-forward "\n" nil t) (replace-match "" nil t))))
</code>```

will remove EVERY newline in a text. This is useful when importing to org creates wrapped text. We want then to unwrap the text per paragraph (not in all buffer, which would create a whole block without distinction between paragraphs).

How would we add the condition that if should only apply to one newlines, and not 2 consecutive newlines? Thanks!

SOLUTION: use UnfillRegion. It does the job!

答:
After searching for the first newline, you can use looking-at-p to see whether the next character is a second newline. So instead of your

```<code>(while (search-forward "\n" nil t) (replace-match "" nil t))
</code>```

you can use

```<code>(while (search-forward "\n" nil t)
  (unless (looking-at-p "\n")  (replace-match "" nil t)))
</code>```

Body:
This function:

(defun remove-newlines-in-region ()
  "Removes all newlines in the region."
  (interactive)
  (save-restriction
    (narrow-to-region (point) (mark))
    (goto-char (point-min))
    (while (search-forward "\n" nil t) (replace-match "" nil t))))

will remove EVERY newline in a text. This is useful when importing to org creates wrapped text. We want then to unwrap the text per paragraph (not in all buffer, which would create a whole block without distinction between paragraphs).

How would we add the condition that if should only apply to one newlines, and not 2 consecutive newlines? Thanks!

SOLUTION: use UnfillRegion. It does the job!

Body:
After searching for the first newline, you can use looking-at-p to see whether the next character is a second newline. So instead of your

(while (search-forward "\n" nil t) (replace-match "" nil t))

you can use

(while (search-forward "\n" nil t)
  (unless (looking-at-p "\n")  (replace-match "" nil t)))


问:
Auto add dashes to entryboxes in tkinter
Is there a way to auto add dashes in a phone number when the person types their phone number like for say phone number is 5551111234, but when they type it in the entry box the number should appear with hyphen b/w the number automatically like 555-1111234.

答:
I used a combination of both this example of tracing tkinter variables and combined it with this answer, I am not 100% sure if this is the correct American formatting because I live in the UK and we format things differently here, but this is the rough example of how that would work:

# Python program to trace
# variable in tkinter

from tkinter import *
import re

root = Tk()

my_var = StringVar()

# defining the callback function (observer)

def phone_format(phone_number):
    try:
        clean_phone_number = re.sub('[^0-9]+', '', phone_number)
        formatted_phone_number = re.sub(
            r"(\d)(?=(\d{3})+(?!\d))", r"\1-", "%d" % int(clean_phone_number[:-1])) + clean_phone_number[-1]
        return formatted_phone_number
    except ValueError:
        return phone_number

def my_callback(var, indx, mode):
    my_var.set(phone_format(my_var.get()))
    label.configure(text=my_var.get())

my_var.trace_add('write', my_callback)

label = Label(root)
label.pack(padx=5, pady=5)

Entry(root, textvariable=my_var).pack(padx=5, pady=5)

root.mainloop()
```
<h1>Alternative</h1>
<pre class="lang-py prettyprint-override"><code># Python program to trace
# variable in tkinter

from tkinter import *
import phonenumbers
import re

root = Tk()

my_var = StringVar()

# defining the callback function (observer)

# def phone_format(phone_number):
#     try:
#         clean_phone_number = re.sub('[^0-9]+', '', phone_number)
#         formatted_phone_number = re.sub(
#             r"(\d)(?=(\d{3})+(?!\d))", r"\1-", "%d" % int(clean_phone_number[:-1])) + clean_phone_number[-1]
#         return formatted_phone_number
#     except ValueError:
#         return phone_number

def phone_format(n):
    # return format(int(n[:-1]), ",").replace(",", "-") + n[-1]
    # return phonenumbers.format_number(n, phonenumbers.PhoneNumberFormat.NATIONAL)
    formatter = phonenumbers.AsYouTypeFormatter("US")
    for digit in re.findall(r'\d', n)[:-1]:
        formatter.input_digit(digit)
    return formatter.input_digit(re.findall(r'\d', n)[-1])

def my_callback(var, indx, mode):
    print(my_var.get())
    my_var.set(phone_format(my_var.get()))
    label.configure(text=my_var.get())

def callback(event):
    entry.icursor(END)

my_var.trace_add('write', my_callback)

label = Label(root)
label.pack(padx=5, pady=5)

entry = Entry(root, textvariable=my_var)
entry.bind("<Key>", callback)
entry.pack(padx=5, pady=5)

root.mainloop()
</code>```

This was my solution, using phonenumbers from PyPi, which seemed to make it work.

Body:
I used a combination of both this example of tracing tkinter variables and combined it with this answer, I am not 100% sure if this is the correct American formatting because I live in the UK and we format things differently here, but this is the rough example of how that would work:

# Python program to trace
# variable in tkinter

from tkinter import *
import re

root = Tk()

my_var = StringVar()

# defining the callback function (observer)

def phone_format(phone_number):
    try:
        clean_phone_number = re.sub('[^0-9]+', '', phone_number)
        formatted_phone_number = re.sub(
            r"(\d)(?=(\d{3})+(?!\d))", r"\1-", "%d" % int(clean_phone_number[:-1])) + clean_phone_number[-1]
        return formatted_phone_number
    except ValueError:
        return phone_number

def my_callback(var, indx, mode):
    my_var.set(phone_format(my_var.get()))
    label.configure(text=my_var.get())

my_var.trace_add('write', my_callback)

label = Label(root)
label.pack(padx=5, pady=5)

Entry(root, textvariable=my_var).pack(padx=5, pady=5)

root.mainloop()

Alternative

# Python program to trace
# variable in tkinter

from tkinter import *
import phonenumbers
import re

root = Tk()

my_var = StringVar()

# defining the callback function (observer)

# def phone_format(phone_number):
#     try:
#         clean_phone_number = re.sub('[^0-9]+', '', phone_number)
#         formatted_phone_number = re.sub(
#             r"(\d)(?=(\d{3})+(?!\d))", r"\1-", "%d" % int(clean_phone_number[:-1])) + clean_phone_number[-1]
#         return formatted_phone_number
#     except ValueError:
#         return phone_number

def phone_format(n):
    # return format(int(n[:-1]), ",").replace(",", "-") + n[-1]
    # return phonenumbers.format_number(n, phonenumbers.PhoneNumberFormat.NATIONAL)
    formatter = phonenumbers.AsYouTypeFormatter("US")
    for digit in re.findall(r'\d', n)[:-1]:
        formatter.input_digit(digit)
    return formatter.input_digit(re.findall(r'\d', n)[-1])

def my_callback(var, indx, mode):
    print(my_var.get())
    my_var.set(phone_format(my_var.get()))
    label.configure(text=my_var.get())

def callback(event):
    entry.icursor(END)

my_var.trace_add('write', my_callback)

label = Label(root)
label.pack(padx=5, pady=5)

entry = Entry(root, textvariable=my_var)
entry.bind("<Key>", callback)
entry.pack(padx=5, pady=5)

root.mainloop()

This was my solution, using phonenumbers from PyPi, which seemed to make it work.


问:
Symfony 5 User roles
Im wondering how do I compare users's roles coming from database with a role I suggest something like </p>

```<code>{% for user in users %}
  {% if user.something == ' EXEMPLE_role' %}
  {% endif %}
{% endfor %}
</code>```

答:
I found the solution for this </p>

```<code>{% if 'ROLE_EXAMPLE' in user.roles %}
{% endif %}
</code>```

Title: Symfony 5 User roles

Body:
Im wondering how do I compare users's roles coming from database with a role I suggest something like

{% for user in users %}
  {% if user.something == ' EXEMPLE_role' %}
  {% endif %}
{% endfor %}

Body:
I found the solution for this

{% if 'ROLE_EXAMPLE' in user.roles %}
{% endif %}


问:
Loop over array and create `n` other arrays based on item value in array
Id like to loop over an array of objects which is of unknown length and (some) unknown content and create a new set of enumerated arrays.

I know that the array has a consistent set of key:value pairs, which I'd like to use a reference to chunk out the array.

Here's the example array:

```<code>[{something:test,value:10},{something:example,value:20},{something:test,value:30}]
</code>```

The function should recognize the key 'something' and create a number of arrays based on the variations of the corresponding value, so for example, in this case 2 arrays would result with an object form:

```<code>{
    test: [{something:test,value:10},{something:test,value:30},
    example: [{something:example,value:20}]
}
</code>```

In other words I need to chunk an array based on some items value in the array, rather than size / length.

I have considered / tried using index on values etc to get size parameter, but this seems a like a huge undertaking, and I'm sure there's a faster solution.

Lodash etc do not seem to have something like this in their library.

答:
You can use Array.reduce() and push the objects into arrays.

const arr = [{something:'test',value:10},{something:'example',value:20},{something:'test',value:30}]

const result = arr.reduce((acc,cur) => {
    if(!Object.keys(acc).some(key => key === cur.something)){
        acc[cur.something] = [cur]
    }else{
        acc[cur.something].push(cur)
    }
    return acc
},{})

console.log(result)```

Body:
Id like to loop over an array of objects which is of unknown length and (some) unknown content and create a new set of enumerated arrays.

I know that the array has a consistent set of key:value pairs, which I'd like to use a reference to chunk out the array.

Here's the example array:

[{something:test,value:10},{something:example,value:20},{something:test,value:30}]

The function should recognize the key 'something' and create a number of arrays based on the variations of the corresponding value, so for example, in this case 2 arrays would result with an object form:

{
    test: [{something:test,value:10},{something:test,value:30},
    example: [{something:example,value:20}]
}

In other words I need to chunk an array based on some items value in the array, rather than size / length.

I have considered / tried using index on values etc to get size parameter, but this seems a like a huge undertaking, and I'm sure there's a faster solution.

Lodash etc do not seem to have something like this in their library.


问:
Calling Functions Based on Content of a Dictionary C#
I'm working on a program that will have a dictionary storing commands. There are two dictionaries, one of executables and one of internal functions. Right now, I'm just using the executable one, which has a command name attached to the path of the executable. It will check for the input in the dictionary and run the attached exe if possible and run that command. I started the function dictionary because there are some functions that are not executables. Would it be possible to do the same thing I did with the executables with functions inside the program?</p>

```<code>    private Dictionary<string, string> ExternalCommands = new Dictionary<string, string>
    {
        {"help", @".\help.exe"}
    };

    private Dictionary<string, string> InternalFunctions = new Dictionary<string, string>
    {
        **{"exit", function()}**
    };
    public int Execute(string input)
    {
        try
        {
            if (ExternalCommands.Keys.Contains(input))
            {
                var process = new Process();
                process.StartInfo = new ProcessStartInfo(ExternalCommands[input])
                {
                    UseShellExecute = false
                };

                process.Start();
                process.WaitForExit();

                return 0;
            }
            Console.WriteLine($"{input} NOT FOUND");
            return 1;
        }
        catch
        {
            return 1;
        }
</code>```

答:
How you would do this depends upon the method signatures and what, if any, parameters you need to pass. In general, though, you'd need to create a dictionary of delegates. Action and Func are pretty easy to use in this situation.

Something like this would work:

```<code>private void Test()
{
    var commands = new Dictionary<string, Action>();
    commands.Add("exit", Exit);
    commands.Add("greet", SayHello);

    commands["greet"]();
    commands["exit"]();
}

private void Exit()
{
    this.Close();
}

private void SayHello()
{
    MessageBox.Show("Hello!");
}
</code>```

You could also use lambda expressions to add delegates to such a dictionary for even more flexibility:

```<code>commands.Add("exit", () => this.Close());
commands.Add("greet", () => MessageBox.Show("Hello!"));
</code>```

Body:
I'm working on a program that will have a dictionary storing commands. There are two dictionaries, one of executables and one of internal functions. Right now, I'm just using the executable one, which has a command name attached to the path of the executable. It will check for the input in the dictionary and run the attached exe if possible and run that command. I started the function dictionary because there are some functions that are not executables. Would it be possible to do the same thing I did with the executables with functions inside the program?

    private Dictionary<string, string> ExternalCommands = new Dictionary<string, string>
    {
        {"help", @".\help.exe"}
    };

    private Dictionary<string, string> InternalFunctions = new Dictionary<string, string>
    {
        **{"exit", function()}**
    };
    public int Execute(string input)
    {
        try
        {
            if (ExternalCommands.Keys.Contains(input))
            {
                var process = new Process();
                process.StartInfo = new ProcessStartInfo(ExternalCommands[input])
                {
                    UseShellExecute = false
                };

                process.Start();
                process.WaitForExit();

                return 0;
            }
            Console.WriteLine($"{input} NOT FOUND");
            return 1;
        }
        catch
        {
            return 1;
        }

Body:
How you would do this depends upon the method signatures and what, if any, parameters you need to pass. In general, though, you'd need to create a dictionary of delegates. Action and Func are pretty easy to use in this situation.

Something like this would work:

private void Test()
{
    var commands = new Dictionary<string, Action>();
    commands.Add("exit", Exit);
    commands.Add("greet", SayHello);

    commands["greet"]();
    commands["exit"]();
}

private void Exit()
{
    this.Close();
}

private void SayHello()
{
    MessageBox.Show("Hello!");
}

You could also use lambda expressions to add delegates to such a dictionary for even more flexibility:

commands.Add("exit", () => this.Close());
commands.Add("greet", () => MessageBox.Show("Hello!"));


问:
Accessing the elements of an ndarray
I am working on a machine learning problem in which the input has the shape (10, 1, 5, 4) for 10 samples, each sample shape  (1,5,4). Below I show more details:

```<code>X = np.random.randn(10, 1, 5, 4)
a = np.zeros(5, dtype=int)
b = np.ones(5, dtype=int)
y = np.hstack((a,b))

print(X.shape)
print(y.shape)
(10, 1, 5, 4)
(10,)
</code>```

The value of each sample in X is an array representing four parameters, thus:

```<code>X[0]

array([[[ 0.41246417,  1.0105981 , -0.64404467, -0.53073642],
    [-0.81929058, -0.14408449, -0.80003834,  0.974497  ],
    [-0.56111328,  0.63726127,  1.56704848,  1.16701553],
    [-0.3643063 , -0.57204605, -0.36627686,  0.61098743],
    [-0.25378511, -0.14519147, -0.22557196,  0.87733856]]])
</code>```

In the above, the first row [ 0.41246417,  1.0105981,  -0.64404467, -0.53073642] represents say min_speed, avg_speed, min_vel, avg_vel so also other rows in this manner.

But I want to create a new array which is a stack of min_speed, avg_speed, min_vel, avg_vel so that  min_speed = [0.41246417, -0.81929058, -0.56111328, -0.3643063, -0.25378511] (i.e. first column in each case), avg_speed =[1.0105981 , -0.14408449,0.63726127, -0.57204605, -0.14519147] (second column) like that.

How I do manipulate this?

答:
This will do the job</p>

```<code>X.transpose((0, 1, 3, 2))
</code>```

Title: Accessing the elements of an ndarray

Body:
I am working on a machine learning problem in which the input has the shape (10, 1, 5, 4) for 10 samples, each sample shape  (1,5,4). Below I show more details:

X = np.random.randn(10, 1, 5, 4)
a = np.zeros(5, dtype=int)
b = np.ones(5, dtype=int)
y = np.hstack((a,b))

print(X.shape)
print(y.shape)
(10, 1, 5, 4)
(10,)

The value of each sample in X is an array representing four parameters, thus:

X[0]

array([[[ 0.41246417,  1.0105981 , -0.64404467, -0.53073642],
    [-0.81929058, -0.14408449, -0.80003834,  0.974497  ],
    [-0.56111328,  0.63726127,  1.56704848,  1.16701553],
    [-0.3643063 , -0.57204605, -0.36627686,  0.61098743],
    [-0.25378511, -0.14519147, -0.22557196,  0.87733856]]])

In the above, the first row [ 0.41246417,  1.0105981,  -0.64404467, -0.53073642] represents say min_speed, avg_speed, min_vel, avg_vel so also other rows in this manner.

But I want to create a new array which is a stack of min_speed, avg_speed, min_vel, avg_vel so that  min_speed = [0.41246417, -0.81929058, -0.56111328, -0.3643063, -0.25378511] (i.e. first column in each case), avg_speed =[1.0105981 , -0.14408449,0.63726127, -0.57204605, -0.14519147] (second column) like that.

How I do manipulate this?

Body:
This will do the job

X.transpose((0, 1, 3, 2))