问:
Looking for an efficient way of making a new data frame of totals across categories in R
Total R beginner here, looking for the quickest / most sensible way to do this:

I have a data frame that looks similar to this (but much longer):

dataframe:

date
a
b
c

1/1/2021
4
3
2

1/2/2021
2
2
1

1/3/2021
5
3
5

I am attempting to create a new data frame showing totals for a, b, and c (which go on for a while), and don't need the dates. I want to make a data frame that would look this:

letter
total

a
11

b
8

c
8

So far, the closest I have got to this is by writing a pipe like this:

```<code>dataframe <- totals %>%
   summarize(total_a = sum(a), total_b = sum(b), total_c = sum(c))
</code>```

which almost gives me what I want, a data frame that looks like this:
|a|b|c|
|:-:|:-:|:-:|
|11|8|8|

Is there a way (besides manually typing out a new data frame for totals) to quickly turn my totals table into the format I'm looking for? Or is there a better way to write the pipe that will give me the table I want? I want to use these totals to make a pie chart but am running into problems when I attempt to make a pie chart out of the table like I have it now. I really appreciate any help in advance and hope I was able to explain what I'm trying to do correctly.

答:
Try this :

```<code>totals %>% select(a:c) %>% colSums() %>% as.list() %>% as_tibble() %>%
  pivot_longer(everything(), names_to = "letter", values_to = "total")
</code>```

Actually totals %>% select(a:c) %>% colSums() gives what you need as a named vector and the next steps are to turn that into a tibble again. You can skip that part if you don't need it.

Body:
Total R beginner here, looking for the quickest / most sensible way to do this:

I have a data frame that looks similar to this (but much longer):

dataframe:

date
a
b
c

1/1/2021
4
3
2

1/2/2021
2
2
1

1/3/2021
5
3
5

I am attempting to create a new data frame showing totals for a, b, and c (which go on for a while), and don't need the dates. I want to make a data frame that would look this:

letter
total

a
11

b
8

c
8

So far, the closest I have got to this is by writing a pipe like this:

dataframe <- totals %>%
   summarize(total_a = sum(a), total_b = sum(b), total_c = sum(c))

which almost gives me what I want, a data frame that looks like this:
|a|b|c|
|:-:|:-:|:-:|
|11|8|8|

Is there a way (besides manually typing out a new data frame for totals) to quickly turn my totals table into the format I'm looking for? Or is there a better way to write the pipe that will give me the table I want? I want to use these totals to make a pie chart but am running into problems when I attempt to make a pie chart out of the table like I have it now. I really appreciate any help in advance and hope I was able to explain what I'm trying to do correctly.

Body:
Try this :

totals %>% select(a:c) %>% colSums() %>% as.list() %>% as_tibble() %>%
  pivot_longer(everything(), names_to = "letter", values_to = "total")

Actually totals %>% select(a:c) %>% colSums() gives what you need as a named vector and the next steps are to turn that into a tibble again. You can skip that part if you don't need it.


来源: stackexchange

问:
Using input tag helper "name" and getting input value empty. ASP.NET MVC (.NET 5)
I have simple form for creating items

```<code>    <form asp-action="CreateItem" enctype="multipart/form-data">
            <div class="form-group">
                <label asp-for="@Model.ItemPhoto" class="control-label"></label>
                <input type="file" asp-for="@Model.ItemPhoto" name="Photo" class="form-control-file" />
                <span asp-validation-for="@Model.ItemPhoto" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="@Model.Name" class="control-label"></label>
                <input asp-for="@Model.Name" class="form-control" />
                <span asp-validation-for="@Model.Name" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="@Model.ItemType" class="control-label"></label>
                <select asp-for="@Model.ItemType" class="form-control">
                    @foreach (var itemType in Enum.GetValues(typeof(RandApp.Enums.ItemType)))
                    {
                        <option value="@itemType.ToString()">@itemType</option>
                    }
                </select>
                <span asp-validation-for="@Model.ItemType" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="@Model.MaterialType" class="control-label"></label>
                <select asp-for="@Model.MaterialType" class="form-control">
                    @foreach (var materialType in Enum.GetValues(typeof(RandApp.Enums.MaterialType)))
                    {
                        <option value="@materialType.ToString()">@materialType</option>
                    }
                </select>
                <span asp-validation-for="@Model.MaterialType" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="@Model.Color" class="control-label"></label>
                <select asp-for="@Model.Color" class="form-control">
                    @foreach (var color in Enum.GetValues(typeof(RandApp.Enums.ItemColor)))
                    {
                        <option value="@color.ToString()">@color</option>
                    }
                </select>
                <span asp-validation-for="@Model.Color" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="@Model.Size" class="control-label"></label>
                <select asp-for="@Model.Size" class="form-control">
                    @foreach (var size in Enum.GetValues(typeof(RandApp.Enums.ItemSize)))
                    {
                        <option value="@size.ToString()">@size</option>
                    }
                </select>
                <span asp-validation-for="@Model.Size" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="@Model.DesignedFor" class="control-label"></label>
                <select asp-for="@Model.DesignedFor" class="form-control">
                    @foreach (var desigendFor in Enum.GetValues(typeof(RandApp.Enums.DesignedFor)))
                    {
                        <option value="@desigendFor.ToString()">@desigendFor</option>
                    }
                </select>
                <span asp-validation-for="@Model.DesignedFor" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="@Model.Price" class="control-label"></label>
                <input asp-for="@Model.Price" class="form-control" />
                <span asp-validation-for="@Model.Price" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="@Model.Description" class="control-label"></label>
                <textarea asp-for="@Model.Description" class="form-control"></textarea>
                <span asp-validation-for="@Model.Description" class="text-danger"></span>
            </div>
            <div class="form-group">
                <input type="submit" value="Create" class="btn btn-primary" />
            </div>
        </form>
</code>```

there is its controller

```<code>public async Task<IActionResult> CreateItem(Item item, IFormFile Photo)
        {
            if (ModelState.IsValid)
            {
                var path = Path.Combine(_webHostEnvironment.WebRootPath, "assets", Photo.FileName);
                var stream = new FileStream(path, FileMode.Create);
                await Photo.CopyToAsync(stream);
                item.ItemPhoto = Photo.FileName;
                await _itemRepo.CreateAsync(item);
                ViewBag.Item = item;
                return RedirectToAction("ReadItems");
            }

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

my goal is to get the path of chosen photo and save it in folder called "assets"(located in "wwwroot" folder).
The problem is that when i fill the fields and submitting the values, i get item.ItemPhoto value null and i can't enter in if statement. (see the photo down below).
[1]: https://i.stack.imgur.com/H2aLt.png

one solution i have found is to remove "enctype="multipart/form-data" from form and "name="Photo" tag helper from input

```<code><form asp-action="CreateItem" enctype="multipart/form-data">
            <div class="form-group">
                <label asp-for="@Model.ItemPhoto" class="control-label"></label>
                <input type="file" asp-for="@Model.ItemPhoto" name="Photo" class="form-control-file" />
                <span asp-validation-for="@Model.ItemPhoto" class="text-danger"></span>
            </div>
</code>```

but in this case i can't get the path properly.
what can i do to solve this problem, why am i getting empty value from input?

答:
File and string type cannot be passed together with the same name automatically and cannot achieve this requirement by using just one input. You can set a hidden input for ItemPhoto and use js to set the value when the file changed:

```<code>@model Item
<form asp-action="CreateItem" enctype="multipart/form-data">
            <div class="form-group">
                <label asp-for="@Model.ItemPhoto" class="control-label"></label>
                                    //change here...
                <input type="file" name="ItemPhoto" class="form-control-file" onchange="SetValue(this)"  />
                             //add hidden input......
                <input asp-for="@Model.ItemPhoto" hidden/>
                <span asp-validation-for="@Model.ItemPhoto" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="@Model.Name" class="control-label"></label>
                <input asp-for="@Model.Name" class="form-control" />
                <span asp-validation-for="@Model.Name" class="text-danger"></span>
            </div>
            <input type="submit" value="Create"/>
