问:
Static files not loading
url inside main 'mySite' directory

```<code>urlpatterns = [
    path('admin/', admin.site.urls),
    path('coming-soon/', include('comingSoon.urls')),
]
</code>```

url inside comingSoon app directory

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

views.index inside comingSoon app

```<code>def index(request):
return render(request, 'comingSoon/coming-soon.html')
</code>```

inside template "coming-soon.html'

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="" />
    <meta name="keywords" content="" />
    <title>My Website</title>
    <link rel="icon" href="images/fav.png" type="image/png" sizes="16x16">
    {% load static %}
    {% load staticfiles %}
<link rel="stylesheet" href="{% static 'css/main.min.css' %}">
<link rel="stylesheet" href="{% static 'css/style.css' %}">
<link rel="stylesheet" href="{% static 'css/color.css' %}">
<link rel="stylesheet" href="{% static 'css/responsive.css' %}">

</head>
<body>
<div class="theme-layout">

    <div class="gap2 mate-black medium-opacity vh100">
        <div class="bg-image" style="background-image:url(images/resources/coming-soon-bg.jpg);"></div>
        <div class="container">
            <div class="row">
                <div class="col-lg-12">
                    <div class="coming-head">
                        <div class="logo">
                            <a href="index.html" title=""><img src="images/logo.png" alt=""></a>
                        </div>
                        <ul class="social-circle ">
                            <li><a class="facebook-color" href="#" title=""><i class="fa fa-facebook"></i></a></li>
                            <li><a class="twitter-color" href="#" title=""><i class="fa fa-twitter"></i></a></li>
                            <li><a class="google-color" href="#" title=""><i class="fa fa-google-plus"></i></a></li>
                            <li><a class="vk-color" href="#" title=""><i class="fa fa-vk"></i></a></li>
                        </ul>
                    </div>
                    <div class="coming-meta">
                        <h1>We're Coming!</h1>
                        <p>We are working hard to bring you new experience</p>
                        <ul class="countdown">
                           <li><span class="days">00</span><p class="days_ref"></p></li>
                           <li> <span class="hours">00</span><p class="hours_ref"></p></li>
                           <li> <span class="minutes">00</span><p class="minutes_ref"></p></li>
                           <li> <span class="seconds">00</span><p class="seconds_ref"></p></li>
                        </ul>
                        <form method="post">
                            <input type="text" placeholder="Submit inquiry...">
                            <button type="submit"><i class="fa fa-arrow-right"></i></button>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>

</div>

    <script src="{% static 'js/main.min.js' %}"></script>
    <script src="{% static 'js/downCount.js' %}"></script>
    <script src="{% static 'js/script.js' %}"></script>

</body>
</html>
</code>```

at this point if I try to run, its loading with html but failed to load css and js

Folder Structure - 1

```<code>mySite.com
|-- mySite                   // django project directory
|   |-- mySite               // app directory
|   |   |-- __init__.py
|   |   |-- wsgi.py
|   |   |-- urls.py
|   |   |-- asgi.py
|   |   |-- setting.py
|   |
|   |-- comingSoon          // comingsoon  app
|   |   |-- migrations
|   |   |-- __init__.py
|   |   |-- admin.py
|   |   |-- apps.py
|   |   |-- models.py
|   |   |-- tests.py
|   |   |-- urls.py
|   |   |-- views.py
|   |
|   |-- static         // static files intentionally placing outside app directory (***but not loading***)
|   |   |-- css
|   |   |-- js
|   |   |-- images
|   |   |-- fonts
|   |
|   |-- templates                // templates folder for base templates.
|   |   |-- base1.html
|   |   |-- base2.html
|   |   |-- comingSoon           // comingSoon directory
|   |   |   |-- coming-soon.html // html file - this is loading
</code>```

I have done few modification like i have added an app called 'audio' and created a static folder inside it and now if i access my static folder its working fine. But i want to access by keeping static files as like in Folder Structure - 1

```<code>mySite.com
    |-- mySite                   // django project directory
    |   |-- mySite               // app directory
    |   |   |-- __init__.py
    |   |   |-- wsgi.py
    |   |   |-- urls.py
    |   |   |-- asgi.py
    |   |   |-- setting.py
    |   |
    |   |-- audio          // Audio app
    |   |   |-- migrations
    |   |   |-- static
    |   |   |   |-- audio
    |   |   |       |-- css
    |   |   |       |-- js
    |   |   |-- __init__.py
    |   |   |-- admin.py
    |   |   |-- apps.py
    |   |   |-- models.py
    |   |   |-- tests.py
    |   |   |-- urls.py
    |   |   |-- views.py
    |   |
    |   |-- comingSoon          // comingsoon  app
    |   |   |-- migrations
    |   |   |-- __init__.py
    |   |   |-- admin.py
    |   |   |-- apps.py
    |   |   |-- models.py
    |   |   |-- tests.py
    |   |   |-- urls.py
    |   |   |-- views.py
    |   |
    |   |-- static         // static files intentionally placing outside app directory (***but not loading***)
    |   |   |-- css
    |   |   |-- js
    |   |   |-- images
    |   |   |-- fonts
    |   |
    |   |-- templates                // templates folder for base templates.
    |   |   |-- base1.html
    |   |   |-- base2.html
    |   |   |-- comingSoon           // comingSoon directory
    |   |   |   |-- coming-soon.html // html file - this is loading
