问:
Kubernetes cluster "cni config uninitialized"
The problem i'm running into is very similar to the other existing post, except they all have the same solution therefore im creating a new thread.

The Problem:
The Master node is still in "NotReady" status after installing Flannel.

Expected result:
Master Node becomes "Ready" after installing Flannel.

Background:
I am following this guide when installing Flannel

My concern is that I am using Kubelet v1.17.2 by default that just came out like last month (Can anyone confirm if v1.17.2 works with Flannel?"

Here is the output after running the command on master node: kubectl describe node machias

```<code>Name:               machias
Roles:              master
Labels:             beta.kubernetes.io/arch=amd64
                    beta.kubernetes.io/os=linux
                    kubernetes.io/arch=amd64
                    kubernetes.io/hostname=machias
                    kubernetes.io/os=linux
                    node-role.kubernetes.io/master=
Annotations:        flannel.alpha.coreos.com/backend-data: {"VtepMAC":"be:78:65:7f:ae:6d"}
                    flannel.alpha.coreos.com/backend-type: vxlan
                    flannel.alpha.coreos.com/kube-subnet-manager: true
                    flannel.alpha.coreos.com/public-ip: 192.168.122.172
                    kubeadm.alpha.kubernetes.io/cri-socket: /var/run/dockershim.sock
                    node.alpha.kubernetes.io/ttl: 0
                    volumes.kubernetes.io/controller-managed-attach-detach: true
CreationTimestamp:  Sat, 15 Feb 2020 01:00:01 -0500
Taints:             node.kubernetes.io/not-ready:NoExecute
                    node-role.kubernetes.io/master:NoSchedule
                    node.kubernetes.io/not-ready:NoSchedule
Unschedulable:      false
Lease:
  HolderIdentity:  machias
  AcquireTime:     <unset>
  RenewTime:       Sat, 15 Feb 2020 13:54:56 -0500
Conditions:
  Type             Status  LastHeartbeatTime                 LastTransitionTime                Reason                       Message
  ----             ------  -----------------                 ------------------                ------                       -------
  MemoryPressure   False   Sat, 15 Feb 2020 13:54:52 -0500   Sat, 15 Feb 2020 00:59:54 -0500   KubeletHasSufficientMemory   kubelet has sufficient memory available
  DiskPressure     False   Sat, 15 Feb 2020 13:54:52 -0500   Sat, 15 Feb 2020 00:59:54 -0500   KubeletHasNoDiskPressure     kubelet has no disk pressure
  PIDPressure      False   Sat, 15 Feb 2020 13:54:52 -0500   Sat, 15 Feb 2020 00:59:54 -0500   KubeletHasSufficientPID      kubelet has sufficient PID available
  Ready            False   Sat, 15 Feb 2020 13:54:52 -0500   Sat, 15 Feb 2020 00:59:54 -0500   KubeletNotReady              runtime network not ready: NetworkReady=false reason:NetworkPluginNotReady message:docker: network plugin is not ready: cni config uninitialized
Addresses:
  InternalIP:  192.168.122.172
  Hostname:    machias
Capacity:
  cpu:                2
  ephemeral-storage:  38583284Ki
  hugepages-2Mi:      0
  memory:             4030364Ki
  pods:               110
Allocatable:
  cpu:                2
  ephemeral-storage:  35558354476
  hugepages-2Mi:      0
  memory:             3927964Ki
  pods:               110
System Info:
  Machine ID:                 20cbe0d737dd43588f4a2bccd70681a2
  System UUID:                ee9bc138-edee-471a-8ecc-f1c567c5f796
  Boot ID:                    0ba49907-ec32-4e80-bc4c-182fccb0b025
  Kernel Version:             5.3.5-200.fc30.x86_64
  OS Image:                   Fedora 30 (Workstation Edition)
  Operating System:           linux
  Architecture:               amd64
  Container Runtime Version:  docker://19.3.5
  Kubelet Version:            v1.17.2
  Kube-Proxy Version:         v1.17.2
PodCIDR:                      10.244.0.0/24
PodCIDRs:                     10.244.0.0/24
Non-terminated Pods:          (6 in total)
  Namespace                   Name                                          CPU Requests  CPU Limits  Memory Requests  Memory Limits  AGE
  ---------                   ----                                          ------------  ----------  ---------------  -------------  ---
  kube-system                 etcd-machias                     0 (0%)        0 (0%)      0 (0%)           0 (0%)         12h
  kube-system                 kube-apiserver-machias            250m (12%)    0 (0%)      0 (0%)           0 (0%)         12h
  kube-system                 kube-controller-manager-machias    200m (10%)    0 (0%)      0 (0%)           0 (0%)         12h
  kube-system                 kube-flannel-ds-amd64-rrfht                   100m (5%)     100m (5%)   50Mi (1%)        50Mi (1%)      12h
  kube-system                 kube-proxy-z2q7d                              0 (0%)        0 (0%)      0 (0%)           0 (0%)         12h
  kube-system                 kube-scheduler-machias            100m (5%)     0 (0%)      0 (0%)           0 (0%)         12h
Allocated resources:
  (Total limits may be over 100 percent, i.e., overcommitted.)
  Resource           Requests    Limits
  --------           --------    ------
  cpu                650m (32%)  100m (5%)
  memory             50Mi (1%)   50Mi (1%)
  ephemeral-storage  0 (0%)      0 (0%)
Events:              <none>
</code>```

And the following command: kubectl get pods --all-namespaces

```<code>NAMESPACE     NAME                                         READY   STATUS    RESTARTS   AGE
kube-system   coredns-6955765f44-7nz46                     0/1     Pending   0          12h
kube-system   coredns-6955765f44-xk5r2                     0/1     Pending   0          13h
kube-system   etcd-machias.cs.unh.edu                      1/1     Running   0          13h
kube-system   kube-apiserver-machias.cs.unh.edu            1/1     Running   0          13h
kube-system   kube-controller-manager-machias.cs.unh.edu   1/1     Running   0          13h
kube-system   kube-flannel-ds-amd64-rrfht                  1/1     Running   0          12h
kube-system   kube-flannel-ds-amd64-t7p2p                  1/1     Running   0          12h
kube-system   kube-proxy-fnn78                             1/1     Running   0          12h
kube-system   kube-proxy-z2q7d                             1/1     Running   0          13h
kube-system   kube-scheduler-machias.cs.unh.edu            1/1     Running   0          13h
</code>```

Thank you for your help!

答:
I've reproduced your scenario using the same versions you are using to make sure these versions work with Flannel.

After testing it I can affirm that there is no problem with the version you are using.

I created it following these steps:

Ensure iptables tooling does not use the nftables backend Source

```<code>update-alternatives --set iptables /usr/sbin/iptables-legacy
</code>```

Installing runtime

```<code>sudo yum remove docker   docker-common  docker-selinux   docker-engine
sudo yum install -y yum-utils   device-mapper-persistent-data   lvm2
sudo yum-config-manager   --add-repo    https://download.docker.com/linux/centos/docker-ce.repo
sudo yum install docker-ce-19.03.5-3.el7
sudo systemctl start docker
</code>```

Installing kubeadm, kubelet and kubectl

```<code>sudo su -c "cat <<EOF > /etc/yum.repos.d/kubernetes.repo
[kubernetes]
name=Kubernetes
baseurl=https://packages.cloud.google.com/yum/repos/kubernetes-el7-x86_64
enabled=1
gpgcheck=1
repo_gpgcheck=1
gpgkey=https://packages.cloud.google.com/yum/doc/yum-key.gpg https://packages.cloud.google.com/yum/doc/rpm-package-key.gpg
EOF"

sudo setenforce 0
sudo sed -i 's/^SELINUX=enforcing$/SELINUX=permissive/' /etc/selinux/config
sudo yum install -y kubelet-1.17.2-0 kubeadm-1.17.2-0 kubectl-1.17.2-0 --disableexcludes=kubernetes
sudo systemctl enable --now kubelet
</code>```

Note:

Setting SELinux in permissive mode by running  setenforce 0  and  sed ...  effectively disables it. This is required to allow containers to access the host filesystem, which is needed by pod networks for example. You have to do this until SELinux support is improved in the kubelet.

Some users on RHEL/CentOS 7 have reported issues with traffic being routed incorrectly due to iptables being bypassed. You should ensure  net.bridge.bridge-nf-call-iptables  is set to 1 in your  sysctl  config, e.g.

cat <<EOF > /etc/sysctl.d/k8s.conf
net.bridge.bridge-nf-call-ip6tables = 1
net.bridge.bridge-nf-call-iptables = 1
EOF
sysctl --system
```</li>
<li><p>Make sure that the  <code>br_netfilter</code>  module is loaded before this step. This can be done by running  <code>lsmod | grep br_netfilter</code>. To load it explicitly call  <code>modprobe br_netfilter</code>.</p></li>
</ul>

<p><strong>Initialize cluster with Flannel CIDR</strong></p>

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

```mkdir -p $HOME/.kube
sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config
sudo chown $(id -u):$(id -g) $HOME/.kube/config
```

<p><strong>Add Flannel CNI</strong></p>

```kubectl apply -f https://raw.githubusercontent.com/coreos/flannel/2140ac876ef134e0ed5af15c65e414cf26827915/Documentation/kube-flannel.yml
```

<p>By default, your cluster will not schedule Pods on the control-plane node for security reasons. If you want to be able to schedule Pods on the control-plane node, e.g. for a single-machine Kubernetes cluster for development, run:</p>

<pre class="lang-sh prettyprint-override"><code>kubectl taint nodes --all node-role.kubernetes.io/master-
</code>```

As can be seen, my master node is Ready. Please, follow this How-to and let me know if you can achieve your desired state.

```<code>$ kubectl describe nodes
Name:               kubeadm-fedora
Roles:              master
Labels:             beta.kubernetes.io/arch=amd64
                    beta.kubernetes.io/os=linux
                    kubernetes.io/arch=amd64
                    kubernetes.io/hostname=kubeadm-fedora
                    kubernetes.io/os=linux
                    node-role.kubernetes.io/master=
Annotations:        flannel.alpha.coreos.com/backend-data: {"VtepMAC":"8e:7e:bf:d9:21:1e"}
                    flannel.alpha.coreos.com/backend-type: vxlan
                    flannel.alpha.coreos.com/kube-subnet-manager: true
                    flannel.alpha.coreos.com/public-ip: 10.128.15.200
                    kubeadm.alpha.kubernetes.io/cri-socket: /var/run/dockershim.sock
                    node.alpha.kubernetes.io/ttl: 0
                    volumes.kubernetes.io/controller-managed-attach-detach: true
CreationTimestamp:  Mon, 17 Feb 2020 11:31:59 +0000
Taints:             node-role.kubernetes.io/master:NoSchedule
Unschedulable:      false
Lease:
  HolderIdentity:  kubeadm-fedora
  AcquireTime:     <unset>
  RenewTime:       Mon, 17 Feb 2020 11:47:52 +0000
Conditions:
  Type             Status  LastHeartbeatTime                 LastTransitionTime                Reason                       Message
  ----             ------  -----------------                 ------------------                ------                       -------
  MemoryPressure   False   Mon, 17 Feb 2020 11:47:37 +0000   Mon, 17 Feb 2020 11:31:51 +0000   KubeletHasSufficientMemory   kubelet has sufficient memory available
  DiskPressure     False   Mon, 17 Feb 2020 11:47:37 +0000   Mon, 17 Feb 2020 11:31:51 +0000   KubeletHasNoDiskPressure     kubelet has no disk pressure
  PIDPressure      False   Mon, 17 Feb 2020 11:47:37 +0000   Mon, 17 Feb 2020 11:31:51 +0000   KubeletHasSufficientPID      kubelet has sufficient PID available
  Ready            True    Mon, 17 Feb 2020 11:47:37 +0000   Mon, 17 Feb 2020 11:32:32 +0000   KubeletReady                 kubelet is posting ready status
Addresses:
  InternalIP:  10.128.15.200
  Hostname:    kubeadm-fedora
Capacity:
  cpu:                2
  ephemeral-storage:  104844988Ki
  hugepages-1Gi:      0
  hugepages-2Mi:      0
  memory:             7493036Ki
  pods:               110
Allocatable:
  cpu:                2
  ephemeral-storage:  96625140781
  hugepages-1Gi:      0
  hugepages-2Mi:      0
  memory:             7390636Ki
  pods:               110
System Info:
  Machine ID:                 41689852cca44b659f007bb418a6fa9f
  System UUID:                390D88CD-3D28-5657-8D0C-83AB1974C88A
  Boot ID:                    bff1c808-788e-48b8-a789-4fee4e800554
  Kernel Version:             3.10.0-1062.9.1.el7.x86_64
  OS Image:                   CentOS Linux 7 (Core)
  Operating System:           linux
  Architecture:               amd64
  Container Runtime Version:  docker://19.3.5
  Kubelet Version:            v1.17.2
  Kube-Proxy Version:         v1.17.2
PodCIDR:                      10.244.0.0/24
PodCIDRs:                     10.244.0.0/24
Non-terminated Pods:          (8 in total)
  Namespace                   Name                                      CPU Requests  CPU Limits  Memory Requests  Memory Limits  AGE
  ---------                   ----                                      ------------  ----------  ---------------  -------------  ---
  kube-system                 coredns-6955765f44-d9fb4                  100m (5%)     0 (0%)      70Mi (0%)        170Mi (2%)     15m
  kube-system                 coredns-6955765f44-l7xrk                  100m (5%)     0 (0%)      70Mi (0%)        170Mi (2%)     15m
  kube-system                 etcd-kubeadm-fedora                       0 (0%)        0 (0%)      0 (0%)           0 (0%)         15m
  kube-system                 kube-apiserver-kubeadm-fedora             250m (12%)    0 (0%)      0 (0%)           0 (0%)         15m
  kube-system                 kube-controller-manager-kubeadm-fedora    200m (10%)    0 (0%)      0 (0%)           0 (0%)         15m
  kube-system                 kube-flannel-ds-amd64-v6m2w               100m (5%)     100m (5%)   50Mi (0%)        50Mi (0%)      15m
  kube-system                 kube-proxy-d65kl                          0 (0%)        0 (0%)      0 (0%)           0 (0%)         15m
  kube-system                 kube-scheduler-kubeadm-fedora             100m (5%)     0 (0%)      0 (0%)           0 (0%)         15m
Allocated resources:
  (Total limits may be over 100 percent, i.e., overcommitted.)
  Resource           Requests    Limits
  --------           --------    ------
  cpu                850m (42%)  100m (5%)
  memory             190Mi (2%)  390Mi (5%)
  ephemeral-storage  0 (0%)      0 (0%)
Events:
  Type    Reason                   Age                From                        Message
  ----    ------                   ----               ----                        -------
  Normal  NodeHasSufficientMemory  16m (x6 over 16m)  kubelet, kubeadm-fedora     Node kubeadm-fedora status is now: NodeHasSufficientMemory
  Normal  NodeHasNoDiskPressure    16m (x5 over 16m)  kubelet, kubeadm-fedora     Node kubeadm-fedora status is now: NodeHasNoDiskPressure
  Normal  NodeHasSufficientPID     16m (x5 over 16m)  kubelet, kubeadm-fedora     Node kubeadm-fedora status is now: NodeHasSufficientPID
  Normal  NodeAllocatableEnforced  16m                kubelet, kubeadm-fedora     Updated Node Allocatable limit across pods
  Normal  Starting                 15m                kubelet, kubeadm-fedora     Starting kubelet.
  Normal  NodeHasSufficientMemory  15m                kubelet, kubeadm-fedora     Node kubeadm-fedora status is now: NodeHasSufficientMemory
  Normal  NodeHasNoDiskPressure    15m                kubelet, kubeadm-fedora     Node kubeadm-fedora status is now: NodeHasNoDiskPressure
  Normal  NodeHasSufficientPID     15m                kubelet, kubeadm-fedora     Node kubeadm-fedora status is now: NodeHasSufficientPID
  Normal  NodeAllocatableEnforced  15m                kubelet, kubeadm-fedora     Updated Node Allocatable limit across pods
  Normal  Starting                 15m                kube-proxy, kubeadm-fedora  Starting kube-proxy.
  Normal  NodeReady                15m                kubelet, kubeadm-fedora     Node kubeadm-fedora status is now: NodeReady
</code>```

```<code>$ kubectl get nodes
NAME             STATUS   ROLES    AGE   VERSION
kubeadm-fedora   Ready    master   17m   v1.17.2
</code>```

```<code>$ kubectl get pods -A
NAMESPACE     NAME                                     READY   STATUS    RESTARTS   AGE
kube-system   coredns-6955765f44-d9fb4                 1/1     Running   0          17m
kube-system   coredns-6955765f44-l7xrk                 1/1     Running   0          17m
kube-system   etcd-kubeadm-fedora                      1/1     Running   0          17m
kube-system   kube-apiserver-kubeadm-fedora            1/1     Running   0          17m
kube-system   kube-controller-manager-kubeadm-fedora   1/1     Running   0          17m
kube-system   kube-flannel-ds-amd64-v6m2w              1/1     Running   0          17m
kube-system   kube-proxy-d65kl                         1/1     Running   0          17m
kube-system   kube-scheduler-kubeadm-fedora            1/1     Running   0          17m
</code>```

Body:
The problem i'm running into is very similar to the other existing post, except they all have the same solution therefore im creating a new thread.

The Problem:
The Master node is still in "NotReady" status after installing Flannel.

Expected result:
Master Node becomes "Ready" after installing Flannel.

Background:
I am following this guide when installing Flannel

My concern is that I am using Kubelet v1.17.2 by default that just came out like last month (Can anyone confirm if v1.17.2 works with Flannel?"

Here is the output after running the command on master node: kubectl describe node machias

Name:               machias
Roles:              master
Labels:             beta.kubernetes.io/arch=amd64
                    beta.kubernetes.io/os=linux
                    kubernetes.io/arch=amd64
                    kubernetes.io/hostname=machias
                    kubernetes.io/os=linux
                    node-role.kubernetes.io/master=
Annotations:        flannel.alpha.coreos.com/backend-data: {"VtepMAC":"be:78:65:7f:ae:6d"}
                    flannel.alpha.coreos.com/backend-type: vxlan
                    flannel.alpha.coreos.com/kube-subnet-manager: true
                    flannel.alpha.coreos.com/public-ip: 192.168.122.172
                    kubeadm.alpha.kubernetes.io/cri-socket: /var/run/dockershim.sock
                    node.alpha.kubernetes.io/ttl: 0
                    volumes.kubernetes.io/controller-managed-attach-detach: true
CreationTimestamp:  Sat, 15 Feb 2020 01:00:01 -0500
Taints:             node.kubernetes.io/not-ready:NoExecute
                    node-role.kubernetes.io/master:NoSchedule
                    node.kubernetes.io/not-ready:NoSchedule
Unschedulable:      false
Lease:
  HolderIdentity:  machias
  AcquireTime:     <unset>
  RenewTime:       Sat, 15 Feb 2020 13:54:56 -0500
Conditions:
  Type             Status  LastHeartbeatTime                 LastTransitionTime                Reason                       Message
  ----             ------  -----------------                 ------------------                ------                       -------
  MemoryPressure   False   Sat, 15 Feb 2020 13:54:52 -0500   Sat, 15 Feb 2020 00:59:54 -0500   KubeletHasSufficientMemory   kubelet has sufficient memory available
  DiskPressure     False   Sat, 15 Feb 2020 13:54:52 -0500   Sat, 15 Feb 2020 00:59:54 -0500   KubeletHasNoDiskPressure     kubelet has no disk pressure
  PIDPressure      False   Sat, 15 Feb 2020 13:54:52 -0500   Sat, 15 Feb 2020 00:59:54 -0500   KubeletHasSufficientPID      kubelet has sufficient PID available
  Ready            False   Sat, 15 Feb 2020 13:54:52 -0500   Sat, 15 Feb 2020 00:59:54 -0500   KubeletNotReady              runtime network not ready: NetworkReady=false reason:NetworkPluginNotReady message:docker: network plugin is not ready: cni config uninitialized
Addresses:
  InternalIP:  192.168.122.172
  Hostname:    machias
Capacity:
  cpu:                2
  ephemeral-storage:  38583284Ki
  hugepages-2Mi:      0
  memory:             4030364Ki
  pods:               110
Allocatable:
  cpu:                2
  ephemeral-storage:  35558354476
  hugepages-2Mi:      0
  memory:             3927964Ki
  pods:               110
System Info:
  Machine ID:                 20cbe0d737dd43588f4a2bccd70681a2
  System UUID:                ee9bc138-edee-471a-8ecc-f1c567c5f796
  Boot ID:                    0ba49907-ec32-4e80-bc4c-182fccb0b025
  Kernel Version:             5.3.5-200.fc30.x86_64
  OS Image:                   Fedora 30 (Workstation Edition)
  Operating System:           linux
  Architecture:               amd64
  Container Runtime Version:  docker://19.3.5
  Kubelet Version:            v1.17.2
  Kube-Proxy Version:         v1.17.2
PodCIDR:                      10.244.0.0/24
PodCIDRs:                     10.244.0.0/24
Non-terminated Pods:          (6 in total)
  Namespace                   Name                                          CPU Requests  CPU Limits  Memory Requests  Memory Limits  AGE
  ---------                   ----                                          ------------  ----------  ---------------  -------------  ---
  kube-system                 etcd-machias                     0 (0%)        0 (0%)      0 (0%)           0 (0%)         12h
  kube-system                 kube-apiserver-machias            250m (12%)    0 (0%)      0 (0%)           0 (0%)         12h
  kube-system                 kube-controller-manager-machias    200m (10%)    0 (0%)      0 (0%)           0 (0%)         12h
  kube-system                 kube-flannel-ds-amd64-rrfht                   100m (5%)     100m (5%)   50Mi (1%)        50Mi (1%)      12h
  kube-system                 kube-proxy-z2q7d                              0 (0%)        0 (0%)      0 (0%)           0 (0%)         12h
  kube-system                 kube-scheduler-machias            100m (5%)     0 (0%)      0 (0%)           0 (0%)         12h
Allocated resources:
  (Total limits may be over 100 percent, i.e., overcommitted.)
  Resource           Requests    Limits
  --------           --------    ------
  cpu                650m (32%)  100m (5%)
  memory             50Mi (1%)   50Mi (1%)
  ephemeral-storage  0 (0%)      0 (0%)
Events:              <none>

And the following command: kubectl get pods --all-namespaces

NAMESPACE     NAME                                         READY   STATUS    RESTARTS   AGE
kube-system   coredns-6955765f44-7nz46                     0/1     Pending   0          12h
kube-system   coredns-6955765f44-xk5r2                     0/1     Pending   0          13h
kube-system   etcd-machias.cs.unh.edu                      1/1     Running   0          13h
kube-system   kube-apiserver-machias.cs.unh.edu            1/1     Running   0          13h
kube-system   kube-controller-manager-machias.cs.unh.edu   1/1     Running   0          13h
kube-system   kube-flannel-ds-amd64-rrfht                  1/1     Running   0          12h
kube-system   kube-flannel-ds-amd64-t7p2p                  1/1     Running   0          12h
kube-system   kube-proxy-fnn78                             1/1     Running   0          12h
kube-system   kube-proxy-z2q7d                             1/1     Running   0          13h
kube-system   kube-scheduler-machias.cs.unh.edu            1/1     Running   0          13h

Thank you for your help!

Body:
I've reproduced your scenario using the same versions you are using to make sure these versions work with Flannel.

After testing it I can affirm that there is no problem with the version you are using.

I created it following these steps:

Ensure iptables tooling does not use the nftables backend Source

update-alternatives --set iptables /usr/sbin/iptables-legacy

Installing runtime

sudo yum remove docker   docker-common  docker-selinux   docker-engine
sudo yum install -y yum-utils   device-mapper-persistent-data   lvm2
sudo yum-config-manager   --add-repo    https://download.docker.com/linux/centos/docker-ce.repo
sudo yum install docker-ce-19.03.5-3.el7
sudo systemctl start docker

Installing kubeadm, kubelet and kubectl

sudo su -c "cat <<EOF > /etc/yum.repos.d/kubernetes.repo
[kubernetes]
name=Kubernetes
baseurl=https://packages.cloud.google.com/yum/repos/kubernetes-el7-x86_64
enabled=1
gpgcheck=1
repo_gpgcheck=1
gpgkey=https://packages.cloud.google.com/yum/doc/yum-key.gpg https://packages.cloud.google.com/yum/doc/rpm-package-key.gpg
EOF"

sudo setenforce 0
sudo sed -i 's/^SELINUX=enforcing$/SELINUX=permissive/' /etc/selinux/config
sudo yum install -y kubelet-1.17.2-0 kubeadm-1.17.2-0 kubectl-1.17.2-0 --disableexcludes=kubernetes
sudo systemctl enable --now kubelet

Note:

Setting SELinux in permissive mode by running  setenforce 0  and  sed ...  effectively disables it. This is required to allow containers to access the host filesystem, which is needed by pod networks for example. You have to do this until SELinux support is improved in the kubelet.

Some users on RHEL/CentOS 7 have reported issues with traffic being routed incorrectly due to iptables being bypassed. You should ensure  net.bridge.bridge-nf-call-iptables  is set to 1 in your  sysctl  config, e.g.

cat <<EOF > /etc/sysctl.d/k8s.conf
net.bridge.bridge-nf-call-ip6tables = 1
net.bridge.bridge-nf-call-iptables = 1
EOF
sysctl --system

Make sure that the  br_netfilter  module is loaded before this step. This can be done by running  lsmod | grep br_netfilter. To load it explicitly call  modprobe br_netfilter.

Initialize cluster with Flannel CIDR

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

mkdir -p $HOME/.kube
sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config
sudo chown $(id -u):$(id -g) $HOME/.kube/config

Add Flannel CNI

kubectl apply -f https://raw.githubusercontent.com/coreos/flannel/2140ac876ef134e0ed5af15c65e414cf26827915/Documentation/kube-flannel.yml

By default, your cluster will not schedule Pods on the control-plane node for security reasons. If you want to be able to schedule Pods on the control-plane node, e.g. for a single-machine Kubernetes cluster for development, run:

kubectl taint nodes --all node-role.kubernetes.io/master-

As can be seen, my master node is Ready. Please, follow this How-to and let me know if you can achieve your desired state.

$ kubectl describe nodes
Name:               kubeadm-fedora
Roles:              master
Labels:             beta.kubernetes.io/arch=amd64
                    beta.kubernetes.io/os=linux
                    kubernetes.io/arch=amd64
                    kubernetes.io/hostname=kubeadm-fedora
                    kubernetes.io/os=linux
                    node-role.kubernetes.io/master=
Annotations:        flannel.alpha.coreos.com/backend-data: {"VtepMAC":"8e:7e:bf:d9:21:1e"}
                    flannel.alpha.coreos.com/backend-type: vxlan
                    flannel.alpha.coreos.com/kube-subnet-manager: true
                    flannel.alpha.coreos.com/public-ip: 10.128.15.200
                    kubeadm.alpha.kubernetes.io/cri-socket: /var/run/dockershim.sock
                    node.alpha.kubernetes.io/ttl: 0
                    volumes.kubernetes.io/controller-managed-attach-detach: true
CreationTimestamp:  Mon, 17 Feb 2020 11:31:59 +0000
Taints:             node-role.kubernetes.io/master:NoSchedule
Unschedulable:      false
Lease:
  HolderIdentity:  kubeadm-fedora
  AcquireTime:     <unset>
  RenewTime:       Mon, 17 Feb 2020 11:47:52 +0000
Conditions:
  Type             Status  LastHeartbeatTime                 LastTransitionTime                Reason                       Message
  ----             ------  -----------------                 ------------------                ------                       -------
  MemoryPressure   False   Mon, 17 Feb 2020 11:47:37 +0000   Mon, 17 Feb 2020 11:31:51 +0000   KubeletHasSufficientMemory   kubelet has sufficient memory available
  DiskPressure     False   Mon, 17 Feb 2020 11:47:37 +0000   Mon, 17 Feb 2020 11:31:51 +0000   KubeletHasNoDiskPressure     kubelet has no disk pressure
  PIDPressure      False   Mon, 17 Feb 2020 11:47:37 +0000   Mon, 17 Feb 2020 11:31:51 +0000   KubeletHasSufficientPID      kubelet has sufficient PID available
  Ready            True    Mon, 17 Feb 2020 11:47:37 +0000   Mon, 17 Feb 2020 11:32:32 +0000   KubeletReady                 kubelet is posting ready status
Addresses:
  InternalIP:  10.128.15.200
  Hostname:    kubeadm-fedora
Capacity:
  cpu:                2
  ephemeral-storage:  104844988Ki
  hugepages-1Gi:      0
  hugepages-2Mi:      0
  memory:             7493036Ki
  pods:               110
Allocatable:
  cpu:                2
  ephemeral-storage:  96625140781
  hugepages-1Gi:      0
  hugepages-2Mi:      0
  memory:             7390636Ki
  pods:               110
System Info:
  Machine ID:                 41689852cca44b659f007bb418a6fa9f
  System UUID:                390D88CD-3D28-5657-8D0C-83AB1974C88A
  Boot ID:                    bff1c808-788e-48b8-a789-4fee4e800554
  Kernel Version:             3.10.0-1062.9.1.el7.x86_64
  OS Image:                   CentOS Linux 7 (Core)
  Operating System:           linux
  Architecture:               amd64
  Container Runtime Version:  docker://19.3.5
  Kubelet Version:            v1.17.2
  Kube-Proxy Version:         v1.17.2
PodCIDR:                      10.244.0.0/24
PodCIDRs:                     10.244.0.0/24
Non-terminated Pods:          (8 in total)
  Namespace                   Name                                      CPU Requests  CPU Limits  Memory Requests  Memory Limits  AGE
  ---------                   ----                                      ------------  ----------  ---------------  -------------  ---
  kube-system                 coredns-6955765f44-d9fb4                  100m (5%)     0 (0%)      70Mi (0%)        170Mi (2%)     15m
  kube-system                 coredns-6955765f44-l7xrk                  100m (5%)     0 (0%)      70Mi (0%)        170Mi (2%)     15m
  kube-system                 etcd-kubeadm-fedora                       0 (0%)        0 (0%)      0 (0%)           0 (0%)         15m
  kube-system                 kube-apiserver-kubeadm-fedora             250m (12%)    0 (0%)      0 (0%)           0 (0%)         15m
  kube-system                 kube-controller-manager-kubeadm-fedora    200m (10%)    0 (0%)      0 (0%)           0 (0%)         15m
  kube-system                 kube-flannel-ds-amd64-v6m2w               100m (5%)     100m (5%)   50Mi (0%)        50Mi (0%)      15m
  kube-system                 kube-proxy-d65kl                          0 (0%)        0 (0%)      0 (0%)           0 (0%)         15m
  kube-system                 kube-scheduler-kubeadm-fedora             100m (5%)     0 (0%)      0 (0%)           0 (0%)         15m
Allocated resources:
  (Total limits may be over 100 percent, i.e., overcommitted.)
  Resource           Requests    Limits
  --------           --------    ------
  cpu                850m (42%)  100m (5%)
  memory             190Mi (2%)  390Mi (5%)
  ephemeral-storage  0 (0%)      0 (0%)
Events:
  Type    Reason                   Age                From                        Message
  ----    ------                   ----               ----                        -------
  Normal  NodeHasSufficientMemory  16m (x6 over 16m)  kubelet, kubeadm-fedora     Node kubeadm-fedora status is now: NodeHasSufficientMemory
  Normal  NodeHasNoDiskPressure    16m (x5 over 16m)  kubelet, kubeadm-fedora     Node kubeadm-fedora status is now: NodeHasNoDiskPressure
  Normal  NodeHasSufficientPID     16m (x5 over 16m)  kubelet, kubeadm-fedora     Node kubeadm-fedora status is now: NodeHasSufficientPID
  Normal  NodeAllocatableEnforced  16m                kubelet, kubeadm-fedora     Updated Node Allocatable limit across pods
  Normal  Starting                 15m                kubelet, kubeadm-fedora     Starting kubelet.
  Normal  NodeHasSufficientMemory  15m                kubelet, kubeadm-fedora     Node kubeadm-fedora status is now: NodeHasSufficientMemory
  Normal  NodeHasNoDiskPressure    15m                kubelet, kubeadm-fedora     Node kubeadm-fedora status is now: NodeHasNoDiskPressure
  Normal  NodeHasSufficientPID     15m                kubelet, kubeadm-fedora     Node kubeadm-fedora status is now: NodeHasSufficientPID
  Normal  NodeAllocatableEnforced  15m                kubelet, kubeadm-fedora     Updated Node Allocatable limit across pods
  Normal  Starting                 15m                kube-proxy, kubeadm-fedora  Starting kube-proxy.
  Normal  NodeReady                15m                kubelet, kubeadm-fedora     Node kubeadm-fedora status is now: NodeReady

$ kubectl get nodes
NAME             STATUS   ROLES    AGE   VERSION
kubeadm-fedora   Ready    master   17m   v1.17.2

$ kubectl get pods -A
NAMESPACE     NAME                                     READY   STATUS    RESTARTS   AGE
kube-system   coredns-6955765f44-d9fb4                 1/1     Running   0          17m
kube-system   coredns-6955765f44-l7xrk                 1/1     Running   0          17m
kube-system   etcd-kubeadm-fedora                      1/1     Running   0          17m
kube-system   kube-apiserver-kubeadm-fedora            1/1     Running   0          17m
kube-system   kube-controller-manager-kubeadm-fedora   1/1     Running   0          17m
kube-system   kube-flannel-ds-amd64-v6m2w              1/1     Running   0          17m
kube-system   kube-proxy-d65kl                         1/1     Running   0          17m
kube-system   kube-scheduler-kubeadm-fedora            1/1     Running   0          17m


来源: stackexchange

问:
.toString not encoding bytes to utf8 text?
I am trying to encrypt a string and then decrypt it. However, the conversion from bytes to text isn't working properly.

Code:

```<code>var cjs = require("crypto-js");
const fs = require("file-system");

var text1 = "Some text to be encrypted";

var ctext = cjs.AES.encrypt(text1, "key 123").toString();

var bytes = cjs.AES.decrypt(ctext, "key 123");

var uctext = bytes.toString();
console.log(bytes + "   "+uctext);
//console.log("\n\n\n\n\n\n" + uctext);
console.log(text1 === uctext);
</code>```

The code outputs bytes on both "sides" and the variable that is supposed to be equal to the original text is still just bytes.

答:
You need to do this const uctext = bytes.toString(cjs.enc.Utf8);. Basically convert it to utf before comparing.

full code

```<code>const cjs = require("crypto-js");

const text1 = "Some text to be encrypted";

const ctext = cjs.AES.encrypt(text1, "key 123").toString();

const bytes = cjs.AES.decrypt(ctext, "key 123");

const uctext = bytes.toString(cjs.enc.Utf8);
console.log(`${bytes }   ${uctext}`);
// console.log("\n\n\n\n\n\n" + uctext);
console.log(text1 === uctext);

</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to encrypt a string and then decrypt it. However, the conversion from bytes to text isn't working properly.

Code:

var cjs = require("crypto-js");
const fs = require("file-system");

var text1 = "Some text to be encrypted";

var ctext = cjs.AES.encrypt(text1, "key 123").toString();

var bytes = cjs.AES.decrypt(ctext, "key 123");

var uctext = bytes.toString();
console.log(bytes + "   "+uctext);
//console.log("\n\n\n\n\n\n" + uctext);
console.log(text1 === uctext);

The code outputs bytes on both "sides" and the variable that is supposed to be equal to the original text is still just bytes.

Body:
You need to do this const uctext = bytes.toString(cjs.enc.Utf8);. Basically convert it to utf before comparing.

full code

const cjs = require("crypto-js");

const text1 = "Some text to be encrypted";

const ctext = cjs.AES.encrypt(text1, "key 123").toString();

const bytes = cjs.AES.decrypt(ctext, "key 123");

const uctext = bytes.toString(cjs.enc.Utf8);
console.log(`${bytes }   ${uctext}`);
// console.log("\n\n\n\n\n\n" + uctext);
console.log(text1 === uctext);


问:
Use an Email Template from a CakePHP Plugin
I have a CakePHP Shell Script that's sending an email. This script is contained in a CakePHP plugin (foo).

Setting the Email Template as

```<code>$this->Email->template = "foo/email_template_name";
</code>```

Does not work, the email sends successfully, however the email just says

```<code>Not Found: /path_to_app/app/views/elements/email/html/foo/email_template_name.ctp
</code>```

I have verified that the template is named correctly and does exist.

Minor Notes:

```<code>$this->Email->sendAs = "both";
</code>```

If the template is moved to /path_to_app/app/views/elements/email/html/foo/email_template_name.ctp
it does work correctly. However I was hoping to ship this as much as possible as a self contained email including the templates in the plugin itself.

答:
Please post all your code for $this->Email.

Check:

```<code>$this->Email->sendAs = 'html';
</code>```

Have you tried

```<code>$this->Email->template = "email_template_name";
</code>```

and moving the template to

```<code>/path_to_app/app/views/elements/email/html/email_template_name.ctp
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a CakePHP Shell Script that's sending an email. This script is contained in a CakePHP plugin (foo).

Setting the Email Template as

$this->Email->template = "foo/email_template_name";

Does not work, the email sends successfully, however the email just says

Not Found: /path_to_app/app/views/elements/email/html/foo/email_template_name.ctp

I have verified that the template is named correctly and does exist.

Minor Notes:

$this->Email->sendAs = "both";

If the template is moved to /path_to_app/app/views/elements/email/html/foo/email_template_name.ctp
it does work correctly. However I was hoping to ship this as much as possible as a self contained email including the templates in the plugin itself.

Body:
Please post all your code for $this->Email.

Check:

$this->Email->sendAs = 'html';

Have you tried

$this->Email->template = "email_template_name";

and moving the template to

/path_to_app/app/views/elements/email/html/email_template_name.ctp


问:
Find the last file name in python
I have same file name eg: filename1, filename2 , filename3, filename4 ..... filename10

I want to find last file of that specific name
over here last file name is filename10

```<code>import os
import datetime
import re

files = []
for file in os.listdir("C:\\Users\\Mayur Pawar\\Desktop\\FTP work"):
    if file.endswith(".csv"):
        files.append(file)
#s = sorted(files)

#print(files)

sorted(files)
</code>```

答:
you can use the built-in function max:

```<code>import re

last_file = max(files, key=lambda x: int(re.search(r'\d+', x).group()))
</code>```

Title: Find the last file name in python

Body:
I have same file name eg: filename1, filename2 , filename3, filename4 ..... filename10

I want to find last file of that specific name
over here last file name is filename10

import os
import datetime
import re

files = []
for file in os.listdir("C:\\Users\\Mayur Pawar\\Desktop\\FTP work"):
    if file.endswith(".csv"):
        files.append(file)
#s = sorted(files)

#print(files)

sorted(files)

Body:
you can use the built-in function max:

import re

last_file = max(files, key=lambda x: int(re.search(r'\d+', x).group()))


问:
What is actually use of non escaping closures?
If a function can return a value itself then why need to call non escaping closure to return value?
Consider following example </p>

```<code> func add(a: Int, b: Int, completion: (Int) -> ()) {
        let addition = a + b
        completion(addition)
 }
</code>```

答:
For example, a and b parameters must be a positive numbers by some reason. There are 3 way to workaroud this case:

1) You can add this check in a function that calls add. If you do so you will repeat this code any time before add calling. It's a bad idea because of code duplication; 2) You can add this check in the add method and return an error to a closure. In any closure you have to handle this error even if you don't want to execute any code at this case. So it's not a good idea too; 3) You can add this check in the add method and return a boolean value showing a correctness of parameters. If parameters is correct you calculate a result and call the closure like in this code:

```<code>func add(a: Int, b: Int, completion: (Int) -> ()) -> Bool {
    guard a > 0, b > 0 else {
      return false
    }

    let addition = a + b
    completion(addition)

    return true
}

if !add(a: someA, b: someB, completion: {sum in print(sum)}) {
  print("Wrong numbers!")
}
</code>```

Body:
If a function can return a value itself then why need to call non escaping closure to return value?
Consider following example

 func add(a: Int, b: Int, completion: (Int) -> ()) {
        let addition = a + b
        completion(addition)
 }

Body:
For example, a and b parameters must be a positive numbers by some reason. There are 3 way to workaroud this case:

1) You can add this check in a function that calls add. If you do so you will repeat this code any time before add calling. It's a bad idea because of code duplication; 2) You can add this check in the add method and return an error to a closure. In any closure you have to handle this error even if you don't want to execute any code at this case. So it's not a good idea too; 3) You can add this check in the add method and return a boolean value showing a correctness of parameters. If parameters is correct you calculate a result and call the closure like in this code:

func add(a: Int, b: Int, completion: (Int) -> ()) -> Bool {
    guard a > 0, b > 0 else {
      return false
    }

    let addition = a + b
    completion(addition)

    return true
}

if !add(a: someA, b: someB, completion: {sum in print(sum)}) {
  print("Wrong numbers!")
}


问:
aspnet_compiler and msbuild.exe
I am pretty new to msbuild and aspnet_compiler.

I am using aspnet_compiler to compile web application project. Now I just saw the MSBuild.exe and noticed that its builds my website into the /mywebsite/precompiledWeb folder. Now why do I need to use MSBuild.exe? Can't I directly use the aspnet_compiler to see if my website can be built properly?

(Not sure if I explained it very well).

答:
msbuild.exe is usually used to build projects and its dependencies. When you have a web application project with a project file, vs can use this to build not only your web project but all the dependencies involved. This would only build your source code files, not the markup files (.aspx,.ascx,.etc).

aspnet_compiler is meant to build a web site project that doesn't have a project file. This said, you can also use it to make sure your markup files are also built for your web application project.

Title: aspnet_compiler and msbuild.exe


问:
Should I avoid tail recursion in Prolog and in general?
I'm working through "Learn Prolog now" online book for fun.

I'm trying to write a predicate that goes through each member of a list and adds one to it, using accumulators. I have already done it easily without tail recursion.

