问:
Times, Quotient and Remainder predicates in Prolog
how can I do the following.

I needed to define the predicate shownumber (X,N), which is true when the symbol X corresponds to the natural number N. For example, shownumber(s(zero),1) is true. Okay, now I've got a predicate:

```<code>shownumber (zero, 0).
shownumber (s (N), X): - shownumber (N, Y), X is Y + 1.
</code>```

Now I need to use the shownumber (X, Y) predicate to define:

1) times (X, Y, Z) which is true if X * Y = Z.

2) quotient (X, Y, Q) which is true if X / Y = Q (in natural number arithmetic)

3) remainder (X, Y, R) which is true if X divided by Y gives the remainder R.

The quotient (X, Y, Q) and the remainder (X, Y, R) must be defined for Y = zero.

How can I do that? Could you help me with this one?

答:
This code may help:

peano_redux.pl

It took me a long time to finish it and it still has bad corners. I tried to stay "close the Peano Axioms" but some shortcuts had to be taken - this is programming, not general theorem proving.

I also used the old-school & messy Peano notation s(s(s(s(z))) instead the far cleaner and appropriate list-based notation: [s,s,s,s].

It would be extremely cool to be able to set up a constraint between two
variables PN and NN, so that if NN is bound to a natural number, PN is
automatically bound to the coressponding Peano Number, and vice-versa.
That can probably be done with some effort using attributed variables, but I haven't thought about that.

Computation is expectedly very slow. It would be interesting to try tabling on the padd/pmult predicates.

The bidirectional transformation between Peano Numbers and Naturals exists in two version: One using CLP(FD) and one using basic Prolog. Comment out the version you don't want.

This is overall an interesting (but time-consuming exercise). It gives a lot of practice in debugging and thinking about control flow, and forces you to watch out for undesired unification, non-termination, early termination  and special cases of bound/fresh variable configurations.

It also highlights the absolute need to write unit tests as you program, to give you a scaffolding for progress,

Seemingly innocuous rearrangements of code may cause a previously working Prolog program to fail or loop indefinitely for hard-to-explain reasons. Having test cases to get back on track avoids meaninglessly burning time on "fixing things until they work" and possibly "running tests by hand".

Unit tests are also of great use for communicating your problem's specification Programming courses should really orbit around that concept first - this isn't the 80s anymore.

Run all test cases by issuing command rtall for great success:

```<code>?- rt_all.
Correct to: "rtall"? yes
% PL-Unit: pm ................... done
% All 19 tests passed
% PL-Unit: pnat ......... done
% All 9 tests passed
% PL-Unit: pequal .... done
% All 4 tests passed
% PL-Unit: padd ................................. done
% All 33 tests passed
% PL-Unit: pless ................. done
% All 17 tests passed
% PL-Unit: pmult .......................
% 1,649 inferences, 0.000 CPU in 0.000 seconds (100% CPU, 8951351 Lips)
.
% 3,097 inferences, 0.000 CPU in 0.000 seconds (98% CPU, 10109979 Lips)
.
% 5,813 inferences, 0.001 CPU in 0.001 seconds (100% CPU, 11183341 Lips)
.
% 2,598 inferences, 0.000 CPU in 0.000 seconds (100% CPU, 9577492 Lips)
.
% 768 inferences, 0.000 CPU in 0.000 seconds (100% CPU, 8491724 Lips)
.
% 1,847 inferences, 0.000 CPU in 0.000 seconds (96% CPU, 9731501 Lips)
.
% 8,453,914 inferences, 0.668 CPU in 0.674 seconds (99% CPU, 12651865 Lips)
.
% 4,273 inferences, 0.000 CPU in 0.000 seconds (100% CPU, 10987655 Lips)
.
% 8,389 inferences, 0.001 CPU in 0.001 seconds (99% CPU, 11702424 Lips)
.
% 12,506 inferences, 0.001 CPU in 0.001 seconds (100% CPU, 11900038 Lips)
.
% 45,453 inferences, 0.004 CPU in 0.004 seconds (100% CPU, 11844692 Lips)
. done
% All 34 tests passed
% PL-Unit: pqr ................Found: 16*13+8=216
Found: 37*12+8=452
Found: 7*53+1=372
Found: 28*7+13=209
Found: 33*14+6=468
Found: 23*5+19=134
Found: 21*3+3=66
Found: 31*8+1=249
Found: 14*20+9=289
Found: 5*2+4=14
Found: 4*9+0=36
Found: 30*3+6=96
Found: 40*11+16=456
Found: 11*4+8=52
Found: 10*12+3=123
Found: 18*20+0=360
Found: 5*61+2=307
Found: 46*2+0=92
Found: 1*215+0=215
Found: 47*7+30=359
. done
% All 17 tests passed
true.
</code>```

Some references vaguely consulted:

Natural number

Peano axioms

Proofs involving the addition of natural
numbers

Body:
how can I do the following.

I needed to define the predicate shownumber (X,N), which is true when the symbol X corresponds to the natural number N. For example, shownumber(s(zero),1) is true. Okay, now I've got a predicate:

shownumber (zero, 0).
shownumber (s (N), X): - shownumber (N, Y), X is Y + 1.

Now I need to use the shownumber (X, Y) predicate to define:

1) times (X, Y, Z) which is true if X * Y = Z.

2) quotient (X, Y, Q) which is true if X / Y = Q (in natural number arithmetic)

3) remainder (X, Y, R) which is true if X divided by Y gives the remainder R.

The quotient (X, Y, Q) and the remainder (X, Y, R) must be defined for Y = zero.

How can I do that? Could you help me with this one?

Body:
This code may help:

peano_redux.pl

It took me a long time to finish it and it still has bad corners. I tried to stay "close the Peano Axioms" but some shortcuts had to be taken - this is programming, not general theorem proving.