</code>```

STATIC at settings.py - Updated

```<code>BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
</code>```

not finding the actual mistake/s after several attempts

errors what i am getting is as follows

```<code>[02/Jun/2020 02:28:05] "GET /coming-soon/ HTTP/1.1" 200 2555
[02/Jun/2020 02:28:05] "GET /static/css/main.min.css HTTP/1.1" 404 1672
[02/Jun/2020 02:28:05] "GET /static/css/color.css HTTP/1.1" 404 1663
[02/Jun/2020 02:28:05] "GET /static/css/responsive.css HTTP/1.1" 404 1678
[02/Jun/2020 02:28:05] "GET /static/css/style.css HTTP/1.1" 404 1663
[02/Jun/2020 02:28:05] "GET /static/js/downCount.js HTTP/1.1" 404 1669
[02/Jun/2020 02:28:05] "GET /static/main.min.js HTTP/1.1" 404 1657
Not Found: /coming-soon/images/logo.png
[02/Jun/2020 02:28:05] "GET /coming-soon/images/logo.png HTTP/1.1" 404 3713
[02/Jun/2020 02:28:05] "GET /static/js/script.js HTTP/1.1" 404 1660
Not Found: /coming-soon/images/resources/coming-soon-bg.jpg
[02/Jun/2020 02:28:05] "GET /coming-soon/images/resources/coming-soon-bg.jpg HTTP/1.1" 404 3773
[02/Jun/2020 02:28:05] "GET /static/js/downCount.js HTTP/1.1" 404 1669
[02/Jun/2020 02:28:05] "GET /static/js/script.js HTTP/1.1" 404 1660
[02/Jun/2020 02:28:06] "GET /coming-soon/ HTTP/1.1" 200 2555
[02/Jun/2020 02:28:06] "GET /static/css/main.min.css HTTP/1.1" 404 1672
[02/Jun/2020 02:28:06] "GET /static/main.min.js HTTP/1.1" 404 1657
[02/Jun/2020 02:28:06] "GET /static/css/style.css HTTP/1.1" 404 1663
[02/Jun/2020 02:28:06] "GET /static/js/downCount.js HTTP/1.1" 404 1669
[02/Jun/2020 02:28:06] "GET /static/css/responsive.css HTTP/1.1" 404 1678
[02/Jun/2020 02:28:06] "GET /static/css/color.css HTTP/1.1" 404 1663
[02/Jun/2020 02:28:06] "GET /static/js/script.js HTTP/1.1" 404 1660
Not Found: /coming-soon/images/logo.png
[02/Jun/2020 02:28:06] "GET /coming-soon/images/logo.png HTTP/1.1" 404 3713
Not Found: /coming-soon/images/resources/coming-soon-bg.jpg
[02/Jun/2020 02:28:06] "GET /coming-soon/images/resources/coming-soon-bg.jpg HTTP/1.1" 404 3773
[02/Jun/2020 02:28:06] "GET /static/js/downCount.js HTTP/1.1" 404 1669
[02/Jun/2020 02:28:06] "GET /static/js/script.js HTTP/1.1" 404 1660
[02/Jun/2020 02:28:07] "GET /coming-soon/ HTTP/1.1" 200 2555
[02/Jun/2020 02:28:07] "GET /static/css/responsive.css HTTP/1.1" 404 1678
[02/Jun/2020 02:28:07] "GET /static/css/style.css HTTP/1.1" 404 1663
[02/Jun/2020 02:28:07] "GET /static/js/downCount.js HTTP/1.1" 404 1669
[02/Jun/2020 02:28:07] "GET /static/main.min.js HTTP/1.1" 404 1657
[02/Jun/2020 02:28:07] "GET /static/css/main.min.css HTTP/1.1" 404 1672
[02/Jun/2020 02:28:07] "GET /static/css/color.css HTTP/1.1" 404 1663
Not Found: /coming-soon/images/logo.png
[02/Jun/2020 02:28:07] "GET /static/js/script.js HTTP/1.1" 404 1660
[02/Jun/2020 02:28:07] "GET /coming-soon/images/logo.png HTTP/1.1" 404 3713
[02/Jun/2020 02:28:07] "GET /static/js/downCount.js HTTP/1.1" 404 1669
Not Found: /coming-soon/images/resources/coming-soon-bg.jpg
[02/Jun/2020 02:28:07] "GET /coming-soon/images/resources/coming-soon-bg.jpg HTTP/1.1" 404 3773
[02/Jun/2020 02:28:07] "GET /static/js/script.js HTTP/1.1" 404 1660
[02/Jun/2020 02:28:07] "GET /coming-soon/ HTTP/1.1" 200 2555
[02/Jun/2020 02:28:07] "GET /static/css/style.css HTTP/1.1" 404 1663
[02/Jun/2020 02:28:07] "GET /static/css/responsive.css HTTP/1.1" 404 1678
[02/Jun/2020 02:28:07] "GET /static/css/main.min.css HTTP/1.1" 404 1672
[02/Jun/2020 02:28:07] "GET /static/css/color.css HTTP/1.1" 404 1663
[02/Jun/2020 02:28:07] "GET /static/main.min.js HTTP/1.1" 404 1657
[02/Jun/2020 02:28:07] "GET /static/js/downCount.js HTTP/1.1" 404 1669
Not Found: /coming-soon/images/logo.png
[02/Jun/2020 02:28:07] "GET /coming-soon/images/logo.png HTTP/1.1" 404 3713
[02/Jun/2020 02:28:07] "GET /static/js/script.js HTTP/1.1" 404 1660
Not Found: /coming-soon/images/resources/coming-soon-bg.jpg
[02/Jun/2020 02:28:07] "GET /coming-soon/images/resources/coming-soon-bg.jpg HTTP/1.1" 404 3773
[02/Jun/2020 02:28:07] "GET /static/js/downCount.js HTTP/1.1" 404 1669
[02/Jun/2020 02:28:07] "GET /static/js/script.js HTTP/1.1" 404 1660
[02/Jun/2020 02:28:08] "GET /coming-soon/ HTTP/1.1" 200 2555
[02/Jun/2020 02:28:08] "GET /static/css/style.css HTTP/1.1" 404 1663
[02/Jun/2020 02:28:08] "GET /static/css/main.min.css HTTP/1.1" 404 1672
[02/Jun/2020 02:28:08] "GET /static/js/downCount.js HTTP/1.1" 404 1669
[02/Jun/2020 02:28:08] "GET /static/css/color.css HTTP/1.1" 404 1663
[02/Jun/2020 02:28:08] "GET /static/css/responsive.css HTTP/1.1" 404 1678
[02/Jun/2020 02:28:08] "GET /static/main.min.js HTTP/1.1" 404 1657
[02/Jun/2020 02:28:08] "GET /static/js/script.js HTTP/1.1" 404 1660
Not Found: /coming-soon/images/resources/coming-soon-bg.jpg
[02/Jun/2020 02:28:08] "GET /coming-soon/images/resources/coming-soon-bg.jpg HTTP/1.1" 404 3773
Not Found: /coming-soon/images/logo.png
[02/Jun/2020 02:28:08] "GET /coming-soon/images/logo.png HTTP/1.1" 404 3713
[02/Jun/2020 02:28:08] "GET /static/js/downCount.js HTTP/1.1" 404 1669
[02/Jun/2020 02:28:08] "GET /static/js/script.js HTTP/1.1" 404 1660
[02/Jun/2020 02:32:34] "GET /coming-soon/ HTTP/1.1" 200 2555
[02/Jun/2020 02:32:34] "GET /static/css/color.css HTTP/1.1" 404 1663
[02/Jun/2020 02:32:34] "GET /static/main.min.js HTTP/1.1" 404 1657
[02/Jun/2020 02:32:34] "GET /static/css/responsive.css HTTP/1.1" 404 1678
[02/Jun/2020 02:32:34] "GET /static/js/downCount.js HTTP/1.1" 404 1669
[02/Jun/2020 02:32:34] "GET /static/css/main.min.css HTTP/1.1" 404 1672
[02/Jun/2020 02:32:34] "GET /static/css/style.css HTTP/1.1" 404 1663
[02/Jun/2020 02:32:34] "GET /static/js/script.js HTTP/1.1" 404 1660
Not Found: /coming-soon/images/logo.png
[02/Jun/2020 02:32:34] "GET /coming-soon/images/logo.png HTTP/1.1" 404 3713
[02/Jun/2020 02:32:34] "GET /static/js/downCount.js HTTP/1.1" 404 1669
Not Found: /coming-soon/images/resources/coming-soon-bg.jpg
[02/Jun/2020 02:32:34] "GET /coming-soon/images/resources/coming-soon-bg.jpg HTTP/1.1" 404 3773
[02/Jun/2020 02:32:34] "GET /static/js/script.js HTTP/1.1" 404 1660
</code>```

答:
Changing your STATICFILES_DIRS to

```<code>BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
</code>```

should do the trick.

In your html there is also a % missing to close the static tag:

```<code><script src="{% static 'js/script.js' %}"></script>
</code>```

And run py manage.py collectstatic

Title: Static files not loading

Body:
url inside main 'mySite' directory

urlpatterns = [
    path('admin/', admin.site.urls),
    path('coming-soon/', include('comingSoon.urls')),
]

url inside comingSoon app directory

urlpatterns = [
    path("", views.index, name="coming-Soon")
]

views.index inside comingSoon app

def index(request):
return render(request, 'comingSoon/coming-soon.html')

inside template "coming-soon.html'

<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="" />
    <meta name="keywords" content="" />
    <title>My Website</title>
    <link rel="icon" href="images/fav.png" type="image/png" sizes="16x16">
    {% load static %}
    {% load staticfiles %}
<link rel="stylesheet" href="{% static 'css/main.min.css' %}">
<link rel="stylesheet" href="{% static 'css/style.css' %}">
<link rel="stylesheet" href="{% static 'css/color.css' %}">
<link rel="stylesheet" href="{% static 'css/responsive.css' %}">

We're Coming!

We are working hard to bring you new experience

00

 00

 00

 00

                        <form method="post">
                            <input type="text" placeholder="Submit inquiry...">
                            <button type="submit"></button>
                        </form>

at this point if I try to run, its loading with html but failed to load css and js

Folder Structure - 1

mySite.com
|-- mySite                   // django project directory
|   |-- mySite               // app directory
|   |   |-- __init__.py
|   |   |-- wsgi.py
|   |   |-- urls.py
|   |   |-- asgi.py
|   |   |-- setting.py
|   |
|   |-- comingSoon          // comingsoon  app
|   |   |-- migrations
|   |   |-- __init__.py
|   |   |-- admin.py
|   |   |-- apps.py
|   |   |-- models.py
|   |   |-- tests.py
|   |   |-- urls.py
|   |   |-- views.py
|   |
|   |-- static         // static files intentionally placing outside app directory (***but not loading***)
|   |   |-- css
|   |   |-- js
|   |   |-- images
|   |   |-- fonts
|   |
|   |-- templates                // templates folder for base templates.
|   |   |-- base1.html
|   |   |-- base2.html
|   |   |-- comingSoon           // comingSoon directory
|   |   |   |-- coming-soon.html // html file - this is loading

I have done few modification like i have added an app called 'audio' and created a static folder inside it and now if i access my static folder its working fine. But i want to access by keeping static files as like in Folder Structure - 1

mySite.com
    |-- mySite                   // django project directory
    |   |-- mySite               // app directory
    |   |   |-- __init__.py
    |   |   |-- wsgi.py
    |   |   |-- urls.py
    |   |   |-- asgi.py
    |   |   |-- setting.py
    |   |
    |   |-- audio          // Audio app
    |   |   |-- migrations
    |   |   |-- static
    |   |   |   |-- audio
    |   |   |       |-- css
    |   |   |       |-- js
    |   |   |-- __init__.py
    |   |   |-- admin.py
    |   |   |-- apps.py
    |   |   |-- models.py
    |   |   |-- tests.py
    |   |   |-- urls.py
    |   |   |-- views.py
    |   |
    |   |-- comingSoon          // comingsoon  app
    |   |   |-- migrations
    |   |   |-- __init__.py
    |   |   |-- admin.py
    |   |   |-- apps.py
    |   |   |-- models.py
    |   |   |-- tests.py
    |   |   |-- urls.py
    |   |   |-- views.py
    |   |
    |   |-- static         // static files intentionally placing outside app directory (***but not loading***)
    |   |   |-- css
    |   |   |-- js
    |   |   |-- images
    |   |   |-- fonts
    |   |
    |   |-- templates                // templates folder for base templates.
    |   |   |-- base1.html
    |   |   |-- base2.html
    |   |   |-- comingSoon           // comingSoon directory
    |   |   |   |-- coming-soon.html // html file - this is loading

STATIC at settings.py - Updated

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]

not finding the actual mistake/s after several attempts

errors what i am getting is as follows

[02/Jun/2020 02:28:05] "GET /coming-soon/ HTTP/1.1" 200 2555
[02/Jun/2020 02:28:05] "GET /static/css/main.min.css HTTP/1.1" 404 1672
[02/Jun/2020 02:28:05] "GET /static/css/color.css HTTP/1.1" 404 1663
[02/Jun/2020 02:28:05] "GET /static/css/responsive.css HTTP/1.1" 404 1678
[02/Jun/2020 02:28:05] "GET /static/css/style.css HTTP/1.1" 404 1663
[02/Jun/2020 02:28:05] "GET /static/js/downCount.js HTTP/1.1" 404 1669
[02/Jun/2020 02:28:05] "GET /static/main.min.js HTTP/1.1" 404 1657
Not Found: /coming-soon/images/logo.png
[02/Jun/2020 02:28:05] "GET /coming-soon/images/logo.png HTTP/1.1" 404 3713
[02/Jun/2020 02:28:05] "GET /static/js/script.js HTTP/1.1" 404 1660
Not Found: /coming-soon/images/resources/coming-soon-bg.jpg
[02/Jun/2020 02:28:05] "GET /coming-soon/images/resources/coming-soon-bg.jpg HTTP/1.1" 404 3773
[02/Jun/2020 02:28:05] "GET /static/js/downCount.js HTTP/1.1" 404 1669
[02/Jun/2020 02:28:05] "GET /static/js/script.js HTTP/1.1" 404 1660
[02/Jun/2020 02:28:06] "GET /coming-soon/ HTTP/1.1" 200 2555
[02/Jun/2020 02:28:06] "GET /static/css/main.min.css HTTP/1.1" 404 1672
[02/Jun/2020 02:28:06] "GET /static/main.min.js HTTP/1.1" 404 1657
[02/Jun/2020 02:28:06] "GET /static/css/style.css HTTP/1.1" 404 1663
[02/Jun/2020 02:28:06] "GET /static/js/downCount.js HTTP/1.1" 404 1669
[02/Jun/2020 02:28:06] "GET /static/css/responsive.css HTTP/1.1" 404 1678
[02/Jun/2020 02:28:06] "GET /static/css/color.css HTTP/1.1" 404 1663
[02/Jun/2020 02:28:06] "GET /static/js/script.js HTTP/1.1" 404 1660
Not Found: /coming-soon/images/logo.png
[02/Jun/2020 02:28:06] "GET /coming-soon/images/logo.png HTTP/1.1" 404 3713
Not Found: /coming-soon/images/resources/coming-soon-bg.jpg
[02/Jun/2020 02:28:06] "GET /coming-soon/images/resources/coming-soon-bg.jpg HTTP/1.1" 404 3773
[02/Jun/2020 02:28:06] "GET /static/js/downCount.js HTTP/1.1" 404 1669
[02/Jun/2020 02:28:06] "GET /static/js/script.js HTTP/1.1" 404 1660
[02/Jun/2020 02:28:07] "GET /coming-soon/ HTTP/1.1" 200 2555
[02/Jun/2020 02:28:07] "GET /static/css/responsive.css HTTP/1.1" 404 1678
[02/Jun/2020 02:28:07] "GET /static/css/style.css HTTP/1.1" 404 1663
[02/Jun/2020 02:28:07] "GET /static/js/downCount.js HTTP/1.1" 404 1669
[02/Jun/2020 02:28:07] "GET /static/main.min.js HTTP/1.1" 404 1657
[02/Jun/2020 02:28:07] "GET /static/css/main.min.css HTTP/1.1" 404 1672
[02/Jun/2020 02:28:07] "GET /static/css/color.css HTTP/1.1" 404 1663
Not Found: /coming-soon/images/logo.png
[02/Jun/2020 02:28:07] "GET /static/js/script.js HTTP/1.1" 404 1660
[02/Jun/2020 02:28:07] "GET /coming-soon/images/logo.png HTTP/1.1" 404 3713
[02/Jun/2020 02:28:07] "GET /static/js/downCount.js HTTP/1.1" 404 1669
Not Found: /coming-soon/images/resources/coming-soon-bg.jpg
[02/Jun/2020 02:28:07] "GET /coming-soon/images/resources/coming-soon-bg.jpg HTTP/1.1" 404 3773
[02/Jun/2020 02:28:07] "GET /static/js/script.js HTTP/1.1" 404 1660
[02/Jun/2020 02:28:07] "GET /coming-soon/ HTTP/1.1" 200 2555
[02/Jun/2020 02:28:07] "GET /static/css/style.css HTTP/1.1" 404 1663
[02/Jun/2020 02:28:07] "GET /static/css/responsive.css HTTP/1.1" 404 1678
[02/Jun/2020 02:28:07] "GET /static/css/main.min.css HTTP/1.1" 404 1672
[02/Jun/2020 02:28:07] "GET /static/css/color.css HTTP/1.1" 404 1663
[02/Jun/2020 02:28:07] "GET /static/main.min.js HTTP/1.1" 404 1657
[02/Jun/2020 02:28:07] "GET /static/js/downCount.js HTTP/1.1" 404 1669
Not Found: /coming-soon/images/logo.png
[02/Jun/2020 02:28:07] "GET /coming-soon/images/logo.png HTTP/1.1" 404 3713
[02/Jun/2020 02:28:07] "GET /static/js/script.js HTTP/1.1" 404 1660
Not Found: /coming-soon/images/resources/coming-soon-bg.jpg
[02/Jun/2020 02:28:07] "GET /coming-soon/images/resources/coming-soon-bg.jpg HTTP/1.1" 404 3773
[02/Jun/2020 02:28:07] "GET /static/js/downCount.js HTTP/1.1" 404 1669
[02/Jun/2020 02:28:07] "GET /static/js/script.js HTTP/1.1" 404 1660
[02/Jun/2020 02:28:08] "GET /coming-soon/ HTTP/1.1" 200 2555
[02/Jun/2020 02:28:08] "GET /static/css/style.css HTTP/1.1" 404 1663
[02/Jun/2020 02:28:08] "GET /static/css/main.min.css HTTP/1.1" 404 1672
[02/Jun/2020 02:28:08] "GET /static/js/downCount.js HTTP/1.1" 404 1669
[02/Jun/2020 02:28:08] "GET /static/css/color.css HTTP/1.1" 404 1663
[02/Jun/2020 02:28:08] "GET /static/css/responsive.css HTTP/1.1" 404 1678
[02/Jun/2020 02:28:08] "GET /static/main.min.js HTTP/1.1" 404 1657
[02/Jun/2020 02:28:08] "GET /static/js/script.js HTTP/1.1" 404 1660
Not Found: /coming-soon/images/resources/coming-soon-bg.jpg
[02/Jun/2020 02:28:08] "GET /coming-soon/images/resources/coming-soon-bg.jpg HTTP/1.1" 404 3773
Not Found: /coming-soon/images/logo.png
[02/Jun/2020 02:28:08] "GET /coming-soon/images/logo.png HTTP/1.1" 404 3713
[02/Jun/2020 02:28:08] "GET /static/js/downCount.js HTTP/1.1" 404 1669
[02/Jun/2020 02:28:08] "GET /static/js/script.js HTTP/1.1" 404 1660
[02/Jun/2020 02:32:34] "GET /coming-soon/ HTTP/1.1" 200 2555
[02/Jun/2020 02:32:34] "GET /static/css/color.css HTTP/1.1" 404 1663
[02/Jun/2020 02:32:34] "GET /static/main.min.js HTTP/1.1" 404 1657
[02/Jun/2020 02:32:34] "GET /static/css/responsive.css HTTP/1.1" 404 1678
[02/Jun/2020 02:32:34] "GET /static/js/downCount.js HTTP/1.1" 404 1669
[02/Jun/2020 02:32:34] "GET /static/css/main.min.css HTTP/1.1" 404 1672
[02/Jun/2020 02:32:34] "GET /static/css/style.css HTTP/1.1" 404 1663
[02/Jun/2020 02:32:34] "GET /static/js/script.js HTTP/1.1" 404 1660
Not Found: /coming-soon/images/logo.png
[02/Jun/2020 02:32:34] "GET /coming-soon/images/logo.png HTTP/1.1" 404 3713
[02/Jun/2020 02:32:34] "GET /static/js/downCount.js HTTP/1.1" 404 1669
Not Found: /coming-soon/images/resources/coming-soon-bg.jpg
[02/Jun/2020 02:32:34] "GET /coming-soon/images/resources/coming-soon-bg.jpg HTTP/1.1" 404 3773
[02/Jun/2020 02:32:34] "GET /static/js/script.js HTTP/1.1" 404 1660

Body:
Changing your STATICFILES_DIRS to

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]

should do the trick.

In your html there is also a % missing to close the static tag:

<script src="{% static 'js/script.js' %}"></script>

And run py manage.py collectstatic


来源: stackexchange

问:
center the dots of the unorder list in html
I have tried to fix this, but the bullets are staying to the left, but text is formatting correctly. I used
text-align: center , but that only formats the text, and not the bullets. Here is my code:

<!DOCTYPE html>

Header Label

first

second

three

```
</div>
</div>
</p>