```<code>addone([],[]).
addone([X|Xs],[Y|Ys]) :- Y is X+1, addone(Xs,Ys).
</code>```

But I have read that it is better to avoid this type of recursion for performance reasons. Is this true? Is it considered 'good practice' to use tail recursion always? Will it be worth the effort to use accumulators to get into a good habit?

I have tried to change this example into using accumulators, but it reverses the list. How can I avoid this?

```<code>accAddOne([X|Xs],Acc,Result) :- Xnew is X+1, accAddOne(Xs,[Xnew|Acc],Result).
accAddOne([],A,A).
addone(List,Result) :- accAddOne(List,[],Result).
</code>```

答:
In contrast to so some other programming languages, certain Prolog implementations are well suited for tail recursive programs. Tail recursion can be handled as a special case of last call optimization (LCO). For example this here in Java doesn't work:

```<code>public static boolean count(int n) {
    if (n == 0) {
        return true;
    } else {
        return count(n-1);
    }
}

public static void main(String[] args) {
    System.out.println("count(1000)="+count(1000));
    System.out.println("count(1000000)="+count(1000000));
}
</code>```

The result will be:

```<code>count(1000)=true
Exception in thread "main" java.lang.StackOverflowError
    at protect.Count.count(Count.java:9)
    at protect.Count.count(Count.java:9)
</code>```