I also used the old-school & messy Peano notation s(s(s(s(z))) instead the far cleaner and appropriate list-based notation: [s,s,s,s].

It would be extremely cool to be able to set up a constraint between two
variables PN and NN, so that if NN is bound to a natural number, PN is
automatically bound to the coressponding Peano Number, and vice-versa.
That can probably be done with some effort using attributed variables, but I haven't thought about that.

Computation is expectedly very slow. It would be interesting to try tabling on the padd/pmult predicates.

The bidirectional transformation between Peano Numbers and Naturals exists in two version: One using CLP(FD) and one using basic Prolog. Comment out the version you don't want.

This is overall an interesting (but time-consuming exercise). It gives a lot of practice in debugging and thinking about control flow, and forces you to watch out for undesired unification, non-termination, early termination  and special cases of bound/fresh variable configurations.

It also highlights the absolute need to write unit tests as you program, to give you a scaffolding for progress,

Seemingly innocuous rearrangements of code may cause a previously working Prolog program to fail or loop indefinitely for hard-to-explain reasons. Having test cases to get back on track avoids meaninglessly burning time on "fixing things until they work" and possibly "running tests by hand".

Unit tests are also of great use for communicating your problem's specification Programming courses should really orbit around that concept first - this isn't the 80s anymore.

Run all test cases by issuing command rtall for great success:

?- rt_all.
Correct to: "rtall"? yes
% PL-Unit: pm ................... done
% All 19 tests passed
% PL-Unit: pnat ......... done
% All 9 tests passed
% PL-Unit: pequal .... done
% All 4 tests passed
% PL-Unit: padd ................................. done
% All 33 tests passed
% PL-Unit: pless ................. done
% All 17 tests passed
% PL-Unit: pmult .......................
% 1,649 inferences, 0.000 CPU in 0.000 seconds (100% CPU, 8951351 Lips)
.
% 3,097 inferences, 0.000 CPU in 0.000 seconds (98% CPU, 10109979 Lips)
.
% 5,813 inferences, 0.001 CPU in 0.001 seconds (100% CPU, 11183341 Lips)
.
% 2,598 inferences, 0.000 CPU in 0.000 seconds (100% CPU, 9577492 Lips)
.
% 768 inferences, 0.000 CPU in 0.000 seconds (100% CPU, 8491724 Lips)
.
% 1,847 inferences, 0.000 CPU in 0.000 seconds (96% CPU, 9731501 Lips)
.
% 8,453,914 inferences, 0.668 CPU in 0.674 seconds (99% CPU, 12651865 Lips)
.
% 4,273 inferences, 0.000 CPU in 0.000 seconds (100% CPU, 10987655 Lips)
.
% 8,389 inferences, 0.001 CPU in 0.001 seconds (99% CPU, 11702424 Lips)
.
% 12,506 inferences, 0.001 CPU in 0.001 seconds (100% CPU, 11900038 Lips)
.
% 45,453 inferences, 0.004 CPU in 0.004 seconds (100% CPU, 11844692 Lips)
. done
% All 34 tests passed
% PL-Unit: pqr ................Found: 16*13+8=216
Found: 37*12+8=452
Found: 7*53+1=372
Found: 28*7+13=209
Found: 33*14+6=468
Found: 23*5+19=134
Found: 21*3+3=66
Found: 31*8+1=249
Found: 14*20+9=289
Found: 5*2+4=14
Found: 4*9+0=36
Found: 30*3+6=96
Found: 40*11+16=456
Found: 11*4+8=52
Found: 10*12+3=123
Found: 18*20+0=360
Found: 5*61+2=307
Found: 46*2+0=92
Found: 1*215+0=215
Found: 47*7+30=359
. done
% All 17 tests passed
true.

Some references vaguely consulted:

Natural number

Peano axioms

Proofs involving the addition of natural
numbers


来源: stackexchange

问:
Can't get the second View to show. Probably hidden under first view?
I have a layout which consists of a TableLayout and a WebView. Only one of which should be shown. I've set all Views to visibility:gone. So, if the TableView is atop, I can't see the WebView and vice versa.

My Layout file looks like this:

```<code><androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.swiperefreshlayout.widget.SwipeRefreshLayout
        android:id="@+id/swipe"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="?attr/colorPrimary">

        <androidx.core.widget.NestedScrollView
            android:id="@+id/nest1"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:visibility="gone">

            <TableLayout
                android:id="@+id/tableLayout2"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:stretchColumns="3"
                android:visibility="gone">

                <TableRow
                    android:id="@+id/tableRow0"
                    android:background="@color/design_default_color_background"
                    android:visibility="gone">

                    <TextView
                        android:id="@+id/textView1"
                        android:text="Linie"
                        android:textColor="?attr/colorPrimary" />

                    <TextView
                        android:id="@+id/textView2"
                        android:text="Endstation"
                        android:textColor="?attr/colorPrimary" />

                    <TextView
                        android:id="@+id/textView3"
                        android:text="Abfahrt"
                        android:textColor="?attr/colorPrimary" />

                </TableRow>

            </TableLayout>

        </androidx.core.widget.NestedScrollView>

        <androidx.core.widget.NestedScrollView
            android:id="@+id/nest2"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:visibility="gone">

            <WebView
                android:id="@+id/webView2"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_gravity="top|center"
                android:visibility="gone" />
        </androidx.core.widget.NestedScrollView>

    </androidx.swiperefreshlayout.widget.SwipeRefreshLayout>

</androidx.coordinatorlayout.widget.CoordinatorLayout>
</code>```

If I switch Tableview with Webview, then I can see the webview, but not the Tableview. Even thought all are set to GONE and I set the one view I want to see to VISIBLE.

I guess the second view is at the bottom of the first view and is there but "hidden".

How do I fix this?

Thanks

Edit:
Code to enable/disable view looks like this

```<code>        NestedScrollView v1 = findViewById(R.id.nest1);
        NestedScrollView v2 = findViewById(R.id.nest2);
        TableLayout layout = findViewById(R.id.tableLayout2);
        TableRow row = findViewById(R.id.tableRow0);
        WebView wv2 = findViewById(R.id.webView2);

            v1.setVisibility(View.GONE);
            v2.setVisibility(View.VISIBLE);
            layout.setVisibility(View.GONE);
            row.setVisibility(View.VISIBLE);
            wv2.setVisibility(View.VISIBLE);
</code>```

答: You use match_parent size for WebView and TableView, so one of views displayed on whole screen and another one doesn't have enough space for inflating. Change height and width for one of views to wrap_content. It maybe helps you.</p>

ContentLicense: CC BY-SA 4.0

Body:
I have a layout which consists of a TableLayout and a WebView. Only one of which should be shown. I've set all Views to visibility:gone. So, if the TableView is atop, I can't see the WebView and vice versa.

My Layout file looks like this:

<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.swiperefreshlayout.widget.SwipeRefreshLayout
        android:id="@+id/swipe"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="?attr/colorPrimary">

        <androidx.core.widget.NestedScrollView
            android:id="@+id/nest1"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:visibility="gone">

            <TableLayout
                android:id="@+id/tableLayout2"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:stretchColumns="3"
                android:visibility="gone">

                <TableRow
                    android:id="@+id/tableRow0"
                    android:background="@color/design_default_color_background"
                    android:visibility="gone">

                    <TextView
                        android:id="@+id/textView1"
                        android:text="Linie"
                        android:textColor="?attr/colorPrimary" />

                    <TextView
                        android:id="@+id/textView2"
                        android:text="Endstation"
                        android:textColor="?attr/colorPrimary" />

                    <TextView
                        android:id="@+id/textView3"
                        android:text="Abfahrt"
                        android:textColor="?attr/colorPrimary" />

                </TableRow>

            </TableLayout>

        </androidx.core.widget.NestedScrollView>

        <androidx.core.widget.NestedScrollView
            android:id="@+id/nest2"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:visibility="gone">

            <WebView
                android:id="@+id/webView2"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_gravity="top|center"
                android:visibility="gone" />
        </androidx.core.widget.NestedScrollView>

    </androidx.swiperefreshlayout.widget.SwipeRefreshLayout>

</androidx.coordinatorlayout.widget.CoordinatorLayout>

If I switch Tableview with Webview, then I can see the webview, but not the Tableview. Even thought all are set to GONE and I set the one view I want to see to VISIBLE.

I guess the second view is at the bottom of the first view and is there but "hidden".

How do I fix this?

Thanks

Edit:
Code to enable/disable view looks like this

        NestedScrollView v1 = findViewById(R.id.nest1);
        NestedScrollView v2 = findViewById(R.id.nest2);
        TableLayout layout = findViewById(R.id.tableLayout2);
        TableRow row = findViewById(R.id.tableRow0);
        WebView wv2 = findViewById(R.id.webView2);

            v1.setVisibility(View.GONE);
            v2.setVisibility(View.VISIBLE);
            layout.setVisibility(View.GONE);
            row.setVisibility(View.VISIBLE);
            wv2.setVisibility(View.VISIBLE);


问:
Azure Active Directory with Biometrics and certificates for mobile app
I am looking for help with the topic of user authorization via biometrics or certificates in my mobile app. What I need to find out is how to setup the Azure Active Directory as well as the whole authorization process.

Currently, I have an application registered in the Azure Portal under App Registration, there are quick start guides for UWP/Windows and other platforms - they all work fine with email and password. I have no idea what are the requirements and how to setup the biometrics or certificates authentication.

I read that if I want to use certificates then I need something called "Root certificate authority" and in terms of Azure, it looks like I need a virtual machine - is that correct?

Can someone please guide me through the whole process of setting up the users in Azure Active Directory and then enabling the biometrics in my app?

Kindest regards,
Joseph

答:
you can look here for passwordless auth on azure here:
https://learn.microsoft.com/en-us/azure/active-directory/authentication/concept-authentication-passwordless
you can use the microsoft authentication app or use a fido2 compatible system from one of the products/services that have fido2 with biometrics passwordless.

to enable passwordless on your azure tenant,

https://learn.microsoft.com/en-us/azure/active-directory/authentication/howto-authentication-passwordless-phone

The other option is to use the android/ios fingerprint/touch id to unlock refresh tokens to log into azure ad. in this way, you would need to first log into azure, then store the refresh token and secure it using the mobile platforms fingerprint stuff. suggestion from here: Sign in with fingerprint in oauth 2.0

I'm not sure if this answers your question, but it's somewhere to start reading.


问:
sort Array by another Array like GroupBy NodeJs
Hello I have two array and I want to sort them another array but i want to sort like group by.

```<code>var a = [1,2,3,2,1,3,3,2,1]
var b = [b,b,b,c,c,c,d,d,d]
</code>```

The result I want like;

```<code>var a =[3,2,1,3,2,1,3,2,1]
var b =[b,b,b,c,c,c,d,d,d]
</code>```

答:
If you had an array of pairs like this

```<code>const arr = [ {a:1, b:'b'} , {a:2, b:'b'}, {a:3, b:'b'},
              {a:2, b:'c'} , {a:1, b:'c'}, {a:3, b:'c'},
              {a:3, b:'d'} , {a:2, b:'d'}, {a:1, b:'d'} ]
</code>```

you would establish a link between the two arrays in your question.

You could sort that array into an order descending on the a and ascending on the b  like this

```<code> arr.sort ( (y,z) =>
      {
         const c = y.b.localeCompare(z.b)
         if (c !== 0) return c
         return z.a - y.a   /* order switched for descending sort */
      } )
</code>```

Body:
Hello I have two array and I want to sort them another array but i want to sort like group by.

var a = [1,2,3,2,1,3,3,2,1]
var b = [b,b,b,c,c,c,d,d,d]

The result I want like;

var a =[3,2,1,3,2,1,3,2,1]
var b =[b,b,b,c,c,c,d,d,d]

Body:
If you had an array of pairs like this

const arr = [ {a:1, b:'b'} , {a:2, b:'b'}, {a:3, b:'b'},
              {a:2, b:'c'} , {a:1, b:'c'}, {a:3, b:'c'},
              {a:3, b:'d'} , {a:2, b:'d'}, {a:1, b:'d'} ]

you would establish a link between the two arrays in your question.

You could sort that array into an order descending on the a and ascending on the b  like this

 arr.sort ( (y,z) =>
      {
         const c = y.b.localeCompare(z.b)
         if (c !== 0) return c
         return z.a - y.a   /* order switched for descending sort */
      } )


问:
How to handle large file uploads in Quarkus
My question is two fold:

I'm looking for a way to implement multipart file uploads on a quarkus application server that allows the programmer access to the uploaded file.
Going through the documentation it seems there is https://quarkus.io/guides/rest-client-multipart, but this doesn't tell me where on the server, the file is stored (if it is at all).

I'd also like to know what's going on under the hood. For large files (>100MB) what would the memory footprint look like?

答:
As @kolossus has pointed out, You can configure file handling through the built-in quarkus options. However, it seems that quarkus will handle file uploads in pretty much the exact same way regardless of whether or not these options are set.

For example, using RESTEasy's @MultipartForm

public class Resource {

    @FormParam("file")
    public File file;
}
```

<p>And then in some controller method:</p>

<pre class="lang-java prettyprint-override"><code>@POST
@Path("/file")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response fileUpload(@MultipartForm Resource upload) {
    log.info("File path: {}", upload.file.getAbsolutePath());
}
</code>```

Then call this method with a file in the request body and you should see the log output containing the path to the uploaded file (Something ugly like /var/folders/y_/_3mfhd2s5ks08fsmhnn80q440000gn/T/5e84410f27304d289f168a76d51b240a).

When you look in that path however, you wont see that file anywhere.

So it seems that quarkus has the options set to the corresponding values by default:

quarkus.http.body.handle-file-uploads=true

quarkus.http.body.uploads-directory=<some random directory in /var>

quarkus.http.body.delete-uploaded-files-on-end=true

Note: tested on v1.4.1.Final

Body:
As @kolossus has pointed out, You can configure file handling through the built-in quarkus options. However, it seems that quarkus will handle file uploads in pretty much the exact same way regardless of whether or not these options are set.

For example, using RESTEasy's @MultipartForm

public class Resource {

    @FormParam("file")
    public File file;
}

And then in some controller method:

@POST
@Path("/file")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response fileUpload(@MultipartForm Resource upload) {
    log.info("File path: {}", upload.file.getAbsolutePath());
}

Then call this method with a file in the request body and you should see the log output containing the path to the uploaded file (Something ugly like /var/folders/y_/_3mfhd2s5ks08fsmhnn80q440000gn/T/5e84410f27304d289f168a76d51b240a).

When you look in that path however, you wont see that file anywhere.

So it seems that quarkus has the options set to the corresponding values by default:

quarkus.http.body.handle-file-uploads=true

quarkus.http.body.uploads-directory=<some random directory in /var>

quarkus.http.body.delete-uploaded-files-on-end=true

Note: tested on v1.4.1.Final


问:
I have a problem with the django authenticate function
When I input the same username and password as in the database it shows "invalid credentials" instead of "Success".

def login(request):
    if request.method  == 'POST':

```<code>    username           = request.POST.get('user')
    password1          = request.POST.get('password1')
    a                  = authenticate( username=username, password=password1)
    if a is not None:
        return HttpResponse("Success")
    else:
        return HttpResponse("Invalid Credentials")
return render(request, 'login.html')
</code>```

答:
The problem is not with the authentication itself, but with creating users. You can not create users with raw passwords in the database. Django stores hashed passwords in the database. By default the PBKDF2 hasher is used, although you can configure that. That means that a password looks like:

```<code><i>algorithm</i>$<i>iterations</i>$<i>salt</i>$<i>hash</i></code>```

The authentication module will hash the password you give, and check if this matches.

You can make use of the createsuperuser management command [Django-doc] to make a superuser:

```<code>django-admin <b>createsuperuser</b></code>```

or you can change the password of a user with the changepassword management command [Django-doc]:

```<code>django-admin <b>changepassword</b> <i>username</i></code>```

For normal users, you can make for example through the admin pages, or with the the .create_user(…) method [Django-doc] in the shell:

```<code>$ python manage.py shell
Python 3.6.8 (default, Jan 14 2019, 11:02:34)
[GCC 8.0.1 20180414 (experimental) [trunk revision 259383]] on linux
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from django.contrib.auth import get_user_model
>>> get_user_model().objects.<b>create_user(</b>username=<i>'username'</i>, password=<i>'thepassword'</i><b>)</b>
<User: username></code>```

Body:
When I input the same username and password as in the database it shows "invalid credentials" instead of "Success".

def login(request):
    if request.method  == 'POST':

    username           = request.POST.get('user')
    password1          = request.POST.get('password1')
    a                  = authenticate( username=username, password=password1)
    if a is not None:
        return HttpResponse("Success")
    else:
        return HttpResponse("Invalid Credentials")
return render(request, 'login.html')

Body:
The problem is not with the authentication itself, but with creating users. You can not create users with raw passwords in the database. Django stores hashed passwords in the database. By default the PBKDF2 hasher is used, although you can configure that. That means that a password looks like:

algorithm$iterations$salt$hash

The authentication module will hash the password you give, and check if this matches.

You can make use of the createsuperuser management command [Django-doc] to make a superuser:

django-admin createsuperuser

or you can change the password of a user with the changepassword management command [Django-doc]:

django-admin changepassword username

For normal users, you can make for example through the admin pages, or with the the .create_user(…) method [Django-doc] in the shell:

$ python manage.py shell
Python 3.6.8 (default, Jan 14 2019, 11:02:34)
[GCC 8.0.1 20180414 (experimental) [trunk revision 259383]] on linux
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from django.contrib.auth import get_user_model
>>> get_user_model().objects.create_user(username='username', password='thepassword')
<User: username>


问:
How can I eliminate spacing between inline elements in CSS?
I have a div with a bunch of image tags inside, here is an example:

```<code><div style="margin: 0; padding: 0; border: 0;">
    <a href="/view/foo1"><img src="foo1.jpg" alt="Foo1" /></a>
    <a href="/view/foo2"><img src="foo2.jpg" alt="Foo2" /></a>
    <a href="/view/foo3"><img src="foo3.jpg" alt="Foo3" /></a>
</div>
</code>```

Because there is whitespace between the tags, browsers will display some whitespace between the images (Chrome decides on 4px). How can I tell the browser to show NO whitespace whatsoever between the images, without placing the > and < directly next to each other? I know letter-spacing applies in addition to what the browser decides to use, so that's useless even with a negative value. Basically I'm going for something like Twitter has at the bottom of their home page. I looked at their code and they're using an unordered list. I could just do that but I'd like the technical explanation for why there appears to be no way to eliminate the white space from between these images.

答:
try to add img {margin:0;padding:0;float:left}

in other words remove any default margin and padding of browsers for img and float them.

Demo: http://jsfiddle.net/PZPbJ/

ContentLicense: CC BY-SA 3.0

Body:
I have a div with a bunch of image tags inside, here is an example:

Because there is whitespace between the tags, browsers will display some whitespace between the images (Chrome decides on 4px). How can I tell the browser to show NO whitespace whatsoever between the images, without placing the > and < directly next to each other? I know letter-spacing applies in addition to what the browser decides to use, so that's useless even with a negative value. Basically I'm going for something like Twitter has at the bottom of their home page. I looked at their code and they're using an unordered list. I could just do that but I'd like the technical explanation for why there appears to be no way to eliminate the white space from between these images.


问:
Elasticsearch "keep_types" filter doesn't work with "pattern" tokenizer
I am having a problem using the "keep_types" filter with a "pattern" tokenizer, here is an example:

```<code>    {
        "tokenizer": {
            "type": "pattern",
            "pattern": "[()., _-]"
        },
        "filter": [
            "lowercase",
            "asciifolding",
            {
                "type": "keep_types",
                "types": [
                    "<ALPHANUM>"
                ]
            }
        ],
        "text": [
            "7002982065_8031949292_Bomba (Vácuo,pressão) - Suryha.pdf"
        ]
    }
</code>```

The result against the _analyze API is:

```<code>  {
    "tokens": []
  }
</code>```

If I remove the keep_types it works as intended.

I also noted it works fine if I use the "standard" analyzer, but in this case, it wouldn't tokenize the text in the desired way.

I am using version 6.8, but also  tried in 7.5 with same results...

Any ideas?

答:
I was able to get to the intendend result using the "letter" tokenizer, it removes numbers and quotes without the need of filters.

```<code>{
    "tokenizer": {
        "type": "letter"
    },
    "filter": [
        "lowercase",
        "asciifolding"
    ],
    "text": [
        "7002982065_8031949292_Bomba (\"Vácuo,pressão) - Suryha.pdf"
    ]
}
</code>```

the result is

```<code>[
  "bomba",
  "vacuo",
  "pressao",
  "suryha",
  "pdf"
]
</code>```

But I still think it is worth answering the main question, so I will keep it open

Body:
I am having a problem using the "keep_types" filter with a "pattern" tokenizer, here is an example:

    {
        "tokenizer": {
            "type": "pattern",
            "pattern": "[()., _-]"
        },
        "filter": [
            "lowercase",
            "asciifolding",
            {
                "type": "keep_types",
                "types": [
                    "<ALPHANUM>"
                ]
            }
        ],
        "text": [
            "7002982065_8031949292_Bomba (Vácuo,pressão) - Suryha.pdf"
        ]
    }

The result against the _analyze API is:

  {
    "tokens": []
  }

If I remove the keep_types it works as intended.

I also noted it works fine if I use the "standard" analyzer, but in this case, it wouldn't tokenize the text in the desired way.

I am using version 6.8, but also  tried in 7.5 with same results...

Any ideas?

Body:
I was able to get to the intendend result using the "letter" tokenizer, it removes numbers and quotes without the need of filters.

{
    "tokenizer": {
        "type": "letter"
    },
    "filter": [
        "lowercase",
        "asciifolding"
    ],
    "text": [
        "7002982065_8031949292_Bomba (\"Vácuo,pressão) - Suryha.pdf"
    ]
}

the result is

[
  "bomba",
  "vacuo",
  "pressao",
  "suryha",
  "pdf"
]

But I still think it is worth answering the main question, so I will keep it open


问:
How to bulk insert in ElasticSearch? (Pentaho Kettle is not working)
I have an ETL process that I am implementing using Pentaho Kettle (Spoon). Everything is working fine, except that I can't insert the generated data into my ElasticSearch remote server.
I tried using Kettle's component "Elastic Search Bulk Insert", but Kettle can't find my Elastic Search nodes (as it can be seen here) .
Is there any reliable way to add a lot of information to my ES server? Solutions with kettle or independent scripts/plugins/etc are accepted, the only constraint is that The ETL process will run in a different machine from Elastic Search.
Kettle has a custom Java script element that could also be used.

EDIT: I found out that Pentaho is using a very old version of elastic search (0.16.3), I am trying to find a way to update it. No luck until now...

答:
One common mistake in this context is copying elasticsearch-6.4.2.jar to \data-integration\lib. This is unnecessary and counterproductive.

Steps:

Servers:       localhost         9300

Settings:      cluster.name      my_cluster_name    // from elasticsearch.yml

PDI 8.2 or 8.3 or 9.0

Elasticsearch ver 6.4.2


问:
Why does 'typeid(x) == typeid(y)' evaluate to true, where 'x' and 'y' are id-expression of type T and T& respectively?
I am reading the C++11 draft standard and the section on [expr.typeid] mentions the following (emphasis mine):

[...]

When typeid is applied to an expression other than a glvalue of a polymorphic class type, the result refers
  to a std::type_info object representing the static type of the expression. Lvalue-to-rvalue (4.1), array-topointer
  (4.2), and function-to-pointer (4.3) conversions are not applied to the expression. If the type of the
  expression is a class type, the class shall be completely-defined. The expression is an unevaluated operand
  (Clause 5).

When typeid is applied to a type-id, the result refers to a std::type_info object representing the type of
  the type-id. If the type of the type-id is a reference to a possibly cv-qualified type, the result of the typeid
  expression refers to a std::type_info object representing the cv-unqualified referenced type. If the type of
  the type-id is a class type or a reference to a class type, the class shall be completely-defined.

Further in p5 of the same section, it goes on to give the following example:

```<code>class D { /* ... */ };
D d1;
const D d2;

typeid(d1) == typeid(d2); // yields true
typeid(D)  == typeid(const D); // yields true
typeid(D)  == typeid(d2); // yields true
typeid(D)  == typeid(const D&); // yields true   -- (1)
</code>```

Given the following code sample:

```<code>int main()
{
    int foo = 42;
    int &bar = foo;
    bool comp1 = (typeid(int) == typeid(int&));    // Yields true, same as (1)   -- (2)
    bool comp2 = (typeid(foo) == typeid(bar));     // Yields true, Why?          -- (3)
}
</code>```

My understanding is that [expr.typeid]p4 talks only about the form typeid(type-id) and bar in typeid(bar) is an id-expression and not a type-id. Why does (3) above evaluate to true? Which text in the standard covers this? What have I missed?

答:
Much of C++'s expression "system" works this way. You're observing just one example of a rule that's interwoven throughout the language: references sometimes aren't really "things" in the context of an expression; they just refer to an extant object in the same way that its original name of declaration would. They're intended to be "transparent" at some layers, and this is evident in some of the inner workings.

It may seem counter-intuitive in places; for example, though std::move(expr) returns a T&&, the resulting expression is an rvalue T (not a T&&) … it is the fact that this expression is an rvalue that allows it to bind to rvalue reference parameters when you later pass it to some function. (There is a common misconception that it is the matching type T&& that makes this work.)

typeid is arguably another counter-intuitive example. The specific rule you're missing is [expr.type], responsible for "decaying" these reference types in an expression before any other processing. At that point, the value category of the expression takes on important meaning, and this value category is at least partially determined by the original, unadjusted type. This is how the type and value category of expressions evolves as data moves through your program.

(The subsequent stripping of the const is part of the rules for typeid that you already quoted.)

(The rules for typeid when passed a type are also distinct).

Usually, we don't have to worry about this. Unfortunately, there are several places where you can observe it that feel a bit like an abstraction leak. You've found one of those places. The rules do make everything come together in the end though.

Body:
I am reading the C++11 draft standard and the section on [expr.typeid] mentions the following (emphasis mine):

[...]

When typeid is applied to an expression other than a glvalue of a polymorphic class type, the result refers
  to a std::type_info object representing the static type of the expression. Lvalue-to-rvalue (4.1), array-topointer
  (4.2), and function-to-pointer (4.3) conversions are not applied to the expression. If the type of the
  expression is a class type, the class shall be completely-defined. The expression is an unevaluated operand
  (Clause 5).

When typeid is applied to a type-id, the result refers to a std::type_info object representing the type of
  the type-id. If the type of the type-id is a reference to a possibly cv-qualified type, the result of the typeid
  expression refers to a std::type_info object representing the cv-unqualified referenced type. If the type of
  the type-id is a class type or a reference to a class type, the class shall be completely-defined.

Further in p5 of the same section, it goes on to give the following example:

class D { /* ... */ };
D d1;
const D d2;

typeid(d1) == typeid(d2); // yields true
typeid(D)  == typeid(const D); // yields true
typeid(D)  == typeid(d2); // yields true
typeid(D)  == typeid(const D&); // yields true   -- (1)

Given the following code sample:

int main()
{
    int foo = 42;
    int &bar = foo;
    bool comp1 = (typeid(int) == typeid(int&));    // Yields true, same as (1)   -- (2)
    bool comp2 = (typeid(foo) == typeid(bar));     // Yields true, Why?          -- (3)
}

My understanding is that [expr.typeid]p4 talks only about the form typeid(type-id) and bar in typeid(bar) is an id-expression and not a type-id. Why does (3) above evaluate to true? Which text in the standard covers this? What have I missed?


问:
Receiving a TypeError when trying to run or initiate dataTables.js
I'm trying to run or initiate script using a plugin called dataTables.js. I've managed to import the library using ES6 import statement along with the jquery dependency. When I tried to run or initiate the plugin I get an error as shown below

```<code>jQuery.Deferred exception: (0 , _jquery.default)(...).DataTable is not a function TypeError: (0 , _jquery.default)(...).DataTable is not a function
    at HTMLDocument.eval (https://juwto.csb.app/src/index.js:13:37)
    at j (https://juwto.csb.app/src/jquery.js:1977:29)
    at k (https://juwto.csb.app/src/jquery.js:1983:19)
</code>```

Sandbox Link - https://codesandbox.io/s/gracious-chaplygin-juwto?file=/index.html

I can't seem to find a proper solution or answer even though I managed to import the libraries properly

```<code>import $ from "./jquery";
import _dt from "./datatables";

$(document).ready(function() {
  $("#table").DataTable({
    paging: false,
    bFilter: false,
    bInfo: false
  });
});
</code>```

答: Assuming the path is correct, try to import DataTables like this: import "./datatables.net";

Body:
I'm trying to run or initiate script using a plugin called dataTables.js. I've managed to import the library using ES6 import statement along with the jquery dependency. When I tried to run or initiate the plugin I get an error as shown below

jQuery.Deferred exception: (0 , _jquery.default)(...).DataTable is not a function TypeError: (0 , _jquery.default)(...).DataTable is not a function
    at HTMLDocument.eval (https://juwto.csb.app/src/index.js:13:37)
    at j (https://juwto.csb.app/src/jquery.js:1977:29)
    at k (https://juwto.csb.app/src/jquery.js:1983:19)

Sandbox Link - https://codesandbox.io/s/gracious-chaplygin-juwto?file=/index.html

I can't seem to find a proper solution or answer even though I managed to import the libraries properly

import $ from "./jquery";
import _dt from "./datatables";

$(document).ready(function() {
  $("#table").DataTable({
    paging: false,
    bFilter: false,
    bInfo: false
  });
});


答: You can also make all anchors to float-left and set margin-left to -1</p>

Title: How can I eliminate spacing between inline elements in CSS?


问:
Flask - allowing users into a group of projects, based on project being a variable and an @app.route id
I am using flask-security. I would like to set up @roles_accepted with a variable based upon the app route.

For example, if _id = Lon_2020 the @roles_accepted would allow Lon. This would grant certain users to projects, but not others, based on the _id.

```<code>@app.route('/<string:_id>')
@app.route('/<string:_id>/')
@roles_accepted('admin',_id[:3])
def home(_id):
    return redirect(url_for('tb',_id=_id))
</code>```

At the moment, this causes an error, because _id is not defined. The roles_accepted relies on the _id data.

If this is not possible, would you mind letting me know a better way of allowing certain users into certain projects. e.g.

```<code>Lon_2019
Lon_2020
Lon_2021
Par_2019
Par_2020
Par_2021
Ber_2018
Ber_2019

where the identified is the first 3 characters 'Lon','Par','Ber'
</code>```

Any help is much appreciated. Thank you.

答:
Below is the documentation from Flask-Security library for roles_accepted decorator.

flask_security.decorators.roles_accepted(*roles):
    Decorator which specifies that a user must have at least one of the specified roles. Example:

```<code>@app.route('/create_post')
@roles_accepted('editor', 'author')
def create_post():
    return 'Create Post'
</code>```

In order to use this decorator, you need to first create the roles in your role table, and user your model and role model needs to follow the certain format so that Flask-Security library can recognize existing roles.

Model Example

```<code># association table between user and role
roles_users = db.Table(
'roles_users',
db.Column('user_id', db.Integer(), db.ForeignKey('user.id')),
db.Column('role_id', db.Integer(), db.ForeignKey('role.id'))
)

# role table
class Role(db.Model, RoleMixin):

    __tablename__ = 'role'

    id = db.Column(db.Integer(), primary_key=True)
    name = db.Column(db.String(30), unique=True)

# user table
class User(db.Model, UserMixin):

    __tablename__ = 'user'

    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(50), unique=True)
    password = db.Column(db.String(255))
</code>```

Once you've specified the mode such as above, then you create the role by inserting into role table. Once you create editor and author roles like shown above in the view, when the user with either editor or author role come in to /create_post view, it will be able to control the access-control based on roles.

If you are getting the ID of user or role from above, and want to perform access-control based on that (which I think it is unnecessary) because Flask-Security has current_user variable where you can parse out all information about that user without you manually making the query).
You will have to first make the query using the ID to user or role table, then based on that, you will either throw 403 or allow the content to return which then you won't require to have your own @roles_accepted('editor', 'author'), because you are doing that manually.

Body:
I am using flask-security. I would like to set up @roles_accepted with a variable based upon the app route.

For example, if _id = Lon_2020 the @roles_accepted would allow Lon. This would grant certain users to projects, but not others, based on the _id.

@app.route('/<string:_id>')
@app.route('/<string:_id>/')
@roles_accepted('admin',_id[:3])
def home(_id):
    return redirect(url_for('tb',_id=_id))

At the moment, this causes an error, because _id is not defined. The roles_accepted relies on the _id data.

If this is not possible, would you mind letting me know a better way of allowing certain users into certain projects. e.g.

Lon_2019
Lon_2020
Lon_2021
Par_2019
Par_2020
Par_2021
Ber_2018
Ber_2019

where the identified is the first 3 characters 'Lon','Par','Ber'

Any help is much appreciated. Thank you.

Body:
Below is the documentation from Flask-Security library for roles_accepted decorator.

flask_security.decorators.roles_accepted(*roles):
    Decorator which specifies that a user must have at least one of the specified roles. Example:

@app.route('/create_post')
@roles_accepted('editor', 'author')
def create_post():
    return 'Create Post'

In order to use this decorator, you need to first create the roles in your role table, and user your model and role model needs to follow the certain format so that Flask-Security library can recognize existing roles.

Model Example

# association table between user and role
roles_users = db.Table(
'roles_users',
db.Column('user_id', db.Integer(), db.ForeignKey('user.id')),
db.Column('role_id', db.Integer(), db.ForeignKey('role.id'))
)

# role table
class Role(db.Model, RoleMixin):

    __tablename__ = 'role'

    id = db.Column(db.Integer(), primary_key=True)
    name = db.Column(db.String(30), unique=True)

# user table
class User(db.Model, UserMixin):

    __tablename__ = 'user'

    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(50), unique=True)
    password = db.Column(db.String(255))

Once you've specified the mode such as above, then you create the role by inserting into role table. Once you create editor and author roles like shown above in the view, when the user with either editor or author role come in to /create_post view, it will be able to control the access-control based on roles.

If you are getting the ID of user or role from above, and want to perform access-control based on that (which I think it is unnecessary) because Flask-Security has current_user variable where you can parse out all information about that user without you manually making the query).
You will have to first make the query using the ID to user or role table, then based on that, you will either throw 403 or allow the content to return which then you won't require to have your own @roles_accepted('editor', 'author'), because you are doing that manually.


问:
Spring (mvc, websockets) sometimes raises an Exception while creating an instance
On our production (tomcat, java8) servers, from time to time, we're seeing the following stacktrace in the logfiles:

```<code>java.lang.Exception
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
        at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:142)
        at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:102)
        at org.springframework.web.method.annotation.ModelAttributeMethodProcessor.createAttribute(ModelAttributeMethodProcessor.java:139)
        at org.springframework.web.servlet.mvc.method.annotation.ServletModelAttributeMethodProcessor.createAttribute(ServletModelAttributeMethodProcessor.java:82)
        at org.springframework.web.method.annotation.ModelAttributeMethodProcessor.resolveArgument(ModelAttributeMethodProcessor.java:106)
        at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:121)
        at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:158)
        at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:128)
        at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97)
        at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
        at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
        at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
        at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:967)
        at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901)
        at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
        at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:635)
        at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
        at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:728)
        at org.apache.catalina.core.ApplicationDispatcher.doInclude(ApplicationDispatcher.java:591)
        at org.apache.catalina.core.ApplicationDispatcher.include(ApplicationDispatcher.java:527)
        at org.apache.catalina.core.StandardHostValve.custom(StandardHostValve.java:380)
        at org.apache.catalina.core.StandardHostValve.throwable(StandardHostValve.java:323)
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:166)
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
        at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:660)
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
        at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:798)
        at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
        at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:806)
        at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1498)
        at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
        at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
        at java.lang.Thread.run(Thread.java:748)
</code>```

What could be the cause of this exception and how can I trace the origin?

Thanks

答:
Based on e.g.: Spring Boot custom error controller is showing the incorrect exception this
might be an Exception thrown from your own code, so maybe search your own codebase for places where Exception is thrown.

To complicate matters a bit this is all implemented in native code, see: class newInstance propagates checked and unchecked exceptions - is it true?

But maybe it is further obfuscated because the original exception on your production system has already been generated many times (since startup) and has been converted to extremely optimized native code.

In that case you can:

see this in the logging when the application just is started; or

if you start Java with this extra parameter: -XX:-OmitStackTraceInFastThrow (before your applications jar/Main class name and application arguments)

I hope that helps, I'm curious if this is the case, so please let me (and all other readers that might come here later know).

Body:
On our production (tomcat, java8) servers, from time to time, we're seeing the following stacktrace in the logfiles:

java.lang.Exception
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
        at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:142)
        at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:102)
        at org.springframework.web.method.annotation.ModelAttributeMethodProcessor.createAttribute(ModelAttributeMethodProcessor.java:139)
        at org.springframework.web.servlet.mvc.method.annotation.ServletModelAttributeMethodProcessor.createAttribute(ServletModelAttributeMethodProcessor.java:82)
        at org.springframework.web.method.annotation.ModelAttributeMethodProcessor.resolveArgument(ModelAttributeMethodProcessor.java:106)
        at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:121)
        at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:158)
        at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:128)
        at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97)
        at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
        at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
        at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
        at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:967)
        at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901)
        at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
        at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:635)
        at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
        at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:728)
        at org.apache.catalina.core.ApplicationDispatcher.doInclude(ApplicationDispatcher.java:591)
        at org.apache.catalina.core.ApplicationDispatcher.include(ApplicationDispatcher.java:527)
        at org.apache.catalina.core.StandardHostValve.custom(StandardHostValve.java:380)
        at org.apache.catalina.core.StandardHostValve.throwable(StandardHostValve.java:323)
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:166)
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
        at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:660)
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
        at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:798)
        at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
        at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:806)
        at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1498)
        at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
        at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
        at java.lang.Thread.run(Thread.java:748)