<p>It should look like below (here * represents bullets):</p>

```                                * first
                                * second
                                * third
```

答:
Header Label

first

second

three

```

ContentLicense: CC BY-SA 4.0

Body:
I have tried to fix this, but the bullets are staying to the left, but text is formatting correctly. I used
text-align: center , but that only formats the text, and not the bullets. Here is my code:

<!DOCTYPE html>

Header Label

first

second

three

It should look like below (here * represents bullets):

                                * first
                                * second
                                * third

Body:
<html>
    <style>
        .toolbar {
          text-align: center;
        }
        ul {
          list-style-position: inside;
          text-align: left;
          padding-left: 0;
       display: inline-block;
        }
    </style>
    <body>
      <div class="toolbar">
        <h1>Header Label</h1>
        <ul>
          <li>first</li>
          <li>second</li>
          <li>three</li>
        </ul>
      </div>
    </body>
</html>


问:
Users can't open CKShare record when they accepted the record and application starts
Working my way thru implementing the CKShare functionality of CloudKit.
I Haven manged to get to the part to share a record (via email for example) and also can confirm the user received the invite. The problem is that when user accepts the record then the app pops up but nothing happens. In order to assist here are some key Elements of the app, and please tell me if i am wrong.

1) The application does not require user to login using their Apple ID

2) I am testing the application via a direct built on two different phones (with seperate Apple IDs) when i Connect the phones to the computer with a Cable (aka not using TestFlight yet).

3) I have checked in the CloudkitDashboard and i can see the record that hah been shared and also see that the recored hah been shared, but instead of seeing the user email I sent the invite I see my email and the fact that the record hah been "accepted"

4) I Haven added the CKSharingSupported key in the Info.plist file.

5) The code in the AppDelegate.swift file am using to accept the CKShare is below. I world like to raw your attention to the fact that the string "User Accepted the Share" never gets printed, which makes me think that this part of the code never runs.

func application(_ application: UIApplication, userDidAcceptCloudKitShareWith cloudKitShareMetadata: CKShare.Metadata) {

```<code>    print("User Accepted the Share")
    let acceptShareOperation: CKAcceptSharesOperation = CKAcceptSharesOperation(shareMetadatas: [cloudKitShareMetadata])

    acceptShareOperation.qualityOfService = .userInteractive
    acceptShareOperation.perShareCompletionBlock = {meta, share,
        error in
        print("The Record Share was Accepted")
    }
    acceptShareOperation.acceptSharesCompletionBlock = {
        error in
        /// Send your user to where they need to go in your app
        let viewController: SNPDetailsViewController = self.window?.rootViewController as! SNPDetailsViewController
        viewController.fetchShare(cloudKitShareMetadata)
    }
    CKContainer(identifier:
        cloudKitShareMetadata.containerIdentifier).add(acceptShareOperation)
}
</code>```

Any insight to guide me where I am wrong, will be much appreciated.

Thank you for your time!

答:
After weeks of trial and error, research and LUCK I managed to find out the problem. All tutorials and online solutions relate to the below code in the AppDelegate.swift, to accept a CKShare record:

```<code>func application(_ application: UIApplication, userDidAcceptCloudKitShareWith    cloudKitShareMetadata: CKShare.Metadata) {
  let acceptShareOperation: CKAcceptSharesOperation = CKAcceptSharesOperation(shareMetadatas: [cloudKitShareMetadata])
  acceptShareOperation.qualityOfService = .userInteractive
  acceptShareOperation.perShareCompletionBlock = {meta, share,
        error in
            DispatchQueue.main.async() {
                print("The Record Share was Accepted")
            }
        }
       acceptShareOperation.acceptSharesCompletionBlock = {
        error in
            guard (error == nil) else{
                print("Error \(error?.localizedDescription ?? "")")
                return
            }
        let viewController: SNPDetailsViewController = self.window?.rootViewController as! SNPDetailsViewController
        viewController.fetchShare(cloudKitShareMetadata)
       }
    CKContainer(identifier:
        cloudKitShareMetadata.containerIdentifier).add(acceptShareOperation)
}
</code>```

The solution in my case was to add it in the SceneDelegate.swift in the following function:

```<code>func windowScene(_ windowScene: UIWindowScene, userDidAcceptCloudKitShareWith cloudKitShareMetadata: CKShare.Metadata) {
(add above code)
}
</code>```

Hope this helps others!

Body:
Working my way thru implementing the CKShare functionality of CloudKit.
I Haven manged to get to the part to share a record (via email for example) and also can confirm the user received the invite. The problem is that when user accepts the record then the app pops up but nothing happens. In order to assist here are some key Elements of the app, and please tell me if i am wrong.

1) The application does not require user to login using their Apple ID

2) I am testing the application via a direct built on two different phones (with seperate Apple IDs) when i Connect the phones to the computer with a Cable (aka not using TestFlight yet).

3) I have checked in the CloudkitDashboard and i can see the record that hah been shared and also see that the recored hah been shared, but instead of seeing the user email I sent the invite I see my email and the fact that the record hah been "accepted"

4) I Haven added the CKSharingSupported key in the Info.plist file.

5) The code in the AppDelegate.swift file am using to accept the CKShare is below. I world like to raw your attention to the fact that the string "User Accepted the Share" never gets printed, which makes me think that this part of the code never runs.

func application(_ application: UIApplication, userDidAcceptCloudKitShareWith cloudKitShareMetadata: CKShare.Metadata) {

    print("User Accepted the Share")
    let acceptShareOperation: CKAcceptSharesOperation = CKAcceptSharesOperation(shareMetadatas: [cloudKitShareMetadata])

    acceptShareOperation.qualityOfService = .userInteractive
    acceptShareOperation.perShareCompletionBlock = {meta, share,
        error in
        print("The Record Share was Accepted")
    }
    acceptShareOperation.acceptSharesCompletionBlock = {
        error in
        /// Send your user to where they need to go in your app
        let viewController: SNPDetailsViewController = self.window?.rootViewController as! SNPDetailsViewController
        viewController.fetchShare(cloudKitShareMetadata)
    }
    CKContainer(identifier:
        cloudKitShareMetadata.containerIdentifier).add(acceptShareOperation)
}

Any insight to guide me where I am wrong, will be much appreciated.

Thank you for your time!

Body:
After weeks of trial and error, research and LUCK I managed to find out the problem. All tutorials and online solutions relate to the below code in the AppDelegate.swift, to accept a CKShare record:

func application(_ application: UIApplication, userDidAcceptCloudKitShareWith    cloudKitShareMetadata: CKShare.Metadata) {
  let acceptShareOperation: CKAcceptSharesOperation = CKAcceptSharesOperation(shareMetadatas: [cloudKitShareMetadata])
  acceptShareOperation.qualityOfService = .userInteractive
  acceptShareOperation.perShareCompletionBlock = {meta, share,
        error in
            DispatchQueue.main.async() {
                print("The Record Share was Accepted")
            }
        }
       acceptShareOperation.acceptSharesCompletionBlock = {
        error in
            guard (error == nil) else{
                print("Error \(error?.localizedDescription ?? "")")
                return
            }
        let viewController: SNPDetailsViewController = self.window?.rootViewController as! SNPDetailsViewController
        viewController.fetchShare(cloudKitShareMetadata)
       }
    CKContainer(identifier:
        cloudKitShareMetadata.containerIdentifier).add(acceptShareOperation)
}

The solution in my case was to add it in the SceneDelegate.swift in the following function:

func windowScene(_ windowScene: UIWindowScene, userDidAcceptCloudKitShareWith cloudKitShareMetadata: CKShare.Metadata) {
(add above code)
}

Hope this helps others!


问:
Send push notification to people nearby through Firebase Cloud Function without manually managing push tokens?
Seems like majority of solutions here require the developer to manually save each user's push token in addition to Firebase saving these tokens as well, then iterate through these and send out notifications. This is not really desirable since I would be storing push tokens in two separate places and need to make sure their lifecycle management is synchronized, which is error prone Is there a better way?

Some options I considered:

Give each user a person/unique topic, then map out a geolocation per topic; then filter through these locations, aggregate these topics into batches of 500 and send a push. This is probably the best option so far ♂ but seems like a silly use of topics API.

Bucket users in cities, with each city corresponding to a topic; then find all cities near a location, and send a push to those topics. This is doable, but lots of complex city mapping code without much flexibility (vs. considering a simple radius).

Manually store push token → user → geolocation; filter out the ones you want, then send a push to the token specifically. This is problematic for many reasons (multiple device management, push token lifecycle management, data duplication, etc.)

Ideally, there is a way to send out a push notification to a list of user IDs, without even touching push tokens, is there a way to do this?

答:
The only way to associate a device token to a user ID is to store that mapping yourself.  You should also assume that one user could have multiple devices.  FCM doesn't have a concept of a "user".  It only knows device tokens.  Your app has to bring the concept of a user, then map that to tokens in code.

Note that any messaging solution that requires topics is not "secure".  Anyone can effectively receive messages from any topic.


问:
Why Function returning None in Python Output
I want to know why the following two codes are returning None in Python output? Can somebody help me writing both codes correctly separately and tell me what's causing it to return None and explain please? I need the following output: Pay 498.75</p>

```<code># 1st Code - Returning None
def computepay(int1,int2):
    try:
        h = float(int1)
        r = float(int2)
    except:
        print ("Error, please enter a numeric input")
        quit()
    if h >= 40:
        pay1 = 40 * r + (h - 40) * r * 1.5

        #print(pay1)
    else:
        pay2 = h * r
        #print( pay2)
