问:
Number of observations used by cor function in R
I have a big matrix in R with more than 2000 columns and 10,000 rows, and many missing values. This line of code calculates the correlation matrix in R.

cor(data, use = "complete.obs")

My question is: how can I find the number of observations that have been used to calculate each correlation in the output matrix?

The output should be something like this:

v1
v2
v3
v4

v1
20
12
15
18

v2
12
15
10
11

v3
15
10
25
20

v4
18
11
20
20

Thanks for any suggestion

Body:
Let's use a sample matrix data filled with random NAs:

library(dplyr)

set.seed(1234)
data <- rnorm(100) %>%
    matrix(nrow = 10) %>%
    {
        m <- .
        m[rnorm(100) > .5] <- NA
        m

    }

            [,1]       [,2]       [,3]        [,4]       [,5]       [,6]
 [1,] 0.48522682         NA  0.8951720 -0.32439330 0.05913517  0.4369306
 [2,] 0.69676878 -0.4002352  0.6602126          NA 0.41339889         NA
 [3,] 0.18551392  1.4934931  2.2734835 -0.93350334         NA  0.4521904
 [4,]         NA -1.6070809  1.1734976          NA         NA  0.6631986
 [5,] 0.31168103 -0.4157518  0.2877097  0.31916024 0.71888873 -1.1363736
 [6,] 0.76046236         NA -0.6597701 -1.07754212         NA         NA
 [7,] 1.84246363 -0.1517365         NA -3.23315213 1.35727444         NA
 [8,]         NA         NA  0.6774155          NA 0.40446847 -1.2239038
 [9,] 0.03266396 -0.3047211         NA  0.02951783 0.26436427  0.2580684
[10,]         NA  0.6295361  0.1864921  0.59427377 0.26804390         NA
            [,7]       [,8]       [,9]      [,10]
 [1,]         NA -0.3046139 -1.0118219         NA
 [2,]         NA  1.8250111  0.4701675  0.1832475
 [3,]  0.1586254  0.6705594 -0.7009703 -1.7662292
 [4,] -1.7632551  0.9486326         NA         NA
 [5,]  0.3385960  2.0494030         NA         NA
 [6,]         NA -0.6511136         NA         NA
 [7,] -0.2386466  0.8086193         NA -1.1750368
 [8,] -1.1877653  0.9865806 -0.2457632         NA
 [9,]  0.3849353         NA -1.5528590  0.3536254
[10,]         NA  0.3190524  0.1284340  0.3191562

You can transform it into a logical matrix dna where dna[i,j] == TRUE means that data[i,j] is not NA:

dna <- !is.na(data)

Then you can perform matrix product of dna with t(dna) to obtain the number of non-missing observations.

dna <- !is.na(data)

dna %*% t(dna)

      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
 [1,]    8    7    4    6    4    3    4    8    5     7
 [2,]    7    9    6    6    5    4    6    8    6     8
 [3,]    4    6    6    4    4    3    4    5    4     5
 [4,]    6    6    4    7    3    3    3    6    5     6
 [5,]    4    5    4    3    5    2    4    5    3     4
 [6,]    3    4    3    3    2    5    4    4    3     5
 [7,]    4    6    4    3    4    4    6    5    4     6
 [8,]    8    8    5    6    5    4    5    9    5     8
 [9,]    5    6    4    5    3    3    4    5    6     5
[10,]    7    8    5    6    4    5    6    8    5     9


来源: stackexchange

问:
Yocto recipe set hostname on raspberry
How can I set a hostname with Yocto recipe for raspberry pi 4?
I'am trying to set up a personalized hostname and hosts files on yocto raspberry image but I don't know how to do it.
Here is my file's examples.
"hosts"

```<code>pi@raspberrypi:/etc $ sudo vim hosts
127.0.0.1       localhost
::1             localhost ip6-localhost ip6-loopback
ff02::1         ip6-allnodes
ff02::2         ip6-allrouters

127.0.1.1       my_personalized_hostname
</code>```

and hostname

```<code>hostname
</code>```

Any helps? thanks.

答: Set hostname_pn-base-files = "your_hostname" in local.conf.

ContentLicense: CC BY-SA 4.0

Title: Yocto recipe set hostname on raspberry

Body:
How can I set a hostname with Yocto recipe for raspberry pi 4?
I'am trying to set up a personalized hostname and hosts files on yocto raspberry image but I don't know how to do it.
Here is my file's examples.
"hosts"

pi@raspberrypi:/etc $ sudo vim hosts
127.0.0.1       localhost
::1             localhost ip6-localhost ip6-loopback
ff02::1         ip6-allnodes
ff02::2         ip6-allrouters

127.0.1.1       my_personalized_hostname

and hostname

hostname

Any helps? thanks.


问:
Android, accessing internal sound files as resource IDs
I need to send some feedback to user by playing a click sound. I'm trying to use MediaPlayer.create () with built in OGG sound files, mainly  KeypressStandard.ogg.

How do I refer to these files as resource IDs?

答:
For anybody interested in this question, found a solution like this:

```<code>MediaPlayer mp = MediaPlayer.create(getApplicationContext(), Uri.parse("/system/media/audio/ui/Effect_Tick.ogg") );
mp.start();
</code>```

I fired this inside an AsyncTask where I do my visual feedback chores, in onPreExecute() I draw "selected" state, play click sound and  wait for 300mS. in onPostExecute(), I redraw object and free resources, works very nice, sample code:

```<code>private class FeedbackHandler extends AsyncTask<Void,Void,Void>{
    MediaPlayer mp;

    @Override
    protected Void doInBackground(Void... arg0) {
    return null;

    }

    @Override
    protected void onPostExecute(Void result) {
    super.onPostExecute(result);

    mp.release(); // free resources
    mp=null; // help GC
    myDrawUnselectedState(myObject); // draw normal state
    ImageView iv = (ImageView) findViewById(R.id.myobjectcontainer);
    iv.invalidate(); // mark UI for refresh
    }

    @Override
    protected void onPreExecute() {
    super.onPreExecute();

    myDrawSelectedState(myObject); // draw selected
    ImageView iv = (ImageView) findViewById(R.id.mycontainer);
    iv.invalidate(); // mark for refreshing
    mp = MediaPlayer.create(getApplicationContext(), Uri.parse("/system/media/audio/ui/Effect_Tick.ogg") );
    mp.start(); // play sound
    SystemClock.sleep(300); // wait a little bit for user to see effect
    }
}
</code>```

By the way, Effect_Tick.ogg its the one that fires when you press a button. It seems that these file names are pretty much Android standard, found in many different devices signed with Android copyright disclaimer.

ContentLicense: CC BY-SA 3.0

Body:
For anybody interested in this question, found a solution like this:

MediaPlayer mp = MediaPlayer.create(getApplicationContext(), Uri.parse("/system/media/audio/ui/Effect_Tick.ogg") );
mp.start();

I fired this inside an AsyncTask where I do my visual feedback chores, in onPreExecute() I draw "selected" state, play click sound and  wait for 300mS. in onPostExecute(), I redraw object and free resources, works very nice, sample code:

private class FeedbackHandler extends AsyncTask<Void,Void,Void>{
    MediaPlayer mp;

    @Override
    protected Void doInBackground(Void... arg0) {
    return null;

    }

    @Override
    protected void onPostExecute(Void result) {
    super.onPostExecute(result);

    mp.release(); // free resources
    mp=null; // help GC
    myDrawUnselectedState(myObject); // draw normal state
    ImageView iv = (ImageView) findViewById(R.id.myobjectcontainer);
    iv.invalidate(); // mark UI for refresh
    }

    @Override
    protected void onPreExecute() {
    super.onPreExecute();

    myDrawSelectedState(myObject); // draw selected
    ImageView iv = (ImageView) findViewById(R.id.mycontainer);
    iv.invalidate(); // mark for refreshing
    mp = MediaPlayer.create(getApplicationContext(), Uri.parse("/system/media/audio/ui/Effect_Tick.ogg") );
    mp.start(); // play sound
    SystemClock.sleep(300); // wait a little bit for user to see effect
    }
}

By the way, Effect_Tick.ogg its the one that fires when you press a button. It seems that these file names are pretty much Android standard, found in many different devices signed with Android copyright disclaimer.


问:
After updating to Bumblebee, it does not build properly

(Actually, I thought I had updated to Bumblebee, but I get a notification like the image.)

A few days ago, I ran Android Studio as usual and proceeded with the update according to the update notification.

But when I try to build today, it doesn't work at all.

At first I got this problem and in gradle I modified the nav_version like the solution in the link.

but after rebuild
I got the following error:

```<code>Dependency 'androidx.navigation:navigation-ui-ktx:2.5.0-alpha01' requires 'compileSdkVersion' to be set to 31 or higher.
Compilation target for module ':app' is 'android-30'
</code>```

After that, I modified gradle :app as following.

Changed sdkversion and targetsdkversion to 31.

```<code>android {
    compileSdkVersion 31
    buildToolsVersion "30.0.3"
    defaultConfig {
        minSdkVersion 24
        targetSdkVersion 31
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = '1.8'
    }
}
</code>```

But it still doesn't work and this problem occurs again in the ViewModelFactory class.

Inheritance from an interface with jvmdefault members is only allowed with option

I thought it was updated to Bumblebee, but it doesn't seem to have been updated and it doesn't even build, which is embarrassing.

答:
I've run into the same thing and I looked at the same questions and the answers were not specific enough or didn't work.  I ended up trying this in my app level build.gradle.

```<code>kotlinOptions {
    freeCompilerArgs = ['-Xjvm-default=compatibility']
}
</code>```

More specifically to my project, my kotlinOptions look like this:

```<code>kotlinOptions {
        jvmTarget = '1.8'
        freeCompilerArgs = ['-Xjvm-default=compatibility']
    }
</code>```

This is where I found it.
@JvmDefault and how add compiler option

This was an answer I found that didn't work for me but it was the answer to my specific question and explained the problem with more depth.
https://stackoverflow.com/a/70993001/5705252

Body:
(Actually, I thought I had updated to Bumblebee, but I get a notification like the image.)

A few days ago, I ran Android Studio as usual and proceeded with the update according to the update notification.

But when I try to build today, it doesn't work at all.

At first I got this problem and in gradle I modified the nav_version like the solution in the link.

but after rebuild
I got the following error:

Dependency 'androidx.navigation:navigation-ui-ktx:2.5.0-alpha01' requires 'compileSdkVersion' to be set to 31 or higher.
Compilation target for module ':app' is 'android-30'

After that, I modified gradle :app as following.

Changed sdkversion and targetsdkversion to 31.

android {
    compileSdkVersion 31
    buildToolsVersion "30.0.3"
    defaultConfig {
        minSdkVersion 24
        targetSdkVersion 31
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = '1.8'
    }
}

But it still doesn't work and this problem occurs again in the ViewModelFactory class.

Inheritance from an interface with jvmdefault members is only allowed with option

I thought it was updated to Bumblebee, but it doesn't seem to have been updated and it doesn't even build, which is embarrassing.

Body:
I've run into the same thing and I looked at the same questions and the answers were not specific enough or didn't work.  I ended up trying this in my app level build.gradle.

kotlinOptions {
    freeCompilerArgs = ['-Xjvm-default=compatibility']
}

More specifically to my project, my kotlinOptions look like this:

kotlinOptions {
        jvmTarget = '1.8'
        freeCompilerArgs = ['-Xjvm-default=compatibility']
    }

This is where I found it.
@JvmDefault and how add compiler option

This was an answer I found that didn't work for me but it was the answer to my specific question and explained the problem with more depth.
https://stackoverflow.com/a/70993001/5705252


问:
Can't deploy Cloud Functions because of "Unhandled error cleaning up build images"
I've deployed hundreds of function and this is the first time I encounter this issue. Simply, it stops deploying function process, saying:

Unhandled error cleaning up build images. This could result in a small monthly bill if not corrected. You can attempt to delete these images by redeploying or you can delete them manually at https://console.cloud.google.com/gcr/images/[project-name]/us/gcf

The way I deploy is through Firebase CLI command: firebase deploy --only functions:nameOfFunction

Question is what are those images I have to delete? Why? How can I solve it?

答:
For me, the issue was caused by a silly typo.

The error:

Functions deploy had errors with the following functions:
sendNotification(europe-west) i  functions: cleaning up build files... ⚠  functions: Unhandled error cleaning up build images. This
could result in a small monthly bill if not corrected. You can attempt
to delete these images by redeploying or you can delete them manually
at...

The fix was choosing the right region.

The incorrect region:

```<code>exports.sendNotification = functions
  .region("europe-west")...
</code>```

The correct region:

```<code>exports.sendNotification = functions
      .region("europe-west3")...
</code>```

Body:
For me, the issue was caused by a silly typo.

The error:

Functions deploy had errors with the following functions:
sendNotification(europe-west) i  functions: cleaning up build files... ⚠  functions: Unhandled error cleaning up build images. This
could result in a small monthly bill if not corrected. You can attempt
to delete these images by redeploying or you can delete them manually
at...

The fix was choosing the right region.

The incorrect region:

exports.sendNotification = functions
  .region("europe-west")...

The correct region:

exports.sendNotification = functions
      .region("europe-west3")...


问:
Is there a way to link a single M Code document to multiple workbooks?
I have several workbooks linked to the same set of CSV files. I use the same Power Query transform steps for each CSV file in each workbook. Instead of copying M code from the advanced editor of one workbook and pasting it into the advanced editor of another, is there somewhere I can store a "master" M code document? I would like to be able to link all workbooks to a single text file containing M code so that when I make changes in this master document the Power Query transformations are made in each linked workbook - similar to style sheets in css.</p>

答:
See https://blog.crossjoin.co.uk/2014/02/04/loading-power-query-m-code-from-text-files/</p>
```<code>let
//Load M code from text file
// https://blog.crossjoin.co.uk/2014/02/04/loading-power-query-m-code-from-text-files/
Source = Text.FromBinary(File.Contents("C:\directory\MyMCode.txt")),
//Evaluate the code from the file as an M expression
EvaluatedExpression = Expression.Evaluate(Source, #shared)
in
EvaluatedExpression
</code>```

Body:
See https://blog.crossjoin.co.uk/2014/02/04/loading-power-query-m-code-from-text-files/