On the other hand major Prolog implementations don't have any problem with it:

```<code> ?- [user].
 count(0) :- !.
 count(N) :- M is N-1, count(M).
 ^D
</code>```

The result will be:

```<code>?- count(1000).
true.
?- count(1000000).
true.
</code>```

The reason Prolog systems can do that, is that their execution is most often anyway trampolin style, and last call optimization is then a matter of choice point elimination and environment trimming. Environment trimming was already documented in early WAM.

But yes, debugging might be a problem.

Body:
I'm working through "Learn Prolog now" online book for fun.

I'm trying to write a predicate that goes through each member of a list and adds one to it, using accumulators. I have already done it easily without tail recursion.

addone([],[]).
addone([X|Xs],[Y|Ys]) :- Y is X+1, addone(Xs,Ys).

But I have read that it is better to avoid this type of recursion for performance reasons. Is this true? Is it considered 'good practice' to use tail recursion always? Will it be worth the effort to use accumulators to get into a good habit?

I have tried to change this example into using accumulators, but it reverses the list. How can I avoid this?

accAddOne([X|Xs],Acc,Result) :- Xnew is X+1, accAddOne(Xs,[Xnew|Acc],Result).
accAddOne([],A,A).
addone(List,Result) :- accAddOne(List,[],Result).