</form>
@section Scripts
{
    <script>
        function SetValue(input) {
            var fileName = input.files[0].name;
            //asp-for will generate the id and name
            //so you can get the selector by using $("#ItemPhoto")
            $("#ItemPhoto").val(fileName);
        }
    </script>
}
</code>```

Backend (The name attribute should always match with the parameter/property name):

```<code>public async Task<IActionResult> CreateItem(Item item, IFormFile ItemPhoto)
{
    //....
    return View();
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have simple form for creating items

    <form asp-action="CreateItem" enctype="multipart/form-data">

                <input type="file" asp-for="@Model.ItemPhoto" name="Photo" class="form-control-file" />

                <input asp-for="@Model.Name" class="form-control" />

                <select asp-for="@Model.ItemType" class="form-control">
                    @foreach (var itemType in Enum.GetValues(typeof(RandApp.Enums.ItemType)))
                    {
                        <option value="@itemType.ToString()">@itemType</option>
                    }
                </select>

                <select asp-for="@Model.MaterialType" class="form-control">
                    @foreach (var materialType in Enum.GetValues(typeof(RandApp.Enums.MaterialType)))
                    {
                        <option value="@materialType.ToString()">@materialType</option>
                    }
                </select>

                <select asp-for="@Model.Color" class="form-control">
                    @foreach (var color in Enum.GetValues(typeof(RandApp.Enums.ItemColor)))
                    {
                        <option value="@color.ToString()">@color</option>
                    }
                </select>

                <select asp-for="@Model.Size" class="form-control">
                    @foreach (var size in Enum.GetValues(typeof(RandApp.Enums.ItemSize)))
                    {
                        <option value="@size.ToString()">@size</option>
                    }
                </select>

                <select asp-for="@Model.DesignedFor" class="form-control">
                    @foreach (var desigendFor in Enum.GetValues(typeof(RandApp.Enums.DesignedFor)))
                    {
                        <option value="@desigendFor.ToString()">@desigendFor</option>
                    }
                </select>

                <input asp-for="@Model.Price" class="form-control" />

                <textarea asp-for="@Model.Description" class="form-control"></textarea>

                <input type="submit" value="Create" class="btn btn-primary" />

        </form>

there is its controller

public async Task<IActionResult> CreateItem(Item item, IFormFile Photo)
        {
            if (ModelState.IsValid)
            {
                var path = Path.Combine(_webHostEnvironment.WebRootPath, "assets", Photo.FileName);
                var stream = new FileStream(path, FileMode.Create);
                await Photo.CopyToAsync(stream);
                item.ItemPhoto = Photo.FileName;
                await _itemRepo.CreateAsync(item);
                ViewBag.Item = item;
                return RedirectToAction("ReadItems");
            }

            return View();
        }

my goal is to get the path of chosen photo and save it in folder called "assets"(located in "wwwroot" folder).
The problem is that when i fill the fields and submitting the values, i get item.ItemPhoto value null and i can't enter in if statement. (see the photo down below).
[1]: https://i.stack.imgur.com/H2aLt.png

one solution i have found is to remove "enctype="multipart/form-data" from form and "name="Photo" tag helper from input

<form asp-action="CreateItem" enctype="multipart/form-data">

                <input type="file" asp-for="@Model.ItemPhoto" name="Photo" class="form-control-file" />

but in this case i can't get the path properly.
what can i do to solve this problem, why am i getting empty value from input?

Body:
File and string type cannot be passed together with the same name automatically and cannot achieve this requirement by using just one input. You can set a hidden input for ItemPhoto and use js to set the value when the file changed:

@model Item
<form asp-action="CreateItem" enctype="multipart/form-data">
            <div class="form-group">
                <label asp-for="@Model.ItemPhoto" class="control-label"></label>
                                    //change here...
                <input type="file" name="ItemPhoto" class="form-control-file" onchange="SetValue(this)"  />
                             //add hidden input......
                <input asp-for="@Model.ItemPhoto" hidden/>
                <span asp-validation-for="@Model.ItemPhoto" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="@Model.Name" class="control-label"></label>
                <input asp-for="@Model.Name" class="form-control" />
                <span asp-validation-for="@Model.Name" class="text-danger"></span>
            </div>
            <input type="submit" value="Create"/>
</form>
@section Scripts
{
    <script>
        function SetValue(input) {
            var fileName = input.files[0].name;
            //asp-for will generate the id and name
            //so you can get the selector by using $("#ItemPhoto")
            $("#ItemPhoto").val(fileName);
        }
    </script>
}

Backend (The name attribute should always match with the parameter/property name):

public async Task<IActionResult> CreateItem(Item item, IFormFile ItemPhoto)
{
    //....
    return View();
}


问:
How do I sort negative and positive values from a datagridview in vb.net?
I am relatively new to coding, and i was hoping someone could help me with sorting a column of negative and positive values in a datagridview. It is not connected to a datatable, as I am only reading the values from a textfile, that uses commas to separate each bits of data and display it in the datagridview. I have tried to use this code:

```<code>DGV.Sort(DGV.Columns(2), System.ComponentModel.ListSortDirection.descending)
</code>```

However it only sorts according to the first integer of the value, and ignores the negative sign, so for example if the cells under that column had

```<code>3
-5
-2
</code>```

It would sort so it would be

```<code>-5
3
-2
</code>```

How can I sort so it takes the negative sign into account?

答:
this work for me</p>
```<code>Private Sub Grd_AssetList_SortCompare(sender As Object, e As DataGridViewSortCompareEventArgs) Handles Grd_AssetList.SortCompare
        Dim num1 As Double
        Dim num2 As Double
        num1 = Val(e.CellValue1) : num2 = Val(e.CellValue2)
        e.SortResult = num1.CompareTo(num2)
        e.Handled = True
End Sub
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am relatively new to coding, and i was hoping someone could help me with sorting a column of negative and positive values in a datagridview. It is not connected to a datatable, as I am only reading the values from a textfile, that uses commas to separate each bits of data and display it in the datagridview. I have tried to use this code:

DGV.Sort(DGV.Columns(2), System.ComponentModel.ListSortDirection.descending)

However it only sorts according to the first integer of the value, and ignores the negative sign, so for example if the cells under that column had

3
-5
-2

It would sort so it would be

-5
3
-2

How can I sort so it takes the negative sign into account?

Body:
this work for me

Private Sub Grd_AssetList_SortCompare(sender As Object, e As DataGridViewSortCompareEventArgs) Handles Grd_AssetList.SortCompare
        Dim num1 As Double
        Dim num2 As Double
        num1 = Val(e.CellValue1) : num2 = Val(e.CellValue2)
        e.SortResult = num1.CompareTo(num2)
        e.Handled = True
End Sub


问:
Access NodePort Service Outside Kubeadm K8S Cluster
I have two Ubuntu VMs created using Oracle Virtual Box on my Windows 11 laptop. I setup a k8s cluster using kubeadm with these two Ubuntu VMs, one of them is a master node and an another one is a worker node. Both the nodes are running with Ubuntu 20.04.3 LTS and docker://20.10.7. I deployed my spring boot app into the k8s cluster and exposed a node port service for my spring boot app with port 30000, but I am not really sure on how to access my node port service on the internet outside my cluster. Could you please help me with this issue?

Following are the IP address of my nodes in k8s cluster - master [192.168.254.94] and worker [192.168.254.95]. I tried with the following urls but none of them worked

http://192.168.254.94:30000/swagger-ui.html
http://192.168.254.95:30000/swagger-ui.html

These above urls throwing message which says refused to connect

http://192.168.9.13:30000/swagger-ui.html
http://192.168.9.14:30000/swagger-ui.html

These above urls says that the site cannot be reached

Below is the content of my application.yaml which I used for deploying the spring boot app and its corresponding service

```<code>apiVersion: apps/v1
kind: Deployment
metadata:
   name: dealer-engine
spec:
   replicas: 1
   selector:
      matchLabels:
         app: dealer-engine
   template:
      metadata:
        labels:
           app: dealer-engine
      spec:
         containers:
            - name: dealer-engine
              image: moviepopcorn/dealer_engine:0.0.1
              ports:
                 - containerPort: 9090
              env:
                 - name: MONGO_URL
                   value: mongodb://mongo-service:27017/mazda
              imagePullPolicy: Always
---
apiVersion: v1
kind: Service
metadata:
   name: dealer-engine
spec:
   type: NodePort
   selector:
      app: dealer-engine
   ports:
      - port: 9091
        targetPort: 9090
        nodePort: 30000
   externalIPs:
    - 10.0.0.12
</code>```

I am a beginner in k8s so please help me on how I can access my node port service outside my k8s cluster.

答:
Have you install any CNI plugin like flannel?

If yes, Check your CIDR setting here

kubectl get node k8s-master -o yaml | grep podCIDR:
kubectl get configmap -n kube-system kube-flannel-cfg -o yaml | grep '"Network":'
```
<p>Basically yes, CNI is must. flannel is the most simple one.</p>
<blockquote>
<p>https://kubernetes.io/docs/setup/production-environment/tools/kubeadm/create-cluster-kubeadm/#pod-network</p>
</blockquote>
<blockquote>
<p>You must deploy a Container Network Interface (CNI) based Pod network add-on so that your Pods can communicate with each other. Cluster DNS (CoreDNS) will not start up before a network is installed.</p>
</blockquote>
<ol>
<li>Download cni pulgin on every server.</li>
</ol>
<pre class="lang-sh prettyprint-override"><code># download cni plugin
wget https://github.com/containernetworking/plugins/releases/download/v0.9.1/cni-plugins-linux-amd64-v0.9.1.tgz
sudo mkdir -p /opt/cni/bin
sudo tar -xzvf cni-plugins-linux-amd64-v0.9.1.tgz -C /opt/cni/bin
</code>```

Reset you cluster

kubeadm reset
```
<ol start="3">
<li>Init your cluster with cidr setting must same as flannel config, default <code>10.244.0.0</code></li>
</ol>
<pre class="lang-sh prettyprint-override"><code>kubeadm init --pod-network-cidr=10.244.0.0/16
</code>```

Apply cni plugin.

kubectl apply -f https://raw.githubusercontent.com/flannel-io/flannel/master/Documentation/kube-flannel.yml
```

Body:
I have two Ubuntu VMs created using Oracle Virtual Box on my Windows 11 laptop. I setup a k8s cluster using kubeadm with these two Ubuntu VMs, one of them is a master node and an another one is a worker node. Both the nodes are running with Ubuntu 20.04.3 LTS and docker://20.10.7. I deployed my spring boot app into the k8s cluster and exposed a node port service for my spring boot app with port 30000, but I am not really sure on how to access my node port service on the internet outside my cluster. Could you please help me with this issue?

Following are the IP address of my nodes in k8s cluster - master [192.168.254.94] and worker [192.168.254.95]. I tried with the following urls but none of them worked

http://192.168.254.94:30000/swagger-ui.html
http://192.168.254.95:30000/swagger-ui.html

These above urls throwing message which says refused to connect

http://192.168.9.13:30000/swagger-ui.html
http://192.168.9.14:30000/swagger-ui.html

These above urls says that the site cannot be reached

Below is the content of my application.yaml which I used for deploying the spring boot app and its corresponding service

apiVersion: apps/v1
kind: Deployment
metadata:
   name: dealer-engine
spec:
   replicas: 1
   selector:
      matchLabels:
         app: dealer-engine
   template:
      metadata:
        labels:
           app: dealer-engine
      spec:
         containers:
            - name: dealer-engine
              image: moviepopcorn/dealer_engine:0.0.1
              ports:
                 - containerPort: 9090
              env:
                 - name: MONGO_URL
                   value: mongodb://mongo-service:27017/mazda
              imagePullPolicy: Always
---
apiVersion: v1
kind: Service
metadata:
   name: dealer-engine
spec:
   type: NodePort
   selector:
      app: dealer-engine
   ports:
      - port: 9091
        targetPort: 9090
        nodePort: 30000
   externalIPs:
    - 10.0.0.12

I am a beginner in k8s so please help me on how I can access my node port service outside my k8s cluster.

Body:
Have you install any CNI plugin like flannel?

If yes, Check your CIDR setting here

kubectl get node k8s-master -o yaml | grep podCIDR:
kubectl get configmap -n kube-system kube-flannel-cfg -o yaml | grep '"Network":'

Basically yes, CNI is must. flannel is the most simple one.

https://kubernetes.io/docs/setup/production-environment/tools/kubeadm/create-cluster-kubeadm/#pod-network

You must deploy a Container Network Interface (CNI) based Pod network add-on so that your Pods can communicate with each other. Cluster DNS (CoreDNS) will not start up before a network is installed.

Download cni pulgin on every server.

# download cni plugin
wget https://github.com/containernetworking/plugins/releases/download/v0.9.1/cni-plugins-linux-amd64-v0.9.1.tgz
sudo mkdir -p /opt/cni/bin
sudo tar -xzvf cni-plugins-linux-amd64-v0.9.1.tgz -C /opt/cni/bin

Reset you cluster

kubeadm reset

Init your cluster with cidr setting must same as flannel config, default 10.244.0.0

kubeadm init --pod-network-cidr=10.244.0.0/16

Apply cni plugin.

kubectl apply -f https://raw.githubusercontent.com/flannel-io/flannel/master/Documentation/kube-flannel.yml


问:
Can I have aligned bottomCenter instead of topLeft for performing animateContentSize?
I have this code that perform "animateContentSize" with text size changes.

```<code>    Column(
        modifier = Modifier.fillMaxSize(),
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        var message by remember { mutableStateOf("") }

        Box (Modifier
            .animateContentSize(
                animationSpec = tween(2000)
            ),
            contentAlignment = Alignment.BottomCenter){
            Text(message)
        }

        Button(onClick = {
            message = newText('O')
        }) {
            Text("Click Me")
        }

    }

</code>```

I'm expecting it to animate with the content aligned BottomCenter. However it is always aligned TopLeft (as you see, when it shrink, the text went up to TopLeft and then slowly moved toward Center.)

Is there a way to make it aligned BottomCenter, so the Text won't fly up as the size shrink.

答:
To align views BottomCenter, you can add verticalArrangement = Arrangement.Bottom to your Column

```<code> Column(
            modifier = Modifier.fillMaxSize(),
            verticalArrangement = Arrangement.Bottom,
            horizontalAlignment = Alignment.CenterHorizontally
        ) {}
</code>```

Body:
I have this code that perform "animateContentSize" with text size changes.

    Column(
        modifier = Modifier.fillMaxSize(),
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        var message by remember { mutableStateOf("") }

        Box (Modifier
            .animateContentSize(
                animationSpec = tween(2000)
            ),
            contentAlignment = Alignment.BottomCenter){
            Text(message)
        }

        Button(onClick = {
            message = newText('O')
        }) {
            Text("Click Me")
        }

    }

I'm expecting it to animate with the content aligned BottomCenter. However it is always aligned TopLeft (as you see, when it shrink, the text went up to TopLeft and then slowly moved toward Center.)

Is there a way to make it aligned BottomCenter, so the Text won't fly up as the size shrink.

Body:
To align views BottomCenter, you can add verticalArrangement = Arrangement.Bottom to your Column

 Column(
            modifier = Modifier.fillMaxSize(),
            verticalArrangement = Arrangement.Bottom,
            horizontalAlignment = Alignment.CenterHorizontally
        ) {}


问:
PHPInfo / Valet - Two different PHP versions
OK so I am experiencing something quite odd. My phpinfo() shows one version while php -v shows another.

I am running locally on a MacBook Air (Mojave), with Laravel and Valet.

phpinfo():

```<code>PHP Version 7.2.13

Configuration File (php.ini) Path   /usr/local/etc/php/7.2
Loaded Configuration File   /usr/local/etc/php/7.2/php.ini
Scan this dir for additional .ini files /usr/local/etc/php/7.2/conf.d
</code>```

While in my terminal, it shows:

php -v

```<code>PHP 7.3.0 (cli) (built: Dec  7 2018 11:00:11) ( NTS )
</code>```

Now, if I do a which php I get this:

```<code>/usr/local/bin/php
</code>```

In my ~/.bash-profile, I have this:

export "PATH=~/.composer/vendor/bin:$PATH"

I have tried to:

Restart Nginx

Restart Valet

Unlink PHP@7.2 and link PHP@7.3with Homebrew:

Olivers-MacBook-Air:~ oliverbusk$ brew unlink php@7.2
Error: No such keg: /usr/local/Cellar/php@7.2

How can I get my actual valet site to use php@7.3?

答:
NB: Tested this solution on Ubuntu 20.04 Desktop

If you are using Valet Linux Plus(Has more features than Valet Linux) Just do valet use {your PHP version} --update-cli.  For instance to use php8.0 just run:

```<code>valet use 8.0 --update-cli
</code>```

This will update both php-fpm version plus php-cli version too.

Body:
OK so I am experiencing something quite odd. My phpinfo() shows one version while php -v shows another.

I am running locally on a MacBook Air (Mojave), with Laravel and Valet.

phpinfo():

PHP Version 7.2.13

Configuration File (php.ini) Path   /usr/local/etc/php/7.2
Loaded Configuration File   /usr/local/etc/php/7.2/php.ini
Scan this dir for additional .ini files /usr/local/etc/php/7.2/conf.d

While in my terminal, it shows:

php -v

PHP 7.3.0 (cli) (built: Dec  7 2018 11:00:11) ( NTS )

Now, if I do a which php I get this:

/usr/local/bin/php

In my ~/.bash-profile, I have this:

export "PATH=~/.composer/vendor/bin:$PATH"

I have tried to:

Restart Nginx

Restart Valet

Unlink PHP@7.2 and link PHP@7.3with Homebrew:

Olivers-MacBook-Air:~ oliverbusk$ brew unlink php@7.2
Error: No such keg: /usr/local/Cellar/php@7.2

How can I get my actual valet site to use php@7.3?

Body:
NB: Tested this solution on Ubuntu 20.04 Desktop

If you are using Valet Linux Plus(Has more features than Valet Linux) Just do valet use {your PHP version} --update-cli.  For instance to use php8.0 just run:

valet use 8.0 --update-cli

This will update both php-fpm version plus php-cli version too.


问:
Is it free to use Spire PDF in a .NET web development and deployment to the Production server
I would like to use SpirePDF in my .NET web application to load a template, fill a few fields and save it as a new pdf. I tried downloading the nuget package and its working fine as I expected. Now is the question. Is it free to use for a .NET developer in the webapp and also deploy the code in the server??</p>

答:
Spire.PDF is a commercial library, so if you use it without applying a valid license, you'll see a red watermark at the top of the output files. You can request a 1-month temporary license here to remove it and have a full trial on the library.

It also provides a free community edition (Free Spire.PDF) which is free for personal and commercial use, but it's limited to 10 pages when loading or saving PDF files. If it's enough for your case, go for it.


问:
Python code to read a csv file and create a master csv file
I have a folder let's say as 'input_Folder' which has a list of CSV files with data. I'm trying to write a Python code which reads this list of CSV files from the input_folder and creates a master CSV file with two columns.

The columns in the master CSV files are 'Scenario' and 'Status'.

Column Name requirement are as follows,
Scenario =  Name of the file from the directory and
Status = if the file has a value in the second row of second column then populate as 'Pass' else 'Fail'

Below is my code. After executing the code I'm able to see Master CSV created but with empty lines. I'm quite new to python so could somebody help me out here please

import os
import csv

path = (Input file path)

with open("SUMMARY.csv", 'w') as csvfile:
    writer = csv.writer(csvfile)
    writer.writerow(['SCENARIO', 'STATUS'])
    for files in os.walk(path):
        for filename in files:
    with open("input_file.csv") as csv_file: #checking if the code is working for
        # one sample file
        all_rows = list(csv_file)
        line_count = 0
        for row in all_rows[1:2]:
            if line_count == 1:
                if row[1].value == None:
                    writer.writerow([os.path.basename(filename).split(".")[0], 'PASS'])
                else:
                    writer.writerow([os.path.basename(filename).split(".")[0], 'FAIL'])
            line_count += 1
```

答:
Your attempt has three problems; it uses os.walk which traverses subdirectories (perhaps this is not a problem because your folder does not have subdirectories, but you should use the correct function for your use case regardless), and you are opening a file in the current directory instead of the one actually returned by os.walk. Finally, the input from csv.reader cannot be None; either the line contains fewer fields (in which case you cannot access the second field at all, and trying will get you an IndexError), or it contains an empty string. (More fundamentally, your indentation seems to be broken, but since you are not asking about a syntax error, I'm guessing your actual code doesn't have this problem.)

Here's a quick refactoring to use glob.glob instead of os.walk, assuming that the input CSV files have an empty field where you were looking for None. (It would obviously not be hard to change it to if len(line) < 2: if you wanted to, or cover both conditions.)

```<code>import csv
import os
from glob import glob

with open("SUMMARY.csv", 'w', encoding='utf-8') as output_file:
    writer = csv.writer(output_file)
    writer.writerow(['SCENARIO', 'STATUS'])
    for filename in glob(f"{path}/*.csv"):
        with open(filename, 'r', encoding='utf-8') as input_file:
            value = "FAIL"
            reader = csv.reader(input_file)
            for lineno, line in enumerate(reader, 1):
                if lineno != 2:
                    continue
                if line[1] != "":
                    value = "PASS"
                break
        writer.writerow([os.path.basename(filename).split(".")[0], value])
</code>```

Tangentially perhaps notice also how I avoid having two variables with almost the same names csvfile and csv_file.

The logic writes "FAIL" if there is only one input line, too. (Refactored in response to a comment.)

Body:
Your attempt has three problems; it uses os.walk which traverses subdirectories (perhaps this is not a problem because your folder does not have subdirectories, but you should use the correct function for your use case regardless), and you are opening a file in the current directory instead of the one actually returned by os.walk. Finally, the input from csv.reader cannot be None; either the line contains fewer fields (in which case you cannot access the second field at all, and trying will get you an IndexError), or it contains an empty string. (More fundamentally, your indentation seems to be broken, but since you are not asking about a syntax error, I'm guessing your actual code doesn't have this problem.)

Here's a quick refactoring to use glob.glob instead of os.walk, assuming that the input CSV files have an empty field where you were looking for None. (It would obviously not be hard to change it to if len(line) < 2: if you wanted to, or cover both conditions.)

import csv
import os
from glob import glob

with open("SUMMARY.csv", 'w', encoding='utf-8') as output_file:
    writer = csv.writer(output_file)
    writer.writerow(['SCENARIO', 'STATUS'])
    for filename in glob(f"{path}/*.csv"):
        with open(filename, 'r', encoding='utf-8') as input_file:
            value = "FAIL"
            reader = csv.reader(input_file)
            for lineno, line in enumerate(reader, 1):
                if lineno != 2:
                    continue
                if line[1] != "":
                    value = "PASS"
                break
        writer.writerow([os.path.basename(filename).split(".")[0], value])

Tangentially perhaps notice also how I avoid having two variables with almost the same names csvfile and csv_file.

The logic writes "FAIL" if there is only one input line, too. (Refactored in response to a comment.)


问:
How to create a simple countdown timer in Kotlin?
I know how to create a simple countdown timer in Java. But I'd like to create this one in Kotlin.

package android.os;

new CountDownTimer(20000, 1000) {
    public void onTick(long millisUntilFinished) {
        mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
    }
    public void onFinish() {
        mTextField.setText("Time's finished!");
    }
}.start();
```

How can I do it using Kotlin?

答:
CountDownTimer in Kotlin:

```<code>object: CountDownTimer(3000, 1000){
    override fun onTick(p0: Long) {}
    override fun onFinish() {
        //add your code here
    }
 }.start()
</code>```

Body:
I know how to create a simple countdown timer in Java. But I'd like to create this one in Kotlin.

package android.os;

new CountDownTimer(20000, 1000) {
    public void onTick(long millisUntilFinished) {
        mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
    }
    public void onFinish() {
        mTextField.setText("Time's finished!");
    }
}.start();

How can I do it using Kotlin?

Body:
CountDownTimer in Kotlin:

object: CountDownTimer(3000, 1000){
    override fun onTick(p0: Long) {}
    override fun onFinish() {
        //add your code here
    }
 }.start()


问:
how can i prevent a selected option from opening the url
I'm wanting to import each option value via ajax , but i haven't had any success stopping the option from redirecting to the original site when selected

existing html

```<code><select name="LOCATION" size="1" onchange="self.location=this.options[this.selectedIndex].value">
<option>Jump To...</option>
<option value="https://www63.myfantasyleague.com/2021/options?L=43570&O=123&MONTH=1&YEAR=2021">Feb 2021</option>
<option value="https://www63.myfantasyleague.com/2021/options?L=43570&O=123&MONTH=2&YEAR=2021">Mar 2021</option>
</select>
</code>```

trying to stop the option from triggering to the url , so i can get the url and bring into my page

```<code>$(document).on('change', 'select', function (e) {
    e.preventDefault(); // not working to stop the selected option from opening new url
    var href = $('option:selected').val();
    console.log(href);
});
</code>```

答:
That inline event isn't really attached on the DOM load, so you can simply remove that attribute.

// jQuery
$('[name="LOCATION"]').attr('onchange', false)

// Plain JS version
// document.querySelector('[name="LOCATION"]').removeAttribute('onchange')```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<select name="LOCATION" size="1" onchange="console.log(this.options[this.selectedIndex].value)">
  <option>Jump To...</option>
  <option value="test1">Feb 2021</option>
  <option value="test2">Mar 2021</option>
</select></code>```

Body:
I'm wanting to import each option value via ajax , but i haven't had any success stopping the option from redirecting to the original site when selected

existing html

<select name="LOCATION" size="1" onchange="self.location=this.options[this.selectedIndex].value">
<option>Jump To...</option>
<option value="https://www63.myfantasyleague.com/2021/options?L=43570&O=123&MONTH=1&YEAR=2021">Feb 2021</option>
<option value="https://www63.myfantasyleague.com/2021/options?L=43570&O=123&MONTH=2&YEAR=2021">Mar 2021</option>
</select>

trying to stop the option from triggering to the url , so i can get the url and bring into my page

$(document).on('change', 'select', function (e) {
    e.preventDefault(); // not working to stop the selected option from opening new url
    var href = $('option:selected').val();
    console.log(href);
});

Body:
That inline event isn't really attached on the DOM load, so you can simply remove that attribute.

// jQuery
$('[name="LOCATION"]').attr('onchange', false)

// Plain JS version
// document.querySelector('[name="LOCATION"]').removeAttribute('onchange')

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<select name="LOCATION" size="1" onchange="console.log(this.options[this.selectedIndex].value)">
  <option>Jump To...</option>
  <option value="test1">Feb 2021</option>
  <option value="test2">Mar 2021</option>
</select>


问:
How to query for relations that are empty?
I have two classes with one-to-many relation:

@Entity()
class Lesson {
  final course = ToOne<Course>();
}

@Entity()
class Course {
  @Backlink('course')
  final lessons = ToMany<Lesson>();
}
```
<p>I want to query for all lessons that does not belong to any course. Below does not work:</p>
<pre class="lang-dart prettyprint-override"><code>final qb = _box.query(Lesson_.course.isNull());
</code>```

And the reason is explained in this issue.

So I have to do this:

final qb = _box.query(Lesson_.course.equals(0));
```

Is there a better or a recommended way for this?

答:
Yes, for ObjectBox for Dart adding an equals 0 condition on the ToOne is the way to find objects without a ToOne target:

```<code>final noToOneTargetQuery = box.query(Entity_.toOne.equals(0)).build();
</code>```

See ObjectBox for Dart test code for more.

Body:
I have two classes with one-to-many relation:

@Entity()
class Lesson {
  final course = ToOne<Course>();
}

@Entity()
class Course {
  @Backlink('course')
  final lessons = ToMany<Lesson>();
}

I want to query for all lessons that does not belong to any course. Below does not work:

final qb = _box.query(Lesson_.course.isNull());

And the reason is explained in this issue.

So I have to do this:

final qb = _box.query(Lesson_.course.equals(0));

Is there a better or a recommended way for this?

Body:
Yes, for ObjectBox for Dart adding an equals 0 condition on the ToOne is the way to find objects without a ToOne target:

final noToOneTargetQuery = box.query(Entity_.toOne.equals(0)).build();

See ObjectBox for Dart test code for more.


问:
How to clear the current figure in matplotlib?
The code snippet is given below. I want to save a new figure at each iteration of the loop. But, the original figure is overwritten instead of creating a new one. I have used plt.cla(), plt.clf(). but could not get the desired result.

```<code>for i in range(17)
    ax.scatter(x_coord, y_coord, color = 'red')
    ax.text(x_coord[i], y_coord[i], str(i))

plt.savefig(f"{output_dir}/{counter}.png")
counter += 1
plt.clf()

</code>```

答:
It worked for me with minor changes.
It seems you have just to move some statements WITHIN the loop. I run your code with these minor changes:

created simple series

initialised the "counter"

I just used the current directory (no path).

This is the code:

```<code>import matplotlib
import matplotlib.pyplot as plt
x_coord = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18]
y_coord = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18]
counter = 1

for i in range(17):

    fig, ax = plt.subplots()
    ax.scatter(x_coord, y_coord, color = 'red')
    ax.text(x_coord[i], y_coord[i], str(i))
    plt.savefig(f"{counter}.png")
    counter += 1
    plt.clf()
#end
</code>```

Body:
The code snippet is given below. I want to save a new figure at each iteration of the loop. But, the original figure is overwritten instead of creating a new one. I have used plt.cla(), plt.clf(). but could not get the desired result.

for i in range(17)
    ax.scatter(x_coord, y_coord, color = 'red')
    ax.text(x_coord[i], y_coord[i], str(i))

plt.savefig(f"{output_dir}/{counter}.png")
counter += 1
plt.clf()

Body:
It worked for me with minor changes.
It seems you have just to move some statements WITHIN the loop. I run your code with these minor changes:

created simple series

initialised the "counter"

I just used the current directory (no path).

This is the code:

import matplotlib
import matplotlib.pyplot as plt
x_coord = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18]
y_coord = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18]
counter = 1