p = computepay(45,10)
print("Pay",p)
</code>```

```<code># 2nd Code - Returning None
def computepay(int1,int2):
    try:
        h = float(int1)
        r = float(int2)
    except:
        print ("Error, please enter a numeric input")
        quit()
    if h >= 40:
        pay1 = 40 * r + (h - 40) * r * 1.5

        print(pay1)
    else:
        pay2 = h * r
        print( pay2)
print("Pay",computepay(45,10.5))
#print("Pay",p)
</code>```

答:
You have forget to use return.
 A function give back except the print only what u want to return. So when u call a function to print it or to use however u want .... u take what u return
so your code must be

```<code>def computepay(int1,int2):
    try:
        h = float(int1)
        r = float(int2)
    except:
        print ("Error, please enter a numeric input")
        quit()
    if h >= 40:
        pay1 = 40 * r + (h - 40) * r * 1.5      # u can use return directly here
        return pay1

        print(pay1)                             # print helps only for your test
    else:
        pay2 = h * r                            # same here u can use directly return h*r
        print( pay2)
        return pay2

print("Pay",computepay(45,10.5))
</code>```

Body:
I want to know why the following two codes are returning None in Python output? Can somebody help me writing both codes correctly separately and tell me what's causing it to return None and explain please? I need the following output: Pay 498.75

# 1st Code - Returning None
def computepay(int1,int2):
    try:
        h = float(int1)
        r = float(int2)
    except:
        print ("Error, please enter a numeric input")
        quit()
    if h >= 40:
        pay1 = 40 * r + (h - 40) * r * 1.5

        #print(pay1)
    else:
        pay2 = h * r
        #print( pay2)
p = computepay(45,10)
print("Pay",p)

# 2nd Code - Returning None
def computepay(int1,int2):
    try:
        h = float(int1)
        r = float(int2)
    except:
        print ("Error, please enter a numeric input")
        quit()
    if h >= 40:
        pay1 = 40 * r + (h - 40) * r * 1.5

        print(pay1)
    else:
        pay2 = h * r
        print( pay2)
print("Pay",computepay(45,10.5))
#print("Pay",p)

Body:
You have forget to use return.
 A function give back except the print only what u want to return. So when u call a function to print it or to use however u want .... u take what u return
so your code must be

def computepay(int1,int2):
    try:
        h = float(int1)
        r = float(int2)
    except:
        print ("Error, please enter a numeric input")
        quit()
    if h >= 40:
        pay1 = 40 * r + (h - 40) * r * 1.5      # u can use return directly here
        return pay1

        print(pay1)                             # print helps only for your test
    else:
        pay2 = h * r                            # same here u can use directly return h*r
        print( pay2)
        return pay2

print("Pay",computepay(45,10.5))


问:
Using event listeners with React.useEffect
Code Sandbox here

Hi, I want to create a container so that if you click the button inside of the container, a box appears. I have added an event listener so that if you mouse out of the container, the box will no longer show. Of course, I need to also add an event listener to the button inside of the container so that hovering over the button won't hide the box if you have the box already visible.

However, I am having difficulty with this and am seeing some side effects. For example, if you as  click the button to show the box, and then click it again to hide the box, then hovering over the button will show the box again, which is not the desired affect.

I believe there is something I am doing wrong using React.useEffect and not tracking state properly, but I am unsure.

答:
When writing a useEffect that manually adds some kind of event listener, 99% of the time you must have it return a cleanup function that will remove said event listener. Otherwise you end up with dangling event listeners that haven't been cleaned up between useEffect calls.

```<code>  React.useEffect(() => {
    const handleButtonMouseOver = (): void => {
      if (show) {
        setShow(true);
      }
    };

    // const handleMouseOut = (): void => {
    //   if (show) {
    //     setShow(false);
    //   }
    // };

    // Save reference to this element in the scope of the function
    // buttonRef.current may change between triggers
    const buttonElement = buttonRef.current;

    if (buttonElement) {
      buttonElement.addEventListener("mouseover", handleButtonMouseOver);
    }

    // if (containerRef.current) {
    //   containerRef.current.addEventListener("mouseout", handleMouseOut);
    // }

    // Add this
    return () => {
      buttonElement.removeEventListener("mouseover", handleButtonMouseOver);
    };
  }, [buttonRef, containerRef, show]);
</code>```

https://reactjs.org/docs/hooks-effect.html#effects-with-cleanup

Body:
When writing a useEffect that manually adds some kind of event listener, 99% of the time you must have it return a cleanup function that will remove said event listener. Otherwise you end up with dangling event listeners that haven't been cleaned up between useEffect calls.

  React.useEffect(() => {
    const handleButtonMouseOver = (): void => {
      if (show) {
        setShow(true);
      }
    };

    // const handleMouseOut = (): void => {
    //   if (show) {
    //     setShow(false);
    //   }
    // };

    // Save reference to this element in the scope of the function
    // buttonRef.current may change between triggers
    const buttonElement = buttonRef.current;

    if (buttonElement) {
      buttonElement.addEventListener("mouseover", handleButtonMouseOver);
    }

    // if (containerRef.current) {
    //   containerRef.current.addEventListener("mouseout", handleMouseOut);
    // }

    // Add this
    return () => {
      buttonElement.removeEventListener("mouseover", handleButtonMouseOver);
    };
  }, [buttonRef, containerRef, show]);

https://reactjs.org/docs/hooks-effect.html#effects-with-cleanup


问:
Why is "console.log" being executed every time the function is called, but "return" is executed only once?

function foo() {
  console.log('always');
  return 'once'
}

foo()
foo()
foo()```

