问:
Hot to compile a Swift script to a universal binary
We can easily compile a Swift script with:

```<code>$ swiftc /path/to/script.swift -o /path/to/binary
</code>```

However, that only compiles for the current architecture.

```<code>$ lipo -archs /path/to/binary
arm64
</code>```

I found some commands to build for multiple architectures, but they seem to require setting up a new project. I don’t want or need to do that yet, for now I just want to compile a single script file easily, hence swiftc. Is there a way to do this?

As a bonus, does Rosetta 2 need to be installed to generate universal binaries, or is it possible to make them without it?

答:
You would need to build the binary two times, for example, for a project that's targeting macOS, you would compile once with -target x86_64-apple-macos10.15 and the other one with -target arm64-apple-macos10.15.

After that, you would use lipo -create to stitch those together into a single file like this lipo -create <path/to/arm64-slice> <path/to/x86_64-slice> -output <path/to/universal/binary>.

This is how I did it:

```<code>➜  UniversalBinaryTest swiftc source.swift -target x86_64-apple-macos10.15 -o binary_x86-64
➜  UniversalBinaryTest lipo -archs binary_x86-64
x86_64
➜  UniversalBinaryTest swiftc source.swift -target arm64-apple-macos10.15 -o binary_arm64
➜  UniversalBinaryTest lipo -archs binary_arm64
arm64
➜  UniversalBinaryTest lipo -create binary_x86-64 binary_arm64 -output binary_universal
➜  UniversalBinaryTest lipo -archs binary_universal
x86_64 arm64
</code>```

After all of that, you would probably want to re-sign the new binary.

Edit: Actually, it looks like lipo handles signing for you if both slices are signed:

```<code>➜  UniversalBinaryTest codesign -s - binary_x86-64
➜  UniversalBinaryTest codesign -vvv binary_x86-64
binary_x86-64: valid on disk
binary_x86-64: satisfies its Designated Requirement
➜  UniversalBinaryTest codesign -vvvvv binary_x86-64
binary_x86-64: valid on disk
binary_x86-64: satisfies its Designated Requirement
➜  UniversalBinaryTest codesign -s - binary_arm64
➜  UniversalBinaryTest lipo -create binary_x86-64 binary_arm64 -output binary_universal
➜  UniversalBinaryTest codesign -vvv binary_universal
binary_universal: valid on disk
binary_universal: satisfies its Designated Requirement
</code>```

Body:
We can easily compile a Swift script with:

$ swiftc /path/to/script.swift -o /path/to/binary

However, that only compiles for the current architecture.

$ lipo -archs /path/to/binary
arm64

I found some commands to build for multiple architectures, but they seem to require setting up a new project. I don’t want or need to do that yet, for now I just want to compile a single script file easily, hence swiftc. Is there a way to do this?

As a bonus, does Rosetta 2 need to be installed to generate universal binaries, or is it possible to make them without it?

Body:
You would need to build the binary two times, for example, for a project that's targeting macOS, you would compile once with -target x86_64-apple-macos10.15 and the other one with -target arm64-apple-macos10.15.

After that, you would use lipo -create to stitch those together into a single file like this lipo -create <path/to/arm64-slice> <path/to/x86_64-slice> -output <path/to/universal/binary>.

This is how I did it:

➜  UniversalBinaryTest swiftc source.swift -target x86_64-apple-macos10.15 -o binary_x86-64
➜  UniversalBinaryTest lipo -archs binary_x86-64
x86_64
➜  UniversalBinaryTest swiftc source.swift -target arm64-apple-macos10.15 -o binary_arm64
➜  UniversalBinaryTest lipo -archs binary_arm64
arm64
➜  UniversalBinaryTest lipo -create binary_x86-64 binary_arm64 -output binary_universal
➜  UniversalBinaryTest lipo -archs binary_universal
x86_64 arm64

After all of that, you would probably want to re-sign the new binary.

Edit: Actually, it looks like lipo handles signing for you if both slices are signed:

➜  UniversalBinaryTest codesign -s - binary_x86-64
➜  UniversalBinaryTest codesign -vvv binary_x86-64
binary_x86-64: valid on disk
binary_x86-64: satisfies its Designated Requirement
➜  UniversalBinaryTest codesign -vvvvv binary_x86-64
binary_x86-64: valid on disk
binary_x86-64: satisfies its Designated Requirement
➜  UniversalBinaryTest codesign -s - binary_arm64
➜  UniversalBinaryTest lipo -create binary_x86-64 binary_arm64 -output binary_universal
➜  UniversalBinaryTest codesign -vvv binary_universal
binary_universal: valid on disk
binary_universal: satisfies its Designated Requirement


来源: stackexchange

问:
Page not found at /about/. The current path, about/, did not match any of these. Why can't django follow my URL path?
I'm sure this question has been asked many times before but I'm sure I'm doing everything exactly as the tutorial says and it's still not working. I can access the home page just fine but not the about page.

Here is screenshot of the error:

https://i.stack.imgur.com/oFNAJ.png

I have the URL path in my .urls file (file below)

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

urlpatterns = [
    path('', views.homepage, name='main-home'),
    path('about/', views.about, name='main-about'),
]
</code>```

And in the .urls file I have referenced the .views file (below)

```<code>from django.shortcuts import render
from django.http import HttpResponse

def homepage(request):
    return HttpResponse('<h1>Home</h1>')

def about(request):
    return HttpResponse('<h1>About</h1>')
</code>```

I could be missing something blatantly obvious but I've been staring at this for hours now and still can't figure out why it can't find the page.

EDIT: I am referring to the app urls file in the main post. In case its useful, here is the project .urls file:

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

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

答:
Then prefixed your url with homepage as

```<code>localhost:8000/homepage/about/
</code>```

It's always better to use {% url %} [Django-doc] template tags for urls inside templates which will point to your correct url even after you change url path but with the same name.

ContentLicense: CC BY-SA 4.0

Body:
I'm sure this question has been asked many times before but I'm sure I'm doing everything exactly as the tutorial says and it's still not working. I can access the home page just fine but not the about page.

Here is screenshot of the error:

https://i.stack.imgur.com/oFNAJ.png

I have the URL path in my .urls file (file below)

from django.urls import path
from . import views

urlpatterns = [
    path('', views.homepage, name='main-home'),
    path('about/', views.about, name='main-about'),
]

And in the .urls file I have referenced the .views file (below)

from django.shortcuts import render
from django.http import HttpResponse

def homepage(request):
    return HttpResponse('
Home
')

def about(request):
    return HttpResponse('
About
')

I could be missing something blatantly obvious but I've been staring at this for hours now and still can't figure out why it can't find the page.

EDIT: I am referring to the app urls file in the main post. In case its useful, here is the project .urls file:

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

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

Body:
Then prefixed your url with homepage as

localhost:8000/homepage/about/

It's always better to use {% url %} [Django-doc] template tags for urls inside templates which will point to your correct url even after you change url path but with the same name.


问:
How to justify SVG text to the right?
I am using SVG to create some tables and put some text inside them. I can controll the placement of the text with SVG coordinates, but the text length is variable as it comes from some data. There is some way to get the length of the text or some other tool to justify it to the right?</p>

答:
align right

Place your text on a textPath, set pathLength=100

https://developer.mozilla.org/en-US/docs/Web/SVG/Element/textPath

startoffset and text-anchor take care of positioning

play with lower startoffset to add right-padding

<svg viewbox="0 0 200 50">
  <path id="P" pathLength="100" d="M0 25h200" stroke="blue"/>
  <text>
    <textPath href="#P"
              startoffset="100" text-anchor="end"
              dominant-baseline="middle"
              fill="green" font-size="14px">Right aligned</textPath>
  </text>
</svg>```

Title: How to justify SVG text to the right?


问:
Resetting Java's Authenticator
I'm using the Autheticator class to access a password-protected URL. I've extended it and created my own authenticator, and I set it as the default authenticator using Authenticator#setDefault(java.net.Authenticator). Once I'm done accessing the URL, I'd like to reset the authenticator. The Javadoc says that setting it to null removes any previously set authenticator. But I'm not sure if that means that it has been reset to use the default authenticator (is there such a thing?).

答: In the source code of Sun's JDK implemenentation null is the default value.

ContentLicense: CC BY-SA 3.0

Title: Resetting Java's Authenticator


问:
How to get Difference between two datetime?
I want to get difference between two datetime in minutes. I have attached picture of my data stored in table and datatype of my columns is Varchar2. I have created below query and I am getting error of "Not a valid month". what I want that when user_closer_date column is null then I want to add default sysdate.

```<code>SELECT ROUND(60*24*(COALESCE(TO_DATE(lse.user_closer_date , 'DD-Mon-RR HH24:MI:SS'), sysdate) - to_date(Request_Raised_Date
  ||' '
  ||request_raised_time, 'DD-Mon-RR HH24:MI:SS'))) AS TAT
  FROM sml.Xx_Lsp_Linestoppage_Entry lse
  Left join Emp_Master cm ON Lse.Raised_By = Cm.Emp_No
  Left join Emp_Master cm1 ON Lse.Closer_User = Cm1.Emp_No
  Left join Emp_Master cm2 ON Lse.Final_Closed_By = Cm2.Emp_No
  where Lse.Request_Raised_Date Between To_Date('01-Jan-2022', 'DD-Mon-YYYY') and To_Date('28-Feb-2022', 'DD-Mon-YYYY')
  ORDER BY lse.Line_Stop_Id Asc;
</code>```

答:
Your query is exactly how it's done, only the datatypes should be DATE as @EdStevens said, which contains both day and time. Conventionally, your task would be done like that:

```<code>CREATE TABLE lse (
  request_raised DATE,
  user_closer    DATE
);
INSERT INTO lse VALUES (TIMESTAMP '2022-02-11 09:20:00', NULL);
INSERT INTO lse VALUES (TIMESTAMP '2022-02-11 08:00:00', TIMESTAMP '2022-02-11 08:15:00');
INSERT INTO lse VALUES (TIMESTAMP '2022-02-11 06:34:00', TIMESTAMP '2022-02-11 06:50:00');
INSERT INTO lse VALUES (TIMESTAMP '2022-02-11 06:36:00', NULL);
</code>```

Then your query just works:

```<code>SELECT ROUND(60*24* (COALESCE(user_closer, SYSDATE) - request_raised))
  FROM lse
 WHERE request_raised BETWEEN TIMESTAMP '2022-01-01 00:00:00'
                          AND TIMESTAMP '2022-02-28 23:59:59';

666
15
16
830
</code>```

BTW, you can use of course TO_DATE('2022-Feb-11 09:20', 'YYYY-Mon-DD HH24:MI') instead of the ANSI literal `DATE '2022-02-11 09:20:00', I find the latter just personally shorter and clearer.

In case you are forced to present day and time as string, you can easily convert a DATE to a VARCHAR2, even on the fly with a virtual column:

```<code>ALTER TABLE lse ADD request_raised_date GENERATED ALWAYS AS
  (TO_CHAR(request_raised, 'DD-Mon-YYYY', 'nls_date_language=ENGLISH')) VIRTUAL;

ALTER TABLE lse ADD request_raised_time
  GENERATED ALWAYS AS (TO_CHAR(request_raised, 'HH24:MI')) VIRTUAL;

SELECT * FROM lse;