let
//Load M code from text file
// https://blog.crossjoin.co.uk/2014/02/04/loading-power-query-m-code-from-text-files/
Source = Text.FromBinary(File.Contents("C:\directory\MyMCode.txt")),
//Evaluate the code from the file as an M expression
EvaluatedExpression = Expression.Evaluate(Source, #shared)
in
EvaluatedExpression


问:
How do I pass SCSI (CDB) commands through a USB connection
I am trying to talk to a MSC USB device (interface class 8, subclass 6, protocol 0x50) via a plain USB API with endpoints (all set up for me).

Provided I have a valid CDB, such as for "Test Unit Ready", how to I send that over the USB interface?

Where can I find examples or docs for how this is done?

Background: The actual platform is macOS, which doesn't provide SCSI-passthrough for block devices, and the native SCSI API is also not available in this case.

I have, however, been able to initiate communication on the USB level with the device, and am now trying to circumvent the blocked SCSI device level access by talking thru USB directly.

答:
Most such devices implement the so-called “Bulk Only” protocol, which is specified here: https://usb.org/document-library/mass-storage-bulk-only-10

Essentially, you send a 31-byte “Command Block Wrapper”, which includes the CDB and is specified in section 5.1 of the spec, to the device via the bulk out endpoint. You then read or write the data to be transferred from the input bulk endpoint or to the output bulk endpoint and finally read the 13-byte command status wrapper from the bulk in pipe.

However, note that you’ll need to make sure the OS hasn’t already loaded a driver for the device - from user space, the system won’t give you access to the endpoints when a kernel driver has claimed them anyway, but if you were to attempt to use the same pipes as the default driver from a kext, you’d get unpredictable results.


问:
TcpTestSucceeded: False cannot connect to specific port
I am trying to connect to open up port 89 on my Windows machine so others can access it, but I'm having trouble doing so. I added a rule to Firewall to allow access to port 89, but it still seems like it's not working. Any advice on how to resolve or even how to debug?

```<code>PS D:\> Test-NetConnection devbox -p 89
WARNING: TCP connect to (fe80::188d:3b90:868b:c3f6%5 : 89) failed                                                       WARNING: TCP connect to (2001:4898:3:25:7975:d61e:f88e:bfe2 : 89) failed                                                WARNING: TCP connect to (2001:4898:3:25:188d:3b90:868b:c3f6 : 89) failed                                                WARNING: TCP connect to (fe80::4c9e:1380:c530:b43a%42 : 89) failed                                                      WARNING: TCP connect to (fe80::6d77:dd66:a5b1:902c%26 : 89) failed                                                      WARNING: TCP connect to (fe80::69d3:4282:2917:485d%18 : 89) failed                                                      WARNING: TCP connect to (fe80::c9a:5dbc:5823:fdd9%13 : 89) failed                                                       WARNING: TCP connect to (10.123.77.38 : 89) failed                                                                      WARNING: TCP connect to (172.24.96.1 : 89) failed                                                                       WARNING: TCP connect to (172.24.48.1 : 89) failed                                                                       WARNING: TCP connect to (172.21.128.1 : 89) failed                                                                      WARNING: TCP connect to (2001:0:d5b:9458:c9a:5dbc:5823:fdd9 : 89) failed                                                                                ComputerName           : devbox                                                                                RemoteAddress          : fe80::188d:3b90:868b:c3f6%5                                                                    RemotePort             : 89
InterfaceAlias         : vEthernet (New Virtual Switch)
SourceAddress          : 2001:4898:3:25:188d:3b90:868b:c3f6
PingSucceeded          : True
PingReplyDetails (RTT) : 0 ms
TcpTestSucceeded       : False
</code>```

答:
Be sure that you or your friend exactly do this:

Navigate to Control Panel, System and Security and Windows Firewall.
Select Advanced settings and highlight Inbound Rules in the left pane.
Right click Inbound Rules and select New Rule.
Add the port you need to open and click Next.
Add the protocol (TCP or UDP) and the port number into the next window and click Next.
Select Allow the connection in the next window and hit Next.
Select the network type as you see fit and click Next.
Name the rule something meaningful and click Finish.
That's all you have to do to open a firewall port in Windows 10

Many devices have open ports to send error reports to a server. But
the things is those devices are their to send and then recieve
acknowledgement to the sent packet. So what you need is a device to
recieve and then send to. To overcome this problem, you need to become
that server which the device request/send to and recieve the service
from it. You can send a .bat file to a friend/ victim laptop which cab
change its dns and gateway address to your server which you will be
running ,hence Becoming the middle man.(just an example)

Client tries to connect to IPv6 address: TCP connect to (fe80::188d:3b90:868b:c3f6%5 : 89) failed.
Maybe your server is listening only IPv4.

Also the problem may come from trying to connect to an IPv6 address instead of the IPv4 address that you are listening to. Instead, you can try entering the IPv4 address, 10.3.10.200, as the "ComputerName" to restrict the test to IPv4.

Notify me if this works for you.

Body:
I am trying to connect to open up port 89 on my Windows machine so others can access it, but I'm having trouble doing so. I added a rule to Firewall to allow access to port 89, but it still seems like it's not working. Any advice on how to resolve or even how to debug?

PS D:\> Test-NetConnection devbox -p 89
WARNING: TCP connect to (fe80::188d:3b90:868b:c3f6%5 : 89) failed                                                       WARNING: TCP connect to (2001:4898:3:25:7975:d61e:f88e:bfe2 : 89) failed                                                WARNING: TCP connect to (2001:4898:3:25:188d:3b90:868b:c3f6 : 89) failed                                                WARNING: TCP connect to (fe80::4c9e:1380:c530:b43a%42 : 89) failed                                                      WARNING: TCP connect to (fe80::6d77:dd66:a5b1:902c%26 : 89) failed                                                      WARNING: TCP connect to (fe80::69d3:4282:2917:485d%18 : 89) failed                                                      WARNING: TCP connect to (fe80::c9a:5dbc:5823:fdd9%13 : 89) failed                                                       WARNING: TCP connect to (10.123.77.38 : 89) failed                                                                      WARNING: TCP connect to (172.24.96.1 : 89) failed                                                                       WARNING: TCP connect to (172.24.48.1 : 89) failed                                                                       WARNING: TCP connect to (172.21.128.1 : 89) failed                                                                      WARNING: TCP connect to (2001:0:d5b:9458:c9a:5dbc:5823:fdd9 : 89) failed                                                                                ComputerName           : devbox                                                                                RemoteAddress          : fe80::188d:3b90:868b:c3f6%5                                                                    RemotePort             : 89
InterfaceAlias         : vEthernet (New Virtual Switch)
SourceAddress          : 2001:4898:3:25:188d:3b90:868b:c3f6
PingSucceeded          : True
PingReplyDetails (RTT) : 0 ms
TcpTestSucceeded       : False


问:
in status field should be approved once boolean field is true how to write syntax
mode.py

this image of model file in this once Boolean is true the status field value should be approved how to write syntax

答:
You can override save function as</p>
```<code>class Cloudstrats1(models.Model)
    Projectname = models CharField(max_length=30)
    ProjectDetail = models.TextField()
    .........
    .........

    def save(self, *args, **kwargs):
        if self.Approved == True:
            self.status = 'approved'
        super(Cloudstrats1, self).save(*args, **kwargs)
</code>```

Body:
You can override save function as

class Cloudstrats1(models.Model)
    Projectname = models CharField(max_length=30)
    ProjectDetail = models.TextField()
    .........
    .........

    def save(self, *args, **kwargs):
        if self.Approved == True:
            self.status = 'approved'
        super(Cloudstrats1, self).save(*args, **kwargs)


问:
I have accidentally cleared contents from /var/log/messages and now log messages are not getting logged on my RHEL7.6 OS
On my RHEL 7.6 OS system, I have accidentally cleared contents from /var/log/messages and now logs are getting logged.

I have tried restarting the rsyslog using service rsyslog restart, After executing this command in /var/log/messages file below messages got generated. Even though in generated message it says Started System Logging Service still logs not getting logged. please suggest how to make this right.

```<code>Feb 10 12:15:31 dragon systemd: Stopping System Logging Service...
Feb 10 12:15:31 dragon rsyslogd: [origin software="rsyslogd" swVersion="8.24.0-34.el7" x-pid="5588" x-info="http://www.rsyslog.com"] exiting on signal 15.
Feb 10 12:15:31 dragon systemd: Stopped System Logging Service.
Feb 10 12:15:31 dragon systemd: Starting System Logging Service...
Feb 10 12:15:31 dragon rsyslogd: [origin software="rsyslogd" swVersion="8.24.0-34.el7" x-pid="20937" x-info="http://www.rsyslog.com"] start
Feb 10 12:15:31 dragon systemd: Started System Logging Service.
</code>```

答:
for RHEL7 OS, we need to use systemctl restart rsyslog command where service rsyslog restart can be use on RHEL6 servers.

To test command worked fine, you can try with logger -i "New log is my command reaching.."  if the statement gets logged on \var\log\messages then it has restarted logging back.

Body:
On my RHEL 7.6 OS system, I have accidentally cleared contents from /var/log/messages and now logs are getting logged.

I have tried restarting the rsyslog using service rsyslog restart, After executing this command in /var/log/messages file below messages got generated. Even though in generated message it says Started System Logging Service still logs not getting logged. please suggest how to make this right.

Feb 10 12:15:31 dragon systemd: Stopping System Logging Service...
Feb 10 12:15:31 dragon rsyslogd: [origin software="rsyslogd" swVersion="8.24.0-34.el7" x-pid="5588" x-info="http://www.rsyslog.com"] exiting on signal 15.
Feb 10 12:15:31 dragon systemd: Stopped System Logging Service.
Feb 10 12:15:31 dragon systemd: Starting System Logging Service...
Feb 10 12:15:31 dragon rsyslogd: [origin software="rsyslogd" swVersion="8.24.0-34.el7" x-pid="20937" x-info="http://www.rsyslog.com"] start
Feb 10 12:15:31 dragon systemd: Started System Logging Service.


问:
Using Netbeans to configure context-root for JBoss
I have a Spring application that is being deployed to JBoss 4.2.  I can manually edit the generated WAR file and alter the jboss-web.xml file to set the context-root value and that works perfectly well.  I would like to be able to do the samething via netbeans (6.9.1), but I have been unable to locate where to make the adjustment.  I've tried tweaking the project's properties and setting the Context Path value.  When I Run the application that value is reset to the Project's name.  I've located the jboss-web.xml file in the project and changed it there, also reset upon run.  So it appears that Netbeans is deciding that the value need to be set but I can't locate where.  If it's of any use, the project also uses Maven2, but all the controls I can find for impacting context-root are geared towards EAR files instead of WAR.

Has anyone been able to do this or am I just in a world of making the change post build?

答: I had a similar problem once where netbeans was sometimes removing the context-root element from the glassfish-web.xml configuration. I have not been able to track it down exactly but you could try to remove the file nb-configuration.xml in the project root folder and see if that helps.


问:
Custom SQL Query in Tableau produces incorrect output when same query in SSMS runs as expected
I built SQL query that works as expected when I execute it in Microsoft SQL Server Management Studio, however when I use same query in Tableau (Custom SQL query), some columns (where aggregation was performed) are showing incorrect output (always 0).

Issue is in the lines of code shown here. I guess @@ROWCOUNT could be an issue.

```<code>SUM(CASE WHEN a.LocationName = 'Home' THEN @@ROWCOUNT ELSE 0 END) AS CountHomeServices,
SUM(CASE WHEN a.LocationName = 'Office' THEN @@ROWCOUNT ELSE 0 END) AS CountOfficeServices
</code>```

Is there a way to make it work in Tableau?

答:
A more intuitive approach would be</p>
```<code>COUNT(CASE WHEN a.LocationName = 'Home' THEN a.LocationName END) AS CountHomeServices,
COUNT(CASE WHEN a.LocationName = 'Office' THEN a.LocationName END) AS CountOfficeServices
</code>```

Body:
I built SQL query that works as expected when I execute it in Microsoft SQL Server Management Studio, however when I use same query in Tableau (Custom SQL query), some columns (where aggregation was performed) are showing incorrect output (always 0).

Issue is in the lines of code shown here. I guess @@ROWCOUNT could be an issue.

SUM(CASE WHEN a.LocationName = 'Home' THEN @@ROWCOUNT ELSE 0 END) AS CountHomeServices,
SUM(CASE WHEN a.LocationName = 'Office' THEN @@ROWCOUNT ELSE 0 END) AS CountOfficeServices

Is there a way to make it work in Tableau?

Body:
A more intuitive approach would be

COUNT(CASE WHEN a.LocationName = 'Home' THEN a.LocationName END) AS CountHomeServices,
COUNT(CASE WHEN a.LocationName = 'Office' THEN a.LocationName END) AS CountOfficeServices


问:
How to consume ASP.NET Core WebAPI using MVC Razor view
I am trying to build a web application using ASP.NET Core Web API and MVC with Razor views.

Here is my code for the TopicController:

```<code>  public async Task'<'IResult'>' Index()
  {
      return Results.Ok(await _Data.GetAllTopics());
  }
</code>```

Output of this controller is:

```<code>{
    "value": [
                 {
                   "id": 1,
                   "topicName": "ACCESS MODIFIER",
                   "videoName": null,
                   "videoURL":null
                 },
                 {
                   "id": 2,
                   "topicName": "GENERICS",
                   "videoName": null,
                   "videoURL": null
                 }
             ],
    "statusCode": 200,
    "contentType": null
}
</code>```

I am able display data if the return type of Index() is IActionResult for a complex object. But not sure how to interpret result from above Index() function.

I am new to front end, any help would be appreciated.

答:
I was able to make my code work. Instead of returning JSON I am retuning a view. However I have to do a local mapping of the objects.</p>
```<code>public async Task<IActionResult> Index()
{

List<Models.Topic> topics = new List<Models.Topic>();

  var result = await _Data.GetAllTopics();

foreach (var item in result)
{
  topics.Add(new Models.Topic
  {
    Id = item.Id,
    TopicName = item.TopicName,
    VideoName= item.VideoName,
    VideoURL = item.VideoURL
  });
}

return View(topics);
}
</code>```

Body:
I am trying to build a web application using ASP.NET Core Web API and MVC with Razor views.

Here is my code for the TopicController:

  public async Task'<'IResult'>' Index()
  {
      return Results.Ok(await _Data.GetAllTopics());
  }

Output of this controller is:

{
    "value": [
                 {
                   "id": 1,
                   "topicName": "ACCESS MODIFIER",
                   "videoName": null,
                   "videoURL":null
                 },
                 {
                   "id": 2,
                   "topicName": "GENERICS",
                   "videoName": null,
                   "videoURL": null
                 }
             ],
    "statusCode": 200,
    "contentType": null
}

I am able display data if the return type of Index() is IActionResult for a complex object. But not sure how to interpret result from above Index() function.

I am new to front end, any help would be appreciated.

Body:
I was able to make my code work. Instead of returning JSON I am retuning a view. However I have to do a local mapping of the objects.

public async Task<IActionResult> Index()
{

List<Models.Topic> topics = new List<Models.Topic>();

  var result = await _Data.GetAllTopics();

foreach (var item in result)
{
  topics.Add(new Models.Topic
  {
    Id = item.Id,
    TopicName = item.TopicName,
    VideoName= item.VideoName,
    VideoURL = item.VideoURL
  });
}

return View(topics);
}


问:
ADB pair unknown command using r32 platform tools
I've just downloaded a fresh install of SDK platform tools since I don't need the IDE.
Version: r32.0.0

When using adb pair i get the following:

```<code>PS C:\*userpath*\platform-tools_r32.0.0-windows\platform-tools> adb pair
adb: usage: unknown command pair
</code>```

Tried downloading fresh again, and still the same error. Do I need to install other packages aswell? I just want the command line tools.

答:
Ended up using an ADB version I didn't know was installed. Opening PowerShell directly in the folder and running

```<code>./adb
</code>```

Made it work, just fine.

Body:
I've just downloaded a fresh install of SDK platform tools since I don't need the IDE.
Version: r32.0.0

When using adb pair i get the following:

PS C:\*userpath*\platform-tools_r32.0.0-windows\platform-tools> adb pair
adb: usage: unknown command pair

Tried downloading fresh again, and still the same error. Do I need to install other packages aswell? I just want the command line tools.

Body:
Ended up using an ADB version I didn't know was installed. Opening PowerShell directly in the folder and running

./adb

Made it work, just fine.


问:
How to run same function on multiple elements?
I created a web page with 3 counters that can be triggered separately, but I have a problem with the count function I can't use it on the 3 counters.

I manage to retrieve the index of each button but I don't know how to use it to trigger each counter separately.

can you help me to solve this problem please ?

Here is my code.

"use strict";

/* ___________________________Déclarer les variables et les fonctions______________________________ */

/* Déclaration des variables */
var item = document.querySelectorAll('.slider-item');
var str = document.querySelectorAll('.buttons--start');
var stp = document.querySelectorAll('.button--stop');
var start = 0;
var end = 0;
var diff = 0;
var timer = 0;

/* Fonction chrono */
function chrono(){
    end = new Date();
    diff = end - start;
    diff = new Date(diff);
    var sec = diff.getSeconds();
    item.innerHTML = sec;
    timer = setTimeout("chrono()", 10);
}

/* Fonction pour déclancher le chrono */
function chronoStart(i){
    start = new Date();
    chrono();
    console.log('start '+i);
}

/* Fonction pour arrêter et rénitialiser le chrono */
function chronoStop(i){
    clearTimeout(timer)
    item[i].innerHTML = "0";
    start = new Date();
    console.log('stop '+i);
}

/* Fonction qui change la couleur du background */
function changeColor(i){
    let bgColor = '#' + Math.random().toString(16).substr(-6);
    item[i].style.backgroundColor = bgColor;
}

/* ___________________________Écouter les événements__________________________________ */

/* Appeler la fonction qui déclanche le chrono lorsqu'on clique sur start*/
for (let i=0; i<item.length; i++)
{
    str[i].addEventListener('click',(e)=>{
        chronoStart(i);
    });
    //currentPos = i ;
}

/* Appeler la fonction qui arrête le chrono lorsqu'on clique sur stop*/
for (let i=0; i<item.length; i++)
{
    stp[i].addEventListener('click',(e)=>{
        chronoStop(i);
    });
}

/* Appeler la fonction qui change la couleur du background lorsque l'évenement est déclancher*/

for (let i=0; i<item.length; i++)
{
    item[i].addEventListener("click",(e)=>{
        changeColor(i);
    });
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
    font-family: Arial, sans-serif;
}

.wrapper {
    /* display: flex;
    flex-flow: column wrap;
    position: fixed;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    padding: 50px; */
}

.slider {
    display: flex;
    align-items: center;
    justify-content: center;
    flex-grow: 1;
}

.slider-item {
    font-size: 120px;
    font-weight: bold;
    padding: 15px;
    background-color: yellow;
    user-select: none;
}

.buttons {
    margin-top: 15px;
    text-align: center;
}

.buttons button {
    display: inline-block;
    padding: 15px;
    font-size: 16px;
    color: #fff;
    border: none;
    outline: none;
    background-color: #000;
    cursor: pointer;
}</code>```

0

                <button class="buttons--start" type="button">Start</button>
                <button class="button--stop" type="button">Stop</button>

0

                <button class="buttons--start" type="button">Start</button>
                <button class="button--stop" type="button">Stop</button>

0

                <button class="buttons--start" type="button">Start</button>
                <button class="button--stop" type="button">Stop</button>

```

答:
As Rory pointed out while I was doodling this up, you have repeated markup but a single set of variables tracking the timers.

You could remedy this by iterating over the occurrences in the HTML and setting up distinct handlers for each. Here's one way you could do that:

"use strict";

function init() {
  // get elements whose id begins with "slider-"
  const sliders = document.querySelectorAll('[id^=slider-]');

  // set up event listeners for each occurrence:
  sliders.forEach(s => {
    // the setInterval/timeout identifier for this instance
    let timerId;

    // get references to the child elements we need
    const startButton = s.querySelector('.buttons--start');
    const stopButton = s.querySelector('.button--stop');
    const display = s.querySelector('.slider-item');

    // add a start button click listener
    startButton.addEventListener('click', () => {
      // clear existing timer if already running
      clearTimeout(timerId);

      // capture the start time
      const start = new Date();

      // function to update the display
      const update = () => {
        display.innerHTML = ((Date.now() - start) / 1000).toFixed(1);
      }

      // start a timer, update the timerId variable
      timerId = setInterval(update, 100)

      // add a listener for the stop button to kill this timer
      const stopHandler = () => clearInterval(timerId);
      stopButton.addEventListener('click', () => {
        stopHandler();
        // only needs to run once; remove the listener
        stopButton.removeEventListener('click', stopHandler);
      });
    });
  });
}

// kick it off
init();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  font-family: Arial, sans-serif;
}