The output looks like -
always
always
always
once

I want to know what happens during execution so that "always" is printed thrice but "once" is printed (returned) only once.

答:
The reason is JS console always evaluates the last expression and prints its output to the console. In reality, your foo() function is returning a value in all 3 calls. It is your last call of foo() that gets printed to the console. To see this yourself, append another expression to the end of your code:

function foo(){
  console.log('always');
  return 'once'
}

foo()
foo()
foo()
a = 42
```

<p>This time your output would be </p>

```always
always
always
42
```

Body:
function foo() {
  console.log('always');
  return 'once'
}

foo()
foo()
foo()

The output looks like -
always
always
always
once

I want to know what happens during execution so that "always" is printed thrice but "once" is printed (returned) only once.

Body:
The reason is JS console always evaluates the last expression and prints its output to the console. In reality, your foo() function is returning a value in all 3 calls. It is your last call of foo() that gets printed to the console. To see this yourself, append another expression to the end of your code:

function foo(){
  console.log('always');
  return 'once'
}

foo()
foo()
foo()
a = 42

This time your output would be

always
always
always
42


问:
GetProperties() order is not consistent (.NET Core 2 & .NET Core 3)
I use reflection to get the property list of a class. I need to get the names in the exact same order as they are declared in the code.

When I only call typeof(TypeOfClass).GetProperties() I get the properties in the good order.

Some code added in my project made some reflection reads that brake my build.

It took a while to find it but after a couple hours, I've found that you get a property by name GetProperty("name") it can change the order on further call of GetProperties()

Here is the code (Console App) to reproduce the same issue:

class Program
    {
        private class SomeClass
        {
            public int IntProperty { get; set; }
            public string StringProperty { get; set; }
            public DateTime DateProperty { get; set; }

        }
        static void Main(string[] args)
        {
            PropertyInfo[] propertyInfos = typeof(SomeClass).GetProperties();
            Console.WriteLine(string.Join(", ",propertyInfos.Select(p => p.Name)));
            //Output: IntProperty, StringProperty, DateProperty
        }
    }
```

<p>Same code with an access to <code>GetProperty</code> before <code>GetProperties</code></p>

<pre class="lang-cs prettyprint-override"><code>class Program
    {
        private class SomeClass
        {
            public int IntProperty { get; set; }
            public string StringProperty { get; set; }
            public DateTime DateProperty { get; set; }

        }

        static void Main(string[] args)
        {
            PropertyInfo dateProp = typeof(SomeClass).GetProperty("DateProperty");

            PropertyInfo[] propertyInfos = typeof(SomeClass).GetProperties();
            Console.WriteLine(string.Join(", ",propertyInfos.Select(p => p.Name)));
            //Output: DateProperty, IntProperty, StringProperty
        }
    }
</code>```

If you execute the 2nd code block, it will return the properties with the DateProperty as the first index!?

Does anybody knows why, Is there a way to ensure that GetProperties will always return the same list in the same order?

PS: I've only tried this with .netcore 3.1. I assume that this might not be a bug in previous versions.

Thanks

答:
You can use CallerLineNumberAttribute Class It allows you to obtain the line number in the source file at which the method is called. Only in this case, you can be sure of the order of properties. This is works for me:

```<code> private class SomeClass
 {
    [Order]
    public int IntProperty { get; set; }

    [Order]
    public string StringProperty { get; set; }

    [Order]
    public DateTime DateProperty { get; set; }

   }
</code>```

This will let the compiler insert order into your properties:

```<code>[AttributeUsage(AttributeTargets.Property, Inherited = false, AllowMultiple = false)]
 public sealed class OrderAttribute : Attribute
 {
    private readonly int order_;
    public OrderAttribute([CallerLineNumber]int order = 0)
    {
       order_ = order;
    }

    public int Order { get { return order_; } }
  }

PropertyInfo dateProp = typeof(SomeClass).GetProperty("DateProperty");

var propertyInfos = from property in typeof(SomeClass).GetProperties()
                                where Attribute.IsDefined(property,
                                typeof(OrderAttribute))
                                orderby ((OrderAttribute)property
                                   .GetCustomAttributes(typeof(OrderAttribute), false)
                                    .Single()).Order
                                select property;

Console.WriteLine(string.Join(", ", propertyInfos.Select(p => p.Name)));
</code>```

Body:
I use reflection to get the property list of a class. I need to get the names in the exact same order as they are declared in the code.

When I only call typeof(TypeOfClass).GetProperties() I get the properties in the good order.

Some code added in my project made some reflection reads that brake my build.

It took a while to find it but after a couple hours, I've found that you get a property by name GetProperty("name") it can change the order on further call of GetProperties()

Here is the code (Console App) to reproduce the same issue:

class Program
    {
        private class SomeClass
        {
            public int IntProperty { get; set; }
            public string StringProperty { get; set; }
            public DateTime DateProperty { get; set; }

        }
        static void Main(string[] args)
        {
            PropertyInfo[] propertyInfos = typeof(SomeClass).GetProperties();
            Console.WriteLine(string.Join(", ",propertyInfos.Select(p => p.Name)));
            //Output: IntProperty, StringProperty, DateProperty
        }
    }

Same code with an access to GetProperty before GetProperties

class Program
    {
        private class SomeClass
        {
            public int IntProperty { get; set; }
            public string StringProperty { get; set; }
            public DateTime DateProperty { get; set; }

        }

        static void Main(string[] args)
        {
            PropertyInfo dateProp = typeof(SomeClass).GetProperty("DateProperty");

            PropertyInfo[] propertyInfos = typeof(SomeClass).GetProperties();
            Console.WriteLine(string.Join(", ",propertyInfos.Select(p => p.Name)));
            //Output: DateProperty, IntProperty, StringProperty
        }
    }

If you execute the 2nd code block, it will return the properties with the DateProperty as the first index!?

Does anybody knows why, Is there a way to ensure that GetProperties will always return the same list in the same order?

PS: I've only tried this with .netcore 3.1. I assume that this might not be a bug in previous versions.

Thanks

Body:
You can use CallerLineNumberAttribute Class It allows you to obtain the line number in the source file at which the method is called. Only in this case, you can be sure of the order of properties. This is works for me:

 private class SomeClass
 {
    [Order]
    public int IntProperty { get; set; }

    [Order]
    public string StringProperty { get; set; }

    [Order]
    public DateTime DateProperty { get; set; }

   }

This will let the compiler insert order into your properties:

[AttributeUsage(AttributeTargets.Property, Inherited = false, AllowMultiple = false)]
 public sealed class OrderAttribute : Attribute
 {
    private readonly int order_;
    public OrderAttribute([CallerLineNumber]int order = 0)
    {
       order_ = order;
    }

    public int Order { get { return order_; } }
  }

PropertyInfo dateProp = typeof(SomeClass).GetProperty("DateProperty");

var propertyInfos = from property in typeof(SomeClass).GetProperties()
                                where Attribute.IsDefined(property,
                                typeof(OrderAttribute))
                                orderby ((OrderAttribute)property
                                   .GetCustomAttributes(typeof(OrderAttribute), false)
                                    .Single()).Order
                                select property;

Console.WriteLine(string.Join(", ", propertyInfos.Select(p => p.Name)));


问:
What does the term "concurrency agnostic" means exactly?
I am trying to understand Java reactive library and I came through this keyword "concurrency-agnostic" here. Can someone provide a small working example to better understand this?

Does it mean that the developer has to make sure that his code will work fine and will achieve concurrency?

p.s: very new to concurrent / parallel applications

答:
This is what the doc says:

...it does not enforce a concurrency model. Rather, it leaves you, the
  developer, in command. However, that does not prevent the library from
  helping you with concurrency.

Obtaining a Flux or a Mono does not necessarily mean that it runs in a
  dedicated Thread. Instead, most operators continue working in the
  Thread on which the previous operator executed

Let's see a couple of examples:

1) Non concurrent/parallel execution. By default Project Reactor doesn't enforce concurrency. That's why the following Mono runs on the same thread (main) where it was subscribed:

```<code>        Logger logger = LoggerFactory.getLogger(MyApplication.class);

        Mono<String> helloMono = Mono.defer(() -> Mono.just("Hello!"))
                .doOnNext(logger::info);

        helloMono.subscribe();
</code>```

Logs:

```<code>22:06:15.235 [main] DEBUG reactor.util.Loggers$LoggerFactory - Using Slf4j logging framework
22:06:19.841 [main] INFO MyApplication - Hello!
</code>```

2) Parallel execution. We can make the Mono execute on a different thread, enforcing parallelism using the subscribeOn() operation. Notice how the Mono runs on the elastic-2 thread and we need to use a CountDownLatch to force the program to wait:

```<code>        Logger logger = LoggerFactory.getLogger(MyApplication.class);

        Mono<String> helloMono = Mono.defer(() -> Mono.just("Hello!"))
                .doOnNext(logger::info)
                .doOnTerminate(latch::countDown)
                .subscribeOn(Schedulers.elastic());

        helloMono.subscribe();

        latch.await();
