问:
ARM template with DSC extension fails with security error after reboot during create new AD forest and domain
For months I have reliably used an ARM template that creates primary and backup domain controllers (based on 'active-directory-new-domain-ha-2-dc' in the quick start templates). On Friday it stopped working without any modifications being made.

The problem is on the primary DC. The xADDomain DSC resource triggers a reboot as shown in this excerpt from the first DSC log:

```<code>VERBOSE: [2020-05-22 15:22:17Z] [VERBOSE] [tipaADPDC]: LCM:  [ End    Resource
]  [[xADDomain]FirstDS]
VERBOSE: [2020-05-22 15:22:17Z] [VERBOSE] [tipaADPDC]:
   [] A reboot is required to progress further. Please reboot the system.
Configuration will not be continued after the reboot. To continue
configuration, use Start-DscConfiguration -UseExisting after reboot.
VERBOSE: [2020-05-22 15:22:17Z] [WARNING] [tipaADPDC]:
   [] A reboot is required to progress further. Please reboot the system.
Configuration will not be continued after the reboot. To continue
configuration, use Start-DscConfiguration -UseExisting after reboot.
</code>```

After the reboot the following security error can be seen in the second DSC log:

```<code>VERBOSE: [2020-05-22 15:23:28Z] Will continue the existing configuration.
Executing Start-DscConfiguration with -UseExisting option ...
VERBOSE: [2020-05-22 15:23:28Z] Settings handler status to 'transitioning'
(C:\Packages\Plugins\Microsoft.Powershell.DSC\2.80.0.0\Status\0.status)
VERBOSE: [2020-05-22 15:23:29Z] [VERBOSE] Perform operation 'Invoke CimMethod'
with following parameters, ''methodName' = ApplyConfiguration,'className' =
MSFT_DSCLocalConfigurationManager,'namespaceName' =
root/Microsoft/Windows/DesiredStateConfiguration'.
VERBOSE: [2020-05-22 15:23:29Z] [ERROR] WinRM cannot process the request. The
following error with errorcode 0x80090350 occurred while using Negotiate
authentication: An unknown security error occurred.
</code>```

As no changes had been made to the ARM template or the DSC resources I assume that this is due to the deployment picking up the latest version of something.

Things I have tried:

Using DSC 2.76 instead of 2.80

Using WMF 5.0 instead of 5.1

Using Windows Server 2019-Datacenter instead of 2016 (it seems
there has been no update to the 2016 image since 20190603).

I have also looked into preventing DSC from restarting after the reboot (there are no more resources to process). However, I think that those settings are already made due to the following entries in the first DSC log:

```<code>VERBOSE: [2020-05-22 15:18:42Z] WMF 5 or newer, Injecting RebootNodeIfNeeded =
False and ActionAfterReboot = "StopConfiguration"

VERBOSE: [2020-05-22 15:18:47Z] Get-DscLocalConfigurationManager:
ActionAfterReboot              : StopConfiguration
RebootNodeIfNeeded             : False
</code>```

I am stuck. Does anyone have any ideas?
Thanks.

答:
Encountered similar issue recently. A little bit different is that instead of xADDomain, I'm using ActiveDirectoryDsc.
And the error was gone when I upgraded OS to Windows Server 2019-Datacenter.

A potential root cause might because of the version of Powershell between 2016 and 2019. Here's my log.

Windows Server 2016

```<code>VERBOSE: [2020-06-01 03:47:34Z] Settings handler status to 'transitioning'
(C:\Packages\Plugins\Microsoft.Powershell.DSC\2.80.0.0\Status\0.status)
VERBOSE: [2020-06-01 03:47:34Z] Retrieving system information ...
VERBOSE: [2020-06-01 03:47:40Z]     OS Version : 10.0
VERBOSE: [2020-06-01 03:47:40Z]     Server OS  : True
VERBOSE: [2020-06-01 03:47:40Z]     64-bit OS  : True
VERBOSE: [2020-06-01 03:47:40Z]     PS Version : 5.1.14393.3471
VERBOSE: [2020-06-01 03:47:40Z] Validating user provided settings for the DSC
Extension Handler ...
</code>```

And after reboot

```<code>VERBOSE: [2020-06-01 03:53:05Z] Settings handler status to 'transitioning'
(C:\Packages\Plugins\Microsoft.Powershell.DSC\2.80.0.0\Status\0.status)
VERBOSE: [2020-06-01 03:53:05Z] Will continue the existing configuration.
Executing Start-DscConfiguration with -UseExisting option ...
VERBOSE: [2020-06-01 03:53:05Z] Settings handler status to 'transitioning'
(C:\Packages\Plugins\Microsoft.Powershell.DSC\2.80.0.0\Status\0.status)
VERBOSE: [2020-06-01 03:53:07Z] [VERBOSE] Perform operation 'Invoke CimMethod'
with following parameters, ''methodName' = ApplyConfiguration,'className' =
MSFT_DSCLocalConfigurationManager,'namespaceName' =
root/Microsoft/Windows/DesiredStateConfiguration'.
VERBOSE: [2020-06-01 03:53:07Z] [ERROR] WinRM cannot process the request. The
following error with errorcode 0x80090350 occurred while using Negotiate
authentication: An unknown security error occurred.

 Possible causes are:

  -The user name or password specified are invalid.

  -Kerberos is used when no authentication method and no user name are
specified.

  -Kerberos accepts domain user names, but not local user names.

  -The Service Principal Name (SPN) for the remote computer name and port does
not exist.

  -The client and remote computers are in different domains and there is no
trust between the two domains.

 After checking for the above issues, try the following:

  -Check the Event Viewer for events related to authentication.

  -Change the authentication method; add the destination computer to the WinRM
TrustedHosts configuration setting or use HTTPS transport.

 Note that computers in the TrustedHosts list might not be authenticated.

   -For more information about WinRM configuration, run the following command:
winrm help config.
VERBOSE: [2020-06-01 03:53:07Z] [VERBOSE] Operation 'Invoke CimMethod'
complete.
VERBOSE: [2020-06-01 03:53:07Z] [VERBOSE] Time taken for configuration job to
complete is 0.039 seconds
</code>```

Windows Server 2019

```<code>VERBOSE: [2020-06-01 08:33:17Z] Settings handler status to 'transitioning'
(C:\Packages\Plugins\Microsoft.Powershell.DSC\2.80.0.0\Status\0.status)
VERBOSE: [2020-06-01 08:33:18Z] Retrieving system information ...
VERBOSE: [2020-06-01 08:33:22Z]     OS Version : 10.0
VERBOSE: [2020-06-01 08:33:22Z]     Server OS  : True
VERBOSE: [2020-06-01 08:33:22Z]     64-bit OS  : True
VERBOSE: [2020-06-01 08:33:22Z]     PS Version : 5.1.17763.1007
VERBOSE: [2020-06-01 08:33:22Z] Validating user provided settings for the DSC Extension Handler ...
</code>```

And after reboot

```<code>VERBOSE: [2020-06-01 08:38:49Z] Settings handler status to 'transitioning'
(C:\Packages\Plugins\Microsoft.Powershell.DSC\2.80.0.0\Status\0.status)
VERBOSE: [2020-06-01 08:38:49Z] Will continue the existing configuration. Executing Start-DscConfiguration with
-UseExisting option ...
VERBOSE: [2020-06-01 08:38:50Z] Settings handler status to 'transitioning'
(C:\Packages\Plugins\Microsoft.Powershell.DSC\2.80.0.0\Status\0.status)
VERBOSE: [2020-06-01 08:38:51Z] [VERBOSE] Perform operation 'Invoke CimMethod' with following parameters, ''methodName'
 = ApplyConfiguration,'className' = MSFT_DSCLocalConfigurationManager,'namespaceName' =
root/Microsoft/Windows/DesiredStateConfiguration'.
VERBOSE: [2020-06-01 08:38:51Z] [VERBOSE] An LCM method call arrived from computer adPDC with user sid S-1-5-18.
</code>```

Body:
For months I have reliably used an ARM template that creates primary and backup domain controllers (based on 'active-directory-new-domain-ha-2-dc' in the quick start templates). On Friday it stopped working without any modifications being made.

The problem is on the primary DC. The xADDomain DSC resource triggers a reboot as shown in this excerpt from the first DSC log:

VERBOSE: [2020-05-22 15:22:17Z] [VERBOSE] [tipaADPDC]: LCM:  [ End    Resource
]  [[xADDomain]FirstDS]
VERBOSE: [2020-05-22 15:22:17Z] [VERBOSE] [tipaADPDC]:
   [] A reboot is required to progress further. Please reboot the system.
Configuration will not be continued after the reboot. To continue
configuration, use Start-DscConfiguration -UseExisting after reboot.
VERBOSE: [2020-05-22 15:22:17Z] [WARNING] [tipaADPDC]:
   [] A reboot is required to progress further. Please reboot the system.
Configuration will not be continued after the reboot. To continue
configuration, use Start-DscConfiguration -UseExisting after reboot.

After the reboot the following security error can be seen in the second DSC log:

VERBOSE: [2020-05-22 15:23:28Z] Will continue the existing configuration.
Executing Start-DscConfiguration with -UseExisting option ...
VERBOSE: [2020-05-22 15:23:28Z] Settings handler status to 'transitioning'
(C:\Packages\Plugins\Microsoft.Powershell.DSC\2.80.0.0\Status\0.status)
VERBOSE: [2020-05-22 15:23:29Z] [VERBOSE] Perform operation 'Invoke CimMethod'
with following parameters, ''methodName' = ApplyConfiguration,'className' =
MSFT_DSCLocalConfigurationManager,'namespaceName' =
root/Microsoft/Windows/DesiredStateConfiguration'.
VERBOSE: [2020-05-22 15:23:29Z] [ERROR] WinRM cannot process the request. The
following error with errorcode 0x80090350 occurred while using Negotiate
authentication: An unknown security error occurred.

As no changes had been made to the ARM template or the DSC resources I assume that this is due to the deployment picking up the latest version of something.

Things I have tried:

Using DSC 2.76 instead of 2.80

Using WMF 5.0 instead of 5.1

Using Windows Server 2019-Datacenter instead of 2016 (it seems
there has been no update to the 2016 image since 20190603).

I have also looked into preventing DSC from restarting after the reboot (there are no more resources to process). However, I think that those settings are already made due to the following entries in the first DSC log:

VERBOSE: [2020-05-22 15:18:42Z] WMF 5 or newer, Injecting RebootNodeIfNeeded =
False and ActionAfterReboot = "StopConfiguration"

VERBOSE: [2020-05-22 15:18:47Z] Get-DscLocalConfigurationManager:
ActionAfterReboot              : StopConfiguration
RebootNodeIfNeeded             : False

I am stuck. Does anyone have any ideas?
Thanks.

Body:
Encountered similar issue recently. A little bit different is that instead of xADDomain, I'm using ActiveDirectoryDsc.
And the error was gone when I upgraded OS to Windows Server 2019-Datacenter.

A potential root cause might because of the version of Powershell between 2016 and 2019. Here's my log.

Windows Server 2016

VERBOSE: [2020-06-01 03:47:34Z] Settings handler status to 'transitioning'
(C:\Packages\Plugins\Microsoft.Powershell.DSC\2.80.0.0\Status\0.status)
VERBOSE: [2020-06-01 03:47:34Z] Retrieving system information ...
VERBOSE: [2020-06-01 03:47:40Z]     OS Version : 10.0
VERBOSE: [2020-06-01 03:47:40Z]     Server OS  : True
VERBOSE: [2020-06-01 03:47:40Z]     64-bit OS  : True
VERBOSE: [2020-06-01 03:47:40Z]     PS Version : 5.1.14393.3471
VERBOSE: [2020-06-01 03:47:40Z] Validating user provided settings for the DSC
Extension Handler ...

And after reboot