.wrapper {
  /* display: flex;
    flex-flow: column wrap;
    position: fixed;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    padding: 50px; */
}

.slider {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-grow: 1;
}

.slider-item {
  font-size: 120px;
  font-weight: bold;
  padding: 15px;
  background-color: yellow;
  user-select: none;
}

.buttons {
  margin-top: 15px;
  text-align: center;
}

.buttons button {
  display: inline-block;
  padding: 15px;
  font-size: 16px;
  color: #fff;
  border: none;
  outline: none;
  background-color: #000;
  cursor: pointer;
}</code>```

0

    <button class="buttons--start" type="button">Start</button>
    <button class="button--stop" type="button">Stop</button>

0

    <button class="buttons--start" type="button">Start</button>
    <button class="button--stop" type="button">Stop</button>

0

    <button class="buttons--start" type="button">Start</button>
    <button class="button--stop" type="button">Stop</button>

```

Body:
I created a web page with 3 counters that can be triggered separately, but I have a problem with the count function I can't use it on the 3 counters.

I manage to retrieve the index of each button but I don't know how to use it to trigger each counter separately.

can you help me to solve this problem please ?

Here is my code.

"use strict";

/* ___________________________Déclarer les variables et les fonctions______________________________ */

/* Déclaration des variables */
var item = document.querySelectorAll('.slider-item');
var str = document.querySelectorAll('.buttons--start');
var stp = document.querySelectorAll('.button--stop');
var start = 0;
var end = 0;
var diff = 0;
var timer = 0;

/* Fonction chrono */
function chrono(){
    end = new Date();
    diff = end - start;
    diff = new Date(diff);
    var sec = diff.getSeconds();
    item.innerHTML = sec;
    timer = setTimeout("chrono()", 10);
}

/* Fonction pour déclancher le chrono */
function chronoStart(i){
    start = new Date();
    chrono();
    console.log('start '+i);
}

/* Fonction pour arrêter et rénitialiser le chrono */
function chronoStop(i){
    clearTimeout(timer)
    item[i].innerHTML = "0";
    start = new Date();
    console.log('stop '+i);
}

/* Fonction qui change la couleur du background */
function changeColor(i){
    let bgColor = '#' + Math.random().toString(16).substr(-6);
    item[i].style.backgroundColor = bgColor;
}

/* ___________________________Écouter les événements__________________________________ */

/* Appeler la fonction qui déclanche le chrono lorsqu'on clique sur start*/
for (let i=0; i<item.length; i++)
{
    str[i].addEventListener('click',(e)=>{
        chronoStart(i);
    });
    //currentPos = i ;
}

/* Appeler la fonction qui arrête le chrono lorsqu'on clique sur stop*/
for (let i=0; i<item.length; i++)
{
    stp[i].addEventListener('click',(e)=>{
        chronoStop(i);
    });
}

/* Appeler la fonction qui change la couleur du background lorsque l'évenement est déclancher*/

for (let i=0; i<item.length; i++)
{
    item[i].addEventListener("click",(e)=>{
        changeColor(i);
    });
}

body {
    font-family: Arial, sans-serif;
}

.wrapper {
    /* display: flex;
    flex-flow: column wrap;
    position: fixed;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    padding: 50px; */
}

.slider {
    display: flex;
    align-items: center;
    justify-content: center;
    flex-grow: 1;
}

.slider-item {
    font-size: 120px;
    font-weight: bold;
    padding: 15px;
    background-color: yellow;
    user-select: none;
}

.buttons {
    margin-top: 15px;
    text-align: center;
}

.buttons button {
    display: inline-block;
    padding: 15px;
    font-size: 16px;
    color: #fff;
    border: none;
    outline: none;
    background-color: #000;
    cursor: pointer;
}

0

                <button class="buttons--start" type="button">Start</button>
                <button class="button--stop" type="button">Stop</button>

0

                <button class="buttons--start" type="button">Start</button>
                <button class="button--stop" type="button">Stop</button>

0

                <button class="buttons--start" type="button">Start</button>
                <button class="button--stop" type="button">Stop</button>

Body:
As Rory pointed out while I was doodling this up, you have repeated markup but a single set of variables tracking the timers.

You could remedy this by iterating over the occurrences in the HTML and setting up distinct handlers for each. Here's one way you could do that:

"use strict";

function init() {
  // get elements whose id begins with "slider-"
  const sliders = document.querySelectorAll('[id^=slider-]');

  // set up event listeners for each occurrence:
  sliders.forEach(s => {
    // the setInterval/timeout identifier for this instance
    let timerId;

    // get references to the child elements we need
    const startButton = s.querySelector('.buttons--start');
    const stopButton = s.querySelector('.button--stop');
    const display = s.querySelector('.slider-item');

    // add a start button click listener
    startButton.addEventListener('click', () => {
      // clear existing timer if already running
      clearTimeout(timerId);

      // capture the start time
      const start = new Date();

      // function to update the display
      const update = () => {
        display.innerHTML = ((Date.now() - start) / 1000).toFixed(1);
      }

      // start a timer, update the timerId variable
      timerId = setInterval(update, 100)

      // add a listener for the stop button to kill this timer
      const stopHandler = () => clearInterval(timerId);
      stopButton.addEventListener('click', () => {
        stopHandler();
        // only needs to run once; remove the listener
        stopButton.removeEventListener('click', stopHandler);
      });
    });
  });
}

// kick it off
init();

body {
  font-family: Arial, sans-serif;
}

.wrapper {
  /* display: flex;
    flex-flow: column wrap;
    position: fixed;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    padding: 50px; */
}

.slider {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-grow: 1;
}

.slider-item {
  font-size: 120px;
  font-weight: bold;
  padding: 15px;
  background-color: yellow;
  user-select: none;
}

.buttons {
  margin-top: 15px;
  text-align: center;
}

.buttons button {
  display: inline-block;
  padding: 15px;
  font-size: 16px;
  color: #fff;
  border: none;
  outline: none;
  background-color: #000;
  cursor: pointer;
}

<div class="wrapper" id="slider-1">
  <div class="slider">
    <div class="slider-item">0</div>
  </div>
  <div class="buttons">
    <button class="buttons--start" type="button">Start</button>
    <button class="button--stop" type="button">Stop</button>
  </div>

</div>
<div class="wrapper" id="slider-2">
  <div class="slider">
    <div class="slider-item">0</div>
  </div>
  <div class="buttons">
    <button class="buttons--start" type="button">Start</button>
    <button class="button--stop" type="button">Stop</button>
  </div>

</div>
<div class="wrapper" id="slider-3">
  <div class="slider">
    <div class="slider-item">0</div>
  </div>
  <div class="buttons">
    <button class="buttons--start" type="button">Start</button>
    <button class="button--stop" type="button">Stop</button>
  </div>

</div>


问:
Why do different ways of calling Raku result in very different startup times?
I have v2020.12 of Rakudo installed on my computer and have also built v2020.12 from source.  When profiling startup times, I noticed the following results: (these benchmarks use hyperfine, but I also got similar results with time).

$ which raku
/opt/rakudo-pkg/bin/raku
$ /opt/rakudo-pkg/bin/raku --version
Welcome to Rakudo(tm) v2020.12.
Implementing the Raku(tm) programming language v6.d.
Built on MoarVM version 2020.12.
$ /opt/rakudo-pkg/bin/raku ~/.raku/bin/red --help > /dev/null # make sure modules are compiled
$ hyperfine -i '/opt/rakudo-pkg/bin/raku /home/dsock/.raku/bin/red'
Benchmark #1: /opt/rakudo-pkg/bin/raku /home/dsock/.raku/bin/red
  Time (mean ± σ):     890.0 ms ±  15.5 ms    [User: 1.411 s, System: 0.068 s]
  Range (min … max):   861.3 ms … 913.4 ms    10 runs

  Warning: Ignoring non-zero exit code.

$ ~/forks/rakudo-clean/install/bin/raku --version
Welcome to Rakudo(tm) v2020.12.
Implementing the Raku(tm) programming language v6.d.
Built on MoarVM version 2020.12.
$ ~/forks/rakudo-clean/install/bin/raku ~/.raku/bin/red --help > /dev/null # compile modules
$ hyperfine -i '~/forks/rakudo-clean/install/bin/raku /home/dsock/.raku/bin/red'
Benchmark #1: ~/forks/rakudo-clean/install/bin/raku /home/dsock/.raku/bin/red
  Time (mean ± σ):     343.9 ms ±   7.9 ms    [User: 461.3 ms, System: 43.9 ms]
  Range (min … max):   328.1 ms … 355.9 ms    10 runs

  Warning: Ignoring non-zero exit code.
```
<p>As you can see, <code>red --help</code> took ~3× as long to execute when I used the version of raku installed in <code>/opt</code>.  This isn't an issue specific to <code>red</code> – I also tested with <code>zef --help</code> and observed a similar issue.  Interestingly, the issue did <em>not</em> occur if I ran the <code>/opt</code> copy of raku from inside the <code>~/forks/rakudo-clean/</code> directory.</p>
<p>This last point leads me to wonder whether the underling issue is somehow related to <code>$PATH</code> searches or something similar.  (Maybe something like the difficulty Ruby has with <code>$LOAD_PATH</code>?)</p>
<p>A few alternatives:</p>
<ol>
<li>I have somehow misconfigured my raku install in a way that causes this slowdown, but people who installed raku correctly don't run into this issue (this possibility is why this is a question on SO rather than being reported as a bug).</li>
<li>The default installation for raku causes this issue.  Everyone experiences it, but we can fix it by updating build/install instructions.</li>
<li>This is a bug in Rakudo that needs to be fixed at that level rather than through installation configuration.</li>
<li>Something else/I'm more deeply confused.</li>
</ol>
<p>I appreciate any help you can provide, including just letting me know if you also see the same large difference in start times.  Thanks!</p>
<p><strong>EDIT</strong>:</p>
<p>I did a bit more digging,and discovered the <code>RAKUDO_MODULE_DEBUG</code> environmental variable.  After setting that, I discovered some more info – specifically, in the slower version (<code>/opt/rakudo-pkg/bin/raku</code>), I have a number of lines like the following:</p>
<pre class="lang-sh prettyprint-override"><code> 1 RMD: Trying to load 77AFF4B677E65751FF5E96B6D6FA230222D29DFE.repo-id from /home/dsock/lib/.precomp
 1 RMD: Repo changed:
          9255FA5B5841CF5E09BDD37B3C43740099B4851F
          97741FE305502F0915F57D977BCFC518F958D4FC
        Need to re-check dependencies.
</code>```

