问:
Kubernetes calico node CrashLoopBackOff
While there are some questions just like mine out there, the fixes do not work for me.
I'm using the kubernetes v1.9.3 binaries and using flannel and calico to setup a kubernetes cluster. After applying calico yaml files it gets stuck on creating the second pod.
What am I doing wrong? The logs aren't really clear in saying what's wrong

kubectl get pods --all-namespaces

```<code>root@kube-master01:/home/john/cookem/kubeadm-ha# kubectl logs calico-node-
n87l7 --namespace=kube-system
Error from server (BadRequest): a container name must be specified for pod
calico-node-n87l7, choose one of: [calico-node install-cni]
root@kube-master01:/home/john/cookem/kubeadm-ha# kubectl logs calico-node-
n87l7 --namespace=kube-system install-cni
Installing any TLS assets from /calico-secrets
cp: can't stat '/calico-secrets/*': No such file or directory
</code>```

kubectl describe pod calico-node-n87l7 returns

```<code>Name:         calico-node-n87l7
Namespace:    kube-system
Node:         kube-master01/10.100.102.62
Start Time:   Thu, 22 Feb 2018 15:21:38 +0100
Labels:       controller-revision-hash=653023576
              k8s-app=calico-node
              pod-template-generation=1
Annotations:  scheduler.alpha.kubernetes.io/critical-pod=
              scheduler.alpha.kubernetes.io/tolerations=[{"key": "dedicated", "value": "master", "effect": "NoSchedule" },
 {"key":"CriticalAddonsOnly", "operator":"Exists"}]

Status:         Running
IP:             10.100.102.62
Controlled By:  DaemonSet/calico-node
Containers:
  calico-node:
    Container ID:   docker://6024188a667d98a209078b6a252505fa4db42124800baaf3a61e082ae2476147
    Image:          quay.io/calico/node:v3.0.1
    Image ID:       docker-pullable://quay.io/calico/node@sha256:e32b65742e372e2a4a06df759ee2466f4de1042e01588bea4d4df3f6d26d0581
    Port:           <none>
    State:          Running
      Started:      Thu, 22 Feb 2018 15:21:40 +0100
    Ready:          True
    Restart Count:  0
    Requests:
      cpu:      250m
    Liveness:   http-get http://:9099/liveness delay=10s timeout=1s period=10s #success=1 #failure=6
    Readiness:  http-get http://:9099/readiness delay=0s timeout=1s period=10s #success=1 #failure=3
    Environment:
      ETCD_ENDPOINTS:                     <set to the key 'etcd_endpoints' of config map 'calico-config'>  Optional: false
      CALICO_NETWORKING_BACKEND:          <set to the key 'calico_backend' of config map 'calico-config'>  Optional: false
      CLUSTER_TYPE:                       k8s,bgp
      CALICO_DISABLE_FILE_LOGGING:        true
      CALICO_K8S_NODE_REF:                 (v1:spec.nodeName)
      FELIX_DEFAULTENDPOINTTOHOSTACTION:  ACCEPT
      CALICO_IPV4POOL_CIDR:               10.244.0.0/16
      CALICO_IPV4POOL_IPIP:               Always
      FELIX_IPV6SUPPORT:                  false
      FELIX_LOGSEVERITYSCREEN:            info
      FELIX_IPINIPMTU:                    1440
      ETCD_CA_CERT_FILE:                  <set to the key 'etcd_ca' of config map 'calico-config'>    Optional: false
      ETCD_KEY_FILE:                      <set to the key 'etcd_key' of config map 'calico-config'>   Optional: false
      ETCD_CERT_FILE:                     <set to the key 'etcd_cert' of config map 'calico-config'>  Optional: false
      IP:                                 autodetect
      IP_AUTODETECTION_METHOD:            can-reach=10.100.102.0
      FELIX_HEALTHENABLED:                true
    Mounts:
      /calico-secrets from etcd-certs (rw)
      /lib/modules from lib-modules (ro)
      /var/run/calico from var-run-calico (rw)
      /var/run/secrets/kubernetes.io/serviceaccount from calico-node-token-p7d9n (ro)
  install-cni:
    Container ID:  docker://d9fd7a0f3fa9364c9a104c8482e3d86fc877e3f06f47570d28cd1b296303a960
    Image:         quay.io/calico/cni:v2.0.0
    Image ID:      docker-pullable://quay.io/calico/cni@sha256:ddb91b6fb7d8136d75e828e672123fdcfcf941aad61f94a089d10eff8cd95cd0
    Port:          <none>
    Command:
      /install-cni.sh
    State:          Waiting
      Reason:       CrashLoopBackOff
    Last State:     Terminated
      Reason:       Error
      Exit Code:    1
      Started:      Thu, 22 Feb 2018 15:53:16 +0100
      Finished:     Thu, 22 Feb 2018 15:53:16 +0100
    Ready:          False
    Restart Count:  11
    Environment:
      CNI_CONF_NAME:       10-calico.conflist
      ETCD_ENDPOINTS:      <set to the key 'etcd_endpoints' of config map 'calico-config'>      Optional: false
      CNI_NETWORK_CONFIG:  <set to the key 'cni_network_config' of config map 'calico-config'>  Optional: false
    Mounts:
      /calico-secrets from etcd-certs (rw)
      /host/etc/cni/net.d from cni-net-dir (rw)
      /host/opt/cni/bin from cni-bin-dir (rw)
      /var/run/secrets/kubernetes.io/serviceaccount from calico-node-token-p7d9n (ro)
Conditions:
  Type           Status
  Initialized    True
  Ready          False
  PodScheduled   True
Volumes:
  lib-modules:
    Type:          HostPath (bare host directory volume)
    Path:          /lib/modules
    HostPathType:
  var-run-calico:
    Type:          HostPath (bare host directory volume)
    Path:          /var/run/calico
    HostPathType:
  cni-bin-dir:
    Type:          HostPath (bare host directory volume)
    Path:          /opt/cni/binenter code here
    HostPathType:
  cni-net-dir:
    Type:          HostPath (bare host directory volume)
    Path:          /etc/cni/net.d
    HostPathType:
  etcd-certs:
    Type:        Secret (a volume populated by a Secret)
    SecretName:  calico-etcd-secrets
    Optional:    false
  calico-node-token-p7d9n:
    Type:        Secret (a volume populated by a Secret)
    SecretName:  calico-node-token-p7d9n
    Optional:    false
QoS Class:       Burstable
Node-Selectors:  <none>
Tolerations:     node.kubernetes.io/disk-pressure:NoSchedule
                 node.kubernetes.io/memory-pressure:NoSchedule
                 node.kubernetes.io/not-ready:NoExecute
                 node.kubernetes.io/unreachable:NoExecute
Events:
  Type     Reason                 Age                 From                    Message
  ----     ------                 ----                ----                    -------
  Normal   SuccessfulMountVolume  34m                 kubelet, kube-master01  MountVolume.SetUp succeeded for volume "cni-net-dir"
  Normal   SuccessfulMountVolume  34m                 kubelet, kube-master01  MountVolume.SetUp succeeded for volume "var-run-calico"
  Normal   SuccessfulMountVolume  34m                 kubelet, kube-master01  MountVolume.SetUp succeeded for volume "cni-bin-dir"
  Normal   SuccessfulMountVolume  34m                 kubelet, kube-master01  MountVolume.SetUp succeeded for volume "lib-modules"
  Normal   SuccessfulMountVolume  34m                 kubelet, kube-master01  MountVolume.SetUp succeeded for volume "calico-node-token-p7d9n"
  Normal   SuccessfulMountVolume  34m                 kubelet, kube-master01  MountVolume.SetUp succeeded for volume "etcd-certs"
  Normal   Created                34m                 kubelet, kube-master01  Created container
  Normal   Pulled                 34m                 kubelet, kube-master01  Container image "quay.io/calico/node:v3.0.1" already present on machine
  Normal   Started                34m                 kubelet, kube-master01  Started container
  Normal   Started                34m (x3 over 34m)   kubelet, kube-master01  Started container
  Normal   Pulled                 33m (x4 over 34m)   kubelet, kube-master01  Container image "quay.io/calico/cni:v2.0.0" already present on machine
  Normal   Created                33m (x4 over 34m)   kubelet, kube-master01  Created container
  Warning  BackOff                4m (x139 over 34m)  kubelet, kube-master01  Back-off restarting failed container
</code>```

答:
On CentOS:

firewall-cmd --zone=public --add-port=179/tcp --permanent

firewall-cmd --zone=public --add-port=4789/tcp --permanent

firewall-cmd --reload

Title: Kubernetes calico node CrashLoopBackOff

Body:
While there are some questions just like mine out there, the fixes do not work for me.
I'm using the kubernetes v1.9.3 binaries and using flannel and calico to setup a kubernetes cluster. After applying calico yaml files it gets stuck on creating the second pod.
What am I doing wrong? The logs aren't really clear in saying what's wrong

kubectl get pods --all-namespaces