REQUEST_RAISED   USER_CLOSER       REQUEST_RAISED_DATE  REQUEST_RAISED_TIME
---------------- ---------------   -------------------  --------------------
2022-02-11 09:20 (null)            11-Feb-2022          09:20
2022-02-11 08:00 2022-02-11 08:15  11-Feb-2022          08:00
2022-02-11 06:34 2022-02-11 06:50  11-Feb-2022          06:34
2022-02-11 06:36 (null)            11-Feb-2022          06:36
</code>```

Body:
I want to get difference between two datetime in minutes. I have attached picture of my data stored in table and datatype of my columns is Varchar2. I have created below query and I am getting error of "Not a valid month". what I want that when user_closer_date column is null then I want to add default sysdate.

SELECT ROUND(60*24*(COALESCE(TO_DATE(lse.user_closer_date , 'DD-Mon-RR HH24:MI:SS'), sysdate) - to_date(Request_Raised_Date
  ||' '
  ||request_raised_time, 'DD-Mon-RR HH24:MI:SS'))) AS TAT
  FROM sml.Xx_Lsp_Linestoppage_Entry lse
  Left join Emp_Master cm ON Lse.Raised_By = Cm.Emp_No
  Left join Emp_Master cm1 ON Lse.Closer_User = Cm1.Emp_No
  Left join Emp_Master cm2 ON Lse.Final_Closed_By = Cm2.Emp_No
  where Lse.Request_Raised_Date Between To_Date('01-Jan-2022', 'DD-Mon-YYYY') and To_Date('28-Feb-2022', 'DD-Mon-YYYY')
  ORDER BY lse.Line_Stop_Id Asc;

Body:
Your query is exactly how it's done, only the datatypes should be DATE as @EdStevens said, which contains both day and time. Conventionally, your task would be done like that:

CREATE TABLE lse (
  request_raised DATE,
  user_closer    DATE
);
INSERT INTO lse VALUES (TIMESTAMP '2022-02-11 09:20:00', NULL);
INSERT INTO lse VALUES (TIMESTAMP '2022-02-11 08:00:00', TIMESTAMP '2022-02-11 08:15:00');
INSERT INTO lse VALUES (TIMESTAMP '2022-02-11 06:34:00', TIMESTAMP '2022-02-11 06:50:00');
INSERT INTO lse VALUES (TIMESTAMP '2022-02-11 06:36:00', NULL);

Then your query just works:

SELECT ROUND(60*24* (COALESCE(user_closer, SYSDATE) - request_raised))
  FROM lse
 WHERE request_raised BETWEEN TIMESTAMP '2022-01-01 00:00:00'
                          AND TIMESTAMP '2022-02-28 23:59:59';

666
15
16
830

BTW, you can use of course TO_DATE('2022-Feb-11 09:20', 'YYYY-Mon-DD HH24:MI') instead of the ANSI literal `DATE '2022-02-11 09:20:00', I find the latter just personally shorter and clearer.

In case you are forced to present day and time as string, you can easily convert a DATE to a VARCHAR2, even on the fly with a virtual column:

ALTER TABLE lse ADD request_raised_date GENERATED ALWAYS AS
  (TO_CHAR(request_raised, 'DD-Mon-YYYY', 'nls_date_language=ENGLISH')) VIRTUAL;

ALTER TABLE lse ADD request_raised_time
  GENERATED ALWAYS AS (TO_CHAR(request_raised, 'HH24:MI')) VIRTUAL;

SELECT * FROM lse;

REQUEST_RAISED   USER_CLOSER       REQUEST_RAISED_DATE  REQUEST_RAISED_TIME
---------------- ---------------   -------------------  --------------------
2022-02-11 09:20 (null)            11-Feb-2022          09:20
2022-02-11 08:00 2022-02-11 08:15  11-Feb-2022          08:00
2022-02-11 06:34 2022-02-11 06:50  11-Feb-2022          06:34
2022-02-11 06:36 (null)            11-Feb-2022          06:36


问:
unknown error on npm install "npm ERR! Unexpected token '.'" on using NVM-Windows, Node v17, NPM v8
This seems to be a semi-common error, but it's unclear to me what is causing it. I want to know what is causing this error and how can I resolve it.

Using NVM I have installed Node @latest (Version 17.4.0), which has installed npm's matching latest (v8.3.1).

```<code>PS C:\myRepo> node -v
v17.4.0
PS C:\myRepo> npm -v
8.3.1
PS C:\myRepo> nvm list

  * 17.4.0 (Currently using 64-bit executable)
    17.0.0
    15.6.0
    14.18.3
    14.15.4
    12.20.1
</code>```

I then go to install a package dependency from npm and it gives me an error regardless of the package name:

```<code>PS C:\myRepo> npm install -g npm
npm ERR! Unexpected token '.'

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\yodama\AppData\Local\npm-cache\_logs\2022-01-25T16_38_44_607Z-debug-0.log

</code>```

And we can see the full debug log:

```<code>0 verbose cli [
0 verbose cli   'C:\\Program Files\\nodejs\\node.exe',
0 verbose cli   'C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js',
0 verbose cli   'install',
0 verbose cli   '-g',
0 verbose cli   'npm'
0 verbose cli ]
1 info using npm@8.3.1
2 info using node@v17.4.0
3 timing npm:load:whichnode Completed in 0ms
4 timing config:load:defaults Completed in 1ms
5 timing config:load:file:C:\Users\yodama\AppData\Roaming\nvm\v17.4.0\node_modules\npm\npmrc Completed in 3ms
6 timing config:load:builtin Completed in 3ms
7 timing config:load:cli Completed in 3ms
8 timing config:load:env Completed in 0ms
9 timing config:load:project Completed in 3ms
10 timing config:load:file:C:\Users\yodama\.npmrc Completed in 4ms
11 timing config:load:user Completed in 4ms
12 timing config:load:file:C:\Program Files\nodejs\etc\npmrc Completed in 0ms
13 timing config:load:global Completed in 0ms
14 timing config:load:validate Completed in 0ms
15 timing config:load:credentials Completed in 1ms
16 timing config:load:setEnvs Completed in 1ms
17 timing config:load Completed in 19ms
18 timing npm:load:configload Completed in 20ms
19 timing npm:load:setTitle Completed in 1ms
20 timing config:load:flatten Completed in 4ms
21 timing npm:load:display Completed in 7ms
22 verbose logfile C:\Users\yodama\AppData\Local\npm-cache\_logs\2022-01-25T16_38_44_607Z-debug-0.log
23 timing npm:load:logFile Completed in 13ms
24 timing npm:load:timers Completed in 0ms
25 timing npm:load:configScope Completed in 0ms
26 timing npm:load Completed in 42ms
27 verbose stack C:\Users\yodama\AppData\Roaming\nvm\v17.4.0\node_modules\npm\node_modules\libnpmfund:1
27 verbose stack ../workspaces/libnpmfund
27 verbose stack ^
27 verbose stack
27 verbose stack SyntaxError: Unexpected token '.'
27 verbose stack     at Object.compileFunction (node:vm:352:18)
27 verbose stack     at wrapSafe (node:internal/modules/cjs/loader:1026:15)
27 verbose stack     at Module._compile (node:internal/modules/cjs/loader:1061:27)
27 verbose stack     at Object.Module._extensions..js (node:internal/modules/cjs/loader:1149:10)
27 verbose stack     at Module.load (node:internal/modules/cjs/loader:975:32)
27 verbose stack     at Function.Module._load (node:internal/modules/cjs/loader:822:12)
27 verbose stack     at Module.require (node:internal/modules/cjs/loader:999:19)
27 verbose stack     at require (node:internal/modules/cjs/helpers:102:18)
27 verbose stack     at Object.<anonymous> (C:\Users\yodama\AppData\Roaming\nvm\v17.4.0\node_modules\npm\lib\utils\reify-output.js:16:38)
27 verbose stack     at Module._compile (node:internal/modules/cjs/loader:1097:14)
28 verbose cwd C:\myRepo
29 verbose Windows_NT 10.0.22000
30 verbose argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "install" "-g" "npm"
31 verbose node v17.4.0
32 verbose npm  v8.3.1
33 error Unexpected token '.'
34 verbose exit 1
35 timing npm Completed in 262ms
36 verbose code 1
</code>```

switching using nvm for windows to Node 14 fixes this issue:

```<code>
PS C:\myRepo> nvm use 14.18.3
Now using node v14.18.3 (64-bit)
PS C:\myRepo> node -v
v14.18.3
PS C:\myRepo> npm -v
6.14.15
PS C:\myRepo> npm i -g @microsoft/rush
npm WARN deprecated @opentelemetry/types@0.2.0: Package renamed to @opentelemetry/api, see https://github.com/open-telemetry/opentelemetry-js
C:\Program Files\nodejs\rush -> C:\Program Files\nodejs\node_modules\@microsoft\rush\bin\rush
C:\Program Files\nodejs\rushx -> C:\Program Files\nodejs\node_modules\@microsoft\rush\bin\rushx
+ @microsoft/rush@5.61.1
added 286 packages from 296 contributors in 26.69s
</code>```

What is going wrong here? Is this an NVM issue, or a npm 8.x issue? I need to do testing in Node v17 for a specific bug, so just using the older versions of Node isn't a viable workaround.

答:
Update the NVM-Windows to the newest version, which is by now
1.1.9

They've had fixed this issue, Workspace folder must be symlink.

The issue goes with NVM-Windows not NPM

Body:
This seems to be a semi-common error, but it's unclear to me what is causing it. I want to know what is causing this error and how can I resolve it.

Using NVM I have installed Node @latest (Version 17.4.0), which has installed npm's matching latest (v8.3.1).

PS C:\myRepo> node -v
v17.4.0
PS C:\myRepo> npm -v
8.3.1
PS C:\myRepo> nvm list

  * 17.4.0 (Currently using 64-bit executable)
    17.0.0
    15.6.0
    14.18.3
    14.15.4
    12.20.1

I then go to install a package dependency from npm and it gives me an error regardless of the package name:

PS C:\myRepo> npm install -g npm
npm ERR! Unexpected token '.'

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\yodama\AppData\Local\npm-cache\_logs\2022-01-25T16_38_44_607Z-debug-0.log

And we can see the full debug log:

0 verbose cli [
0 verbose cli   'C:\\Program Files\\nodejs\\node.exe',
0 verbose cli   'C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js',
0 verbose cli   'install',
0 verbose cli   '-g',
0 verbose cli   'npm'
0 verbose cli ]
1 info using npm@8.3.1
2 info using node@v17.4.0
3 timing npm:load:whichnode Completed in 0ms
4 timing config:load:defaults Completed in 1ms
5 timing config:load:file:C:\Users\yodama\AppData\Roaming\nvm\v17.4.0\node_modules\npm\npmrc Completed in 3ms
6 timing config:load:builtin Completed in 3ms
7 timing config:load:cli Completed in 3ms
8 timing config:load:env Completed in 0ms
9 timing config:load:project Completed in 3ms
10 timing config:load:file:C:\Users\yodama\.npmrc Completed in 4ms
11 timing config:load:user Completed in 4ms
12 timing config:load:file:C:\Program Files\nodejs\etc\npmrc Completed in 0ms
13 timing config:load:global Completed in 0ms
14 timing config:load:validate Completed in 0ms
15 timing config:load:credentials Completed in 1ms
16 timing config:load:setEnvs Completed in 1ms
17 timing config:load Completed in 19ms
18 timing npm:load:configload Completed in 20ms
19 timing npm:load:setTitle Completed in 1ms
20 timing config:load:flatten Completed in 4ms
21 timing npm:load:display Completed in 7ms
22 verbose logfile C:\Users\yodama\AppData\Local\npm-cache\_logs\2022-01-25T16_38_44_607Z-debug-0.log
23 timing npm:load:logFile Completed in 13ms
24 timing npm:load:timers Completed in 0ms
25 timing npm:load:configScope Completed in 0ms
26 timing npm:load Completed in 42ms
27 verbose stack C:\Users\yodama\AppData\Roaming\nvm\v17.4.0\node_modules\npm\node_modules\libnpmfund:1
27 verbose stack ../workspaces/libnpmfund
27 verbose stack ^
27 verbose stack
27 verbose stack SyntaxError: Unexpected token '.'
27 verbose stack     at Object.compileFunction (node:vm:352:18)
27 verbose stack     at wrapSafe (node:internal/modules/cjs/loader:1026:15)
27 verbose stack     at Module._compile (node:internal/modules/cjs/loader:1061:27)
27 verbose stack     at Object.Module._extensions..js (node:internal/modules/cjs/loader:1149:10)
27 verbose stack     at Module.load (node:internal/modules/cjs/loader:975:32)
27 verbose stack     at Function.Module._load (node:internal/modules/cjs/loader:822:12)
27 verbose stack     at Module.require (node:internal/modules/cjs/loader:999:19)
27 verbose stack     at require (node:internal/modules/cjs/helpers:102:18)
27 verbose stack     at Object.<anonymous> (C:\Users\yodama\AppData\Roaming\nvm\v17.4.0\node_modules\npm\lib\utils\reify-output.js:16:38)
27 verbose stack     at Module._compile (node:internal/modules/cjs/loader:1097:14)
28 verbose cwd C:\myRepo
29 verbose Windows_NT 10.0.22000
30 verbose argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "install" "-g" "npm"
31 verbose node v17.4.0
32 verbose npm  v8.3.1
33 error Unexpected token '.'
34 verbose exit 1
35 timing npm Completed in 262ms
36 verbose code 1

