问:
Swift + Not Deleting Current Item in Single Linked List
I have a linked list that is not deleting the current item based off the inserted value which in the case below is the value of 5.0. I want to delete 5.0 from my inserted values but the console is still printing out all inserted values of 5.0, 8.0, and 10.0. I tried changing the conditions in func delete() and tried several changes in the block of code that is executed in func delete() as well. I suspect something is backwards with head?.nextNodeAddress = head?.nextNodeAddress inside func delete(). Also, does the current value actually get deleted in a linked list when setting head (e.g. pointer) to the next node address or does it just overlook the current node value that matches the inserted value?

Note: I did not include func insert(value:) because it did not seem to pertain to the issue. The value insert as expected.

//Node Class:

```<code>class Node {

    let value: Double
    var nextNodeAddress: Node?

    init(value: Double, next: Node?) {
        self.value = value
        self.nextNodeAddress = next
    }
}
</code>```

//Linked List

```<code>class LinkedList {

    var head: Node?

    func delete(value: Double) {
        if head?.value != value {
            head?.nextNodeAddress = head?.nextNodeAddress
        }
    }

    func displayListItems() {

        var current = head
        while current != nil {
            print(current?.value ?? "")
            current = current?.nextNodeAddress
        }
    }

}

let boltSize = LinkedList()
boltSize.insert(value: 5.0)
boltSize.insert(value: 8.0)
boltSize.insert(value: 10.0)
boltSize.delete(value: 5.0)
boltSize.displayListItems()
</code>```

答:
As Rob stated above, it's best to add your insert function as well so that we can rule out any bugs in the insert.

However, I does not seem like the delete function does anything.

Let's trace it.

After your three inserts your linked list looks like this assuming your insert works fine.

node(5.0) -> node(8.0) -> node(10.0) and Head is pointing to node(5.0)

Then you call boltSize.delete(value: 5.0)

and let's look at what the function does

```<code>func delete(value: Double) {
        if head?.value != value {
            head?.nextNodeAddress = head?.nextNodeAddress
        }
    }
</code>```

You pass the function 5.0

The it compares Head.value != 5.0 which is 5.0 != 5.0 - false

So your next line of code does not run anyways and nothing gets deleted

Let's take another example, say you want to delete 8.0

You pass the function 8.0

The it compares Head.value != 5.0 which is 5.0 != 8.0 - true

So inside the if block head?.nextNodeAddress = head?.nextNodeAddress - Head's next node address is Node(8.0) and this line keeps it Node(8.0)

The function ends

So as you can see two issues:

There is no deletion happening

Your delete code does not have a loop to reach the correct node to delete as it ends after one iteration and comparison with the head

This is how I would approach the deletion and actually is similar to what you did in your display function:

```<code>func delete(_ value: Int)
{
    // Check if head itself has the data to be deleted
    if head?.value == value
    {
        // The new head is the node after head
        head = head?.nextNodeAddress

        // We can exit, nothing more to do
        return
    }

    // Create a temp node pointer that will iterate through
    // your linked list starting starting from the head
    var currentNode = head

    // Loop through the list till you reach the end
    while currentNode?.nextNodeAddress != nil
    {
        // Check if the next node has the value we want to delete
        if currentNode?.nextNodeAddress?.value == value
        {
            // Retrieve the next node
            let nextNode = currentNode?.nextNodeAddress

            // Assign current node's next to next node's next
            // This way, there is no link to the next node anymore
            currentNode?.nextNodeAddress = nextNode?.nextNodeAddress

            // The delete is complete and we can exit
            return
        }

        // Since the node was not found in this iteration, advance
        // the pointer
        currentNode = currentNode?.nextNodeAddress
    }
}
</code>```

This is probably more verbose way to clarify what is going on, you can feel free to shorten it as you see fit.

Body:
I have a linked list that is not deleting the current item based off the inserted value which in the case below is the value of 5.0. I want to delete 5.0 from my inserted values but the console is still printing out all inserted values of 5.0, 8.0, and 10.0. I tried changing the conditions in func delete() and tried several changes in the block of code that is executed in func delete() as well. I suspect something is backwards with head?.nextNodeAddress = head?.nextNodeAddress inside func delete(). Also, does the current value actually get deleted in a linked list when setting head (e.g. pointer) to the next node address or does it just overlook the current node value that matches the inserted value?

Note: I did not include func insert(value:) because it did not seem to pertain to the issue. The value insert as expected.

//Node Class:

class Node {

    let value: Double
    var nextNodeAddress: Node?

    init(value: Double, next: Node?) {
        self.value = value
        self.nextNodeAddress = next
    }
}

//Linked List

class LinkedList {

    var head: Node?

    func delete(value: Double) {
        if head?.value != value {
            head?.nextNodeAddress = head?.nextNodeAddress
        }
    }

    func displayListItems() {

        var current = head
        while current != nil {
            print(current?.value ?? "")
            current = current?.nextNodeAddress
        }
    }

}

let boltSize = LinkedList()
boltSize.insert(value: 5.0)
boltSize.insert(value: 8.0)
boltSize.insert(value: 10.0)
boltSize.delete(value: 5.0)
boltSize.displayListItems()

Body:
As Rob stated above, it's best to add your insert function as well so that we can rule out any bugs in the insert.

However, I does not seem like the delete function does anything.

Let's trace it.

After your three inserts your linked list looks like this assuming your insert works fine.

node(5.0) -> node(8.0) -> node(10.0) and Head is pointing to node(5.0)

Then you call boltSize.delete(value: 5.0)

and let's look at what the function does

func delete(value: Double) {
        if head?.value != value {
            head?.nextNodeAddress = head?.nextNodeAddress
        }
    }

You pass the function 5.0

The it compares Head.value != 5.0 which is 5.0 != 5.0 - false

So your next line of code does not run anyways and nothing gets deleted

Let's take another example, say you want to delete 8.0

You pass the function 8.0

The it compares Head.value != 5.0 which is 5.0 != 8.0 - true

So inside the if block head?.nextNodeAddress = head?.nextNodeAddress - Head's next node address is Node(8.0) and this line keeps it Node(8.0)

The function ends

So as you can see two issues:

There is no deletion happening

Your delete code does not have a loop to reach the correct node to delete as it ends after one iteration and comparison with the head

This is how I would approach the deletion and actually is similar to what you did in your display function:

func delete(_ value: Int)
{
    // Check if head itself has the data to be deleted
    if head?.value == value
    {
        // The new head is the node after head
        head = head?.nextNodeAddress

        // We can exit, nothing more to do
        return
    }

    // Create a temp node pointer that will iterate through
    // your linked list starting starting from the head
    var currentNode = head

    // Loop through the list till you reach the end
    while currentNode?.nextNodeAddress != nil
    {
        // Check if the next node has the value we want to delete
        if currentNode?.nextNodeAddress?.value == value
        {
            // Retrieve the next node
            let nextNode = currentNode?.nextNodeAddress

            // Assign current node's next to next node's next
            // This way, there is no link to the next node anymore
            currentNode?.nextNodeAddress = nextNode?.nextNodeAddress

            // The delete is complete and we can exit
            return
        }

        // Since the node was not found in this iteration, advance
        // the pointer
        currentNode = currentNode?.nextNodeAddress
    }
}

This is probably more verbose way to clarify what is going on, you can feel free to shorten it as you see fit.


来源: stackexchange

问:
Setting rows and columns in input <textarea> in reactJS form
I have a ReactJS function that takes a long text string as input and uses it for further processing :

```<code>import React, { useState } from "react";
import p21logo from '../images/p21logo-002-1.png'; // with import

export default function SetFilter() {
const filter1 = {"exaltG.Ju": {"$eq": true}}
const [filter, setFilter] = useState(JSON.stringify(filter1));

  const handleSubmit = (e) => {
    e.preventDefault()
    const message = `data is ${filter}`;
    window.alert(message);
    window.open(`/getfilteredrecords/${filter}`);
  };

 return (
   <div>
       <table>
           <tr>
            <td>
            C<img src={p21logo} alt="ParasharLogo"></img>
            </td>
            <td>
            <form onSubmit={handleSubmit}>
              <p>Set Filter :</p>
              <label>
                <input
                  type="textarea"
                  value={filter}
                  onChange={(e) => setFilter(e.target.value)}
                  rows={5}
                  cols={60}
                />

              </label>
              <br></br>
              <input type="submit" />
            </form>
            </td>
          </tr>
      </table>
   </div>
 );
}
</code>```

However, irrespective of what I set as the number of rows and columns of the textarea, what shows up is the small, single line default text field. While I can still enter a large text string in this small field, by scrolling to the right, it would be better if I could give a large area as this would obviously help the user to visually see whether the full text has been entered correctly. How should I change my code to offer a larger textarea for data entry?

答:
You need to use TextArea</p>
```<code><textarea name="Text1" cols="60" rows="5"></textarea>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a ReactJS function that takes a long text string as input and uses it for further processing :

import React, { useState } from "react";
import p21logo from '../images/p21logo-002-1.png'; // with import

export default function SetFilter() {
const filter1 = {"exaltG.Ju": {"$eq": true}}
const [filter, setFilter] = useState(JSON.stringify(filter1));

  const handleSubmit = (e) => {
    e.preventDefault()
    const message = `data is ${filter}`;
    window.alert(message);
    window.open(`/getfilteredrecords/${filter}`);
  };

 return (

            C

            <form onSubmit={handleSubmit}>

Set Filter :

                <input
                  type="textarea"
                  value={filter}
                  onChange={(e) => setFilter(e.target.value)}
                  rows={5}
                  cols={60}
                />

              <input type="submit" />
            </form>

 );
}

However, irrespective of what I set as the number of rows and columns of the textarea, what shows up is the small, single line default text field. While I can still enter a large text string in this small field, by scrolling to the right, it would be better if I could give a large area as this would obviously help the user to visually see whether the full text has been entered correctly. How should I change my code to offer a larger textarea for data entry?

Body:
You need to use TextArea

<textarea name="Text1" cols="60" rows="5"></textarea>


问:
Plotting histogram with mixture density curve in ggplot
I'm trying to plot the geyser data from the R library MASS and add onto it a curve representing the mixture density f(x)=1/3\phi_1(x) + 2/3\phi_2(x) where \phi_1(x) and \phi_2(x) are the normal densities with standard deviation 7 and means 52 and 80 respectively.

I was able to plot it with hist() and line(), but how do I do the same thing in ggplot?

```<code>library(MASS)
data("geyser")
hist(geyser$waiting, breaks = 25, col = "red", freq = F,
     xlab = "Time", ylab = "Frequency", main = "Waiting Time For Eruption")

x.seq <- seq(40, 110, length.out = 100)
pdf <- dnorm(x.seq, mean = 52, sd = 7)/3 + 2*dnorm(x.seq, mean = 80, sd = 7)/3
lines(pdf~x.seq, col = "black")
</code>```

答:
You can use something like

```<code>library(ggplot2)
df_pdf = data.frame(x = x.seq, y = pdf)
ggplot(geyser) +
   geom_histogram(aes(x = waiting, y = ..density..), binwidth = 5) +
   geom_line(data = df_pdf, aes(x = x, y = y), color = "red")