for i in range(17):

    fig, ax = plt.subplots()
    ax.scatter(x_coord, y_coord, color = 'red')
    ax.text(x_coord[i], y_coord[i], str(i))
    plt.savefig(f"{counter}.png")
    counter += 1
    plt.clf()
#end


问:
RegisterForEventValidation can only be called during Render
I have a webmethod which will be called from jquery ajax:

```<code>[WebMethod]
public string TestMethod(string param1, string param2)
{
    StringBuilder b = new StringBuilder();
    HtmlTextWriter h = new HtmlTextWriter(new StringWriter(b));
    this.LoadControl("~/Pages/Controls/Listing.ascx").RenderControl(h);
    string controlAsString = b.ToString();
    return controlAsString;
}
</code>```

(it's a non-static method and we are able to hit it. That's not an issue)

When the loadControl() method is executed, I get an error saying: RegisterForEventValidation can only be called during Render.

I have already included EnableEventValidation="false" for the current aspx, disabled viewstate also. but still i get the same error. Any ideas on this?

答:
You need to notify ASP.Net that not to validate the event by setting the EnableEventValidation flag to false.

You can set it in the Web.Config in the following way

```<code><%@ Page Language="C#" AutoEventWireup="true" EnableEventValidation = "false"
</code>```

Body:
I have a webmethod which will be called from jquery ajax:

[WebMethod]
public string TestMethod(string param1, string param2)
{
    StringBuilder b = new StringBuilder();
    HtmlTextWriter h = new HtmlTextWriter(new StringWriter(b));
    this.LoadControl("~/Pages/Controls/Listing.ascx").RenderControl(h);
    string controlAsString = b.ToString();
    return controlAsString;
}

(it's a non-static method and we are able to hit it. That's not an issue)

When the loadControl() method is executed, I get an error saying: RegisterForEventValidation can only be called during Render.

I have already included EnableEventValidation="false" for the current aspx, disabled viewstate also. but still i get the same error. Any ideas on this?

Body:
You need to notify ASP.Net that not to validate the event by setting the EnableEventValidation flag to false.

You can set it in the Web.Config in the following way

<%@ Page Language="C#" AutoEventWireup="true" EnableEventValidation = "false"


问:
Exception of type 'Microsoft.TeamFoundation.Git.Contracts.GitCheckoutConflictException' was thrown
While trying to checkout to a new branch in Visual Studio 2019, I'm getting the below error:

I tried to do the same from GitBash cmd using the command git checkout branchname but here also, I'm getting an error:

```<code>error: The following untracked working tree files would be overwritten by checkout:
//list of file names below
...
...
...
Aborting
</code>```

I tried restarting VS also but it was of no help. Can you please assist?

答:
I was also facing the same issue and the below steps worked for me

Navigated to \.git\refs\remotes folder in my local system

Deleted the branch that was causing the issue

Now i checked out the branch using git bash using git checkout <branchname>

Body:
While trying to checkout to a new branch in Visual Studio 2019, I'm getting the below error:

I tried to do the same from GitBash cmd using the command git checkout branchname but here also, I'm getting an error:

error: The following untracked working tree files would be overwritten by checkout:
//list of file names below
...
...
...
Aborting

I tried restarting VS also but it was of no help. Can you please assist?


问:
'method' object is not subscriptable - Pandas
I have the following two lines of codes

```<code>temp['AD_Free_Cancel'] = temp[(temp['ISFREEPOLICY']=='N') & (temp['PRODUCT'].isin['SAD1','SAD2','SAD3','SAD4','SADFR1','SADFR2','SIAD']) & (temp['POLICYSTATUS']=='C')]

temp['AD_Paid_Cancel'] = temp[(temp['ISFREEPOLICY']!='N') & (temp['PRODUCT'].isin['SAD1','SAD2','SAD3','SAD4','SADFR1','SADFR2','SIAD']) & (temp['POLICYSTATUS']=='C')]
</code>```

Can someone please help me understand the error and how can I fix it? Thank You

答: You are having error because isin() is a function but you are using it as .isin[], It should be isin()</p>

Body:
I have the following two lines of codes

temp['AD_Free_Cancel'] = temp[(temp['ISFREEPOLICY']=='N') & (temp['PRODUCT'].isin['SAD1','SAD2','SAD3','SAD4','SADFR1','SADFR2','SIAD']) & (temp['POLICYSTATUS']=='C')]

temp['AD_Paid_Cancel'] = temp[(temp['ISFREEPOLICY']!='N') & (temp['PRODUCT'].isin['SAD1','SAD2','SAD3','SAD4','SADFR1','SADFR2','SIAD']) & (temp['POLICYSTATUS']=='C')]

Can someone please help me understand the error and how can I fix it? Thank You


问:
Multiple scrape jobs running on same target in Prometheus
I'm working on use case where I need to scrape metrics at different scrape intervals. For example, metric_one needs to be scraped for every 1 hr and metric_two is scraped for every 15s. Both of these metrics are from the same target. The solution that I have tried is following:

```<code>global:
scrape_interval: 15s
scrape_configs:
 - job_name: 'job_two'
   static_configs:
     - targets:
       - targets: ["engine:5001"]
   metric_relabel_configs:
   - source_labels: [ __name__ ]
     regex: 'metric_one'
     action: drop
 - job_name: 'job_one'
   scrape_interval: 3600s
   static_configs:
     - targets:
       - targets: ["engine:5001"]
   metric_relabel_configs:
   - source_labels: [ __name__ ]
     regex: 'metric_two'
     action: drop
</code>```

This Prometheus config tries to run two different scrape jobs on same host. job_one only scrapes metric_one and job_two only scrapes metric_one, but the Prometheus service discovery does not work properly with job_two and heath-check status is shown unknown and sometimes it doesn't appear at all when I run up in Prometheus console.
Is there any other proper solution to this or am I doing something wrong in this solution?