switching using nvm for windows to Node 14 fixes this issue:

PS C:\myRepo> nvm use 14.18.3
Now using node v14.18.3 (64-bit)
PS C:\myRepo> node -v
v14.18.3
PS C:\myRepo> npm -v
6.14.15
PS C:\myRepo> npm i -g @microsoft/rush
npm WARN deprecated @opentelemetry/types@0.2.0: Package renamed to @opentelemetry/api, see https://github.com/open-telemetry/opentelemetry-js
C:\Program Files\nodejs\rush -> C:\Program Files\nodejs\node_modules\@microsoft\rush\bin\rush
C:\Program Files\nodejs\rushx -> C:\Program Files\nodejs\node_modules\@microsoft\rush\bin\rushx
+ @microsoft/rush@5.61.1
added 286 packages from 296 contributors in 26.69s

What is going wrong here? Is this an NVM issue, or a npm 8.x issue? I need to do testing in Node v17 for a specific bug, so just using the older versions of Node isn't a viable workaround.


问:
Positioning an image on top of text
How can I position an image on top text. Like in the image given

答:
Here is a basic example using flex. I put a border on the div so you can see exactly what the flex does. Also, for an example like this where you want the image to be directly over text, you have to lookout for default margins/padding. For example, the
 element has a default margin which I set to 0.

.row {
  display: flex;
  flex-direction: column;
  border: solid 1px black;
  width: 200px;
  height: 80px;
  padding: 20px;
  background-color: #1e3f5a;
}

p {
  margin: 0; /* removes default p margin */
  text-align: center;
  font-size: 30px;
  color: white;
}