VERBOSE: [2020-06-01 03:53:05Z] Settings handler status to 'transitioning'
(C:\Packages\Plugins\Microsoft.Powershell.DSC\2.80.0.0\Status\0.status)
VERBOSE: [2020-06-01 03:53:05Z] Will continue the existing configuration.
Executing Start-DscConfiguration with -UseExisting option ...
VERBOSE: [2020-06-01 03:53:05Z] Settings handler status to 'transitioning'
(C:\Packages\Plugins\Microsoft.Powershell.DSC\2.80.0.0\Status\0.status)
VERBOSE: [2020-06-01 03:53:07Z] [VERBOSE] Perform operation 'Invoke CimMethod'
with following parameters, ''methodName' = ApplyConfiguration,'className' =
MSFT_DSCLocalConfigurationManager,'namespaceName' =
root/Microsoft/Windows/DesiredStateConfiguration'.
VERBOSE: [2020-06-01 03:53:07Z] [ERROR] WinRM cannot process the request. The
following error with errorcode 0x80090350 occurred while using Negotiate
authentication: An unknown security error occurred.

 Possible causes are:

  -The user name or password specified are invalid.

  -Kerberos is used when no authentication method and no user name are
specified.

  -Kerberos accepts domain user names, but not local user names.

  -The Service Principal Name (SPN) for the remote computer name and port does
not exist.

  -The client and remote computers are in different domains and there is no
trust between the two domains.

 After checking for the above issues, try the following:

  -Check the Event Viewer for events related to authentication.

  -Change the authentication method; add the destination computer to the WinRM
TrustedHosts configuration setting or use HTTPS transport.

 Note that computers in the TrustedHosts list might not be authenticated.

   -For more information about WinRM configuration, run the following command:
winrm help config.
VERBOSE: [2020-06-01 03:53:07Z] [VERBOSE] Operation 'Invoke CimMethod'
complete.
VERBOSE: [2020-06-01 03:53:07Z] [VERBOSE] Time taken for configuration job to
complete is 0.039 seconds

Windows Server 2019

VERBOSE: [2020-06-01 08:33:17Z] Settings handler status to 'transitioning'
(C:\Packages\Plugins\Microsoft.Powershell.DSC\2.80.0.0\Status\0.status)
VERBOSE: [2020-06-01 08:33:18Z] Retrieving system information ...
VERBOSE: [2020-06-01 08:33:22Z]     OS Version : 10.0
VERBOSE: [2020-06-01 08:33:22Z]     Server OS  : True
VERBOSE: [2020-06-01 08:33:22Z]     64-bit OS  : True
VERBOSE: [2020-06-01 08:33:22Z]     PS Version : 5.1.17763.1007
VERBOSE: [2020-06-01 08:33:22Z] Validating user provided settings for the DSC Extension Handler ...

And after reboot

VERBOSE: [2020-06-01 08:38:49Z] Settings handler status to 'transitioning'
(C:\Packages\Plugins\Microsoft.Powershell.DSC\2.80.0.0\Status\0.status)
VERBOSE: [2020-06-01 08:38:49Z] Will continue the existing configuration. Executing Start-DscConfiguration with
-UseExisting option ...
VERBOSE: [2020-06-01 08:38:50Z] Settings handler status to 'transitioning'
(C:\Packages\Plugins\Microsoft.Powershell.DSC\2.80.0.0\Status\0.status)
VERBOSE: [2020-06-01 08:38:51Z] [VERBOSE] Perform operation 'Invoke CimMethod' with following parameters, ''methodName'
 = ApplyConfiguration,'className' = MSFT_DSCLocalConfigurationManager,'namespaceName' =
root/Microsoft/Windows/DesiredStateConfiguration'.
VERBOSE: [2020-06-01 08:38:51Z] [VERBOSE] An LCM method call arrived from computer adPDC with user sid S-1-5-18.


来源: stackexchange

问:
Center a text inside an spinning element
I have a simple loader animation and I want to add a loading text inside the circle.

As I'm spinning the .slide-loader and my text is inside it I've tried to exclude the .loader-text but it still spins?! how can I fix the loader-text inside the circle?

Here is the code:

.slide-loader:not(.loader-text) {
  position: absolute;
  top:0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
  border: 6px solid #f3f3f3;
  border-radius: 50%;
  border-top: 6px solid #3498db;
  width: 100px;
  height: 100px;
  -webkit-animation: spin 2s linear infinite;
  animation: spin 2s linear infinite;

}