Body:
In contrast to so some other programming languages, certain Prolog implementations are well suited for tail recursive programs. Tail recursion can be handled as a special case of last call optimization (LCO). For example this here in Java doesn't work:

public static boolean count(int n) {
    if (n == 0) {
        return true;
    } else {
        return count(n-1);
    }
}

public static void main(String[] args) {
    System.out.println("count(1000)="+count(1000));
    System.out.println("count(1000000)="+count(1000000));
}

The result will be:

count(1000)=true
Exception in thread "main" java.lang.StackOverflowError
    at protect.Count.count(Count.java:9)
    at protect.Count.count(Count.java:9)

On the other hand major Prolog implementations don't have any problem with it:

 ?- [user].
 count(0) :- !.
 count(N) :- M is N-1, count(M).
 ^D

The result will be:

?- count(1000).
true.
?- count(1000000).
true.

The reason Prolog systems can do that, is that their execution is most often anyway trampolin style, and last call optimization is then a matter of choice point elimination and environment trimming. Environment trimming was already documented in early WAM.

But yes, debugging might be a problem.


问:
How does COUNT work with multiple streams in XREADGROUP?
I want to use the Redis XREADGROUP command to consume messages from multiple Redis streams. What does the COUNT parameter mean in such cases (i.e. is it the total number of messages, or a number of messages per stream)? Also, is it possible to read exactly one message with this scenario?

答:
COUNT is the maximum number of elements per stream. The XREADGROUP command is a special version of the XREAD command with support for consumer groups. So the documentation for XREAD applies.

You can set COUNT as 1, then you'll get up to 1 element per stream in the command.

If you don't set COUNT, you get all messages available per stream.


问:
Why functions locals and arguments are pushed to the stack?
how functions are stored on memory i.e : the data segment as normal variables expressions or on the code segment
in either one What is pushed to the stack
  a pointer? or the whole function and why do we need to push the local variables and arguments too if they are already stored in the data segment ?</p>

答:
For example, in C/C++ whenever a function is executed, the execution scope is in stack memory i.e. Memory is allocated for that function in stack. It means the local variables within it including arguments are only available inside that stack unless you pass the argument as pass by address/reference instead of pass by value.
In case of pass by reference/address, we use pointer in order to access the variable present outside of this function.

Hope it answers your question. If not, please provide more details.