img {
  align-self: flex-end;
  margin-right: 1.5rem; /* optional */
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="row">
  <img src="https://dummyimage.com/55x25/ed7014/fff&text=Trending">
  <p>Dex Activity</p>
</div></code>```

Title: Positioning an image on top of text

Body:
Here is a basic example using flex. I put a border on the div so you can see exactly what the flex does. Also, for an example like this where you want the image to be directly over text, you have to lookout for default margins/padding. For example, the <p> element has a default margin which I set to 0.

.row {
  display: flex;
  flex-direction: column;
  border: solid 1px black;
  width: 200px;
  height: 80px;
  padding: 20px;
  background-color: #1e3f5a;
}

p {
  margin: 0; /* removes default p margin */
  text-align: center;
  font-size: 30px;
  color: white;
}

img {
  align-self: flex-end;
  margin-right: 1.5rem; /* optional */
}

<div class="row">
  <img src="https://dummyimage.com/55x25/ed7014/fff&text=Trending">
  <p>Dex Activity</p>
</div>


问:
Python warning confusion
I have the following code which correlates data brought in from PgSQL.

```<code>if wd is not None and dd is not None:
    alldata=np.concatenate((wd,dd))
    alldat_df=pd.DataFrame(alldata, index=None, columns=['datetime','rain', 'raindiff'])

    alldat_df.drop(alldat_df.loc[2708:2738].index, inplace=True)
    alldata=np.array(alldat_df)
    alldata[0,2]=0
    mask = (alldat_df['datetime'] > fdate) & (alldat_df['datetime'] <= tdate)
    ndf=alldat_df.loc[mask]
    ndf.loc[0,['raindiff']]=0
    ndf.index=ndf['datetime']
    ndf.drop(columns=['datetime'], inplace=True)
    davisdfnew=ndf.resample(bs, offset=bs, origin=fdate).sum()
    davisdfnew.rename(columns={'rain':'rain sum','raindiff':'raindiff sum'}, inplace=True)

if dd is None:
    alldat_df=pd.DataFrame(wd, index=None, columns=['datetime', 'rain', 'raindiff'])
    mask = (alldat_df['datetime'] > fdate) & (alldat_df['datetime'] <= tdate)
    ndf=alldat_df.loc[mask]
    ndf.loc[0,['raindiff']]=0
    ndf.index=ndf['datetime']
    ndf.drop(columns=['datetime'], inplace=True)
    davisdfnew=ndf.resample(bs, offset=bs, origin=fdate).sum()
    davisdfnew.rename(columns={'rain':'rain sum','raindiff':'raindiff sum'}, inplace=True)

if wd is None:
    alldat_df=pd.DataFrame(dd, index=None, columns=['datetime', 'rain', 'raindiff'])
    mask = (alldat_df['datetime'] > fdate) & (alldat_df['datetime'] <= tdate)
    ndf=alldat_df.loc[mask]
    ndf.loc[0,['raindiff']]=0
    ndf.index=ndf['datetime']
    ndf.drop(columns=['datetime'], inplace=True)
    davisdfnew=ndf.resample(bs, offset=bs, origin=fdate).sum()
    davisdfnew.rename(columns={'rain':'rain sum','raindiff':'raindiff sum'}, inplace=True)
</code>```

When it runs and the first two if conditions are met it throws the following warning

```<code>SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame

See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
  ndf.loc[0,['raindiff']]=0
</code>```

but when the condition if wd is None is met there is no warning
in all cases the value at ndf.loc[0,['raindif']] is a none type object

I would appreciate it if someone could shed some light on this!

edited as per @john giorgio comment

wd=

```<code>array([[datetime.datetime(2021, 5, 20, 10, 45), 0.0, None],
       [datetime.datetime(2021, 5, 20, 11, 0), 0.0, 0.0],
       [datetime.datetime(2021, 5, 20, 11, 15), 0.0, 0.0],
       ...,
       [datetime.datetime(2021, 6, 17, 22, 30), 96.6, 0.0],
       [datetime.datetime(2021, 6, 17, 22, 45), 96.6, 0.0],
       [datetime.datetime(2021, 6, 17, 23, 0), 96.6, 0.0]], dtype=object)
</code>```

dd=

```<code>array([[datetime.datetime(2021, 6, 17, 15, 30, 42), 96.6, None],
       [datetime.datetime(2021, 6, 17, 15, 35, 42), 96.6, 0.0],
       [datetime.datetime(2021, 6, 17, 15, 40, 42), 96.6, 0.0],
       ...,
       [datetime.datetime(2021, 6, 30, 23, 45, 41), 113.8, 0.0],
       [datetime.datetime(2021, 6, 30, 23, 50, 41), 113.8, 0.0],
       [datetime.datetime(2021, 6, 30, 23, 55, 41), 113.8, 0.0]],
      dtype=object)
</code>```

as I said, the error occurs when wd exists. If both wd and dd exist they are combined, and duplicate datetimes removed to give ndf.
if only wd exists ndf is formed from it, in both these cases the error occurs.

If only dd exists ndf is formed from this, and the error does not occur

答: What you could try to do is resetting the index, .reset_index(drop=True) each time you take a subsample of your original dataset, before performing any other action.

Title: Python warning confusion

Body:
I have the following code which correlates data brought in from PgSQL.

if wd is not None and dd is not None:
    alldata=np.concatenate((wd,dd))
    alldat_df=pd.DataFrame(alldata, index=None, columns=['datetime','rain', 'raindiff'])

    alldat_df.drop(alldat_df.loc[2708:2738].index, inplace=True)
    alldata=np.array(alldat_df)
    alldata[0,2]=0
    mask = (alldat_df['datetime'] > fdate) & (alldat_df['datetime'] <= tdate)
    ndf=alldat_df.loc[mask]
    ndf.loc[0,['raindiff']]=0
    ndf.index=ndf['datetime']
    ndf.drop(columns=['datetime'], inplace=True)
    davisdfnew=ndf.resample(bs, offset=bs, origin=fdate).sum()
    davisdfnew.rename(columns={'rain':'rain sum','raindiff':'raindiff sum'}, inplace=True)

if dd is None:
    alldat_df=pd.DataFrame(wd, index=None, columns=['datetime', 'rain', 'raindiff'])
    mask = (alldat_df['datetime'] > fdate) & (alldat_df['datetime'] <= tdate)
    ndf=alldat_df.loc[mask]
    ndf.loc[0,['raindiff']]=0
    ndf.index=ndf['datetime']
    ndf.drop(columns=['datetime'], inplace=True)
    davisdfnew=ndf.resample(bs, offset=bs, origin=fdate).sum()
    davisdfnew.rename(columns={'rain':'rain sum','raindiff':'raindiff sum'}, inplace=True)

if wd is None:
    alldat_df=pd.DataFrame(dd, index=None, columns=['datetime', 'rain', 'raindiff'])
    mask = (alldat_df['datetime'] > fdate) & (alldat_df['datetime'] <= tdate)
    ndf=alldat_df.loc[mask]
    ndf.loc[0,['raindiff']]=0
    ndf.index=ndf['datetime']
    ndf.drop(columns=['datetime'], inplace=True)
    davisdfnew=ndf.resample(bs, offset=bs, origin=fdate).sum()
    davisdfnew.rename(columns={'rain':'rain sum','raindiff':'raindiff sum'}, inplace=True)

When it runs and the first two if conditions are met it throws the following warning

SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame

See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
  ndf.loc[0,['raindiff']]=0

but when the condition if wd is None is met there is no warning
in all cases the value at ndf.loc[0,['raindif']] is a none type object

I would appreciate it if someone could shed some light on this!

edited as per @john giorgio comment

wd=

array([[datetime.datetime(2021, 5, 20, 10, 45), 0.0, None],
       [datetime.datetime(2021, 5, 20, 11, 0), 0.0, 0.0],
       [datetime.datetime(2021, 5, 20, 11, 15), 0.0, 0.0],
       ...,
       [datetime.datetime(2021, 6, 17, 22, 30), 96.6, 0.0],
       [datetime.datetime(2021, 6, 17, 22, 45), 96.6, 0.0],
       [datetime.datetime(2021, 6, 17, 23, 0), 96.6, 0.0]], dtype=object)

dd=

array([[datetime.datetime(2021, 6, 17, 15, 30, 42), 96.6, None],
       [datetime.datetime(2021, 6, 17, 15, 35, 42), 96.6, 0.0],
       [datetime.datetime(2021, 6, 17, 15, 40, 42), 96.6, 0.0],
       ...,
       [datetime.datetime(2021, 6, 30, 23, 45, 41), 113.8, 0.0],
       [datetime.datetime(2021, 6, 30, 23, 50, 41), 113.8, 0.0],
       [datetime.datetime(2021, 6, 30, 23, 55, 41), 113.8, 0.0]],
      dtype=object)

as I said, the error occurs when wd exists. If both wd and dd exist they are combined, and duplicate datetimes removed to give ndf.
if only wd exists ndf is formed from it, in both these cases the error occurs.

If only dd exists ndf is formed from this, and the error does not occur


问:
How to use an object outside of scope of a loop in javascript
The following function compares a value against an array and goes through the elements of the array until finds an element that is smaller than the comparison value. As a result it should return the index of that element where condition was met. In this example it should return the index of 4 (with value of 5). I store this index in lowestNumberIndex but can only access it within the scope of last if() function. How can I access it outside the for loop? Notice that I have initiated the object outside of the for loop.

```<code>function findLowerIndex () {

  let firstArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
  let compareValue = [6];

  var lowerNumber = null;
  var lowestNumberIndex = null;

  for (i=firstArray.length-1; i>0; i--) {
    lowerNumber = firstArray[i];
    if (lowerNumber < compareValue) {
      lowestNumberIndex = i;
      return;
    }
  }
}
</code>```

In case you are wondering, I need to have the for loop in reverse format because this is part of a larger code and the dataset is organized in a way that doing it backwards ensures efficiency of run.

答: So thanks to all the comments and solutions I figured what the problem was. The problem was that I did not know using return jumps you out of the whole function. Using break instead worked!

Body:
The following function compares a value against an array and goes through the elements of the array until finds an element that is smaller than the comparison value. As a result it should return the index of that element where condition was met. In this example it should return the index of 4 (with value of 5). I store this index in lowestNumberIndex but can only access it within the scope of last if() function. How can I access it outside the for loop? Notice that I have initiated the object outside of the for loop.

function findLowerIndex () {

  let firstArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
  let compareValue = [6];

  var lowerNumber = null;
  var lowestNumberIndex = null;

  for (i=firstArray.length-1; i>0; i--) {
    lowerNumber = firstArray[i];
    if (lowerNumber < compareValue) {
      lowestNumberIndex = i;
      return;
    }
  }
}

In case you are wondering, I need to have the for loop in reverse format because this is part of a larger code and the dataset is organized in a way that doing it backwards ensures efficiency of run.


问:
I got this error while creating a new Laravel project -> Laravel new projectName
CLICK HERE to look the SCREENSHOT of the Problem

I am creating a new Laravel project by using following command, Laravel new projectName

答:
your php version is lower than what laravel 9 has required.
you need to upgrade your php to version 8 and above .

see the instruction below

https://wecode101.com/upgrade-xampp-from-php-7-to-8-windows-10

hope that would work for you .


问:
if statement php?
i don't know why but this is not working:

I am working on an Ajax send , i have send a value to a PHP script which parses the values and store the values in a php variable.
and now:

```<code>$id = $_GET['id'];
$url = $_GET['url'];
$check = $_GET['check'];
$filid = mysql_real_escape_string($id);
$filurl = mysql_real_escape_string($url);

if($check == 'true'){
    $insert  = "INSERT INTO tab (id,url) VALUES ('$filid','$filurl')";
    mysql_query($insert) or die(mysql_error());
}
</code>```

I am confirmed that my Ajax code is working , i'm not sure about php.When i remove the if statement and directly put the data into my database , it's working.

I'm new so please tolerate.
I hope someone can point me out my mistakes are.

Thanks!

答:
Anything you get from the browser is iffy. There is nasty people about,

sanitize the inputs.

Title: if statement php?

Body:
i don't know why but this is not working:

I am working on an Ajax send , i have send a value to a PHP script which parses the values and store the values in a php variable.
and now:

$id = $_GET['id'];
$url = $_GET['url'];
$check = $_GET['check'];
$filid = mysql_real_escape_string($id);
$filurl = mysql_real_escape_string($url);

if($check == 'true'){
    $insert  = "INSERT INTO tab (id,url) VALUES ('$filid','$filurl')";
    mysql_query($insert) or die(mysql_error());
}

I am confirmed that my Ajax code is working , i'm not sure about php.When i remove the if statement and directly put the data into my database , it's working.

I'm new so please tolerate.
I hope someone can point me out my mistakes are.

Thanks!


问:
Material Design WPF TextBox Validation error message change position when scrolling page
I'm new in Material Design. Could someone, please, explain me how can I fix a bug with validation message in textbox

Validation error shows uncorrectly - changes position when I'm scrolling view.
Here is code from .xaml

```<code><TextBox Grid.Row="11"
                 Grid.Column="1"
                 Width="20"
                 VerticalAlignment="Center"
                 materialDesign:ValidationAssist.UsePopup="True"
                 materialDesign:ValidationAssist.OnlyShowOnFocus="True"
                 HorizontalAlignment="Left"
                 ToolTip="Use a popup which can escape the bounds of the control where space is limited">
            <TextBox.Text>
                <Binding Path="Name"
                         UpdateSourceTrigger="PropertyChanged">
                    <Binding.ValidationRules>
                        <helpers:NotEmptyValidationRule ValidatesOnTargetUpdated="True" />
                    </Binding.ValidationRules>
                </Binding>
            </TextBox.Text>
        </TextBox>
</code>```

答:
This Validation TextBox uses data binding behind the scenes to work. The code is correct but you might be missing the data binding on the Name.

```<code>    <Binding Path="Name" UpdateSourceTrigger="PropertyChanged">
</code>```

For this, to work you need to data bind the path to the Name property.

This can be done in two steps.

Create/reuse a property Name in the desired class.

Assign the data context of the XAML page to the desired class.

Sample (desired class is shown as MainWindow here)

Step 1, file: MainWindow.xaml.cs

```<code>    private string _name;

    public string Name
    {
        get { return _name; }
        set { _name = value; }
    }
</code>```

Step 2, file: MainWindow.xaml.cs

```<code>    public MainWindow()
    {
        InitializeComponent();
        this.DataContext = this;
        ...
    }
</code>```

And then the problem should be solved.

Body:
I'm new in Material Design. Could someone, please, explain me how can I fix a bug with validation message in textbox

Validation error shows uncorrectly - changes position when I'm scrolling view.
Here is code from .xaml

<TextBox Grid.Row="11"
                 Grid.Column="1"
                 Width="20"
                 VerticalAlignment="Center"
                 materialDesign:ValidationAssist.UsePopup="True"
                 materialDesign:ValidationAssist.OnlyShowOnFocus="True"
                 HorizontalAlignment="Left"
                 ToolTip="Use a popup which can escape the bounds of the control where space is limited">
            <TextBox.Text>
                <Binding Path="Name"
                         UpdateSourceTrigger="PropertyChanged">
                    <Binding.ValidationRules>
                        <helpers:NotEmptyValidationRule ValidatesOnTargetUpdated="True" />
                    </Binding.ValidationRules>
                </Binding>
            </TextBox.Text>
        </TextBox>

Body:
This Validation TextBox uses data binding behind the scenes to work. The code is correct but you might be missing the data binding on the Name.

    <Binding Path="Name" UpdateSourceTrigger="PropertyChanged">

For this, to work you need to data bind the path to the Name property.

This can be done in two steps.

Create/reuse a property Name in the desired class.

Assign the data context of the XAML page to the desired class.

Sample (desired class is shown as MainWindow here)

Step 1, file: MainWindow.xaml.cs

    private string _name;

    public string Name
    {
        get { return _name; }
        set { _name = value; }
    }

Step 2, file: MainWindow.xaml.cs

    public MainWindow()
    {
        InitializeComponent();
        this.DataContext = this;
        ...
    }

And then the problem should be solved.


问:
React-Native: cannot update a component while rendering a different component
I've got this simple component Login:

```<code>function Login() {
  const [isFormValidState, setIsFormValidState] = React.useState(false);
  const [credentialState, setCredentialState] = React.useState();

  function getFormErrors(errors: any, dirty: boolean) {
    setIsFormValidState(!Object.keys(errors).length && dirty);
  }

  function getFormValues(values: any) {
    setCredentialState(values);
  }

  function doAction() {
    //credentialState rest call...
  }

  return (
    <View>
      <Text>Login</Text>
      <UserCredentialForm getFormValues={getFormValues} getFormErrors={getFormErrors}/>
      <Button title='Entra' disabled={!isFormValidState} onPress={doAction}/>
    </View>
  );
}
</code>```

Which calls UserCredentialForm:

```<code>export default function UserCredentialForm({ getFormValues, getFormErrors }) {
[...]
  return (
    <Formik innerRef={formRef} validationSchema={formSchema} initialValues={state.form} onSubmit={() => { }}>
      {({ handleChange, values, touched, errors, dirty }) => {
        getFormValues(values);
        getFormErrors(errors, dirty);
        return <React.Fragment>
          // <TextInput/>....
        </React.Fragment>
      }}
    </Formik>
  );

[...]
}
</code>```

While navigating in my app I've got this error:

react native cannot update a component Login while rendering a
different component Formik.

Then it points me to the error in the setCredentialState inside getFormValues handler in Login component.
I've resolved this using a ref instead of a state, but the problem itself is unsolved to me.

What if I need to update my parent component view after a child event?

答:
The reason for that error is because you call setState inside render(). The call getFormValues(values), which set the state of credentialState is called inside the render.

When the state is set, the Login component get rerendered, thus recreating a new function of getFormValues. As this is used as the prop of UserCredentialForm, it also causes that component to rerender, which causes the render prop inside Formik to calls again, which calls getFormValues causing the state change, causing an infinite loop.

One solution you can try is to add useCallback to the two functions, which prevent them to have new identities after the state changes and consequently change the props, thus creating infinite rerender.

function Login() {
  const [isFormValidState, setIsFormValidState] = React.useState(false);
  const [credentialState, setCredentialState] = React.useState();

  const getFormErrors = useCallback(function getFormErrors(errors: any, dirty: boolean) {
    setIsFormValidState(!Object.keys(errors).length && dirty);
  }, []);

  const getFormValues = useCallback(function getFormValues(values: any) {
    setCredentialState(values);
  }, []);

  function doAction() {
    //credentialState rest call...
  }

  return (
    <View>
      <Text>Login</Text>
      <UserCredentialForm getFormValues={getFormValues} getFormErrors={getFormErrors}/>
      <Button title='Entra' disabled={!isFormValidState} onPress={doAction}/>
    </View>
  );
}
```
<p>However, there is still an issue and that is the identity of <code>values</code> may not be stable and by setting it to state, it will keep causing rerender. What you want to do is to tell <code>UserCredentialForm</code> not to rerender even when that state changes, and since the state is not used as a prop in <code>UserCredentialForm</code>, you can do that with React.memo.</p>
<pre class="lang-js prettyprint-override"><code>
export default React.memo(function UserCredentialForm({ getFormValues, getFormErrors }) {
[...]
  return (
    <Formik innerRef={formRef} validationSchema={formSchema} initialValues={state.form} onSubmit={() => { }}>
      {({ handleChange, values, touched, errors, dirty }) => {
        getFormValues(values);
        getFormErrors(errors, dirty);
        return <React.Fragment>
          // <TextInput/>....
        </React.Fragment>
      }}
    </Formik>
  );

[...]
})
</code>```

Body:
I've got this simple component Login:

function Login() {
  const [isFormValidState, setIsFormValidState] = React.useState(false);
  const [credentialState, setCredentialState] = React.useState();

  function getFormErrors(errors: any, dirty: boolean) {
    setIsFormValidState(!Object.keys(errors).length && dirty);
  }

  function getFormValues(values: any) {
    setCredentialState(values);
  }

  function doAction() {
    //credentialState rest call...
  }

  return (
    <View>
      <Text>Login</Text>
      <UserCredentialForm getFormValues={getFormValues} getFormErrors={getFormErrors}/>
      <Button title='Entra' disabled={!isFormValidState} onPress={doAction}/>
    </View>
  );
}

Which calls UserCredentialForm:

export default function UserCredentialForm({ getFormValues, getFormErrors }) {
[...]
  return (
    <Formik innerRef={formRef} validationSchema={formSchema} initialValues={state.form} onSubmit={() => { }}>
      {({ handleChange, values, touched, errors, dirty }) => {
        getFormValues(values);
        getFormErrors(errors, dirty);
        return <React.Fragment>
          // <TextInput/>....
        </React.Fragment>
      }}
    </Formik>
  );

[...]
}

While navigating in my app I've got this error:

react native cannot update a component Login while rendering a
different component Formik.

Then it points me to the error in the setCredentialState inside getFormValues handler in Login component.
I've resolved this using a ref instead of a state, but the problem itself is unsolved to me.

What if I need to update my parent component view after a child event?

Body:
The reason for that error is because you call setState inside render(). The call getFormValues(values), which set the state of credentialState is called inside the render.

When the state is set, the Login component get rerendered, thus recreating a new function of getFormValues. As this is used as the prop of UserCredentialForm, it also causes that component to rerender, which causes the render prop inside Formik to calls again, which calls getFormValues causing the state change, causing an infinite loop.

One solution you can try is to add useCallback to the two functions, which prevent them to have new identities after the state changes and consequently change the props, thus creating infinite rerender.

function Login() {
  const [isFormValidState, setIsFormValidState] = React.useState(false);
  const [credentialState, setCredentialState] = React.useState();

  const getFormErrors = useCallback(function getFormErrors(errors: any, dirty: boolean) {
    setIsFormValidState(!Object.keys(errors).length && dirty);
  }, []);

  const getFormValues = useCallback(function getFormValues(values: any) {
    setCredentialState(values);
  }, []);

  function doAction() {
    //credentialState rest call...
  }

  return (
    <View>
      <Text>Login</Text>
      <UserCredentialForm getFormValues={getFormValues} getFormErrors={getFormErrors}/>
      <Button title='Entra' disabled={!isFormValidState} onPress={doAction}/>
    </View>
  );
}

However, there is still an issue and that is the identity of values may not be stable and by setting it to state, it will keep causing rerender. What you want to do is to tell UserCredentialForm not to rerender even when that state changes, and since the state is not used as a prop in UserCredentialForm, you can do that with React.memo.

export default React.memo(function UserCredentialForm({ getFormValues, getFormErrors }) {
[...]
  return (
    <Formik innerRef={formRef} validationSchema={formSchema} initialValues={state.form} onSubmit={() => { }}>
      {({ handleChange, values, touched, errors, dirty }) => {
        getFormValues(values);
        getFormErrors(errors, dirty);
        return <React.Fragment>
          // <TextInput/>....
        </React.Fragment>
      }}
    </Formik>
  );

[...]
})


问:
Long press to select an option from a dropdown menu
I have to do a long press to select an option from a dropdown menu. I want the selection to be immediate.  How can I solve this problem.

```<code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var cell = UITableViewCell()

        cell = countryTableView.dequeueReusableCell(withIdentifier: "countryCell", for: indexPath)
        cell.textLabel?.text = country[indexPath.row]

        return cell
}
</code>```

答:
Have you tried implementing the UITableViewDelegate function?

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)

Body:
I have to do a long press to select an option from a dropdown menu. I want the selection to be immediate.  How can I solve this problem.

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var cell = UITableViewCell()

        cell = countryTableView.dequeueReusableCell(withIdentifier: "countryCell", for: indexPath)
        cell.textLabel?.text = country[indexPath.row]

        return cell
}


问:
Powerapps how to append data from form to an existing Excel File
I created the Powerapps form below. My goal is to have a user fill out this form, click Save, and have the data appended to an Excel file.

I connected the individual drop down boxes to a SQL database. The drop downs all work correctly and show the data that I want the user to choose from.

I don't understand how to take the data from this form and append the data to an existing Excel spreadsheet. I saw something that said I had to make a Collection out of it and I think that part worked. But the next step said to use the Patch function and I keep getting errors referencing the drop down values in the Patch statement.  It accepts the text fields, just not the drop downs.  Is there a better way to accomplish what I'm trying to do?  I am winging it with Powerapps and it's hard to find specific information on what I'm trying to do.

Thanks for any help.

```<code>Collect
( MyItems,
    {LocIdC: LocationId.SelectedText, CatIdC: CategoryIdSelected.SelectedText, SubCatIdC: SubCategoryId.SelectedText,
    ClientIdC: ClientId.SelectedText, EventIdC: EventId.Text, CharityIdC: CharityId.SelectedText,
    DateSelectedC: DateSelected.SelectedDate, WeightC: WeightTons.Text, UnitsC: Units.Text, DollarsC: Dollars.Text } );