What could be the cause of this exception and how can I trace the origin?

Thanks


问:
python pyusb import usb.core doesn't work
I am following the tutorial(http://pyusb.sourceforge.net/docs/1.0/tutorial.html)

I am on windows xp sp3,
my python version is 2.7 and I downloaded and installed the pyusb-1.0.0-a1.zip

and libusb-win32-bin-1.2.4.0.zip

```<code>import usb
</code>```

works fine

but

```<code>import usb.core
</code>```

doesn't working at all

it says

```<code>Traceback (most recent call last):
  File "D:\py\usb.py", line 1, in <module>
    from usb import core
  File "D:\py\usb.py", line 1, in <module>
    from usb import core
ImportError: cannot import name core
</code>```

any solution?

thanks!

p.s.
"from usb import core"
this make

```<code>Traceback (most recent call last):
  File "D:\py\usb.py", line 1, in <module>
    from usb import core
  File "D:\py\usb.py", line 1, in <module>
    from usb import core
ImportError: cannot import name core
</code>```

full source code is here

```<code>from usb import core
#find device
dev = usb.core.find(idVendor=0x1516, idProduct=0x8628)
#found?
if dev is None :
        raise ValueError('device not found')

#set the active config. with no args, the first config will be the active one

dev.set_configuration()

#get an end point instance
ep = usb.util.find_descriptor(
    dev.get_interface_altsetting(), #first interface
    #match the first Out Endpoint
    custom_match = \
        lambda e: \
            usb.util.endpoint_direction(e.bEndpointAddress) == \
            usb.util.ENDPOINT_OUT)
assert ep is not None

while(1):
    ep.write(0x5553424350DDBC880000000000000600000000000000000000000000000000)
    ep.write(0x5553425350ddbc880000000000)
</code>```

答:
In both cases error is:

```<code>Traceback (most recent call last):
  File "D:\py\usb.py", line 1, in <module>
</code>```

which means it has file usb.py in PATH earlier (probably in . which is D:\py\ in this case) than path to python modules.

Did you install this module properly? Try rename this usb.py file to something else, you'll see if the error becomes "ImportError: No module named usb". Also check Python install path (something like C:\Python27\) for usb folder i.e. <python_path>\lib\site-packages\usb\core.py.

Body:
I am following the tutorial(http://pyusb.sourceforge.net/docs/1.0/tutorial.html)

I am on windows xp sp3,
my python version is 2.7 and I downloaded and installed the pyusb-1.0.0-a1.zip

and libusb-win32-bin-1.2.4.0.zip

import usb

works fine

but

import usb.core

doesn't working at all

it says

Traceback (most recent call last):
  File "D:\py\usb.py", line 1, in <module>
    from usb import core
  File "D:\py\usb.py", line 1, in <module>
    from usb import core
ImportError: cannot import name core

any solution?

thanks!

p.s.
"from usb import core"
this make

Traceback (most recent call last):
  File "D:\py\usb.py", line 1, in <module>
    from usb import core
  File "D:\py\usb.py", line 1, in <module>
    from usb import core
ImportError: cannot import name core

full source code is here

from usb import core
#find device
dev = usb.core.find(idVendor=0x1516, idProduct=0x8628)
#found?
if dev is None :
        raise ValueError('device not found')

#set the active config. with no args, the first config will be the active one

dev.set_configuration()

#get an end point instance
ep = usb.util.find_descriptor(
    dev.get_interface_altsetting(), #first interface
    #match the first Out Endpoint
    custom_match = \
        lambda e: \
            usb.util.endpoint_direction(e.bEndpointAddress) == \
            usb.util.ENDPOINT_OUT)
assert ep is not None

while(1):
    ep.write(0x5553424350DDBC880000000000000600000000000000000000000000000000)
    ep.write(0x5553425350ddbc880000000000)

Body:
In both cases error is:

Traceback (most recent call last):
  File "D:\py\usb.py", line 1, in <module>

which means it has file usb.py in PATH earlier (probably in . which is D:\py\ in this case) than path to python modules.

Did you install this module properly? Try rename this usb.py file to something else, you'll see if the error becomes "ImportError: No module named usb". Also check Python install path (something like C:\Python27\) for usb folder i.e. <python_path>\lib\site-packages\usb\core.py.


问:
Receiving parameter in API method in Blazor Server project from GetFromJsonAsync call in Blazor WebAssembly Client project
I have a Controller in my Blazor Server project and I am calling it from a razor page in the client project passing a parameter, eg

in razor page

```<code>var FlatData = await Http.GetFromJsonAsync<IEnumerable<TreeItem>>("TreeItem?Id=3FD09A3");
</code>```

in server Controller

```<code>[HttpGet]
public IEnumerable<TreeItem> Get(string tag)
{

    IEnumerable<TreeItem> treeItems =  Enumerable.Range(1, 11).Select(index => new TreeItem
    {
        ...
    })
    .ToArray();
    return treeItems;
}
</code>```

TreeItem is a class defined in my Shared project.

I get into my Controller method OK and can return data OK, but I do not get the parameter to refine the data.  How do I get my parameter data from "TreeItem?Id=3FD09A3".  My "tag" parameter on my Get method is always null.  How can I get my parameter data?

答:
You have to match on name, case-sensitive:</p>

```<code>[HttpGet]
//public IEnumerable<TreeItem> Get(string tag)
public IEnumerable<TreeItem> Get(string Id)   // because ?Id=3FD09A3
</code>```

Body:
I have a Controller in my Blazor Server project and I am calling it from a razor page in the client project passing a parameter, eg

in razor page

var FlatData = await Http.GetFromJsonAsync<IEnumerable<TreeItem>>("TreeItem?Id=3FD09A3");

in server Controller

[HttpGet]
public IEnumerable<TreeItem> Get(string tag)
{

    IEnumerable<TreeItem> treeItems =  Enumerable.Range(1, 11).Select(index => new TreeItem
    {
        ...
    })
    .ToArray();
    return treeItems;
}

TreeItem is a class defined in my Shared project.

I get into my Controller method OK and can return data OK, but I do not get the parameter to refine the data.  How do I get my parameter data from "TreeItem?Id=3FD09A3".  My "tag" parameter on my Get method is always null.  How can I get my parameter data?

Body:
You have to match on name, case-sensitive:

[HttpGet]
//public IEnumerable<TreeItem> Get(string tag)
public IEnumerable<TreeItem> Get(string Id)   // because ?Id=3FD09A3


问:
Combo box listing latest 2 folders from path
I am quite new to VBA as I have been using other programming languages.

I am trying to use a combo box to list the latest 2 folders from my path.

I have already been able to select all data from the required path as well as I have sorted this.

I need support to be able to list only the latest 2 folders based on my code but am struggling and require help.

```<code>Drivepath = Mid(ThisWorkbook.Path, 1, 2)
On Error Resume Next
filepath = Drivepath & "C:\Users\Documents\Month\" & ThisWorkbook.Sheets("Months"). ComboBox1.Value & "\"

Application.Workbooks.Open (filepath & s_workbook)

Application.Sheets(1).Activate

Dim name
ThisWorkbook.Sheets("Months"). ComboBox1.Clear
Drivepath = Mid(ThisWorkbook.Path, 1,2)

For Each name In ListDirectory(Path:=Drivepath & "C:\Users\Documents\Month”, AttrInclude:=vbDirectory, AttrExclude:=vbSystem Or vbHidden)
    If Len(name) > 4 Then
        If InStr(name, "list") = 0 Then ThisWorkbook.Sheets("Months"). ComboBox1.AddItem name
    End If
Next name

'Sort the list

ComBoList = ThisWorkbook.Sheets("Months"). ComboBox1.List

For X = LBound(ComBoList) To UBound(ComBoList) - 1
    For j = X + 1 To UBound(ComBoList)
        If ComBoList(X, 0) > ComBoList(j, 0) Then
            ComBoTemp = ComBoList(X, 0)
            ComBoList(X, 0) = ComBoList(j, 0)
            ComBoList(j, 0) = ComBoTemp
        End If
    Next j
Next X

hold_name = ComBoList(UBound(ComBoList), 0)

ThisWorkbook.Sheets("Months"). ComboBox1.List = ComBoList
ThisWorkbook.Sheets("Months"). ComboBox1.Value = hold_name

ListDirectory
</code>```

ListDirectory function

```<code>Function ListDirectory(Path As String, AttrInclude As VbFileAttribute, Optional AttrExclude As VbFileAttribute = False) As Collection

    Dim Filename As String

    Dim Attribs As VbFileAttribute
    Set ListDirectory = New Collection
    ' first call to Dir() initializes the list

    Filename = Dir(Path, AttrInclude)
    While Filename <> ""
        Attribs = GetAttr(Path & Filename)

        ' to be added, a file must have the right set of attributes

        If Attribs And AttrInclude And Not (Attribs And AttrExclude) Then

            If Len(Filename) > 4 And InStr(Filename, "Oracle") = 0 Then
                ListDirectory.Add Filename, Path & Filename
            End If

        ' fetch next filename

        Filename = Dir

    Wend

End Function
</code>```

Am using sorting to sort the folders as all the required folders are named the following. E.g, 201901, 201902, 201903, 201904, 201905 and etc.

I just need a solution for selecting the last 2 folders which are 202003 & 202004.

I could easily delete all the other folders from the path but am looking for a more efficient way to only display 2 of the latest folders in the combo box.

Again, I have already sorted them but once I sorted them I would like to display or select only the latest folders based on sorting them.

答:
```<code>K = UBound(ComboList)
TwoNewest = ComboList(K) & vbcrlf & ComboList(K-1)
ComboBox1.List = split(TwoNewest,vbcrlf)
</code>```

There my be better ways but that'll work

Body:
I am quite new to VBA as I have been using other programming languages.

I am trying to use a combo box to list the latest 2 folders from my path.

I have already been able to select all data from the required path as well as I have sorted this.

I need support to be able to list only the latest 2 folders based on my code but am struggling and require help.

Drivepath = Mid(ThisWorkbook.Path, 1, 2)
On Error Resume Next
filepath = Drivepath & "C:\Users\Documents\Month\" & ThisWorkbook.Sheets("Months"). ComboBox1.Value & "\"

Application.Workbooks.Open (filepath & s_workbook)

Application.Sheets(1).Activate

Dim name
ThisWorkbook.Sheets("Months"). ComboBox1.Clear
Drivepath = Mid(ThisWorkbook.Path, 1,2)

For Each name In ListDirectory(Path:=Drivepath & "C:\Users\Documents\Month”, AttrInclude:=vbDirectory, AttrExclude:=vbSystem Or vbHidden)
    If Len(name) > 4 Then
        If InStr(name, "list") = 0 Then ThisWorkbook.Sheets("Months"). ComboBox1.AddItem name
    End If
Next name

'Sort the list

ComBoList = ThisWorkbook.Sheets("Months"). ComboBox1.List

For X = LBound(ComBoList) To UBound(ComBoList) - 1
    For j = X + 1 To UBound(ComBoList)
        If ComBoList(X, 0) > ComBoList(j, 0) Then
            ComBoTemp = ComBoList(X, 0)
            ComBoList(X, 0) = ComBoList(j, 0)
            ComBoList(j, 0) = ComBoTemp
        End If
    Next j
Next X

hold_name = ComBoList(UBound(ComBoList), 0)

ThisWorkbook.Sheets("Months"). ComboBox1.List = ComBoList
ThisWorkbook.Sheets("Months"). ComboBox1.Value = hold_name

ListDirectory

ListDirectory function

Function ListDirectory(Path As String, AttrInclude As VbFileAttribute, Optional AttrExclude As VbFileAttribute = False) As Collection

    Dim Filename As String

    Dim Attribs As VbFileAttribute
    Set ListDirectory = New Collection
    ' first call to Dir() initializes the list

    Filename = Dir(Path, AttrInclude)
    While Filename <> ""
        Attribs = GetAttr(Path & Filename)

        ' to be added, a file must have the right set of attributes

        If Attribs And AttrInclude And Not (Attribs And AttrExclude) Then

            If Len(Filename) > 4 And InStr(Filename, "Oracle") = 0 Then
                ListDirectory.Add Filename, Path & Filename
            End If

        ' fetch next filename

        Filename = Dir

    Wend

End Function

Am using sorting to sort the folders as all the required folders are named the following. E.g, 201901, 201902, 201903, 201904, 201905 and etc.

I just need a solution for selecting the last 2 folders which are 202003 & 202004.

I could easily delete all the other folders from the path but am looking for a more efficient way to only display 2 of the latest folders in the combo box.

Again, I have already sorted them but once I sorted them I would like to display or select only the latest folders based on sorting them.

Body:
K = UBound(ComboList)
TwoNewest = ComboList(K) & vbcrlf & ComboList(K-1)
ComboBox1.List = split(TwoNewest,vbcrlf)

There my be better ways but that'll work


问:
MERN project routing not working on Heroku
I have created a personal website. It is developed using ReactJs, Express, Node, and MongoDB. It is working fine on my localhost also, Heroku (using react-router-dom) too. But, when I direct hit the URL on Heroku then it is showing error. The homepage is working only.

Here is the URL, https://amper.herokuapp.com/

package.json

```<code>{
  "name": "amper",
  "version": "1.0.0",
  "description": "",
  "main": "server.js",
  "homepage": "https://amper.herokuapp.com",
  "scripts": {
    "dev-client": "PORT=3000 react-scripts start",
    "server": "node server.js",
    "dev-server": "nodemon ./server.js",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "start": "PORT=3000 react-scripts start && node server.js",
    "dev": "concurrently --kill-others \"npm run dev-client\" \"npm run dev-server\""
  },
  "author": "Amper",
  "license": "ISC",
  "dependencies": {
    "@ckeditor/ckeditor5-build-classic": "^19.0.1",
    "@ckeditor/ckeditor5-react": "^2.1.0",
    "@fortawesome/fontawesome-svg-core": "^1.2.28",
    "@fortawesome/free-brands-svg-icons": "^5.13.0",
    "@fortawesome/react-fontawesome": "^0.1.9",
    "@testing-library/jest-dom": "^5.9.0",
    "@testing-library/react": "^10.0.4",
    "@testing-library/user-event": "^10.4.0",
    "axios": "^0.19.2",
    "bcrypt": "^4.0.1",
    "body-parser": "^1.19.0",
    "bootstrap": "^4.5.0",
    "cors": "^2.8.5",
    "dotenv": "^8.2.0",
    "draft-js": "^0.11.5",
    "express": "^4.17.1",
    "jsonwebtoken": "^8.5.1",
    "moment": "^2.26.0",
    "mongoose": "^5.9.16",
    "path": "^0.12.7",
    "react": "^16.13.1",
    "react-bootstrap": "^1.0.1",
    "react-dom": "^16.13.1",
    "react-feather": "^2.0.8",
    "react-helmet": "^6.0.0",
    "react-moment": "^0.9.7",
    "react-router-dom": "^5.2.0",
    "react-scripts": "^3.4.1",
    "react-select": "^3.1.0",
    "serve-static": "^1.14.1"
  },
  "engines": {
    "node": "12.16.3"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "concurrently": "^5.2.0",
    "node-sass": "^4.14.1",
    "nodemon": "^2.0.4"
  }
}
</code>```

server.js

```<code>const express = require('express');
const mongoose = require('mongoose');
const bodyparser = require('body-parser');
const cors = require('cors');
const path = require('path');
const serveStatic = require('serve-static');
require('dotenv').config();

const routes = require('./server/routes');

const app = express();
const port = process.env.PORT;

// mongo connection
mongoose.Promise = global.Promise;
mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true })
  .then(() => console.log('Database Connected'))
  .catch((err) => console.log(err));

app.use(serveStatic(path.join(__dirname, 'build')));

// bodyparser setup
app.use(bodyparser.urlencoded({ extended: true }));
app.use(bodyparser.json());

// cors setup
app.use(cors());

routes(app);

app.listen(port, () => console.log(`App is running on port ${port}`));
</code>```

Project folder structure

```<code>amper
|_ node_modules
|_ public
   |_ favicon.ico
   |_ index.html
   |_ manifest.json
   |_ robots.txt
|_ server
   |_ controllers
   |_ middleware
   |_ models
   |_ routes
|_ src
   |_ assets
   |_ components
   |_ App.js
   |_ index.js
   |_ serviceWorker.js
   |_ setupTests.js
|_ .env
|_ .gitignore
|_ package-lock.json
|_ package.json
|_ README.md
|_ server.js
</code>```

答:
Currently facing the exact same issue.

mongoose.connect(process.env.MONGO_URI ...

My env variable was not set-up on Heroku. I added it under:

heroku -> settings -> config vars -> reveal config vars

Now, my app shows 503 Service Unavailable (when I check under network-info on chrome-dev-tools). Heroku log says H12 "Request timeout" and when checking, I get this page.

So, I tried postman to initiate a very simple 'GET' request which would send back 1 row. The postman GET also fails.

Although this is not an answer per-se, I have tried to list down steps taken. Some of these are using other questions on stackoverflow & will try to link those.

Related stackoverflow questions:

Node.js API working locally but not on Heroku

Mongodb atlas + node.js working locally but stop when pushed to Heroku

application times out when connecting to MongoLab from Heroku

As an addendum, I would also like to view any "console.log" messages from server.js. Have just last week built my first-ever MERN-app & looking for any pointers.

Problem solved: Huge thanks to below answer by mousto090.

```<code>if (process.env.NODE_ENV === "production") {
  // Set the static assets folder (ie, client build)
  app.use(express.static('client/build'));
  app.get('*', (req,res) => {
  res.sendFile(path.resolve(__dirname, 'client', 'build', index.html'))
  });
}
</code>```

Above code was on my server.js. Clearly, there is an expectation of a NODE_ENV variable which I missed to declare on Heroku settings. Added it & the code works now. Thank you mousto090 !!

Body:
I have created a personal website. It is developed using ReactJs, Express, Node, and MongoDB. It is working fine on my localhost also, Heroku (using react-router-dom) too. But, when I direct hit the URL on Heroku then it is showing error. The homepage is working only.

Here is the URL, https://amper.herokuapp.com/

package.json

{
  "name": "amper",
  "version": "1.0.0",
  "description": "",
  "main": "server.js",
  "homepage": "https://amper.herokuapp.com",
  "scripts": {
    "dev-client": "PORT=3000 react-scripts start",
    "server": "node server.js",
    "dev-server": "nodemon ./server.js",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "start": "PORT=3000 react-scripts start && node server.js",
    "dev": "concurrently --kill-others \"npm run dev-client\" \"npm run dev-server\""
  },
  "author": "Amper",
  "license": "ISC",
  "dependencies": {
    "@ckeditor/ckeditor5-build-classic": "^19.0.1",
    "@ckeditor/ckeditor5-react": "^2.1.0",
    "@fortawesome/fontawesome-svg-core": "^1.2.28",
    "@fortawesome/free-brands-svg-icons": "^5.13.0",
    "@fortawesome/react-fontawesome": "^0.1.9",
    "@testing-library/jest-dom": "^5.9.0",
    "@testing-library/react": "^10.0.4",
    "@testing-library/user-event": "^10.4.0",
    "axios": "^0.19.2",
    "bcrypt": "^4.0.1",
    "body-parser": "^1.19.0",
    "bootstrap": "^4.5.0",
    "cors": "^2.8.5",
    "dotenv": "^8.2.0",
    "draft-js": "^0.11.5",
    "express": "^4.17.1",
    "jsonwebtoken": "^8.5.1",
    "moment": "^2.26.0",
    "mongoose": "^5.9.16",
    "path": "^0.12.7",
    "react": "^16.13.1",
    "react-bootstrap": "^1.0.1",
    "react-dom": "^16.13.1",
    "react-feather": "^2.0.8",
    "react-helmet": "^6.0.0",
    "react-moment": "^0.9.7",
    "react-router-dom": "^5.2.0",
    "react-scripts": "^3.4.1",
    "react-select": "^3.1.0",
    "serve-static": "^1.14.1"
  },
  "engines": {
    "node": "12.16.3"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "concurrently": "^5.2.0",
    "node-sass": "^4.14.1",
    "nodemon": "^2.0.4"
  }
}

server.js

const express = require('express');
const mongoose = require('mongoose');
const bodyparser = require('body-parser');
const cors = require('cors');
const path = require('path');
const serveStatic = require('serve-static');
require('dotenv').config();

const routes = require('./server/routes');

const app = express();
const port = process.env.PORT;

// mongo connection
mongoose.Promise = global.Promise;
mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true })
  .then(() => console.log('Database Connected'))
  .catch((err) => console.log(err));

app.use(serveStatic(path.join(__dirname, 'build')));

// bodyparser setup
app.use(bodyparser.urlencoded({ extended: true }));
app.use(bodyparser.json());

// cors setup
app.use(cors());

routes(app);

app.listen(port, () => console.log(`App is running on port ${port}`));

Project folder structure

amper
|_ node_modules
|_ public
   |_ favicon.ico
   |_ index.html
   |_ manifest.json
   |_ robots.txt
|_ server
   |_ controllers
   |_ middleware
   |_ models
   |_ routes
|_ src
   |_ assets
   |_ components
   |_ App.js
   |_ index.js
   |_ serviceWorker.js
   |_ setupTests.js
|_ .env
|_ .gitignore
|_ package-lock.json
|_ package.json
|_ README.md
|_ server.js

Body:
Currently facing the exact same issue.

mongoose.connect(process.env.MONGO_URI ...

My env variable was not set-up on Heroku. I added it under:

heroku -> settings -> config vars -> reveal config vars

Now, my app shows 503 Service Unavailable (when I check under network-info on chrome-dev-tools). Heroku log says H12 "Request timeout" and when checking, I get this page.

So, I tried postman to initiate a very simple 'GET' request which would send back 1 row. The postman GET also fails.

Although this is not an answer per-se, I have tried to list down steps taken. Some of these are using other questions on stackoverflow & will try to link those.

Related stackoverflow questions:

Node.js API working locally but not on Heroku

Mongodb atlas + node.js working locally but stop when pushed to Heroku

application times out when connecting to MongoLab from Heroku

As an addendum, I would also like to view any "console.log" messages from server.js. Have just last week built my first-ever MERN-app & looking for any pointers.

Problem solved: Huge thanks to below answer by mousto090.

if (process.env.NODE_ENV === "production") {
  // Set the static assets folder (ie, client build)
  app.use(express.static('client/build'));
  app.get('*', (req,res) => {
  res.sendFile(path.resolve(__dirname, 'client', 'build', index.html'))
  });
}

Above code was on my server.js. Clearly, there is an expectation of a NODE_ENV variable which I missed to declare on Heroku settings. Added it & the code works now. Thank you mousto090 !!


问:
Best way to compare nullable DateTimeOffset variables?
I have code that intends to take the largest of two DateTimeOffset? variables. I have been doing this using the following code:

```<code>return firstTimestamp > secondTimestamp ? firstTimestamp : secondTimestamp
</code>```

However, as described by the MSDN documentation, if either of the values is null then the operation always resolves to False. This means that if a value is in firstTimestamp, and secondTimestamp is null, then null is returned where firstTimestamp should be returned.

Is there an efficient short-hand way of doing this comparison accounting for null values? The only solution I can think of is something like:

```<code>if(firstTimestamp.HasValue && secondTimestamp.HasValue){
    return firstTimestamp > secondTimestamp ? firstTimestamp : secondTimestamp;
}else if(firstTimestamp.HasValue){
    return firstTimestamp;
}
return secondTimestamp;
</code>```

答:
You can use Nullable.Compare<T> method for that

DateTimeOffset? firstTimestamp = DateTimeOffset.Now;
DateTimeOffset? secondTimestamp = null;

var result = Nullable.Compare(firstTimestamp, secondTimestamp) > 0 ? firstTimestamp : secondTimestamp;
```

If firstTimestamp is not null and secondTimestamp is null, it returns a value, greater then 0, and vise versa. Then you can use this value in conditional operator ?: to get an expected result.

Body:
I have code that intends to take the largest of two DateTimeOffset? variables. I have been doing this using the following code:

return firstTimestamp > secondTimestamp ? firstTimestamp : secondTimestamp

However, as described by the MSDN documentation, if either of the values is null then the operation always resolves to False. This means that if a value is in firstTimestamp, and secondTimestamp is null, then null is returned where firstTimestamp should be returned.

Is there an efficient short-hand way of doing this comparison accounting for null values? The only solution I can think of is something like:

if(firstTimestamp.HasValue && secondTimestamp.HasValue){
    return firstTimestamp > secondTimestamp ? firstTimestamp : secondTimestamp;
}else if(firstTimestamp.HasValue){
    return firstTimestamp;
}
return secondTimestamp;

Body:
You can use Nullable.Compare<T> method for that

DateTimeOffset? firstTimestamp = DateTimeOffset.Now;
DateTimeOffset? secondTimestamp = null;

var result = Nullable.Compare(firstTimestamp, secondTimestamp) > 0 ? firstTimestamp : secondTimestamp;

If firstTimestamp is not null and secondTimestamp is null, it returns a value, greater then 0, and vise versa. Then you can use this value in conditional operator ?: to get an expected result.


问:
Search for value in column and overwrite the row, otherwise add new row
I'm working on a script that allows users to enter data into a spreadsheet using an HTML form. I'm trying to implement a feature where the script searches through a column for a string from the form: if found, the old data in the row should be overwritten with data from the form; if not, the data should be appended as a new row.

This the snippet I have right now:

```<code>    var col4 = sheet.getRange(2, 4, sheet.getLastRow(), 1);
    var searchCol4 = SSNs.createTextFinder(e.parameter.Col4);
    searchCol4.matchEntireCell(true);
    var existingCol4Row = searchCol4.findNext().getRow();

    if (existingCol4Row !== null) {
      var nextRow = existingCol4Row
    } else {
      var nextRow = sheet.getLastRow() + 1
    }

    var newRow = headers.map(function(header) {
      return e.parameter[header]
    })

    sheet.getRange(nextRow, 1, 1, newRow.length).setValues([newRow])
</code>```

The problem I have is that the script only works if it finds a match in the column; if it doesn't, it doesn't add a new row as it should.
If I replace the whole if ... statement with var nextRow = sheet.getLastRow() + 1 then the script appends new rows, but obviously it doesn't replace old data anymore. I've also tried changing the condition to just existingCol4Row, with the same result.

Any tips?

EDIT: I got the code working, thanks to ziganotschka. I changed the conditional statement to check if searchCol4.findNext() was null rather than searchCol4.findNext().getRow(). I also made sure the code would only call .getRow() if searchCol4.findNext() wasn't null, as calling the method on a null range seems to make the code fail (anything past that line wouldn't run, including logging). Here's the working snippet:

```<code>var Col4 = sheet.getRange(2, 4, sheet.getLastRow(), 1);
    var searchCol4 = Col4.createTextFinder(e.parameter.Col4);
    searchCol4.matchEntireCell(true);
    var existingCol4 = searchCol4.findNext();

    if (existingCol4 !== null) {
      var nextRow = existingCol4.getRow();
    } else {
      var nextRow = sheet.getLastRow() + 1
    }
</code>```

答:
Log searchSSNs.findNext() and searchSSNs.findNext().getRow().

Result

If searchSSNs.findNext() is NULL, getRow() will return you the first row of the search range, so in your case row 2.

Thus,

searchSSNs.findNext().getRow() will never be NULL

Solution

Change your conditional statement to

if (searchSSNs.findNext() !== null) {

Sidenote: There is a confusion with the name of your textfinder range
  (searchSSNs or searchCol4?), I assume this is jsut a typing
  mistake.

Body:
I'm working on a script that allows users to enter data into a spreadsheet using an HTML form. I'm trying to implement a feature where the script searches through a column for a string from the form: if found, the old data in the row should be overwritten with data from the form; if not, the data should be appended as a new row.

This the snippet I have right now:

    var col4 = sheet.getRange(2, 4, sheet.getLastRow(), 1);
    var searchCol4 = SSNs.createTextFinder(e.parameter.Col4);
    searchCol4.matchEntireCell(true);
    var existingCol4Row = searchCol4.findNext().getRow();

    if (existingCol4Row !== null) {
      var nextRow = existingCol4Row
    } else {
      var nextRow = sheet.getLastRow() + 1
    }

    var newRow = headers.map(function(header) {
      return e.parameter[header]
    })

    sheet.getRange(nextRow, 1, 1, newRow.length).setValues([newRow])

The problem I have is that the script only works if it finds a match in the column; if it doesn't, it doesn't add a new row as it should.
If I replace the whole if ... statement with var nextRow = sheet.getLastRow() + 1 then the script appends new rows, but obviously it doesn't replace old data anymore. I've also tried changing the condition to just existingCol4Row, with the same result.

Any tips?

EDIT: I got the code working, thanks to ziganotschka. I changed the conditional statement to check if searchCol4.findNext() was null rather than searchCol4.findNext().getRow(). I also made sure the code would only call .getRow() if searchCol4.findNext() wasn't null, as calling the method on a null range seems to make the code fail (anything past that line wouldn't run, including logging). Here's the working snippet:

var Col4 = sheet.getRange(2, 4, sheet.getLastRow(), 1);
    var searchCol4 = Col4.createTextFinder(e.parameter.Col4);
    searchCol4.matchEntireCell(true);
    var existingCol4 = searchCol4.findNext();

    if (existingCol4 !== null) {
      var nextRow = existingCol4.getRow();
    } else {
      var nextRow = sheet.getLastRow() + 1
    }


问:
Why get request http dont working in Kotlin?
Hi guys i have problem with getting http request if i write "http://10.0.1.42:8080/state"(this is my ip) on emulator chrome this working, but if i want getting http request aplication close. Can someone help me?

```<code>import android.content.Intent
import android.os.Bundle
import android.widget.ImageButton
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import io.ktor.client.HttpClient
import io.ktor.client.request.get
import kotlinx.coroutines.runBlocking
import java.util.*

class kmnActivity : AppCompatActivity() {
    val EXTRA_TEXT = "com.example.application.example.EXTRA_TEXT"
    var uuid = UUID.randomUUID().toString()
    var response = "nothing"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_kmn)

        val textView = findViewById<TextView>(R.id.textView3)

        val kamenButton = findViewById<ImageButton>(R.id.kamen)
        val papierButton = findViewById<ImageButton>(R.id.papier)
        val nozniceButton = findViewById<ImageButton>(R.id.noznice)

        kamenButton.setOnClickListener {
            get_state()
            textView.setText(response)
           // openRollActivity()
        }

        papierButton.setOnClickListener {
            openRollActivity()
        }

        nozniceButton.setOnClickListener {
            openRollActivity()
        }
    }

    fun get_state(){
        val client = HttpClient()

        runBlocking {
             response = client.get<String>("http://10.0.1.42:8080/state") //Here not working
        }

        client.close()
    }

    fun openRollActivity() {
        val intent = Intent(this@kmnActivity, rollActivity::class.java)
        intent.putExtra("id", uuid)
        startActivity(intent)
    }
}
</code>```

Or if somebody have better way, He can said me. Thanks for your help.

答:
android:usesCleartextTraffic="true"
Add this code AndroidManifest.xml file
could refer to this https://medium.com/@son.rommer/fix-cleartext-traffic-error-in-android-9-pie-2f4e9e2235e6 u will get the clear idea over it

another possible fix will be
instead of HTTP can use https

Body:
Hi guys i have problem with getting http request if i write "http://10.0.1.42:8080/state"(this is my ip) on emulator chrome this working, but if i want getting http request aplication close. Can someone help me?

import android.content.Intent
import android.os.Bundle
import android.widget.ImageButton
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import io.ktor.client.HttpClient
import io.ktor.client.request.get
import kotlinx.coroutines.runBlocking
import java.util.*

class kmnActivity : AppCompatActivity() {
    val EXTRA_TEXT = "com.example.application.example.EXTRA_TEXT"
    var uuid = UUID.randomUUID().toString()
    var response = "nothing"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_kmn)

        val textView = findViewById<TextView>(R.id.textView3)

        val kamenButton = findViewById<ImageButton>(R.id.kamen)
        val papierButton = findViewById<ImageButton>(R.id.papier)
        val nozniceButton = findViewById<ImageButton>(R.id.noznice)

        kamenButton.setOnClickListener {
            get_state()
            textView.setText(response)
           // openRollActivity()
        }

        papierButton.setOnClickListener {
            openRollActivity()
        }

        nozniceButton.setOnClickListener {
            openRollActivity()
        }
    }

    fun get_state(){
        val client = HttpClient()

        runBlocking {
             response = client.get<String>("http://10.0.1.42:8080/state") //Here not working
        }

        client.close()
    }

    fun openRollActivity() {
        val intent = Intent(this@kmnActivity, rollActivity::class.java)
        intent.putExtra("id", uuid)
        startActivity(intent)
    }
}

Or if somebody have better way, He can said me. Thanks for your help.


问:
Value is correct when logged in Console but is undefined when using in variable
I fetched data from an API which gave me an object. When I tried to console log a specific value from the data i worked fine but when i tried using it as a variable i'm getting an error:

Cannot Read property from '.....' of undefined.

I'm using ReactJS.

This Is the Code Where I'm trying to access the value

```<code>
import React, { useContext, useState } from "react";
import ApexContext from "../context/apexContext";

const Overview = () => {
  const apexContext = useContext(ApexContext);

  const { gamer } = apexContext;

  const test = () => {
    console.log(gamer.platformInfo.platformSlug);
  };

  return (
    <div>
      <div>
        <img
          src="https://trackercdn.com/cdn/apex.tracker.gg/ranks/gold4.png"
          alt="Rank"
        />
        <h2>Active Legend: {gamer.platformInfo.platformSlug}</h2>
      </div>
      <div className="ui raised very padded text container segment">
        <button className="ui button" onClick={test}>
          Test
        </button>
      </div>
    </div>
  );
};

export default Overview;
</code>```

I am Using Context BTW.
Here IS the Code in which gamer object is being stored as an object

```<code>import React, { useReducer } from "react";
import Axios from "axios";
import ApexContext from "./apexContext";
import ApexReducer from "./apexReducer";
import {
  METADATA,
  PLATFORM_INFO,
  STATS,
  LOADING_TRUE,
  LOADING_FALSE,
  GAMER,
} from "./types";

const ApexState = (props) => {
  const InitialState = {
    metadata: {},
    platformInfo: {},
    overallStats: {},
    loading: false,
    gamer: {},
  };

  // Iniialize Reducer
  const [state, dispatch] = useReducer(ApexReducer, InitialState);

  // Finding The Specific Gamer Details
  const getGamer = async (platform, gamerId) => {
    dispatch({
      type: LOADING_TRUE,
    });

    const res = await Axios.get(
      `http://localhost:5000/api/v2/profile/${platform}/${gamerId}`
    );

    dispatch({
      type: GAMER,
      payload: res.data.data,
    });

    dispatch({
      type: LOADING_FALSE,
    });
  };

  return (
    <ApexContext.Provider
      value={{
        // loading: state.loading,
        // activeLegend: state.metadata.activeLegendName,
        // platformInfo: state.platformInfo,
        // overallStats: state.overallStats,
        gamer: state.gamer,
        getGamer,
      }}
    >
      {props.children}
    </ApexContext.Provider>
  );
};

export default ApexState;
</code>```

答:
Try conditional rendering

```<code>import React, { useContext, useState } from "react";
import ApexContext from "../context/apexContext";

const Overview = () => {
  const apexContext = useContext(ApexContext);

  const { gamer } = apexContext;

  const test = () => {
    console.log(gamer.platformInfo.platformSlug);
  };

  return (
    <div>
      <div>
        <img
          src="https://trackercdn.com/cdn/apex.tracker.gg/ranks/gold4.png"
          alt="Rank"
        />
        <h2>
          Active Legend:
          { gamer?.platformInfo?.platformSlug
            ? gamer.platformInfo.platformSlug
            : null}
        </h2>
      </div>
      <div className="ui raised very padded text container segment">
        <button className="ui button" onClick={test}>
          Test
        </button>
      </div>
    </div>
  );
};

export default Overview;
</code>```

// Update on this answer

You can achieve the same using optional chaining
{ gamer?.platformInfo?.platformSlug}

Looks elegant, isn't it?

Body:
I fetched data from an API which gave me an object. When I tried to console log a specific value from the data i worked fine but when i tried using it as a variable i'm getting an error:

Cannot Read property from '.....' of undefined.

I'm using ReactJS.

This Is the Code Where I'm trying to access the value

import React, { useContext, useState } from "react";
import ApexContext from "../context/apexContext";

const Overview = () => {
  const apexContext = useContext(ApexContext);

  const { gamer } = apexContext;

  const test = () => {
    console.log(gamer.platformInfo.platformSlug);
  };

  return (

Active Legend: {gamer.platformInfo.platformSlug}

        <button className="ui button" onClick={test}>
          Test
        </button>

  );
};

export default Overview;

I am Using Context BTW.
Here IS the Code in which gamer object is being stored as an object

import React, { useReducer } from "react";
import Axios from "axios";
import ApexContext from "./apexContext";
import ApexReducer from "./apexReducer";
import {
  METADATA,
  PLATFORM_INFO,
  STATS,
  LOADING_TRUE,
  LOADING_FALSE,
  GAMER,
} from "./types";

const ApexState = (props) => {
  const InitialState = {
    metadata: {},
    platformInfo: {},
    overallStats: {},
    loading: false,
    gamer: {},
  };

  // Iniialize Reducer
  const [state, dispatch] = useReducer(ApexReducer, InitialState);

  // Finding The Specific Gamer Details
  const getGamer = async (platform, gamerId) => {
    dispatch({
      type: LOADING_TRUE,
    });

    const res = await Axios.get(
      `http://localhost:5000/api/v2/profile/${platform}/${gamerId}`
    );

    dispatch({
      type: GAMER,
      payload: res.data.data,
    });

    dispatch({
      type: LOADING_FALSE,
    });
  };

  return (
    <ApexContext.Provider
      value={{
        // loading: state.loading,
        // activeLegend: state.metadata.activeLegendName,
        // platformInfo: state.platformInfo,
        // overallStats: state.overallStats,
        gamer: state.gamer,
        getGamer,
      }}
    >
      {props.children}
    </ApexContext.Provider>
  );
};