答:
The easiest solution is to decrease the scrape interval to 5 minutes or less.

This is something like Prometheus internals. PromQL only looks back for 5 minutes to find samples, so after this amount of time since the last scrape you start seeing the described behavior. It is easy to see on a graph, you will quickly notice that the metric like breaks shortly after the last scrape. In order to prevent this, you need to scrape the metric at least every five minutes, even if the metric value does not change that often. This is just to tell Prometheus that the metric is still there.

Body:
I'm working on use case where I need to scrape metrics at different scrape intervals. For example, metric_one needs to be scraped for every 1 hr and metric_two is scraped for every 15s. Both of these metrics are from the same target. The solution that I have tried is following:

global:
scrape_interval: 15s
scrape_configs:
 - job_name: 'job_two'
   static_configs:
     - targets:
       - targets: ["engine:5001"]
   metric_relabel_configs:
   - source_labels: [ __name__ ]
     regex: 'metric_one'
     action: drop
 - job_name: 'job_one'
   scrape_interval: 3600s
   static_configs:
     - targets:
       - targets: ["engine:5001"]
   metric_relabel_configs:
   - source_labels: [ __name__ ]
     regex: 'metric_two'
     action: drop

This Prometheus config tries to run two different scrape jobs on same host. job_one only scrapes metric_one and job_two only scrapes metric_one, but the Prometheus service discovery does not work properly with job_two and heath-check status is shown unknown and sometimes it doesn't appear at all when I run up in Prometheus console.
Is there any other proper solution to this or am I doing something wrong in this solution?


问:
I can't http request in localhost
I want to use localhost as a server. I can receive index.html on the browser, but I can't send data to the server with "post" method in Html.
are there any properties for interaction with localhost in the chrome browser?

HTTP request in the network of chrome developer

答:
I just forgot to change the type of button to submit in the HTML file. :)

<button type="submit">Calculate</button>
```

Title: I can't http request in localhost


问:
Binary Search Tree, Height Method not returning correct values
Java Binary Search trees, Height method not returning the correct height. I tried a lot of stuff on the internet, none of it worked. If someone can point out the issue with my code it will be very helpful.

```<code>@Override
public int height()
{

    return heightRecursive(root);

}

private int heightRecursive(Node node) {

    if(node == null || (node.right == null && node.right == null)) return 0;

    int lh=0;
    int rh=0;

    if(node.left!=null) {
        lh=heightRecursive(node.left);
        System.out.println(lh);
    }
    if(node.right!=null) {
        rh=heightRecursive(node.right);
    }

    //System.out.println("--------"+1+Math.max(lh, rh));

    return 1+Math.max(lh, rh);

}
</code>```

The Add() Method is below:

```<code>@Override
public boolean add(Comparable e)
{
    addR(e,root);
    return true;
}
public Node addR(Comparable e,Node n)
{
    //System.out.println("Null --"+n+" "+e+" "+size);
    if(n==null)
    {

        n=new Node(e);
        size++;
        System.out.println("final --"+n+" "+e+" "+size);

    }

    else if(e.compareTo(n.value)<0)
    {

        n.left = addR(e,n.left);
        //size++;
    }
    else if(e.compareTo(n.value)>0)
    {
        n.right = addR(e,n.right);
        //size++;
    }

    return n;
}
</code>```

I can't seem to get to the root cause of this, after inputting the debug printline code in add method, this is the output:

```<code>A final --trees.SimpleTreeSet$Node@58c1670b A 1
B final --trees.SimpleTreeSet$Node@6b57696f B 2
R final --trees.SimpleTreeSet$Node@44c8afef R 1
W final --trees.SimpleTreeSet$Node@12f41634 W 1
O final --trees.SimpleTreeSet$Node@262b2c86 O 1
final --trees.SimpleTreeSet$Node@5ed828d A 1
Y final --trees.SimpleTreeSet$Node@7a3d45bd Y 1
</code>```

答:
The main problem is in your add method: the root will never change. So if you add a first node to an empty tree, that new node is lost: it is returned by addR, but your code ignores it.

So:

```<code>public boolean add(Comparable e)
{
    root = addR(e,root);
    return true;
}
</code>```

Another problem concerns the base case of the height recursion:

```<code>if(node == null || (node.right == null && node.right == null)) return 0;
</code>```

You should check node.left (not twice node.right) and also distinguish between a null and a node. There is a height difference between those two cases. When a single-node-tree has height 0, then an empty tree should have height -1.

Corrected:

```<code>if (node == null) return -1;
if (node.left == null && node.right == null)) return 0;
</code>```

Body:
Java Binary Search trees, Height method not returning the correct height. I tried a lot of stuff on the internet, none of it worked. If someone can point out the issue with my code it will be very helpful.

@Override
public int height()
{

    return heightRecursive(root);

}

private int heightRecursive(Node node) {

    if(node == null || (node.right == null && node.right == null)) return 0;

    int lh=0;
    int rh=0;

    if(node.left!=null) {
        lh=heightRecursive(node.left);
        System.out.println(lh);
    }
    if(node.right!=null) {
        rh=heightRecursive(node.right);
    }

    //System.out.println("--------"+1+Math.max(lh, rh));

    return 1+Math.max(lh, rh);

}

The Add() Method is below:

@Override
public boolean add(Comparable e)
{
    addR(e,root);
    return true;
}
public Node addR(Comparable e,Node n)
{
    //System.out.println("Null --"+n+" "+e+" "+size);
    if(n==null)
    {

        n=new Node(e);
        size++;
        System.out.println("final --"+n+" "+e+" "+size);

    }

    else if(e.compareTo(n.value)<0)
    {

        n.left = addR(e,n.left);
        //size++;
    }
    else if(e.compareTo(n.value)>0)
    {
        n.right = addR(e,n.right);
        //size++;
    }

    return n;
}

I can't seem to get to the root cause of this, after inputting the debug printline code in add method, this is the output:

A final --trees.SimpleTreeSet$Node@58c1670b A 1
B final --trees.SimpleTreeSet$Node@6b57696f B 2
R final --trees.SimpleTreeSet$Node@44c8afef R 1
W final --trees.SimpleTreeSet$Node@12f41634 W 1
O final --trees.SimpleTreeSet$Node@262b2c86 O 1
final --trees.SimpleTreeSet$Node@5ed828d A 1
Y final --trees.SimpleTreeSet$Node@7a3d45bd Y 1

Body:
The main problem is in your add method: the root will never change. So if you add a first node to an empty tree, that new node is lost: it is returned by addR, but your code ignores it.

So:

public boolean add(Comparable e)
{
    root = addR(e,root);
    return true;
}

Another problem concerns the base case of the height recursion:

if(node == null || (node.right == null && node.right == null)) return 0;

You should check node.left (not twice node.right) and also distinguish between a null and a node. There is a height difference between those two cases. When a single-node-tree has height 0, then an empty tree should have height -1.

Corrected:

if (node == null) return -1;
if (node.left == null && node.right == null)) return 0;


问:
How to check newly generated logfile on a folder path
I'm working on a simple script wherein I wanted to check if a log contains a specific string and give me an output if it contains the string or not. However the logfile gets updated daily and I wanted to check the most recent file. Is there a command I can add to my script to get the output I needed?. Or is there other way I can do this without using Select-String?.</p>
```<code>$SEL = Select-String -Path Pathfile.LOG -Pattern "String"
if ($SEL -ne $null)
{
    echo Contains String
}
else
{
    echo Not Contains String
}}
</code>```

答:
Thanks for your help!. This is what I got and it worked as expected.</p>
```<code>Invoke-Command -Computername 'servername' -ScriptBlock {$SEL = Get-ChildItem 'Filepath' | Sort CreationTime -Descending | Select -First 1 | Select-String -Pattern "STRING" -CaseSensitive

if ($SEL -ne $null)
{
    echo STRING found
}
else
{
    echo STRING not found
}}
</code>```

Body:
I'm working on a simple script wherein I wanted to check if a log contains a specific string and give me an output if it contains the string or not. However the logfile gets updated daily and I wanted to check the most recent file. Is there a command I can add to my script to get the output I needed?. Or is there other way I can do this without using Select-String?.

$SEL = Select-String -Path Pathfile.LOG -Pattern "String"
if ($SEL -ne $null)
{
    echo Contains String
}
else
{
    echo Not Contains String
}}

Body:
Thanks for your help!. This is what I got and it worked as expected.

Invoke-Command -Computername 'servername' -ScriptBlock {$SEL = Get-ChildItem 'Filepath' | Sort CreationTime -Descending | Select -First 1 | Select-String -Pattern "STRING" -CaseSensitive

if ($SEL -ne $null)
{
    echo STRING found
}
else
{
    echo STRING not found
}}


问:
How can I calculate audio dB level?
I want to calculate room noise level with the computer's microphone. I record noise as an audio file, but how can I calculate the noise dB level?

I don't know how to start!

答:
Well! I Used RobertT's Method But It Always Giving Me Oveflow Exception, Then I Used:- int dB = -36 - (value * -1), The Exception Gone, I Don't Know Whether It's Telling dB Values, If You Knew Using Code Given Below, Please Comment Me Whether it's A dB Value or not.

VB.NET:-

Dim dB As Integer = -36 - (9 * -1)

C#:-

int dB = -36 - (9 * -1)

Title: How can I calculate audio dB level?


问:
How to replace IN clause with JOIN in Postgres?
I have the following query.

```<code>select *
from table table0_
where (table0_.col1, table0_.col2, table0_.col3) in (($1, $2, $3) , ($4, $5, $6) , ($7, $8, $9) , ($10, $11, $12) , ($13, $14, $15))
</code>```

How to replace IN clause with JOIN as shown in the below in the Postgres.

```<code>select *
from table0_
where table0_.col1=$1
  and table0_.col2=$2
  and table0_.col3=$3
</code>```

EDIT: I read from somewhere that IN operator does not make use of indexes. Also, this query is taking more time if passing more parameters.

答:
I don't know why you should do that because actually no difference between them. You can use the below query and use CTE to create a temp table and join together.

with data as (
  select
    *
  from (
    values ($1, $2, $3) , ($4, $5, $6) , ($7, $8, $9) , ($10, $11, $12) , ($13, $14, $15)
  ) t (col1, col2, col3)
)
select
  table0_.*
from
  table0_, data
where
  table0_.col1 = data.col1
  and table0_.col2 = data.col2
  and table0_.col3 = $data.col3
```

Body:
I have the following query.

select *
from table table0_
where (table0_.col1, table0_.col2, table0_.col3) in (($1, $2, $3) , ($4, $5, $6) , ($7, $8, $9) , ($10, $11, $12) , ($13, $14, $15))

How to replace IN clause with JOIN as shown in the below in the Postgres.

select *
from table0_
where table0_.col1=$1
  and table0_.col2=$2
  and table0_.col3=$3

EDIT: I read from somewhere that IN operator does not make use of indexes. Also, this query is taking more time if passing more parameters.


问:
C# why does this reload method block the UI for a visible second
I have a function that makes a call to an API, and then binds the data to the view (along with a lot of local calculations in between.)