</code>```

ClearCollect(myCSV, {csvString:"LocIdC,CatIdC,SubCatIdC,ClientIdC,EventIdC,CharityIdC,DateSelectedC,WeightC,UnitsC,DollarsC"&Char(10)});

ForAll(
MyItems,
Patch(
myCSV,
First(myCSV),
{csvString: First(myCSV).csvString&LocIdC&","&CatIdC&","&SubCatIdC&","&ClientIdC&","&EventIdC&","&CharityIdC&","&DateSelectedC&","&WeightC&","&UnitsC&","&DollarsC&Char(10)})
);

答: Instead of .selectedText, try .Selected.Value</p>

Body:
I created the Powerapps form below. My goal is to have a user fill out this form, click Save, and have the data appended to an Excel file.

I connected the individual drop down boxes to a SQL database. The drop downs all work correctly and show the data that I want the user to choose from.

I don't understand how to take the data from this form and append the data to an existing Excel spreadsheet. I saw something that said I had to make a Collection out of it and I think that part worked. But the next step said to use the Patch function and I keep getting errors referencing the drop down values in the Patch statement.  It accepts the text fields, just not the drop downs.  Is there a better way to accomplish what I'm trying to do?  I am winging it with Powerapps and it's hard to find specific information on what I'm trying to do.

Thanks for any help.

Collect
( MyItems,
    {LocIdC: LocationId.SelectedText, CatIdC: CategoryIdSelected.SelectedText, SubCatIdC: SubCategoryId.SelectedText,
    ClientIdC: ClientId.SelectedText, EventIdC: EventId.Text, CharityIdC: CharityId.SelectedText,
    DateSelectedC: DateSelected.SelectedDate, WeightC: WeightTons.Text, UnitsC: Units.Text, DollarsC: Dollars.Text } );

ClearCollect(myCSV, {csvString:"LocIdC,CatIdC,SubCatIdC,ClientIdC,EventIdC,CharityIdC,DateSelectedC,WeightC,UnitsC,DollarsC"&Char(10)});

ForAll(
MyItems,
Patch(
myCSV,
First(myCSV),
{csvString: First(myCSV).csvString&LocIdC&","&CatIdC&","&SubCatIdC&","&ClientIdC&","&EventIdC&","&CharityIdC&","&DateSelectedC&","&WeightC&","&UnitsC&","&DollarsC&Char(10)})
);


问:
How to make non-blocking javascript code?
How can I make a simple, non-block Javascript function call?  For example:

```<code>  //begin the program
  console.log('begin');
  nonBlockingIncrement(10000000);
  console.log('do more stuff');

  //define the slow function; this would normally be a server call
  function nonBlockingIncrement(n){
    var i=0;
    while(i<n){
      i++;
    }
    console.log('0 incremented to '+i);
  }
</code>```

outputs

```<code>"beginPage"
"0 incremented to 10000000"
"do more stuff"
</code>```

How can I form this simple loop to execute asynchronously and output the results via a callback function?  The idea is to not block "do more stuff":

```<code>"beginPage"
"do more stuff"
"0 incremented to 10000000"
</code>```

I've tried following tutorials on callbacks and continuations, but they all seem to rely on external libraries or functions. None of them answer the question in a vacuum: how does one write Javascript code to be non-blocking!?

I have searched very hard for this answer before asking; please don't assume I didn't look.  Everything I found is Node.js specific ([1], [2], [3], [4], [5]) or otherwise specific to other functions or libraries ([6], [7], [8], [9], [10], [11]), notably JQuery and setTimeout().  Please help me write non-blocking code using Javascript, not Javascript-written tools like JQuery and Node.  Kindly reread the question before marking it as duplicate.

答:
Using ECMA async function it's very easy to write non-blocking async code, even if it performs CPU-bound operations. Let's do this on a typical academic task - Fibonacci calculation for the incredible huge value.
All you need is to insert an operation that allows the event loop to be reached from time to time. Using this approach, you will never freeze the user interface or I/O.

Basic implementation:

const fibAsync = async (n) => {
  let lastTimeCalled = Date.now();

  let a = 1n,
    b = 1n,
    sum,
    i = n - 2;
  while (i-- > 0) {
    sum = a + b;
    a = b;
    b = sum;
    if (Date.now() - lastTimeCalled > 15) { // Do we need to poll the eventloop?
      lastTimeCalled = Date.now();
      await new Promise((resolve) => setTimeout(resolve, 0)); // do that
    }
  }
  return b;
};
```
<p>And now we can use it (Live Demo):</p>
<pre class="lang-js prettyprint-override"><code>let ticks = 0;

console.warn("Calulation started");

fibAsync(100000)
  .then((v) => console.log(`Ticks: ${ticks}\nResult: ${v}`), console.warn)
  .finally(() => {
    clearTimeout(timer);
  });

const timer = setInterval(
  () => console.log("timer tick - eventloop is not freezed", ticks++),
  0
);
</code>```

As we can see, the timer is running normally, which indicates the event loop is not blocking.

I published an improved implementation of these helpers as antifreeze2 npm package. It uses setImmediate internally, so to get the maximum performance you need to import setImmediate polyfill for environments without native support.

Live Demo

import { antifreeze, isNeeded } from "antifreeze2";

const fibAsync = async (n) => {
  let a = 1n,
    b = 1n,
    sum,
    i = n - 2;
  while (i-- > 0) {
    sum = a + b;
    a = b;
    b = sum;
    if (isNeeded()) {
      await antifreeze();
    }
  }
  return b;
};
```

Body:
How can I make a simple, non-block Javascript function call?  For example:

  //begin the program
  console.log('begin');
  nonBlockingIncrement(10000000);
  console.log('do more stuff');

  //define the slow function; this would normally be a server call
  function nonBlockingIncrement(n){
    var i=0;
    while(i<n){
      i++;
    }
    console.log('0 incremented to '+i);
  }

outputs

"beginPage"
"0 incremented to 10000000"
"do more stuff"

How can I form this simple loop to execute asynchronously and output the results via a callback function?  The idea is to not block "do more stuff":

"beginPage"
"do more stuff"
"0 incremented to 10000000"

I've tried following tutorials on callbacks and continuations, but they all seem to rely on external libraries or functions. None of them answer the question in a vacuum: how does one write Javascript code to be non-blocking!?

I have searched very hard for this answer before asking; please don't assume I didn't look.  Everything I found is Node.js specific ([1], [2], [3], [4], [5]) or otherwise specific to other functions or libraries ([6], [7], [8], [9], [10], [11]), notably JQuery and setTimeout().  Please help me write non-blocking code using Javascript, not Javascript-written tools like JQuery and Node.  Kindly reread the question before marking it as duplicate.

Body:
Using ECMA async function it's very easy to write non-blocking async code, even if it performs CPU-bound operations. Let's do this on a typical academic task - Fibonacci calculation for the incredible huge value.
All you need is to insert an operation that allows the event loop to be reached from time to time. Using this approach, you will never freeze the user interface or I/O.

Basic implementation:

const fibAsync = async (n) => {
  let lastTimeCalled = Date.now();

  let a = 1n,
    b = 1n,
    sum,
    i = n - 2;
  while (i-- > 0) {
    sum = a + b;
    a = b;
    b = sum;
    if (Date.now() - lastTimeCalled > 15) { // Do we need to poll the eventloop?
      lastTimeCalled = Date.now();
      await new Promise((resolve) => setTimeout(resolve, 0)); // do that
    }
  }
  return b;
};

And now we can use it (Live Demo):

let ticks = 0;

console.warn("Calulation started");

fibAsync(100000)
  .then((v) => console.log(`Ticks: ${ticks}\nResult: ${v}`), console.warn)
  .finally(() => {
    clearTimeout(timer);
  });

const timer = setInterval(
  () => console.log("timer tick - eventloop is not freezed", ticks++),
  0
);

As we can see, the timer is running normally, which indicates the event loop is not blocking.

I published an improved implementation of these helpers as antifreeze2 npm package. It uses setImmediate internally, so to get the maximum performance you need to import setImmediate polyfill for environments without native support.