@-webkit-keyframes spin {
  0% { -webkit-transform: rotate(0deg); }
  100% { -webkit-transform: rotate(360deg); }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>  <div class="slide-loader">
    <div class="loader-text">Loading...</div>
  </div></code>```

答:
Use an absolutely positioned pseudo-element (::before) for the rotating area, and center the text with a flexbox:

.slide-loader {
  display: flex;
  justify-content: center;
  align-items: center;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
  width: 100px;
  height: 100px;
}

.slide-loader::before {
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  width: 100%;
  border: 6px solid #f3f3f3;
  border-radius: 50%;
  border-top: 6px solid #3498db;
  animation: spin 2s linear infinite;
  content: '';
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="slide-loader">Loading...</div></code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a simple loader animation and I want to add a loading text inside the circle.

As I'm spinning the .slide-loader and my text is inside it I've tried to exclude the .loader-text but it still spins?! how can I fix the loader-text inside the circle?

Here is the code:

.slide-loader:not(.loader-text) {
  position: absolute;
  top:0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
  border: 6px solid #f3f3f3;
  border-radius: 50%;
  border-top: 6px solid #3498db;
  width: 100px;
  height: 100px;
  -webkit-animation: spin 2s linear infinite;
  animation: spin 2s linear infinite;

}

@-webkit-keyframes spin {
  0% { -webkit-transform: rotate(0deg); }
  100% { -webkit-transform: rotate(360deg); }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

Loading...

Body:
Use an absolutely positioned pseudo-element (::before) for the rotating area, and center the text with a flexbox:

.slide-loader {
  display: flex;
  justify-content: center;
  align-items: center;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
  width: 100px;
  height: 100px;
}

.slide-loader::before {
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  width: 100%;
  border: 6px solid #f3f3f3;
  border-radius: 50%;
  border-top: 6px solid #3498db;
  animation: spin 2s linear infinite;
  content: '';
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

<div class="slide-loader">Loading...</div>


问:
Can't run 'mongod' command, says not recognized
I'm trying to set up a local db server on my Windows 10 x64 machine. When I try to run anything with mongod it doesn't run. I've already added the PATH, which is now C:/mongodb/bin (tried just C:/mongodb already). Also when I try to run mongo.exe and mongod.exe from the bin folders, the command box launches and immediately disappears, even when run as administrator. What's going on?

答:
after add mongo.exe path into env path in windows 10 i can run this command

but not applied

and after close terminal and vscode then restart all of them again

ContentLicense: CC BY-SA 3.0


问:
Selected Range Save As PDF
With Excel VBA, for example, I want to save the area between A1 and J26 as pdf, but since it doesn't fit, it saves A1 to E26.What should I do to save my chosen area by fitting it on the page? The code I use is below.</p>

```<code>With Sheets(1).Range("A1:J26")
   .ExportAsFixedFormat _
    Type:=xlTypePDF, _
    Filename:="C:\File_Name_Test.pdf", _
    Quality:=xlQualityStandard, _
    IncludeDocProperties:=True, _
    IgnorePrintAreas:=False, _
    OpenAfterPublish:=False '
End With
</code>```

答:
The code below saw my work, thanks</p>

```<code>With Sheets("Sayfa1").PageSetup
.Orientation = xlPortrait
.PaperSize = xlPaperA4
.FirstPageNumber = xlAutomatic
.Order = xlDownThenOver
.Zoom = False
.FitToPagesWide = 1
.FitToPagesTall = 1
.PrintErrors = xlPrintErrorsDisplayed
.ScaleWithDocHeaderFooter = True
.AlignMarginsHeaderFooter = True
End With

With Sheets("Sayfa1").Range("A1:J22")
.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:="D:\_AppData_\Desktop\File_Name22.pdf", _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False '
End With
</code>```

Title: Selected Range Save As PDF

Body:
With Excel VBA, for example, I want to save the area between A1 and J26 as pdf, but since it doesn't fit, it saves A1 to E26.What should I do to save my chosen area by fitting it on the page? The code I use is below.

With Sheets(1).Range("A1:J26")
   .ExportAsFixedFormat _
    Type:=xlTypePDF, _
    Filename:="C:\File_Name_Test.pdf", _
    Quality:=xlQualityStandard, _
    IncludeDocProperties:=True, _
    IgnorePrintAreas:=False, _
    OpenAfterPublish:=False '
End With

Body:
The code below saw my work, thanks

With Sheets("Sayfa1").PageSetup
.Orientation = xlPortrait
.PaperSize = xlPaperA4
.FirstPageNumber = xlAutomatic
.Order = xlDownThenOver
.Zoom = False
.FitToPagesWide = 1
.FitToPagesTall = 1
.PrintErrors = xlPrintErrorsDisplayed
.ScaleWithDocHeaderFooter = True
.AlignMarginsHeaderFooter = True
End With

With Sheets("Sayfa1").Range("A1:J22")
.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:="D:\_AppData_\Desktop\File_Name22.pdf", _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False '
End With


问:
Is there an easier way to pause execution then a callback on an async function?
I have a nodejs application where I download a file which is then immediately used and the rest of the program depends on that file being used, the only problem is that the only function I have to download the file through Google Cloud is asynchronous which means in order to stop the program from immediately crashing when it realizes the file hasn't been fully downloaded is to stick a callback on my asyncronous function for downloading.

This would normally be fine, but unfortunately the rest of the program is around 400 LINES LONG which means a 400 LINE LONG CALLBACK FUNCTION. Which is understandably ugly.

If anyone can tell me of a simpler method for pausing execution than this callback function, I would appreciate it.

Feel free to let me know if this is a duplicate question and this exact one has been answered elsewhere. I scoured for this question myself, but couldn't find it.

async function downloader(callback){
  await download(file); //insert download function here

 callback();
}
downloader(function(){
  var usefulthing = JSON.parse(file);
  //Insert 400 lines of code here
});```

答:
You can separate your 400 lines of code into a file and export a function, let say named handleFile. Then in your callback function just call:

downloader(function(){
  var usefulthing = JSON.parse(file);
  handleFile(file)
});
```


问:
string manipulation: partly convert to lowercase
As the title says: What's best way of converting a string from any-case to lowercase keeping a portion unchanged? e.g. a string like: FormatDate(%M)==2 or stArTDate(%Y/%m)==11/3 and I want to convert it to formatdate(%M)==2 or startdate(%Y/%m)==11/3 i.e. change it to lowercase except the part in between the braces (). For the first example, I came up something like this:

```<code>>>> import re
>>> fdt = re.compile('(F|f)(O|o)(R|r)(M|m)(A|a)(T|t)(D|d)(A|a)(T|t)(E|e)\(')
>>> ss = "forMatDate(%M)==2"
>>> if fdt.match(ss):
...   SS = ss.split('(')
...   SS[0] = SS[0].lower()
...   ss = "(".join(SS)
...
>>> print ss
formatdate(%M)==2
</code>```

Whilst it works just fine, I didn't quite like it doing this way. The regular expression is ugly and it makes thing pretty much restricted to a particular string. Is there any better (hence, dynamic) way of doing that? Thanks in advance. Cheers!!

Update:

I probably didn't say it very clearly: it's not always formatdate(), sometimes it's startdate() or enddate() along with UserName==JohnDee and so on.. (it's part of the user-input) but the format is always the same and I wanted something reusable. So, this is the updated version based on Krumelur's script.

```<code>>>> fdt = re.compile('\(%[dmwyMW].*\)')
>>> ss = "formatDate(%M)==4"
>>> st = "UserName==JohnDee"
>>>
>>> def dt_lower(sX):
...   if fdt.search(sX):
...     p1,p2 = sX.split('(',1)
...     sX = "%s(%s" % (p1.lower(), p2)
...   else: sX = sX.lower()
...   return sX
...
>>> print dt_lower(ss)
formatdate(%M)==4
>>>
>>> print dt_lower(st)
username==johndee
</code>```

This is exactly what I wanted. Thanks everyone for helping. Cheers!!

答:
Just to add to Krumerlur's answer,u may want to make it

p1,p2 = inst.split( '(' , 1 )

Body:
As the title says: What's best way of converting a string from any-case to lowercase keeping a portion unchanged? e.g. a string like: FormatDate(%M)==2 or stArTDate(%Y/%m)==11/3 and I want to convert it to formatdate(%M)==2 or startdate(%Y/%m)==11/3 i.e. change it to lowercase except the part in between the braces (). For the first example, I came up something like this:

>>> import re
>>> fdt = re.compile('(F|f)(O|o)(R|r)(M|m)(A|a)(T|t)(D|d)(A|a)(T|t)(E|e)\(')
>>> ss = "forMatDate(%M)==2"
>>> if fdt.match(ss):
...   SS = ss.split('(')
...   SS[0] = SS[0].lower()
...   ss = "(".join(SS)
...
>>> print ss
formatdate(%M)==2

Whilst it works just fine, I didn't quite like it doing this way. The regular expression is ugly and it makes thing pretty much restricted to a particular string. Is there any better (hence, dynamic) way of doing that? Thanks in advance. Cheers!!

Update:

I probably didn't say it very clearly: it's not always formatdate(), sometimes it's startdate() or enddate() along with UserName==JohnDee and so on.. (it's part of the user-input) but the format is always the same and I wanted something reusable. So, this is the updated version based on Krumelur's script.

>>> fdt = re.compile('\(%[dmwyMW].*\)')
>>> ss = "formatDate(%M)==4"
>>> st = "UserName==JohnDee"
>>>
>>> def dt_lower(sX):
...   if fdt.search(sX):
...     p1,p2 = sX.split('(',1)
...     sX = "%s(%s" % (p1.lower(), p2)
...   else: sX = sX.lower()
...   return sX
...
>>> print dt_lower(ss)
formatdate(%M)==4
>>>
>>> print dt_lower(st)
username==johndee

This is exactly what I wanted. Thanks everyone for helping. Cheers!!


问:
Moving props data to state to generate forms
I'm planning to add a prefilled form with React. I have the actual data on props. This is what I came up with.

```<code>@connect(...)
class Some extends React.Component {
   state = {
      ...this.props.auth.user
   }

   render() {
     // Create a form using the data on state
   }
}
</code>```

It looks not correct since I'm not using a react lifecycle hook here. I would like to ask if there is a better practice to achieve what I'm trying to do.

答:
I am not sure about your architecture,since you are using uncontrolled component here, it is  recommended to keep the source of truth at one place.

you can do something like this:

```<code>@connect(...)
class Some extends React.Component {
constructor(props) {
    super(props);
    this.state = {
      userName:this.props.auth.user
   }
}
handleChange = (event) => {
    this.setState({userName: event.target.value});
  }

   render() {
      return(
         <div>
          <input onChange={this.handleChange} id="some" type="text" value= {this.state.userName}/>
        </div>
     )
   }
}
</code>```

If you want to use controlled component that is controlled through parent/container. you can manage the values through props and set the props onChange.

Body:
I'm planning to add a prefilled form with React. I have the actual data on props. This is what I came up with.

@connect(...)
class Some extends React.Component {
   state = {
      ...this.props.auth.user
   }

   render() {
     // Create a form using the data on state
   }
}

It looks not correct since I'm not using a react lifecycle hook here. I would like to ask if there is a better practice to achieve what I'm trying to do.

Body:
I am not sure about your architecture,since you are using uncontrolled component here, it is  recommended to keep the source of truth at one place.

you can do something like this:

@connect(...)
class Some extends React.Component {
constructor(props) {
    super(props);
    this.state = {
      userName:this.props.auth.user
   }
}
handleChange = (event) => {
    this.setState({userName: event.target.value});
  }

   render() {
      return(
         <div>
          <input onChange={this.handleChange} id="some" type="text" value= {this.state.userName}/>
        </div>
     )
   }
}

If you want to use controlled component that is controlled through parent/container. you can manage the values through props and set the props onChange.


问:
Error: credentials argument needs to implement signRequest method
I got a question -- I am trying to reuse the response from the ms-rest-nodeauth library. This way everytime I use my tool, I only need to authenticate if the authentication context is not valid.. Whenever I try to use the returned response I get this error

```<code>Error: credentials argument needs to implement signRequest method
</code>```

Anyone got any suggestions?

答:
If not already done then I believe that you would have to double check the code by leveraging the samples provided in this repo. If those samples are not helpful to resolve your error then raising an issue here / here would help you with better response from the repository contributors, etc.

Other references:

ms-rest-nodeauth (azure-sdk-for-js) : Error: credentials argument needs to implement signRequest method

https://github.com/Azure/azure-sdk-for-js/issues/3936

Body:
I got a question -- I am trying to reuse the response from the ms-rest-nodeauth library. This way everytime I use my tool, I only need to authenticate if the authentication context is not valid.. Whenever I try to use the returned response I get this error

Error: credentials argument needs to implement signRequest method

Anyone got any suggestions?


问:
My Matomo installation doesn't work on desktop
Matomo doesn't work on desktop release.

Ooops ... there was a problem during the request. Maybe the server had
  a temporary problem or maybe you requested a report with too much
  data.

This is the matomo.log:
'''
ERROR Piwik\FrontController[2020-05-31 18:25:07 UTC] [b5304] Uncaught exception: /membri/impressionism/matomo/plugins/Live/templates/_visitorLogIcons.twig(16): The string to escape is not a valid UTF-8 string.
ERROR Piwik\FrontController[2020-05-31 18:25:07 UTC] [b5304] The string to escape is not a valid UTF-8 string.
ERROR Piwik\FrontController[2020-05-31 18:25:07 UTC] [b5304] #0 /membri/impressionism/matomo/core/Twig.php(69): twig_escape_filter(Object(Twig\Environment), 'San Mart\xEDn de l...', 'html_attr', 'UTF-8', false)
ERROR Piwik\FrontController[2020-05-31 18:25:07 UTC] [b5304] #1 /membri/impressionism/matomo/tmp/templates_c/8f/8f3293af9e355d51978f0a1005aca83f01464bfbc8d55751a8d3178f9975d9bf.php(64): Piwik\piwik_escape_filter(Object(Twig\Environment), 'San Mart\xEDn de l...', 'html_attr')
ERROR Piwik\FrontController[2020-05-31 18:25:07 UTC] [b5304] #2 /membri/impressionism/matomo/vendor/twig/twig/src/Template.php(455): __TwigTemplate_48ad10421548dbe27c8ef303b7c040c271a9b7e5cb17d293981650bfb3aee5ce->doDisplay(Array, Array)
ERROR Piwik\FrontController[2020-05-31 18:25:07 UTC] [b5304] #3 /membri/impressionism/matomo/vendor/twig/twig/src/Template.php(422): Twig\Template->displayWithErrorHandling(Array, Array)
ERROR Piwik\FrontController[2020-05-31 18:25:07 UTC] [b5304] #4 /membri/impressionism/matomo/vendor/twig/twig/src/Template.php(434): Twig\Template->display(Array)
ERROR Piwik\FrontController[2020-05-31 18:25:07 UTC] [b5304] #5 /membri/impressionism/matomo/vendor/twig/twig/src/TemplateWrapper.php(47): Twig\Template->render(Array, Array)
ERROR Piwik\FrontController[2020-05-31 18:25:07 UTC] [b5304] #6 /membri/impressionism/matomo/vendor/twig/twig/src/Environment.php(384): Twig\TemplateWrapper->render(Array)
ERROR Piwik\FrontController[2020-05-31 18:25:07 UTC] [b5304] #7 /membri/impressionism/matomo/core/View.php(311): Twig\Environment->render('@Live/_visitorL...', Array)
ERROR Piwik\FrontController[2020-05-31 18:25:07 UTC] [b5304] #8 /membri/impressionism/matomo/core/View.php(295): Piwik\View->renderTwigTemplate()
ERROR Piwik\FrontController[2020-05-31 18:25:07 UTC] [b5304] #9 /membri/impressionism/matomo/plugins/Live/VisitorDetails.php(126): Piwik\View->render()
ERROR Piwik\FrontController[2020-05-31 18:25:07 UTC] [b5304] #10 /membri/impressionism/matomo/plugins/Live/Live.php(138): Piwik\Plugins\Live\VisitorDetails->renderIcons(Object(Piwik\DataTable\Row))
ERROR Piwik\FrontController[2020-05-31 18:25:07 UTC] [b5304] #11 [internal function]: Piwik\Plugins\Live\Live->renderVisitorIcons('', Object(Piwik\DataTable\Row))
ERROR Piwik\FrontController[2020-05-31 18:25:07 UTC] [b5304] #12 /membri/impressionism/matomo/core/EventDispatcher.php(141): call_user_func_array(Array, Array)
ERROR Piwik\FrontController[2020-05-31 18:25:07 UTC] [b5304] #13 /membri/impressionism/matomo/core/Piwik.php(775): Piwik\EventDispatcher->postEvent('Live.renderVisi...', Array, false, Array)
ERROR Piwik\FrontController[2020-05-31 18:25:07 UTC] [b5304] #14 /membri/impressionism/matomo/core/Twig.php(289): Piwik\Piwik::postEvent('Live.renderVisi...', Array)
ERROR Piwik\FrontController[2020-05-31 18:25:07 UTC] [b5304] #15 /membri/impressionism/matomo/tmp/templates_c/47/4700797b9f5741a2216205f8c2053127fd14c140de58d5313fc3939e2f7b25b9.php(123): Piwik\Twig->Piwik{closure}('Live.renderVisi...', Object(Piwik\DataTable\Row))
ERROR Piwik\FrontController[2020-05-31 18:25:07 UTC] [b5304] #16 /membri/impressionism/matomo/vendor/twig/twig/src/Template.php(455): __TwigTemplate_f7387213c57911a4fe2fa844a9dea404f3cc42ae869b2de1f203141fa4f2e5f3->doDisplay(Array, Array)
ERROR Piwik\FrontController[2020-05-31 18:25:07 UTC] [b5304] #17 /membri/impressionism/matomo/vendor/twig/twig/src/Template.php(422): Twig\Template->displayWithErrorHandling(Array, Array)
ERROR Piwik\FrontController[2020-05-31 18:25:07 UTC] [b5304] #18 /membri/impressionism/matomo/vendor/twig/twig/src/Template.php(434): Twig\Template->display(Array)
ERROR Piwik\FrontController[2020-05-31 18:25:07 UTC] [b5304] #19 /membri/impressionism/matomo/vendor/twig/twig/src/TemplateWrapper.php(47): Twig\Template->render(Array, Array)
ERROR Piwik\FrontController[2020-05-31 18:25:07 UTC] [b5304] #20 /membri/impressionism/matomo/vendor/twig/twig/src/Environment.php(384): Twig\TemplateWrapper->render(Array)
ERROR Piwik\FrontController[2020-05-31 18:25:07 UTC] [b5304] #21 /membri/impressionism/matomo/core/View.php(311): Twig\Environment->render('@Live/getLastVi...', Array)
ERROR Piwik\FrontController[2020-05-31 18:25:07 UTC] [b5304] #22 /membri/impressionism/matomo/core/View.php(295): Piwik\View->renderTwigTemplate()
ERROR Piwik\FrontController[2020-05-31 18:25:07 UTC] [b5304] #23 /membri/impressionism/matomo/plugins/Live/Controller.php(58): Piwik\View->render()
ERROR Piwik\FrontController[2020-05-31 18:25:07 UTC] [b5304] #24 /membri/impressionism/matomo/plugins/Live/Controller.php(101): Piwik\Plugins\Live\Controller->render(Object(Piwik\View))
ERROR Piwik\FrontController[2020-05-31 18:25:07 UTC] [b5304] #25 /membri/impressionism/matomo/plugins/Live/Controller.php(41): Piwik\Plugins\Live\Controller->getLastVisitsStart()
ERROR Piwik\FrontController[2020-05-31 18:25:07 UTC] [b5304] #26 [internal function]: Piwik\Plugins\Live\Controller->widget()
ERROR Piwik\FrontController[2020-05-31 18:25:07 UTC] [b5304] #27 /membri/impressionism/matomo/core/FrontController.php(590): call_user_func_array(Array, Array)
ERROR Piwik\FrontController[2020-05-31 18:25:07 UTC] [b5304] #28 /membri/impressionism/matomo/core/FrontController.php(165): Piwik\FrontController->doDispatch('Live', 'widget', Array)
ERROR Piwik\FrontController[2020-05-31 18:25:07 UTC] [b5304] #29 /membri/impressionism/matomo/core/dispatch.php(34): Piwik\FrontController->dispatch()
ERROR Piwik\FrontController[2020-05-31 18:25:07 UTC] [b5304] #30 /membri/impressionism/matomo/index.php(27): require_once('/membri/impress...')
ERROR Piwik\FrontController[2020-05-31 18:25:07 UTC] [b5304] #31 {main}
ERROR Piwik\FrontController[2020-05-31 18:29:50 UTC] [c2ce5] Uncaught exception: /membri/impressionism/matomo/plugins/Live/templates/_visitorLogIcons.twig(16): The string to escape is not a valid UTF-8 string.
ERROR Piwik\FrontController[2020-05-31 18:29:50 UTC] [c2ce5] The string to escape is not a valid UTF-8 string.
ERROR Piwik\FrontController[2020-05-31 18:29:50 UTC] [c2ce5] #0 /membri/impressionism/matomo/core/Twig.php(69): twig_escape_filter(Object(Twig\Environment), 'San Mart\xEDn de l...', 'html_attr', 'UTF-8', false)
ERROR Piwik\FrontController[2020-05-31 18:29:50 UTC] [c2ce5] #1 /membri/impressionism/matomo/tmp/templates_c/8f/8f3293af9e355d51978f0a1005aca83f01464bfbc8d55751a8d3178f9975d9bf.php(64): Piwik\piwik_escape_filter(Object(Twig\Environment), 'San Mart\xEDn de l...', 'html_attr')
ERROR Piwik\FrontController[2020-05-31 18:29:50 UTC] [c2ce5] #2 /membri/impressionism/matomo/vendor/twig/twig/src/Template.php(455): __TwigTemplate_48ad10421548dbe27c8ef303b7c040c271a9b7e5cb17d293981650bfb3aee5ce->doDisplay(Array, Array)
ERROR Piwik\FrontController[2020-05-31 18:29:50 UTC] [c2ce5] #3 /membri/impressionism/matomo/vendor/twig/twig/src/Template.php(422): Twig\Template->displayWithErrorHandling(Array, Array)
ERROR Piwik\FrontController[2020-05-31 18:29:50 UTC] [c2ce5] #4 /membri/impressionism/matomo/vendor/twig/twig/src/Template.php(434): Twig\Template->display(Array)
ERROR Piwik\FrontController[2020-05-31 18:29:50 UTC] [c2ce5] #5 /membri/impressionism/matomo/vendor/twig/twig/src/TemplateWrapper.php(47): Twig\Template->render(Array, Array)
ERROR Piwik\FrontController[2020-05-31 18:29:50 UTC] [c2ce5] #6 /membri/impressionism/matomo/vendor/twig/twig/src/Environment.php(384): Twig\TemplateWrapper->render(Array)
ERROR Piwik\FrontController[2020-05-31 18:29:50 UTC] [c2ce5] #7 /membri/impressionism/matomo/core/View.php(311): Twig\Environment->render('@Live/_visitorL...', Array)
ERROR Piwik\FrontController[2020-05-31 18:29:50 UTC] [c2ce5] #8 /membri/impressionism/matomo/core/View.php(295): Piwik\View->renderTwigTemplate()
ERROR Piwik\FrontController[2020-05-31 18:29:50 UTC] [c2ce5] #9 /membri/impressionism/matomo/plugins/Live/VisitorDetails.php(126): Piwik\View->render()
ERROR Piwik\FrontController[2020-05-31 18:29:50 UTC] [c2ce5] #10 /membri/impressionism/matomo/plugins/Live/Live.php(138): Piwik\Plugins\Live\VisitorDetails->renderIcons(Object(Piwik\DataTable\Row))
ERROR Piwik\FrontController[2020-05-31 18:29:50 UTC] [c2ce5] #11 [internal function]: Piwik\Plugins\Live\Live->renderVisitorIcons('', Object(Piwik\DataTable\Row))
ERROR Piwik\FrontController[2020-05-31 18:29:50 UTC] [c2ce5] #12 /membri/impressionism/matomo/core/EventDispatcher.php(141): call_user_func_array(Array, Array)
ERROR Piwik\FrontController[2020-05-31 18:29:50 UTC] [c2ce5] #13 /membri/impressionism/matomo/core/Piwik.php(775): Piwik\EventDispatcher->postEvent('Live.renderVisi...', Array, false, Array)
ERROR Piwik\FrontController[2020-05-31 18:29:50 UTC] [c2ce5] #14 /membri/impressionism/matomo/core/Twig.php(289): Piwik\Piwik::postEvent('Live.renderVisi...', Array)
ERROR Piwik\FrontController[2020-05-31 18:29:50 UTC] [c2ce5] #15 /membri/impressionism/matomo/tmp/templates_c/47/4700797b9f5741a2216205f8c2053127fd14c140de58d5313fc3939e2f7b25b9.php(123): Piwik\Twig->Piwik{closure}('Live.renderVisi...', Object(Piwik\DataTable\Row))
ERROR Piwik\FrontController[2020-05-31 18:29:50 UTC] [c2ce5] #16 /membri/impressionism/matomo/vendor/twig/twig/src/Template.php(455): __TwigTemplate_f7387213c57911a4fe2fa844a9dea404f3cc42ae869b2de1f203141fa4f2e5f3->doDisplay(Array, Array)
ERROR Piwik\FrontController[2020-05-31 18:29:50 UTC] [c2ce5] #17 /membri/impressionism/matomo/vendor/twig/twig/src/Template.php(422): Twig\Template->displayWithErrorHandling(Array, Array)
ERROR Piwik\FrontController[2020-05-31 18:29:50 UTC] [c2ce5] #18 /membri/impressionism/matomo/vendor/twig/twig/src/Template.php(434): Twig\Template->display(Array)
ERROR Piwik\FrontController[2020-05-31 18:29:50 UTC] [c2ce5] #19 /membri/impressionism/matomo/vendor/twig/twig/src/TemplateWrapper.php(47): Twig\Template->render(Array, Array)
ERROR Piwik\FrontController[2020-05-31 18:29:50 UTC] [c2ce5] #20 /membri/impressionism/matomo/vendor/twig/twig/src/Environment.php(384): Twig\TemplateWrapper->render(Array)
ERROR Piwik\FrontController[2020-05-31 18:29:50 UTC] [c2ce5] #21 /membri/impressionism/matomo/core/View.php(311): Twig\Environment->render('@Live/getLastVi...', Array)
ERROR Piwik\FrontController[2020-05-31 18:29:50 UTC] [c2ce5] #22 /membri/impressionism/matomo/core/View.php(295): Piwik\View->renderTwigTemplate()
ERROR Piwik\FrontController[2020-05-31 18:29:50 UTC] [c2ce5] #23 /membri/impressionism/matomo/plugins/Live/Controller.php(58): Piwik\View->render()
ERROR Piwik\FrontController[2020-05-31 18:29:50 UTC] [c2ce5] #24 /membri/impressionism/matomo/plugins/Live/Controller.php(101): Piwik\Plugins\Live\Controller->render(Object(Piwik\View))
ERROR Piwik\FrontController[2020-05-31 18:29:50 UTC] [c2ce5] #25 /membri/impressionism/matomo/plugins/Live/Controller.php(41): Piwik\Plugins\Live\Controller->getLastVisitsStart()
ERROR Piwik\FrontController[2020-05-31 18:29:50 UTC] [c2ce5] #26 [internal function]: Piwik\Plugins\Live\Controller->widget()
ERROR Piwik\FrontController[2020-05-31 18:29:50 UTC] [c2ce5] #27 /membri/impressionism/matomo/core/FrontController.php(590): call_user_func_array(Array, Array)
ERROR Piwik\FrontController[2020-05-31 18:29:50 UTC] [c2ce5] #28 /membri/impressionism/matomo/core/FrontController.php(165): Piwik\FrontController->doDispatch('Live', 'widget', Array)
ERROR Piwik\FrontController[2020-05-31 18:29:50 UTC] [c2ce5] #29 /membri/impressionism/matomo/core/dispatch.php(34): Piwik\FrontController->dispatch()
ERROR Piwik\FrontController[2020-05-31 18:29:50 UTC] [c2ce5] #30 /membri/impressionism/matomo/index.php(27): require_once('/membri/impress...')
ERROR Piwik\FrontController[2020-05-31 18:29:50 UTC] [c2ce5] #31 {main}
'''
Thank you for help me.

答:
This issue The string to escape is not a valid UTF-8 string is fixed in Matomo 4 currently in development. If you are blocked, you can always try to upgrade to the Matomo 4 in development at: https://github.com/matomo-org/matomo (branch 4.x-dev). Learn more about the issue here: https://github.com/matomo-org/matomo/issues/14485
which was fixed in https://github.com/matomo-org/matomo/pull/15618
(will be released in Matomo 4 in a few months)


问:
varA = varA + varB doesn't work in typescript
I'm making a running total calculator method for my angular project in ts,

```<code>Total(){
let t: any;
for (let n = 0; n < this.checkoutItems.length; n++) {
  let key = this.checkoutItems[n].item_id ;
  this.itemsService.getCheckoutItem(key, 2).subscribe((response: any) => {
  this.checkoutItem = response;
  let y = localStorage.getItem(key);
  console.log("y:");
  console.log(y);
  let x=+y;
  console.log("x:");
  console.log(x);
  let a= +this.checkoutItems[n].price;
  console.log("a:");
  console.log(a);
  let b = a*x;
  console.log("b:");
  console.log(b);
   t +=b;
  console.log("t:");
  console.log(t);
  })
}
}
</code>```

Everything works fine upto the console log of b, they print the desired output on my console but for some reason the console log of t returns NaN ? why does that happen? I'm sorry I'm new to typescript.

答:
t +=b means t = t+b so where did set t before this line?

Because of that... you have t = undefined + b so NaN, that is what I guess without trying your code (shame on me).

If you are dealing with a counter you can safely set t to 0 when you define it at the very beginning. Something like => let t = 0.
If t is your result you can even use reduce avoiding an external variable declaration and a for loop.

Body:
I'm making a running total calculator method for my angular project in ts,

Total(){
let t: any;
for (let n = 0; n < this.checkoutItems.length; n++) {
  let key = this.checkoutItems[n].item_id ;
  this.itemsService.getCheckoutItem(key, 2).subscribe((response: any) => {
  this.checkoutItem = response;
  let y = localStorage.getItem(key);
  console.log("y:");
  console.log(y);
  let x=+y;
  console.log("x:");
  console.log(x);
  let a= +this.checkoutItems[n].price;
  console.log("a:");
  console.log(a);
  let b = a*x;
  console.log("b:");
  console.log(b);
   t +=b;
  console.log("t:");
  console.log(t);
  })
}
}

Everything works fine upto the console log of b, they print the desired output on my console but for some reason the console log of t returns NaN ? why does that happen? I'm sorry I'm new to typescript.


问:
How to migrate users from user service database to spring boot auth server database?
I am building a micro service bases spring boot application. In order to protect my rest APIs, i have implemented spring boot authorization server to provide oauth2 tokens to users. Currently i have users in master database under the table users. Authorization server is authenticating users from the authorization database under its users table. Do i need to migrate all my users from my master database to authorization server database? or should i call an API to user service and authenticate users?</p>

答:
This depends on your overall architecture, but in General you do not need to migrate users, you can check the permissions of users by calling the API of the service that stores these users.

In my opinion, this is the preferred way to divide microservices into an authentication/authorization microservice and a user information storage microservice, since user information is not related to authentication/authorization and has low connectivity, so you can easily change the authentication/authorization microservice in the future.

But there are also opposite points of view, in favor of combining authentication/authorization microservices and user storage. The main advantage of this approach is the simplicity of managing and supporting a single microservice.


问:
Use Laravel Eloquent joining
Hello I want to retrieve only rows of quizzes that the student didn't take yet
When he completes a quiz the variable done in QuizStudent table is going to become 1

Quiz table

My relationships:
Quiz Modal:

```<code> public function quizstudents(){
        return $this->hasMany('App\Quizstudent');

    }
</code>```

QuizStudent Modal:

```<code>  public function quiz(){
        return $this->belongsTo('App\Quiz','quiz_id');

    }
</code>```

I tried to do it using Query Builder It's working

```<code> $idUser = Auth::User()->id;
        $quizs= DB::table('quizzes')
       ->join('quizstudents', 'quizzes.id', '=', 'quizstudents.quizze_id')
       ->select('quizzes.id')
       ->where([['quizstudents.student_id','=',$idUser],['quizstudents.done','=','0']])

       ->distinct()
        ->get();
</code>```

but the problem is that I get the error on my view

Undefined property: stdClass::$classe

Because in view I use Eloquent style example: $quiz->answer and because I want to use paginate etc ..

So i tried to convert the QueryBuilder code above to eloquent I tried this:

```<code>   $quizs= Quiz::with('quizstudents')->whereIn('classe_id', $classes)->where([['quizstudents.student_id','=',$idUser],['quizstudents.done','=','0']])->orderBy('created_at','desc')->paginate(10);
</code>```

But I get the error

```<code>Column not found: 1054 Unknown column 'quizstudents.student_id' in 'where clause' (SQL: select count(*) as aggregate from `quizzes` where `classe_id` in (1) and (`quizstudents`.`student_id` = 79 and `quizstudents`.`done` = 0))
</code>```

Thank you for your time and sorry in advance

Edit: The two answers in bottom are amazing they are both working
  thanks for the  people who helped, please don't miss the part to set
  up your foreign key in the relationship if it's different than what's
  normal  A little explanation I created the modal Quiz and the
  migration and controller in the same time using modal:make Quiz -mc
  And didn't realise that the plural of quiz is quizzes so when I've set
  the foreign key I thoughet about quizze_id will be the default but
  Laravel is too smart and know that it should be quiz_id as default,
  the luck on english can hurt you beware of this  And sorry for my bad
  english

答:
You are not joining you Eloquent model, if you join would also get more rows than expected, you solve that by using distinct. An easy sub query solution, is to use whereHas() instead.

```<code>Quiz::with('quizstudents')
    ->whereIn('classe_id', $classes)
    ->whereHas('quizstudents', function ($query) use ($idUser) {
        $query->where('student_id', $idUser);
        $query->where('quizstudents.done', '0');
    })
    ->orderBy('created_at','desc')
    ->paginate(10);
</code>```

This is not faster than joins, but achieves it fairly simple and for a start in my opinion is the way to go.

Title: Use Laravel Eloquent joining

Body:
Hello I want to retrieve only rows of quizzes that the student didn't take yet
When he completes a quiz the variable done in QuizStudent table is going to become 1

Quiz table

My relationships:
Quiz Modal:

 public function quizstudents(){
        return $this->hasMany('App\Quizstudent');

    }

QuizStudent Modal:

  public function quiz(){
        return $this->belongsTo('App\Quiz','quiz_id');

    }

I tried to do it using Query Builder It's working

 $idUser = Auth::User()->id;
        $quizs= DB::table('quizzes')
       ->join('quizstudents', 'quizzes.id', '=', 'quizstudents.quizze_id')
       ->select('quizzes.id')
       ->where([['quizstudents.student_id','=',$idUser],['quizstudents.done','=','0']])

       ->distinct()
        ->get();

but the problem is that I get the error on my view

Undefined property: stdClass::$classe

Because in view I use Eloquent style example: $quiz->answer and because I want to use paginate etc ..

So i tried to convert the QueryBuilder code above to eloquent I tried this:

   $quizs= Quiz::with('quizstudents')->whereIn('classe_id', $classes)->where([['quizstudents.student_id','=',$idUser],['quizstudents.done','=','0']])->orderBy('created_at','desc')->paginate(10);

But I get the error

Column not found: 1054 Unknown column 'quizstudents.student_id' in 'where clause' (SQL: select count(*) as aggregate from `quizzes` where `classe_id` in (1) and (`quizstudents`.`student_id` = 79 and `quizstudents`.`done` = 0))

Thank you for your time and sorry in advance

Edit: The two answers in bottom are amazing they are both working
  thanks for the  people who helped, please don't miss the part to set
  up your foreign key in the relationship if it's different than what's
  normal  A little explanation I created the modal Quiz and the
  migration and controller in the same time using modal:make Quiz -mc
  And didn't realise that the plural of quiz is quizzes so when I've set
  the foreign key I thoughet about quizze_id will be the default but
  Laravel is too smart and know that it should be quiz_id as default,
  the luck on english can hurt you beware of this  And sorry for my bad
  english

Body:
You are not joining you Eloquent model, if you join would also get more rows than expected, you solve that by using distinct. An easy sub query solution, is to use whereHas() instead.

Quiz::with('quizstudents')
    ->whereIn('classe_id', $classes)
    ->whereHas('quizstudents', function ($query) use ($idUser) {
        $query->where('student_id', $idUser);
        $query->where('quizstudents.done', '0');
    })
    ->orderBy('created_at','desc')
    ->paginate(10);

This is not faster than joins, but achieves it fairly simple and for a start in my opinion is the way to go.


问:
webrtc onicecandidate not called on opera browser
I have a problem, my onicecandidate event is not being fired in opera browser, here is my code

I tried me getUserMedia added the stream to RTCPeerConnection in different ways (via addStream and addTrack), set offerToReceiveAudio and offerToReceiveVideo, none of this helped

CODE

```<code>const RTCPeerConnection =  window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
const RTCSessionDescription = window.RTCSessionDescription || window.mozRTCSessionDescription || window.RTCSessionDescription;
const RTCIceCandidate = window.mozRTCIceCandidate || window.RTCIceCandidate;

const mediaConstraints = {
    offerToReceiveAudio: true,
    offerToReceiveVideo: false
}

const options = {
    iceServers: [
        {
          urls: 'turn:74.11.232.11:3478',
          credential: 'password',
          username: 'username'
        }
    ],
};

function getUserMedia(callback) {
    navigator.mediaDevices.getUserMedia({
        audio: true,
        video: false
    }).then(callback);
}

getUserMedia((stream) => {
     localStream = stream

     localStream.getAudioTracks()[0].enabled = false

     WebRtcPeerConnection = new RTCPeerConnection(options)

     WebRtcPeerConnection.addStream(stream)

     WebRtcPeerConnection.createOffer(mediaConstraints).then((offer) => {
         console.log(offer.sdp)
         WebRtcPeerConnection.setLocalDescription(offer);
         WebRtcPeerConnection.onicecandidate = onRoomIceCandidate
         onRoomOffer(null, offer)
     });
})
</code>```

答:
My mistake was to declare the constant RTCPeerConnection, as I understood in Opera browser RTCPeerConnection is a global class (which is not in window.RTCPeerConnection, etc.)
I needed to replace this line

const RTCPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;

to this

const RTCPeerConnection = RTCPeerConnection || window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;

Body:
I have a problem, my onicecandidate event is not being fired in opera browser, here is my code

I tried me getUserMedia added the stream to RTCPeerConnection in different ways (via addStream and addTrack), set offerToReceiveAudio and offerToReceiveVideo, none of this helped

CODE

const RTCPeerConnection =  window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
const RTCSessionDescription = window.RTCSessionDescription || window.mozRTCSessionDescription || window.RTCSessionDescription;
const RTCIceCandidate = window.mozRTCIceCandidate || window.RTCIceCandidate;

const mediaConstraints = {
    offerToReceiveAudio: true,
    offerToReceiveVideo: false
}

const options = {
    iceServers: [
        {
          urls: 'turn:74.11.232.11:3478',
          credential: 'password',
          username: 'username'
        }
    ],
};

function getUserMedia(callback) {
    navigator.mediaDevices.getUserMedia({
        audio: true,
        video: false
    }).then(callback);
}

getUserMedia((stream) => {
     localStream = stream

     localStream.getAudioTracks()[0].enabled = false

     WebRtcPeerConnection = new RTCPeerConnection(options)

     WebRtcPeerConnection.addStream(stream)

     WebRtcPeerConnection.createOffer(mediaConstraints).then((offer) => {
         console.log(offer.sdp)
         WebRtcPeerConnection.setLocalDescription(offer);
         WebRtcPeerConnection.onicecandidate = onRoomIceCandidate
         onRoomOffer(null, offer)
     });
})


问:
Redirect requests to / that come from /subdirectory to go to /subdirectory
I have the following folder structure:

```<code>/
    index.html
    /sub
        index.html
        dist/...
</code>```

When visiting the url /sub there are some resources in /sub/dist that are being requested from /dist instead of /sub/dist. Obviously this results in a 404.

I need to rewrite ONLY those requests that come from under /sub to actually go to /sub, rather than from the root url.

答:
I found a solution:

First, I check if the referrer came from my subdirectory:

```<code>RewriteCond %{HTTP_REFERER} /sub
</code>```

Then, I check if it has /sub in it's URI:

```<code>RewriteCond %{REQUEST_URI} !^/driving/
</code>```

Finally, I add in /sub to the url:

```<code>RewriteRule ^(.*)$ /sub/$1 [L]
</code>```

Body:
I have the following folder structure:

/
    index.html
    /sub
        index.html
        dist/...

When visiting the url /sub there are some resources in /sub/dist that are being requested from /dist instead of /sub/dist. Obviously this results in a 404.

I need to rewrite ONLY those requests that come from under /sub to actually go to /sub, rather than from the root url.

Body:
I found a solution:

First, I check if the referrer came from my subdirectory:

RewriteCond %{HTTP_REFERER} /sub

Then, I check if it has /sub in it's URI:

RewriteCond %{REQUEST_URI} !^/driving/

Finally, I add in /sub to the url:

RewriteRule ^(.*)$ /sub/$1 [L]


问:
Class view with post, get and data
I have practically finished the microblogging application and I want to change to class base views now. I read about generic views, but it looks like each of them has specific properties. In my index view I display two models and two forms, so I created IndexView (View) and put the get and post functions there and it works, but it doesn't look like there are any benefits of class views, so I'm probably doing something wrong. Currently, several views repeat a lot of code, and I thought that class views would solve this problem. I would like an example of how such a view should be written as class view with reusable get.</p>

```<code>class IndexView(View):

    def get(self, request, *args, **kwargs):
        post_form = AddPostForm()
        comment_form = AddCommentForm()
        if request.user.is_authenticated:
            logged_user = CustomUser.objects.get(id=request.user.id)
            blocked_users = logged_user.blocked.all()
            posts = Post.objects.exclude(author__in=blocked_users)
            print(blocked_users)
            posts = posts.order_by('-pub_date')
        else:
            posts = Post.objects.all()
            posts = posts.order_by('-pub_date')

        comments = Comment.objects.all()
        comments = comments.order_by("-pub_date")

        return render(request, 'mikroblog/index.html', {'posts': posts, 'comments': comments,
                                                    'post_form': post_form, 'comment_form': comment_form})

    def post(self, request, *args, **kwargs):
        if request.method == 'POST':
            post_form = AddPostForm(request.POST)
            comment_form = AddCommentForm(request.POST)
            if post_form.is_valid():
                new_post = post_form.save(commit=False)
                new_post.author = request.user
                new_post.tags = ''
                content = ''
                for word in new_post.content_post.split():
                    if '#' in word:
                        new_post.tags += f"{word} "
                        content += f"{word} "
                    else:
                        content += f"{word} "

                new_post.content_post = content
                new_post.save()

                for word in content.split():
                    if '@' in word:
                        print(word)
                        user_to_notificate = CustomUser.objects.get(username=word[1:])

                        new_notification = TalkAbout()
                        new_notification.where = new_post
                        new_notification._from = new_post.author
                        new_notification.to = user_to_notificate
                        new_notification.sended = False
                        print(new_notification)
                        new_notification.save()

                post_form = AddPostForm()

            if comment_form.is_valid():
                new_comment = comment_form.save(commit=False)
                new_comment.author = request.user
                new_comment.save()
                comment_form = AddCommentForm()

            return HttpResponseRedirect(reverse('index'))
</code>```

答:
Use class-based views and override the 'post' and 'get' methods if you need to.
Follow this link:
Django CBVs documentation</p>

Title: Class view with post, get and data

Body:
I have practically finished the microblogging application and I want to change to class base views now. I read about generic views, but it looks like each of them has specific properties. In my index view I display two models and two forms, so I created IndexView (View) and put the get and post functions there and it works, but it doesn't look like there are any benefits of class views, so I'm probably doing something wrong. Currently, several views repeat a lot of code, and I thought that class views would solve this problem. I would like an example of how such a view should be written as class view with reusable get.

class IndexView(View):

    def get(self, request, *args, **kwargs):
        post_form = AddPostForm()
        comment_form = AddCommentForm()
        if request.user.is_authenticated:
            logged_user = CustomUser.objects.get(id=request.user.id)
            blocked_users = logged_user.blocked.all()
            posts = Post.objects.exclude(author__in=blocked_users)
            print(blocked_users)
            posts = posts.order_by('-pub_date')
        else:
            posts = Post.objects.all()
            posts = posts.order_by('-pub_date')

        comments = Comment.objects.all()
        comments = comments.order_by("-pub_date")

        return render(request, 'mikroblog/index.html', {'posts': posts, 'comments': comments,
                                                    'post_form': post_form, 'comment_form': comment_form})

    def post(self, request, *args, **kwargs):
        if request.method == 'POST':
            post_form = AddPostForm(request.POST)
            comment_form = AddCommentForm(request.POST)
            if post_form.is_valid():
                new_post = post_form.save(commit=False)
                new_post.author = request.user
                new_post.tags = ''
                content = ''
                for word in new_post.content_post.split():
                    if '#' in word:
                        new_post.tags += f"{word} "
                        content += f"{word} "
                    else:
                        content += f"{word} "

                new_post.content_post = content
                new_post.save()

                for word in content.split():
                    if '@' in word:
                        print(word)
                        user_to_notificate = CustomUser.objects.get(username=word[1:])

                        new_notification = TalkAbout()
                        new_notification.where = new_post
                        new_notification._from = new_post.author
                        new_notification.to = user_to_notificate
                        new_notification.sended = False
                        print(new_notification)
                        new_notification.save()

                post_form = AddPostForm()

            if comment_form.is_valid():
                new_comment = comment_form.save(commit=False)
                new_comment.author = request.user
                new_comment.save()
                comment_form = AddCommentForm()

            return HttpResponseRedirect(reverse('index'))


问:
Apache Solr Search for Distance Calculation
Hi I am using Apache solr v8

I need to calculate distance between n-dim vector in query search,
how could i do that.

Because I need to calculate distance between face encoding vectors in python's Face_recognition module

答:
Edit:
There is a dist function in Solr, see answer provided by the original poster.

Approximate Near Neighbor (ANN) vector search is not yet natively supported in Solr. There is an ongoing effort to integrate it in both Solr and Lucene. You can find a detailed analysis and track progress on this Solr Jira ticket: https://issues.apache.org/jira/browse/SOLR-14397

There is also a section "Note on Prior Approaches" on the ticket that summarizes the solutions/workarounds so far for that problem.


问:
PHP randomly assign people to a team
I'm currently building up a little game, where users need to be randomly assigned to teams.

What I got is a table in the database, where the logged in users are listed. Also, each user has a column for the team.

Now in PHP, I got all users stored in a variable, like the following (output of var_export)

```<code>array ( 0 => array ( 'ID' => '3', 'name' => 'olaf', 'team' => NULL, ), 1 => array ( 'ID' => '4', 'name' => 'Peter', 'team' => NULL, ), 2 => array ( 'ID' => '5', 'name' => 'chris', 'team' => NULL, ), 3 => array ( 'ID' => '6', 'name' => 'günther', 'team' => NULL, ), )
</code>```

Now I got two teams, Team Red and Team Blue. My goal is, that every person has randomly been assigned to one of the two teams, however, both teams should have a similar amount of team members (or if an odd number of users is logged in, one team can have one more player).

When assigned, I would then write the information to the database. However, I'd like to always be able to shuffle the teams and then have new teams.

The number of logged in users can vary between 2 and 50 persons.

So far, I thought about multiple ways of doing it, like randomly picking a number between 1 and sizeof(array of users) and then assigning him a team, however, I couldn't get it to work...

Also I this Stackoverflow post, however, using this code, my team Red always had player 1 and 3 or 1 and 4 and my team Blue always had player 2 and 3 or 2 and 4. It never happened, that player 1 was in team red. However, as mentioned, the mix should be completely random.

Can anybody help me out with this or has an idea, how I could manage to do that?

答:
This would be an example:

```<code><?php

// just preparing the set of players for the demonstration
$numberOfPLayers = 6;
$players = [];
for ($i = 0; $i < $numberOfPLayers; $i++) {
    $players[] = [
        'id' => $i,
        'name' => sprintf("Player %d", $i + 1),
        'team' => null
    ];
}

// here starts the actual assignment
shuffle($players);

array_walk($players, function(&$player, $index) {
    $player['team'] = $index % 2 ? "Red" : "Blue";
});

usort($players, function($a, $b) {
    return $a['id'] <=> $b['id'];
});

// just a test output of the set of players
print_r($players);
</code>```

The code snippet creates a list of players, you can play around with the number of players. It first shuffles the players, then assigns teams alternatingly, so evenly and finally again sorts the set of players.

One possible output is (depends on the randomizing shuffle of course):

```<code>Array
(
    [0] => Array
        (
            [id] => 0
            [name] => Player 1
            [team] => Blue
        )

    [1] => Array
        (
            [id] => 1
            [name] => Player 2
            [team] => Red
        )

    [2] => Array
        (
            [id] => 2
            [name] => Player 3
            [team] => Red
        )

    [3] => Array
        (
            [id] => 3
            [name] => Player 4
            [team] => Blue
        )

    [4] => Array
        (
            [id] => 4
            [name] => Player 5
            [team] => Red
        )

    [5] => Array
        (
            [id] => 5
            [name] => Player 6
            [team] => Blue
        )

)
</code>```

Title: PHP randomly assign people to a team

Body:
I'm currently building up a little game, where users need to be randomly assigned to teams.

What I got is a table in the database, where the logged in users are listed. Also, each user has a column for the team.

Now in PHP, I got all users stored in a variable, like the following (output of var_export)

array ( 0 => array ( 'ID' => '3', 'name' => 'olaf', 'team' => NULL, ), 1 => array ( 'ID' => '4', 'name' => 'Peter', 'team' => NULL, ), 2 => array ( 'ID' => '5', 'name' => 'chris', 'team' => NULL, ), 3 => array ( 'ID' => '6', 'name' => 'günther', 'team' => NULL, ), )

Now I got two teams, Team Red and Team Blue. My goal is, that every person has randomly been assigned to one of the two teams, however, both teams should have a similar amount of team members (or if an odd number of users is logged in, one team can have one more player).

When assigned, I would then write the information to the database. However, I'd like to always be able to shuffle the teams and then have new teams.

The number of logged in users can vary between 2 and 50 persons.

So far, I thought about multiple ways of doing it, like randomly picking a number between 1 and sizeof(array of users) and then assigning him a team, however, I couldn't get it to work...

Also I this Stackoverflow post, however, using this code, my team Red always had player 1 and 3 or 1 and 4 and my team Blue always had player 2 and 3 or 2 and 4. It never happened, that player 1 was in team red. However, as mentioned, the mix should be completely random.

Can anybody help me out with this or has an idea, how I could manage to do that?

Body:
This would be an example:

<?php

// just preparing the set of players for the demonstration
$numberOfPLayers = 6;
$players = [];
for ($i = 0; $i < $numberOfPLayers; $i++) {
    $players[] = [
        'id' => $i,
        'name' => sprintf("Player %d", $i + 1),
        'team' => null
    ];
}

// here starts the actual assignment
shuffle($players);

array_walk($players, function(&$player, $index) {
    $player['team'] = $index % 2 ? "Red" : "Blue";
});

usort($players, function($a, $b) {
    return $a['id'] <=> $b['id'];
});

// just a test output of the set of players
print_r($players);

The code snippet creates a list of players, you can play around with the number of players. It first shuffles the players, then assigns teams alternatingly, so evenly and finally again sorts the set of players.

One possible output is (depends on the randomizing shuffle of course):

Array
(
    [0] => Array
        (
            [id] => 0
            [name] => Player 1
            [team] => Blue
        )

    [1] => Array
        (
            [id] => 1
            [name] => Player 2
            [team] => Red
        )

    [2] => Array
        (
            [id] => 2
            [name] => Player 3
            [team] => Red
        )

    [3] => Array
        (
            [id] => 3
            [name] => Player 4
            [team] => Blue
        )

    [4] => Array
        (
            [id] => 4
            [name] => Player 5
            [team] => Red
        )

    [5] => Array
        (
            [id] => 5
            [name] => Player 6
            [team] => Blue
        )

)


问:
Can we say “If an API is following 6 constraints of REST then it’s a RESTful API”?
Can we say “If an API is following 6 constraints of REST then it’s a RESTful API”?
or my statement is completely wrong?</p>

答:
Can we say “If an API is following 6 constraints of REST then it’s a RESTful API”? or my statement is completely wrong?

You probably need to be detailed about the nature of the "uniform interface" constraint:

REST is defined by four interface constraints: identification of resources; manipulation of resources through representations; self-descriptive messages; and, hypermedia as the engine of application state.

See also REST APIs Must be Hypertext Driven (Fielding 2008).


问:
How to use a custom helper via the "helper" method in Rails 3?
I'm trying to create a custom helper like this:

```<code># app/controllers/my_controller.rb
class MyController < ApplicationController
  helper :my
  def index
    puts foo
  end
end

# app/helpers/my_helper.rb
module MyHelper
  def foo
    "Hello"
  end
end
</code>```

But, I got the following error:

```<code>undefined local variable or method `foo' for #<MyController:0x20e01d0>
</code>```

What am I missing ?

答:
Generally, I do the opposite: I use controller methods as helpers.</p>

```<code>class MyController < ApplicationController
  helper_method :my_helper

  private
  def my_helper
    "text"
  end
end
</code>```

Body:
I'm trying to create a custom helper like this:

# app/controllers/my_controller.rb
class MyController < ApplicationController
  helper :my
  def index
    puts foo
  end
end

# app/helpers/my_helper.rb
module MyHelper
  def foo
    "Hello"
  end
end

But, I got the following error:

undefined local variable or method `foo' for #<MyController:0x20e01d0>

What am I missing ?

Body:
Generally, I do the opposite: I use controller methods as helpers.

class MyController < ApplicationController
  helper_method :my_helper

  private
  def my_helper
    "text"
  end
end


问:
Cordova Build ios
Im trying to peacefully compile a cordova project, and its throwing an error of

error: No profile for team '[TEAM_ID]' matching 'APP Development' found: Xcode couldn't find any provisioning profiles matching '[TEAM_ID]/APP Development'. Install the profile (by dragging and dropping it onto Xcode's dock item) or select a different one in the Signing & Capabilities tab of the target editor. (in target 'APP' from project 'APP')

Ive done everything from cleaning the build to everything. When i run the app on Xcode it runs smooth and it builds perfectly! Also was able to deploy to TestFlight perfectly. This issue only occurs when i run it through Terminal sudo cordova build ios

Where do i "drag and drop" file?

If anyone has solved this issue please help me. Im running Cordova ios 5.1.1.

答:
Xcode saying you need to set

Team

Provisioning profile.

open Xcode

click on your a project

select targets click on your project

select(Siging&Capabilities)on topbar

In Sigigng part you need to select team and p.profile.

Title: Cordova Build ios


问:
MutationObserver on dynamic child content
I'm working on a Prestashop site project with a particularly fiddly megamenu setup.

The MutationObserver does a pretty good job of pushing the menu back when the cart overlay is open, but the issue if the menu is dynamically pulled in by another JavaScript library that is obfusticated beyond any rescue and as such the MutationObserver gets unlinked from the node each time, causing everything to be drawn incorrectly if anything is added to the cart after page load.

The MutationObserver is currently linked directly to the main page container object (category).

```<code>//  CREATE A MUTATION OBSERVER OBJECT TO MONITOR ANY STATE CHANGES ON THE JS NODE
    let observer = new MutationObserver(blockCartOpened);

    function blockCartOpened(mutationRecords) {
    //  PROCESS THE LIST OF MUTATION THAT HAVE OCCURED
        mutationRecords.forEach (function (mutation) {
        //  GET THE MUTATION TARGET AND SEE IF THE DISPLAY STYLE ATTRIBUTE IS SET OR NOT
        //  AND REACT ACCORDINGLY
            var target = $(mutation.target);
            if(target.hasClass("cart_block")) {
                if(target.css("display") == "block") {
                    $(".ets_mm_megamenu").css("z-index", "-1");
                } else {
                    $(".ets_mm_megamenu").css("z-index", "2");
                }
            }
            mutation.addedNodes.forEach(function(node) {
            //  Nothing to be here yet...
            });
        });
    }

//  SET THE TARGETNODE AS WELL AS THE SETTINGS FOR WHAT TO TRIGGER THE OBSERVER ON, IN THIS CASE
//  TRIGGER THE OBSERVER ON ANY CHANGES TO THE STYLE ATTRIBURES OF THE NODE
    var targetNodes = document.getElementById("category");
    var observerOptions = {
        childList: true,
        subtree: true,
        attributes: true,
        attributeFilter: ["style"]
    }

//  SINCE THIS IS A CLASS, A EACH LOOP IS REQUIRED EVEN IF THERE IS ONLY ONE RESULT
    observer.observe(targetNodes, observerOptions);
</code>```

Is there a way to monitor for the attribute changes on created child nodes inside the parent, or is this just a pipe dream?

答:
Well in the end I didn't have to use a MutationObserver, since the issue proved to be unsuited for that sort of solution. So I took the path of least resistence, i.e the solution isn't elegant but it works PERFECTLY:

```<code>//  BPK: CODE ADDITIONS
    $(document).on("click", function(event) {
        var target = $(".blockcart-header");
        if(target.hasClass("open")) {
            $(".ets_mm_megamenu").css("z-index", "-1");
        } else {
            $(".ets_mm_megamenu").css("z-index", "2");
        }
    });

    $(document).on("click", ".blockcart-header a", function(event) {
        var target = $(".blockcart-header");
        if(target.hasClass("open")) {
            $(".ets_mm_megamenu").css("z-index", "-1");
        } else {
            $(".ets_mm_megamenu").css("z-index", "2");
        }
    });
//  END BPK
</code>```

Using a document wide click event to monitor for "closing" clicks and a click event on the trigger button for the cart display just to be sure solved the problem for me.

Lesson: Don't try to go too complicated to solve a problem...

Body:
I'm working on a Prestashop site project with a particularly fiddly megamenu setup.

The MutationObserver does a pretty good job of pushing the menu back when the cart overlay is open, but the issue if the menu is dynamically pulled in by another JavaScript library that is obfusticated beyond any rescue and as such the MutationObserver gets unlinked from the node each time, causing everything to be drawn incorrectly if anything is added to the cart after page load.

The MutationObserver is currently linked directly to the main page container object (category).

//  CREATE A MUTATION OBSERVER OBJECT TO MONITOR ANY STATE CHANGES ON THE JS NODE
    let observer = new MutationObserver(blockCartOpened);

    function blockCartOpened(mutationRecords) {
    //  PROCESS THE LIST OF MUTATION THAT HAVE OCCURED
        mutationRecords.forEach (function (mutation) {
        //  GET THE MUTATION TARGET AND SEE IF THE DISPLAY STYLE ATTRIBUTE IS SET OR NOT
        //  AND REACT ACCORDINGLY
            var target = $(mutation.target);
            if(target.hasClass("cart_block")) {
                if(target.css("display") == "block") {
                    $(".ets_mm_megamenu").css("z-index", "-1");
                } else {
                    $(".ets_mm_megamenu").css("z-index", "2");
                }
            }
            mutation.addedNodes.forEach(function(node) {
            //  Nothing to be here yet...
            });
        });
    }

//  SET THE TARGETNODE AS WELL AS THE SETTINGS FOR WHAT TO TRIGGER THE OBSERVER ON, IN THIS CASE
//  TRIGGER THE OBSERVER ON ANY CHANGES TO THE STYLE ATTRIBURES OF THE NODE
    var targetNodes = document.getElementById("category");
    var observerOptions = {
        childList: true,
        subtree: true,
        attributes: true,
        attributeFilter: ["style"]
    }

//  SINCE THIS IS A CLASS, A EACH LOOP IS REQUIRED EVEN IF THERE IS ONLY ONE RESULT
    observer.observe(targetNodes, observerOptions);

Is there a way to monitor for the attribute changes on created child nodes inside the parent, or is this just a pipe dream?

Body:
Well in the end I didn't have to use a MutationObserver, since the issue proved to be unsuited for that sort of solution. So I took the path of least resistence, i.e the solution isn't elegant but it works PERFECTLY:

//  BPK: CODE ADDITIONS
    $(document).on("click", function(event) {
        var target = $(".blockcart-header");
        if(target.hasClass("open")) {
            $(".ets_mm_megamenu").css("z-index", "-1");
        } else {
            $(".ets_mm_megamenu").css("z-index", "2");
        }
    });

    $(document).on("click", ".blockcart-header a", function(event) {
        var target = $(".blockcart-header");
        if(target.hasClass("open")) {
            $(".ets_mm_megamenu").css("z-index", "-1");
        } else {
            $(".ets_mm_megamenu").css("z-index", "2");
        }
    });
//  END BPK

Using a document wide click event to monitor for "closing" clicks and a click event on the trigger button for the cart display just to be sure solved the problem for me.

Lesson: Don't try to go too complicated to solve a problem...


问:
Why am I getting "validation failed" error?
I have a basic expressjs application. When I am trying to make a POST request I am always getting error, which says: "User validation failed: name: Path "name" is required., email: Path "email" is required., password: Path "password" is required."

My request(json):

```<code>[
   {
      "name":"test",
      "email":"test@gmail.com",
      "password":"testtest"
   }
]
</code>```

Controller:

```<code>router.post("/", (req, res) => {
  service.saveUser(req, res);
});
</code>```

Service (I think something here should be wrong):

```<code>const saveUser = async (req, res) => {
  console.log(req.body);
  const newUser = new User({
    name: req.body.name,
    email: req.body.email,
    password: req.body.password,
  });
  const savedUser = newUser.save();
  res.json(savedUser);
};
</code>```

And finally the User mode:

```<code>const Model = db.Schema({
  id: {
    type: Number,
    unique: true,
  },
  name: {
    type: String,
    required: true,
  },
  email: {
    type: String,
    required: true,
  },
  password: {
    type: String,
    required: true,
  },
});
</code>```

答:
You request

```<code>[
   {
      "name":"test",
      "email":"test@gmail.com",
      "password":"testtest"
   }
]
</code>```

but you should instead request

```<code>{
   "name":"test",
   "email":"test@gmail.com",
   "password":"testtest"
}
</code>```

Body:
I have a basic expressjs application. When I am trying to make a POST request I am always getting error, which says: "User validation failed: name: Path "name" is required., email: Path "email" is required., password: Path "password" is required."

My request(json):

[
   {
      "name":"test",
      "email":"test@gmail.com",
      "password":"testtest"
   }
]

Controller:

router.post("/", (req, res) => {
  service.saveUser(req, res);
});

Service (I think something here should be wrong):

const saveUser = async (req, res) => {
  console.log(req.body);
  const newUser = new User({
    name: req.body.name,
    email: req.body.email,
    password: req.body.password,
  });
  const savedUser = newUser.save();
  res.json(savedUser);
};

And finally the User mode:

const Model = db.Schema({
  id: {
    type: Number,
    unique: true,
  },
  name: {
    type: String,
    required: true,
  },
  email: {
    type: String,
    required: true,
  },
  password: {
    type: String,
    required: true,
  },
});

Body:
You request

[
   {
      "name":"test",
      "email":"test@gmail.com",
      "password":"testtest"
   }
]

but you should instead request

{
   "name":"test",
   "email":"test@gmail.com",
   "password":"testtest"
}


问:
Update script not working and no error shows
I am a newbie updating the database (i have skipped some steps so that i do some things quicker) I have this code but the database does not update and i do not get any error.</p>

```<code><?php
require_once '../includes/configuration.php';

if (isset($_POST['enter']))
{
    $_POST['employee_id_passport'] = $employee_id_passport;
    $_POST['first_name'] = $first_name;
    $_POST['surname'] = $surname;
    $_POST['mobile_number'] = $mobile_number;
    $sql_query_update = "UPDATE employee_master
                             SET first_name = '$first_name',
                             surname = '$surname',
                             mobile_number = '$mobile_number'
                             WHERE employee_id_passport = '$employee_id_passport'";
            $result = mysql_query($sql_query_update, $connection);
    echo "this";

}
else
    {

            //display form with employee details
            if (isset($_GET['idno']))
            {
                $employee_id_passport = $_GET['idno'];

                $sql_get_employee_details_query = "SELECT * FROM employee_master WHERE employee_id_passport = '$employee_id_passport'";
                $result = mysql_query($sql_get_employee_details_query, $connection);
                $row = mysql_fetch_assoc($result);
                echo $row['employee_id_passport'] . "<br /> " . $row['surname'] . "<br /> " . $row['first_name'] . "<br /> " . $row['mobile_number'] . "<br /> ";

                echo "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"";
                echo "\"http:www.w3.org/TR/xhthml1/DTD/xhtml1-transitional.dtd\">";

                echo "<html xmls=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\">";

                echo "<head>";
                echo    "<title> </title>";

                echo    "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\" />";
                echo "</head>";

                echo "<body>";
                echo   "<form name=\"view_employee\" method=\"POST\" action=\"" .  $_SERVER['PHP_SELF'] . " \"   />";
                echo        "Employee ID/Passport: <input type=\"text\" name=\"id_passport\" disabled=\"disabled\" value=\" " .  $row['employee_id_passport'] . "\" /> <br />";
                echo        "First Name: <input type=\"text\" name=\"first_name\" value=\" ".  $row['first_name'] .  "\" /> <br />";
                echo        "Surname: <input type=\"text\" name=\"surname\" value=\" " .  $row['surname'] . "\" /> <br />";
                echo        "Mobile Number: <input type=\"text\" name=\"mobile_number\" value=\" " .   $row['mobile_number'] . "\"/> <br />";
                echo        "<input type=\"submit\" value=\"enter\" name=\"submit\" />";
                echo    "</form>";
                echo "</body>";

                echo "<html>";
            }
    }

?>
</code>```

答:
You're not executing the update query. Add this before the echo "this" line

```<code>if (false === mysql_query($sql_query_update)) {
    throw new Exception(mysql_error());
}
</code>```

Your script is also vulnerable to SQL injection... you know what, I'm tired of spouting this line. Read up on SQL Injection and use PDO, prepared statements and parameter binding.

Body:
I am a newbie updating the database (i have skipped some steps so that i do some things quicker) I have this code but the database does not update and i do not get any error.

<?php
require_once '../includes/configuration.php';

if (isset($_POST['enter']))
{
    $_POST['employee_id_passport'] = $employee_id_passport;
    $_POST['first_name'] = $first_name;
    $_POST['surname'] = $surname;
    $_POST['mobile_number'] = $mobile_number;
    $sql_query_update = "UPDATE employee_master
                             SET first_name = '$first_name',
                             surname = '$surname',
                             mobile_number = '$mobile_number'
                             WHERE employee_id_passport = '$employee_id_passport'";
            $result = mysql_query($sql_query_update, $connection);
    echo "this";

}
else
    {

            //display form with employee details
            if (isset($_GET['idno']))
            {
                $employee_id_passport = $_GET['idno'];

                $sql_get_employee_details_query = "SELECT * FROM employee_master WHERE employee_id_passport = '$employee_id_passport'";
                $result = mysql_query($sql_get_employee_details_query, $connection);
                $row = mysql_fetch_assoc($result);
                echo $row['employee_id_passport'] . "
 " . $row['surname'] . "
 " . $row['first_name'] . "
 " . $row['mobile_number'] . "
 ";

                echo "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"";
                echo "\"http:www.w3.org/TR/xhthml1/DTD/xhtml1-transitional.dtd\">";

                echo "";

                echo "";
                echo    "<title> </title>";

                echo    "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\" />";
                echo "";

                echo "";
                echo   "<form name=\"view_employee\" method=\"POST\" action=\"" .  $_SERVER['PHP_SELF'] . " \"   />";
                echo        "Employee ID/Passport: <input type=\"text\" name=\"id_passport\" disabled=\"disabled\" value=\" " .  $row['employee_id_passport'] . "\" />
";
                echo        "First Name: <input type=\"text\" name=\"first_name\" value=\" ".  $row['first_name'] .  "\" />
";
                echo        "Surname: <input type=\"text\" name=\"surname\" value=\" " .  $row['surname'] . "\" />
";
                echo        "Mobile Number: <input type=\"text\" name=\"mobile_number\" value=\" " .   $row['mobile_number'] . "\"/>
";
                echo        "<input type=\"submit\" value=\"enter\" name=\"submit\" />";
                echo    "</form>";
                echo "";

                echo "";
            }
    }

?>

Body:
You're not executing the update query. Add this before the echo "this" line

if (false === mysql_query($sql_query_update)) {
    throw new Exception(mysql_error());
}

Your script is also vulnerable to SQL injection... you know what, I'm tired of spouting this line. Read up on SQL Injection and use PDO, prepared statements and parameter binding.


问:
Adding Text beneath each column 4X4 using CSS GRID
I am very new to CSS Grid and am trying to create a 2 X 2 grid. I am able to create the four image divs ( 2 on each row and 2 on each column) but I want the text to appear underneath each one. I have tried to use the grid-template-areas property but all the text just appears under one div all overlapped.

Any help would be appreciated, please.

.image {
  width: 526px;
  height: 360px;
  border: 1px solid #000;
  border-radius: 10px;
  margin-top: 35px;
  margin-bottom: 35px;
}

.grid-container {
  display: grid;
  grid-template-rows: auto;
  grid-template-columns: 1fr 1fr;
  column-gap: 10px;
  row-gap: 1em;
  grid-template-areas: "image image " "text text";
}

.text {
  grid-area: text;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="banner">
  <div class="wrapper">
    <div class="grid-container">
      <div class="image"></div>
      <p class="text">TEXT 1</p>
      <div class="image"></div>
      <p class="text">
        TEXT 2
      </p>
      <div class="image"></div>
      <p class="text">TEXT 3</p>
      <div class="image"></div>
      <p class="text">TEXT 4</p>
    </div>
  </div>
  <!-- wrapper -->

</div>
<!-- banner --></code>```

答:
You can use nth-child() to correctly place your elements instead of grid-area:

.image {
  width: 200px;
  height: 150px;
  border: 1px solid #000;
  border-radius: 10px;
  margin-top: 35px;
  margin-bottom: 35px;
}

.grid-container {
  display: grid;
  grid-auto-flow: dense; /* this one is important to fill all the cells */
  grid-auto-columns: 1fr;
  column-gap: 10px;
}

.image:nth-child(4n + 3) {
  grid-column: 2;
}

.text:nth-child(4n + 2) {
  grid-column: 1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="banner">
  <div class="wrapper">
    <div class="grid-container">
      <div class="image"></div>
      <p class="text">TEXT 1</p>
      <div class="image"></div>
      <p class="text">TEXT 2</p>
      <div class="image"></div>
      <p class="text">TEXT 3</p>
      <div class="image"></div>
      <p class="text">TEXT 4</p>
    </div>
  </div>
</div></code>```

This will work even if you add more image/text:

.image {
  width: 200px;
  height: 150px;
  border: 1px solid #000;
  border-radius: 10px;
  margin-top: 35px;
  margin-bottom: 35px;
}

.grid-container {
  display: grid;
  grid-auto-flow: dense; /* this one is important to fill all the cells */
  grid-auto-columns: 1fr;
  column-gap: 10px;
}

.image:nth-child(4n + 3) {
  grid-column: 2;
}

.text:nth-child(4n + 2) {
  grid-column: 1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="banner">
  <div class="wrapper">
    <div class="grid-container">
      <div class="image"></div>
      <p class="text">TEXT 1</p>
      <div class="image"></div>
      <p class="text">TEXT 2</p>
      <div class="image"></div>
      <p class="text">TEXT 3</p>
      <div class="image"></div>
      <p class="text">TEXT 4</p>
      <div class="image"></div>
      <p class="text">TEXT 5</p>
      <div class="image"></div>
      <p class="text">TEXT 6</p>
      <div class="image"></div>
      <p class="text">TEXT 7</p>
      <div class="image"></div>
      <p class="text">TEXT 8</p>
    </div>
  </div>
</div></code>```

Body:
I am very new to CSS Grid and am trying to create a 2 X 2 grid. I am able to create the four image divs ( 2 on each row and 2 on each column) but I want the text to appear underneath each one. I have tried to use the grid-template-areas property but all the text just appears under one div all overlapped.

Any help would be appreciated, please.

.image {
  width: 526px;
  height: 360px;
  border: 1px solid #000;
  border-radius: 10px;
  margin-top: 35px;
  margin-bottom: 35px;
}

.grid-container {
  display: grid;
  grid-template-rows: auto;
  grid-template-columns: 1fr 1fr;
  column-gap: 10px;
  row-gap: 1em;
  grid-template-areas: "image image " "text text";
}

.text {
  grid-area: text;
}

TEXT 1

        TEXT 2

TEXT 3

TEXT 4

Body:
You can use nth-child() to correctly place your elements instead of grid-area:

.image {
  width: 200px;
  height: 150px;
  border: 1px solid #000;
  border-radius: 10px;
  margin-top: 35px;
  margin-bottom: 35px;
}

.grid-container {
  display: grid;
  grid-auto-flow: dense; /* this one is important to fill all the cells */
  grid-auto-columns: 1fr;
  column-gap: 10px;
}

.image:nth-child(4n + 3) {
  grid-column: 2;
}

.text:nth-child(4n + 2) {
  grid-column: 1;
}

<div class="banner">
  <div class="wrapper">
    <div class="grid-container">
      <div class="image"></div>
      <p class="text">TEXT 1</p>
      <div class="image"></div>
      <p class="text">TEXT 2</p>
      <div class="image"></div>
      <p class="text">TEXT 3</p>
      <div class="image"></div>
      <p class="text">TEXT 4</p>
    </div>
  </div>
</div>

This will work even if you add more image/text:

.image {
  width: 200px;
  height: 150px;
  border: 1px solid #000;
  border-radius: 10px;
  margin-top: 35px;
  margin-bottom: 35px;
}

.grid-container {
  display: grid;
  grid-auto-flow: dense; /* this one is important to fill all the cells */
  grid-auto-columns: 1fr;
  column-gap: 10px;
}

.image:nth-child(4n + 3) {
  grid-column: 2;
}

.text:nth-child(4n + 2) {
  grid-column: 1;
}

<div class="banner">
  <div class="wrapper">
    <div class="grid-container">
      <div class="image"></div>
      <p class="text">TEXT 1</p>
      <div class="image"></div>
      <p class="text">TEXT 2</p>
      <div class="image"></div>
      <p class="text">TEXT 3</p>
      <div class="image"></div>
      <p class="text">TEXT 4</p>
      <div class="image"></div>
      <p class="text">TEXT 5</p>
      <div class="image"></div>
      <p class="text">TEXT 6</p>
      <div class="image"></div>
      <p class="text">TEXT 7</p>
      <div class="image"></div>
      <p class="text">TEXT 8</p>
    </div>
  </div>
</div>


问:
Number of consumers in kafka comsumer-group
If a producer has 3 topics and 4 partitions each topic, should the consumer group contains 4 or 12 consumers?
I want to achieve ideal consumption.</p>

答:
If you have N partitions, then you can have up to N consumers within the same consumer group each of which reading from a single partition. When you have less consumers than partitions, then some of the consumers will read from more than one partition. Also, if you have more consumers than partitions then some of the consumers will be inactive and will receive no messages at all.

You cannot have multiple consumers -within the same consumer group- consuming data from a single partition. Therefore, in order to consume data from the same partition using N consumers, you'd need to create N distinct consumer groups too.

Note that partitioning enhances the parallelism within a Kafka cluster. If you create thousands of consumers to consume data from only one partition, I suspect that you will lose some level of parallelism.


问:
The system cannot find the path specified. (os error 3)
I am using deno for the first time and The system cannot find the path specified. (os error 3) is the error I am getting. My code below:-

```<code>import { Application } from 'https://deno.land/x/oak/mod.ts'

const app = new Application();
const port = 3000;

app.use((ctx) => {
    ctx.response.body = "Hello World"
})

app.listen({ port })
console.log(`localhost:${port}`)
</code>```

I am using deno run --allow-net .\server.js on powershell to start deno. Any help would be appreciated.

EDIT: If I try to do a simple console.log and run the file with deno run server.js it runs fine which mean that the deno environment is setup correctly. As soon as I add the import statement at the top, the error starts happening.

答:
The issue might be that you have a cached version of oak for an old version of deno.

do:

```<code>deno cache --reload server.js
</code>```

And then run your server again:

```<code>deno run --allow-net server.js
</code>```

It is considered a bad practice to use non-versioned URL, but in this case since there's no new version released yet for deno 1.0.3 you don't have a choice but to use master.

UPDATE: The error might be fixed by PR #6000

Body:
I am using deno for the first time and The system cannot find the path specified. (os error 3) is the error I am getting. My code below:-

import { Application } from 'https://deno.land/x/oak/mod.ts'

const app = new Application();
const port = 3000;

app.use((ctx) => {
    ctx.response.body = "Hello World"
})

app.listen({ port })
console.log(`localhost:${port}`)

I am using deno run --allow-net .\server.js on powershell to start deno. Any help would be appreciated.

EDIT: If I try to do a simple console.log and run the file with deno run server.js it runs fine which mean that the deno environment is setup correctly. As soon as I add the import statement at the top, the error starts happening.

Body:
The issue might be that you have a cached version of oak for an old version of deno.

do:

deno cache --reload server.js

And then run your server again:

deno run --allow-net server.js

It is considered a bad practice to use non-versioned URL, but in this case since there's no new version released yet for deno 1.0.3 you don't have a choice but to use master.

UPDATE: The error might be fixed by PR #6000


问:
how to auto login user
here is what i am  trying to do:

user logs in and check rember me.

user then closes the site.

next time the user visits the sites he is auto logged in withoutre-entring his user or password

thanks

using asp.net 3.5. using forms authentication

答:
Depending on your authentication model, I have a manual authentication process, by that i mean i Have a site whos entire authentication model has been coded from the ground up to suite the website.

No built in .net is used.

We hold an auto login feature in our cookie. The way this is done is by adding the login username and password to the cookie, but all key names and values in the cookie are encrypted with triple des encryption. So in the unlikely event the cookie is decrypted, they then face a triple des encryption to get the user credentials.

We have a handler that checks if the user is logged in on each request, various flags in the session are set to signify whats happening. eg you first land on the site, the handler checks for cookie support, if not provided a flag in the session signifies client doesnt support cookies and no further attempts are made. If it does support cookies the cookie is read, and if auto login is checked the credentials from the cookie are used to login.

It is easier to use the built in .net authentication model, but for ultimate control, DIY.

Title: how to auto login user