In contrast, loading the same dependecy with ~/forks/rakudo-clean/install/bin/raku produced the following output (among much else, of course).

```<code> 1 RMD: Trying to load 77AFF4B677E65751FF5E96B6D6FA230222D29DFE.repo-id from /home/dsock/lib/.precomp
 1 RMD: dependency: FFEE376ADAD76513435BB73B169C73EC50B35567 home#sources/FFEE376ADAD76513435BB73B169C73EC50B35567 CAB0E9BB22A61F32FA98CFEA40EDFDD6E4495D06 CompUnit::DependencySpecification.new(:short-name<CX::Red::Bool>)
</code>```

This partly answers my question: the /opt version launches more slowly because it is re-checking dependencies.  But this really just raises more questions.  Why is that version finding something different when it looks in the same folder?  Given that it is, why isn't it updating the cache properly so that it finds what it's looking for the next time it runs?

答:
A year later, I am no longer experiencing this issue (rakudo v2021.12).  Additionally, comments on the question (and a lack of answers/activity) suggest that others were never experiencing the same issue.

Thus, I'm concluding that whatever issue I experienced was an idiosyncratic configuration error on my part and considering this question resolved.

Body:
I have v2020.12 of Rakudo installed on my computer and have also built v2020.12 from source.  When profiling startup times, I noticed the following results: (these benchmarks use hyperfine, but I also got similar results with time).

$ which raku
/opt/rakudo-pkg/bin/raku
$ /opt/rakudo-pkg/bin/raku --version
Welcome to Rakudo(tm) v2020.12.
Implementing the Raku(tm) programming language v6.d.
Built on MoarVM version 2020.12.
$ /opt/rakudo-pkg/bin/raku ~/.raku/bin/red --help > /dev/null # make sure modules are compiled
$ hyperfine -i '/opt/rakudo-pkg/bin/raku /home/dsock/.raku/bin/red'
Benchmark #1: /opt/rakudo-pkg/bin/raku /home/dsock/.raku/bin/red
  Time (mean ± σ):     890.0 ms ±  15.5 ms    [User: 1.411 s, System: 0.068 s]
  Range (min … max):   861.3 ms … 913.4 ms    10 runs

  Warning: Ignoring non-zero exit code.

$ ~/forks/rakudo-clean/install/bin/raku --version
Welcome to Rakudo(tm) v2020.12.
Implementing the Raku(tm) programming language v6.d.
Built on MoarVM version 2020.12.
$ ~/forks/rakudo-clean/install/bin/raku ~/.raku/bin/red --help > /dev/null # compile modules
$ hyperfine -i '~/forks/rakudo-clean/install/bin/raku /home/dsock/.raku/bin/red'
Benchmark #1: ~/forks/rakudo-clean/install/bin/raku /home/dsock/.raku/bin/red
  Time (mean ± σ):     343.9 ms ±   7.9 ms    [User: 461.3 ms, System: 43.9 ms]
  Range (min … max):   328.1 ms … 355.9 ms    10 runs

  Warning: Ignoring non-zero exit code.

As you can see, red --help took ~3× as long to execute when I used the version of raku installed in /opt.  This isn't an issue specific to red – I also tested with zef --help and observed a similar issue.  Interestingly, the issue did not occur if I ran the /opt copy of raku from inside the ~/forks/rakudo-clean/ directory.

This last point leads me to wonder whether the underling issue is somehow related to $PATH searches or something similar.  (Maybe something like the difficulty Ruby has with $LOAD_PATH?)

A few alternatives:

I have somehow misconfigured my raku install in a way that causes this slowdown, but people who installed raku correctly don't run into this issue (this possibility is why this is a question on SO rather than being reported as a bug).

The default installation for raku causes this issue.  Everyone experiences it, but we can fix it by updating build/install instructions.

This is a bug in Rakudo that needs to be fixed at that level rather than through installation configuration.

Something else/I'm more deeply confused.

I appreciate any help you can provide, including just letting me know if you also see the same large difference in start times.  Thanks!

EDIT:

I did a bit more digging,and discovered the RAKUDO_MODULE_DEBUG environmental variable.  After setting that, I discovered some more info – specifically, in the slower version (/opt/rakudo-pkg/bin/raku), I have a number of lines like the following:

 1 RMD: Trying to load 77AFF4B677E65751FF5E96B6D6FA230222D29DFE.repo-id from /home/dsock/lib/.precomp
 1 RMD: Repo changed:
          9255FA5B5841CF5E09BDD37B3C43740099B4851F
          97741FE305502F0915F57D977BCFC518F958D4FC
        Need to re-check dependencies.

In contrast, loading the same dependecy with ~/forks/rakudo-clean/install/bin/raku produced the following output (among much else, of course).

 1 RMD: Trying to load 77AFF4B677E65751FF5E96B6D6FA230222D29DFE.repo-id from /home/dsock/lib/.precomp
 1 RMD: dependency: FFEE376ADAD76513435BB73B169C73EC50B35567 home#sources/FFEE376ADAD76513435BB73B169C73EC50B35567 CAB0E9BB22A61F32FA98CFEA40EDFDD6E4495D06 CompUnit::DependencySpecification.new(:short-name<CX::Red::Bool>)

This partly answers my question: the /opt version launches more slowly because it is re-checking dependencies.  But this really just raises more questions.  Why is that version finding something different when it looks in the same folder?  Given that it is, why isn't it updating the cache properly so that it finds what it's looking for the next time it runs?


问:
Android Check Application Status
I have a question about Android application status. I want to know that am I able to check whether application is alive or dead, visible or on background. I need to make a decision according to application status in my broadcast receiver.

Thanks in advance..

答:
Basically, when your receive broadcast your application is guaranteed to run. That's because broadcast can not be received without application process started first. And if there were no components active (like activities) when broadcast is sent, then application process is started for the sole purpose of processing this broadcast.

As for the other part, detecting if any Activity is currently active and/or visible - I haven't seen any API calls for this. There are might be some workaround (like manually keeping the counter in a singleton), but as far as I know there is no direct support for this. Though I might be wrong.

Title: Android Check Application Status


问:
How can I capitalize the first letter of each word in a string?
```<code>s = 'the brown fox'
</code>```

...do something here...

s should be:

```<code>'The Brown Fox'
</code>```

What's the easiest way to do this?

答:
Another oneline solution could be:</p>
```<code>" ".join(map(lambda d: d.capitalize(), word.split(' ')))
</code>```

Body:
s = 'the brown fox'

...do something here...

s should be:

'The Brown Fox'

What's the easiest way to do this?

Body:
Another oneline solution could be:

" ".join(map(lambda d: d.capitalize(), word.split(' ')))


问:
Using macro as a range in C. Nested Loops. Logic
I am trying to make this program which takes YYYY and MM from the user. I have defined macros outside the main function, which is kinda range for years to be taken as input. For months, i have declared JAN and DEC as 1 and 12 respectively. What I am trying to is,show an error when something(month and year) is out of range, and the loop should repeat untill the right input has been entered. I tried my best to do that, but i didnt get anything. here is my code.</p>
```<code>#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>

#define MIN_YEAR 2012
#define MAX_YEAR 2022

int main(void)
{
    const int JAN = 1;
    const int DEC = 12;
    int year = 0;
    int month = 0;

    do
    {
        printf("Set the year and month(YYYY MM): ");
        scanf(" %d %d", &year, &month);

        if ((MIN_YEAR > year && year > MAX_YEAR))
        {
            printf("ERROR: The year must be between 2012 and 2022 inclusive");
        }

        if ((JAN >= month >= DEC))
        {
            printf("ERROR: Jan.(1) - Dec.(12)");
        }

        else
        {
            printf("*** Log date set! ***");
        }

    } while (MIN_YEAR <= year <= MAX_YEAR , JAN <= month <= DEC);

    return 0;
}
</code>```

答:
This condition

```<code>if ((MIN_YEAR > year && year > MAX_YEAR))
</code>```

is logically incorrect. It seems you mean

```<code>if ( year < MIN_YEAR || year > MAX_YEAR )
</code>```

The condition in this if statement

```<code>    if ((JAN >= month >= DEC))
</code>```

will always evaluate to false.

It is equivalent to

```<code>    if ( (JAN >= month ) >= DEC )
</code>```

So the sub-expression (JAN >= month ) evaluates either to 0 or 1 that in any case is less than DEC.

It seems you mean

```<code>    if ( month < JAN || month > DEC )
</code>```

In this condition

```<code>while (MIN_YEAR <= year <= MAX_YEAR , JAN <= month <= DEC)
</code>```

there is used the comma operator. Its value is the values of the second operand JAN <= month <= DEC. That is as the first operand has no side effect then in fact the first operand MIN_YEAR <= year <= MAX_YEAR is ignored and does not influence on the result.

It seems you mean

```<code>while ( year < MIN_YEAR || year > MAX_YEAR || month < JAN  || month > DEC)
</code>```

Also there is another logical error

```<code>    if ( ... )
    {
        printf("ERROR: The year must be between 2012 and 2022 inclusive");
    }

    if ( ... )
    {
        printf("ERROR: Jan.(1) - Dec.(12)");
    }

    else
    {
        printf("*** Log date set! ***");
    }
</code>```

The else statements belongs to the second if statement. So even if the year was entered incorrectly but the month was specified correctly then the else statement gets the control.

You should write for example

```<code>    if ( ... )
    {
        printf("ERROR: The year must be between 2012 and 2022 inclusive");
    }

    else if ( ... )
    {
        printf("ERROR: Jan.(1) - Dec.(12)");
    }

    else
    {
        printf("*** Log date set! ***");
    }
</code>```

Body:
I am trying to make this program which takes YYYY and MM from the user. I have defined macros outside the main function, which is kinda range for years to be taken as input. For months, i have declared JAN and DEC as 1 and 12 respectively. What I am trying to is,show an error when something(month and year) is out of range, and the loop should repeat untill the right input has been entered. I tried my best to do that, but i didnt get anything. here is my code.

#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>

#define MIN_YEAR 2012
#define MAX_YEAR 2022

int main(void)
{
    const int JAN = 1;
    const int DEC = 12;
    int year = 0;
    int month = 0;

    do
    {
        printf("Set the year and month(YYYY MM): ");
        scanf(" %d %d", &year, &month);

        if ((MIN_YEAR > year && year > MAX_YEAR))
        {
            printf("ERROR: The year must be between 2012 and 2022 inclusive");
        }

        if ((JAN >= month >= DEC))
        {
            printf("ERROR: Jan.(1) - Dec.(12)");
        }

        else
        {
            printf("*** Log date set! ***");
        }

    } while (MIN_YEAR <= year <= MAX_YEAR , JAN <= month <= DEC);

    return 0;
}