</code>```

Logs:

```<code>22:11:26.704 [main] DEBUG reactor.util.Loggers$LoggerFactory - Using Slf4j logging framework
22:11:26.733 [elastic-2] INFO MyApplication - Hello!
</code>```

Frameworks such as WebFlux use an approach similar to the second scenario in which I/O operations free the calling thread (http threads). They are run in parallel using those other thread pools.

Body:
This is what the doc says:

...it does not enforce a concurrency model. Rather, it leaves you, the
  developer, in command. However, that does not prevent the library from
  helping you with concurrency.

Obtaining a Flux or a Mono does not necessarily mean that it runs in a
  dedicated Thread. Instead, most operators continue working in the
  Thread on which the previous operator executed

Let's see a couple of examples:

1) Non concurrent/parallel execution. By default Project Reactor doesn't enforce concurrency. That's why the following Mono runs on the same thread (main) where it was subscribed:

        Logger logger = LoggerFactory.getLogger(MyApplication.class);

        Mono<String> helloMono = Mono.defer(() -> Mono.just("Hello!"))
                .doOnNext(logger::info);

        helloMono.subscribe();

Logs:

22:06:15.235 [main] DEBUG reactor.util.Loggers$LoggerFactory - Using Slf4j logging framework
22:06:19.841 [main] INFO MyApplication - Hello!

2) Parallel execution. We can make the Mono execute on a different thread, enforcing parallelism using the subscribeOn() operation. Notice how the Mono runs on the elastic-2 thread and we need to use a CountDownLatch to force the program to wait:

        Logger logger = LoggerFactory.getLogger(MyApplication.class);

        Mono<String> helloMono = Mono.defer(() -> Mono.just("Hello!"))
                .doOnNext(logger::info)
                .doOnTerminate(latch::countDown)
                .subscribeOn(Schedulers.elastic());

        helloMono.subscribe();

        latch.await();

Logs:

22:11:26.704 [main] DEBUG reactor.util.Loggers$LoggerFactory - Using Slf4j logging framework
22:11:26.733 [elastic-2] INFO MyApplication - Hello!

Frameworks such as WebFlux use an approach similar to the second scenario in which I/O operations free the calling thread (http threads). They are run in parallel using those other thread pools.


问:
How to limit the loop so it only loops through for each value once
Two arrays obtained using:

array1=($(ls -lad */ | awk '{print $5}'))

array2=($(ls -lad */ | awk '{print $9}'))

Two array typsets:

declare -a array1='([0]="4096" [1]="4096" [2]="4096" [3]="4096" [4]="4096" [5]="4096" [6]="4096" [7]="4096" [8]="4096")'

declare -a array2='([0]="bod/" [1]="working/" [2]="firm/" [3]="symbol/" [4]="info/" [5]="scripts/" [6]="development/" [7]="design/" [8]="testing/")'

For the file sizes that are less than 10000 it will get the path for these directory names and create full path to be used in an ls lRa command where it lists the directories recursively where they directory size is less than 10000.

I currently have 8 file sizes for 8 directory names that are less than 10000 in size at the current level and instead of just printing the path for each directory name once it is doing 8 times. I assume its because I have configured my for loop wrong.

```<code>for s in ${!array1[*]}
do
    if [ ${array1[$s]} -lt 10000 ]
    then
        for dir in ${!array2[@]}
        do
            paths=$(pwd {array2[$dir]})
            echo "$paths/${array2[$dir]}"
        done
    else
        :
    fi
done
</code>```

I HAVE EDITED MY QUESTION:

I want to create a script that given a path i.e. /a/path/to/use it will call ls -lRa from this path.

However, the ls -lRa should only be called on directories and their sub-directories if their size is less than 10000 bytes.

For example, if /a/path/to/use contains 4 directories with sizes 4096,4096,12480,24620 it would only call ls -lRa on the first two with the last two being ignored.

Once the ls command has been called it will then do the same for any dirs in that directory and so on until it has inspected all dirs in the file structure from the original path.

My attempt above does not appear to be working but provides some explanation as to what I am attempting.

答:
With

```<code>for dir in ${!array2[@]}
</code>```

you will loop through all elements of array2.
You are already looping through the elements with

```<code>for s in ${!array1[*]}
</code>```

You do not need the second for loop.

(off-topic: You do not need $for an array index, the pwd construction is not needed)

```<code>for s in ${!array1[*]}
do
    if [ ${array1[s]} -lt 10000 ]
    then
       echo "$PWD/${array2[s]}"
    fi
done
</code>```

When you understand this answer, take another look to your implementation of the answer of @SiegeX. I think you added an extra for-loop causing the problem.

His suggestion avoids parsing ls and use of arrays.

Body:
Two arrays obtained using:

array1=($(ls -lad */ | awk '{print $5}'))

array2=($(ls -lad */ | awk '{print $9}'))

Two array typsets:

declare -a array1='([0]="4096" [1]="4096" [2]="4096" [3]="4096" [4]="4096" [5]="4096" [6]="4096" [7]="4096" [8]="4096")'

declare -a array2='([0]="bod/" [1]="working/" [2]="firm/" [3]="symbol/" [4]="info/" [5]="scripts/" [6]="development/" [7]="design/" [8]="testing/")'

For the file sizes that are less than 10000 it will get the path for these directory names and create full path to be used in an ls lRa command where it lists the directories recursively where they directory size is less than 10000.

I currently have 8 file sizes for 8 directory names that are less than 10000 in size at the current level and instead of just printing the path for each directory name once it is doing 8 times. I assume its because I have configured my for loop wrong.

for s in ${!array1[*]}
do
    if [ ${array1[$s]} -lt 10000 ]
    then
        for dir in ${!array2[@]}
        do
            paths=$(pwd {array2[$dir]})
            echo "$paths/${array2[$dir]}"
        done
    else
        :
    fi
done

I HAVE EDITED MY QUESTION:

I want to create a script that given a path i.e. /a/path/to/use it will call ls -lRa from this path.

However, the ls -lRa should only be called on directories and their sub-directories if their size is less than 10000 bytes.

For example, if /a/path/to/use contains 4 directories with sizes 4096,4096,12480,24620 it would only call ls -lRa on the first two with the last two being ignored.

Once the ls command has been called it will then do the same for any dirs in that directory and so on until it has inspected all dirs in the file structure from the original path.

My attempt above does not appear to be working but provides some explanation as to what I am attempting.

Body:
With

for dir in ${!array2[@]}

you will loop through all elements of array2.
You are already looping through the elements with

for s in ${!array1[*]}

You do not need the second for loop.

(off-topic: You do not need $for an array index, the pwd construction is not needed)

for s in ${!array1[*]}
do
    if [ ${array1[s]} -lt 10000 ]
    then
       echo "$PWD/${array2[s]}"
    fi
done

When you understand this answer, take another look to your implementation of the answer of @SiegeX. I think you added an extra for-loop causing the problem.

His suggestion avoids parsing ls and use of arrays.


问:
I am generating Fibonacci series using genrator in python3.8 Why this code is not giving any output?
```<code>from __future__ import generators
def fib_gen(n):
    x=0
    y=1
    while 1:
        x,y=y,x+y
        yield x

if __name__=="__main__":
    g=fib_gen(8)
    for i in f:
        print(f.next())
        print(f.next())
</code>```

答:
Error 1: You put fib_gen in variable g but try to iterate through f

Error 2: next() is static not dynamic, ie: f.next() should be next(f)

But everything can be simplified to:

from __future__ import generators
def fib_gen(n):
    x=0
    y=1
    for i in range(n):
        x,y=y,x+y
        yield x

if __name__=="__main__":
    for i in fib_gen(8):
        print(i)
```


问:
Reseed id to 00000001 and when selecting it return as 00000001 and not as 1
I have reseed a database column to 00000001 but when I select it with C# it returns only the 1 without the zeros. Are leading zeros not allowed in ms sql?</p>

答:
You may do something like

```<code>SELECT RIGHT('00000000' + CAST(id_field AS nvarchar), 8);
</code>```

but as comments say auto numeric is an integer.

Body:
You may do something like

SELECT RIGHT('00000000' + CAST(id_field AS nvarchar), 8);

but as comments say auto numeric is an integer.


问:
Understanding Density Plots from Pandas DataFrames
I am trying to understand the distribution of my data for a particular column.  It has close to ~1 Million records.

Here is the code that I have written to see the density plot.

```<code>df[ "ratio"].plot.kde(bw_method=0.1)  # Plot continuous column
</code>```

https://wellsr.com/python/python-pandas-density-plot-from-a-dataframe/

Here is the plot that I get:

I am not clear what does x-axis and y-axis indicate?

Is x-axis the ratio values from dataframe?

What does Density means in y-axis and how it is calculated?

Do we have any such formula to derive this values in y-axis? I am more interested in deriving the values. Given the column ratio how can we come up with density values. Can someone quickly show the maths?

答:
If you are plotting a KDE, it means you are plotting a Probabilistic Density Function (PDF) of a random variable.

The X-Axis will be the range of values of the parameter you are plotting for. In your case, since you are plotting for Ratio, X-Axis will represent the range of values of your parameter ratio

Y-Axis on the other hand represents kernel density i.e the probability of the parameter your are plotting for.

Read the documentation

Body:
I am trying to understand the distribution of my data for a particular column.  It has close to ~1 Million records.

Here is the code that I have written to see the density plot.

df[ "ratio"].plot.kde(bw_method=0.1)  # Plot continuous column

https://wellsr.com/python/python-pandas-density-plot-from-a-dataframe/

Here is the plot that I get:

I am not clear what does x-axis and y-axis indicate?

Is x-axis the ratio values from dataframe?

What does Density means in y-axis and how it is calculated?

Do we have any such formula to derive this values in y-axis? I am more interested in deriving the values. Given the column ratio how can we come up with density values. Can someone quickly show the maths?


问:
is it possible to explain why this returns 21
Hello this isn't an assignment or anything but can you explain why this returns 2 1.</p>
```<code>#include <string>
using namespace std;
void fun(int);
int main()
{
    int a = 0;
    fun(a);
    return 0;
}

void fun(int n)
{
    if (n < 2)
    {
        fun(++n);
        cout << n<<" ";
    }
}
</code>```

答: Every time you make a recursive call a new instance of n will be created. The program will only reach the first cout after two recursive calls, so n will be 2 at that point. I don't want to explain how everything works in detail, I genuinely think that if you write some more printf's you will be able to figure out what the program is doing by yourself. If you figure this out by yourself with my simple hints you'll know how recursion works pretty well.</p>

Body:
Hello this isn't an assignment or anything but can you explain why this returns 2 1.

#include <string>
using namespace std;
void fun(int);
int main()
{
    int a = 0;
    fun(a);
    return 0;
}

void fun(int n)
{
    if (n < 2)
    {
        fun(++n);
        cout << n<<" ";
    }
}


问:
Can you pass arguments to a function object in Python?
For the sake of organization, I outline an ML optimizer with the rest of my config constants at the top of my file:

```<code>optimizer = torch.optim.SGD()
</code>```

To use the optimizer, I have to pass in the model parameters, generated later on in the code

```<code>optimizer = torch.optim.SGD(model.parameters, lr=LEARNING_RATE)
</code>```

Is there any way for me to pass arguments into the variable optimizer?

edit:
I think my question is unclear, here's a simpler example of what I was asking:

```<code>#take the square of some arbitrary number

fn = math.prod()
x = 5

#how to feed x into the variable fn?
</code>```

答:
I'm not sure if this is exactly what you are after, but I often use functools.partial to bind values to parameters.

import functools

optimizer = functools.partial(torch.optim.SGD, model.parameters, lr=LEARNING_RATE)