问:
Finding a min() value on each row using an arrayformula() within Google Sheets
I'm kind of in a pickle with a sheet I've been working on, I was looking for some clarification. For some reason my old account is gone that Ive for years :(, I apologize.

I'm trying get a min value for each row I've added data in. There is 2 columns where I need to convert the data first, and then find the lowest value for for all 3 columns for each row.

I've tried multiple things and only entering the formula I've created for each row works perfectly.
For Instance:

=MIN( IF(E124 > 0, E124*$E$6), IF(F124 > 0, F124*$F$6), IF(G124 > 0, G124) )

I've tried to use other examples, however, I am not familiar with QUERY. Trying to do simple calculations (adding) within the formula is confusing. Example I've tried using:

```<code>=QUERY(TRANSPOSE(QUERY(TRANSPOSE(A1:C),
 "select "&REGEXREPLACE(JOIN( , ARRAYFORMULA(IF(LEN(A1:A&B1:B&C1:C),
 "min(Col"&ROW(A1:A)-ROW(A1)+1&"),", ""))), ".\z", "")&"")),
 "select Col2")
</code>```

That has multiple problems when adding it. I want to ignore empty cells and text like headers. It will not write over text, and does not execute (gives me an error about overwriting values).

I've tried writing an =arrayformula but does not like calculating the min value. It does do the calculations for the rows.

```<code>=ArrayFormula(IF(ISBLANK({E8:E;F8:8;G8:8}), "", added my formula here))
</code>```

Down below was something I've worked on for hours, I believe the problem is selecting the ranges inside the MIN function that is causing the problems

```<code>=arrayformula(IF(LEN(E8:G)<>0, MIN( IF(E8:E > 0, E8:E*$E$6), IF(F8:F > 0, F8:F*$F$6), IF(G8:G > 0, G124) ),)
</code>```

If there's a way to do this, I'd really appreciate some help

LINK: a viewable version of a sample I made as my actual sheet is over 500 lines long.
https://docs.google.com/spreadsheets/d/133LJHY3s45ZyxWq0PWew1KikbyNE4MTt-wOeWHBrZY0/edit?usp=sharing

答:
try (which works for all rows till bottom):

```<code>=ARRAYFORMULA(TEXT(SUBSTITUTE(QUERY(TRANSPOSE(QUERY(TRANSPOSE(
 IF(E3:G<>"", {E3:E*M5, F3:F*N5, G3:G}, 999^99)),
 "select "&TEXTJOIN(",", 1,
 "min(Col"&ROW(A3:A)-ROW(A3)+1&")")&"")),
 "select Col2", 0), 999^99, ), "$#,###.00"))
</code>```

Body:
I'm kind of in a pickle with a sheet I've been working on, I was looking for some clarification. For some reason my old account is gone that Ive for years :(, I apologize.

I'm trying get a min value for each row I've added data in. There is 2 columns where I need to convert the data first, and then find the lowest value for for all 3 columns for each row.

I've tried multiple things and only entering the formula I've created for each row works perfectly.
For Instance:

=MIN( IF(E124 > 0, E124*$E$6), IF(F124 > 0, F124*$F$6), IF(G124 > 0, G124) )

I've tried to use other examples, however, I am not familiar with QUERY. Trying to do simple calculations (adding) within the formula is confusing. Example I've tried using:

=QUERY(TRANSPOSE(QUERY(TRANSPOSE(A1:C),
 "select "&REGEXREPLACE(JOIN( , ARRAYFORMULA(IF(LEN(A1:A&B1:B&C1:C),
 "min(Col"&ROW(A1:A)-ROW(A1)+1&"),", ""))), ".\z", "")&"")),
 "select Col2")

That has multiple problems when adding it. I want to ignore empty cells and text like headers. It will not write over text, and does not execute (gives me an error about overwriting values).

I've tried writing an =arrayformula but does not like calculating the min value. It does do the calculations for the rows.

=ArrayFormula(IF(ISBLANK({E8:E;F8:8;G8:8}), "", added my formula here))

Down below was something I've worked on for hours, I believe the problem is selecting the ranges inside the MIN function that is causing the problems

=arrayformula(IF(LEN(E8:G)<>0, MIN( IF(E8:E > 0, E8:E*$E$6), IF(F8:F > 0, F8:F*$F$6), IF(G8:G > 0, G124) ),)

If there's a way to do this, I'd really appreciate some help

LINK: a viewable version of a sample I made as my actual sheet is over 500 lines long.
https://docs.google.com/spreadsheets/d/133LJHY3s45ZyxWq0PWew1KikbyNE4MTt-wOeWHBrZY0/edit?usp=sharing

Body:
try (which works for all rows till bottom):

=ARRAYFORMULA(TEXT(SUBSTITUTE(QUERY(TRANSPOSE(QUERY(TRANSPOSE(
 IF(E3:G<>"", {E3:E*M5, F3:F*N5, G3:G}, 999^99)),
 "select "&TEXTJOIN(",", 1,
 "min(Col"&ROW(A3:A)-ROW(A3)+1&")")&"")),
 "select Col2", 0), 999^99, ), "$#,###.00"))


问:
Groovy way of null-checking constructor parameter
I want to inject non-null values into my groovy class

```<code>class MyClass {
    private final String foo
    private final Integer bar

    MyClass(String foo, Integer bar) {
        // wanted ctr body
    }
    ...
}
</code>```

Within the constructor, I want to assign the params to the respective fields AND prevent null values.

I wonder if there is a groovier way of doing this than the quite verbose

```<code>assert foo != null
assert bar != null
this.foo = foo
this.bar = bar
</code>```

or

```<code>this.foo = Objects.requireNonNull foo
this.bar = Objects.requireNonNull bar
</code>```

答:
If you use Groovy 3, you can use @NullCheck annotation that adds defensive conditions constructor (or any methods) arguments.

import groovy.transform.NullCheck

@NullCheck
class MyClass {
    private final String foo
    private final Integer bar

    MyClass(String foo, Integer bar) {
        this.foo = foo
        this.bar = bar
    }
}

// Examples:
new MyClass("test", null) // throws IllegalArgumentException("bar cannot be null")

new MyClass(null, "test") // throws IllegalArgumentException("foo cannot be null")
```

When you add @NullCheck on the class definition level, defensive null-check will be applied to all constructors and methods. Alternatively, you can add @NullCheck annotation to the methods (or constructors) you want to use this null-check only.

Before Groovy 3 such defensive checks have to be implemented manually.

Body:
I want to inject non-null values into my groovy class

class MyClass {
    private final String foo
    private final Integer bar

    MyClass(String foo, Integer bar) {
        // wanted ctr body
    }
    ...
}

Within the constructor, I want to assign the params to the respective fields AND prevent null values.

I wonder if there is a groovier way of doing this than the quite verbose

assert foo != null
assert bar != null
this.foo = foo
this.bar = bar

or

this.foo = Objects.requireNonNull foo
this.bar = Objects.requireNonNull bar

Body:
If you use Groovy 3, you can use @NullCheck annotation that adds defensive conditions constructor (or any methods) arguments.

import groovy.transform.NullCheck

@NullCheck
class MyClass {
    private final String foo
    private final Integer bar

    MyClass(String foo, Integer bar) {
        this.foo = foo
        this.bar = bar
    }
}

// Examples:
new MyClass("test", null) // throws IllegalArgumentException("bar cannot be null")

new MyClass(null, "test") // throws IllegalArgumentException("foo cannot be null")

When you add @NullCheck on the class definition level, defensive null-check will be applied to all constructors and methods. Alternatively, you can add @NullCheck annotation to the methods (or constructors) you want to use this null-check only.

Before Groovy 3 such defensive checks have to be implemented manually.


问:
python mechanize to access Sharepoint website
I'm trying to access Sharepoint using mechanize but i got a 401 error. Here's the code i'm using:

```<code>import mechanize

url = "http://sharepoint:8080/foo/bar/foobar.aspx"

br.addheaders = [('User-agent', 'Mozilla/4.0(compatible; MSIE 7.0b; Windows NT 6.0)')]
br.add_password(url, 'domain\\user', 'myPassword')
r = br.open(url)
html = r.read()
</code>```

Did i miss anything?

答:
Try with:

```<code>br.addheaders = [('User-agent', 'Mozilla/4.0(compatible; MSIE 7.0b; Windows NT 6.0)'), ('Authorization', 'Basic %s:%s' % ('domain\\user', 'myPassword'))]
</code>```

instead of

```<code>br.addheaders = [('User-agent', 'Mozilla/4.0(compatible; MSIE 7.0b; Windows NT 6.0)')]
</code>```

This should work if your sharepoint server provides Basic Auth.

Body:
I'm trying to access Sharepoint using mechanize but i got a 401 error. Here's the code i'm using:

import mechanize

url = "http://sharepoint:8080/foo/bar/foobar.aspx"

br.addheaders = [('User-agent', 'Mozilla/4.0(compatible; MSIE 7.0b; Windows NT 6.0)')]
br.add_password(url, 'domain\\user', 'myPassword')
r = br.open(url)
html = r.read()

Did i miss anything?

Body:
Try with:

br.addheaders = [('User-agent', 'Mozilla/4.0(compatible; MSIE 7.0b; Windows NT 6.0)'), ('Authorization', 'Basic %s:%s' % ('domain\\user', 'myPassword'))]

instead of

br.addheaders = [('User-agent', 'Mozilla/4.0(compatible; MSIE 7.0b; Windows NT 6.0)')]

This should work if your sharepoint server provides Basic Auth.


问:
bootstrap dropdown for navbar not working (in angular)
I have installed :popper.js, bootstrap and jquery.
My angular json file is:

```<code>"styles": [
              "src/styles.css",
              "../node_modules/bootstrap/dist/css/bootstrap.min.css"
           ],
"scripts": [
              "../node_modules/jquery/dist/jquery.min.js",
              "../node_modules/popper.js/dist/umd/popper.min.js",
              "../node_modules/bootstrap/dist/js/bootstrap.min.js"
           ]
</code>```

In the styles.css file I import:
@import '~bootstrap/dist/css/bootstrap.min.css';.

Even though I do these things my dropdown menu in the navbar is not working: my html code is:

```<code><nav class="navbar navbar-expand-lg navbar-light bg-light">
  <a class="navbar-brand" href="#">Navbar</a>
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>

  <div class="collapse navbar-collapse" id="navbarSupportedContent">
    <ul class="navbar-nav mr-auto">
      <li class="nav-item active">
        <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Link</a>
      </li>
      <li class="nav-item dropdown">
        <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
          Dropdown
        </a>
        <div class="dropdown-menu" aria-labelledby="navbarDropdown">
          <a class="dropdown-item" href="#">Action</a>
          <a class="dropdown-item" href="#">Another action</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="#">Something else here</a>
        </div>
      </li>
      <li class="nav-item">
        <a class="nav-link disabled" href="#" tabindex="-1" aria-disabled="true">Disabled</a>
      </li>
    </ul>
    <form class="form-inline my-2 my-lg-0">
      <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search">
      <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
    </form>
  </div>
</nav>
</code>```

I got the code from : https://getbootstrap.com/docs/4.0/components/navbar/

Thank you in advance!

答:
I think you are setting path to access you styles and scripts.

Node Modules is inside you main project folder; therefore skip one folder only, you are skipping/jumping two folder(../)

```<code>    "styles": [
       "src/styles.css",
       "./node_modules/bootstrap/dist/css/bootstrap.min.css"
     ],
    "scripts": [
       "./node_modules/jquery/dist/jquery.min.js",
       "./node_modules/popper.js/dist/umd/popper.min.js",
       "./node_modules/bootstrap/dist/js/bootstrap.min.js"
     ]
</code>```

Body:
I have installed :popper.js, bootstrap and jquery.
My angular json file is:

"styles": [
              "src/styles.css",
              "../node_modules/bootstrap/dist/css/bootstrap.min.css"
           ],
"scripts": [
              "../node_modules/jquery/dist/jquery.min.js",
              "../node_modules/popper.js/dist/umd/popper.min.js",
              "../node_modules/bootstrap/dist/js/bootstrap.min.js"
           ]

In the styles.css file I import:
@import '~bootstrap/dist/css/bootstrap.min.css';.

Even though I do these things my dropdown menu in the navbar is not working: my html code is:

  Navbar
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

  </button>

        Home (current)

        Link

          Dropdown

          Action
          Another action

          Something else here

        Disabled

    <form class="form-inline my-2 my-lg-0">
      <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search">
      <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
    </form>

I got the code from : https://getbootstrap.com/docs/4.0/components/navbar/

Thank you in advance!

Body:
I think you are setting path to access you styles and scripts.

Node Modules is inside you main project folder; therefore skip one folder only, you are skipping/jumping two folder(../)

    "styles": [
       "src/styles.css",
       "./node_modules/bootstrap/dist/css/bootstrap.min.css"
     ],
    "scripts": [
       "./node_modules/jquery/dist/jquery.min.js",
       "./node_modules/popper.js/dist/umd/popper.min.js",
       "./node_modules/bootstrap/dist/js/bootstrap.min.js"
     ]


问:
What exactly happens when a character array is initialized with data larger than its size?
```<code>int main(void)
{

    char s[4] = "heloo"; // The character array is initialized with more data than its size

    printf("%s",s);
}
</code>```

The output is: helo�[�G�.

Why is the output in this format?

答:
The compiler shall issue an error because there are more initializers than the number of elements of the array and the redundant initializer is not the
terminating zero of the string literal.

From the C Standard (6.7.9 Initialization)

2 No initializer shall attempt to provide a value for an object not
  contained within the entity being initialized.

The one exclusion of this rule is regards character arrays when the terminating zero of a string literal can be excluded from initializers if the character array does not have a corresponding element.

14 An array of character type may be initialized by a character string
  literal or UTF−8 string literal, optionally enclosed in braces.
  Successive bytes of the string literal (including the terminating null
  character if there is room or if the array is of unknown size)
  initialize the elements of the array.

If the program was run then it has undefined behavior. The character array does not contain a string that is required when the conversion specifier %s is used.

Body:
int main(void)
{

    char s[4] = "heloo"; // The character array is initialized with more data than its size

    printf("%s",s);
}

The output is: helo�[�G�.

Why is the output in this format?


问:
How to clone Google Container Cluster / Kubernetes cluster?
As in title. I want to clone (create a copy of existing cluster).

If it's not possible to copy/clone Google Container Engine cluster, then how to clone Kubernetes cluster?

If that's not possible, is there a way to dump the whole cluster config?

Note:

I try to modify the cluster's configs by calling:

```<code>kubectl apply -f some-resource.yaml
</code>```

But nothing stops me/other employee modifying the cluster by running:

```<code>kubectl edit service/resource
</code>```

Or setting properties from command line kubectl calls.

答:
You can now create/clone an existing cluster,
On the Clusters page, click on create cluster and choose an existing cluster. But remember, this will not clone the api-resources you may have to use a third party tool such as Velero to help you backup the resources.

Here are some useful links

Cluster Creation

Velero

Medium Article on How to use Velero

Body:
As in title. I want to clone (create a copy of existing cluster).

If it's not possible to copy/clone Google Container Engine cluster, then how to clone Kubernetes cluster?

If that's not possible, is there a way to dump the whole cluster config?

Note:

I try to modify the cluster's configs by calling:

kubectl apply -f some-resource.yaml

But nothing stops me/other employee modifying the cluster by running:

kubectl edit service/resource

Or setting properties from command line kubectl calls.


问:
puppet master not able to find configdir, how to fix this?
sudo puppet master --verbose --no-daemonize

When I ran above command

[root@puppetmaster bin]# sudo puppet master --verbose --no-daemonize
/usr/lib/ruby/site_ruby/1.8/puppet/settings.rb:1348:in convert': Error converting value for param 'basemodulepath': Could not find value for $configdir (Puppet::Settings::InterpolationError)
        from /usr/lib/ruby/site_ruby/1.8/puppet/settings.rb:1337:ingsub'
        from /usr/lib/ruby/site_ruby/1.8/puppet/settings.rb:1337:in convert'
        from /usr/lib/ruby/site_ruby/1.8/puppet/settings.rb:1315:ininterpolate'
        from /usr/lib/ruby/site_ruby/1.8/puppet/settings.rb:1060:in value'
        from /usr/lib/ruby/site_ruby/1.8/puppet/settings.rb:121:in[]'
        from /usr/lib/ruby/site_ruby/1.8/puppet.rb:184:in base_context'
        from /usr/lib/ruby/site_ruby/1.8/puppet/application.rb:356:inrun'
        from /usr/lib/ruby/site_ruby/1.8/puppet/util/command_line.rb:146:in run'
        from /usr/lib/ruby/site_ruby/1.8/puppet/util/command_line.rb:92:inexecute'
        from /usr/bin/puppet:8

Even I created a environment variable now with $configdir with value /etc/puppet, but still same issue.

Please suggest how to rectify this

答:
Puppet does not ordinarily provide or rely on any "configdir" setting, but it does provide and rely on confdir.  Since Puppet is complaining about being able to determine the value of a different parameter, basemodulepath, I infer that,

You are using Puppet 3.8 with directory environments enabled (Ruby 1.8 is not supported in later versions, and basemodulepath is a directory environments thing), and

One of your environment.conf files erroneously specifies a value for its environment's basemodulepath in terms of $configdir instead of $confdir.

Note that Puppet 3.8 is obsolete and unsupported.  As I write this, the latest is Puppet 6.12.


问:
how to hide properties of class during serialization?
can i override function that is responsbile for serializing and Php class to an array/stdclass so that i can implement my own logic "like hiding certain attributes based on condition)</p>

```<code>class UserModel{
  $hidden = ['password'];

  function __construct(array $data) {
    foreach($data as $key=>$value)$this->$key = $value;
  }

}

$user = new UserModel(['id'=>1,'password'=>123]);

var_dump($user);
</code>```

答:
For a simple solution you can also use __sleep Magic Method.

https://www.php.net/manual/en/language.oop5.magic.php

```<code>class UserModel {
    protected $id;
    protected $password;
    protected $username;
    protected $email;

    public function __sleep(){
       return array('id','username','email');
    }
}
</code>```

Body:
can i override function that is responsbile for serializing and Php class to an array/stdclass so that i can implement my own logic "like hiding certain attributes based on condition)

class UserModel{
  $hidden = ['password'];

  function __construct(array $data) {
    foreach($data as $key=>$value)$this->$key = $value;
  }

}

$user = new UserModel(['id'=>1,'password'=>123]);

var_dump($user);

Body:
For a simple solution you can also use __sleep Magic Method.

https://www.php.net/manual/en/language.oop5.magic.php

class UserModel {
    protected $id;
    protected $password;
    protected $username;
    protected $email;

    public function __sleep(){
       return array('id','username','email');
    }
}


问:
tsconfig.json: Build:No inputs were found in config file
I have an ASP.NET core project and I'm getting this error when I try to build it:

```<code>error TS18003: Build:No inputs were found in config file 'Z:/Projects/client/ZV/src/ZV/Scripts/tsconfig.json'. Specified 'include' paths were '["**/*"]' and 'exclude' paths were '["../wwwroot/app","node_modules/*"]'.
1>         The command exited with code 1.
1>       Done executing task "VsTsc" -- FAILED.
</code>```

This is my tsconfig.json file:

```<code>{
  "compileOnSave": true,
  "compilerOptions": {
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "lib": [ "es5", "dom" ],
    "module": "commonjs",
    "moduleResolution": "node",
    "noEmitOnError": true,
    "noImplicitAny": false,
    "outDir": "../wwwroot/app/",
    "removeComments": false,
    "sourceMap": true,
    "target": "es6"
  },
  "exclude": [
    "../wwwroot/app",
    "node_modules/*"
  ]
}
</code>```

Is this a bug or am I doing something wrong? I did recently upgrade Visual Studio 2015 to update 3. Has anyone encountered this before?

答: If you are using the vs code for editing then try restarting the editor.This scenario fixed my issue.I think it's the issue with editor cache.</p>

Body:
I have an ASP.NET core project and I'm getting this error when I try to build it:

error TS18003: Build:No inputs were found in config file 'Z:/Projects/client/ZV/src/ZV/Scripts/tsconfig.json'. Specified 'include' paths were '["**/*"]' and 'exclude' paths were '["../wwwroot/app","node_modules/*"]'.
1>         The command exited with code 1.
1>       Done executing task "VsTsc" -- FAILED.

This is my tsconfig.json file:

{
  "compileOnSave": true,
  "compilerOptions": {
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "lib": [ "es5", "dom" ],
    "module": "commonjs",
    "moduleResolution": "node",
    "noEmitOnError": true,
    "noImplicitAny": false,
    "outDir": "../wwwroot/app/",
    "removeComments": false,
    "sourceMap": true,
    "target": "es6"
  },
  "exclude": [
    "../wwwroot/app",
    "node_modules/*"
  ]
}

Is this a bug or am I doing something wrong? I did recently upgrade Visual Studio 2015 to update 3. Has anyone encountered this before?


问:
Problem with @Autowired in JUnit Test on a Spring MVC project
Hi guys so here are my JUnit Test Class which doesn't get to autowire my DAO Class.
Bellow are my classes and the xml file for the MVC configuration:

```<code>
import java.util.List;

import org.springframework.stereotype.Component;

import com.luv2code.springdemo.entity.Address;

public interface AddressDAO {

    public List<Address> findAllAdrressesOfCustomer(int customerId);

}
</code>```

```<code>package com.luv2code.springdemo.dao;

import java.util.Arrays;
import java.util.List;

import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;

import com.luv2code.springdemo.entity.Address;

@Repository
public class AdrressDAOImpl implements AddressDAO {

    @Override
    public List<Address> findAllAdrressesOfCustomer(int customerId) {
        Address myAddress=new Address(6,"Mainstreet","12A","USA","Los Angeles","Los Angeles","41221") ;
        return Arrays.asList(myAddress);
    }

}
</code>```

Here my Junit class that I want to use in order to test my AdressDAOImpl class:

```<code>package com.luv2code.springdemo.test;

import static org.junit.Assert.assertTrue;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;

import com.luv2code.springdemo.dao.AddressDAO;
import com.luv2code.springdemo.dao.CustomerDAO;

@WebAppConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath*:spring-mvc-crud-demo-servlet_test.xml")
public class AddressDaoLayerTester {

    @Autowired
    AddressDAO myAddressDao;

    @Test
    public void testFindAllById() {
        assertTrue(!myAddressDao.findAllAdrressesOfCustomer(1).isEmpty());

    }

}

</code>```

and here my xml configuration file:

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd">

    <!-- Add support for component scanning -->
    <context:component-scan base-package="com.luv2code.springdemo" />

    <!-- Add support for conversion, formatting and validation support -->
    <mvc:annotation-driven/>

    <!-- Define Spring MVC view resolver -->
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/view/" />
        <property name="suffix" value=".jsp" />
    </bean>

    <!-- Step 1: Define Database DataSource / connection pool -->
    <bean id="myDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
          destroy-method="close">
        <property name="driverClass" value="com.mysql.jdbc.Driver" />
        <property name="jdbcUrl" value="jdbc:mysql://localhost:6703/my_first_db?useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true" />
        <property name="user" value="root" />
        <property name="password" value="24081983" />

        <!-- these are connection pool properties for C3P0 -->
        <property name="minPoolSize" value="5" />
        <property name="maxPoolSize" value="20" />
        <property name="maxIdleTime" value="30000" />
    </bean>

    <!-- Step 2: Setup Hibernate session factory -->
    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        <property name="dataSource" ref="myDataSource" />
        <property name="packagesToScan" value="com.luv2code.springdemo.entity" />
        <property name="hibernateProperties">
           <props>
              <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
              <prop key="hibernate.show_sql">true</prop>
           </props>
        </property>
   </bean>

    <!-- Step 3: Setup Hibernate transaction manager -->
    <bean id="myTransactionManager"
            class="org.springframework.orm.hibernate5.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"/>
    </bean>

    <!-- Step 4: Enable configuration of transactional behavior based on annotations -->
    <tx:annotation-driven transaction-manager="myTransactionManager" />

    <!-- Add support for reading web resources: css, images, js, etc ... -->
    <mvc:resources location="/resources/" mapping="/resources/**"></mvc:resources>

</beans>

</code>```

So now comes my Problem, when I go ahead and call the class AddressDaoLayerTester I get the following stacktrace:

```<code>org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'com.luv2code.springdemo.test.AddressDaoLayerTester': Unsatisfied dependency expressed through field 'myAddressDao'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.luv2code.springdemo.dao.AddressDAO' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:643)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:116)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:399)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1422)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:393)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:119)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83)
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:244)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:227)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:289)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:291)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:246)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:115)
    at org.junit.vintage.engine.execution.RunnerExecutor.execute(RunnerExecutor.java:40)
    at java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:183)
    at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:195)
    at java.base/java.util.Iterator.forEachRemaining(Iterator.java:133)
    at java.base/java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801)
    at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484)
    at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474)
    at java.base/java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:150)
    at java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:173)
    at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
    at java.base/java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:497)
    at org.junit.vintage.engine.VintageTestEngine.executeAllChildren(VintageTestEngine.java:80)
    at org.junit.vintage.engine.VintageTestEngine.execute(VintageTestEngine.java:71)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:229)
    at org.junit.platform.launcher.core.DefaultLauncher.lambda$execute$6(DefaultLauncher.java:197)
    at org.junit.platform.launcher.core.DefaultLauncher.withInterceptedStreams(DefaultLauncher.java:211)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:191)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:137)
    at org.eclipse.jdt.internal.junit5.runner.JUnit5TestReference.run(JUnit5TestReference.java:89)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:542)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:770)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:464)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:210)
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.luv2code.springdemo.dao.AddressDAO' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1695)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1253)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1207)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:640)
    ... 48 more
</code>```

I also provide here the structure of my project:

Obviously the stacktrace says that Spring can not autowire the AddressDAO class because he cannot find it, although it is there and it is correctly annotated.
Do you have any suggestion about the reasons that could cause this problem?

答: Your usage of classpath*: will silently return without any errors if it doesn't finds the file, may be it doesn't scans subdirectories and it couldn't find the xml. Try using classpath*:com/**/<filename>.xml

Body:
Hi guys so here are my JUnit Test Class which doesn't get to autowire my DAO Class.
Bellow are my classes and the xml file for the MVC configuration:

import java.util.List;

import org.springframework.stereotype.Component;

import com.luv2code.springdemo.entity.Address;

public interface AddressDAO {

    public List<Address> findAllAdrressesOfCustomer(int customerId);

}

package com.luv2code.springdemo.dao;

import java.util.Arrays;
import java.util.List;

import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;

import com.luv2code.springdemo.entity.Address;

@Repository
public class AdrressDAOImpl implements AddressDAO {

    @Override
    public List<Address> findAllAdrressesOfCustomer(int customerId) {
        Address myAddress=new Address(6,"Mainstreet","12A","USA","Los Angeles","Los Angeles","41221") ;
        return Arrays.asList(myAddress);
    }

}

Here my Junit class that I want to use in order to test my AdressDAOImpl class:

package com.luv2code.springdemo.test;

import static org.junit.Assert.assertTrue;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;

import com.luv2code.springdemo.dao.AddressDAO;
import com.luv2code.springdemo.dao.CustomerDAO;

@WebAppConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath*:spring-mvc-crud-demo-servlet_test.xml")
public class AddressDaoLayerTester {

    @Autowired
    AddressDAO myAddressDao;

    @Test
    public void testFindAllById() {
        assertTrue(!myAddressDao.findAllAdrressesOfCustomer(1).isEmpty());

    }

}

and here my xml configuration file:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd">

    <context:component-scan base-package="com.luv2code.springdemo" />

    <mvc:annotation-driven/>

    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/view/" />
        <property name="suffix" value=".jsp" />
    </bean>

    <bean id="myDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
          destroy-method="close">
        <property name="driverClass" value="com.mysql.jdbc.Driver" />
        <property name="jdbcUrl" value="jdbc:mysql://localhost:6703/my_first_db?useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true" />
        <property name="user" value="root" />
        <property name="password" value="24081983" />

        <property name="minPoolSize" value="5" />
        <property name="maxPoolSize" value="20" />
        <property name="maxIdleTime" value="30000" />
    </bean>

    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        <property name="dataSource" ref="myDataSource" />
        <property name="packagesToScan" value="com.luv2code.springdemo.entity" />
        <property name="hibernateProperties">
           <props>
              <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
              <prop key="hibernate.show_sql">true</prop>
           </props>
        </property>
   </bean>

    <bean id="myTransactionManager"
            class="org.springframework.orm.hibernate5.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"/>
    </bean>

    <tx:annotation-driven transaction-manager="myTransactionManager" />

    <mvc:resources location="/resources/" mapping="/resources/**"></mvc:resources>

</beans>

So now comes my Problem, when I go ahead and call the class AddressDaoLayerTester I get the following stacktrace:

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'com.luv2code.springdemo.test.AddressDaoLayerTester': Unsatisfied dependency expressed through field 'myAddressDao'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.luv2code.springdemo.dao.AddressDAO' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:643)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:116)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:399)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1422)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:393)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:119)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83)
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:244)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:227)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:289)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:291)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:246)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:115)
    at org.junit.vintage.engine.execution.RunnerExecutor.execute(RunnerExecutor.java:40)
    at java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:183)
    at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:195)
    at java.base/java.util.Iterator.forEachRemaining(Iterator.java:133)
    at java.base/java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801)
    at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484)
    at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474)
    at java.base/java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:150)
    at java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:173)
    at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
    at java.base/java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:497)
    at org.junit.vintage.engine.VintageTestEngine.executeAllChildren(VintageTestEngine.java:80)
    at org.junit.vintage.engine.VintageTestEngine.execute(VintageTestEngine.java:71)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:229)
    at org.junit.platform.launcher.core.DefaultLauncher.lambda$execute$6(DefaultLauncher.java:197)
    at org.junit.platform.launcher.core.DefaultLauncher.withInterceptedStreams(DefaultLauncher.java:211)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:191)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:137)
    at org.eclipse.jdt.internal.junit5.runner.JUnit5TestReference.run(JUnit5TestReference.java:89)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:542)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:770)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:464)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:210)
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.luv2code.springdemo.dao.AddressDAO' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1695)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1253)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1207)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:640)
    ... 48 more