Body:
This condition

if ((MIN_YEAR > year && year > MAX_YEAR))

is logically incorrect. It seems you mean

if ( year < MIN_YEAR || year > MAX_YEAR )

The condition in this if statement

    if ((JAN >= month >= DEC))

will always evaluate to false.

It is equivalent to

    if ( (JAN >= month ) >= DEC )

So the sub-expression (JAN >= month ) evaluates either to 0 or 1 that in any case is less than DEC.

It seems you mean

    if ( month < JAN || month > DEC )

In this condition

while (MIN_YEAR <= year <= MAX_YEAR , JAN <= month <= DEC)

there is used the comma operator. Its value is the values of the second operand JAN <= month <= DEC. That is as the first operand has no side effect then in fact the first operand MIN_YEAR <= year <= MAX_YEAR is ignored and does not influence on the result.

It seems you mean

while ( year < MIN_YEAR || year > MAX_YEAR || month < JAN  || month > DEC)

Also there is another logical error

    if ( ... )
    {
        printf("ERROR: The year must be between 2012 and 2022 inclusive");
    }

    if ( ... )
    {
        printf("ERROR: Jan.(1) - Dec.(12)");
    }

    else
    {
        printf("*** Log date set! ***");
    }

The else statements belongs to the second if statement. So even if the year was entered incorrectly but the month was specified correctly then the else statement gets the control.

You should write for example

    if ( ... )
    {
        printf("ERROR: The year must be between 2012 and 2022 inclusive");
    }

    else if ( ... )
    {
        printf("ERROR: Jan.(1) - Dec.(12)");
    }

    else
    {
        printf("*** Log date set! ***");
    }


问:
build flat array of objects from tree object
I'm struggling with converting nested object to needed format. I want an array containing objects from nested object to suit table data format. Here are links for
format example and table i want

```<code>const data = [
    [
        "team",
        "year",
        "product",
        "downTime",
        "totalCount"
    ],
    {
        "metrics": [
            24965836704,
            25161192
        ],
        "children": [
            {
                "name": "UNDEFINED",
                "metrics": [
                    14697807552,
                    6858384
                ],
                "children": [
                    {
                        "name": "2021",
                        "metrics": [
                            14697807552,
                            6858384
                        ],
                        "children": [
                            {
                                "name": "UNDEFINED",
                                "metrics": [
                                    null,
                                    null
                                ]
                            },
                            {
                                "name": "cola",
                                "metrics": [
                                    14697807552,
                                    6858384
                                ]
                            }
                        ]
                    }
                ]
            },
            ...another object just like above
        ]
    }
]
</code>```

In short I want this piece of data above to be in form of like:

```<code>[
  { team: 'UNDEFINED', year: '2021', product: 'cola', downTime: 14697807552, totalCount: 6858384},
  { team: 'UNDEFINED', year: '2021', product: 'cola', downTime: 14697807552, totalCount: 6858384},
  ...
];
</code>```

Any help is appreciated!

答:
Maybe this works for you. it take the metrics from the final level.

const
    getFlat = (array, keys, level = 0) => array.flatMap(o => {
        const
            q = { [keys[level]]: o.name },
            m = Object.fromEntries(keys.slice(-2).map((k, i) => [k, o.metrics[i]]));

        return o.children
            ? getFlat(o.children, keys, level + 1).map(p => ({ ...q, ...p }))
            : { ...q, ...m };
    }),
    data = [["team", "year", "product", "downTime", "totalCount"], { metrics: [24965836704, 25161192], children: [{ name: "UNDEFINED", metrics: [14697807552, 6858384], children: [{ name: "2021", metrics: [14697807552, 6858384], children: [{ name: "UNDEFINED", metrics: [null, null] }, { name: "cola", metrics: [14697807552, 6858384] }] }] }] }],
    [keys, { children: array }] = data,
    result = getFlat(array, keys, 0);

console.log(result);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
I'm struggling with converting nested object to needed format. I want an array containing objects from nested object to suit table data format. Here are links for
format example and table i want

const data = [
    [
        "team",
        "year",
        "product",
        "downTime",
        "totalCount"
    ],
    {
        "metrics": [
            24965836704,
            25161192
        ],
        "children": [
            {
                "name": "UNDEFINED",
                "metrics": [
                    14697807552,
                    6858384
                ],
                "children": [
                    {
                        "name": "2021",
                        "metrics": [
                            14697807552,
                            6858384
                        ],
                        "children": [
                            {
                                "name": "UNDEFINED",
                                "metrics": [
                                    null,
                                    null
                                ]
                            },
                            {
                                "name": "cola",
                                "metrics": [
                                    14697807552,
                                    6858384
                                ]
                            }
                        ]
                    }
                ]
            },
            ...another object just like above
        ]
    }
]

In short I want this piece of data above to be in form of like:

[
  { team: 'UNDEFINED', year: '2021', product: 'cola', downTime: 14697807552, totalCount: 6858384},
  { team: 'UNDEFINED', year: '2021', product: 'cola', downTime: 14697807552, totalCount: 6858384},
  ...
];

Any help is appreciated!

Body:
Maybe this works for you. it take the metrics from the final level.

const
    getFlat = (array, keys, level = 0) => array.flatMap(o => {
        const
            q = { [keys[level]]: o.name },
            m = Object.fromEntries(keys.slice(-2).map((k, i) => [k, o.metrics[i]]));

        return o.children
            ? getFlat(o.children, keys, level + 1).map(p => ({ ...q, ...p }))
            : { ...q, ...m };
    }),
    data = [["team", "year", "product", "downTime", "totalCount"], { metrics: [24965836704, 25161192], children: [{ name: "UNDEFINED", metrics: [14697807552, 6858384], children: [{ name: "2021", metrics: [14697807552, 6858384], children: [{ name: "UNDEFINED", metrics: [null, null] }, { name: "cola", metrics: [14697807552, 6858384] }] }] }] }],
    [keys, { children: array }] = data,
    result = getFlat(array, keys, 0);

console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
convert string to char c
I am working on a project where I can to convert a api digit to a char. I have used an array of string pointers to get the conversion. However, I want to return just a single ch, as my api that I am using will only accept a char. So ap_five will return "5". But I want to five to be a single char '5'.

I thought maybe I could cast to a char in the return. However, I just get rubbish.

I am sure there is other ways to solve this, how I am just wondering how can I solve with my present program.

```<code>char *digits_conversion[][2]=
{
    {"ap_zero", "0"},
    {"ap_one", "1"},
    {"ap_two", "2"},
    {"ap_three", "3"},
    {"ap_four", "4"},
    {"ap_five", "5"},
    {"ap_six", "6"},
    {"ap_seven", "7"},
    {"ap_eight", "8"},
    {"ap_nine", "9"},
    {"ap_star", "*"},
    {"ap_hash", "#"},
    {NULL, NULL}
};

char convert_to_char(const char *digit)
{
    int i = 0;
    for(i = 0; *digits_conversion[i][1]; i++)
    {
        if(strcmp(digits_conversion[i][0], digit) == 0)
        {
            return (char) digits_conversion[i][1];
        }
    }

    return '\0';
}

int main(void)
{
    char ch;

    ch = convert_to_char("ap_five");

    printf("Converted digit: %c\n", ch);

    return 0;
}
</code>```

答:
The termination of your 'for' loop looks incorrect:

```<code>//...
    {"NULL", "NULL"}
//...
//...
for(i = 0; *digits_conversion[i][1]; i++)
//...
</code>```

The "NULL" you've got at the end of your array is literally, the string "NULL". If you pass a string that doesn't match any of the "ap_zero" through "ap_hash" your program will likely crash as the loop starts dereferencing garbage beyond the end of your array.

Eric fixed this in his example, but I thought I'd point this out specifically.

OwnerDisplayName: robUK

Title: convert string to char c

Body:
I am working on a project where I can to convert a api digit to a char. I have used an array of string pointers to get the conversion. However, I want to return just a single ch, as my api that I am using will only accept a char. So ap_five will return "5". But I want to five to be a single char '5'.

I thought maybe I could cast to a char in the return. However, I just get rubbish.

I am sure there is other ways to solve this, how I am just wondering how can I solve with my present program.

char *digits_conversion[][2]=
{
    {"ap_zero", "0"},
    {"ap_one", "1"},
    {"ap_two", "2"},
    {"ap_three", "3"},
    {"ap_four", "4"},
    {"ap_five", "5"},
    {"ap_six", "6"},
    {"ap_seven", "7"},
    {"ap_eight", "8"},
    {"ap_nine", "9"},
    {"ap_star", "*"},
    {"ap_hash", "#"},
    {NULL, NULL}
};

char convert_to_char(const char *digit)
{
    int i = 0;
    for(i = 0; *digits_conversion[i][1]; i++)
    {
        if(strcmp(digits_conversion[i][0], digit) == 0)
        {
            return (char) digits_conversion[i][1];
        }
    }

    return '\0';
}

int main(void)
{
    char ch;

    ch = convert_to_char("ap_five");

    printf("Converted digit: %c\n", ch);

    return 0;
}

LastEditorDisplayName: robUK

Body:
The termination of your 'for' loop looks incorrect:

//...
    {"NULL", "NULL"}
//...
//...
for(i = 0; *digits_conversion[i][1]; i++)
//...

The "NULL" you've got at the end of your array is literally, the string "NULL". If you pass a string that doesn't match any of the "ap_zero" through "ap_hash" your program will likely crash as the loop starts dereferencing garbage beyond the end of your array.

Eric fixed this in his example, but I thought I'd point this out specifically.

OwnerDisplayName: veefu

ContentLicense: CC BY-SA 2.5


问:
Expert R users, what's in your .Rprofile?
I have always found startup profile files of other people both useful and instructive about the language. Moreover, while I have some customization for Bash and Vim, I have nothing for R.

For example, one thing I always wanted is different colors for input and output text in a window terminal, and maybe even syntax highlighting.

答:
I often have a chain of debug calls I need to call and uncommenting them can be very tedious. With the help of the SO community, I went for the following solution and inserted this into my .Rprofile.site. # BROWSER is there for my Eclipse Tasks so that I have an overview of browser calls in the Task View window.

```<code># turn debugging on or off
# place "browser(expr = isTRUE(getOption("debug"))) # BROWSER" in your function
# and turn debugging on or off by bugon() or bugoff()
bugon <- function() options("debug" = TRUE)
bugoff <- function() options("debug" = FALSE) #pun intended
</code>```

Body:
I often have a chain of debug calls I need to call and uncommenting them can be very tedious. With the help of the SO community, I went for the following solution and inserted this into my .Rprofile.site. # BROWSER is there for my Eclipse Tasks so that I have an overview of browser calls in the Task View window.

# turn debugging on or off
# place "browser(expr = isTRUE(getOption("debug"))) # BROWSER" in your function
# and turn debugging on or off by bugon() or bugoff()
bugon <- function() options("debug" = TRUE)
bugoff <- function() options("debug" = FALSE) #pun intended


问:
Spark Scala - how to use $"col" and S string interpolation together?
I want to achieve this, with a $ instead of col()

```<code>val x = "id"
df.select(col(s"$x"))
</code>```