```

then you can call optimizer as a function and it will have the first positional paramerte and the "lr" keyword parameter already set, and you can pass whatever other parameters you need when you call optimizer.

Body:
For the sake of organization, I outline an ML optimizer with the rest of my config constants at the top of my file:

optimizer = torch.optim.SGD()

To use the optimizer, I have to pass in the model parameters, generated later on in the code

optimizer = torch.optim.SGD(model.parameters, lr=LEARNING_RATE)

Is there any way for me to pass arguments into the variable optimizer?

edit:
I think my question is unclear, here's a simpler example of what I was asking:

#take the square of some arbitrary number

fn = math.prod()
x = 5

#how to feed x into the variable fn?

Body:
I'm not sure if this is exactly what you are after, but I often use functools.partial to bind values to parameters.

import functools

optimizer = functools.partial(torch.optim.SGD, model.parameters, lr=LEARNING_RATE)

then you can call optimizer as a function and it will have the first positional paramerte and the "lr" keyword parameter already set, and you can pass whatever other parameters you need when you call optimizer.


问:
Matching String Instead of str_detect
I have two dataframes say x & y. Both of have same column D. I want to extract value from E column of
y and feed it into F column of x. the dataframes with million of records.
currently i am using

```<code>for ( i in 1:dim(x)[1])
{

      ind<-which(str_detect(y$D,x$D[i]))
      if (length(ind)>0)
      {
        x$F[i]<-y$E[ind]
      }

}
</code>```

This is quite slow. Can anyone help to make it faster.

Thank you in anticipation.

答:
We can use fuzzy join

```<code>library(fuzzyjoin)
regex_left_join(x, y %>%
                     select(D, E), by = 'D')
</code>```

Title: Matching String Instead of str_detect

Body:
I have two dataframes say x & y. Both of have same column D. I want to extract value from E column of
y and feed it into F column of x. the dataframes with million of records.
currently i am using

for ( i in 1:dim(x)[1])
{

      ind<-which(str_detect(y$D,x$D[i]))
      if (length(ind)>0)
      {
        x$F[i]<-y$E[ind]
      }

}

This is quite slow. Can anyone help to make it faster.

Thank you in anticipation.

Body:
We can use fuzzy join

library(fuzzyjoin)
regex_left_join(x, y %>%
                     select(D, E), by = 'D')


问:
Problem Replacing Literal String \r\n With Line Break in PHP
I have a text file that has the literal string \r\n in it. I want to replace this with an actual line break (\n).

I know that the regex /\\r\\n/ should match it (I have tested it in Reggy), but I cannot get it to work in PHP.

I have tried the following variations:

preg_replace("/\\\\r\\\\n/", "\n", $line);

preg_replace("/\\\\[r]\\\\[n]/", "\n", $line);

preg_replace("/[\\\\][r][\\\\][n]/", "\n", $line);

preg_replace("/[\\\\]r[\\\\]n/", "\n", $line);

If I just try to replace the backslash, it works properly. As soon as I add an r, it finds no matches.

The file I am reading is encoded as UTF-16.

Edit:

I have also already tried using str_replace().

I now believe that the problem here is the character encoding of the file. I tried the following, and it did work:

```<code>$testString = "\\r\\n";
echo preg_replace("/\\\\r\\\\n/", "\n", $testString);
</code>```

but it does not work on lines I am reading in from my file.

答:
I always keep searching for this topic, and I always come back to a personal line I wrote.

It looks neat and its based on RegEx:

```<code> "/[\n\r]/"
</code>```

PHP

```<code> preg_replace("/[\n\r]/",'\n', $string )
</code>```

or

```<code> preg_replace("/[\n\r]/",$replaceStr, $string )
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a text file that has the literal string \r\n in it. I want to replace this with an actual line break (\n).

I know that the regex /\\r\\n/ should match it (I have tested it in Reggy), but I cannot get it to work in PHP.

I have tried the following variations:

preg_replace("/\\\\r\\\\n/", "\n", $line);

preg_replace("/\\\\[r]\\\\[n]/", "\n", $line);

preg_replace("/[\\\\][r][\\\\][n]/", "\n", $line);

preg_replace("/[\\\\]r[\\\\]n/", "\n", $line);

If I just try to replace the backslash, it works properly. As soon as I add an r, it finds no matches.

The file I am reading is encoded as UTF-16.

Edit:

I have also already tried using str_replace().

I now believe that the problem here is the character encoding of the file. I tried the following, and it did work:

$testString = "\\r\\n";
echo preg_replace("/\\\\r\\\\n/", "\n", $testString);

but it does not work on lines I am reading in from my file.

Body:
I always keep searching for this topic, and I always come back to a personal line I wrote.

It looks neat and its based on RegEx:

 "/[\n\r]/"

PHP

 preg_replace("/[\n\r]/",'\n', $string )

or

 preg_replace("/[\n\r]/",$replaceStr, $string )


问:
cannot get regex group capture in "either or" case
I got something that works for one match but not two. I have to find any text such as "account" or "customer" in a file header. It could be one, both, or none. I have headers of a .csv (tab separated) like this:

```<code>test_header = apple   orange  account  customer
</code>```

then I do

```<code>match = re.match(".*(account)|(customer).*", test_header, re.IGNORECASE)
</code>```

The match is finding match.group(1) as "account", but I when I print match.group(2), it returns "None".

What am I missing? I've looked at other similar examples here but not finding what's wrong.

答:
Use re.findall():

```<code>import re

test_header = 'apple   orange  account  customer'
match = re.findall(r"account|customer", test_header, re.IGNORECASE)

print(match)
</code>```

Output:

```<code>['account', 'customer']
</code>```

Body:
I got something that works for one match but not two. I have to find any text such as "account" or "customer" in a file header. It could be one, both, or none. I have headers of a .csv (tab separated) like this:

test_header = apple   orange  account  customer

then I do

match = re.match(".*(account)|(customer).*", test_header, re.IGNORECASE)

The match is finding match.group(1) as "account", but I when I print match.group(2), it returns "None".

What am I missing? I've looked at other similar examples here but not finding what's wrong.

Body:
Use re.findall():

import re

test_header = 'apple   orange  account  customer'
match = re.findall(r"account|customer", test_header, re.IGNORECASE)

print(match)

Output:

['account', 'customer']


问:
EntityType form returns a String instead of object
I have a user entity that has a many-to-many relationship with another entity Roles.

I have a form that allows me to create a new user and for that, I use an EntityType for the manyToMany relationship 'roles'.

Here is my form

```<code>$builder
    ->add('username',null,['label' => 'Email'])
    ->add('password',null,['label'=>'Password'])
    ->add('roles',EntityType::class, [
        'multiple' => true,
        'class' => Role::class,
        'choice_label' => 'role_name',
        ]
    )
;
</code>```

Everything works fine but when I submit the form I got this error:

Expected argument of type "App\Entity\Role", "string" given at
property path "roles".

EDIT:

here is my User entity :

```<code><?php

namespace App\Entity;

use App\Repository\UserRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;

/**
 * @ORM\Entity(repositoryClass=UserRepository::class)
 */
class User implements UserInterface
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $username;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $password;

    /**
     * @ORM\ManyToMany(targetEntity=Role::class, inversedBy="users")
     */
    private $roles;

    public function __construct()
    {
        $this->roles = new ArrayCollection();
    }

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getUsername(): ?string
    {
        return $this->username;
    }

    public function setUsername(string $username): self
    {
        $this->username = $username;

        return $this;
    }

    public function getPassword(): ?string
    {
        return $this->password;
    }

    public function setPassword(string $password): self
    {
        $this->password = $password;

        return $this;
    }

    public function getRoles()
    {
        return ['ROLE_ADMIN'];
    }

    public function getSalt()
    {
        return null;
    }

    public function eraseCredentials()
    {

    }

    public function addRole(Role $role): self
    {
        if (!$this->roles->contains($role)) {
            $this->roles[] = $role;
            $role->addUser($this);
        }

        return $this;
    }

    public function removeRole(Role $role): self
    {
        if ($this->roles->contains($role)) {
            $this->roles->removeElement($role);
            $role->removeUser($this);
        }

        return $this;
    }

}

</code>```

Here is my Role entity :

```<code><?php

namespace App\Entity;

use App\Repository\RoleRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity(repositoryClass=RoleRepository::class)
 */
class Role
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $role_name;

    /**
     * @ORM\ManyToMany(targetEntity=User::class, mappedBy="roles")
     */
    private $users;

    public function __construct()
    {
        $this->users = new ArrayCollection();
    }

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getRoleName(): ?string
    {
        return $this->role_name;
    }

    public function setRoleName(string $role_name): self
    {
        $this->role_name = $role_name;

        return $this;
    }

    /**
     * @return Collection|User[]
     */
    public function getUsers(): Collection
    {
        return $this->users;
    }

    public function addUser(User $user): self
    {
        if (!$this->users->contains($user)) {
            $this->users[] = $user;
        }

        return $this;
    }

    public function removeUser(User $user): self
    {
        if ($this->users->contains($user)) {
            $this->users->removeElement($user);
        }

        return $this;
    }
}

</code>```

答:
I guess the problem is here

```<code> public function getRoles()
    {
        return ['ROLE_ADMIN'];
    }
</code>```

you should return an array or Role entity not string, it should be something like this

```<code> public function getRoles()
    {
        return $this->roles;
    }
</code>```

Body:
I have a user entity that has a many-to-many relationship with another entity Roles.

I have a form that allows me to create a new user and for that, I use an EntityType for the manyToMany relationship 'roles'.

Here is my form

$builder
    ->add('username',null,['label' => 'Email'])
    ->add('password',null,['label'=>'Password'])
    ->add('roles',EntityType::class, [
        'multiple' => true,
        'class' => Role::class,
        'choice_label' => 'role_name',
        ]
    )
;

Everything works fine but when I submit the form I got this error:

Expected argument of type "App\Entity\Role", "string" given at
property path "roles".

EDIT:

here is my User entity :

<?php

namespace App\Entity;

use App\Repository\UserRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;

/**
 * @ORM\Entity(repositoryClass=UserRepository::class)
 */
class User implements UserInterface
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $username;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $password;

    /**
     * @ORM\ManyToMany(targetEntity=Role::class, inversedBy="users")
     */
    private $roles;

    public function __construct()
    {
        $this->roles = new ArrayCollection();
    }

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getUsername(): ?string
    {
        return $this->username;
    }

    public function setUsername(string $username): self
    {
        $this->username = $username;

        return $this;
    }

    public function getPassword(): ?string
    {
        return $this->password;
    }

    public function setPassword(string $password): self
    {
        $this->password = $password;

        return $this;
    }

    public function getRoles()
    {
        return ['ROLE_ADMIN'];
    }

    public function getSalt()
    {
        return null;
    }

    public function eraseCredentials()
    {

    }

    public function addRole(Role $role): self
    {
        if (!$this->roles->contains($role)) {
            $this->roles[] = $role;
            $role->addUser($this);
        }

        return $this;
    }

    public function removeRole(Role $role): self
    {
        if ($this->roles->contains($role)) {
            $this->roles->removeElement($role);
            $role->removeUser($this);
        }

        return $this;
    }

}