In short, this method looks like this:

```<code>        private async Task LoadMoreAds()
        {
            Task.Run(async () =>
            {

                await ...random api then
                ... do something with the results then
                ... bind the views

            });
        }
</code>```

This method is called from UI event handler:

```<code>     private async void listview_allAds_FlowItemAppearing(object sender, ItemVisibilityEventArgs e)
{
            TinyAd current = e.Item as TinyAd;
             if (current == contentOfListView[contentOfListView.Count - 2])
                {
                    if (!isCurrentlyLoading)
                        await LoadMoreAds();
                 }
            }

}
</code>```

I think I am doing all my async and awaits correctly.

But still i am seeing a slight hang on UI reload when the user scrolls fast-
Also the framerate is not at 60, rather at avg of 30.

Is there something I can optimize?

答:
Here are some suggestions .

Stop using a Task inside another Task, just remove the inner Task.Run .

Do not await LoadMoreAds  outside , use await inside LoadMoreAds method.

Do the binding stuff in xaml not inside LoadMoreAds method , just request data and modify the binding source(don't involve view manipulation otherwise you need to update it on main thread ).

Refer to the sample here : https://montemagno.com/load-more-items-at-end-of-listview-in/.

Body:
I have a function that makes a call to an API, and then binds the data to the view (along with a lot of local calculations in between.)

In short, this method looks like this:

        private async Task LoadMoreAds()
        {
            Task.Run(async () =>
            {

                await ...random api then
                ... do something with the results then
                ... bind the views

            });
        }

This method is called from UI event handler:

     private async void listview_allAds_FlowItemAppearing(object sender, ItemVisibilityEventArgs e)
{
            TinyAd current = e.Item as TinyAd;
             if (current == contentOfListView[contentOfListView.Count - 2])
                {
                    if (!isCurrentlyLoading)
                        await LoadMoreAds();
                 }
            }

}

I think I am doing all my async and awaits correctly.

But still i am seeing a slight hang on UI reload when the user scrolls fast-
Also the framerate is not at 60, rather at avg of 30.

Is there something I can optimize?


问:
Is it possible to see all publicly-accessible files on a website?
I would like to query a website that provides files for download to see all the available files for download.

For example: webpage called https://download.website.com/path/to/file has a file of interest to me, but I would also like to see other available files available in the system publicly.

Essentially I would like to be able to view a hierarchy of all of the publicly-facing files given some parent link. So if I know I want all files stored under https://download.website.com/path/, the query would turn up a recursive list of available files from https://download.website.com/path/*.

Is this even possible to do for most websites? Would allowing this behavior be too compromising to web frameworks in general, so it might not exist? Am I XYing out of control?

Any help here greatly appreciated.

答:
This method isn't perfect, but you can try it. Just put this query in Google Search.

You can do a Google search for some publicly available and indexed path.

For example if you want to search all available page on a website/domain:

```<code>site:download.website.com
</code>```

If you want to search all PDF files in this site:

```<code>site:download.website.com filetype:pdf
</code>```

If you want to search all links with path download.website.com/wp-content/:

```<code>site:download.website.com inurl:/wp-content/
</code>```

I hope it will help you a little bit.

Body:
This method isn't perfect, but you can try it. Just put this query in Google Search.

You can do a Google search for some publicly available and indexed path.

For example if you want to search all available page on a website/domain:

site:download.website.com

If you want to search all PDF files in this site:

site:download.website.com filetype:pdf

If you want to search all links with path download.website.com/wp-content/:

site:download.website.com inurl:/wp-content/

I hope it will help you a little bit.


问:
How to structure project with feature base if feature depend on other features?
I am a newbie here! I am learning and trying to improve myself for writing a cleaner and better code then I ended up sticking with DDD and also Clean architecture. Those look pretty organizable, But I got confused at some point on how to separate the features.

Let's say I have a UserEntity, ProductEntity, TransactionEntity, These entities have their own repository and helpers class, Is it correct to treat them as separate features? If yes, What about TransactionEntity which contains both ProductEntity and UserEntity inside of it? Is it okay to make one feature depend on other features like that?

答:
Let's say I have a UserEntity, ProductEntity, TransactionEntity, These entities have their own repository and helpers class, Is it correct to treat them as separate features?

It depends on the domain you are working in. DDD is about organizing your code according to the underlying domain. You should structure the code by the bounded contexts of your domain. The reason for this is the single responsibility principle. Classes in a bounded context should only change for one reason. E.g. an organization that sales products usually also provide support for them. Classes in the sales context change for sales reasons while classes in the support context change for support reasons. This also means that you can have an entity with the same name in different contexts. Even the entity has the same name, like Customer, it has different relationships, properties and methods in different contexts and is a different class as this diagram shows.

Bounded Context, Martin Fowler, 2014

The term feature that you used in your question is a bit overloaded. So when you mean bounded context when you say feature you should separate them. If you just mean entity or use case, you should think about the bounded context to which they belong.

If yes, What about TransactionEntity which contains both ProductEntity and UserEntity inside of it? Is it okay to make one feature depend on other features like that?

Like I said above I assume that you mean bounded context when you talk about features. It is okay that bounded contexts have relationships. A dependency is one kind of relationship. When you introduce dependencies you always ask yourself about the direction of the dependency. That's what architects do every day, they manage dependencies. One good principle is the dependency inversion principle. Uncle Bob summarizes it as

Low level policies should depend upon high level policies.

Robert C. Martin

Applied to bounded contexts it means that a higher level (or more abstract) domain context, like customer management, should not depend on lower level (more detailed) domain concepts, like insurance quoting.

You can integrate two bounded contexts by using domain events. So when one context changes it emits an event. The other bounded context listens to this events and performs appropriate actions. You can read more about this in the book Implementing Domain-Driven-Design, Vaughn Vernon.

In short, the event mechanism might be implemented as a simple observer pattern or by using a message queue. Usually message queues are used to communicate between different processes, as in microservice architectures, but they can also be used as an event mechanism in one process.

I hope I could answer some of your questions and guide you to sources that will help you to understand DDD more.


问:
Code syntax explaination help
I am learning WPF and there's a piece of code which I don't quite understand the method declared with constraints:

```<code>public static T FindAncestor<T>(DependencyObject dependencyObject)
    where T : class // Need help to interpret this method declaration
</code>```

I understand this is a shared method and T has be a class but what is what is 'static T FindAncestor'? Having troubles interpreting it as a whole. Thanks!

Code:

```<code>public static class VisualTreeHelperExtensions
{
    public static T FindAncestor<T>(DependencyObject dependencyObject)
        where T : class // Need help to interpret this method
    {
        DependencyObject target = dependencyObject;
        do
        {
            target = VisualTreeHelper.GetParent(target);
        }
        while (target != null && !(target is T));
        return target as T;
    }
}
</code>```

答: It means that it is a static method (you can call it without an instance of the class created) that returns an object of type T. FindAncestor is the name of the method.

Title: Code syntax explaination help

Body:
I am learning WPF and there's a piece of code which I don't quite understand the method declared with constraints:

public static T FindAncestor<T>(DependencyObject dependencyObject)
    where T : class // Need help to interpret this method declaration

I understand this is a shared method and T has be a class but what is what is 'static T FindAncestor'? Having troubles interpreting it as a whole. Thanks!

Code:

public static class VisualTreeHelperExtensions
{
    public static T FindAncestor<T>(DependencyObject dependencyObject)
        where T : class // Need help to interpret this method
    {
        DependencyObject target = dependencyObject;
        do
        {
            target = VisualTreeHelper.GetParent(target);
        }
        while (target != null && !(target is T));
        return target as T;
    }
}


问:
Creating lists from a text file by splitting it vertically
I want to split this text file into 3 (called x, y, and e) lists using Python and I can't seem to do it.

This is what the text file (called data) looks like:

```<code>x y e
-2 2.1 0.170358869161
0 2.4  0.170202773308
2 2.5  -0.138557648063
4 3.5  0.187965696415
6 4.2  -0.473073365465
</code>```

This is the code I have so far that doesn't work:

```<code>x=[]
y=[]
e=[]

try:
    data = open('data.txt', 'rt')
except:
    sys.exit('cannot find file')

with data:
    try:
        x.append(data[:1])
        y.append(data[2:3])
        e.append(data[4:5])
except:
    sys.exit('cannot create lists')
</code>```

答:
I see that the replies above have answers that used hard-coded variables. However I found a way to create lists that can hold infinite lines.

def getFrom(index: int, data: list):
    returnList = []
    for item in data:
        if len(item) >= index:
            returnList.append(item[index])
        else:
            returnList.append("")
    return returnList
```
<p>In this function, data is the list that you want to search, can be nested, while index is the index you wanted to search. This will return a list contains that was in the index on the vertical space.</p>
<p>You can also try</p>
<pre class="lang-py prettyprint-override"><code>data = ...
endList = [getFrom(index, data) for index in range(len(data))]
</code>```

and endList if the result of the array split vertically.

Body:
I want to split this text file into 3 (called x, y, and e) lists using Python and I can't seem to do it.

This is what the text file (called data) looks like:

x y e
-2 2.1 0.170358869161
0 2.4  0.170202773308
2 2.5  -0.138557648063
4 3.5  0.187965696415
6 4.2  -0.473073365465

This is the code I have so far that doesn't work:

x=[]
y=[]
e=[]

try:
    data = open('data.txt', 'rt')
except:
    sys.exit('cannot find file')

with data:
    try:
        x.append(data[:1])
        y.append(data[2:3])
        e.append(data[4:5])
except:
    sys.exit('cannot create lists')

Body:
I see that the replies above have answers that used hard-coded variables. However I found a way to create lists that can hold infinite lines.

def getFrom(index: int, data: list):
    returnList = []
    for item in data:
        if len(item) >= index:
            returnList.append(item[index])
        else:
            returnList.append("")
    return returnList

In this function, data is the list that you want to search, can be nested, while index is the index you wanted to search. This will return a list contains that was in the index on the vertical space.

You can also try

data = ...
endList = [getFrom(index, data) for index in range(len(data))]

and endList if the result of the array split vertically.


问:
Assigning type of a dynamically generate variable to a list in a loop
I have a set of technical indicators in a list - indicator_list = [ema10,ema20,...]
I am trying to generate a indicator series list which will hold the series value for each stock for each indicator as below -

```<code>indicator_ser_dict = {}
for indicator in indicator_list:
   indicator_ser_list = indicator + '_ser_list'
   indicator_ser_dict[indicator] = indicator_ser_list
</code>```

How do I set the type of each indicator_ser_list to a list. That is each of the value in the indicator_ser_dict needs to be a list.
Please note that indicator_ser_list needs to be treated as a variable and not a string.

答:
I am not sure if I get you right.
I understand that you want every item-value in your indicator_ser_dict to be a single item list.

Given your examples, having ema10,ema20 as input you want to put ema10 into a list and place this single-item-list as value in the dictionary.

You can simply put the item to be listed into square brackets:

```<code>indicator_ser_dict = {}
for indicator in indicator_list:
   indicator_ser_list = [indicator + '_ser_list'] #-> makes indicator_ser_list  to be a list of one element
   indicator_ser_dict[indicator] = indicator_ser_list
</code>```

Since ure concatenating a string to each indicator, the indicator_ser_list of course always was a string. Now its a List of a single string.

Body:
I have a set of technical indicators in a list - indicator_list = [ema10,ema20,...]
I am trying to generate a indicator series list which will hold the series value for each stock for each indicator as below -

indicator_ser_dict = {}
for indicator in indicator_list:
   indicator_ser_list = indicator + '_ser_list'
   indicator_ser_dict[indicator] = indicator_ser_list

How do I set the type of each indicator_ser_list to a list. That is each of the value in the indicator_ser_dict needs to be a list.
Please note that indicator_ser_list needs to be treated as a variable and not a string.

Body:
I am not sure if I get you right.
I understand that you want every item-value in your indicator_ser_dict to be a single item list.

Given your examples, having ema10,ema20 as input you want to put ema10 into a list and place this single-item-list as value in the dictionary.

You can simply put the item to be listed into square brackets:

indicator_ser_dict = {}
for indicator in indicator_list:
   indicator_ser_list = [indicator + '_ser_list'] #-> makes indicator_ser_list  to be a list of one element
   indicator_ser_dict[indicator] = indicator_ser_list

Since ure concatenating a string to each indicator, the indicator_ser_list of course always was a string. Now its a List of a single string.


问:
How to assign values (new or existing column) to equivalent of xs with pandas MultiIndex
I have a MultiIndex DataFrame dfA:

```<code>          0  1
i ii iii
A C  D    1  2
     E    3  4
B C  D    5  6
     E    7  8
</code>```

I want to add columns from another DataFrame, dfB,which matches the MultiIndex of dfA on all levels except one:

```<code>      2  3
i ii
A C   1  2
B C   5  6
</code>```

I was able to do so using,

```<code>dfA.loc[idx[:,:,'E'],dfB.columns] = dfB
</code>```

Yielding,

```<code>          0  1    2    3
i ii iii
A C  D    1  2  NaN  NaN
     E    3  4  1.0  2.0
B C  D    5  6  NaN  NaN
     E    7  8  5.0  6.0
</code>```

However, this doesn't work if the MultiIndex only has 2 levels or when I tried a DataFrame that matches on the last levels instead of the first levels.

Is there a better way to do this? Or one that works more consistently (i.e. independent of where the extra level is)? I also want to be able to set the NaN elements afterwards, e.g. using

```<code>dfA.loc[idx[:,:,'D'],dfB.columns] = dfB*2
</code>```

which I was unable to figure out how to merge with existing columns using merge or join, and combine_first doesn't have an option to operate on a subset of the DataFrame as far as I am aware...

答:
You could use pd.merge for that:</p>
```<code>dfC = pd.merge(dfA, dfB, how="outer", left_index=True, right_index=True)
</code>```

Body:
I have a MultiIndex DataFrame dfA:

          0  1
i ii iii
A C  D    1  2
     E    3  4
B C  D    5  6
     E    7  8

I want to add columns from another DataFrame, dfB,which matches the MultiIndex of dfA on all levels except one:

      2  3
i ii
A C   1  2
B C   5  6

I was able to do so using,

dfA.loc[idx[:,:,'E'],dfB.columns] = dfB

Yielding,

          0  1    2    3
i ii iii
A C  D    1  2  NaN  NaN
     E    3  4  1.0  2.0
B C  D    5  6  NaN  NaN
     E    7  8  5.0  6.0

However, this doesn't work if the MultiIndex only has 2 levels or when I tried a DataFrame that matches on the last levels instead of the first levels.

Is there a better way to do this? Or one that works more consistently (i.e. independent of where the extra level is)? I also want to be able to set the NaN elements afterwards, e.g. using

dfA.loc[idx[:,:,'D'],dfB.columns] = dfB*2

which I was unable to figure out how to merge with existing columns using merge or join, and combine_first doesn't have an option to operate on a subset of the DataFrame as far as I am aware...

Body:
You could use pd.merge for that:

dfC = pd.merge(dfA, dfB, how="outer", left_index=True, right_index=True)


问:
Does Explicit Object Parameter Allow Convertible Types?
From §4.2.7 of the proposal http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2021/p0847r7.html#pathological-cases

It said that:

These are even more unlikely to be actually useful code. In this example, B is neither convertible to A nor int, so neither of these functions is even invocable using normal member syntax. However, you could take a pointer to such functions and invoke them through that pointer. (&B::bar)(42) is valid, if weird, call.

However, It does not specify whether the standard does not allow explicit object parameter of type-of-self implicitly convertible to particular another type.

struct A { };
struct B {
    void foo(this A&);
    void bar(this int);
};
```
<p>Does that mean that:</p>
<pre class="lang-cpp prettyprint-override"><code>struct A { };
struct B {
  operator A() const noexcept;
  void foo(this A);
};

// ...
// '&B::foo' is of type function pointer not pointer to member function
// because it uses explicit object parameter.
(&B::foo)(A{});
(&B::foo)(B{});
B{}.foo(); // will work?
</code>```

will work?

In another case, here is a lambda. Since the type of the lambda is unutterable and is always dependent. What about the case above? (this captureless lambda is convertible to int(*)(int, int, int))

auto fib = [](this int(* self)(int, int, int), int n, int a = 0, int b = 1) {
  return n == 0 ? a : n == 1 ? b : self(n - 1, b, a + b);
};
```

Given that:

Non-member functions, static member functions, and explicit object member functions match targets of function pointer type or reference to function type. Non-static Implicit object member functions match targets of pointer-to-member-function type. ([over.match.viable] §12.2.3)

In all contexts, when converting to the implicit object parameter or when converting to the left operand of an assignment operation only standard conversion sequences are allowed. [Note: When converting to the explicit object parameter, if any, user-defined conversion sequences are allowed. - end note ] ([over.best.ics] §12.2.4.2)

答:
For your first question:

struct A { };
struct B {
  operator A() const noexcept;
  void foo(this A);
};

B{}.foo(); // will work?
```
<p>Yes. Candidate lookup will find <code>B::foo</code>, which more or less evaluates as <code>foo(B{})</code>, which is valid due to the conversion function. This is explicitly called out in the note you cited, in [over.ics.best]/7:</p>
<blockquote>
<p>[<em>Note 5</em>: When converting to the explicit object parameter, if any, user-defined conversion sequences are allowed. — <em>end note</em>]</p>
</blockquote>
<hr />
<p>This one, I'm actually not entirely sure about:</p>
<pre class="lang-cpp prettyprint-override"><code>auto fib = [](this int(* self)(int, int, int), int n, int a = 0, int b = 1) {
  return n == 0 ? a : n == 1 ? b : self(n - 1, b, a + b);
};
</code>```

It seems exceedingly unlikely to be useful and you should probably never do this, so I don't know that it matters whether or not it's actually valid. But also am not sure what it means for examples like this:

struct C {
    C(auto);
    void f();
};

auto lambda = [](this C c) { c.f(); }; // OK?
```

If this is convertible to a function pointer, what function pointer type exactly? If it's void(*)(), then which C are we invoking f() on? So it'd kind of have to be void(*)(C), in which case the fib example definitely does not work because it's impossible to spell the function pointer type non-generically in a way that matches.

Body:
From §4.2.7 of the proposal http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2021/p0847r7.html#pathological-cases

It said that:

These are even more unlikely to be actually useful code. In this example, B is neither convertible to A nor int, so neither of these functions is even invocable using normal member syntax. However, you could take a pointer to such functions and invoke them through that pointer. (&B::bar)(42) is valid, if weird, call.

However, It does not specify whether the standard does not allow explicit object parameter of type-of-self implicitly convertible to particular another type.

struct A { };
struct B {
    void foo(this A&);
    void bar(this int);
};

Does that mean that:

struct A { };
struct B {
  operator A() const noexcept;
  void foo(this A);
};

// ...
// '&B::foo' is of type function pointer not pointer to member function
// because it uses explicit object parameter.
(&B::foo)(A{});
(&B::foo)(B{});
B{}.foo(); // will work?

will work?

In another case, here is a lambda. Since the type of the lambda is unutterable and is always dependent. What about the case above? (this captureless lambda is convertible to int(*)(int, int, int))

auto fib = [](this int(* self)(int, int, int), int n, int a = 0, int b = 1) {
  return n == 0 ? a : n == 1 ? b : self(n - 1, b, a + b);
};

Given that:

Non-member functions, static member functions, and explicit object member functions match targets of function pointer type or reference to function type. Non-static Implicit object member functions match targets of pointer-to-member-function type. ([over.match.viable] §12.2.3)

In all contexts, when converting to the implicit object parameter or when converting to the left operand of an assignment operation only standard conversion sequences are allowed. [Note: When converting to the explicit object parameter, if any, user-defined conversion sequences are allowed. - end note ] ([over.best.ics] §12.2.4.2)

Body:
For your first question:

struct A { };
struct B {
  operator A() const noexcept;
  void foo(this A);
};

B{}.foo(); // will work?

Yes. Candidate lookup will find B::foo, which more or less evaluates as foo(B{}), which is valid due to the conversion function. This is explicitly called out in the note you cited, in [over.ics.best]/7:

[Note 5: When converting to the explicit object parameter, if any, user-defined conversion sequences are allowed. — end note]

This one, I'm actually not entirely sure about:

auto fib = [](this int(* self)(int, int, int), int n, int a = 0, int b = 1) {
  return n == 0 ? a : n == 1 ? b : self(n - 1, b, a + b);
};

It seems exceedingly unlikely to be useful and you should probably never do this, so I don't know that it matters whether or not it's actually valid. But also am not sure what it means for examples like this:

struct C {
    C(auto);
    void f();
};

auto lambda = [](this C c) { c.f(); }; // OK?

If this is convertible to a function pointer, what function pointer type exactly? If it's void(*)(), then which C are we invoking f() on? So it'd kind of have to be void(*)(C), in which case the fib example definitely does not work because it's impossible to spell the function pointer type non-generically in a way that matches.


问:
Flutter multiple inheritance and naming conflicts
I have the following class definition:

```<code>import 'dart:async';

import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:honeywell_scanner/honeywell_scanner.dart' as hw;
import 'package:wh_pick_app/common_widgets/overlay_notification.dart';

class Scanner extends StateNotifier<AsyncValue<String>>
    implements hw.ScannerCallBack {
  hw.HoneywellScanner honeywellScanner = hw.HoneywellScanner();

@override
  String? onError(Exception error) {
    return error.toString();
  }
</code>```

I get an error:

'onError' is inherited as a getter (from 'StateNotifier') and also a method (from 'ScannerCallBack').
Try adjusting the supertypes of this class to remove the inconsistency.

Both are libraries that I can't change the naming. How do I prevent the naming conflicts on 'onError'?

Thanks,