</code>```

Body:
I'm trying to plot the geyser data from the R library MASS and add onto it a curve representing the mixture density f(x)=1/3\phi_1(x) + 2/3\phi_2(x) where \phi_1(x) and \phi_2(x) are the normal densities with standard deviation 7 and means 52 and 80 respectively.

I was able to plot it with hist() and line(), but how do I do the same thing in ggplot?

library(MASS)
data("geyser")
hist(geyser$waiting, breaks = 25, col = "red", freq = F,
     xlab = "Time", ylab = "Frequency", main = "Waiting Time For Eruption")

x.seq <- seq(40, 110, length.out = 100)
pdf <- dnorm(x.seq, mean = 52, sd = 7)/3 + 2*dnorm(x.seq, mean = 80, sd = 7)/3
lines(pdf~x.seq, col = "black")

Body:
You can use something like

library(ggplot2)
df_pdf = data.frame(x = x.seq, y = pdf)
ggplot(geyser) +
   geom_histogram(aes(x = waiting, y = ..density..), binwidth = 5) +
   geom_line(data = df_pdf, aes(x = x, y = y), color = "red")


问:
Android Studio icon not showing in taskbar - Windows 11
Recently I upgraded from Windows 10 to Windows 11. But now when I open Android Studio only a blank file icon appears on the taskbar.

Is there any way to retrieve the original Android Studio icon?

I have also checked that the .ico file exists in C:\Program Files\Android\Android Studio\bin\studio.ico

答:
I did this and it showed for me:

From start menu: right-click its icon.

Click More -> Open file location.

Right-lick the shortcut and choose Open file location.

From the opened directory, open the file studio.ico with any app.

And suddenly the taskbar refreshed and it showed.


问:
What is lexical scope?
What is a brief introduction to lexical scoping?</p>

答: Lexical scoping means functions resolve free variables from the scope where they were defined, not from the scope where they are called.</p>

Title: What is lexical scope?


问:
How to Get 10 from this link (https://google.com/?ib=10)
Check this image
I have this link in (note this link not from search URL)
var link = https://google.com/?ib=10 in main.js file.
Now how to get that 10 from this link in javaScript on Page load

I have tried this way

```<code>var link1 = link;
const url3 = new URLSearchParams(link1);
    const ur = url3.get("ib");
    var finaltgid = ur;
    alert(ur);
</code>```

But its not working may be this code only work when we use window.location.search
Instead of var or const

答:
urlsearchparams does not parse full url, you need to pass only query part, like this:

var link = 'https://google.com/?ib=10';
const url = new URLSearchParams(new URL(link).search);
const ib = url.get("ib");
console.log(ib);```

Body:
Check this image
I have this link in (note this link not from search URL)
var link = https://google.com/?ib=10 in main.js file.
Now how to get that 10 from this link in javaScript on Page load

I have tried this way

var link1 = link;
const url3 = new URLSearchParams(link1);
    const ur = url3.get("ib");
    var finaltgid = ur;
    alert(ur);

But its not working may be this code only work when we use window.location.search
Instead of var or const


问:
Kubernetes Cassandra Datacenter deletes PVC while deleting Datacenter
I have cassandra operator installed and I setup cassandra datacenter/cluster with 3 nodes.
I have created sample keyspace, table and inserted the data. I see it has created 3 PVC's in my storage section. When I deleting the dataceneter its delete associated PVC's as well ,So when I setup same configuration Datacenter/cluster , its completely new , No earlier keyspace or tables.
How can I make them persistence for future use? I am using sample yaml from below
https://github.com/datastax/cass-operator/tree/master/operator/example-cassdc-yaml/cassandra-3.11.x

I don't find any persistentVolumeClaim configuration in it , Its having storageConfig:
cassandraDataVolumeClaimSpec:
Is anyone came across such scenario?

Edit: Storage class details:

```<code>allowVolumeExpansion: true
apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata:
  annotations:
    description: Provides RWO and RWX Filesystem volumes with Retain Policy
  storageclass.kubernetes.io/is-default-class: "false"
  name: ocs-storagecluster-cephfs-retain
parameters:
  clusterID: openshift-storage
  csi.storage.k8s.io/controller-expand-secret-name: rook-csi-cephfs-provisioner
  csi.storage.k8s.io/controller-expand-secret-namespace: openshift-storage
  csi.storage.k8s.io/node-stage-secret-name: rook-csi-cephfs-node
  csi.storage.k8s.io/node-stage-secret-namespace: openshift-storage
  csi.storage.k8s.io/provisioner-secret-name: rook-csi-cephfs-provisioner
  csi.storage.k8s.io/provisioner-secret-namespace: openshift-storage
  fsName: ocs-storagecluster-cephfilesystem
provisioner: openshift-storage.cephfs.csi.ceph.com
reclaimPolicy: Retain
volumeBindingMode: Immediate
</code>```

Here is Cassandra cluster YAML:

```<code>    apiVersion: cassandra.datastax.com/v1beta1
kind: CassandraDatacenter
metadata:
  name: dc
  generation: 2
spec:
  size: 3
  config:
    cassandra-yaml:
      authenticator: AllowAllAuthenticator
      authorizer: AllowAllAuthorizer
      role_manager: CassandraRoleManager
    jvm-options:
      additional-jvm-opts:
        - '-Ddse.system_distributed_replication_dc_names=dc1'
        - '-Ddse.system_distributed_replication_per_dc=1'
      initial_heap_size: 800M
      max_heap_size: 800M
  resources: {}
  clusterName: cassandra
  systemLoggerResources: {}
  configBuilderResources: {}
  serverVersion: 3.11.7
  serverType: cassandra
  storageConfig:
    cassandraDataVolumeClaimSpec:
      accessModes:
        - ReadWriteOnce
      resources:
        requests:
          storage: 10Gi
      storageClassName: ocs-storagecluster-cephfs-retain
  managementApiAuth:
    insecure: {}
</code>```

EDIT: PV Details:

```<code>oc get pv pvc-15def0ca-6cbc-4569-a560-7b9e89a7b7a7 -o yaml

apiVersion: v1
kind: PersistentVolume
metadata:
  annotations:
    pv.kubernetes.io/provisioned-by: openshift-storage.cephfs.csi.ceph.com
  creationTimestamp: "2022-02-23T20:52:54Z"
  finalizers:
  - kubernetes.io/pv-protection
  managedFields:
  - apiVersion: v1
    fieldsType: FieldsV1
    fieldsV1:
      f:metadata:
        f:annotations:
          .: {}
          f:pv.kubernetes.io/provisioned-by: {}
      f:spec:
        f:accessModes: {}
        f:capacity:
          .: {}
          f:storage: {}
        f:claimRef:
          .: {}
          f:apiVersion: {}
          f:kind: {}
          f:name: {}
          f:namespace: {}
          f:resourceVersion: {}
          f:uid: {}
        f:csi:
          .: {}
          f:controllerExpandSecretRef:
            .: {}
            f:name: {}
            f:namespace: {}
          f:driver: {}
          f:nodeStageSecretRef:
            .: {}
            f:name: {}
            f:namespace: {}
          f:volumeAttributes:
            .: {}
            f:clusterID: {}
            f:fsName: {}
            f:storage.kubernetes.io/csiProvisionerIdentity: {}
            f:subvolumeName: {}
          f:volumeHandle: {}
        f:persistentVolumeReclaimPolicy: {}
        f:storageClassName: {}
        f:volumeMode: {}
    manager: csi-provisioner
    operation: Update
    time: "2022-02-23T20:52:54Z"
  - apiVersion: v1
    fieldsType: FieldsV1
    fieldsV1:
      f:status:
        f:phase: {}
    manager: kube-controller-manager
    operation: Update
    time: "2022-02-23T20:52:54Z"
  name: pvc-15def0ca-6cbc-4569-a560-7b9e89a7b7a7
  resourceVersion: "51684941"
  selfLink: /api/v1/persistentvolumes/pvc-15def0ca-6cbc-4569-a560-7b9e89a7b7a7
  uid: 8ded2de5-6d4e-45a1-9b89-a385d74d6d4a
spec:
  accessModes:
  - ReadWriteOnce
  capacity:
    storage: 10Gi
  claimRef:
    apiVersion: v1
    kind: PersistentVolumeClaim
    name: server-data-cstone-cassandra-cstone-dc-default-sts-1
    namespace: dv01-cornerstone
    resourceVersion: "51684914"
    uid: 15def0ca-6cbc-4569-a560-7b9e89a7b7a7
  csi:
    controllerExpandSecretRef:
      name: rook-csi-cephfs-provisioner
      namespace: openshift-storage
    driver: openshift-storage.cephfs.csi.ceph.com
    nodeStageSecretRef:
      name: rook-csi-cephfs-node
      namespace: openshift-storage
    volumeAttributes:
      clusterID: openshift-storage
      fsName: ocs-storagecluster-cephfilesystem
      storage.kubernetes.io/csiProvisionerIdentity: 1645064620191-8081-openshift-storage.cephfs.csi.ceph.com
      subvolumeName: csi-vol-92d5e07d-94ea-11ec-92e8-0a580a20028c
    volumeHandle: 0001-0011-openshift-storage-0000000000000001-92d5e07d-94ea-11ec-92e8-0a580a20028c
  persistentVolumeReclaimPolicy: Retain
  storageClassName: ocs-storagecluster-cephfs-retain
  volumeMode: Filesystem
status:
  phase: Bound
</code>```

答:
According to the spec:

The storage configuration. This sets up a 100GB volume at /var/lib/cassandra
on each server pod. The user is left to create the server-storage storage
class by following these directions...
https://cloud.google.com/kubernetes-engine/docs/how-to/persistent-volumes/ssd-pd

Before you deploy the Cassandra spec, first ensure your cluster already have the CSI driver installed and working properly, then proceed to create the StorageClass as the spec required:

```<code>apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata:
  name: server-storage
provisioner: pd.csi.storage.gke.io
volumeBindingMode: WaitForFirstConsumer
allowVolumeExpansion: true
reclaimPolicy: Retain
parameters:
  type: pd-ssd
</code>```

Re-deploy your Cassandra now should have the data disk retain upon deletion.

Body:
I have cassandra operator installed and I setup cassandra datacenter/cluster with 3 nodes.
I have created sample keyspace, table and inserted the data. I see it has created 3 PVC's in my storage section. When I deleting the dataceneter its delete associated PVC's as well ,So when I setup same configuration Datacenter/cluster , its completely new , No earlier keyspace or tables.
How can I make them persistence for future use? I am using sample yaml from below
https://github.com/datastax/cass-operator/tree/master/operator/example-cassdc-yaml/cassandra-3.11.x

I don't find any persistentVolumeClaim configuration in it , Its having storageConfig:
cassandraDataVolumeClaimSpec:
Is anyone came across such scenario?

Edit: Storage class details:

allowVolumeExpansion: true
apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata:
  annotations:
    description: Provides RWO and RWX Filesystem volumes with Retain Policy
  storageclass.kubernetes.io/is-default-class: "false"
  name: ocs-storagecluster-cephfs-retain
parameters:
  clusterID: openshift-storage
  csi.storage.k8s.io/controller-expand-secret-name: rook-csi-cephfs-provisioner
  csi.storage.k8s.io/controller-expand-secret-namespace: openshift-storage
  csi.storage.k8s.io/node-stage-secret-name: rook-csi-cephfs-node
  csi.storage.k8s.io/node-stage-secret-namespace: openshift-storage
  csi.storage.k8s.io/provisioner-secret-name: rook-csi-cephfs-provisioner
  csi.storage.k8s.io/provisioner-secret-namespace: openshift-storage
  fsName: ocs-storagecluster-cephfilesystem
provisioner: openshift-storage.cephfs.csi.ceph.com
reclaimPolicy: Retain
volumeBindingMode: Immediate

Here is Cassandra cluster YAML:

    apiVersion: cassandra.datastax.com/v1beta1
kind: CassandraDatacenter
metadata:
  name: dc
  generation: 2
spec:
  size: 3
  config:
    cassandra-yaml:
      authenticator: AllowAllAuthenticator
      authorizer: AllowAllAuthorizer
      role_manager: CassandraRoleManager
    jvm-options:
      additional-jvm-opts:
        - '-Ddse.system_distributed_replication_dc_names=dc1'
        - '-Ddse.system_distributed_replication_per_dc=1'
      initial_heap_size: 800M
      max_heap_size: 800M
  resources: {}
  clusterName: cassandra
  systemLoggerResources: {}
  configBuilderResources: {}
  serverVersion: 3.11.7
  serverType: cassandra
  storageConfig:
    cassandraDataVolumeClaimSpec:
      accessModes:
        - ReadWriteOnce
      resources:
        requests:
          storage: 10Gi
      storageClassName: ocs-storagecluster-cephfs-retain
  managementApiAuth:
    insecure: {}

EDIT: PV Details:

oc get pv pvc-15def0ca-6cbc-4569-a560-7b9e89a7b7a7 -o yaml