This gives me an error

```<code>df.select($s"$x")
</code>```

But this works -- How is it working without the s prefix? And is this the correct way?

```<code>df.select($"$x")
</code>```

Thanks.

答:
Yes this is correct $"$x" and will return column col("id"). It's working because the method $ is defined like this in SQLImplicits:

implicit class StringToColumn(val sc: StringContext) {
  def $(args: Any*): ColumnName = {
    new ColumnName(sc.s(args: _*))
  }
}
```

As you can see, we call StringContext.sc method which does the string interpolation.

Body:
I want to achieve this, with a $ instead of col()

val x = "id"
df.select(col(s"$x"))

This gives me an error

df.select($s"$x")

But this works -- How is it working without the s prefix? And is this the correct way?

df.select($"$x")

Thanks.

Body:
Yes this is correct $"$x" and will return column col("id"). It's working because the method $ is defined like this in SQLImplicits:

implicit class StringToColumn(val sc: StringContext) {
  def $(args: Any*): ColumnName = {
    new ColumnName(sc.s(args: _*))
  }
}

As you can see, we call StringContext.sc method which does the string interpolation.


问:
Set template in the input box
I want to create a template inside the input box:
when i click on the input it will automatically select me the word "yourName" and (maybe) pressing tab switch to the word "yourEmail".
Basically I want that the user can modify ONLY "yourName" and "yourEmail", the rest must remain like that, how do I do?

input {
  width: 200px;
  height: 20px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="text" value="<yourName>(yourEmail)"></code>```

答:
You can use two inputs and fake the border like the following.
The look is not really nice, but you can apply your own styles to it.

div {
  border: 1px solid grey;
  border-radius: 2px;
  width: max-content;
}

div:hover {
  border-color: dimgrey;
}