Live Demo

import { antifreeze, isNeeded } from "antifreeze2";

const fibAsync = async (n) => {
  let a = 1n,
    b = 1n,
    sum,
    i = n - 2;
  while (i-- > 0) {
    sum = a + b;
    a = b;
    b = sum;
    if (isNeeded()) {
      await antifreeze();
    }
  }
  return b;
};


问:
Is this possible in SQL? Min and Max Dates On a Total. Where it changes in between Dates
I am trying to figure out how to write a query that will give me the correct historical data between dates. But only using sql. I know it is possible coding a loop, but I'm not sure if this is possible in a SQL query. Dates: DD/MM/YYYY

An Example of Data

ID
Points
DATE

1
10
01/01/2018

1
20
02/01/2019

1
25
03/01/2020

1
10
04/01/2021

With a simple query

```<code>SELECT ID, Points, MIN(Date), MAX(Date)
FROM table
GROUP BY ID,POINTS
</code>```

The Min date for 10 points would be 01/01/2018, and the Max Date would be 04/01/2021. Which would be wrong in this instance. As It should be:

ID
Points
Min DATE
Max DATE

1
10
01/01/2018
01/01/2019

1
20
02/01/2019
02/01/2020

1
25
03/01/2020
03/01/2021

1
10
04/01/2021
04/01/2021

I was thinking of using LAG, but need some ideas here. What I haven't told you is there is a record per day. So I would need to group until a change of points. This is to create a view from the data that I already have.

答:
I'm guessing you want the MAX date to be 1 day before the next MIN date.

And you can use the window function LEAD to get the next MIN date.

And if you group also by the year, then the date ranges match the expected result.

```<code>SELECT ID, Points
, MIN([Date]) AS [Min Date]
, COALESCE(DATEADD(day, -1, LEAD(MIN([Date])) OVER (PARTITION BY ID ORDER BY MIN([Date]))), MAX([Date])) AS [Max Date]
FROM your_table
GROUP BY ID, Points, YEAR([Date]);
</code>```

ID
Points
Min Date
Max Date

1
10
2018-01-01
2019-01-01

1
20
2019-01-02
2020-01-02

1
25
2020-01-03
2021-01-03

1
10
2021-01-04
2021-01-04

Test on db<>fiddle here

Body:
I am trying to figure out how to write a query that will give me the correct historical data between dates. But only using sql. I know it is possible coding a loop, but I'm not sure if this is possible in a SQL query. Dates: DD/MM/YYYY

An Example of Data

ID
Points
DATE

1
10
01/01/2018

1
20
02/01/2019

1
25
03/01/2020

1
10
04/01/2021

With a simple query

SELECT ID, Points, MIN(Date), MAX(Date)
FROM table
GROUP BY ID,POINTS

The Min date for 10 points would be 01/01/2018, and the Max Date would be 04/01/2021. Which would be wrong in this instance. As It should be:

ID
Points
Min DATE
Max DATE

1
10
01/01/2018
01/01/2019

1
20
02/01/2019
02/01/2020

1
25
03/01/2020
03/01/2021

1
10
04/01/2021
04/01/2021

I was thinking of using LAG, but need some ideas here. What I haven't told you is there is a record per day. So I would need to group until a change of points. This is to create a view from the data that I already have.

Body:
I'm guessing you want the MAX date to be 1 day before the next MIN date.

And you can use the window function LEAD to get the next MIN date.

And if you group also by the year, then the date ranges match the expected result.

SELECT ID, Points
, MIN([Date]) AS [Min Date]
, COALESCE(DATEADD(day, -1, LEAD(MIN([Date])) OVER (PARTITION BY ID ORDER BY MIN([Date]))), MAX([Date])) AS [Max Date]
FROM your_table
GROUP BY ID, Points, YEAR([Date]);

ID
Points
Min Date
Max Date

1
10
2018-01-01
2019-01-01

1
20
2019-01-02
2020-01-02

1
25
2020-01-03
2021-01-03

1
10
2021-01-04
2021-01-04

Test on db<>fiddle here


问:
Is it possible to use jpackage to ship a javascript frontend java backend
From looking through the documentation for jpackage it doesn't seem there is any examples of how to use jpackage to bundle a javascript front end with a java backend. Is this possible?

答:
The job of jpackage is to take a Java application, bundle it with a Java Runtime, and create a native package / installer from it - NOT "to bundle a javascript front end with a java backend". So the answer to this question would be "no".