apiVersion: v1
kind: PersistentVolume
metadata:
  annotations:
    pv.kubernetes.io/provisioned-by: openshift-storage.cephfs.csi.ceph.com
  creationTimestamp: "2022-02-23T20:52:54Z"
  finalizers:
  - kubernetes.io/pv-protection
  managedFields:
  - apiVersion: v1
    fieldsType: FieldsV1
    fieldsV1:
      f:metadata:
        f:annotations:
          .: {}
          f:pv.kubernetes.io/provisioned-by: {}
      f:spec:
        f:accessModes: {}
        f:capacity:
          .: {}
          f:storage: {}
        f:claimRef:
          .: {}
          f:apiVersion: {}
          f:kind: {}
          f:name: {}
          f:namespace: {}
          f:resourceVersion: {}
          f:uid: {}
        f:csi:
          .: {}
          f:controllerExpandSecretRef:
            .: {}
            f:name: {}
            f:namespace: {}
          f:driver: {}
          f:nodeStageSecretRef:
            .: {}
            f:name: {}
            f:namespace: {}
          f:volumeAttributes:
            .: {}
            f:clusterID: {}
            f:fsName: {}
            f:storage.kubernetes.io/csiProvisionerIdentity: {}
            f:subvolumeName: {}
          f:volumeHandle: {}
        f:persistentVolumeReclaimPolicy: {}
        f:storageClassName: {}
        f:volumeMode: {}
    manager: csi-provisioner
    operation: Update
    time: "2022-02-23T20:52:54Z"
  - apiVersion: v1
    fieldsType: FieldsV1
    fieldsV1:
      f:status:
        f:phase: {}
    manager: kube-controller-manager
    operation: Update
    time: "2022-02-23T20:52:54Z"
  name: pvc-15def0ca-6cbc-4569-a560-7b9e89a7b7a7
  resourceVersion: "51684941"
  selfLink: /api/v1/persistentvolumes/pvc-15def0ca-6cbc-4569-a560-7b9e89a7b7a7
  uid: 8ded2de5-6d4e-45a1-9b89-a385d74d6d4a
spec:
  accessModes:
  - ReadWriteOnce
  capacity:
    storage: 10Gi
  claimRef:
    apiVersion: v1
    kind: PersistentVolumeClaim
    name: server-data-cstone-cassandra-cstone-dc-default-sts-1
    namespace: dv01-cornerstone
    resourceVersion: "51684914"
    uid: 15def0ca-6cbc-4569-a560-7b9e89a7b7a7
  csi:
    controllerExpandSecretRef:
      name: rook-csi-cephfs-provisioner
      namespace: openshift-storage
    driver: openshift-storage.cephfs.csi.ceph.com
    nodeStageSecretRef:
      name: rook-csi-cephfs-node
      namespace: openshift-storage
    volumeAttributes:
      clusterID: openshift-storage
      fsName: ocs-storagecluster-cephfilesystem
      storage.kubernetes.io/csiProvisionerIdentity: 1645064620191-8081-openshift-storage.cephfs.csi.ceph.com
      subvolumeName: csi-vol-92d5e07d-94ea-11ec-92e8-0a580a20028c
    volumeHandle: 0001-0011-openshift-storage-0000000000000001-92d5e07d-94ea-11ec-92e8-0a580a20028c
  persistentVolumeReclaimPolicy: Retain
  storageClassName: ocs-storagecluster-cephfs-retain
  volumeMode: Filesystem
status:
  phase: Bound

Body:
According to the spec:

The storage configuration. This sets up a 100GB volume at /var/lib/cassandra
on each server pod. The user is left to create the server-storage storage
class by following these directions...
https://cloud.google.com/kubernetes-engine/docs/how-to/persistent-volumes/ssd-pd

Before you deploy the Cassandra spec, first ensure your cluster already have the CSI driver installed and working properly, then proceed to create the StorageClass as the spec required:

apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata:
  name: server-storage
provisioner: pd.csi.storage.gke.io
volumeBindingMode: WaitForFirstConsumer
allowVolumeExpansion: true
reclaimPolicy: Retain
parameters:
  type: pd-ssd

Re-deploy your Cassandra now should have the data disk retain upon deletion.


问:
Cannot install pyansys using pip install
I am on Pycharm and wish to install the pyansys package, but I keep getting this error:

```<code>Collecting pyansys
  Using cached pyansys-0.61.3.tar.gz (11 kB)
  Preparing metadata (setup.py) ... error
  error: subprocess-exited-with-error

  × python setup.py egg_info did not run successfully.
  │ exit code: 1
  ╰─> [21 lines of output]

      *** PyAnsys has moved (and expanded!) ***

      To use PyAnsys you need to install the applicable packages for your
      product:

      MAPDL:

      - ``pip install ansys-mapdl-core``

      MAPDL Post-Processing:

      - ``pip install ansys-mapdl-reader``
      - ``pip install ansys-dpf-core``
      - ``pip install ansys-dpf-reader``

      PyAEDT

      - ``pip install pyaedt``

      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
error: metadata-generation-failed

× Encountered error while generating package metadata.
╰─> See above for output.

note: This is an issue with the package mentioned above, not pip.
hint: See above for details.
</code>```

So I went ahead and installed all but one of those packages. I also installed cython. The only package that cannot be installed is ansys-dpf-reader and here is its error message

```<code>ERROR: Could not find a version that satisfies the requirement ansys-pdf-reader (from versions: none)
ERROR: No matching distribution found for ansys-pdf-reader
</code>```

What is going on?

答:
So it seems like 'ansys-dpf-reader' was changed to 'ansys-dpf-post' and the 'pyansys' is not a pacakge anymore, but has now expanded into these 5 packages. Installing all of them will allow the normal use of the old pyansys.

https://docs.pyansys.com/

Body:
I am on Pycharm and wish to install the pyansys package, but I keep getting this error:

Collecting pyansys
  Using cached pyansys-0.61.3.tar.gz (11 kB)
  Preparing metadata (setup.py) ... error
  error: subprocess-exited-with-error

  × python setup.py egg_info did not run successfully.
  │ exit code: 1
  ╰─> [21 lines of output]

      *** PyAnsys has moved (and expanded!) ***

      To use PyAnsys you need to install the applicable packages for your
      product:

      MAPDL:

      - ``pip install ansys-mapdl-core``

      MAPDL Post-Processing:

      - ``pip install ansys-mapdl-reader``
      - ``pip install ansys-dpf-core``
      - ``pip install ansys-dpf-reader``

      PyAEDT

      - ``pip install pyaedt``

      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
error: metadata-generation-failed

× Encountered error while generating package metadata.
╰─> See above for output.

note: This is an issue with the package mentioned above, not pip.
hint: See above for details.

So I went ahead and installed all but one of those packages. I also installed cython. The only package that cannot be installed is ansys-dpf-reader and here is its error message

ERROR: Could not find a version that satisfies the requirement ansys-pdf-reader (from versions: none)
ERROR: No matching distribution found for ansys-pdf-reader

What is going on?


答: URLSearchParams only accepts the actual query part in the constructor. You are including the full link.</p>