div input {
  display: inline;
  min-width: 7rem;
  width: max-content;
  /* you could add the following line, if you want no outlining on focus */
  /*  outline: none;*/
  border: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <span><</span>
  <input type="text" placeholder="yourname">
  <span>></span>
  <span>(</span>
  <input type="email" placeholder="yourEmail">
  <span>)</span>
</div></code>```

Title: Set template in the input box

Body:
I want to create a template inside the input box:
when i click on the input it will automatically select me the word "yourName" and (maybe) pressing tab switch to the word "yourEmail".
Basically I want that the user can modify ONLY "yourName" and "yourEmail", the rest must remain like that, how do I do?

input {
  width: 200px;
  height: 20px;
}

<input type="text" value="<yourName>(yourEmail)">

Body:
You can use two inputs and fake the border like the following.
The look is not really nice, but you can apply your own styles to it.

div {
  border: 1px solid grey;
  border-radius: 2px;
  width: max-content;
}

div:hover {
  border-color: dimgrey;
}

div input {
  display: inline;
  min-width: 7rem;
  width: max-content;
  /* you could add the following line, if you want no outlining on focus */
  /*  outline: none;*/
  border: none;
}

<div>
  <span>&lt;</span>
  <input type="text" placeholder="yourname">
  <span>&gt;</span>
  <span>(</span>
  <input type="email" placeholder="yourEmail">
  <span>)</span>
</div>


问:
strapi graphql Cannot query anything
Reading article A Deep Dive into Strapi GraphQL

REST API work fine

```<code>http://localhost:1337/api/blogs?filters[id][$eq]=1
</code>```

But GraphQL Not

```<code>query {
    blogs {
        id
        Title
        Body
    }
}
</code>```

Response

```<code>{
    "errors": [
        {
            "message": "Cannot query field \"id\" on type \"BlogEntityResponseCollection\".",
        }
        ...
    }
}
</code>```

Strapi v4.0.7 node v14.17.5
Using GraphQL extension for chrome and Altai client for query
Try start Strapi with:

yarn start

yarn develop

答:
using GraphQL playground for chrome hints i make queries like that, different from article</p>
```<code>query {
  blog(id: 1) {
    data {
      attributes{
        Title
      }
    }
  }
}
</code>```

Title: strapi graphql Cannot query anything

Body:
Reading article A Deep Dive into Strapi GraphQL

REST API work fine

http://localhost:1337/api/blogs?filters[id][$eq]=1

But GraphQL Not

query {
    blogs {
        id
        Title
        Body
    }
}

Response

{
    "errors": [
        {
            "message": "Cannot query field \"id\" on type \"BlogEntityResponseCollection\".",
        }
        ...
    }
}

Strapi v4.0.7 node v14.17.5
Using GraphQL extension for chrome and Altai client for query
Try start Strapi with:

yarn start

yarn develop

Body:
using GraphQL playground for chrome hints i make queries like that, different from article

query {
  blog(id: 1) {
    data {
      attributes{
        Title
      }
    }
  }
}


问:
Problem with handling path length
I'm creating library which will be used for file manipulations, both on linux and windows. So I need to handle paths, the main requirements is that my functions will recieve strings in UTF8 format. But it causes some problems, one of them is I'm using MAX_PATH on windows and PATH_MAX in linux, to represent static path variables. In the case of ASCII characters there will be no problem, but when path contains unicode characters, the length of path will be twice shorter if unicode char requires 2 bytes per char, 3 times shorter if unicode char requires 3 bytes per char and so on. So is there good solution for this problem?

Thanks in advance!

p.s. sorry for my english.

答:
UTF-8 is multibyte encoding format ranging from 1 to 4 bytes per character.
As you want to statically define max path value, you may need to define max path as n*4 (where n is the path length in ASCII characters you want to define) to accommodate UTF-8 encoded characters.

Title: Problem with handling path length


问:
How to add fonts to windows servercore 2019 with IIS
I'm trying to host a http to pdf web solution in windows servercore 2019 container with IIS.
The problem is that windows servercore 2019 container only has one font.
I searched and tried to add fonts to the container. It worked fine.

However, my solution is behind IIS, and IIS doesn't seem to pickup the new fonts. How do I let IIS pickup new fonts in windows\fonts folder?

I read somewhere that I have to restart IIS to pickup font changes? But I can't restart IIS in windows servercore container, right? It's entry point is server monitor that monitors IIS.

The Dockerfile:

```<code># escape=`

# base Image
FROM mcr.microsoft.com/dotnet/framework/aspnet:4.8-windowsservercore-ltsc2019 AS base

SHELL ["powershell", "-Command", "$ErrorActionPreference = 'Stop'; $ProgressPreference = 'SilentlyContinue';"]
COPY dotnet-hosting-6.0.1-win.exe .
RUN ./dotnet-hosting-6.0.1-win.exe /quiet /install
# Install Visual C++ Redistributable Packages for Visual Studio 2013
COPY vcredist_x64.exe .
RUN ./vcredist_x64.exe /passive
# Add fonts to the image
COPY Fonts/* /Windows/Fonts/

COPY FontReg.exe .
RUN ./FontReg.exe

# Configure web servers to bind to port 80 when present
ENV ASPNETCORE_URLS=http://+:80 `
    # Enable detection of running in a container
    DOTNET_RUNNING_IN_CONTAINER=true

WORKDIR /app
EXPOSE 80

====== SKIP SOLUTION BUILD ======

FROM base AS final
WORKDIR /inetpub/wwwroot
COPY --from=publish /app/publish .

</code>```

答:
Problem solved.

The idea is to get a clean servercore 2019 image, install fonts first, and then enable IIS. It'll pickup all the installed fonts.

Body:
I'm trying to host a http to pdf web solution in windows servercore 2019 container with IIS.
The problem is that windows servercore 2019 container only has one font.
I searched and tried to add fonts to the container. It worked fine.

However, my solution is behind IIS, and IIS doesn't seem to pickup the new fonts. How do I let IIS pickup new fonts in windows\fonts folder?

I read somewhere that I have to restart IIS to pickup font changes? But I can't restart IIS in windows servercore container, right? It's entry point is server monitor that monitors IIS.

The Dockerfile:

# escape=`

# base Image
FROM mcr.microsoft.com/dotnet/framework/aspnet:4.8-windowsservercore-ltsc2019 AS base

SHELL ["powershell", "-Command", "$ErrorActionPreference = 'Stop'; $ProgressPreference = 'SilentlyContinue';"]
COPY dotnet-hosting-6.0.1-win.exe .
RUN ./dotnet-hosting-6.0.1-win.exe /quiet /install
# Install Visual C++ Redistributable Packages for Visual Studio 2013
COPY vcredist_x64.exe .
RUN ./vcredist_x64.exe /passive
# Add fonts to the image
COPY Fonts/* /Windows/Fonts/

COPY FontReg.exe .
RUN ./FontReg.exe

# Configure web servers to bind to port 80 when present
ENV ASPNETCORE_URLS=http://+:80 `
    # Enable detection of running in a container
    DOTNET_RUNNING_IN_CONTAINER=true

WORKDIR /app
EXPOSE 80

====== SKIP SOLUTION BUILD ======

FROM base AS final
WORKDIR /inetpub/wwwroot
COPY --from=publish /app/publish .


问:
List all harddrives in a linux system
I'm having problems to detect which one of my block devices is the hard drive. My system has a cd-rom drive, USB drives, and a single hard drive of unknown vendor/type.

How can I identify the hard drive with a linux command, script, or C application?

答:
If you have a list of the plausible block devices, then the file

/sys/block/[blockdevname]/removable

will contain "1" if the device is removable, "0" if not removable.

Title: List all harddrives in a linux system


问:
Quadratic Equation with Python and Flask
So currently I am trying to make a program using flask, but I am getting a TypeError when I run it, saying The view function for 'post_factors' did not return a valid response. The function either returned None or ended without a return statement. and I cannot figure how to fix it. Here is the code:

```<code>import math

def dofactors(a, b, c):
    a = int(a)
    b = int(b)
    c = int(c)
    d = b**2-4*a*c # discriminant

    if d < 0:
        result = 'No solutions'
    elif d == 0:
        x1 = -b / (2*a)
        result = f'The sole solution is {str(x1)}'
    else: # if d > 0
        x1 = (-b + math.sqrt(d)) / (2*a)
        x2 = (-b - math.sqrt(d)) / (2*a)
        result = f'Solutions are {str(x1)} and {str(x2)}'

    return(result)
</code>```

and the HTML:

```<code><!DOCTYPE html>
<form method="POST">
  <p><h1>Factorizer</h1></p>
    <p>please enter your variable values assuming the form ax^2+bx+c</p>
  <input type="text", placeholder="a", name="a" oninput="this.value = this.value.replace(/[^0-9.-]/g, '').replace(/(\..*)\./g, '$1');" />
  <input type="text", placeholder="b", name="b" oninput="this.value = this.value.replace(/[^0-9.-]/g, '').replace(/(\..*)\./g, '$1');" />
  <input type="text", placeholder="c", name="c" oninput="this.value = this.value.replace(/[^0-9.-]/g, '').replace(/(\..*)\./g, '$1');" />
  <input type="submit">
</form>
</code>```

EDIT: I forgot to include the code that is calling it in the main class, here it is:

```<code>@app.route('/factors')
def form_factors():
    return render_template('factors.html')
</code>```

and the POST function:

```<code>@app.route('/factors', methods=['POST'])
def post_factors():
    a = str(request.form['a'])
    b = str(request.form['b'])
    c = str(request.form['c'])
    dofactors(a, b, c)
</code>```

答:
You are returning values in your dofactor function, but these 'return's don't apply to the route as they are in a different scope. You could fix this with the following in your post_factors route.

```<code>return(dofactors(a, b, c))
</code>```

Body:
So currently I am trying to make a program using flask, but I am getting a TypeError when I run it, saying The view function for 'post_factors' did not return a valid response. The function either returned None or ended without a return statement. and I cannot figure how to fix it. Here is the code:

import math

def dofactors(a, b, c):
    a = int(a)
    b = int(b)
    c = int(c)
    d = b**2-4*a*c # discriminant

    if d < 0:
        result = 'No solutions'
    elif d == 0:
        x1 = -b / (2*a)
        result = f'The sole solution is {str(x1)}'
    else: # if d > 0
        x1 = (-b + math.sqrt(d)) / (2*a)
        x2 = (-b - math.sqrt(d)) / (2*a)
        result = f'Solutions are {str(x1)} and {str(x2)}'

    return(result)

and the HTML:

<!DOCTYPE html>
<form method="POST">

Factorizer

please enter your variable values assuming the form ax^2+bx+c

  <input type="text", placeholder="a", name="a" oninput="this.value = this.value.replace(/[^0-9.-]/g, '').replace(/(\..*)\./g, '$1');" />
  <input type="text", placeholder="b", name="b" oninput="this.value = this.value.replace(/[^0-9.-]/g, '').replace(/(\..*)\./g, '$1');" />
  <input type="text", placeholder="c", name="c" oninput="this.value = this.value.replace(/[^0-9.-]/g, '').replace(/(\..*)\./g, '$1');" />
  <input type="submit">
</form>

EDIT: I forgot to include the code that is calling it in the main class, here it is:

@app.route('/factors')
def form_factors():
    return render_template('factors.html')

and the POST function:

@app.route('/factors', methods=['POST'])
def post_factors():
    a = str(request.form['a'])
    b = str(request.form['b'])
    c = str(request.form['c'])
    dofactors(a, b, c)

Body:
You are returning values in your dofactor function, but these 'return's don't apply to the route as they are in a different scope. You could fix this with the following in your post_factors route.

return(dofactors(a, b, c))


问:
Remove multiple spaces and new lines inside of String
Suppose we have string like this:

```<code>Hello, my\n       name is Michael.
</code>```

How can I remove that new line and strip those spaces after that into one inside of string to get this?

```<code>Hello, my name is Michael.
</code>```

答:
check out Rails squish method:

https://api.rubyonrails.org/classes/String.html#method-i-squish

Body:
Suppose we have string like this:

Hello, my\n       name is Michael.

How can I remove that new line and strip those spaces after that into one inside of string to get this?

Hello, my name is Michael.


问:
How to combine security with the gateway?
I'm investigating microservices architecture and now focusing on the api gateway along with security.

I found out that there are two different approaches:

1- Where authentication is outside of the gateway, meaning, the user

has to authenticate first,

gets the token,

and then can make calls to the services via the gateway
The most common scenario I've seen that everyone is implementing/presenting) as described on the diagram link
Authentication outside of the gateway

2- Another way is to have everything behind the gateway, which means, user

tries to access a secured resource/service via de the gateway,

he's being redirected to the identity provider login page via the gateway as well,

gets authenticated, the token is passed back to the client/user,

and finally reaches the request service, everything through one http call via the gateway which will result in some additional calls (authorization code flow, url call back to the client, as described on the diagram link as well Authentication behind the gateway

And while some might speak about the 2nd approach, I can't seem to find any actual implementation or detailed description. Which makes me wanna ask ... why?

If I'm following a microservices design, I would naturally have the 2nd implementation, but no ... everyone appeared to be using the 1st one.

According to what I've read, yes, it takes more efforts since you'd have to reroute the necessary authentication and authorization endpoint, but is that it? Aren't there any other reasons which would make us favor the 1st one rather the 2nd one?

Any insights?

答:
Short answer:

The second option is the most common. And you're right. If you don't need to redirect the user, don't.

Long answer:

Before microservices, all of the 'services' were different routes within a single application. The application routed user traffic to the right place.

Putting a gateway in the middle is abstracting that first level router from the single application to its own application.

If the gateway is only routing traffic to backend services, then it's a load balancer (aka application aware proxy, reverse proxy, etc.) The load balancer is a frontend service that redirects traffic to the right internal backend service.

If the gateway is both serving pages, and routing traffic to backend services, then it's a web application and a load balancer.

People who talk about authentication flows that use different user-visible targets (urls) are solving common problems. 3 reasons I can think of:

To make it really clear in diagrams which part is auth and which part is the black box service

As organizations grow, many people build their own services and auth flows. One for the first product, then another one for their next product, and a third for their third product. At some point they need to rationalize how to consolidate their auth into one flow.

Different URLs set different cookie scopes. Sometimes you need many domains to isolate cookies.

Example, take a service like Google Oauth or Okta SAML - you need to login on their domain, and you need a way to get the token back to your domain. Since you can't see google.com or okta.com cookies on yoursite.com, the external flows are necessary. This is often the case as companies add products that have different domains.

Google products redirect a few times every time you login. They are doing cookie management from accounts.google.com to gmail.google.com and keeping google.com cookies isolated the whole time. However, you're hitting the same google load balancer every time (or you theoretically you could).


问:
A C program process is waited by some OS routine?
Well, I'm learning about processes using the C language, and I have seen that when you call the exit function a process is terminated and without waiting for it, it will become a zombie process. My question is, if the first process created when executing the program is a process itself, is there a 0S routine that wait for it after an exit() call, avoiding that it becomes a zombie process? I'm curious about it.</p>

答:
For Unix systems at least (and I expect Windows is similar), when the system boots, it creates one special first process. Every process after that is created by some existing process.

When you log into a windowed desktop interface, there is some desktop manager process (that has been created by the first process or one of its descendants) managing windows. When you start a program by clicking on it, that desktop manager or one of its children (maybe some file manager software) creates a process to run the program. When you start a program by executing a command in a terminal window, there is a command line shell process that is interpreting the things you type, and it creates a process to run the program.

So, in all cases, your user program has a parent process, either a command-line shell or some desktop software.


答:
If a child process creates another child (even as the first instruction) then the parent also has to wait for it or it becomes a zombie.

Basically processes always become zombie until they are removed from the process table, the OS (via the process init) will handle and wait() for orphans (zombies without parents), it does that periodically so normally you won't have orphans running for very long.

Title: A C program process is waited by some OS routine?

Body: Well, I'm learning about processes using the C language, and I have seen that when you call the exit function a process is terminated and without waiting for it, it will become a zombie process. My question is, if the first process created when executing the program is a process itself, is there a 0S routine that wait for it after an exit() call, avoiding that it becomes a zombie process? I'm curious about it.


问:
How to login to wikipedia using mediawiki API through?
I already have two working bots in Wikipedia, but they use different method.
Currently, I am trying to create a bot using C#. On the API documentation page, they have provided some sample codes in java, PHP, and python. But unfortunately, they haven't provided any sample code in C#. It is the only language I am familiar with.

This is the Wikimedia API:Edit documentation page. Would someone kindly convert the few words from java (or any other language) to C#?

If I could get only this code converted to C#, I can build the rest of the bot by myself.
I asked help on the relevant noticeboard(s) on the wikimedia site(s), but nobody there is familiar with C#. That's why I am now asking this outside of wikipedia.

Thanks a lot in advance

This is the java source-code:

```

/*
edit.js

MediaWiki API Demos
Demo of `Login` module: Sending post request to login

MIT license
*/

var request = require( 'request' ).defaults( { jar: true } ),
url = 'https://test.wikipedia.org/w/api.php';

// Step 1: GET request to fetch login token
function getLoginToken() {
var params = {
    action: 'query',
    meta: 'tokens',
    type: 'login',
    format: 'json'
};

request.get( { url: url, qs: params }, function ( error, res, body ) {
    var data;
    if ( error ) {
        return;
    }
    data = JSON.parse( body );
    loginRequest( data.query.tokens.logintoken );
} );
}

// Step 2: POST request to log in.
// Use of main account for login is not
// supported. Obtain credentials via Special:BotPasswords
// (https://www.mediawiki.org/wiki/Special:BotPasswords) for lgname & lgpassword
function loginRequest( loginToken ) {
var params = {
    action: 'login',
    lgname: 'bot_username',
    lgpassword: 'bot_password',
    lgtoken: loginToken,
    format: 'json'
};

request.post( { url: url, form: params }, function ( error, res, body ) {
    if ( error ) {
        return;
    }
    console.log( body );
} );
}

// Start From Step 1
getLoginToken();</code>```

答:
You can try something like this

```<code>private static async Task LoginRequest(string loginToken)
{
    var data = new
    {
        action = "login",
        lgname = "bot_username",
        lgpassword = "bot_password",
        lgtoken = loginToken,
        format = "json"
    };
    using (var client = new HttpClient())
    using (var response = await client.PostAsJsonAsync(LOGIN_URL, data))
    {
        var responseString = await response.Content.ReadAsStringAsync();
        var responseObject = JsonConvert.DeserializeObject<JObject>(responseString);
        Console.WriteLine(responseObject);
    }
}

private static async Task<string?> GetLoginToken()
{
    var url = $"{LOGIN_URL}?action=query&meta=tokens&type=login&format=json";
    using (var client = new HttpClient())
    using (var response = await client.GetAsync(url))
    {
        var responseString = await response.Content.ReadAsStringAsync();
        var responseObject = JsonConvert.DeserializeObject<JObject>(responseString);
        return responseObject?["query"]?["tokens"]?["logintoken"]?.ToString();
    }
}
</code>```

For converting the response you need

```<code>using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
</code>```

You can call these methods from your Main method like this:

```<code>const string LOGIN_URL = "https://test.wikipedia.org/w/api.php";

public static async Task Main()
{
    var loginToken = await GetLoginToken();
    await LoginRequest(loginToken ?? throw new Exception("No login token."));
}
</code>```

Body:
You can try something like this

private static async Task LoginRequest(string loginToken)
{
    var data = new
    {
        action = "login",
        lgname = "bot_username",
        lgpassword = "bot_password",
        lgtoken = loginToken,
        format = "json"
    };
    using (var client = new HttpClient())
    using (var response = await client.PostAsJsonAsync(LOGIN_URL, data))
    {
        var responseString = await response.Content.ReadAsStringAsync();
        var responseObject = JsonConvert.DeserializeObject<JObject>(responseString);
        Console.WriteLine(responseObject);
    }
}

private static async Task<string?> GetLoginToken()
{
    var url = $"{LOGIN_URL}?action=query&meta=tokens&type=login&format=json";
    using (var client = new HttpClient())
    using (var response = await client.GetAsync(url))
    {
        var responseString = await response.Content.ReadAsStringAsync();
        var responseObject = JsonConvert.DeserializeObject<JObject>(responseString);
        return responseObject?["query"]?["tokens"]?["logintoken"]?.ToString();
    }
}

For converting the response you need

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

You can call these methods from your Main method like this:

const string LOGIN_URL = "https://test.wikipedia.org/w/api.php";

public static async Task Main()
{
    var loginToken = await GetLoginToken();
    await LoginRequest(loginToken ?? throw new Exception("No login token."));
}