答:
you can this</p>
```<code>class Renaver extends StateNotifier<AsyncValue<String>> {
  String? onError1 => super.onError();
}
class Scanner extends Renaver
    implements hw.ScannerCallBack {
  hw.HoneywellScanner honeywellScanner = hw.HoneywellScanner();

// this ScannerCallBack.onError
@override
  String? onError(Exception error) {
    return error.toString();
  }
// this StateNotifier<AsyncValue<String>>.onError
@override
String? onError1(){
}
</code>```

Body:
I have the following class definition:

import 'dart:async';

import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:honeywell_scanner/honeywell_scanner.dart' as hw;
import 'package:wh_pick_app/common_widgets/overlay_notification.dart';

class Scanner extends StateNotifier<AsyncValue<String>>
    implements hw.ScannerCallBack {
  hw.HoneywellScanner honeywellScanner = hw.HoneywellScanner();

@override
  String? onError(Exception error) {
    return error.toString();
  }

I get an error:

'onError' is inherited as a getter (from 'StateNotifier') and also a method (from 'ScannerCallBack').
Try adjusting the supertypes of this class to remove the inconsistency.

Both are libraries that I can't change the naming. How do I prevent the naming conflicts on 'onError'?

Thanks,

Body:
you can this

class Renaver extends StateNotifier<AsyncValue<String>> {
  String? onError1 => super.onError();
}
class Scanner extends Renaver
    implements hw.ScannerCallBack {
  hw.HoneywellScanner honeywellScanner = hw.HoneywellScanner();

// this ScannerCallBack.onError
@override
  String? onError(Exception error) {
    return error.toString();
  }
// this StateNotifier<AsyncValue<String>>.onError
@override
String? onError1(){
}


问:
LINQ vs context.entity.Where()
Are these two blocks exactly the same? Does one have any advantage over the other?</p>

```<code>        using (var context = new TRANSITEntities())
        {
            var result = context.Table1.Where(c => c.UserCode == "123");
        }

        using (var context = new TRANSITEntities())
        {
            var result = from c in context.Table1
                         where c.UserCode == "123"
                         select c;
        }
</code>```

答:
Exactly the same.

You can verify this yourself by looking at the ToString()

```<code>    string query1String, query2String;
    using (var context = new TRANSITEntities())
    {
        var result = context.Table1.Where(c => c.UserCode == "123");
        query1String = result.Expression.ToString();
    }

    using (var context = new TRANSITEntities())
    {
        var result = from c in context.Table1
                     where c.UserCode == "123"
                     select c;
        var query2String = result.Expression.ToString();
    }

    Assert.AreEqual(query1String, query2String);
</code>```

It should also be noted that result is NOT actually a result. It's a non-executed/enumerated IQueryable. Meaning it's like a SQL statement that hasn't been run yet (sort of). If you were to do

```<code>    var t1 = result.ToArray()
    var t2 = result.ToArray()
</code>```

then the query would actually be executed twice. t1 and t2 are the REAL results (an in memory array)...not result. In other words, result should really be named query And further, the example you have above will never work...because if you call ToArray on the result outside of the using block, it will fail...because you can't run the query once the context is disposed:

```<code>    using (var context = new TRANSITEntities())
    {
        var result = context.Table1.Where(c => c.UserCode == "123");
    }
    // throws exception:
    var array = result.ToArray();
</code>```

Title: LINQ vs context.entity.Where()

Body:
Are these two blocks exactly the same? Does one have any advantage over the other?

        using (var context = new TRANSITEntities())
        {
            var result = context.Table1.Where(c => c.UserCode == "123");
        }

        using (var context = new TRANSITEntities())
        {
            var result = from c in context.Table1
                         where c.UserCode == "123"
                         select c;
        }

Body:
Exactly the same.

You can verify this yourself by looking at the ToString()

    string query1String, query2String;
    using (var context = new TRANSITEntities())
    {
        var result = context.Table1.Where(c => c.UserCode == "123");
        query1String = result.Expression.ToString();
    }

    using (var context = new TRANSITEntities())
    {
        var result = from c in context.Table1
                     where c.UserCode == "123"
                     select c;
        var query2String = result.Expression.ToString();
    }

    Assert.AreEqual(query1String, query2String);

It should also be noted that result is NOT actually a result. It's a non-executed/enumerated IQueryable. Meaning it's like a SQL statement that hasn't been run yet (sort of). If you were to do

    var t1 = result.ToArray()
    var t2 = result.ToArray()

then the query would actually be executed twice. t1 and t2 are the REAL results (an in memory array)...not result. In other words, result should really be named query And further, the example you have above will never work...because if you call ToArray on the result outside of the using block, it will fail...because you can't run the query once the context is disposed:

    using (var context = new TRANSITEntities())
    {
        var result = context.Table1.Where(c => c.UserCode == "123");
    }
    // throws exception:
    var array = result.ToArray();


问:
Subsetting dataframe in grouped data
I have a dataframe including a column of factors that I would like to subset to select every nth row, after grouping by factor level.  For example,

```<code>my_df <- data.frame(col1 = c(1:12), col2 = rep(c("A","B", "C"), 4))
my_df
  col1 col2
1     1    A
2     2    B
3     3    C
4     4    A
5     5    B
6     6    C
7     7    A
8     8    B
9     9    C
10   10    A
11   11    B
12   12    C
</code>```

Subsetting to select every 2nd row should yield my_new_df as,

```<code>  col1 col2
1    4    A
2   10    A
3    5    B
4   11    B
5    6    C
6   12    C
</code>```

I tried in dplyr:

```<code>my_df %>% group_by(col2) %>%
my_df[seq(2, nrow(my_df), 2), ] -> my_new_df
</code>```

I get an error:

```<code>Error: Can't subset columns that don't exist.
x Locations 4, 6, 8, 10, and 12 don't exist.
ℹ There are only 2 columns.
</code>```

To see if the nrow function was a problem, I tried using the number directly. So,

```<code>my_df %>% group_by(col2) %>%
   my_df[seq(2, 4, 2), ] -> my_new_df
</code>```

Also gave an error,

```<code>Error: Can't subset columns that don't exist.
x Location 4 doesn't exist.
ℹ There are only 2 columns.
Run `rlang::last_error()` to see where the error occurred.
</code>```

My expectation was that it would run the subsetting on each group of data and then combine them into 'my_new_df'.  My understanding of how group_by works is clearly wrong but I am stuck on how to move past this error.  Any help would much appreciated.

答:
Here is a data.table option:

```<code>library(data.table)
data <- as.data.table(my_df)

data[(rowid(col2) %% 2) == 0]

   col1 col2
1:    4    A
2:    5    B
3:    6    C
4:   10    A
5:   11    B
6:   12    C
</code>```

Or base R:

```<code>my_df[as.logical(with(my_df, ave(col1, col2, FUN = function(x)
  seq_along(x) %% 2 == 0))), ]

   col1 col2
4     4    A
5     5    B
6     6    C
10   10    A
11   11    B
12   12    C
</code>```

Title: Subsetting dataframe in grouped data

Body:
I have a dataframe including a column of factors that I would like to subset to select every nth row, after grouping by factor level.  For example,

my_df <- data.frame(col1 = c(1:12), col2 = rep(c("A","B", "C"), 4))
my_df
  col1 col2
1     1    A
2     2    B
3     3    C
4     4    A
5     5    B
6     6    C
7     7    A
8     8    B
9     9    C
10   10    A
11   11    B
12   12    C

Subsetting to select every 2nd row should yield my_new_df as,

  col1 col2
1    4    A
2   10    A
3    5    B
4   11    B
5    6    C
6   12    C

I tried in dplyr:

my_df %>% group_by(col2) %>%
my_df[seq(2, nrow(my_df), 2), ] -> my_new_df

I get an error:

Error: Can't subset columns that don't exist.
x Locations 4, 6, 8, 10, and 12 don't exist.
ℹ There are only 2 columns.

To see if the nrow function was a problem, I tried using the number directly. So,

my_df %>% group_by(col2) %>%
   my_df[seq(2, 4, 2), ] -> my_new_df

Also gave an error,

Error: Can't subset columns that don't exist.
x Location 4 doesn't exist.
ℹ There are only 2 columns.
Run `rlang::last_error()` to see where the error occurred.

My expectation was that it would run the subsetting on each group of data and then combine them into 'my_new_df'.  My understanding of how group_by works is clearly wrong but I am stuck on how to move past this error.  Any help would much appreciated.

Body:
Here is a data.table option:

library(data.table)
data <- as.data.table(my_df)

data[(rowid(col2) %% 2) == 0]

   col1 col2
1:    4    A
2:    5    B
3:    6    C
4:   10    A
5:   11    B
6:   12    C

Or base R:

my_df[as.logical(with(my_df, ave(col1, col2, FUN = function(x)
  seq_along(x) %% 2 == 0))), ]

   col1 col2
4     4    A
5     5    B
6     6    C
10   10    A
11   11    B
12   12    C


问:
Missing compileSdkVersion for google mobile ads
```<code>defaultConfig {
    // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
    applicationId "com.example.ringit2"
    minSdkVersion 21
    targetSdkVersion 30
    versionCode flutterVersionCode.toInteger()
    versionName flutterVersionName
}
</code>```

Here is what I found on my build.gradle and I can't find compileSdkVersion which I have to change to at least 28 in order for google mobile ads to operate.

After I added google_mobile_ads: ^1.1.0 on pubspec.yaml and imported the package to the main.dart, The app opens as I run the simulator but shuts down right away. Console shows me this message and it is stuck just like this forever.

```<code>Launching lib\main.dart on SM G950N in debug mode...
Running Gradle task 'assembleDebug'...
√  Built build\app\outputs\flutter-apk\app-debug.apk.
Installing build\app\outputs\flutter-apk\app.apk...
</code>```

Please note that my ext.kotlin_version is '1.6.10' because people have recommended to upgrade it

```<code>distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.0.2-all.zip
</code>```

Also changed the distributionUrl...

Not sure why google mobile ads package is so hard to use even just to start but what should I change to use it?

答:
The compileSdkVersion will be inside
android>app>build.gradle
inside that you can see compileSdkVersion in line 30

Also check your environment path of flutter

Body:
defaultConfig {
    // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
    applicationId "com.example.ringit2"
    minSdkVersion 21
    targetSdkVersion 30
    versionCode flutterVersionCode.toInteger()
    versionName flutterVersionName
}

Here is what I found on my build.gradle and I can't find compileSdkVersion which I have to change to at least 28 in order for google mobile ads to operate.

After I added google_mobile_ads: ^1.1.0 on pubspec.yaml and imported the package to the main.dart, The app opens as I run the simulator but shuts down right away. Console shows me this message and it is stuck just like this forever.

Launching lib\main.dart on SM G950N in debug mode...
Running Gradle task 'assembleDebug'...
√  Built build\app\outputs\flutter-apk\app-debug.apk.
Installing build\app\outputs\flutter-apk\app.apk...

Please note that my ext.kotlin_version is '1.6.10' because people have recommended to upgrade it

distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.0.2-all.zip

Also changed the distributionUrl...

Not sure why google mobile ads package is so hard to use even just to start but what should I change to use it?