I also provide here the structure of my project:

Obviously the stacktrace says that Spring can not autowire the AddressDAO class because he cannot find it, although it is there and it is correctly annotated.
Do you have any suggestion about the reasons that could cause this problem?


问:
Actionscript 3 Sound ioError Problem
i am having trouble with sound. i am loading it dynamically, url comes from flashvars.
App is working actually but stil gives error, unhandled ioError. but i already handled it.

`
        var sound:Sound = new Sound()

```<code>try{
    sound.load(new URLRequest(req));
} catch(e:IOError){
    trace("catch ioerror");
}
sound.addEventListener(IOErrorEvent.IO_ERROR, function(evt:IOErrorEvent):void { trace("error:",evt) } );

sound.addEventListener(Event.COMPLETE, function(e:Event):void{
    channel = sound.play(0,int.MAX_VALUE);
});`
</code>```

答: Just to rule it out, try commenting out the line channel = sound.play(0,int.MAX_VALUE); perhaps it is this that is throwing the error and not the load, and you have no catch around this.

Title: Actionscript 3 Sound ioError Problem

Body:
i am having trouble with sound. i am loading it dynamically, url comes from flashvars.
App is working actually but stil gives error, unhandled ioError. but i already handled it.

`
        var sound:Sound = new Sound()

try{
    sound.load(new URLRequest(req));
} catch(e:IOError){
    trace("catch ioerror");
}
sound.addEventListener(IOErrorEvent.IO_ERROR, function(evt:IOErrorEvent):void { trace("error:",evt) } );

sound.addEventListener(Event.COMPLETE, function(e:Event):void{
    channel = sound.play(0,int.MAX_VALUE);
});`