Title: How to Get 10 from this link (https://google.com/?ib=10)


问:
Change font size if the text exceeds the boundary of Textblock
I have a textblock with a dimension of Width=511, Height=159. FontSize=28. I want to change the font size if the text exceeds the dimension of the textblock so that all the text will be displayed. Is there a way of doing this? A formula maybe?</p>

答:
I'm not really sure about WPF, but in WinForms you could use MeasureString method, to measure strings dimensions in a given font. So, whenever the contents of the textblock changes, you just need to use this method and if the dimensions of the text are bigger then the dimensions of the text block - reduce the font size and measure again. </p>

<p>(now, after I've written this, I think there should be a simpler method for this)</p>

ContentLicense: CC BY-SA 3.0

Body:
I'm not really sure about WPF, but in WinForms you could use MeasureString method, to measure strings dimensions in a given font. So, whenever the contents of the textblock changes, you just need to use this method and if the dimensions of the text are bigger then the dimensions of the text block - reduce the font size and measure again.

(now, after I've written this, I think there should be a simpler method for this)


问:
Python logging: propagate messages of level below current logger level
I want to log messages of a specific logger name, of a certain level and higher (say INFO and up) to a specific log handler, say a file handler, while still getting all log messages to the console. Python is version 2.7.

What I tried until now was to create two loggers:

A root logger

A named logger

For the root logger, I attached a logging.StreamHandler, and set the log level to logging.DEBUG.

Then I attached a handler to the named logger and set level to logging.INFO for that logger.

When I now call my module, which uses the named logger, I do not get DEBUG logs propagated to the root logger any more.

Note: the extraLogger has a StreamHandler here to demonstrate the issue. In my production code I'd use a FileHandler

```<code>import logging

def do_logging(turn):
    logger = logging.getLogger('extra')
    logger.info('some info turn %d' % turn)
    logger.debug('this is debug fudge turn %d' % turn)

rootLogger = logging.getLogger()
handler = logging.StreamHandler()
rootFormatter = logging.Formatter('root - %(levelname)s: %(msg)s')
handler.setFormatter(rootFormatter)
rootLogger.addHandler(handler)
rootLogger.setLevel(logging.DEBUG)

do_logging(1)

extraLogger = logging.getLogger('extra')
extraHandler = logging.StreamHandler()
extraFormatter = logging.Formatter('extra - %(levelname)s: %(msg)s')
extraHandler.setFormatter(extraFormatter)
extraLogger.addHandler(extraHandler)
extraLogger.setLevel(logging.INFO)

do_logging(2)
</code>```

Actual Output:

```<code>root - INFO: some info turn 1
root - DEBUG: this is debug fudge turn 1
extra - INFO: some info turn 2
root - INFO: some info turn 2
</code>```

Output that I would like to have:

```<code>root - INFO: some info turn 1
root - DEBUG: this is debug fudge turn 1
extra - INFO: some info turn 2
root - INFO: some info turn 2
root - DEBUG: this is debug fudge turn 2
</code>```

I suspect that a custom Filter would be helpful in this case, but I do not know how...

答:
propagate

If this attribute evaluates to true, events logged to this
logger will be passed to the handlers of higher level (ancestor)
loggers, in addition to any handlers attached to this logger. Messages
are passed directly to the ancestor loggers’ handlers - neither the
level nor filters of the ancestor loggers in question are considered.

If this evaluates to false, logging messages are not passed to the
handlers of ancestor loggers.

please visit official python site for detailed discussion regarding this.

Diabling the propagate message

```<code>import logging

handler = logging.StreamHandler()

parent = logging.getLogger("parent")
parent.addHandler(handler)
child = logging.getLogger("parent.child")
child.propagate = False

child.setLevel(logging.DEBUG)
child.addHandler(handler)

child.info("HELLO")
</code>```

Output:

```<code>$ python3.10 propagate.py
HELLO
</code>```

Code without disabling the propagate message

```<code>import logging

handler = logging.StreamHandler()

parent = logging.getLogger("parent")
parent.addHandler(handler)
child = logging.getLogger("parent.child")
#child.propagate = False

child.setLevel(logging.DEBUG)
child.addHandler(handler)

child.info("HELLO")
</code>```

Output:

```<code>$ python3.10 propagate.py
HELLO
HELLO
</code>```

Body:
I want to log messages of a specific logger name, of a certain level and higher (say INFO and up) to a specific log handler, say a file handler, while still getting all log messages to the console. Python is version 2.7.

What I tried until now was to create two loggers:

A root logger

A named logger

For the root logger, I attached a logging.StreamHandler, and set the log level to logging.DEBUG.

Then I attached a handler to the named logger and set level to logging.INFO for that logger.

When I now call my module, which uses the named logger, I do not get DEBUG logs propagated to the root logger any more.

Note: the extraLogger has a StreamHandler here to demonstrate the issue. In my production code I'd use a FileHandler

import logging

def do_logging(turn):
    logger = logging.getLogger('extra')
    logger.info('some info turn %d' % turn)
    logger.debug('this is debug fudge turn %d' % turn)

rootLogger = logging.getLogger()
handler = logging.StreamHandler()
rootFormatter = logging.Formatter('root - %(levelname)s: %(msg)s')
handler.setFormatter(rootFormatter)
rootLogger.addHandler(handler)
rootLogger.setLevel(logging.DEBUG)

do_logging(1)

extraLogger = logging.getLogger('extra')
extraHandler = logging.StreamHandler()
extraFormatter = logging.Formatter('extra - %(levelname)s: %(msg)s')
extraHandler.setFormatter(extraFormatter)
extraLogger.addHandler(extraHandler)
extraLogger.setLevel(logging.INFO)

do_logging(2)

Actual Output:

root - INFO: some info turn 1
root - DEBUG: this is debug fudge turn 1
extra - INFO: some info turn 2
root - INFO: some info turn 2

Output that I would like to have:

root - INFO: some info turn 1
root - DEBUG: this is debug fudge turn 1
extra - INFO: some info turn 2
root - INFO: some info turn 2
root - DEBUG: this is debug fudge turn 2

I suspect that a custom Filter would be helpful in this case, but I do not know how...

Body:
propagate

If this attribute evaluates to true, events logged to this
logger will be passed to the handlers of higher level (ancestor)
loggers, in addition to any handlers attached to this logger. Messages
are passed directly to the ancestor loggers’ handlers - neither the
level nor filters of the ancestor loggers in question are considered.

If this evaluates to false, logging messages are not passed to the
handlers of ancestor loggers.

please visit official python site for detailed discussion regarding this.

Diabling the propagate message

import logging

handler = logging.StreamHandler()

parent = logging.getLogger("parent")
parent.addHandler(handler)
child = logging.getLogger("parent.child")
child.propagate = False

child.setLevel(logging.DEBUG)
child.addHandler(handler)

child.info("HELLO")

Output:

$ python3.10 propagate.py
HELLO

Code without disabling the propagate message

import logging

handler = logging.StreamHandler()

parent = logging.getLogger("parent")
parent.addHandler(handler)
child = logging.getLogger("parent.child")
#child.propagate = False

child.setLevel(logging.DEBUG)
child.addHandler(handler)

child.info("HELLO")

Output:

$ python3.10 propagate.py
HELLO
HELLO


问:
How to paginate collection without keys Laravel
I have an array of values with keys (like 0,1,2 etc). I need to paginate it and at result take collection of those values without keys.

At start I have array like this

```<code>array:11 [
  0 => {#829
    +"id": 2417
    +"date": "2019-12-24 15:05:04"
    +"eventName": "Atlas"
    +"gift_type": null
    +"count": 2
  }
  1 => {#872
    +"id": 2409
    +"date": "2019-08-22 19:00:00"
    +"eventName": "ДАХАБРАХА. ЗЕМЛЯ"
    +"gift_type": "to"
    +"count": 4
  }
]
</code>```

And after pagination I need to get this, and I get it at first page :

```<code>{
    "current_page": 1,
    "data": [
        {
            "id": 2417,
            "date": "2019-12-24 15:05:04",
            "eventName": "Atlas",
            "gift_type": null,
            "count": 2
        },
        {
            "id": 2409,
            "date": "2019-08-22 19:00:00",
            "eventName": "ДАХАБРАХА. ЗЕМЛЯ",
            "gift_type": "to",
            "count": 4
        }
    ],
    "first_page_url": "http://ticketsale/ajax/orders/77?page=1",
    "from": 1,
    "last_page": 4,
    "last_page_url": "http://ticketsale/ajax/orders/77?page=4",
    "next_page_url": "http://ticketsale/ajax/orders/77?page=2",
    "path": "http://ticketsale/ajax/orders/77",
    "per_page": 3,
    "prev_page_url": null,
    "to": 3,
    "total": 11
}
</code>```

But at second page I take values WITH keys:

```<code>{
    "current_page": 2,
    "data": {
        "3": {
            "id": 2404,
            "date": "2019-08-22 19:00:00",
            "eventName": "ДАХАБРАХА. ЗЕМЛЯ",
            "gift_type": "to",
            "count": 3
        },
        "4": {
            "id": 2400,
            "date": "2019-08-22 19:00:00",
            "eventName": "ДАХАБРАХА. ЗЕМЛЯ",
            "gift_type": "to",
            "count": 1
        }
    },
    "first_page_url": "http://ticketsale/ajax/orders/77?page=1",
    "from": 4,
    "last_page": 4,
</code>```

答:
I'm trying to fix it with the following.

```<code>public function paginate($items, $perPage, $page = null, $pageName = "page", $options = []) {
    $page = $page ?: (Paginator::resolveCurrentPage() ?: 1);
    $items = $items instanceof Collection ? $items : Collection::make($items);

    return new LengthAwarePaginator(array_values($items->forPage($page, $perPage)
        ->toArray()), $items->count(), $perPage, $page, $options);
}
</code>```

And:

```<code>$result = (new CollectionUtil())->paginate($model_query, 5);
</code>```

Body:
I have an array of values with keys (like 0,1,2 etc). I need to paginate it and at result take collection of those values without keys.

At start I have array like this

array:11 [
  0 => {#829
    +"id": 2417
    +"date": "2019-12-24 15:05:04"
    +"eventName": "Atlas"
    +"gift_type": null
    +"count": 2
  }
  1 => {#872
    +"id": 2409
    +"date": "2019-08-22 19:00:00"
    +"eventName": "ДАХАБРАХА. ЗЕМЛЯ"
    +"gift_type": "to"
    +"count": 4
  }
]

And after pagination I need to get this, and I get it at first page :

{
    "current_page": 1,
    "data": [
        {
            "id": 2417,
            "date": "2019-12-24 15:05:04",
            "eventName": "Atlas",
            "gift_type": null,
            "count": 2
        },
        {
            "id": 2409,
            "date": "2019-08-22 19:00:00",
            "eventName": "ДАХАБРАХА. ЗЕМЛЯ",
            "gift_type": "to",
            "count": 4
        }
    ],
    "first_page_url": "http://ticketsale/ajax/orders/77?page=1",
    "from": 1,
    "last_page": 4,
    "last_page_url": "http://ticketsale/ajax/orders/77?page=4",
    "next_page_url": "http://ticketsale/ajax/orders/77?page=2",
    "path": "http://ticketsale/ajax/orders/77",
    "per_page": 3,
    "prev_page_url": null,
    "to": 3,
    "total": 11
}

But at second page I take values WITH keys:

{
    "current_page": 2,
    "data": {
        "3": {
            "id": 2404,
            "date": "2019-08-22 19:00:00",
            "eventName": "ДАХАБРАХА. ЗЕМЛЯ",
            "gift_type": "to",
            "count": 3
        },
        "4": {
            "id": 2400,
            "date": "2019-08-22 19:00:00",
            "eventName": "ДАХАБРАХА. ЗЕМЛЯ",
            "gift_type": "to",
            "count": 1
        }
    },
    "first_page_url": "http://ticketsale/ajax/orders/77?page=1",
    "from": 4,
    "last_page": 4,

Body:
I'm trying to fix it with the following.

public function paginate($items, $perPage, $page = null, $pageName = "page", $options = []) {
    $page = $page ?: (Paginator::resolveCurrentPage() ?: 1);
    $items = $items instanceof Collection ? $items : Collection::make($items);

    return new LengthAwarePaginator(array_values($items->forPage($page, $perPage)
        ->toArray()), $items->count(), $perPage, $page, $options);
}

And:

$result = (new CollectionUtil())->paginate($model_query, 5);


答:
Edit: For a given link you can just supply the link in place of document.location (which directly fetches the pages current location)

Considering this as Vanilla JS. You can do the following.

```<code>let params = (new URL(document.location)).searchParams;

let ib = parseInt(params.get('ib')); // is the number 10
</code>```

Note, using the parseInt to get the value as a number.

Body:
Edit: For a given link you can just supply the link in place of document.location (which directly fetches the pages current location)

Considering this as Vanilla JS. You can do the following.

let params = (new URL(document.location)).searchParams;

let ib = parseInt(params.get('ib')); // is the number 10

Note, using the parseInt to get the value as a number.


问:
How to get into each element in a nested list and compare it with the equivalent in all elements in another list?
I need to get into each element in a nested list and compare it with the equivalent in all elements in another list.

I have two nested lists:

LB=

[[1, 0, 1, 0],

[1, 1, 1, 1],

[0, 0, 1, 0]]

LK=

[[1, 0, 1, 0],

[0, 0, 1, 1],

[1, 1, 1, 1],

[0, 0, 1, 0],

[1, 1, 0, 0],

[0, 0, 0, 0]
]

Analysis flow:

I take the first sublist from LK (i.e., [1, 0, 1, 0]) and compare its individual elements (i.e., 1, 0, 1, 0) with subsequent elements from the sublists LB [1, 0, 1, 0], [1, 1, 1, 1], and [0, 0, 1, 0].
I then take the second sublist from LK (i.e., [0, 0, 1, 1]) and compare its individual elements (i.e., 0, 0, 1, 1) with the subsequent elements from the LB sublist [1, 0, 1, 0], [1, 1, 1, 1, 1], and [0, 0, 1, 0]
I then take the third sublist from LK (i.e., [1, 1, 1, 1]) and compare its individual elements (i.e., 1, 1, 1, 1) with the subsequent elements from the LB sublist [1, 0, 1, 0], [1, 1, 1, 1, 1], and [0, 0, 1, 0]

Here is my attempt at the code, but I know it doesn't work properly and doesn't contain all the conditions.

```<code>for i in LK, LB:
    for j in i:
        while j < (len(LK)-1):
            if j == 0:
                j += 1
            elif j != 0:
                i += 1
            else:
                print(LB[i])
</code>```

Additional conditions:

if a given element in a list in LK is equal to 0 and the digit at the same position in LB is also equal to 0 then proceed to compare the next digit in the given list. When you get to the end of the sublist in the LK list, i.e. you pass [1, 0, 1, 0] and the condition with zeroes is fulfilled, write me this element from the LB list

if given element in the list in LK is equal 0, but digit in the same position in the list LB is not equal 0 then skip this case and check another sublist from LB

if there is no element 0 in the list LK (list [1, 1, 1, 1]) then write a sublist from LB

We perform such an iteration for all the elements in the list LB comparing them with the sublists from LK.

In the analyzed example during the comparison:

the first sublist from LK ([1, 0, 1, 0]) => should be extracted from the list LB: [1, 0, 1, 0] and [0, 0, 1, 0]

the second sublist from LK ([0, 0, 1, 1]) => should be printed from the list LB: [0, 0, 1, 0]

the third sublist from LK ([1, 1, 1, 1, 1]) => should be printed from the lists LB: [1, 0, 1, 0], [1, 1, 1, 1] and [0, 0, 1, 0]

the fourth sublist from LK ([0, 0, 1, 0]) => should be printed from the list LB: [0, 0, 1, 0]

the fifth sublist from LK ([1, 1, 0, 0]) => no element should be written out from the list LB

sixth sublist from LK ([0, 0, 0, 0]) => no element should be written out from the list LB

Output:
Displayed LB sublists that meet the conditions (LB sublists can be displayed in several sectors)

答:
This is ugly but it works.   Saw no good way to code your matching conditions.

Iterate though LK,  for each LK iterate through LB.   print if the list "match"

```<code>LB=[[1, 0, 1, 0],
[1, 1, 1, 1],
[0, 0, 1, 0]]

LK=[[1, 0, 1, 0],
[0, 0, 1, 1],
[1, 1, 1, 1],
[0, 0, 1, 0],
[1, 1, 0, 0],
[0, 0, 0, 0] ]

def mch(str1,str2):
    x=0
    while x+1 < len(str1)
        if str1[x] == 0:
            if not str2[x]  == 0:  # 0 not in both strings
                 return False
            if x < (len(str1)-1):  #if both strins are 0 possible match only
                                   # if strings match at next position
                                   # only do check if there is a next position
                if str1[x+1] == str2[x+1]:
                    x+=1
                else:
                    return False
        x+=1
    return True

for str1 in LK:
    print("\n\n","Matches for ", str1, "\n")
    for str2 in LB:
        if mch(str1,str2)
             print(str2)
</code>```

Body:
I need to get into each element in a nested list and compare it with the equivalent in all elements in another list.

I have two nested lists:

LB=

[[1, 0, 1, 0],

[1, 1, 1, 1],

[0, 0, 1, 0]]

LK=

[[1, 0, 1, 0],

[0, 0, 1, 1],

[1, 1, 1, 1],

[0, 0, 1, 0],

[1, 1, 0, 0],

[0, 0, 0, 0]
]

Analysis flow:

I take the first sublist from LK (i.e., [1, 0, 1, 0]) and compare its individual elements (i.e., 1, 0, 1, 0) with subsequent elements from the sublists LB [1, 0, 1, 0], [1, 1, 1, 1], and [0, 0, 1, 0].
I then take the second sublist from LK (i.e., [0, 0, 1, 1]) and compare its individual elements (i.e., 0, 0, 1, 1) with the subsequent elements from the LB sublist [1, 0, 1, 0], [1, 1, 1, 1, 1], and [0, 0, 1, 0]
I then take the third sublist from LK (i.e., [1, 1, 1, 1]) and compare its individual elements (i.e., 1, 1, 1, 1) with the subsequent elements from the LB sublist [1, 0, 1, 0], [1, 1, 1, 1, 1], and [0, 0, 1, 0]

Here is my attempt at the code, but I know it doesn't work properly and doesn't contain all the conditions.

for i in LK, LB:
    for j in i:
        while j < (len(LK)-1):
            if j == 0:
                j += 1
            elif j != 0:
                i += 1
            else:
                print(LB[i])

Additional conditions:

if a given element in a list in LK is equal to 0 and the digit at the same position in LB is also equal to 0 then proceed to compare the next digit in the given list. When you get to the end of the sublist in the LK list, i.e. you pass [1, 0, 1, 0] and the condition with zeroes is fulfilled, write me this element from the LB list

if given element in the list in LK is equal 0, but digit in the same position in the list LB is not equal 0 then skip this case and check another sublist from LB

if there is no element 0 in the list LK (list [1, 1, 1, 1]) then write a sublist from LB

We perform such an iteration for all the elements in the list LB comparing them with the sublists from LK.

In the analyzed example during the comparison:

the first sublist from LK ([1, 0, 1, 0]) => should be extracted from the list LB: [1, 0, 1, 0] and [0, 0, 1, 0]

the second sublist from LK ([0, 0, 1, 1]) => should be printed from the list LB: [0, 0, 1, 0]

the third sublist from LK ([1, 1, 1, 1, 1]) => should be printed from the lists LB: [1, 0, 1, 0], [1, 1, 1, 1] and [0, 0, 1, 0]

the fourth sublist from LK ([0, 0, 1, 0]) => should be printed from the list LB: [0, 0, 1, 0]

the fifth sublist from LK ([1, 1, 0, 0]) => no element should be written out from the list LB

sixth sublist from LK ([0, 0, 0, 0]) => no element should be written out from the list LB

Output:
Displayed LB sublists that meet the conditions (LB sublists can be displayed in several sectors)

Body:
This is ugly but it works.   Saw no good way to code your matching conditions.

Iterate though LK,  for each LK iterate through LB.   print if the list "match"

LB=[[1, 0, 1, 0],
[1, 1, 1, 1],
[0, 0, 1, 0]]

LK=[[1, 0, 1, 0],
[0, 0, 1, 1],
[1, 1, 1, 1],
[0, 0, 1, 0],
[1, 1, 0, 0],
[0, 0, 0, 0] ]

def mch(str1,str2):
    x=0
    while x+1 < len(str1)
        if str1[x] == 0:
            if not str2[x]  == 0:  # 0 not in both strings
                 return False
            if x < (len(str1)-1):  #if both strins are 0 possible match only
                                   # if strings match at next position
                                   # only do check if there is a next position
                if str1[x+1] == str2[x+1]:
                    x+=1
                else:
                    return False
        x+=1
    return True

for str1 in LK:
    print("\n\n","Matches for ", str1, "\n")
    for str2 in LB:
        if mch(str1,str2)
             print(str2)


问:
Change color of matplotlib plt.text based on value
I'm playing with the slider demo (https://matplotlib.org/stable/gallery/widgets/slider_demo.html) and decided to add text to the plot with plt.text, as follows;

```<code>freqtext = plt.text(-5, 22, r'$\nu = %.2f$' % freq_slider.val)
</code>```

I then changed the text value based on freq_slider.val as follows

```<code>freqtext.set_text(r'$\nu = %.2f$' % freq_slider.val)
</code>```

If the value of freq_slider.val is greater than some value, say 10, I would like for the text to change color to red.  I know I can set its value with

```<code>freqtext = plt.text(-5, 22, r'$\nu = %.2f$' % freq_slider.val, color = 'r')
</code>```

However, what I am trying to do is dynamically change the color (or other font parameters) based on its value.  The entire code is below. Note that the only changes are the two described above.

Thanks in advance.

```<code>import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider, Button

# The parametrized function to be plotted
def f(t, amplitude, frequency):
    return amplitude * np.sin(2 * np.pi * frequency * t)

t = np.linspace(0, 1, 1000)

# Define initial parameters
init_amplitude = 5
init_frequency = 3

# Create the figure and the line that we will manipulate
fig, ax = plt.subplots()
line, = plt.plot(t, f(t, init_amplitude, init_frequency), lw=2)
ax.set_xlabel('Time [s]')

# adjust the main plot to make room for the sliders
plt.subplots_adjust(left=0.25, bottom=0.25)

# Make a horizontal slider to control the frequency.
axfreq = plt.axes([0.25, 0.1, 0.65, 0.03])
freq_slider = Slider(
    ax=axfreq,
    label='Frequency [Hz]',
    valmin=0.1,
    valmax=30,
    valinit=init_frequency,
)

# Make a vertically oriented slider to control the amplitude
axamp = plt.axes([0.1, 0.25, 0.0225, 0.63])
amp_slider = Slider(
    ax=axamp,
    label="Amplitude",
    valmin=0,
    valmax=10,
    valinit=init_amplitude,
    orientation="vertical"
)

# The function to be called anytime a slider's value changes
def update(val):
    line.set_ydata(f(t, amp_slider.val, freq_slider.val))
    fig.canvas.draw_idle()
    # make text red if freq_slider.val > 10
    freqtext.set_text(r'$\nu = %.2f$' % freq_slider.val)

# register the update function with each slider
freq_slider.on_changed(update)
amp_slider.on_changed(update)

# Create a `matplotlib.widgets.Button` to reset the sliders to initial values.
resetax = plt.axes([0.8, 0.025, 0.1, 0.04])
button = Button(resetax, 'Reset', hovercolor='0.975')

freqtext = plt.text(-5, 22, r'$\nu = %.2f$' % freq_slider.val, color='r')

def reset(event):
    freq_slider.reset()
    amp_slider.reset()
button.on_clicked(reset)

plt.show()
</code>```

答:
I've rarely used matplotlib's event system, but I set the initial text setting as empty, and update the text and text color in the update function. At that time, I add a numeric judgment of 10 or more.

```<code>import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider, Button
%matplotlib widget

# The parametrized function to be plotted
def f(t, amplitude, frequency):
    return amplitude * np.sin(2 * np.pi * frequency * t)

t = np.linspace(0, 1, 1000)

# Define initial parameters
init_amplitude = 5
init_frequency = 3

# Create the figure and the line that we will manipulate
fig, ax = plt.subplots()
line, = plt.plot(t, f(t, init_amplitude, init_frequency), lw=2)
ax.set_xlabel('Time [s]')
# freqtext = ax.text(-5, 22, []) # update

# adjust the main plot to make room for the sliders
plt.subplots_adjust(left=0.25, bottom=0.25)

# Make a horizontal slider to control the frequency.
axfreq = plt.axes([0.25, 0.1, 0.65, 0.03])
freq_slider = Slider(
    ax=axfreq,
    label='Frequency [Hz]',
    valmin=0.1,
    valmax=30,
    valinit=init_frequency,
)

# Make a vertically oriented slider to control the amplitude
axamp = plt.axes([0.1, 0.25, 0.0225, 0.63])
amp_slider = Slider(
    ax=axamp,
    label="Amplitude",
    valmin=0,
    valmax=10,
    valinit=init_amplitude,
    orientation="vertical"
)

# The function to be called anytime a slider's value changes
def update(val):
    line.set_ydata(f(t, amp_slider.val, freq_slider.val))
    fig.canvas.draw_idle()
    # make text red if freq_slider.val > 10
    c = 'r' if freq_slider.val > 10 else 'k'
    freqtext.set_text(r'$\nu = %.2f$' % freq_slider.val)
    freqtext.set_color(c)

# register the update function with each slider
freq_slider.on_changed(update)
amp_slider.on_changed(update)

# Create a `matplotlib.widgets.Button` to reset the sliders to initial values.
resetax = plt.axes([0.8, 0.025, 0.1, 0.04])
button = Button(resetax, 'Reset', hovercolor='0.975')

#freqtext = plt.text(-5, 22, r'$\nu = %.2f$' % freq_slider.val)
freqtext = plt.text(-5, 22, '')

def reset(event):
    freq_slider.reset()
    amp_slider.reset()
button.on_clicked(reset)

plt.show()
</code>```

Body:
I'm playing with the slider demo (https://matplotlib.org/stable/gallery/widgets/slider_demo.html) and decided to add text to the plot with plt.text, as follows;

freqtext = plt.text(-5, 22, r'$\nu = %.2f$' % freq_slider.val)

I then changed the text value based on freq_slider.val as follows

freqtext.set_text(r'$\nu = %.2f$' % freq_slider.val)

If the value of freq_slider.val is greater than some value, say 10, I would like for the text to change color to red.  I know I can set its value with

freqtext = plt.text(-5, 22, r'$\nu = %.2f$' % freq_slider.val, color = 'r')

However, what I am trying to do is dynamically change the color (or other font parameters) based on its value.  The entire code is below. Note that the only changes are the two described above.

Thanks in advance.

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider, Button

# The parametrized function to be plotted
def f(t, amplitude, frequency):
    return amplitude * np.sin(2 * np.pi * frequency * t)

t = np.linspace(0, 1, 1000)

# Define initial parameters
init_amplitude = 5
init_frequency = 3

# Create the figure and the line that we will manipulate
fig, ax = plt.subplots()
line, = plt.plot(t, f(t, init_amplitude, init_frequency), lw=2)
ax.set_xlabel('Time [s]')

# adjust the main plot to make room for the sliders
plt.subplots_adjust(left=0.25, bottom=0.25)

# Make a horizontal slider to control the frequency.
axfreq = plt.axes([0.25, 0.1, 0.65, 0.03])
freq_slider = Slider(
    ax=axfreq,
    label='Frequency [Hz]',
    valmin=0.1,
    valmax=30,
    valinit=init_frequency,
)

# Make a vertically oriented slider to control the amplitude
axamp = plt.axes([0.1, 0.25, 0.0225, 0.63])
amp_slider = Slider(
    ax=axamp,
    label="Amplitude",
    valmin=0,
    valmax=10,
    valinit=init_amplitude,
    orientation="vertical"
)

# The function to be called anytime a slider's value changes
def update(val):
    line.set_ydata(f(t, amp_slider.val, freq_slider.val))
    fig.canvas.draw_idle()
    # make text red if freq_slider.val > 10
    freqtext.set_text(r'$\nu = %.2f$' % freq_slider.val)

# register the update function with each slider
freq_slider.on_changed(update)
amp_slider.on_changed(update)

# Create a `matplotlib.widgets.Button` to reset the sliders to initial values.
resetax = plt.axes([0.8, 0.025, 0.1, 0.04])
button = Button(resetax, 'Reset', hovercolor='0.975')

freqtext = plt.text(-5, 22, r'$\nu = %.2f$' % freq_slider.val, color='r')

def reset(event):
    freq_slider.reset()
    amp_slider.reset()
button.on_clicked(reset)

plt.show()

Body:
I've rarely used matplotlib's event system, but I set the initial text setting as empty, and update the text and text color in the update function. At that time, I add a numeric judgment of 10 or more.

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider, Button
%matplotlib widget

# The parametrized function to be plotted
def f(t, amplitude, frequency):
    return amplitude * np.sin(2 * np.pi * frequency * t)

t = np.linspace(0, 1, 1000)

# Define initial parameters
init_amplitude = 5
init_frequency = 3

# Create the figure and the line that we will manipulate
fig, ax = plt.subplots()
line, = plt.plot(t, f(t, init_amplitude, init_frequency), lw=2)
ax.set_xlabel('Time [s]')
# freqtext = ax.text(-5, 22, []) # update

# adjust the main plot to make room for the sliders
plt.subplots_adjust(left=0.25, bottom=0.25)

# Make a horizontal slider to control the frequency.
axfreq = plt.axes([0.25, 0.1, 0.65, 0.03])
freq_slider = Slider(
    ax=axfreq,
    label='Frequency [Hz]',
    valmin=0.1,
    valmax=30,
    valinit=init_frequency,
)

# Make a vertically oriented slider to control the amplitude
axamp = plt.axes([0.1, 0.25, 0.0225, 0.63])
amp_slider = Slider(
    ax=axamp,
    label="Amplitude",
    valmin=0,
    valmax=10,
    valinit=init_amplitude,
    orientation="vertical"
)

# The function to be called anytime a slider's value changes
def update(val):
    line.set_ydata(f(t, amp_slider.val, freq_slider.val))
    fig.canvas.draw_idle()
    # make text red if freq_slider.val > 10
    c = 'r' if freq_slider.val > 10 else 'k'
    freqtext.set_text(r'$\nu = %.2f$' % freq_slider.val)
    freqtext.set_color(c)

# register the update function with each slider
freq_slider.on_changed(update)
amp_slider.on_changed(update)

# Create a `matplotlib.widgets.Button` to reset the sliders to initial values.
resetax = plt.axes([0.8, 0.025, 0.1, 0.04])
button = Button(resetax, 'Reset', hovercolor='0.975')

#freqtext = plt.text(-5, 22, r'$\nu = %.2f$' % freq_slider.val)
freqtext = plt.text(-5, 22, '')

def reset(event):
    freq_slider.reset()
    amp_slider.reset()
button.on_clicked(reset)

plt.show()


问:
Finding all disconnected subgraphs in a graph
I have a graph which contains an unknown number of disconnected subgraphs. What's a good algorithm (or Java library) to find them all?</p>

答:
I probably should have found a standard algorithm (Wikipedia has some suggestions), but I came up with this on my own and it worked well for my purposes. My C# implementation takes a couple seconds to process a graph with 40,000 nodes and 44,000 edges to find 160 subgraphs and 20,000 unconnected nodes. I used a HashSet to store each subgraph group, so testing group membership is approximately O(1), and the overall algorithm becomes O(E*C) where E is the number of edges and C is the number of connected components in the graph. Wikipedia mentions an O(N) algorithm, linear in the number of nodes, so I'm sure mine is not maximally efficient, but it was plenty fast for my application. (Edit: I'm also glossing over the cost of merging groups, so don't put too much weight on my complexity analysis.)

Logic:

```<code>For each edge A->B
  If A is in a group and B is not, add B to group A
  If A is not in a group and B is, add A to group B
  If A and B are in different groups, merge the groups
  If neither A or B is in a group, create new group containing A and B
</code>```

Pseudocode:

```<code>graph = {nodes, edges}
groups = {}
foreach edge A->B in graph.edges:
    groupA = findgroup(A)
    groupB = findgroup(B)
    if (groupA && !groupB)
        groupA.add(B)
    elif (!groupA && groupB)
        groupB.add(A)
    elif (groupA && groupB)
        if (groupA != groupB)
            groupA.union(groupB)
            groups.delete(groupB)
    else
        groups.add({A,B})
</code>```
```<code>findgroup(node):
    for group in groups:
        if group.contains(node):
            return group
    return null
</code>```

Note that this won't capture any nodes that aren't involved in edges. For my particular purposes this was fine. If you want to get all the single-node groups you can do a final pass:

```<code>foreach node in graph.nodes:
    group = findgroup(node)
    if !group:
        groups.add({node})
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I probably should have found a standard algorithm (Wikipedia has some suggestions), but I came up with this on my own and it worked well for my purposes. My C# implementation takes a couple seconds to process a graph with 40,000 nodes and 44,000 edges to find 160 subgraphs and 20,000 unconnected nodes. I used a HashSet to store each subgraph group, so testing group membership is approximately O(1), and the overall algorithm becomes O(E*C) where E is the number of edges and C is the number of connected components in the graph. Wikipedia mentions an O(N) algorithm, linear in the number of nodes, so I'm sure mine is not maximally efficient, but it was plenty fast for my application. (Edit: I'm also glossing over the cost of merging groups, so don't put too much weight on my complexity analysis.)

Logic:

For each edge A->B
  If A is in a group and B is not, add B to group A
  If A is not in a group and B is, add A to group B
  If A and B are in different groups, merge the groups
  If neither A or B is in a group, create new group containing A and B

Pseudocode:

graph = {nodes, edges}
groups = {}
foreach edge A->B in graph.edges:
    groupA = findgroup(A)
    groupB = findgroup(B)
    if (groupA && !groupB)
        groupA.add(B)
    elif (!groupA && groupB)
        groupB.add(A)
    elif (groupA && groupB)
        if (groupA != groupB)
            groupA.union(groupB)
            groups.delete(groupB)
    else
        groups.add({A,B})

findgroup(node):
    for group in groups:
        if group.contains(node):
            return group
    return null

Note that this won't capture any nodes that aren't involved in edges. For my particular purposes this was fine. If you want to get all the single-node groups you can do a final pass:

foreach node in graph.nodes:
    group = findgroup(node)
    if !group:
        groups.add({node})


问:
Getting 400 Bad Request error with Python Socket GET request
for a school assignment I need to send GET requests and receive the data using only sockets. I keep getting an HTTP/1.1 400 Bad Request error, no matter how I try to format the GET request.

Here is my code(please excuse me if it's terrible, this is my first ever python project):

```<code>import socket
import sys

try:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    print ("Creation successful")
except socket.error as err:
    print ("Creation unsuccessful. Error: %s" %(err))

port = 80

try:
    ip = socket.gethostbyname('gaia.cs.umass.edu')
except socket.gaierror:
    print("Error resolving host")
    sys.exit()

s.connect((ip, port))

print("Connection successful")
print("Connected to %s" %(ip))

try:
    s.sendall("GET wireshark-labs/HTTP-ethereal-lab-file3.html HTTP/1.1\r\nHost: gaia.cs.umass.edu\r\n\r\n".encode())
    while True:
        data = s.recv(1024)
        print("Data received")
        print(data.decode('UTF-8'))
        if not data:
            print("No Data")
            s.close()
            break
except socket.gaierror:
    print("Error sending data")
    sys.exit()
</code>```

And this is the error I receive:

```<code>HTTP/1.1 400 Bad Request

Date: Mon, 23 Nov 2020 07:04:03 GMT

Server: Apache/2.4.6 (CentOS) OpenSSL/1.0.2k-fips PHP/7.4.12 mod_perl/2.0.11 Perl/v5.16.3

Content-Length: 226

Connection: close

Content-Type: text/html; charset=iso-8859-1

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>400 Bad Request</title>
</head><body>
<h1>Bad Request</h1>
<p>Your browser sent a request that this server could not understand.<br />
</p>
</body></html>
</code>```

Trying to get this GET request to work is driving me insane, thanks in advance for any help you all send my way.

答:
This might help somebody, i had the same issue with the 400 Bad Request.
I looked at the answer of Abhishek Rai (Thank you!) above and i realized my http request had only the newline escapes \n and lacked the \r carriage return escape, when i changed all the \n for \r\n my issue was fixed.</p>

Body:
for a school assignment I need to send GET requests and receive the data using only sockets. I keep getting an HTTP/1.1 400 Bad Request error, no matter how I try to format the GET request.

Here is my code(please excuse me if it's terrible, this is my first ever python project):

import socket
import sys

try:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    print ("Creation successful")
except socket.error as err:
    print ("Creation unsuccessful. Error: %s" %(err))

port = 80

try:
    ip = socket.gethostbyname('gaia.cs.umass.edu')
except socket.gaierror:
    print("Error resolving host")
    sys.exit()

s.connect((ip, port))

print("Connection successful")
print("Connected to %s" %(ip))

try:
    s.sendall("GET wireshark-labs/HTTP-ethereal-lab-file3.html HTTP/1.1\r\nHost: gaia.cs.umass.edu\r\n\r\n".encode())
    while True:
        data = s.recv(1024)
        print("Data received")
        print(data.decode('UTF-8'))
        if not data:
            print("No Data")
            s.close()
            break
except socket.gaierror:
    print("Error sending data")
    sys.exit()

And this is the error I receive:

HTTP/1.1 400 Bad Request

Date: Mon, 23 Nov 2020 07:04:03 GMT

Server: Apache/2.4.6 (CentOS) OpenSSL/1.0.2k-fips PHP/7.4.12 mod_perl/2.0.11 Perl/v5.16.3

Content-Length: 226

Connection: close

Content-Type: text/html; charset=iso-8859-1

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">

<title>400 Bad Request</title>

Bad Request

Your browser sent a request that this server could not understand.

Trying to get this GET request to work is driving me insane, thanks in advance for any help you all send my way.


问:
I have select element on my page with 3 options. I need to show a different form below the select input when selected. How can I do it using PHP?
For example I have 3 choices in select input:
I can select Fruit, Furniture or Movie.

When I select one of them, the form needs to show up below.

For every choice there need to be a different form.

Can anyone help me, how to make it work?

I know how to create forms and everything, but I don't know how they can be changed when the value of select is changed.

I am doing a project using HTML, CSS, JS and PHP.

答:
function myFunction(val) {

    if(val==""){
    document.getElementById("dynamic_part").innerHTML="
Please pick up any thing!!
";
    return;
    }

    const obj = {
      frutas : "Fruit stuff<input type='text' value='Input the fruit    things'>
Fruit stuff<input type='text' value='Input the fruit    things'>",
      moveis: "Movie stuff<input type='text' value='Input the movie    things'>",
      filmes: "Films stuff<input type='text' value='Input the films    things'>
Films stuff<input type='text' value='Input the films    things'>"
    };

    document.getElementById("dynamic_part").innerHTML=obj[val];

}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>input,select{
  height:40px;
  margin:10px;
}</code>```

<form action="">
    Select something
    <select name="" id="" onchange="myFunction(this.value)">
        <option value="">--selection--</option>
        <option value="frutas">Frutas</option>
        <option value="moveis">Móveis</option>
        <option value="filmes">Filmes</option>
    </select>

Please pick up any thing!!

</form>```

Body:
function myFunction(val) {

    if(val==""){
    document.getElementById("dynamic_part").innerHTML="<p>Please pick up any thing!!</p>";
    return;
    }

    const obj = {
      frutas : "<label>Fruit stuff</label><input type='text' value='Input the fruit    things'><br><label>Fruit stuff</label><input type='text' value='Input the fruit    things'>",
      moveis: "<label>Movie stuff</label><input type='text' value='Input the movie    things'>",
      filmes: "<label>Films stuff</label><input type='text' value='Input the films    things'><br><label>Films stuff</label><input type='text' value='Input the films    things'>"
    };

    document.getElementById("dynamic_part").innerHTML=obj[val];

}

input,select{
  height:40px;
  margin:10px;
}

<form action="">
    Select something
    <select name="" id="" onchange="myFunction(this.value)">
        <option value="">--selection--</option>
        <option value="frutas">Frutas</option>
        <option value="moveis">Móveis</option>
        <option value="filmes">Filmes</option>
    </select>

    <div id="dynamic_part">
        <p>Please pick up any thing!!</p>
    </div>

</form>


问:
Quasar app, missing some modules after npm install
I created a quasar app with quasar create, then verified it works with quasar dev. Everything was fine.

But I wanted to upload the code to github to collaborate with other. So I created a repo and uploaded everything except node_modules and package-lock.json.

I then deleted my local repo and cloned the github repo to verify it was working correctly for others as well. I ran npm install, no error, and then quasar dev.

And here is my output :

node:internal/modules/cjs/loader:933
  const err = new Error(message);
              ^

[  Error: Cannot find module '/home/th3g3ntl3man/github/xtreme-sports-app/.postcssrc.js'
  Require stack:
  - /home/th3g3ntl3man/github/xtreme-sports-app/node_modules/@quasar/app/lib/webpack/inject.style-rules.js
  - /home/th3g3ntl3man/github/xtreme-sports-app/node_modules/@quasar/app/lib/webpack/create-chain.js
  - /home/th3g3ntl3man/github/xtreme-sports-app/node_modules/@quasar/app/lib/webpack/index.js
  - /home/th3g3ntl3man/github/xtreme-sports-app/node_modules/@quasar/app/lib/quasar-conf-file.js
  - /home/th3g3ntl3man/github/xtreme-sports-app/node_modules/@quasar/app/bin/quasar-dev
  - /home/th3g3ntl3man/github/xtreme-sports-app/node_modules/@quasar/app/bin/quasar
  - /usr/lib/node_modules/@quasar/cli/bin/quasar

  - loader:933 Function.Module._resolveFilename
    node:internal/modules/cjs/loader:933:15

  - loader:778 Function.Module._load
    node:internal/modules/cjs/loader:778:27

  - loader:999 Module.require
    node:internal/modules/cjs/loader:999:19

  - helpers:102 require
    node:internal/modules/cjs/helpers:102:18

  - inject.style-rules.js:117 create
    [xtreme-sports-app]/[@quasar]/app/lib/webpack/inject.style-rules.js:117:27

  - inject.style-rules.js:41 injectRule
    [xtreme-sports-app]/[@quasar]/app/lib/webpack/inject.style-rules.js:41:3

  - inject.style-rules.js:178 module.exports
    [xtreme-sports-app]/[@quasar]/app/lib/webpack/inject.style-rules.js:178:3

  - create-chain.js:241 module.exports
    [xtreme-sports-app]/[@quasar]/app/lib/webpack/create-chain.js:241:3

  - index.js:62 getSPA
    [xtreme-sports-app]/[@quasar]/app/lib/webpack/index.js:62:17

  - index.js:229 module.exports
    [xtreme-sports-app]/[@quasar]/app/lib/webpack/index.js:229:18

] {
  code: 'MODULE_NOT_FOUND',
  requireStack: [
    '/home/th3g3ntl3man/github/xtreme-sports-app/node_modules/@quasar/app/lib/webpack/inject.style-rules.js',
    '/home/th3g3ntl3man/github/xtreme-sports-app/node_modules/@quasar/app/lib/webpack/create-chain.js',
    '/home/th3g3ntl3man/github/xtreme-sports-app/node_modules/@quasar/app/lib/webpack/index.js',
    '/home/th3g3ntl3man/github/xtreme-sports-app/node_modules/@quasar/app/lib/quasar-conf-file.js',
    '/home/th3g3ntl3man/github/xtreme-sports-app/node_modules/@quasar/app/bin/quasar-dev',
    '/home/th3g3ntl3man/github/xtreme-sports-app/node_modules/@quasar/app/bin/quasar',
    '/usr/lib/node_modules/@quasar/cli/bin/quasar'
  ]
}

Node.js v17.1.0```

I'm not sure if I did everything correctly but I can't find any answer about my issue...

答: For me it's working after deleting yarn.lock and reinstall dependencies</p>

Body:
I created a quasar app with quasar create, then verified it works with quasar dev. Everything was fine.

But I wanted to upload the code to github to collaborate with other. So I created a repo and uploaded everything except node_modules and package-lock.json.

I then deleted my local repo and cloned the github repo to verify it was working correctly for others as well. I ran npm install, no error, and then quasar dev.

And here is my output :

node:internal/modules/cjs/loader:933
  const err = new Error(message);
              ^

[  Error: Cannot find module '/home/th3g3ntl3man/github/xtreme-sports-app/.postcssrc.js'
  Require stack:
  - /home/th3g3ntl3man/github/xtreme-sports-app/node_modules/@quasar/app/lib/webpack/inject.style-rules.js
  - /home/th3g3ntl3man/github/xtreme-sports-app/node_modules/@quasar/app/lib/webpack/create-chain.js
  - /home/th3g3ntl3man/github/xtreme-sports-app/node_modules/@quasar/app/lib/webpack/index.js
  - /home/th3g3ntl3man/github/xtreme-sports-app/node_modules/@quasar/app/lib/quasar-conf-file.js
  - /home/th3g3ntl3man/github/xtreme-sports-app/node_modules/@quasar/app/bin/quasar-dev
  - /home/th3g3ntl3man/github/xtreme-sports-app/node_modules/@quasar/app/bin/quasar
  - /usr/lib/node_modules/@quasar/cli/bin/quasar

  - loader:933 Function.Module._resolveFilename
    node:internal/modules/cjs/loader:933:15

  - loader:778 Function.Module._load
    node:internal/modules/cjs/loader:778:27

  - loader:999 Module.require
    node:internal/modules/cjs/loader:999:19

  - helpers:102 require
    node:internal/modules/cjs/helpers:102:18

  - inject.style-rules.js:117 create
    [xtreme-sports-app]/[@quasar]/app/lib/webpack/inject.style-rules.js:117:27

  - inject.style-rules.js:41 injectRule
    [xtreme-sports-app]/[@quasar]/app/lib/webpack/inject.style-rules.js:41:3

  - inject.style-rules.js:178 module.exports
    [xtreme-sports-app]/[@quasar]/app/lib/webpack/inject.style-rules.js:178:3

  - create-chain.js:241 module.exports
    [xtreme-sports-app]/[@quasar]/app/lib/webpack/create-chain.js:241:3

  - index.js:62 getSPA
    [xtreme-sports-app]/[@quasar]/app/lib/webpack/index.js:62:17

  - index.js:229 module.exports
    [xtreme-sports-app]/[@quasar]/app/lib/webpack/index.js:229:18

] {
  code: 'MODULE_NOT_FOUND',
  requireStack: [
    '/home/th3g3ntl3man/github/xtreme-sports-app/node_modules/@quasar/app/lib/webpack/inject.style-rules.js',
    '/home/th3g3ntl3man/github/xtreme-sports-app/node_modules/@quasar/app/lib/webpack/create-chain.js',
    '/home/th3g3ntl3man/github/xtreme-sports-app/node_modules/@quasar/app/lib/webpack/index.js',
    '/home/th3g3ntl3man/github/xtreme-sports-app/node_modules/@quasar/app/lib/quasar-conf-file.js',
    '/home/th3g3ntl3man/github/xtreme-sports-app/node_modules/@quasar/app/bin/quasar-dev',
    '/home/th3g3ntl3man/github/xtreme-sports-app/node_modules/@quasar/app/bin/quasar',
    '/usr/lib/node_modules/@quasar/cli/bin/quasar'
  ]
}

Node.js v17.1.0

I'm not sure if I did everything correctly but I can't find any answer about my issue...


问:
Can I selectively (force) inline a function?
In the book Clean Code (and a couple of others I have come across and read) it is suggested to keep the functions small and break them up if they become large. It also suggests that functions should do one thing and one thing only.

In Optimizing software in C++ Agner Fog states that he does not like the rule of breaking up a function just because it crosses a certain threshold of a number of lines. He states that this results in unnecessary jumps which degrade performance.

First off, I understand that it will not matter if the code I am working on is not in a tight loop and that the functions are heavy so that the time it takes to call them is dwarfed by the time the code in the function takes to execute. But let's assume that I am working with functions that are, most of the time, used by other objects/functions and are performing relatively trivial tasks. These functions follow the suggestions listed in the first paragraph (that is, perform one single function and are small/comprehensible). Then I start programming a performance critical function that utilizes these other functions in a tight loop and is essentially a frame function. Lastly, assume that in-lining them has a benefit for the performance critical function but no benefit whatsoever to any other function (yes, I have profiled this, albeit with a lot of copying and pasting which I want to avoid).

Immediately, one can say that tag the function inline and let the compiler choose. But what if I don't want all those functions to be in a `.inl file or exposed in the header? In my current situation, the performance critical functions and the other functions it uses are all in the same source file.

To sum it up, can I selectively (force) inline a function(s) for a single function so that the end code behaves like it is one big function instead of several calls to other functions.

答:
You cannot force the inline. Also, function calls are pretty cheap on modern CPUs, compared to the cost of the work done. If your functions are large enough to need to be broken down, the additional time taken to do the call will be essentially nothing.

Failing that, you could ... try ... to use a macro.


问:
What's the difference between the Keyboard HID page and the Generic HID page with the Keyboard ID?
The HID usages specification defines a Generic Desktop Usage Page (0x01) which contains a Keyboard Usage ID (0x06). It also defines a Keyboard Usage Page (0x09) with Usage IDs corresponding to individual keyboard keys. The entry for the former just says to refer to the latter for details. Why does this distinction exist? Is there any practical difference between defining a device as DesktopGeneric/Keyboard vs. just Keyboard?

答:
For background, each USB usage code is a 4-byte number comprising two parts: a 2-byte usage page, followed by a 2-byte usage id. The Generic Desktop page is 0x0001 and the Keyboard/Keypad usage page is 0x0007. A reasonably complete list of known usages can be found at https://github.com/abend0c1/hidrdd/blob/master/rd.conf

The Keyboard usage id (0x0006) within the Generic Desktop page (i.e. usage 0x00010006) has the type "CA" and is meant to be used to identify a keyboard Application Collection. That identifies a collection of usages - usually from the Keyboard/Keypad page (0x0007) and LED Indicator page (0x0008) - that are to be associated with a Keyboard device. This way of identifying a collection of usages may be used by device drivers to direct USB HID reports to the appropriate device handler.

Note that HID report descriptors are formed by specifying GLOBAL and/or LOCAL items first, and then specifying MAIN items that use those GLOBAL/LOCAL items (kind of like Reverse Polish Notation: the operands come first, followed by the operations).

To illustrate, below is the example from "Appendix E.6 Report Descriptor (Keyboard)" of the HID Device Class Definition 1.11 that I have reformatted for clarity. The Generic Desktop Page is specified, then the Keyboard usage within that page, then an Application Collection MAIN item is begun for that usage (0x00010006).

```<code>05 01        (GLOBAL) USAGE_PAGE         0x0001 Generic Desktop Page
09 06        (LOCAL)  USAGE              0x00010006 Keyboard (CA=Application Collection)
A1 01        (MAIN)   COLLECTION         0x01 Application (Usage=0x00010006: Page=Generic Desktop Page, Usage=Keyboard, Type=CA)
05 07          (GLOBAL) USAGE_PAGE         0x0007 Keyboard/Keypad Page
19 E0          (LOCAL)  USAGE_MINIMUM      0x000700E0 Keyboard Left Control (DV=Dynamic Value)
29 E7          (LOCAL)  USAGE_MAXIMUM      0x000700E7 Keyboard Right GUI (DV=Dynamic Value)
15 00          (GLOBAL) LOGICAL_MINIMUM    0x00 (0) <-- Redundant: LOGICAL_MINIMUM is already 0
25 01          (GLOBAL) LOGICAL_MAXIMUM    0x01 (1)
75 01          (GLOBAL) REPORT_SIZE        0x01 (1) Number of bits per field
95 08          (GLOBAL) REPORT_COUNT       0x08 (8) Number of fields
81 02          (MAIN)   INPUT              0x00000002 (8 fields x 1 bit) 0=Data 1=Variable 0=Absolute 0=NoWrap 0=Linear 0=PrefState 0=NoNull 0=NonVolatile 0=Bitmap
95 01          (GLOBAL) REPORT_COUNT       0x01 (1) Number of fields
75 08          (GLOBAL) REPORT_SIZE        0x08 (8) Number of bits per field
81 01          (MAIN)   INPUT              0x00000001 (1 field x 8 bits) 1=Constant 0=Array 0=Absolute 0=Ignored 0=Ignored 0=PrefState 0=NoNull
95 05          (GLOBAL) REPORT_COUNT       0x05 (5) Number of fields
75 01          (GLOBAL) REPORT_SIZE        0x01 (1) Number of bits per field
05 08          (GLOBAL) USAGE_PAGE         0x0008 LED Indicator Page
19 01          (LOCAL)  USAGE_MINIMUM      0x00080001 Num Lock (OOC=On/Off Control)
29 05          (LOCAL)  USAGE_MAXIMUM      0x00080005 Kana (OOC=On/Off Control)
91 02          (MAIN)   OUTPUT             0x00000002 (5 fields x 1 bit) 0=Data 1=Variable 0=Absolute 0=NoWrap 0=Linear 0=PrefState 0=NoNull 0=NonVolatile 0=Bitmap
95 01          (GLOBAL) REPORT_COUNT       0x01 (1) Number of fields
75 03          (GLOBAL) REPORT_SIZE        0x03 (3) Number of bits per field
91 01          (MAIN)   OUTPUT             0x00000001 (1 field x 3 bits) 1=Constant 0=Array 0=Absolute 0=NoWrap 0=Linear 0=PrefState 0=NoNull 0=NonVolatile 0=Bitmap
95 06          (GLOBAL) REPORT_COUNT       0x06 (6) Number of fields
75 08          (GLOBAL) REPORT_SIZE        0x08 (8) Number of bits per field
15 00          (GLOBAL) LOGICAL_MINIMUM    0x00 (0) <-- Redundant: LOGICAL_MINIMUM is already 0
25 65          (GLOBAL) LOGICAL_MAXIMUM    0x65 (101)
05 07          (GLOBAL) USAGE_PAGE         0x0007 Keyboard/Keypad Page
19 00          (LOCAL)  USAGE_MINIMUM      0x00070000 Keyboard No event indicated (Sel=Selector) <-- Redundant: USAGE_MINIMUM is already 0x0000
29 65          (LOCAL)  USAGE_MAXIMUM      0x00070065 Keyboard Application (Sel=Selector)
81 00          (MAIN)   INPUT              0x00000000 (6 fields x 8 bits) 0=Data 0=Array 0=Absolute 0=Ignored 0=Ignored 0=PrefState 0=NoNull
C0           (MAIN)   END_COLLECTION     Application
</code>```

Body:
For background, each USB usage code is a 4-byte number comprising two parts: a 2-byte usage page, followed by a 2-byte usage id. The Generic Desktop page is 0x0001 and the Keyboard/Keypad usage page is 0x0007. A reasonably complete list of known usages can be found at https://github.com/abend0c1/hidrdd/blob/master/rd.conf

The Keyboard usage id (0x0006) within the Generic Desktop page (i.e. usage 0x00010006) has the type "CA" and is meant to be used to identify a keyboard Application Collection. That identifies a collection of usages - usually from the Keyboard/Keypad page (0x0007) and LED Indicator page (0x0008) - that are to be associated with a Keyboard device. This way of identifying a collection of usages may be used by device drivers to direct USB HID reports to the appropriate device handler.

Note that HID report descriptors are formed by specifying GLOBAL and/or LOCAL items first, and then specifying MAIN items that use those GLOBAL/LOCAL items (kind of like Reverse Polish Notation: the operands come first, followed by the operations).

To illustrate, below is the example from "Appendix E.6 Report Descriptor (Keyboard)" of the HID Device Class Definition 1.11 that I have reformatted for clarity. The Generic Desktop Page is specified, then the Keyboard usage within that page, then an Application Collection MAIN item is begun for that usage (0x00010006).

05 01        (GLOBAL) USAGE_PAGE         0x0001 Generic Desktop Page
09 06        (LOCAL)  USAGE              0x00010006 Keyboard (CA=Application Collection)
A1 01        (MAIN)   COLLECTION         0x01 Application (Usage=0x00010006: Page=Generic Desktop Page, Usage=Keyboard, Type=CA)
05 07          (GLOBAL) USAGE_PAGE         0x0007 Keyboard/Keypad Page
19 E0          (LOCAL)  USAGE_MINIMUM      0x000700E0 Keyboard Left Control (DV=Dynamic Value)
29 E7          (LOCAL)  USAGE_MAXIMUM      0x000700E7 Keyboard Right GUI (DV=Dynamic Value)
15 00          (GLOBAL) LOGICAL_MINIMUM    0x00 (0) <-- Redundant: LOGICAL_MINIMUM is already 0
25 01          (GLOBAL) LOGICAL_MAXIMUM    0x01 (1)
75 01          (GLOBAL) REPORT_SIZE        0x01 (1) Number of bits per field
95 08          (GLOBAL) REPORT_COUNT       0x08 (8) Number of fields
81 02          (MAIN)   INPUT              0x00000002 (8 fields x 1 bit) 0=Data 1=Variable 0=Absolute 0=NoWrap 0=Linear 0=PrefState 0=NoNull 0=NonVolatile 0=Bitmap
95 01          (GLOBAL) REPORT_COUNT       0x01 (1) Number of fields
75 08          (GLOBAL) REPORT_SIZE        0x08 (8) Number of bits per field
81 01          (MAIN)   INPUT              0x00000001 (1 field x 8 bits) 1=Constant 0=Array 0=Absolute 0=Ignored 0=Ignored 0=PrefState 0=NoNull
95 05          (GLOBAL) REPORT_COUNT       0x05 (5) Number of fields
75 01          (GLOBAL) REPORT_SIZE        0x01 (1) Number of bits per field
05 08          (GLOBAL) USAGE_PAGE         0x0008 LED Indicator Page
19 01          (LOCAL)  USAGE_MINIMUM      0x00080001 Num Lock (OOC=On/Off Control)
29 05          (LOCAL)  USAGE_MAXIMUM      0x00080005 Kana (OOC=On/Off Control)
91 02          (MAIN)   OUTPUT             0x00000002 (5 fields x 1 bit) 0=Data 1=Variable 0=Absolute 0=NoWrap 0=Linear 0=PrefState 0=NoNull 0=NonVolatile 0=Bitmap
95 01          (GLOBAL) REPORT_COUNT       0x01 (1) Number of fields
75 03          (GLOBAL) REPORT_SIZE        0x03 (3) Number of bits per field
91 01          (MAIN)   OUTPUT             0x00000001 (1 field x 3 bits) 1=Constant 0=Array 0=Absolute 0=NoWrap 0=Linear 0=PrefState 0=NoNull 0=NonVolatile 0=Bitmap
95 06          (GLOBAL) REPORT_COUNT       0x06 (6) Number of fields
75 08          (GLOBAL) REPORT_SIZE        0x08 (8) Number of bits per field
15 00          (GLOBAL) LOGICAL_MINIMUM    0x00 (0) <-- Redundant: LOGICAL_MINIMUM is already 0
25 65          (GLOBAL) LOGICAL_MAXIMUM    0x65 (101)
05 07          (GLOBAL) USAGE_PAGE         0x0007 Keyboard/Keypad Page
19 00          (LOCAL)  USAGE_MINIMUM      0x00070000 Keyboard No event indicated (Sel=Selector) <-- Redundant: USAGE_MINIMUM is already 0x0000
29 65          (LOCAL)  USAGE_MAXIMUM      0x00070065 Keyboard Application (Sel=Selector)
81 00          (MAIN)   INPUT              0x00000000 (6 fields x 8 bits) 0=Data 0=Array 0=Absolute 0=Ignored 0=Ignored 0=PrefState 0=NoNull
C0           (MAIN)   END_COLLECTION     Application


问:
Kubernetes Deployment and Service named ports
Hope life is great for everyone. I am trying to figure to use named ports for Deployment and Service. For pods and service using named ports works fine. But doesn't for Deployment and Service. I dig and no answers are working, example https://github.com/GoogleCloudPlatform/k8s-multicluster-ingress/issues/196 and there is one in Stack Overflow which doesn't helps much, How to make use of Kubernetes port names?

This is the YAML files.

deployment-named-port.yaml

```<code>apiVersion: apps/v1
kind: Deployment
metadata:
  labels:
    app: test-named-ports
  name: test-named-ports
spec:
  replicas: 3
  selector:
    matchLabels:
      app: test-named-ports
  strategy: {}
  template:
    metadata:
      labels:
        app: test-named-ports
    spec:
      containers:
      - image: nginx
        name: nginx
        ports:
        - containerPort: 80
          name: nginx-port
</code>```

named-port-svc.yaml

```<code>apiVersion: v1
kind: Service
metadata:
  name: my-service
spec:
  type: NodePort
  selector:
    app: test-named-ports
  ports:
    - port: nginx-port
      targetPort: nginx-port
      nodePort: 30007

vagrant@kubemaster:~$ kubectl apply -f named-port.yaml
deployment.apps/test-nameed-ports created

vagrant@kubemaster:~$ kubectl apply -f named-port-svc.yaml
error: error validating "named-port-svc.yaml": error validating data: ValidationError(Service.spec.ports[0].port): invalid type for io.k8s.api.core.v1.ServicePort.port: got "string", expected "integer"; if you choose to ignore these errors, turn validation off with --validate=false
</code>```

Can someone please help me. Appreciate all your support.

Thanks,

Joe Antony

答:
Try:</p>
```<code>apiVersion: v1
kind: Service
metadata:
  name: my-service
spec:
  type: NodePort
  selector:
    app: test-named-ports
  ports:
  - name: nginx-port       # <-- port name that this service expose
    port: 80               # <-- port # that this service expose
    targetPort: nginx-port # <-- port name that the backing pod expose
    nodePort: 30007
</code>```

Body:
Hope life is great for everyone. I am trying to figure to use named ports for Deployment and Service. For pods and service using named ports works fine. But doesn't for Deployment and Service. I dig and no answers are working, example https://github.com/GoogleCloudPlatform/k8s-multicluster-ingress/issues/196 and there is one in Stack Overflow which doesn't helps much, How to make use of Kubernetes port names?

This is the YAML files.

deployment-named-port.yaml

apiVersion: apps/v1
kind: Deployment
metadata:
  labels:
    app: test-named-ports
  name: test-named-ports
spec:
  replicas: 3
  selector:
    matchLabels:
      app: test-named-ports
  strategy: {}
  template:
    metadata:
      labels:
        app: test-named-ports
    spec:
      containers:
      - image: nginx
        name: nginx
        ports:
        - containerPort: 80
          name: nginx-port

named-port-svc.yaml

apiVersion: v1
kind: Service
metadata:
  name: my-service
spec:
  type: NodePort
  selector:
    app: test-named-ports
  ports:
    - port: nginx-port
      targetPort: nginx-port
      nodePort: 30007

vagrant@kubemaster:~$ kubectl apply -f named-port.yaml
deployment.apps/test-nameed-ports created

vagrant@kubemaster:~$ kubectl apply -f named-port-svc.yaml
error: error validating "named-port-svc.yaml": error validating data: ValidationError(Service.spec.ports[0].port): invalid type for io.k8s.api.core.v1.ServicePort.port: got "string", expected "integer"; if you choose to ignore these errors, turn validation off with --validate=false

Can someone please help me. Appreciate all your support.

Thanks,

Joe Antony

Body:
Try:

apiVersion: v1
kind: Service
metadata:
  name: my-service
spec:
  type: NodePort
  selector:
    app: test-named-ports
  ports:
  - name: nginx-port       # <-- port name that this service expose
    port: 80               # <-- port # that this service expose
    targetPort: nginx-port # <-- port name that the backing pod expose
    nodePort: 30007


问:
Regex - add new field between semicolon separators - notepad++
I have data like this (some of the fields have values, some of them don't)

```<code>J;555;3;1990-02-19;1234;S;2020-10-17;;;;;value;3;ANOTHERVALUE
</code>```

I need to add a new field right before the 5th semicolon, like this (the F value):

```<code>J;555;3;1990-02-19;1234;F;S;2020-10-17;;;;;value;3;ANOTHERVALUE
</code>```

So far I have this:

```<code>^(([A-Z]);([0-9A-Z]+);([?:0-9]);([0-9\-]+);([A-Z0-9]+));(.*)$
</code>```

And as replacement:

```<code>$1;$2;F;$7
</code>```

As far as I know the ?: before is to mark optional, but in my case I need to represent empty fields between every semicolon

How can I solve this?

答:
You may use this code in notepad++,

Find:^((.*?;){5})

Replace with:$1F;

Body:
I have data like this (some of the fields have values, some of them don't)

J;555;3;1990-02-19;1234;S;2020-10-17;;;;;value;3;ANOTHERVALUE

I need to add a new field right before the 5th semicolon, like this (the F value):

J;555;3;1990-02-19;1234;F;S;2020-10-17;;;;;value;3;ANOTHERVALUE

So far I have this:

^(([A-Z]);([0-9A-Z]+);([?:0-9]);([0-9\-]+);([A-Z0-9]+));(.*)$

And as replacement:

$1;$2;F;$7

As far as I know the ?: before is to mark optional, but in my case I need to represent empty fields between every semicolon

How can I solve this?