There ARE, however, ways to package a JavaScript frontend into a (Spring Boot) Java application, like this one. As you can run this "java backend and javascript frontend" app with java -jar acme-example-app/target/*.jar, you should also be able to package it with jpackage.


问:
How do I disconnect a subrscribed stream from the publisher of the netstream?
I have a publisher who publishes a netstream using stratus p2p. This is then connected to by player who subscribes to the netstream.

I believe one can reject the subscriber when the stream tries to connect by using the onPeerConnect method of the netstream's client. However, I would like to boot the subscriber after they have been connected.

There are potentially other subscribers to that netstream so I cannot just close it. How would I boot a particular subscriber without closing the published netstream?

答: The peerStreams property of your publishing NetStream is an array of NetStraems of all subscribers. You can iterate through it and do something like netStream.peerStreams[0].close();

ContentLicense: CC BY-SA 2.5


问:
OpenCV check if filled
I need your help because of my lack of programming or mathematics. Probably both.

I wrote code that checks if a specific area in a picture is complete green. This works pretty fine. Problem it just works if my area is an rectangle which is straight to the outerlines of the picture. Now it should also work if the rectangle looks like a trapeze. For this i have four points with x and y coordinates. My current code works only with two points (top left and bottom right) for the new code i have four points (point1, point2,...).

Every of this points looks like this: point1 = (250,250)

Current Code is:

```<code>    for j in range(point1[1], point2[1], 15):
        for i in range(point1[0], point2[0], 15):
            if overlay[j, i][1] != 255:
                diskretisierungs_trigger = False
                break
</code>```

Maybe you know some ideas how i can check every pixel in an specific area.

Thank you very much <3

答:
@MarkSetchell had a good idea. Here is how i get it done:

Generated a new image (black_image). Added my polygon in white. The rectangles now fill the black image with black and also the few white spots from the polygon after every picture i count the numbers of nonzero:

```<code>        pts = np.asarray(circles)
        cv2.polylines(image_new, [pts], True, red_color)
        array_size = np.shape(image_new)
        black_image = np.zeros((array_size), dtype="uint8")
        cv2.fillPoly(black_image, [pts], color=white_color)
        for c1, c2 in rectangles:
            cv2.rectangle(black_image, c1, c2, black_color, -1)
        erfüllungsgrade.append(np.count_nonzero(black_image))
</code>```

Title: OpenCV check if filled

Body:
I need your help because of my lack of programming or mathematics. Probably both.

I wrote code that checks if a specific area in a picture is complete green. This works pretty fine. Problem it just works if my area is an rectangle which is straight to the outerlines of the picture. Now it should also work if the rectangle looks like a trapeze. For this i have four points with x and y coordinates. My current code works only with two points (top left and bottom right) for the new code i have four points (point1, point2,...).

Every of this points looks like this: point1 = (250,250)

Current Code is:

    for j in range(point1[1], point2[1], 15):
        for i in range(point1[0], point2[0], 15):
            if overlay[j, i][1] != 255:
                diskretisierungs_trigger = False
                break

Maybe you know some ideas how i can check every pixel in an specific area.

Thank you very much <3

Body:
@MarkSetchell had a good idea. Here is how i get it done:

Generated a new image (black_image). Added my polygon in white. The rectangles now fill the black image with black and also the few white spots from the polygon after every picture i count the numbers of nonzero:

        pts = np.asarray(circles)
        cv2.polylines(image_new, [pts], True, red_color)
        array_size = np.shape(image_new)
        black_image = np.zeros((array_size), dtype="uint8")
        cv2.fillPoly(black_image, [pts], color=white_color)
        for c1, c2 in rectangles:
            cv2.rectangle(black_image, c1, c2, black_color, -1)
        erfüllungsgrade.append(np.count_nonzero(black_image))


问:
Which path for the Modelsim environment variable
in order to run and use all modelsim commands like vcom, vsim etc. which enivronment variables are set in a windows system when NOT using the GUI to run those commands?</p>

答: You need to put the binary path into PATH or call all commands with absolute paths.


问:
jQuery changes select value but doesn't trigger page refresh
I created radio buttons on mobile that need to trigger the hidden select option in order for the page to refresh. I have this code and it does change the select value on radio button click, but it doesn't refresh the page. When I click on it with my mouse the page refreshes with the selected option, but not when I do it just with jQuery. What can I do about it?

Radio buttons:

```<code><div class="m-box">
<input type="radio" class="sort-radio" name="r" value="featured">
<label>Featured Items</label>
<input type="radio" class="sort-radio" name="r" value="newest">
<label>Newest Items</label>
<input type="radio" class="sort-radio" name="r" value="bestselling"><label>Best
Selling</label>
</div>
</code>```

Select:

```<code><select class="form-select form-select--small " name="sort" id="sort" role="listbox">
    <option value="featured" selected="">Featured Items</option>
    <option value="newest">Newest Items</option>
    <option value="bestselling">Best Selling</option>
</select>
</code>```

Code:

```<code>$(".sort-radio").change(function () {
$("#sort")
        .val($(this).val())
        .trigger('change');
});
</code>```

I tried trigger('change') and change()...it does change the select option value, but how can I "fake" a mouse click in order for the whole page to refresh?

答:
$(".sort-radio").change(function() {

```<code>$("#sort").val($(this).val()).trigger('click');
</code>```

});

Body:
I created radio buttons on mobile that need to trigger the hidden select option in order for the page to refresh. I have this code and it does change the select value on radio button click, but it doesn't refresh the page. When I click on it with my mouse the page refreshes with the selected option, but not when I do it just with jQuery. What can I do about it?

Radio buttons:

<input type="radio" class="sort-radio" name="r" value="featured">
Featured Items
<input type="radio" class="sort-radio" name="r" value="newest">
Newest Items
<input type="radio" class="sort-radio" name="r" value="bestselling">Best
Selling

Select:

<select class="form-select form-select--small " name="sort" id="sort" role="listbox">
    <option value="featured" selected="">Featured Items</option>
    <option value="newest">Newest Items</option>
    <option value="bestselling">Best Selling</option>
</select>

Code:

$(".sort-radio").change(function () {
$("#sort")
        .val($(this).val())
        .trigger('change');
});

I tried trigger('change') and change()...it does change the select option value, but how can I "fake" a mouse click in order for the whole page to refresh?

Body:
$(".sort-radio").change(function() {

$("#sort").val($(this).val()).trigger('click');

});


问:
How to add rails relationship after the fact?
I've already created my models and have gone through several migrations.  Now, I want to setup has_many :books in Subject and belongs_to :subject in Book.  I've added those to the .rb files, but I'm still allowed to save a book with a subject_id that does not exist.  I'm expecting a FK constraint violation.

Must I create a migration file for this?  If so, how do I do it?

答:
you can generate a lone migration file (without a model) by using script/generate migration, or rails g migration for rails 2 / 3 respectively. You can then include the constraints to the self.up method in the migration file and run them on the database using a rake db:migrate.

Note however that unless you're planning on handling the error using your own custom code to catch ActiveRecord errors you're probably better off using rails validations to ensure that associations are present. i.e.

app/models/book.rb

```<code>validates_presence_of :subject
</code>```

EDIT: If you want to add foreign keys to your database then you will have to know how to do this using the command set relevant to your database engine (e.g. for MySQL http://dev.mysql.com/doc/refman/5.1/en/innodb-foreign-key-constraints.html). Since rails is designed to work with databases that don't support foreign keys there are no built in functions in the rails migration toolkit which can help you with this process.

as a rough outline of what you'll need in your migration (using MySQL specific syntax):

```<code>def self.up
  execute "ALTER TABLE books FOREIGN KEY `my_foreign_key_name` (subject_id) REFERENCES subjects (id)"
end

def self.down
  execute "ALTER TABLE books DROP FOREIGN KEY `my_foreign_key_name`"
end
</code>```

Body:
you can generate a lone migration file (without a model) by using script/generate migration, or rails g migration for rails 2 / 3 respectively. You can then include the constraints to the self.up method in the migration file and run them on the database using a rake db:migrate.

Note however that unless you're planning on handling the error using your own custom code to catch ActiveRecord errors you're probably better off using rails validations to ensure that associations are present. i.e.

app/models/book.rb

validates_presence_of :subject

EDIT: If you want to add foreign keys to your database then you will have to know how to do this using the command set relevant to your database engine (e.g. for MySQL http://dev.mysql.com/doc/refman/5.1/en/innodb-foreign-key-constraints.html). Since rails is designed to work with databases that don't support foreign keys there are no built in functions in the rails migration toolkit which can help you with this process.

as a rough outline of what you'll need in your migration (using MySQL specific syntax):

def self.up
  execute "ALTER TABLE books FOREIGN KEY `my_foreign_key_name` (subject_id) REFERENCES subjects (id)"
end

def self.down
  execute "ALTER TABLE books DROP FOREIGN KEY `my_foreign_key_name`"
end


问:
Create Array of same Size
I have an array

```<code>a = zeros(2,3)

2×3 Matrix{Float64}:
 0.0  0.0  0.0
 0.0  0.0  0.0
</code>```

and I want to create a Bool array of same size with all values set to false.

答:
You can combine similar and fill! to achieve what you want.

```<code>julia> a = zeros(2,3)
2×3 Matrix{Float64}:
 0.0  0.0  0.0
 0.0  0.0  0.0

julia> fill!(similar(a, Bool), false)
2×3 Matrix{Bool}:
 0  0  0
 0  0  0
</code>```

Title: Create Array of same Size

Body:
I have an array

a = zeros(2,3)

2×3 Matrix{Float64}:
 0.0  0.0  0.0
 0.0  0.0  0.0

and I want to create a Bool array of same size with all values set to false.

Body:
You can combine similar and fill! to achieve what you want.

julia> a = zeros(2,3)
2×3 Matrix{Float64}:
 0.0  0.0  0.0
 0.0  0.0  0.0

julia> fill!(similar(a, Bool), false)
2×3 Matrix{Bool}:
 0  0  0
 0  0  0


问:
Common Lisp structures with dynamically scoped slots
Common Lisp is lexically scoped, but there is a possibility to create dynamic bindings with (declare (special *var*)). What I need, is a way to create a dynamically scoped structure slot, whose value is visible to all other slots. Here is an example:

```<code>(defun start-thread ()
  *delay*) ;; We defer the binding of *delay*
</code>```

This works for a usual lexical environment:

```<code>(let ((*delay* 1))
  (declare (special *delay*))
  (start-thread)) ;; returns 1
</code>```

This does not work:

```<code>(defstruct table
  (*delay* 0)
  (thread (start-thread)))

(make-table) ;; => Error: *delay* is unbound.
</code>```

My questions are

How to refer to the slot delay from other slots?

How to make the slot delay dynamically scoped, so that its value becomes visible
for the function (start-thread) ?

答:
The first thing to realise that there's no good way to have a dynamically-scoped slot in an object (unless the implementation has some deep magic to support this): the only approach that will work is to use, essentially, explicit shallow-binding.  Something like this macro, for instance (this has no error checking at all: I just typed it in):

```<code>(defmacro with-horrible-shallow-bound-slots ((&rest slotds) object &body forms)
  (let ((ovar (make-symbol "OBJECT"))
        (slot-vars (mapcar (lambda (slotd)
                             (make-symbol (symbol-name (first slotd))))
                           slotds)))
    `(let ((,ovar ,object))
       (let ,(mapcar (lambda (v slotd)
                       `(,v (,(first slotd) ,ovar)))
                     slot-vars slotds)
         (unwind-protect
             (progn
               (setf ,@(mapcan (lambda (slotd)
                                 `((,(first slotd) ,ovar) ,(second slotd)))
                               slotds))
               ,@forms)
           (setf ,@(mapcan (lambda (slotd slot-var)
                                 `((,(first slotd) ,ovar) ,slot-var))
                           slotds slot-vars)))))))
</code>```

And now if we have some structure:

```<code>(defstruct foo
  (x 0))
</code>```

Then

```<code>(with-horrible-shallow-bound-slots ((foo-x 1)) foo
  (print (foo-x foo)))
</code>```

expands to

```<code>(let ((#:object foo))
  (let ((#:foo-x (foo-x #:object)))
    (unwind-protect
        (progn (setf (foo-x #:object) 1) (print (foo-x foo)))
      (setf (foo-x #:object) #:foo-x))))
</code>```

where all the gensyms with the same name are in fact the same.  And so:

```<code>> (let ((foo (make-foo)))
    (with-horrible-shallow-bound-slots ((foo-x 1)) foo
      (print (foo-x foo)))
    (print (foo-x foo))
    (values))
1
0
</code>```

But this is a terrible approach because shallow binding is terrible in the presence of multiple threads: any other thread that wants to look at foo's slots will also see the temporary value.  So this is just horrid.

A good approach is then to realise that while you can't safely dynamically-bind a slot in an object, you can dynamically bind a value which that slot indexes by using a secret special variable to hold a  stack of bindings.  In this approach the values of slots do not change, but the values they index do, and can do so safely in the presence of multiple threads.

A way of doing this this is Tim Bradshaw's fluids toy.  The way this works is that you define the value of a slot to be a fluid, and then you can bind that fluid's value, which binding has dynamic scope.

```<code>(defstruct foo
  (slot (make-fluid)))

(defun outer (v)
  (let ((it (make-foo)))
    (setf (fluid-value (foo-slot it) t) v) ;set global value
    (values (fluid-let (((foo-slot it) (1+ (fluid-value (foo-slot it)))))
              (inner it))
            (fluid-value (foo-slot it)))))

(defun inner (thing)
  (fluid-value (foo-slot thing)))
</code>```

This often works better with CLOS objects because of the additional flexibility in things like naming and what you expose (you almost never want to be able to assign to a slot whose value is a fluid, for instance: you want to assign the value of the fluid).

The system uses a special variable behind the scenes to implement deep binding for fluids, so will work properly with threads (ie distinct threads can have different bindings for a fluid) assuming the implementation treats special variables sensibly (which I'm sure all multithreaded implementations do).

Body:
Common Lisp is lexically scoped, but there is a possibility to create dynamic bindings with (declare (special *var*)). What I need, is a way to create a dynamically scoped structure slot, whose value is visible to all other slots. Here is an example:

(defun start-thread ()
  *delay*) ;; We defer the binding of *delay*

This works for a usual lexical environment:

(let ((*delay* 1))
  (declare (special *delay*))
  (start-thread)) ;; returns 1

This does not work:

(defstruct table
  (*delay* 0)
  (thread (start-thread)))

(make-table) ;; => Error: *delay* is unbound.

My questions are

How to refer to the slot delay from other slots?

How to make the slot delay dynamically scoped, so that its value becomes visible
for the function (start-thread) ?

Body:
The first thing to realise that there's no good way to have a dynamically-scoped slot in an object (unless the implementation has some deep magic to support this): the only approach that will work is to use, essentially, explicit shallow-binding.  Something like this macro, for instance (this has no error checking at all: I just typed it in):

(defmacro with-horrible-shallow-bound-slots ((&rest slotds) object &body forms)
  (let ((ovar (make-symbol "OBJECT"))
        (slot-vars (mapcar (lambda (slotd)
                             (make-symbol (symbol-name (first slotd))))
                           slotds)))
    `(let ((,ovar ,object))
       (let ,(mapcar (lambda (v slotd)
                       `(,v (,(first slotd) ,ovar)))
                     slot-vars slotds)
         (unwind-protect
             (progn
               (setf ,@(mapcan (lambda (slotd)
                                 `((,(first slotd) ,ovar) ,(second slotd)))
                               slotds))
               ,@forms)
           (setf ,@(mapcan (lambda (slotd slot-var)
                                 `((,(first slotd) ,ovar) ,slot-var))
                           slotds slot-vars)))))))

And now if we have some structure:

(defstruct foo
  (x 0))

Then

(with-horrible-shallow-bound-slots ((foo-x 1)) foo
  (print (foo-x foo)))

expands to

(let ((#:object foo))
  (let ((#:foo-x (foo-x #:object)))
    (unwind-protect
        (progn (setf (foo-x #:object) 1) (print (foo-x foo)))
      (setf (foo-x #:object) #:foo-x))))

where all the gensyms with the same name are in fact the same.  And so:

> (let ((foo (make-foo)))
    (with-horrible-shallow-bound-slots ((foo-x 1)) foo
      (print (foo-x foo)))
    (print (foo-x foo))
    (values))
1
0

But this is a terrible approach because shallow binding is terrible in the presence of multiple threads: any other thread that wants to look at foo's slots will also see the temporary value.  So this is just horrid.

A good approach is then to realise that while you can't safely dynamically-bind a slot in an object, you can dynamically bind a value which that slot indexes by using a secret special variable to hold a  stack of bindings.  In this approach the values of slots do not change, but the values they index do, and can do so safely in the presence of multiple threads.

A way of doing this this is Tim Bradshaw's fluids toy.  The way this works is that you define the value of a slot to be a fluid, and then you can bind that fluid's value, which binding has dynamic scope.

(defstruct foo
  (slot (make-fluid)))

(defun outer (v)
  (let ((it (make-foo)))
    (setf (fluid-value (foo-slot it) t) v) ;set global value
    (values (fluid-let (((foo-slot it) (1+ (fluid-value (foo-slot it)))))
              (inner it))
            (fluid-value (foo-slot it)))))

(defun inner (thing)
  (fluid-value (foo-slot thing)))

This often works better with CLOS objects because of the additional flexibility in things like naming and what you expose (you almost never want to be able to assign to a slot whose value is a fluid, for instance: you want to assign the value of the fluid).

The system uses a special variable behind the scenes to implement deep binding for fluids, so will work properly with threads (ie distinct threads can have different bindings for a fluid) assuming the implementation treats special variables sensibly (which I'm sure all multithreaded implementations do).


问:
Make an array with every character on keyboard
I want to make an array containing all the letters and numbers on the keyboard (+ !, @, #, $, %, &, etc.) via code, without declaring it. Is there any way to do this in js?</p>

答:
I like 1 liners so

const characters = [...Array(95).keys()].map(i => String.fromCharCode(i+32))
```

Breakdown for those interested to know whats happening:

Array(95).keys() creates an iterator object with 95 items in it.

Because its wrapped in brackets []:

The spread syntax before it (...) iterates those objects into an array.

This results in a numbered array from 0 to 94. ie. [0,1,2,3,...,94]

Next you map the data from the array into the String.fromCharCode method.

Since we want only printable characters (starting from ascii code 32) we add 32 to each number in the source array before piping it into the fromCharCode method.

I've gotten really used to doing this for almost everything because its much faster than writing out a for loop for things. Granted it's slower than a for loop for performance (I think). Usually, I'm not writing code for performance.

Body:
I like 1 liners so

const characters = [...Array(95).keys()].map(i => String.fromCharCode(i+32))

Breakdown for those interested to know whats happening:

Array(95).keys() creates an iterator object with 95 items in it.

Because its wrapped in brackets []:

The spread syntax before it (...) iterates those objects into an array.

This results in a numbered array from 0 to 94. ie. [0,1,2,3,...,94]

Next you map the data from the array into the String.fromCharCode method.

Since we want only printable characters (starting from ascii code 32) we add 32 to each number in the source array before piping it into the fromCharCode method.

I've gotten really used to doing this for almost everything because its much faster than writing out a for loop for things. Granted it's slower than a for loop for performance (I think). Usually, I'm not writing code for performance.


问:
How can I send "audience" field in oauth2/token call made by Swagger-ui?
I am using Swagger-UI with Swashbuckle v5.6 to document an Auth0 (OAuth2) secured .NET Web API.
I've been trying to configure Swagger to obtain a token in the UI from Auth0 service. So far I've managed to do that, but the problem is that I need to send in the POST /token request's body the "audience" field, and I am struggling to find out how to do that from SwaggerConfig.cs.

So far my SwaggerConfig.cs looks like this :

```<code>public class SwaggerConfig
{
    public static void Register()
    {
        var thisAssembly = typeof(SwaggerConfig).Assembly;
        string appName = "myApi";
        var audience = System.Configuration.ConfigurationManager.AppSettings["AuthAudience"];
        string tokenUrl = "somethingsomething/oauth/token";

        GlobalConfiguration.Configuration
            .EnableSwagger(c =>
                {
                    c.SingleApiVersion("v1", "myApi");
                    c.IncludeXmlComments(string.Format(@"{0}\bin\myApi.XML", System.AppDomain.CurrentDomain.BaseDirectory));
                    c.DescribeAllEnumsAsStrings();

                    c.OAuth2("oauth2")
                        .Description("client credentials grant flow")
                        .Flow("password")
                        .TokenUrl(tokenUrl)
                        .Scopes(scopes =>
                        {
                            scopes.Add("myapi", "openid profile email address phone");
                        });

                    c.OperationFilter<AssignOperationFilters>();
                    c.DocumentFilter<SecurityRequirementsDocumentFilter>();
                })
            .EnableSwaggerUi(c =>
            {
                var clientId =  System.Configuration.ConfigurationManager.AppSettings["Auth0ApiClientId"];
                var clientSecret = System.Configuration.ConfigurationManager.AppSettings["Auth0ApiClientSecret"];

                var additionalParams = new Dictionary<string, string>{ {"audience", audience } };

                c.EnableOAuth2Support(clientId,
                                    clientSecret,
                                    appName,
                                    "tmdq",
                                    additionalQueryStringParams: additionalParams);

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

答:
Your can use OAuthAdditionalQueryStringParams...</p>
```<code>   app.UseSwaggerUI(options =>
            {
                options.OAuthClientId("YOUR_CLIENT_ID");
                options.SwaggerEndpoint("v1/swagger.json", "v1");
                options.OAuthAdditionalQueryStringParams(new Dictionary<string, string>() { {"audience","YOUR_AUDIENCE"}});
            });
</code>```

Body:
I am using Swagger-UI with Swashbuckle v5.6 to document an Auth0 (OAuth2) secured .NET Web API.
I've been trying to configure Swagger to obtain a token in the UI from Auth0 service. So far I've managed to do that, but the problem is that I need to send in the POST /token request's body the "audience" field, and I am struggling to find out how to do that from SwaggerConfig.cs.

So far my SwaggerConfig.cs looks like this :

public class SwaggerConfig
{
    public static void Register()
    {
        var thisAssembly = typeof(SwaggerConfig).Assembly;
        string appName = "myApi";
        var audience = System.Configuration.ConfigurationManager.AppSettings["AuthAudience"];
        string tokenUrl = "somethingsomething/oauth/token";

        GlobalConfiguration.Configuration
            .EnableSwagger(c =>
                {
                    c.SingleApiVersion("v1", "myApi");
                    c.IncludeXmlComments(string.Format(@"{0}\bin\myApi.XML", System.AppDomain.CurrentDomain.BaseDirectory));
                    c.DescribeAllEnumsAsStrings();

                    c.OAuth2("oauth2")
                        .Description("client credentials grant flow")
                        .Flow("password")
                        .TokenUrl(tokenUrl)
                        .Scopes(scopes =>
                        {
                            scopes.Add("myapi", "openid profile email address phone");
                        });

                    c.OperationFilter<AssignOperationFilters>();
                    c.DocumentFilter<SecurityRequirementsDocumentFilter>();
                })
            .EnableSwaggerUi(c =>
            {
                var clientId =  System.Configuration.ConfigurationManager.AppSettings["Auth0ApiClientId"];
                var clientSecret = System.Configuration.ConfigurationManager.AppSettings["Auth0ApiClientSecret"];

                var additionalParams = new Dictionary<string, string>{ {"audience", audience } };

                c.EnableOAuth2Support(clientId,
                                    clientSecret,
                                    appName,
                                    "tmdq",
                                    additionalQueryStringParams: additionalParams);

            });
    }
}

Body:
Your can use OAuthAdditionalQueryStringParams...

   app.UseSwaggerUI(options =>
            {
                options.OAuthClientId("YOUR_CLIENT_ID");
                options.SwaggerEndpoint("v1/swagger.json", "v1");
                options.OAuthAdditionalQueryStringParams(new Dictionary<string, string>() { {"audience","YOUR_AUDIENCE"}});
            });


问:
Should a function returned by a React Hook be wrapped in useCallback?
When you have a hook that returns a function should you wrap the function in useCallback to make sure a new reference is not created unnecessarily?

My thought process is if that function was used by another hook in a dependency array, the new function reference would cause the 2nd hook to trigger even when nothing changes.  Should a hook  only change it's output when it had a reason to change, or is it alright if a hook is noisy?

```<code>function useExample(someParam) {

  // ...

  const onChange = () => { /*some operation*/ }

  return { onChange }
}
</code>```
```<code>function Component(props) {

  const { onChange } = useExample(props)

  useEffect(() =>
    //Some action
  , [onChange])

  // ...

}
</code>```

答:
The useEffect hook, or rather, the react-hooks linting rule, can't possibly know the origin of the callback function returned from the other function other than that it sees only a function declared external to the useEffect hook.

The decision to memoize this callback is entirely up to you and the specific use case.

I'm assuming your actual use case isn't as trivial as an effect that only calls the callback, though, so there are probably other dependencies.

If the additional "noise" of the effect running each render cycle when callback is a new reference doesn't cause any undesirable then it is probably ok. Otherwise, yes, memoize the callback to provide a stable reference for the useEffect hook.

Body:
When you have a hook that returns a function should you wrap the function in useCallback to make sure a new reference is not created unnecessarily?

My thought process is if that function was used by another hook in a dependency array, the new function reference would cause the 2nd hook to trigger even when nothing changes.  Should a hook  only change it's output when it had a reason to change, or is it alright if a hook is noisy?

function useExample(someParam) {

  // ...

  const onChange = () => { /*some operation*/ }

  return { onChange }
}

function Component(props) {

  const { onChange } = useExample(props)

  useEffect(() =>
    //Some action
  , [onChange])

  // ...

}


问:
CEF - without rendering
Please explain to me how you can use CEF without rendering pages?

That is, it is necessary that the memory buffer for rendering is not allocated at all.

It seems to write that there is a method CefBrowserHost::Was Hidden - which hides the browser window and the window rendering does not occur.

I use this method:

```<code>void OnAfterCreated(CefRefPtr<CefBrowser>my_CefRefPtr) override
{
    CEF_REQUIRE_UI_THREAD();

    CefRefPtr<CefBrowserHost> CefBrowserHost_ = (*my_CefRefPtr).GetHost();

    (*CefBrowserHost_).WasHidden(true);   //hiding the window
}
</code>```

However, CEF fails:

[0211/221935.695:FATAL:alloy_browser_host_impl.cc(575)] Check failed:
false. Window rendering is not disabled

I don't understand what's wrong? Why the error ?

答:
The error is pretty clear. When you create a new cef browser, make it using off-screen rendering.</p>
```<code>windowInfo.SetAsWindowless(nullptr);
my_CefRefPtr = CefBrowserHost::CreateBrowser(windowInfo, /* whatever */);
</code>```

Title: CEF - without rendering

Body:
Please explain to me how you can use CEF without rendering pages?

That is, it is necessary that the memory buffer for rendering is not allocated at all.

It seems to write that there is a method CefBrowserHost::Was Hidden - which hides the browser window and the window rendering does not occur.

I use this method:

void OnAfterCreated(CefRefPtr<CefBrowser>my_CefRefPtr) override
{
    CEF_REQUIRE_UI_THREAD();

    CefRefPtr<CefBrowserHost> CefBrowserHost_ = (*my_CefRefPtr).GetHost();

    (*CefBrowserHost_).WasHidden(true);   //hiding the window
}

However, CEF fails:

[0211/221935.695:FATAL:alloy_browser_host_impl.cc(575)] Check failed:
false. Window rendering is not disabled

I don't understand what's wrong? Why the error ?

Body:
The error is pretty clear. When you create a new cef browser, make it using off-screen rendering.

windowInfo.SetAsWindowless(nullptr);
my_CefRefPtr = CefBrowserHost::CreateBrowser(windowInfo, /* whatever */);


问:
ModuleNotFound Error - Azure ML with prebuilt docker image
I have developed a module which works perfectly when executed locally.

I have created an environment on azure using a prebuilt docker image found here:
"azureml/minimal-ubuntu18.04-py37-cpu-inference" https://mcr.microsoft.com/v2/_catalog
. Also, Using pythonScriptStep, to run a pipeline. Here is how the step looks

```<code>StepPreprocessing = PythonScriptStep(
    name="Preprocessing",
    script_name=e.preprocess_script_path,
    arguments=[
        "--config_path", e.preprocess_config_path,
        "--task", e.preprocess_task,
    ],
    inputs=None,
    compute_target=aml_compute,
    runconfig=run_config,
    source_directory=e.sources_directory,
    allow_reuse=False
)
print("Step Preprocessing created")
</code>```

This results in error:

```<code>Traceback (most recent call last):
[stderr]  File "Pipeline/custom_pipeline.py", line 4, in <module>
[stderr]    from Preprocess.logger import logger
[stderr]ModuleNotFoundError: No module named 'Preprocess'
</code>```

in the 1st line of entry script (custom_pipeline.py):

```<code>import sys
sys.path.append(".")
from Preprocess.logger import logger
</code>```

The folder structure is as:

```<code>-Preprocess
  -__init__.py
  - Module1
    -__init__.py
    -somefile.py
  - Module2
    -__init__.py
    -someOtherfile.py
  - Pipeline
    -__init__.py
    -custom_pipeline.py
  - logger
    -__init__.py
    -logger.py