root@kube-master01:/home/john/cookem/kubeadm-ha# kubectl logs calico-node-
n87l7 --namespace=kube-system
Error from server (BadRequest): a container name must be specified for pod
calico-node-n87l7, choose one of: [calico-node install-cni]
root@kube-master01:/home/john/cookem/kubeadm-ha# kubectl logs calico-node-
n87l7 --namespace=kube-system install-cni
Installing any TLS assets from /calico-secrets
cp: can't stat '/calico-secrets/*': No such file or directory

kubectl describe pod calico-node-n87l7 returns

Name:         calico-node-n87l7
Namespace:    kube-system
Node:         kube-master01/10.100.102.62
Start Time:   Thu, 22 Feb 2018 15:21:38 +0100
Labels:       controller-revision-hash=653023576
              k8s-app=calico-node
              pod-template-generation=1
Annotations:  scheduler.alpha.kubernetes.io/critical-pod=
              scheduler.alpha.kubernetes.io/tolerations=[{"key": "dedicated", "value": "master", "effect": "NoSchedule" },
 {"key":"CriticalAddonsOnly", "operator":"Exists"}]

Status:         Running
IP:             10.100.102.62
Controlled By:  DaemonSet/calico-node
Containers:
  calico-node:
    Container ID:   docker://6024188a667d98a209078b6a252505fa4db42124800baaf3a61e082ae2476147
    Image:          quay.io/calico/node:v3.0.1
    Image ID:       docker-pullable://quay.io/calico/node@sha256:e32b65742e372e2a4a06df759ee2466f4de1042e01588bea4d4df3f6d26d0581
    Port:           <none>
    State:          Running
      Started:      Thu, 22 Feb 2018 15:21:40 +0100
    Ready:          True
    Restart Count:  0
    Requests:
      cpu:      250m
    Liveness:   http-get http://:9099/liveness delay=10s timeout=1s period=10s #success=1 #failure=6
    Readiness:  http-get http://:9099/readiness delay=0s timeout=1s period=10s #success=1 #failure=3
    Environment:
      ETCD_ENDPOINTS:                     <set to the key 'etcd_endpoints' of config map 'calico-config'>  Optional: false
      CALICO_NETWORKING_BACKEND:          <set to the key 'calico_backend' of config map 'calico-config'>  Optional: false
      CLUSTER_TYPE:                       k8s,bgp
      CALICO_DISABLE_FILE_LOGGING:        true
      CALICO_K8S_NODE_REF:                 (v1:spec.nodeName)
      FELIX_DEFAULTENDPOINTTOHOSTACTION:  ACCEPT
      CALICO_IPV4POOL_CIDR:               10.244.0.0/16
      CALICO_IPV4POOL_IPIP:               Always
      FELIX_IPV6SUPPORT:                  false
      FELIX_LOGSEVERITYSCREEN:            info
      FELIX_IPINIPMTU:                    1440
      ETCD_CA_CERT_FILE:                  <set to the key 'etcd_ca' of config map 'calico-config'>    Optional: false
      ETCD_KEY_FILE:                      <set to the key 'etcd_key' of config map 'calico-config'>   Optional: false
      ETCD_CERT_FILE:                     <set to the key 'etcd_cert' of config map 'calico-config'>  Optional: false
      IP:                                 autodetect
      IP_AUTODETECTION_METHOD:            can-reach=10.100.102.0
      FELIX_HEALTHENABLED:                true
    Mounts:
      /calico-secrets from etcd-certs (rw)
      /lib/modules from lib-modules (ro)
      /var/run/calico from var-run-calico (rw)
      /var/run/secrets/kubernetes.io/serviceaccount from calico-node-token-p7d9n (ro)
  install-cni:
    Container ID:  docker://d9fd7a0f3fa9364c9a104c8482e3d86fc877e3f06f47570d28cd1b296303a960
    Image:         quay.io/calico/cni:v2.0.0
    Image ID:      docker-pullable://quay.io/calico/cni@sha256:ddb91b6fb7d8136d75e828e672123fdcfcf941aad61f94a089d10eff8cd95cd0
    Port:          <none>
    Command:
      /install-cni.sh
    State:          Waiting
      Reason:       CrashLoopBackOff
    Last State:     Terminated
      Reason:       Error
      Exit Code:    1
      Started:      Thu, 22 Feb 2018 15:53:16 +0100
      Finished:     Thu, 22 Feb 2018 15:53:16 +0100
    Ready:          False
    Restart Count:  11
    Environment:
      CNI_CONF_NAME:       10-calico.conflist
      ETCD_ENDPOINTS:      <set to the key 'etcd_endpoints' of config map 'calico-config'>      Optional: false
      CNI_NETWORK_CONFIG:  <set to the key 'cni_network_config' of config map 'calico-config'>  Optional: false
    Mounts:
      /calico-secrets from etcd-certs (rw)
      /host/etc/cni/net.d from cni-net-dir (rw)
      /host/opt/cni/bin from cni-bin-dir (rw)
      /var/run/secrets/kubernetes.io/serviceaccount from calico-node-token-p7d9n (ro)
Conditions:
  Type           Status
  Initialized    True
  Ready          False
  PodScheduled   True
Volumes:
  lib-modules:
    Type:          HostPath (bare host directory volume)
    Path:          /lib/modules
    HostPathType:
  var-run-calico:
    Type:          HostPath (bare host directory volume)
    Path:          /var/run/calico
    HostPathType:
  cni-bin-dir:
    Type:          HostPath (bare host directory volume)
    Path:          /opt/cni/binenter code here
    HostPathType:
  cni-net-dir:
    Type:          HostPath (bare host directory volume)
    Path:          /etc/cni/net.d
    HostPathType:
  etcd-certs:
    Type:        Secret (a volume populated by a Secret)
    SecretName:  calico-etcd-secrets
    Optional:    false
  calico-node-token-p7d9n:
    Type:        Secret (a volume populated by a Secret)
    SecretName:  calico-node-token-p7d9n
    Optional:    false
QoS Class:       Burstable
Node-Selectors:  <none>
Tolerations:     node.kubernetes.io/disk-pressure:NoSchedule
                 node.kubernetes.io/memory-pressure:NoSchedule
                 node.kubernetes.io/not-ready:NoExecute
                 node.kubernetes.io/unreachable:NoExecute
Events:
  Type     Reason                 Age                 From                    Message
  ----     ------                 ----                ----                    -------
  Normal   SuccessfulMountVolume  34m                 kubelet, kube-master01  MountVolume.SetUp succeeded for volume "cni-net-dir"
  Normal   SuccessfulMountVolume  34m                 kubelet, kube-master01  MountVolume.SetUp succeeded for volume "var-run-calico"
  Normal   SuccessfulMountVolume  34m                 kubelet, kube-master01  MountVolume.SetUp succeeded for volume "cni-bin-dir"
  Normal   SuccessfulMountVolume  34m                 kubelet, kube-master01  MountVolume.SetUp succeeded for volume "lib-modules"
  Normal   SuccessfulMountVolume  34m                 kubelet, kube-master01  MountVolume.SetUp succeeded for volume "calico-node-token-p7d9n"
  Normal   SuccessfulMountVolume  34m                 kubelet, kube-master01  MountVolume.SetUp succeeded for volume "etcd-certs"
  Normal   Created                34m                 kubelet, kube-master01  Created container
  Normal   Pulled                 34m                 kubelet, kube-master01  Container image "quay.io/calico/node:v3.0.1" already present on machine
  Normal   Started                34m                 kubelet, kube-master01  Started container
  Normal   Started                34m (x3 over 34m)   kubelet, kube-master01  Started container
  Normal   Pulled                 33m (x4 over 34m)   kubelet, kube-master01  Container image "quay.io/calico/cni:v2.0.0" already present on machine
  Normal   Created                33m (x4 over 34m)   kubelet, kube-master01  Created container
  Warning  BackOff                4m (x139 over 34m)  kubelet, kube-master01  Back-off restarting failed container


来源: stackexchange

问:
Python, detect letters with “in”
I’m learning python and got stuck on the “in” keyword.
I want to write a simple code which detects the Turkish letters, for example ı,ş,ö,ç,ğ,ü. But my code never find those letters. It always prints ok. What can I do?

usern = input("username:")
if usern in ("ş", "ı", "ö", "ç", "ü", "ğ"):
    print("turkish letter detected")
else:
    print("ok.")
```

答:
The most time efficient solution would probably be using hash maps.:

from collections import Counter

def has_turkish_letter(word):
    turkish_letters = ["ş", "ı", "ö", "ç", "ü", "ğ"]
    letter_count = Counter(word.lower())
    for letter in turkish_letters:
        if letter_count.get(letter, 0) > 0:
            return True
    return False

if has_turkish_letter(usern):
    print("turkish letter detected")
else:
    print("ok.")

```

ContentLicense: CC BY-SA 4.0

Title: Python, detect letters with “in”


问:
Creating gender dropdown in Phoenix / Elixir results in "assign @all_genders not available in eex template."
I am wanting to Add Gender to a client that comes from a database (and other look up tables)

I have defined the Client as so:

```<code>defmodule Dropdown.Clients.Client do
  use Ecto.Schema
  import Ecto.Changeset
  alias Dropdown.Clients.Admin

  schema "clients" do
    field :email, :string
    field :name, :string

    belongs_to :genders, Admin
</code>```

And Gender

```<code>defmodule Dropdown.Clients.Admin do
  use Ecto.Schema
  import Ecto.Changeset

  schema "gender" do
    field :gender, :string
    has_many :clients, Client
  end
</code>```

Controller add and create functions are like so:

```<code>  def new(conn, _params) do
    changeset = Clients.change_client(%Client{})
    gender_query = from g in Admin, select: {g.gender, g.id}
    all_genders = Dropdown.Repo.all(gender_query)

    render(conn, "new.html", all_genders: all_genders, changeset: changeset)
  end

  def create(conn, %{"client" => client_params}) do

    case Clients.create_client(client_params) do
      {:ok, client} ->
        conn
        |> put_flash(:info, "Client created successfully.")
        |> redirect(to: Routes.client_path(conn, :show, client))

      {:error, %Ecto.Changeset{} = changeset} ->
        render(conn, "new.html", changeset: changeset)
    end
  end
</code>```

The corresponding Context is:

```<code>    Client
    |> Repo.get!(id)
    |> Repo.preload(:genders)
  end

  def create_client(attrs \\ %{}) do
    %Client{}
    |> IO.inspect()
    |> Client.changeset(attrs)
    |> Repo.insert()
  end
</code>```

In the Add form:

```<code>  <%= select(f, :gender_id, @all_genders) %>
  <%= error_tag f, :gender_id %>
</code>```

I have the form show the Gender dropdown, however, when I submit I get an error:

assign @all_genders not available in eex template.

The IO.inspect shows:

```<code>  [debug] Processing with DropdownWeb.ClientController.create/2
  Parameters: %{"_csrf_token" => "ECAXCnJJEw1ZGRtyFmoZDDF_GjQ3CHFzqvxrAypk0JW5N3kkE1UytpBJ", "client" => %{"email" => "george@example.com", "gender_id" => "1", "name" => "George Company"}}
  Pipelines: [:browser]
</code>```

Any suggestions on fixing this would be much appreciated.

答:
In your error case (when Client.create_client/1 returns an error tuple, you are rendering the new.html template again. However, you are not providing the all_genders assign (key:value), so when it tries to render, it crashes.

You have to modify your controller to include all_genders in the error case as well:

def new(conn, _params) do
  changeset = Clients.change_client(%Client{})
  gender_query = from g in Admin, select: {g.gender, g.id}
  all_genders = Dropdown.Repo.all(gender_query)

  render(conn, "new.html", all_genders: all_genders, changeset: changeset)
end

def create(conn, %{"client" => client_params}) do
  case Clients.create_client(client_params) do
    {:ok, client} ->
      conn
      |> put_flash(:info, "Client created successfully.")
      |> redirect(to: Routes.client_path(conn, :show, client))

    {:error, %Ecto.Changeset{} = changeset} ->
      # This part was missing in your original code
      gender_query = from g in Admin, select: {g.gender, g.id}
      all_genders = Dropdown.Repo.all(gender_query)
      # -----------
      render(conn, "new.html", changeset: changeset, all_genders: all_genders)
  end
end
```

Body:
I am wanting to Add Gender to a client that comes from a database (and other look up tables)

I have defined the Client as so:

defmodule Dropdown.Clients.Client do
  use Ecto.Schema
  import Ecto.Changeset
  alias Dropdown.Clients.Admin

  schema "clients" do
    field :email, :string
    field :name, :string

    belongs_to :genders, Admin

And Gender

defmodule Dropdown.Clients.Admin do
  use Ecto.Schema
  import Ecto.Changeset

  schema "gender" do
    field :gender, :string
    has_many :clients, Client
  end

Controller add and create functions are like so:

  def new(conn, _params) do
    changeset = Clients.change_client(%Client{})
    gender_query = from g in Admin, select: {g.gender, g.id}
    all_genders = Dropdown.Repo.all(gender_query)

    render(conn, "new.html", all_genders: all_genders, changeset: changeset)
  end

  def create(conn, %{"client" => client_params}) do

    case Clients.create_client(client_params) do
      {:ok, client} ->
        conn
        |> put_flash(:info, "Client created successfully.")
        |> redirect(to: Routes.client_path(conn, :show, client))

      {:error, %Ecto.Changeset{} = changeset} ->
        render(conn, "new.html", changeset: changeset)
    end
  end

The corresponding Context is:

    Client
    |> Repo.get!(id)
    |> Repo.preload(:genders)
  end

  def create_client(attrs \\ %{}) do
    %Client{}
    |> IO.inspect()
    |> Client.changeset(attrs)
    |> Repo.insert()
  end

In the Add form:

  <%= select(f, :gender_id, @all_genders) %>
  <%= error_tag f, :gender_id %>

I have the form show the Gender dropdown, however, when I submit I get an error:

assign @all_genders not available in eex template.

The IO.inspect shows:

  [debug] Processing with DropdownWeb.ClientController.create/2
  Parameters: %{"_csrf_token" => "ECAXCnJJEw1ZGRtyFmoZDDF_GjQ3CHFzqvxrAypk0JW5N3kkE1UytpBJ", "client" => %{"email" => "george@example.com", "gender_id" => "1", "name" => "George Company"}}
  Pipelines: [:browser]

Any suggestions on fixing this would be much appreciated.


问:
Median of Multiple Columns of a DF in R (all values together)
I have a dataframe containing a few numeric columns and I need to get the median for all these values (all rows and columns), not by row, not by column, just one median for all values.
Although that seems simple, I could not find an explanation.

The df I have is similar to:

```<code>    rep_id  sex     activator   P16401      P81605      B7Z958      B4DT29
    CF9     Female  Control     808.3071    772.20756   14114.372   5516.857
    CF10    Female  Control     1332.5300   739.96297   19373.688   4855.419
    CF11    Female  Control     748.3975    1449.46860  17310.500   5324.638
    CF12    Female  Control     1271.5207   978.48424   6217.883    6015.900
    CF13    Female  Control     554.3564    461.37956   6659.669    5739.060
    CF14    Female  Control     1575.7039   1770.07244  7143.650    5936.352
</code>```

(the number of rows and columns vary in different use cases, usually many more than this example)
I just need the median of all numerical values. The equivalent of what would be =MEDIAN(D2:G7) in Excel, but for many reasons I prefer analyzing all the data in R.
The expected result for this example would be 3312.74572

答:
additional option with selection of numerical columns</p>

```<code>library(tidyverse)
df %>%
  select_if(is.numeric) %>%
  as.matrix() %>%
  median()
</code>```

Body:
I have a dataframe containing a few numeric columns and I need to get the median for all these values (all rows and columns), not by row, not by column, just one median for all values.
Although that seems simple, I could not find an explanation.

The df I have is similar to:

    rep_id  sex     activator   P16401      P81605      B7Z958      B4DT29
    CF9     Female  Control     808.3071    772.20756   14114.372   5516.857
    CF10    Female  Control     1332.5300   739.96297   19373.688   4855.419
    CF11    Female  Control     748.3975    1449.46860  17310.500   5324.638
    CF12    Female  Control     1271.5207   978.48424   6217.883    6015.900
    CF13    Female  Control     554.3564    461.37956   6659.669    5739.060
    CF14    Female  Control     1575.7039   1770.07244  7143.650    5936.352

(the number of rows and columns vary in different use cases, usually many more than this example)
I just need the median of all numerical values. The equivalent of what would be =MEDIAN(D2:G7) in Excel, but for many reasons I prefer analyzing all the data in R.
The expected result for this example would be 3312.74572

Body:
additional option with selection of numerical columns

library(tidyverse)
df %>%
  select_if(is.numeric) %>%
  as.matrix() %>%
  median()


问:
How to list all directories and files inside docker container?
Following is my dockerfile:

```<code>FROM python:3.6.5-windowsservercore
COPY . /app
WORKDIR /app
RUN pip download -r requirements.txt -d packages
</code>```

To get list of files in the image, I have tried both the following options, but there is error:

```<code>encountered an error during CreateProcess: failure in a Windows system call:
The system cannot find the file specified. (0x2) extra info:
{"CommandLine":"dir","WorkingDirectory":"C:\\app"......
</code>```

Run docker run -it <container_id> dir

Modify the dockerfile and add CMD at end of dockerfile - CMD ["dir"], then run docker run <container_id> dir

How to list all directories and files inside docker?

答:
Simply use the exec command.

Now because you run a windowsservercore based image use powershell command (and not /bin/bash which you can see on many examples for linux based images and which is not installed by default on a windowsservercore based image) so just do:

```<code>docker exec -it <container_id> powershell
</code>```

Now you should get an iteractive terminal and you can list your files with simply doing ls or dir

By the way, i found this question :

Exploring Docker container's file system

It contains a tons of answers and suggestions, maybe you could find other good solutions there (there is for example a very friendly CLI tool to exploring containers : https://github.com/wagoodman/dive)

Body:
Following is my dockerfile:

FROM python:3.6.5-windowsservercore
COPY . /app
WORKDIR /app
RUN pip download -r requirements.txt -d packages

To get list of files in the image, I have tried both the following options, but there is error:

encountered an error during CreateProcess: failure in a Windows system call:
The system cannot find the file specified. (0x2) extra info:
{"CommandLine":"dir","WorkingDirectory":"C:\\app"......

Run docker run -it <container_id> dir

Modify the dockerfile and add CMD at end of dockerfile - CMD ["dir"], then run docker run <container_id> dir

How to list all directories and files inside docker?

Body:
Simply use the exec command.

Now because you run a windowsservercore based image use powershell command (and not /bin/bash which you can see on many examples for linux based images and which is not installed by default on a windowsservercore based image) so just do:

docker exec -it <container_id> powershell

Now you should get an iteractive terminal and you can list your files with simply doing ls or dir

By the way, i found this question :

Exploring Docker container's file system

It contains a tons of answers and suggestions, maybe you could find other good solutions there (there is for example a very friendly CLI tool to exploring containers : https://github.com/wagoodman/dive)


问:
Apply CSS for all buttons except a specific ID
I have a code:

```<code>button {
  background: rgb(1, 81, 227);
  background: linear-gradient(
    90deg,
    rgba(1, 81, 227, 1) 35%,
    rgba(0, 90, 255, 1) 100%
  );
  border: none;
  color: white;
  padding: 15px 32px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 20px;
  margin: 4px 2px;
  cursor: pointer;
  border-radius: 6px;
}
</code>```

And a ton of buttons. I want to apply that css code for all buttons except two, with the IDs startAction & endAction.

How do I do that?

答:
Your startAction and endAction buttons probably share some of those styles.

If so, just keep those shared lines within the generic button declaration and move the other stuff into a new style and then apply that to the rest of the buttons.

Something like...

button {
  display: inline-block;
  border: none;
  color: white;
  ...
}

.fancybutton {
  background: rgb(1, 81, 227);
  background: linear-gradient(
    90deg,
    rgba(1, 81, 227, 1) 35%,
    rgba(0, 90, 255, 1) 100%
  );
  margin: 4px 2px;
  ...
}
```

Body:
I have a code:

button {
  background: rgb(1, 81, 227);
  background: linear-gradient(
    90deg,
    rgba(1, 81, 227, 1) 35%,
    rgba(0, 90, 255, 1) 100%
  );
  border: none;
  color: white;
  padding: 15px 32px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 20px;
  margin: 4px 2px;
  cursor: pointer;
  border-radius: 6px;
}

And a ton of buttons. I want to apply that css code for all buttons except two, with the IDs startAction & endAction.

How do I do that?


问:
using pip3: module "importlib._bootstrap" has no attribute "SourceFileLoader"
I have installed pip for python 3.6 on Ubuntu 14. After I run

```<code>sudo apt-get install python3-pip
</code>```

to install pip3, it works very well. However, after installation, when I am trying to run

```<code>pip3 install packagename
</code>```

to install a new package, something strange occurs:

```<code>File "/usr/lib/python3/dist-packages/pkg_resources.py", line 1479, in <module>
 register_loader-type(importlib_bootstrap.SourceFileLoader, DefaultProvider)
AttributeError: module "importlib._bootstrap" has no attribute "SourceFileLoader"
</code>```

It seems that I did nothing wrong, and I really cannot figure out the reason.

答:
I had faced the same issue on Ubuntu 19.10 and now I upgraded to Ubuntu 20.04 and faced the issue again. This issue is due to broken pip3. So whenever you enter pip3 and hit enter it will show the same error. So instead of using "pip3 uninstall setuptools" use the below code

```<code>python3 -m pip uninstall setuptools
</code>```

It resolved my issue 3rd time

ContentLicense: CC BY-SA 3.0

Body:
I have installed pip for python 3.6 on Ubuntu 14. After I run

sudo apt-get install python3-pip

to install pip3, it works very well. However, after installation, when I am trying to run

pip3 install packagename

to install a new package, something strange occurs:

File "/usr/lib/python3/dist-packages/pkg_resources.py", line 1479, in <module>
 register_loader-type(importlib_bootstrap.SourceFileLoader, DefaultProvider)
AttributeError: module "importlib._bootstrap" has no attribute "SourceFileLoader"

It seems that I did nothing wrong, and I really cannot figure out the reason.

Body:
I had faced the same issue on Ubuntu 19.10 and now I upgraded to Ubuntu 20.04 and faced the issue again. This issue is due to broken pip3. So whenever you enter pip3 and hit enter it will show the same error. So instead of using "pip3 uninstall setuptools" use the below code

python3 -m pip uninstall setuptools

It resolved my issue 3rd time


问:
iOS SwiftUI how to bring up extra actions like "Embed in VStack" when interacting with code?
I am looking at this SwiftUI tutorial and it suggests I can see extra actions upon Command-Clicking the SwiftUI elements in code. In my Xcode, this jumps me to the class definition.

I see there's an option in XCode 11.0 t change the Option key to show SwiftUI inspector, however, this still does not let me modify SwiftUI code elements using actions like "Embed in VStack"

How can I get both inspector and extra SwiftUI actions when interacting with SwiftUI Code (not the preview)?

答:
The accepted answer doesn't work for me on macOS 10.15.5 and Xcode 11.4.1.

The Good news is that you can get it via a shortcut of [Command][Shift][Left Click] on a SwiftUI element or by clicking Show Code Actions on the right click menu.

 Show Code Actions">


问:
Does the Application Master or Cluster Manager launch containers / executors - Spark?
Lets say we have a spark job running in Cluster Mode where the cluster manager is YARN.

In cluster mode

a user submits a pre-compiled JAR, Python script to the cluster manager.
The cluster manager than tells a specific Node Manager to launch the Application Master.

The Spark Driver then runs on the Application Master.
The driver converts the users code containing transformations and actions into a logical plan called the DAG. The DAG is then converted into a physical execution plan

The application master then communicates with the cluster manager and negotiates resources. Resources such as preferred executor locations, and number of containers are requested.

At this point does the cluster manager allocate YARN containers or does the application master allocate the YARN containers? Does the cluster manager create the Spark Executors as well or does the application master do this?

答:
A Spark application submitted to YARN translates into a YARN

application.

Hence when a Client submits a new application/job request to Resource
Manager(Yarn component).

Resource Manager (RM) accepts the job request and allocates a

container to start Application Master  for the given application/job.

Application Master can be thought of as a specialized container which

will manage/monitor application/job tasks.

Application Master sends request to Resource Manager , asking for

resources required to run the application/job.

Resource Manager responds back with a list of containers along with

list of salve nodes that they can be spawned on.

Application Master starts the containers(in case of spark called as

executors) on each of specified salve nodes.

The first fact to understand is: each Spark executor runs as a YARN    container. This and the fact that Spark executors for an application are fixed, and so are the resources allotted to each executor, a Spark application takes up resources for its entire duration. This is in contrast with a MapReduce application which constantly returns resources at the end of each task, and is again allotted at the start of the next task.


问:
pagination with nodejs and mysql
I am currently building an api, in which I need to paginate the data from my database and that shows the page number in the url. my project is structured as follows.

I have tried to add the pagination in several files but I have not been successful, I would like to know exactly where the pagination will go since I am still learning Node. the configured files are as follows. my model first.

onst sql = require("./db.js");

//constructor
const sales_order = function(sales_order) {
    this.id = sales_order.id;
    this.business_units_id = sales_order.business_units_id;

  };

  sales_order.findById = (id, result) => {
    sql.query(`SELECT * FROM sales_order WHERE id = ${id}`, (err, res) => {
      if (err) {
        console.log("error: ", err);
        result(err, null);
        return;
      }

      if (res.length) {
        console.log("Orden Encontrada: ", res[0]);
        result(null, res[0]);
        return;
      }

      result({ kind: "not_found" }, null);
    });
  };

  sales_order.getAll = (result) => {
    const limit = 100
    sql.query("SELECT * FROM sales_order limit "+limit , (err, res) => {
      if (err) {
        console.log("error: ", err);
        result(null, err);

        return;
      }

      console.log("Ordenes de compra encontradas ", res);

      result(null, res);
    });
  };

  sales_order.updateById = (id, sales_order, result) => {
    sql.query(
      "UPDATE sales_order SET estado = ? WHERE id = ?",
      [sales_order.estado, sales_order.active, id],
      (err, res) => {
        if (err) {
          console.log("error: ", err);
          result(null, err);
          return;
        }

        if (res.affectedRows == 0) {
          // not found Customer with the id
          result({ kind: "not_found" }, null);
          return;
        }

        console.log("updated customer: ", { id: id, ...sales_order });
        result(null, { id: id, ...sales_order });
      }
    );
  };
  module.exports = sales_order;```
</div>
</div>
</p>

<p>my db.js file.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const mysql = require("mysql");
const dbConfig = require("../config/db.config.js");

// Se crea la conexión a la base de datos
const connection = mysql.createConnection({
  host: dbConfig.HOST,
  user: dbConfig.USER,
  password: dbConfig.PASSWORD,
  database: dbConfig.DB
});

// Abir la conexión a MySql
connection.connect(error => {
  if (error) throw error;
  console.log("Conectado satisfactoriamente a la base de datos");
});

module.exports = connection;</code>```

my sales_order.controller.js

const Orders = require("../models/sales_order.model.js");

exports.findAll = (req, res, next) => {

    Orders.getAll((err, data) => {
      if (err)
        res.status(500).send({
          message:
            err.message || "Se produjo algún error al recuperar las ordenes de compra."
        });

      else res.send(data);

        next();
    });
  };

  exports.findOne = (req, res) => {
    Orders.findById(req.params.id, (err, data) => {
      if (err) {
        if (err.kind === "not_found") {
          res.status(404).send({
            message: `Orden de compra no encontrado por su ID ${req.params.id}.`
          });
        } else {
          res.status(500).send({
            message: "Error al recuperar la orden de compra por su ID " + req.params.id
          });
        }
      } else res.send(data);
    });
  };

  exports.update = (req, res) => {
    // Validate Request
    if (!req.body) {
      res.status(400).send({
        message: "El contenido no puede estar vacío.!"
      });
    }

    Orders.updateById(
      req.params.customerId,
      new Customer(req.body),
      (err, data) => {
        if (err) {
          if (err.kind === "not_found") {
            res.status(404).send({
              message: `no hay datos diponibles por el ID ${req.params.id}.`
            });
          } else {
            res.status(500).send({
              message: "Error al actualizar las ordenes de compra " + req.params.id
            });
          }
        } else res.send(data);
      }
    );
  };```
</div>
</div>
</p>

<p>sales_order.routes.js</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>module.exports = app => {
    const sales_order = require("../controller/sales_order.controller.js");

    app.get("/" , (req, res) => {
        res.send('Ejecutandose');
    })

    app.get("/sales_orders", sales_order.findAll);

    app.get("/sales_orders/:id", sales_order.findOne);

    app.put("/sales_orders/:id", sales_order.update);

  };</code>```

I would like to know exactly and given the structure of the project exactly where I should paginate and configure the page number to be displayed in the url.

答:
Yes, you achieve this using limit by limiting the number of records in the SQL query.Change the findAll helper of sales order

```<code> sales_order.getAll = (req,res) => {
    var numRows;
    var queryPagination;
    var numPerPage = parseInt(req.query.npp, 10) || 1;
    var page = parseInt(req.query.page, 10) || 0;
    var numPages;
    var skip = page * numPerPage;
    // Here we compute the LIMIT parameter for MySQL query
    var limit = skip + ',' + numPerPage;
        sql.query("SELECT * FROM sales_order limit "+limit , (err, res) => {
          if (err) {
            console.log("error: ", err);
            result(null, err);

            return;
          }
          console.log("Ordenes de compra encontradas ", res);
          result(null, res);
        });
      };
</code>```

And accept the page number from query param

I hope that helps ✌

Title: pagination with nodejs and mysql

Body:
I am currently building an api, in which I need to paginate the data from my database and that shows the page number in the url. my project is structured as follows.

I have tried to add the pagination in several files but I have not been successful, I would like to know exactly where the pagination will go since I am still learning Node. the configured files are as follows. my model first.

onst sql = require("./db.js");

//constructor
const sales_order = function(sales_order) {
    this.id = sales_order.id;
    this.business_units_id = sales_order.business_units_id;

  };

  sales_order.findById = (id, result) => {
    sql.query(`SELECT * FROM sales_order WHERE id = ${id}`, (err, res) => {
      if (err) {
        console.log("error: ", err);
        result(err, null);
        return;
      }

      if (res.length) {
        console.log("Orden Encontrada: ", res[0]);
        result(null, res[0]);
        return;
      }

      result({ kind: "not_found" }, null);
    });
  };

  sales_order.getAll = (result) => {
    const limit = 100
    sql.query("SELECT * FROM sales_order limit "+limit , (err, res) => {
      if (err) {
        console.log("error: ", err);
        result(null, err);

        return;
      }

      console.log("Ordenes de compra encontradas ", res);

      result(null, res);
    });
  };

  sales_order.updateById = (id, sales_order, result) => {
    sql.query(
      "UPDATE sales_order SET estado = ? WHERE id = ?",
      [sales_order.estado, sales_order.active, id],
      (err, res) => {
        if (err) {
          console.log("error: ", err);
          result(null, err);
          return;
        }

        if (res.affectedRows == 0) {
          // not found Customer with the id
          result({ kind: "not_found" }, null);
          return;
        }

        console.log("updated customer: ", { id: id, ...sales_order });
        result(null, { id: id, ...sales_order });
      }
    );
  };
  module.exports = sales_order;

my db.js file.

const mysql = require("mysql");
const dbConfig = require("../config/db.config.js");

// Se crea la conexión a la base de datos
const connection = mysql.createConnection({
  host: dbConfig.HOST,
  user: dbConfig.USER,
  password: dbConfig.PASSWORD,
  database: dbConfig.DB
});

// Abir la conexión a MySql
connection.connect(error => {
  if (error) throw error;
  console.log("Conectado satisfactoriamente a la base de datos");
});

module.exports = connection;

my sales_order.controller.js

const Orders = require("../models/sales_order.model.js");

exports.findAll = (req, res, next) => {

    Orders.getAll((err, data) => {
      if (err)
        res.status(500).send({
          message:
            err.message || "Se produjo algún error al recuperar las ordenes de compra."
        });

      else res.send(data);

        next();
    });
  };

  exports.findOne = (req, res) => {
    Orders.findById(req.params.id, (err, data) => {
      if (err) {
        if (err.kind === "not_found") {
          res.status(404).send({
            message: `Orden de compra no encontrado por su ID ${req.params.id}.`
          });
        } else {
          res.status(500).send({
            message: "Error al recuperar la orden de compra por su ID " + req.params.id
          });
        }
      } else res.send(data);
    });
  };

  exports.update = (req, res) => {
    // Validate Request
    if (!req.body) {
      res.status(400).send({
        message: "El contenido no puede estar vacío.!"
      });
    }

    Orders.updateById(
      req.params.customerId,
      new Customer(req.body),
      (err, data) => {
        if (err) {
          if (err.kind === "not_found") {
            res.status(404).send({
              message: `no hay datos diponibles por el ID ${req.params.id}.`
            });
          } else {
            res.status(500).send({
              message: "Error al actualizar las ordenes de compra " + req.params.id
            });
          }
        } else res.send(data);
      }
    );
  };

sales_order.routes.js

module.exports = app => {
    const sales_order = require("../controller/sales_order.controller.js");

    app.get("/" , (req, res) => {
        res.send('Ejecutandose');
    })

    app.get("/sales_orders", sales_order.findAll);

    app.get("/sales_orders/:id", sales_order.findOne);

    app.put("/sales_orders/:id", sales_order.update);

  };

I would like to know exactly and given the structure of the project exactly where I should paginate and configure the page number to be displayed in the url.

Body:
Yes, you achieve this using limit by limiting the number of records in the SQL query.Change the findAll helper of sales order

 sales_order.getAll = (req,res) => {
    var numRows;
    var queryPagination;
    var numPerPage = parseInt(req.query.npp, 10) || 1;
    var page = parseInt(req.query.page, 10) || 0;
    var numPages;
    var skip = page * numPerPage;
    // Here we compute the LIMIT parameter for MySQL query
    var limit = skip + ',' + numPerPage;
        sql.query("SELECT * FROM sales_order limit "+limit , (err, res) => {
          if (err) {
            console.log("error: ", err);
            result(null, err);

            return;
          }
          console.log("Ordenes de compra encontradas ", res);
          result(null, res);
        });
      };

And accept the page number from query param

I hope that helps ✌


问:
Is there a way to get an array of the values of the properties in an object?
I have an object that stores URLs. In the example below the object has just 4 properties but in my case there are more so I want to know is there a way to do this with more elegant.

public final class MyObject: NSObject {

  private let firstURL: URL
  private let secondURL: URL
  private let thirdURL: URL
  private let fourthURL: URL

  public func values() -> [URL] {
    return // <--- I need to return URLs from properties like [firstURL, secondURL, thirdURL, fourthURL]
  }
}
```

<p>I've found an extension of <code>NSObject</code> to return an array of the name of the properties as a <code>String</code>.</p>

<p>Extension Source</p>

<pre class="lang-swift prettyprint-override"><code>
public extension NSObject {

  //
  // Retrieves an array of property names found on the current object
  // using Objective-C runtime functions for introspection:
  // https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtPropertyIntrospection.html
  //
  func propertyNames() -> Array<String> {
    var results: Array<String> = []

    // retrieve the properties via the class_copyPropertyList function
    var count: UInt32 = 0
    let myClass: AnyClass = classForCoder
    let properties = class_copyPropertyList(myClass, &count)

    // iterate each objc_property_t struct
    for i in 0..<count {
      if let property = properties?[Int(i)] {
        // retrieve the property name by calling property_getName function
        let cname = property_getName(property)

        // covert the c string into a Swift string
        results.append(cname.debugDescription)
      }
    }

    // release objc_property_t structs
    free(properties)

    return results
  }
}
</code>```

But it returns array of the property names like ["firstURL", "secondURL", "thirdURL", "fourthURL"]. I want to return values instead of names.

答:
You can use Mirror</p>

```<code>public final class MyObject: NSObject {
  private let firstURL: URL
  private let secondURL: URL
  private let thirdURL: URL
  private let fourthURL: URL

  public init(firstURL: URL, secondURL: URL, thirdURL: URL, fourthURL: URL) {
    self.firstURL = firstURL
    self.secondURL = secondURL
    self.thirdURL = thirdURL
    self.fourthURL = fourthURL
  }

  public func values() -> [URL] {
    return Mirror(reflecting: self).children.compactMap({ $0.value as? URL })
  }
}

let url = URL(string: "https://stackoverflow.com/")!
let myObject = MyObject(firstURL: url, secondURL: url, thirdURL: url, fourthURL: url)
print(myObject.values()
// [https://stackoverflow.com/, https://stackoverflow.com/, https://stackoverflow.com/, https://stackoverflow.com/]
</code>```

Body:
I have an object that stores URLs. In the example below the object has just 4 properties but in my case there are more so I want to know is there a way to do this with more elegant.

public final class MyObject: NSObject {

  private let firstURL: URL
  private let secondURL: URL
  private let thirdURL: URL
  private let fourthURL: URL

  public func values() -> [URL] {
    return // <--- I need to return URLs from properties like [firstURL, secondURL, thirdURL, fourthURL]
  }
}

I've found an extension of NSObject to return an array of the name of the properties as a String.

Extension Source

public extension NSObject {

  //
  // Retrieves an array of property names found on the current object
  // using Objective-C runtime functions for introspection:
  // https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtPropertyIntrospection.html
  //
  func propertyNames() -> Array<String> {
    var results: Array<String> = []

    // retrieve the properties via the class_copyPropertyList function
    var count: UInt32 = 0
    let myClass: AnyClass = classForCoder
    let properties = class_copyPropertyList(myClass, &count)

    // iterate each objc_property_t struct
    for i in 0..<count {
      if let property = properties?[Int(i)] {
        // retrieve the property name by calling property_getName function
        let cname = property_getName(property)

        // covert the c string into a Swift string
        results.append(cname.debugDescription)
      }
    }

    // release objc_property_t structs
    free(properties)

    return results
  }
}

But it returns array of the property names like ["firstURL", "secondURL", "thirdURL", "fourthURL"]. I want to return values instead of names.

Body:
You can use Mirror

public final class MyObject: NSObject {
  private let firstURL: URL
  private let secondURL: URL
  private let thirdURL: URL
  private let fourthURL: URL

  public init(firstURL: URL, secondURL: URL, thirdURL: URL, fourthURL: URL) {
    self.firstURL = firstURL
    self.secondURL = secondURL
    self.thirdURL = thirdURL
    self.fourthURL = fourthURL
  }

  public func values() -> [URL] {
    return Mirror(reflecting: self).children.compactMap({ $0.value as? URL })
  }
}

let url = URL(string: "https://stackoverflow.com/")!
let myObject = MyObject(firstURL: url, secondURL: url, thirdURL: url, fourthURL: url)
print(myObject.values()
// [https://stackoverflow.com/, https://stackoverflow.com/, https://stackoverflow.com/, https://stackoverflow.com/]


问:
How can you find translations of a word in english to other languages programmatically
The following is a sample set of translations from english --> french

```<code>lundi (monday)
mardi (tuesday)
mercredi (wednesday)
janvier (january)
</code>```

Is there an easier way to find the equivalent words for days and months from english to say french | german | japanese?

答:
You could use SimpleDateFormat:

```<code>Locale locale = new Locale("fr");
SimpleDateFormat df = new SimpleDateFormat("EEEE", locale);
System.out.println(df.format(new Date()));
</code>```

Now instead of new Date() create a date with the required day - monday, tuesday, etc

Body:
The following is a sample set of translations from english --> french

lundi (monday)
mardi (tuesday)
mercredi (wednesday)
janvier (january)

Is there an easier way to find the equivalent words for days and months from english to say french | german | japanese?

Body:
You could use SimpleDateFormat:

Locale locale = new Locale("fr");
SimpleDateFormat df = new SimpleDateFormat("EEEE", locale);
System.out.println(df.format(new Date()));

Now instead of new Date() create a date with the required day - monday, tuesday, etc


答:
How should I incorporate the linking constraints to satisfy the constraints where Y1 = 1, Y2 = 2, Y3 = 3, and Y4 = 4 using Binary.vec?

I believe that you mean Y[i] = 1 [ for i in 1:4 ].

The binary.vec argument is a

Numeric vector like int.vec giving the indices of variables that are required to be binary.

Now the indices here refer to the optimization problem. Thus we need the indices to match the position of Y[i] [for i in 1:4 ]. In this case it's the latter 4 in your objective function, so we could get their indices as

```<code>binary.vec <- seq(length(f.obj), length(f.obj) - 3)
</code>```

Note however, that your current problem is not looking for a strictly binary Y[i], but further you are looking for Y[i] given the value of some other parameter. As it is written it is not a linear constraint, thus we need to do some trickery.

The problem here is that you need Y[i] = 1 if X[i,1] > 0 and X[i, 2] > 0, 0 otherwise, and simply adding Y[i] %in% 0:1 won't necessarily uphold the constraints. There are several ways of getting past this, but the one I find the most intuitive is to reformulate the problem using pseudo-parameters

```<code>C * z[i, j] > x[i, j] [ for all i, j ]
z[i, j] %in% 0:1 [ for all i, j ]
C = Inf
z[i, j] = 1 if X[i, j] > 0, 0 otherwise [ for i in 1:4, j in 1:2 ]
Y[i] <= 0.5 * z[i, 1] + 0.5 * z[i, 2]
</code>```

The trick here is that now we have only linear constrants. Notice that if only z[i, 1] = 1 these constraints forces Y[i] = 0.

We have a increased the number of parameters quite a bit, but this problem is linear as all equations are written in the form y = a * x + b.

However as I described in my answer to your previous question when we add pseudo-parameters we need to

Extend our objective function, so it includes these as pseudo-parameters (make the solver aware of the parameters in the optimization function)

Extend our constraints, in order to keep dimensions correct (make the solver aware of how these affect the remaining constraints)

Extending optimization problem

Now this is the simple part. Simply add the parameters at the end of your existing equation. I always suggest naming the objective function if one finds it hard to keep track

```<code>n <- length(f.obj)
names(f.obj)[seq(n - 4)] <- paste0('X[', rep(1:4, 2), ', ', rep(1:2, each = 4), ']')
names(f.obj)[-seq(n - 4)] <- paste0('Y[', 1:4, ']')
f.obj <- c(f.obj, numeric(8))
n <- length(f.obj)
names(f.obj)[seq(n - 7, n)] <- paste0('z[', rep(1:4, 2), ', ', rep(1:2, each = 4), ']')
tail(f.obj, 12)
   Y[1]    Y[2]    Y[3]    Y[4] z[1, 1] z[2, 1] z[3, 1] z[4, 1] z[1, 2] z[2, 2] z[3, 2] z[4, 2]
   1500    1700    1500    1400       0       0       0       0       0       0       0       0
</code>```

Note here, that they all gain a weight of 0, because their effect is captured by the effect of X[i, j] and Y[i].

Extend your constraints

Now this is again the tricky part. First note as in my answer to the previous question, that the dimensions of your constraints have to match your objective function. In this problem you have length(f.obj) = 28 (including the new pseudo-parameters), so all constraints needs to have 28 columns. The general idea here is that we (figuratively) add sum_[i, j] 0 * X[i, j] + sum_[i] 0 * Y[i] to every constraint. Thus your constraints should be

```<code>cons1 <- numeric(n)
names(cons1) <- names(f.obj)
cons12 <- cons11 <- cons10 <- cons9 <- cons8 <- cons7 <- cons6 <- cons5 <- cons4 <- cons3 <- cons2 <- cons1
cons1[1:4] <- c(2, 1.8, 2.3, 2.1)
cons2[5:8] <- c(2.8, 2.3, 2.2, 2.6)
cons3[9:12] <- c(1.7, 1.75, 1.6, 1.9)
cons4[13:16] <- c( 2.4, 1.9, 2.6, 2.4)
#X[i, j] - Cy[i] * Y[i] <= 0
cons5[c('X[1, 1]', 'Y[1]')] <- c(1, -1500)
cons6[c('X[2, 1]', 'Y[2]')] <- c(1, -2000)
cons7[c('X[3, 1]', 'Y[3]')] <- c(1, -1500)
cons8[c('X[4, 1]', 'Y[4]')] <- c(1, -1800)
cons9[c('X[1, 2]', 'Y[1]')] <- c(1, -500)
cons10[c('X[2, 2]', 'Y[2]')] <- c(1, -500)
cons11[c('X[3, 2]', 'Y[3]')] <- c(1, -500)
cons12[c('X[4, 2]', 'Y[4]')] <- c(1, -500)
#Pseudo-constraints
## Start with C * z[i, j] > x[i, j] for some very large C (here i choose 1e12, but could be any number large enough so X[i, j] does not exceed it!)
pseudo_z_1 <- numeric(n)
names(pseudo_z_1) <- names(f.obj)
pseudo_z_8 <- pseudo_z_7 <- pseudo_z_6 <- pseudo_z_5 <- pseudo_z_4 <- pseudo_z_3 <- pseudo_z_2 <- pseudo_z_1
C <- 1e12
pseudo_z_1[c('X[1, 1]', 'z[1, 1]')] <- c(-1, C)
pseudo_z_2[c('X[2, 1]', 'z[2, 1]')] <- c(-1, C)
pseudo_z_3[c('X[3, 1]', 'z[3, 1]')] <- c(-1, C)
pseudo_z_4[c('X[4, 1]', 'z[4, 1]')] <- c(-1, C)
pseudo_z_5[c('X[1, 2]', 'z[1, 2]')] <- c(-1, C)
pseudo_z_6[c('X[2, 2]', 'z[2, 2]')] <- c(-1, C)
pseudo_z_7[c('X[3, 2]', 'z[3, 2]')] <- c(-1, C)
pseudo_z_8[c('X[4, 2]', 'z[4, 2]')] <- c(-1, C)
## Next create pseudo constraints for Y[i] <= 0.5 * Z[i, 1] + 0.5 * Z[i, 2]
pseudo_y_1 <- numeric(n)
names(pseudo_y_1) <- names(f.obj)
pseudo_y_4 <- pseudo_y_3 <- pseudo_y_2 <- pseudo_y_1
pseudo_y_1[c('Y[1]', 'z[1, 1]', 'z[1, 2]')] <- c(1, -0.5, -0.5)
pseudo_y_2[c('Y[2]', 'z[2, 1]', 'z[2, 2]')] <- c(1, -0.5, -0.5)
pseudo_y_3[c('Y[3]', 'z[3, 1]', 'z[3, 2]')] <- c(1, -0.5, -0.5)
pseudo_y_4[c('Y[4]', 'z[4, 1]', 'z[4, 2]')] <- c(1, -0.5, -0.5)
#Combine them all together
cons <- c(paste0('cons', 1:12), paste0('pseudo_z_', 1:8), paste0('pseudo_y_', 1:4))
cons.mat <- do.call(rbind, mget(cons)) #mget finds all variables given in cons.
</code>```

Phew... Again we then have to create our direction and rhs. And we have to make sure binary.vec specifies z[i, j] as binary. Lets do this in order

```<code>cons.dir <- c(rep('>=', 4), rep('<=', 8), rep('>=' 8), rep('<=', 4))
names(cons.dir) <- cons
cons.rhs <- c(750, 800, 1000, 300, rep(0, 8), rep(0, 8), rep(0, 4))
#Update binary.vec to include z[i, j]
binary.vec <- c(binary.vec, seq(n, n - 7))
</code>```

Now we should've everything set up and ready to go

```<code>lpSolve::lp('min', objective.in = f.obj,
            const.mat = cons.mat,
            const.dir = cons.dir,
            const.rhs = cons.rhs,
            binary.vec = binary.vec)
res$objval
[1] 27483.29
names(res$solution) <- names(f.obj)
options(scipen = 999) #avoid scientific notation. Just to make it readable for us.
round(res$solution[res$solution != 0], 3)
X[4, 1] X[4, 2] X[4, 3] X[3, 4]    Y[4] z[4, 1] z[4, 2]
357.143 307.692 526.316 115.385   1.000   1.000   1.000
</code>```

Which seems to fit with our constraints. As this is rather much to copy-paste into R, i've added the code to this repository, which can be loaded and executed.

Side note

The way I've illustrated the solution here, is a very illustrative step-by-step method. This makes it simple to follow along, but in reality one would use for-loops or software which allows for more naturally written constraints. If problems become a bit more complex than this, I highly encourage using an alternative package, which might also have a faster algorithm implemented.

Should I generate the optimal solution first before satisfying the linking variables?

In your current problem you don't have any linking variables. Linking variables are usually variables obtained from a sub-optimization problem, for example

```<code>Max sum_i a[i] * y[i] * x[i] [for i in 1:10]
st.
y[i] %in% 0:1
x[i] = argmin{
  3 x[i]^2 + 4
  st.
  x[i] != x[j] [ for all i, j ]
}
</code>```

and in this case the standard optimization problem is not necessarily useful.

Title: Minimization problem with linking constraints in R

Body:
How should I incorporate the linking constraints into the optimization problem formulation in equations 1 - 4 where Y_i's are binary variables?

minimize
    22X11 + 20.5X12 + 21X13 + 19X14 + 21X21 + 21X22 + 18X23 + 17X24 +
    22X31 + 24X32 + 22X33 + 23X34 + 22X41 + 16X42 + 17X43 + 17.5X44 +
    1500 Y1 + 1700 Y2 + 1500 Y3 + 1400 Y4

subject to constraints

    2.00 X11 + 1.80 X21 + 2.30 X31 + 2.10 X41 >= 750
    2.80 X12 + 2.30 X22 + 2.20 X32 + 2.60 X42 >= 800
    1.70 X13 + 1.75 X23 + 1.60 X33 + 1.90 X43 >= 1000
    2.40 X14 + 1.90 X24 + 2.60 X34 + 2.40 X44 >= 300

    X11 - 1500 Y1 <= 0
    X21 - 2000 Y2 <= 0
    X31 - 1500 Y3 <= 0
    X41 - 1800 Y4 <= 0
    X12 - 500 Y1 >= 0
    X22 - 500 Y2 >= 0
    X32 - 500 Y3 >= 0
    X42 - 500 Y4 >= 0

    Y1 = 1 if X11>0 and 0 otherwise
    Y1 = 1 if X12>0 and 0 otherwise
    Y2 = 1 if X21>0 and 0 otherwise
    Y2 = 1 if X22>0 and 0 otherwise
    Y3 = 1 if X31>0 and 0 otherwise
    Y3 = 1 if X32>0 and 0 otherwise
    Y4 = 1 if X41>0 and 0 otherwise
    Y4 = 1 if X42>0 and 0 otherwise

R code to find optimal solutions without those linking variables:

library(lpSolve)
f.obj <-  c(22,20.5,21,19,21,21,18,17,22,24,22,23,22,16,17,17.5,1500,1700,1500,1400)

const1 = c(2.00,1.80,2.30,2.10)
const2 = c(2.80,2.30,2.20,2.60)
const3 = c(1.70,1.75,1.60,1.90)
const4 = c(2.40,1.90,2.60,2.40)

f.con <- rbind(const1,const2,const3,const4)
f.dir <- c(rep(">=",2), ">=", ">=")
f.rhs <- c(750,800,1000,300)
res <- lp("min", f.obj, f.con,f.dir,f.rhs, binary.vec=c(1,2))

res$solution
res$objective
res$objval

Body:
How should I incorporate the linking constraints to satisfy the constraints where Y1 = 1, Y2 = 2, Y3 = 3, and Y4 = 4 using Binary.vec?

I believe that you mean Y[i] = 1 [ for i in 1:4 ].

The binary.vec argument is a

Numeric vector like int.vec giving the indices of variables that are required to be binary.

Now the indices here refer to the optimization problem. Thus we need the indices to match the position of Y[i] [for i in 1:4 ]. In this case it's the latter 4 in your objective function, so we could get their indices as

binary.vec <- seq(length(f.obj), length(f.obj) - 3)

Note however, that your current problem is not looking for a strictly binary Y[i], but further you are looking for Y[i] given the value of some other parameter. As it is written it is not a linear constraint, thus we need to do some trickery.

The problem here is that you need Y[i] = 1 if X[i,1] > 0 and X[i, 2] > 0, 0 otherwise, and simply adding Y[i] %in% 0:1 won't necessarily uphold the constraints. There are several ways of getting past this, but the one I find the most intuitive is to reformulate the problem using pseudo-parameters

C * z[i, j] > x[i, j] [ for all i, j ]
z[i, j] %in% 0:1 [ for all i, j ]
C = Inf
z[i, j] = 1 if X[i, j] > 0, 0 otherwise [ for i in 1:4, j in 1:2 ]
Y[i] <= 0.5 * z[i, 1] + 0.5 * z[i, 2]

The trick here is that now we have only linear constrants. Notice that if only z[i, 1] = 1 these constraints forces Y[i] = 0.

We have a increased the number of parameters quite a bit, but this problem is linear as all equations are written in the form y = a * x + b.

However as I described in my answer to your previous question when we add pseudo-parameters we need to

Extend our objective function, so it includes these as pseudo-parameters (make the solver aware of the parameters in the optimization function)

Extend our constraints, in order to keep dimensions correct (make the solver aware of how these affect the remaining constraints)

Extending optimization problem

Now this is the simple part. Simply add the parameters at the end of your existing equation. I always suggest naming the objective function if one finds it hard to keep track

n <- length(f.obj)
names(f.obj)[seq(n - 4)] <- paste0('X[', rep(1:4, 2), ', ', rep(1:2, each = 4), ']')
names(f.obj)[-seq(n - 4)] <- paste0('Y[', 1:4, ']')
f.obj <- c(f.obj, numeric(8))
n <- length(f.obj)
names(f.obj)[seq(n - 7, n)] <- paste0('z[', rep(1:4, 2), ', ', rep(1:2, each = 4), ']')
tail(f.obj, 12)
   Y[1]    Y[2]    Y[3]    Y[4] z[1, 1] z[2, 1] z[3, 1] z[4, 1] z[1, 2] z[2, 2] z[3, 2] z[4, 2]
   1500    1700    1500    1400       0       0       0       0       0       0       0       0

Note here, that they all gain a weight of 0, because their effect is captured by the effect of X[i, j] and Y[i].

Extend your constraints

Now this is again the tricky part. First note as in my answer to the previous question, that the dimensions of your constraints have to match your objective function. In this problem you have length(f.obj) = 28 (including the new pseudo-parameters), so all constraints needs to have 28 columns. The general idea here is that we (figuratively) add sum_[i, j] 0 * X[i, j] + sum_[i] 0 * Y[i] to every constraint. Thus your constraints should be

cons1 <- numeric(n)
names(cons1) <- names(f.obj)
cons12 <- cons11 <- cons10 <- cons9 <- cons8 <- cons7 <- cons6 <- cons5 <- cons4 <- cons3 <- cons2 <- cons1
cons1[1:4] <- c(2, 1.8, 2.3, 2.1)
cons2[5:8] <- c(2.8, 2.3, 2.2, 2.6)
cons3[9:12] <- c(1.7, 1.75, 1.6, 1.9)
cons4[13:16] <- c( 2.4, 1.9, 2.6, 2.4)
#X[i, j] - Cy[i] * Y[i] <= 0
cons5[c('X[1, 1]', 'Y[1]')] <- c(1, -1500)
cons6[c('X[2, 1]', 'Y[2]')] <- c(1, -2000)
cons7[c('X[3, 1]', 'Y[3]')] <- c(1, -1500)
cons8[c('X[4, 1]', 'Y[4]')] <- c(1, -1800)
cons9[c('X[1, 2]', 'Y[1]')] <- c(1, -500)
cons10[c('X[2, 2]', 'Y[2]')] <- c(1, -500)
cons11[c('X[3, 2]', 'Y[3]')] <- c(1, -500)
cons12[c('X[4, 2]', 'Y[4]')] <- c(1, -500)
#Pseudo-constraints
## Start with C * z[i, j] > x[i, j] for some very large C (here i choose 1e12, but could be any number large enough so X[i, j] does not exceed it!)
pseudo_z_1 <- numeric(n)
names(pseudo_z_1) <- names(f.obj)
pseudo_z_8 <- pseudo_z_7 <- pseudo_z_6 <- pseudo_z_5 <- pseudo_z_4 <- pseudo_z_3 <- pseudo_z_2 <- pseudo_z_1
C <- 1e12
pseudo_z_1[c('X[1, 1]', 'z[1, 1]')] <- c(-1, C)
pseudo_z_2[c('X[2, 1]', 'z[2, 1]')] <- c(-1, C)
pseudo_z_3[c('X[3, 1]', 'z[3, 1]')] <- c(-1, C)
pseudo_z_4[c('X[4, 1]', 'z[4, 1]')] <- c(-1, C)
pseudo_z_5[c('X[1, 2]', 'z[1, 2]')] <- c(-1, C)
pseudo_z_6[c('X[2, 2]', 'z[2, 2]')] <- c(-1, C)
pseudo_z_7[c('X[3, 2]', 'z[3, 2]')] <- c(-1, C)
pseudo_z_8[c('X[4, 2]', 'z[4, 2]')] <- c(-1, C)
## Next create pseudo constraints for Y[i] <= 0.5 * Z[i, 1] + 0.5 * Z[i, 2]
pseudo_y_1 <- numeric(n)
names(pseudo_y_1) <- names(f.obj)
pseudo_y_4 <- pseudo_y_3 <- pseudo_y_2 <- pseudo_y_1
pseudo_y_1[c('Y[1]', 'z[1, 1]', 'z[1, 2]')] <- c(1, -0.5, -0.5)
pseudo_y_2[c('Y[2]', 'z[2, 1]', 'z[2, 2]')] <- c(1, -0.5, -0.5)
pseudo_y_3[c('Y[3]', 'z[3, 1]', 'z[3, 2]')] <- c(1, -0.5, -0.5)
pseudo_y_4[c('Y[4]', 'z[4, 1]', 'z[4, 2]')] <- c(1, -0.5, -0.5)
#Combine them all together
cons <- c(paste0('cons', 1:12), paste0('pseudo_z_', 1:8), paste0('pseudo_y_', 1:4))
cons.mat <- do.call(rbind, mget(cons)) #mget finds all variables given in cons.

Phew... Again we then have to create our direction and rhs. And we have to make sure binary.vec specifies z[i, j] as binary. Lets do this in order

cons.dir <- c(rep('>=', 4), rep('<=', 8), rep('>=' 8), rep('<=', 4))
names(cons.dir) <- cons
cons.rhs <- c(750, 800, 1000, 300, rep(0, 8), rep(0, 8), rep(0, 4))
#Update binary.vec to include z[i, j]
binary.vec <- c(binary.vec, seq(n, n - 7))

Now we should've everything set up and ready to go

lpSolve::lp('min', objective.in = f.obj,
            const.mat = cons.mat,
            const.dir = cons.dir,
            const.rhs = cons.rhs,
            binary.vec = binary.vec)
res$objval
[1] 27483.29
names(res$solution) <- names(f.obj)
options(scipen = 999) #avoid scientific notation. Just to make it readable for us.
round(res$solution[res$solution != 0], 3)
X[4, 1] X[4, 2] X[4, 3] X[3, 4]    Y[4] z[4, 1] z[4, 2]
357.143 307.692 526.316 115.385   1.000   1.000   1.000

Which seems to fit with our constraints. As this is rather much to copy-paste into R, i've added the code to this repository, which can be loaded and executed.

Side note

The way I've illustrated the solution here, is a very illustrative step-by-step method. This makes it simple to follow along, but in reality one would use for-loops or software which allows for more naturally written constraints. If problems become a bit more complex than this, I highly encourage using an alternative package, which might also have a faster algorithm implemented.

Should I generate the optimal solution first before satisfying the linking variables?

In your current problem you don't have any linking variables. Linking variables are usually variables obtained from a sub-optimization problem, for example

Max sum_i a[i] * y[i] * x[i] [for i in 1:10]
st.
y[i] %in% 0:1
x[i] = argmin{
  3 x[i]^2 + 4
  st.
  x[i] != x[j] [ for all i, j ]
}

and in this case the standard optimization problem is not necessarily useful.


问:
Cannot Open Python. Error 0xc000007b
I have recently been learning Python 3. I have had no problems on my netbook (32bit Windows 7) I with creating small simple programs. When I installed it on my netbook I had no problems, but now that I've been getting into it I want to install it on my desktop and I have one.
My desktop is a 64 bit OS running Windows 7. Like I did with my netbook, I went to download Python and install the 64 bit edition.

After installing it, I went to open up Python CLI and GUI and no luck. It gave me this error.

```<code>"The application was unable to start correctly (0xc000007b). Click OK to close the application"
</code>```

I also tried reinstalling, but not luck.

I suspect a missing .dll but I am not completely sure. Does anyone know what is keeping me from opening Python and how do I fix it?. I want to resume my work as soon as possible.

答:
Like many have said, Windows cannot load python.exe itself or one of its dependent DLLs because of INVALID_IMAGE_FORMAT:

python.exe is of unsupported bitness. 32bit on 64bit Windows is supported. 64bit on 32bit system is not (solution: install 32bit python, bye).

python.exe or one of its DLLs is corrupted (probably not)

one of the dependent DLLs is not of the same bitness as the EXE:

python.exe (say, 32bit) requires python*.dll (python3.dll or python27.dll). It installs that into Windows System32/SysWOW64 folder. The DLL is of correct bitness (32bit).

Something else overwrites that with 64-bit version, or places a 64-bit version somewhere in the search PATH.

When you run python.exe (32bit), Windows searches for python*.dll, and the first one it founds is the 64bit one. 32bit EXEs cannot normally load 64bit DLLs.

Typical examples:

TortoiseHg installs its own copy of python (both .exe and .dll) into its own folder and adds itself to PATH. The bitness can be different (say, 64bit) and usually matches platform bitness.

Another installation of Python with a different bitness somewhere else overwrites the DLL (it shouldn't, they have different System32s, but who knows)

Diagnostics:

Dependency Walker marks 64bit DLLs with 64bit icons. Verify that icons for python.exe and python*.dll match. Right click -> "Show full paths" to see where the DLL is taken from.

Simple solutions:

Maybe you have another, functioning copy of Python somewhere else? Check it.

Reinstall Python, preferably in the platform version (64bit for 64bit OS, 32bit for 32bit) Yeah, that's what many are saying, but now you know why this is needed.

Remove offenders from PATH. While this maaaay fix your Python, this will break the offenders and some (TortoiseHg explorer plugins) need the PATH. So maybe compromise with them and choose #2.

Title: Cannot Open Python. Error 0xc000007b

Body:
I have recently been learning Python 3. I have had no problems on my netbook (32bit Windows 7) I with creating small simple programs. When I installed it on my netbook I had no problems, but now that I've been getting into it I want to install it on my desktop and I have one.
My desktop is a 64 bit OS running Windows 7. Like I did with my netbook, I went to download Python and install the 64 bit edition.

After installing it, I went to open up Python CLI and GUI and no luck. It gave me this error.

"The application was unable to start correctly (0xc000007b). Click OK to close the application"

I also tried reinstalling, but not luck.

I suspect a missing .dll but I am not completely sure. Does anyone know what is keeping me from opening Python and how do I fix it?. I want to resume my work as soon as possible.


问:
How to tidy exported html file's source code?
Using VBA, I export an Excel spreadsheet as a web page.

The source code of the exported html file is quite messed up. There are multiple line breaks in between. For eg:

```<code> <td colspan="3" class="xl681522" style="height:17.1pt" height="22">Select X
  and Y</td>
<td class="xl731522" style="width:253pt" width="337">Hello World
 and my country</td>
</code>```

How can I tidy up the html source code, like:

```<code><td colspan="3" class="xl681522" style="height:17.1pt" height="22">Select X and Y</td>
<td class="xl731522" style="width:253pt" width="337">Hello World and my country</td>
</code>```

答:
This might help or simply CTRL + H then search <*> and replace with " " (blank)
:</p>

```<code>'PURPOSE: Find & Replace a list of text/values throughout entire workbook from a table
'SOURCE: www.TheSpreadsheetGuru.com/the-code-vault, I used <p*> to <p> in the table
Dim sht As Worksheet
Dim fndList As Integer
Dim rplcList As Integer
Dim tbl As ListObject
Dim myArray As Variant

'Create variable to point to your table
  Set tbl = Worksheets("Sheet1").ListObjects("Table1")

'Create an Array out of the Table's Data
  Set TempArray = tbl.DataBodyRange
  myArray = Application.Transpose(TempArray)

'Designate Columns for Find/Replace data
  fndList = 1
  rplcList = 2

'Loop through each item in Array lists
  For x = LBound(myArray, 1) To UBound(myArray, 2)
    'Loop through each worksheet in ActiveWorkbook (skip sheet with table in it)
      For Each sht In ActiveWorkbook.Worksheets
        If sht.Name <> tbl.Parent.Name Then

          sht.Cells.Replace What:=myArray(fndList, x), Replacement:=myArray(rplcList, x), _
            LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, _
            SearchFormat:=False, ReplaceFormat:=False

        End If
      Next sht
  Next x

End Sub

</code>```

Body:
Using VBA, I export an Excel spreadsheet as a web page.

The source code of the exported html file is quite messed up. There are multiple line breaks in between. For eg:

 Select X
  and Y
Hello World
 and my country

How can I tidy up the html source code, like:

Select X and Y
Hello World and my country

Body:
This might help or simply CTRL + H then search <*> and replace with " " (blank)
:

'PURPOSE: Find & Replace a list of text/values throughout entire workbook from a table
'SOURCE: www.TheSpreadsheetGuru.com/the-code-vault, I used <p*> to <p> in the table
Dim sht As Worksheet
Dim fndList As Integer
Dim rplcList As Integer
Dim tbl As ListObject
Dim myArray As Variant

'Create variable to point to your table
  Set tbl = Worksheets("Sheet1").ListObjects("Table1")

'Create an Array out of the Table's Data
  Set TempArray = tbl.DataBodyRange
  myArray = Application.Transpose(TempArray)

'Designate Columns for Find/Replace data
  fndList = 1
  rplcList = 2

'Loop through each item in Array lists
  For x = LBound(myArray, 1) To UBound(myArray, 2)
    'Loop through each worksheet in ActiveWorkbook (skip sheet with table in it)
      For Each sht In ActiveWorkbook.Worksheets
        If sht.Name <> tbl.Parent.Name Then

          sht.Cells.Replace What:=myArray(fndList, x), Replacement:=myArray(rplcList, x), _
            LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, _
            SearchFormat:=False, ReplaceFormat:=False

        End If
      Next sht
  Next x

End Sub


问:
Is Date.now() okay to use, will it reach a number that JS can't handle?
Is there a possibility that Date.now() will start returning numbers in scientific notation?

It can possibly be a bug like Y2K. Is it safe to use it? Will it cross the biggest
number possible in JavaScript?

答:
The biggest integer (Number.MAX_SAFE_INTEGER) JavaScript can handle is 2^53 - 1.

Converting that to years:

```<code>console.log(Number.MAX_SAFE_INTEGER / 1000 / 60 / 60 / 24 / 365)
// outputs 285616.41472415626
</code>```

So the answer is YES, it's safe to use it.

Body:
The biggest integer (Number.MAX_SAFE_INTEGER) JavaScript can handle is 2^53 - 1.

Converting that to years:

console.log(Number.MAX_SAFE_INTEGER / 1000 / 60 / 60 / 24 / 365)
// outputs 285616.41472415626

So the answer is YES, it's safe to use it.


问:
Binary Data SMS not received on emulator
I'm trying to send and receive binary data sms from my app (sdk 2.1-update 1), with no luck

I have set up the following receivers in the manifest:

```<code><receiver android:name=".MainReceiver">
    <intent-filter android:priority="10">
        <action android:name="android.provider.Telephony.SMS_RECEIVED" />
    </intent-filter>
</receiver>
<receiver android:name=".MainReceiver">
    <intent-filter android:priority="10">
        <action android:name="android.intent.action.DATA_SMS_RECEIVED" />
    </intent-filter>
</receiver>
</code>```

I tried with and without the data tags for the action DATA_SMS_RECEIVED:

```<code><data android:scheme="sms"/>
<data android:host="localhost"/>
<data android:port="16001"/>
</code>```

I specified all the permissions i could related to sending/receiving/reading SMS, or MMS, etc.. just to be sure it isn't a permission issue..

I'm sending an sms, and a data sms, from emulator on port 5556, to emulator on port 5554.

Emulator 5554 receives the ordinary sms without problems, but it doesn't receive the data sms, and nothing shows up in the inbox either..

maybe it's never sent, this is the sample code that sends the sms:

```<code>SmsManager mgr = SmsManager.getDefault();
mgr.sendTextMessage("5554", null, "message", null, null);
mgr.sendDataMessage("5554", null, (short) 16001, "message".getBytes(), null, null);
</code>```

The broadcast receiver just shows a Toast message when it receives something.

I've spent 5 hours trying every possibile combination of receivers, data tags, port numbers, absolutely nothing has ever been received as data sms..

I'm out of ideas, really..

答:
It seems like emulators doesn't work well with data sms.. they don't throw any exception but they don't send the data messages. For this reason, sendDataMessage() seems to work fine because it doesn't throw any error, but the truth is that it just doesn't send anything!

Using a device, everything works well!

Body:
I'm trying to send and receive binary data sms from my app (sdk 2.1-update 1), with no luck

I have set up the following receivers in the manifest:

<receiver android:name=".MainReceiver">
    <intent-filter android:priority="10">
        <action android:name="android.provider.Telephony.SMS_RECEIVED" />
    </intent-filter>
</receiver>
<receiver android:name=".MainReceiver">
    <intent-filter android:priority="10">
        <action android:name="android.intent.action.DATA_SMS_RECEIVED" />
    </intent-filter>
</receiver>

I tried with and without the data tags for the action DATA_SMS_RECEIVED:

<data android:scheme="sms"/>
<data android:host="localhost"/>
<data android:port="16001"/>

I specified all the permissions i could related to sending/receiving/reading SMS, or MMS, etc.. just to be sure it isn't a permission issue..

I'm sending an sms, and a data sms, from emulator on port 5556, to emulator on port 5554.

Emulator 5554 receives the ordinary sms without problems, but it doesn't receive the data sms, and nothing shows up in the inbox either..

maybe it's never sent, this is the sample code that sends the sms:

SmsManager mgr = SmsManager.getDefault();
mgr.sendTextMessage("5554", null, "message", null, null);
mgr.sendDataMessage("5554", null, (short) 16001, "message".getBytes(), null, null);

The broadcast receiver just shows a Toast message when it receives something.

I've spent 5 hours trying every possibile combination of receivers, data tags, port numbers, absolutely nothing has ever been received as data sms..

I'm out of ideas, really..


问:
How to render the values in a parent child relationship in Django
I am creating a django app where the admin can add travel packages. To add the explicit details of the package I created a child that will handle those values. Here is how the code looks like.

```<code>class Category(models.Model):
    title = models.CharField(max_length=30)
    slug = models.SlugField(unique=True)

class Meta:
    ordering = ['title']

def __str__(self):
    return self.title

class SafariPackages(models.Model):
    image = models.ImageField(upload_to='SafariPackages/%Y/%m/%d', null=False)
    title = models.CharField(max_length=200)
    cost = models.FloatField(null=False)
    days = models.FloatField(blank=False, null=False)
    nights = models.FloatField(blank=False, null=False)
    category = models.ManyToManyField(Category)
    exodus = models.CharField(max_length=200)
    destination = models.CharField(max_length=200)
    telegram = models.TextField(max_length=140, null=False)
    description = models.TextField(null=False)
    slug = models.SlugField(max_length=200, unique=True)

objects = EntryQuerySet.as_manager()

def __str__(self):
    return self.title

class Meta:
    verbose_name = 'Safari Package Entry'
    verbose_name_plural = 'Safari Package Entries'

class DayNumber(models.Model):
    daydetails = models.ForeignKey(SafariPackages, related_name='daydetails', default=1, on_delete=models.CASCADE)
    day_number = models.CharField( max_length=10, null=True, blank=True)
    image = models.ImageField (upload_to='SafariPackagesDetails/%Y/%m/%d', null=False, default=1)
    day_description = models.TextField()
</code>```

The views that I have so far look like this

```<code>def safaripackages_view(request, *args,**kwargs):
    print (args, kwargs)
    print (request.user)

    all_safaripackages = SafariPackages.objects.all()

#Paginator
paginator = Paginator(all_safaripackages, 8)
page = request.GET.get('page')
try:
    all_safaripackages = paginator.page(page)
except PageNotAnInteger:
    all_safaripackages = paginator.page(1)
except EmptyPage:
    all_safaripackages = paginator.page(paginator.num_pages)

context = {
'all_safaripackages': all_safaripackages,
}

return render (request, "safaripackages.html", context)

def single_safaripackage(request, post_id):
    safaripackage = SafariPackages.objects.get(pk=post_id)
    return render (request, 'single_safaripackage.html', {'safaripackage':safaripackage,})
</code>```

How do I include the values of the DayNumber model in the single_safaripackage view?

答:
```<code>def single_safaripackage(request, post_id):
    safaripackage = SafariPackages.objects.get(pk=post_id)
    day_number = DayNumber.objects.filter(safaripackage__id = post_id)
    return render (request, 'single_safaripackage.html', {'safaripackage':safaripackage, 'day_number':day_number })
</code>```

Body:
I am creating a django app where the admin can add travel packages. To add the explicit details of the package I created a child that will handle those values. Here is how the code looks like.

class Category(models.Model):
    title = models.CharField(max_length=30)
    slug = models.SlugField(unique=True)

class Meta:
    ordering = ['title']

def __str__(self):
    return self.title

class SafariPackages(models.Model):
    image = models.ImageField(upload_to='SafariPackages/%Y/%m/%d', null=False)
    title = models.CharField(max_length=200)
    cost = models.FloatField(null=False)
    days = models.FloatField(blank=False, null=False)
    nights = models.FloatField(blank=False, null=False)
    category = models.ManyToManyField(Category)
    exodus = models.CharField(max_length=200)
    destination = models.CharField(max_length=200)
    telegram = models.TextField(max_length=140, null=False)
    description = models.TextField(null=False)
    slug = models.SlugField(max_length=200, unique=True)

objects = EntryQuerySet.as_manager()

def __str__(self):
    return self.title

class Meta:
    verbose_name = 'Safari Package Entry'
    verbose_name_plural = 'Safari Package Entries'

class DayNumber(models.Model):
    daydetails = models.ForeignKey(SafariPackages, related_name='daydetails', default=1, on_delete=models.CASCADE)
    day_number = models.CharField( max_length=10, null=True, blank=True)
    image = models.ImageField (upload_to='SafariPackagesDetails/%Y/%m/%d', null=False, default=1)
    day_description = models.TextField()

The views that I have so far look like this

def safaripackages_view(request, *args,**kwargs):
    print (args, kwargs)
    print (request.user)

    all_safaripackages = SafariPackages.objects.all()

#Paginator
paginator = Paginator(all_safaripackages, 8)
page = request.GET.get('page')
try:
    all_safaripackages = paginator.page(page)
except PageNotAnInteger:
    all_safaripackages = paginator.page(1)
except EmptyPage:
    all_safaripackages = paginator.page(paginator.num_pages)

context = {
'all_safaripackages': all_safaripackages,
}

return render (request, "safaripackages.html", context)

def single_safaripackage(request, post_id):
    safaripackage = SafariPackages.objects.get(pk=post_id)
    return render (request, 'single_safaripackage.html', {'safaripackage':safaripackage,})

How do I include the values of the DayNumber model in the single_safaripackage view?


问:
Cannot resolve MultiDexApplication after updating android studio 4.0
After updating android studio to 4.0 and gradle to 6.1.1. There are some issues in my project which can't resolve.

```<code>import androidx.multidex.MultiDexApplication
</code>```

and

```<code>public class MyApplication extends MultiDexApplication
</code>```

I have this lib in my project and using it
works fine on previous version of Android studio.

答:
Do you use MultidexApplication in a module that does not have multidex library dependency?

In you module build.gradle file:

```<code>dependencies {
    implementation 'androidx.multidex:multidex:2.0.1'
}
</code>```

Before gradle 6.1.1, you could use MultidexApplication in a library module and only have multidex dependency in the application module that depends on it. After the update, you need to have multidex depdency in your library module as well.

Body:
After updating android studio to 4.0 and gradle to 6.1.1. There are some issues in my project which can't resolve.

import androidx.multidex.MultiDexApplication

and

public class MyApplication extends MultiDexApplication

I have this lib in my project and using it
works fine on previous version of Android studio.

Body:
Do you use MultidexApplication in a module that does not have multidex library dependency?

In you module build.gradle file:

dependencies {
    implementation 'androidx.multidex:multidex:2.0.1'
}

Before gradle 6.1.1, you could use MultidexApplication in a library module and only have multidex dependency in the application module that depends on it. After the update, you need to have multidex depdency in your library module as well.


问:
Cannot save modified frames with Python OpenCV
I wrote this code to take a video file as input from my local storage, then display it and re-encode the frames in grayscale and save it to an output file. Here is my code:

import cv2 as cv

fourcc = cv.VideoWriter_fourcc(*'XVID')
out = cv.VideoWriter('output.avi', fourcc, 25.0, (640,  480))
cap = cv.VideoCapture(input())
if not cap.isOpened():
    print("Error opening video file")
    exit()
while cap.isOpened():
    ret, frame = cap.read()
    if not ret:
        print("Can't receive frame. Exiting ...")
        break

    frame = cv.cvtColor(frame, cv.COLOR_BGR2GRAY) #This line is causing the problem
    out.write(frame)
    cv.imshow('frame', frame)
    if cv.waitKey(1) == ord('q'):
        break

cap.release()
out.release()
cv.destroyAllWindows()
```

With this code, I can see the video file being played, but the output file appears blank. It works if I write the original frame object into the output file. But, whenever I use frame = cv.cvtColor(frame, cv.COLOR_BGR2GRAY) to convert the frame into grayscale, it does not work and I get a blank output file. What mistake am I doing?

答:
From the cv docs, here the signature of VideoWriter constructor is

```<code>VideoWriter (const String &filename, int fourcc, double fps, Size frameSize, bool isColor=true)
</code>```

i.e. if you're writing a grayscale image, you need to set the isColor param to false since it's true by default. Replace the line with this,

```<code>out = cv.VideoWriter('output.avi', fourcc, 25.0, (640,  480), 0)
</code>```

Body:
I wrote this code to take a video file as input from my local storage, then display it and re-encode the frames in grayscale and save it to an output file. Here is my code:

import cv2 as cv

fourcc = cv.VideoWriter_fourcc(*'XVID')
out = cv.VideoWriter('output.avi', fourcc, 25.0, (640,  480))
cap = cv.VideoCapture(input())
if not cap.isOpened():
    print("Error opening video file")
    exit()
while cap.isOpened():
    ret, frame = cap.read()
    if not ret:
        print("Can't receive frame. Exiting ...")
        break

    frame = cv.cvtColor(frame, cv.COLOR_BGR2GRAY) #This line is causing the problem
    out.write(frame)
    cv.imshow('frame', frame)
    if cv.waitKey(1) == ord('q'):
        break

cap.release()
out.release()
cv.destroyAllWindows()

With this code, I can see the video file being played, but the output file appears blank. It works if I write the original frame object into the output file. But, whenever I use frame = cv.cvtColor(frame, cv.COLOR_BGR2GRAY) to convert the frame into grayscale, it does not work and I get a blank output file. What mistake am I doing?

Body:
From the cv docs, here the signature of VideoWriter constructor is

VideoWriter (const String &filename, int fourcc, double fps, Size frameSize, bool isColor=true)

i.e. if you're writing a grayscale image, you need to set the isColor param to false since it's true by default. Replace the line with this,

out = cv.VideoWriter('output.avi', fourcc, 25.0, (640,  480), 0)


问:
gnuplot epslatex functionality in matplotlib
I am used to plot data with gnuplot, so I can easily put the figures in a LaTeX document, using the epslatex terminal. For example:

```<code>file = "data.dat"

set terminal epslatex
set output "figure1.tex"

plot file
</code>```

This way, two files are generated: one .eps file, which contains the graphics, and one .tex file, which contains the text. The great advantage of this is that text is rendered by LaTeX, so the tics, labels, etc. have the same font as the rest of the document.

Now I am starting with matplotlib, which has a much nicer API, is more scriptable and, well, is Python. But, even though I can make matplotlib render the text with LaTeX, it gets embedded into the image and I cannot achieve the same advantages I had with gnuplot.

Is there any way I can emulate the epslatex terminal in matplotlib?

答: Update: matplotlib 1.2 introduced a new PGF/TikZ backend, and I have successfully used it for the exact purpose stated in this question: make LaTeX / XeTeX render the text of the plot. In the documentation there are some nice examples of plotting using the PGF backend, including custom preambles, custom fonts and full unicode math support.

Body:
I am used to plot data with gnuplot, so I can easily put the figures in a LaTeX document, using the epslatex terminal. For example:

file = "data.dat"

set terminal epslatex
set output "figure1.tex"

plot file

This way, two files are generated: one .eps file, which contains the graphics, and one .tex file, which contains the text. The great advantage of this is that text is rendered by LaTeX, so the tics, labels, etc. have the same font as the rest of the document.

Now I am starting with matplotlib, which has a much nicer API, is more scriptable and, well, is Python. But, even though I can make matplotlib render the text with LaTeX, it gets embedded into the image and I cannot achieve the same advantages I had with gnuplot.

Is there any way I can emulate the epslatex terminal in matplotlib?