问:
Back Space Causes Crash in Calculator
When ever I press the Back Space button when there is no input, the Android Calculator app Crashes.
This code is written in Kotlin and the IDE is Android Studio and the BackSpace is labeled tvBack in MainActivity.kt in the Code below.

What should i do to Handle this crash?

```<code> //BACK
        tvBack.setOnClickListener{
            val string =tvResult.text.toString()
            val string2=tvExpression.text.toString()
            if(string.isEmpty()){
                tvExpression.text = string2.substring(0,string2.length-1)

            }else if(string2.isNotEmpty()){

                tvResult.text=""
            }else if(string2.isEmpty()){
                return@setOnClickListener
            }
</code>```

答:
Problem is this line:

```<code>tvExpression.text = string2.substring(0,string2.length-1)
</code>```

If your string2 is empty, string2.length is 0, so this line evaluates as

```<code>tvExpression.text = string2.substring(0,-1)
</code>```

So it's an invalid substring.

So before generating a substring you should first check if the string is not empty. You can do this by adding the following line after tvBack.setOnClickListener{:

```<code>if (string2.length == 0) return;
</code>```

// EDIT:
Please edit your code to the following:

```<code>    tvBack.setOnClickListener{
        val string =tvResult.text.toString()
        val string2=tvExpression.text.toString()
        if(string2.isNotEmpty()){
            tvExpression.text = string2.substring(0,string2.length-1)
            tvResult.text=""
        }
</code>```

The problem for your new error was, that you did your checks wrong.
You only want to generate and use a substring if the string is not empty. Your code did the opposite

Title: Back Space Causes Crash in Calculator

Body:
When ever I press the Back Space button when there is no input, the Android Calculator app Crashes.
This code is written in Kotlin and the IDE is Android Studio and the BackSpace is labeled tvBack in MainActivity.kt in the Code below.

What should i do to Handle this crash?

 //BACK
        tvBack.setOnClickListener{
            val string =tvResult.text.toString()
            val string2=tvExpression.text.toString()
            if(string.isEmpty()){
                tvExpression.text = string2.substring(0,string2.length-1)

            }else if(string2.isNotEmpty()){

                tvResult.text=""
            }else if(string2.isEmpty()){
                return@setOnClickListener
            }

Body:
Problem is this line:

tvExpression.text = string2.substring(0,string2.length-1)

If your string2 is empty, string2.length is 0, so this line evaluates as

tvExpression.text = string2.substring(0,-1)

So it's an invalid substring.

So before generating a substring you should first check if the string is not empty. You can do this by adding the following line after tvBack.setOnClickListener{:

if (string2.length == 0) return;

// EDIT:
Please edit your code to the following:

    tvBack.setOnClickListener{
        val string =tvResult.text.toString()
        val string2=tvExpression.text.toString()
        if(string2.isNotEmpty()){
            tvExpression.text = string2.substring(0,string2.length-1)
            tvResult.text=""
        }

The problem for your new error was, that you did your checks wrong.
You only want to generate and use a substring if the string is not empty. Your code did the opposite