</code>```

答: I found out that the python script step copies everything inside the source_dir and therefore in my case it was copying the modules and not the root folder. So I had to put the dir Preprocess inside another dir and mention the new dir as source_dir.</p>

Body:
I have developed a module which works perfectly when executed locally.

I have created an environment on azure using a prebuilt docker image found here:
"azureml/minimal-ubuntu18.04-py37-cpu-inference" https://mcr.microsoft.com/v2/_catalog
. Also, Using pythonScriptStep, to run a pipeline. Here is how the step looks

StepPreprocessing = PythonScriptStep(
    name="Preprocessing",
    script_name=e.preprocess_script_path,
    arguments=[
        "--config_path", e.preprocess_config_path,
        "--task", e.preprocess_task,
    ],
    inputs=None,
    compute_target=aml_compute,
    runconfig=run_config,
    source_directory=e.sources_directory,
    allow_reuse=False
)
print("Step Preprocessing created")

This results in error:

Traceback (most recent call last):
[stderr]  File "Pipeline/custom_pipeline.py", line 4, in <module>
[stderr]    from Preprocess.logger import logger
[stderr]ModuleNotFoundError: No module named 'Preprocess'

in the 1st line of entry script (custom_pipeline.py):

import sys
sys.path.append(".")
from Preprocess.logger import logger

The folder structure is as:

-Preprocess
  -__init__.py
  - Module1
    -__init__.py
    -somefile.py
  - Module2
    -__init__.py
    -someOtherfile.py
  - Pipeline
    -__init__.py
    -custom_pipeline.py
  - logger
    -__init__.py
    -logger.py