export default ApexState;

Body:
Try conditional rendering

import React, { useContext, useState } from "react";
import ApexContext from "../context/apexContext";

const Overview = () => {
  const apexContext = useContext(ApexContext);

  const { gamer } = apexContext;

  const test = () => {
    console.log(gamer.platformInfo.platformSlug);
  };

  return (
    <div>
      <div>
        <img
          src="https://trackercdn.com/cdn/apex.tracker.gg/ranks/gold4.png"
          alt="Rank"
        />
        <h2>
          Active Legend:
          { gamer?.platformInfo?.platformSlug
            ? gamer.platformInfo.platformSlug
            : null}
        </h2>
      </div>
      <div className="ui raised very padded text container segment">
        <button className="ui button" onClick={test}>
          Test
        </button>
      </div>
    </div>
  );
};

export default Overview;

// Update on this answer

You can achieve the same using optional chaining
{ gamer?.platformInfo?.platformSlug}

Looks elegant, isn't it?


问:
Customize working directory run gradle run task / project structure for web application
I'm working on small web app and I want to serve static files. I'm using application plugin. Part of it is distribution plugin which copies src/main/dist files into distribution zip. Running application with gradlew run uses project dir as working directory. For this reason static files are not found.

Is there a simple way to change working directory for run task?

Is there any other recommended structure for web app gradle project setup?

答:
You need to add the following to your build.gradle file to modify the working directory of a gradle task.

```<code>File runningDir = new File('build/run/')
runningDir.mkdirs()
tasks.run.workingDir = runningDir
</code>```

Check this thread for reference.

Body:
You need to add the following to your build.gradle file to modify the working directory of a gradle task.

File runningDir = new File('build/run/')
runningDir.mkdirs()
tasks.run.workingDir = runningDir

Check this thread for reference.


问:
Guard duty and vpc flow log
We have enabled vpc flow logs which are stored in s3 bucket. We have also enabled guard duty and i see it analyze vpc logs.

Anybody have suggestions, do we still need Athena table to point to S3 bucket for analyzing logs Or guard duty is sufficient

答:
GuardDuty will perform threat detection based on the contents of the VPC Flow Logs. If it finds a threat it has support to attempt to remediate the security concern.

If you're looking to investigate your network traffic and debug you'll still want Athena.

Title: Guard duty and vpc flow log