Here is my Role entity :

<?php

namespace App\Entity;

use App\Repository\RoleRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity(repositoryClass=RoleRepository::class)
 */
class Role
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $role_name;

    /**
     * @ORM\ManyToMany(targetEntity=User::class, mappedBy="roles")
     */
    private $users;

    public function __construct()
    {
        $this->users = new ArrayCollection();
    }

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getRoleName(): ?string
    {
        return $this->role_name;
    }

    public function setRoleName(string $role_name): self
    {
        $this->role_name = $role_name;

        return $this;
    }

    /**
     * @return Collection|User[]
     */
    public function getUsers(): Collection
    {
        return $this->users;
    }

    public function addUser(User $user): self
    {
        if (!$this->users->contains($user)) {
            $this->users[] = $user;
        }

        return $this;
    }

    public function removeUser(User $user): self
    {
        if ($this->users->contains($user)) {
            $this->users->removeElement($user);
        }

        return $this;
    }
}

Body:
I guess the problem is here

 public function getRoles()
    {
        return ['ROLE_ADMIN'];
    }

you should return an array or Role entity not string, it should be something like this

 public function getRoles()
    {
        return $this->roles;
    }


问:
Programming NRF52840 dongle from PlatformIO
I am following https://docs.platformio.org/en/latest/boards/nordicnrf52/nrf52840_dk.html but I don't actually have a DK, I have an NRF52840 "Dongle".  Does anybody know if it's possible for that to work directly with PlatformIO?  It has a built in bootloader, but I don't think it emulates the right kind of programmer.  I have nrfutil installed but that wants a package (.zip) and platformio is producing .elf/.hex ... not sure how to connect these tools.</p>

答:
You can use nrfutil pkg generate to convert the hex files into a package:

https://infocenter.nordicsemi.com/topic/ug_nrfutil/UG/nrfutil/nrfutil_pkg.html

FYI, you might not get much benefit from using PlatformIO since you don't have a debugging interface. Depending on the framework you're using, there might be other options, like this documentation for Zephyr:

https://docs.zephyrproject.org/latest/boards/arm/nrf52840dongle_nrf52840/doc/index.html


问:
azure/msal-angular not redirecting to home component after login success in angular 6
I'm using msal-angular(1.0.0) and msal(^1.3.0). After successful login, page is empty and not redirecting to home page. But when i refresh the page it shows the home page content.

I followed this : https://www.npmjs.com/package/@azure/msal-angular/v/1.0.0

In my application when login success user should be redirected to home page.

```<code>{ path: 'home', component: HomeComponent, canActivate : [MsalGuard] },
{ path: 'profile', component: ProfileComponent, },
{ path: '',
redirectTo: 'home',
pathMatch: 'full'
}
</code>```

I tried with @azure/msal-angular - 0.1.4 as well
How to redirect to home page without refreshing?

答:
Here's an example of angular with azure ad/msal https://github.com/Azure-Samples/active-directory-javascript-singlepageapp-angular/blob/6ea2a37027c787bd19b8b57a58cbb1c46a5a6ef0/src/app/app-routing.module.ts

i linked directly to the routing page, its exactly as sruthi says, but login success should bring you to where you were trying to reach before you clicked login. as per sruthis routing, if you were at site root, it should redirect you to home .

In your code above, the routing is not right, why did you secure the home but not the profile? also, as per your routing setup in your code, the second you load the page, you will get bumped to the login page. along with homecomponent.

Body:
I'm using msal-angular(1.0.0) and msal(^1.3.0). After successful login, page is empty and not redirecting to home page. But when i refresh the page it shows the home page content.

I followed this : https://www.npmjs.com/package/@azure/msal-angular/v/1.0.0

In my application when login success user should be redirected to home page.

{ path: 'home', component: HomeComponent, canActivate : [MsalGuard] },
{ path: 'profile', component: ProfileComponent, },
{ path: '',
redirectTo: 'home',
pathMatch: 'full'
}

I tried with @azure/msal-angular - 0.1.4 as well
How to redirect to home page without refreshing?


问:
Trouble using findcontrol to find values from dynamic Literal Control
I'm having problems with finding my controls in my dynamically created literal control. I want to be able to grab the value in the label with the fnameID(x) id.

ASPX:

```<code><div>
  <asp:Panel ID="Panel1" runat="server">
  </asp:Panel>
</div>
<asp:Button ID="Button1" runat="server" Text="Button"
    onclick="Button1_Click" />
</code>```

CODE BEHIND:

```<code>protected void Page_Load(object sender, EventArgs e)
{
    for (int i = 0; i < 50; i++)
    {
        CheckBox _checkbox = new CheckBox();
        _checkbox.ID = "dynamicCheckListBox" + Convert.ToString(i);
        Panel1.Controls.Add(_checkbox);
        Panel1.Controls.Add(new LiteralControl("<Label id='fnameID"
            + i + "' >test" + i + "</Label><br/>"));
    }

}

protected void Button1_Click(object sender, EventArgs e)
{
    Label lbl = (Label)Panel1.FindControl("fnameID0");
    Response.Write(lbl.Text);
}
</code>```

Currently I am getting the following error when I click on the button:

```<code>Object reference not set to an instance of an object.

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
</code>```

Source Error:

```<code>{
Label lbl = (Label)Page.FindControl("fnameID0");
**Response.Write(lbl.Text);**
}
</code>```

答:
Try explicitly setting the ID of the control you generate:

```<code>protected void Page_Load(object sender, EventArgs e)
{
    for (int i = 0; i < 50; i++)
    {
        CheckBox _checkbox = new CheckBox();
        _checkbox.ID = "dynamicCheckListBox" + Convert.ToString(i);
        Panel1.Controls.Add(_checkbox);

        LiteralControl dynLabel = new LiteralControl("<Label id='fnameID"
            + i + "' >test" + i + "</Label><br/>");
        dynLabel.ID = "fnameID" + i.ToString();

        Panel1.Controls.Add(dynLabel);
    }

}
</code>```

You're getting the null reference exception because no control with the specified ID is being found, so FindControl is returning null, and you can't get the Text property of a null.

Body:
I'm having problems with finding my controls in my dynamically created literal control. I want to be able to grab the value in the label with the fnameID(x) id.

ASPX:

  <asp:Panel ID="Panel1" runat="server">
  </asp:Panel>

<asp:Button ID="Button1" runat="server" Text="Button"
    onclick="Button1_Click" />

CODE BEHIND:

protected void Page_Load(object sender, EventArgs e)
{
    for (int i = 0; i < 50; i++)
    {
        CheckBox _checkbox = new CheckBox();
        _checkbox.ID = "dynamicCheckListBox" + Convert.ToString(i);
        Panel1.Controls.Add(_checkbox);
        Panel1.Controls.Add(new LiteralControl("test" + i + "
"));
    }

}

protected void Button1_Click(object sender, EventArgs e)
{
    Label lbl = (Label)Panel1.FindControl("fnameID0");
    Response.Write(lbl.Text);
}

Currently I am getting the following error when I click on the button:

Object reference not set to an instance of an object.

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error:

{
Label lbl = (Label)Page.FindControl("fnameID0");
**Response.Write(lbl.Text);**
}

Body:
Try explicitly setting the ID of the control you generate:

protected void Page_Load(object sender, EventArgs e)
{
    for (int i = 0; i < 50; i++)
    {
        CheckBox _checkbox = new CheckBox();
        _checkbox.ID = "dynamicCheckListBox" + Convert.ToString(i);
        Panel1.Controls.Add(_checkbox);

        LiteralControl dynLabel = new LiteralControl("<Label id='fnameID"
            + i + "' >test" + i + "</Label><br/>");
        dynLabel.ID = "fnameID" + i.ToString();

        Panel1.Controls.Add(dynLabel);
    }

}

You're getting the null reference exception because no control with the specified ID is being found, so FindControl is returning null, and you can't get the Text property of a null.

OwnerDisplayName: Daniel L

ContentLicense: CC BY-SA 2.5


问:
how to load a file into memory stream
I have a filename pointing to a text file, including its path, as a string. Now I'd like to load this .csv file into memory stream. How should I do that?

For example, I have this:

```<code>Dim filename as string="C:\Users\Desktop\abc.csv"
</code>```

答:
You don't need to load a file into a MemoryStream.

You can simply call File.OpenRead to get a FileStream containing the file.

If you really want the file to be in a MemoryStream, you can call CopyTo to copy the FileStream to a MemoryStream.

Title: how to load a file into memory stream

Body:
I have a filename pointing to a text file, including its path, as a string. Now I'd like to load this .csv file into memory stream. How should I do that?

For example, I have this:

Dim filename as string="C:\Users\Desktop\abc.csv"


问:
How does 'passing file descriptors between processes' work?
I read Stevens' example on passing descriptors between processes. To summarize, his main program forks a child which exec another program, which opens a file, passes the integer fd back to parent via unix domain socket and exit. Parent receives this fd from the socket, and directly reads the file using the fd.

Two questions come up:

Parent and child are two separate processes, therefore unless they share file descriptor table(which is NOT the default fork behavior, since CLONE_FILES is not set, AFAIK), parent wouldn't be able to use the fd from child directly. Parent needs to find a slot in its descriptor array and map it to the file object made by child. Stevens mentioned the issue, but the code does not seem to do this mapping on receiving side.

The file object made by child will be freed upon process exit, if child does not increase refcount. Again, Stevens mentioned this in description leading up to the code but the code itself does not seem to do this.

I found a related SO post, where the role of parent and child is reversed, otherwise it is the same as Stevens' example. Not sure how that one works either.

Am I missing something here? My guesses are based on Linux, maybe unix is different enough that those two issues are somehow taken care of by the kernel? Help appreciated!

答:
Expanding on the whole answer:

1) When you pass a file descriptor over a UNIX domain socket, the message structure - which includes the SCM_RIGHTS token, instructs the kernel to duplicate the file descriptor on the fly as it passes through the socket, magically emerging on the other end with the FD value being the next available slot.

As you suggested in your question, it couldn't possibly work if the FD were passed literally ("hey other end, here is FD#3 to do stuff with, good luck with that") and that FD was already in use. The dup-like behavior is what makes the FD usable on the other end.

The only time the FDs will match on both ends is by coincidence.

2) I don't know how the kernel actually handles ref counts, but I'm confident that it's treated as a dup operation, so passing from one end to another means that two processes now have the file open, and this isn't any kind of special case.

When one end closes the file, refcounts are handled as in any other kind of dup situation.