问:
SQL group by exclude NULL value from grouping
I've got this situation in a table

```<code>client   staff   code   time1   time2
------------------------
c1       null    code1
c2       null    code1
null     s1      code1
null     s2      code1
</code>```

Trying to grouping rows by staff and code :

```<code>SELECT GROUP_CONCAT(client),staff,code from table GROUP BY staff,code
</code>```

I get obviously:

```<code>client   staff   code   ...  time1   time2
------------------------
c1,c2    null    code1
null     s1      code1   <-
null     s2      code1   <-
</code>```

For the purpose of the feature requested i need the entries "focused" on the staff so i can get also relative time1 and time2.
The problem is that the rows indicated by the arrows above don't have any clients id so there is no chance to retrieve their data.
Client informations are into the staff = null row.

How can i achieve something like this?

```<code>client   staff   code   ...  time1   time2
------------------------
c1,c2    s1      code1   <-
c1,c2    s2      code1   <-
</code>```

thanks

答:
Use SELECT * and determine your common unique row. In my example I wanted profiles. Some people might not have messages, some people might not have authenticated. So instead of using GROUP BY on authentication or messages I used GROUP BY on the user name - all rows will have this data to return even after adding GROUP BY and rows with NULL columns will still be returned.

The code posted in the question does not return any unique rows hence commenting out the GROUP BY clause and using SELECT * to find that unique row is critical to determining which row you should use GROUP BY with. As pointed out by the other two answers you can use multiple columns for GROUP BY (and ORDER BY as well) delimited by commas.

Body:
I've got this situation in a table

client   staff   code   time1   time2
------------------------
c1       null    code1
c2       null    code1
null     s1      code1
null     s2      code1

Trying to grouping rows by staff and code :

SELECT GROUP_CONCAT(client),staff,code from table GROUP BY staff,code

I get obviously:

client   staff   code   ...  time1   time2
------------------------
c1,c2    null    code1
null     s1      code1   <-
null     s2      code1   <-

For the purpose of the feature requested i need the entries "focused" on the staff so i can get also relative time1 and time2.
The problem is that the rows indicated by the arrows above don't have any clients id so there is no chance to retrieve their data.
Client informations are into the staff = null row.

How can i achieve something like this?

client   staff   code   ...  time1   time2
------------------------
c1,c2    s1      code1   <-
c1,c2    s2      code1   <-

thanks


来源: stackexchange

问:
Increase max pod on Node
docker info : Server Version: 18.06.3-ce

```<code>[root@lgn-test-cp65 ~]# kubectl version
Client Version: version.Info{Major:"1", Minor:"11", GitVersion:"v1.11.9", GitCommit:"16236ce91790d4c75b79f6ce96841db1c843e7d2", GitTreeState:"clean", BuildDate:"2019-03-25T06:40:24Z", GoVersion:"go1.10.8", Compiler:"gc", Platform:"linux/amd64"}
Server Version: version.Info{Major:"1", Minor:"11", GitVersion:"v1.11.9", GitCommit:"16236ce91790d4c75b79f6ce96841db1c843e7d2", GitTreeState:"clean", BuildDate:"2019-03-25T06:30:48Z", GoVersion:"go1.10.8", Compiler:"gc", Platform:"linux/amd64"}
</code>```

I'm trying to increase MaxPods in Node but it's not working.
I would like to increase MaxPods from 110 to 200

My command

```<code>kubelet --max-pods=200 --kubeconfig=/root/.kube/config
</code>```

And result

```<code>[root@lgn-test-cp65 ~]# kubelet --max-pods=200 --kubeconfig=/root/.kube/config
Flag --max-pods has been deprecated, This parameter should be set via the config file specified by the Kubelet's --config flag. See https://kubernetes.io/docs/tasks/administer-cluster/kubelet-config-file/ for more information.
I0218 11:16:09.655793   22675 server.go:408] Version: v1.11.9
I0218 11:16:09.656132   22675 plugins.go:97] No cloud provider specified.
W0218 11:16:19.708398   22675 manager.go:251] Timeout trying to communicate with docker during initialization, will retry
I0218 11:16:20.723226   22675 server.go:648] --cgroups-per-qos enabled, but --cgroup-root was not specified.  defaulting to /
I0218 11:16:20.727579   22675 container_manager_linux.go:243] container manager verified user specified cgroup-root exists: []
I0218 11:16:20.727635   22675 container_manager_linux.go:248] Creating Container Manager object based on Node Config: {RuntimeCgroupsName: SystemCgroupsName: KubeletCgroupsName: ContainerRuntime:docker CgroupsPerQOS:true CgroupRoot:/ CgroupDriver:cgroupfs KubeletRootDir:/var/lib/kubelet ProtectKernelDefaults:false NodeAllocatableConfig:{KubeReservedCgroupName: SystemReservedCgroupName: EnforceNodeAllocatable:map[pods:{}] KubeReserved:map[] SystemReserved:map[] HardEvictionThresholds:[{Signal:memory.available Operator:LessThan Value:{Quantity:100Mi Percentage:0} GracePeriod:0s MinReclaim:<nil>} {Signal:nodefs.available Operator:LessThan Value:{Quantity:<nil> Percentage:0.1} GracePeriod:0s MinReclaim:<nil>} {Signal:nodefs.inodesFree Operator:LessThan Value:{Quantity:<nil> Percentage:0.05} GracePeriod:0s MinReclaim:<nil>} {Signal:imagefs.available Operator:LessThan Value:{Quantity:<nil> Percentage:0.15} GracePeriod:0s MinReclaim:<nil>}]} QOSReserved:map[] ExperimentalCPUManagerPolicy:none ExperimentalCPUManagerReconcilePeriod:10s ExperimentalPodPidsLimit:-1 EnforceCPULimits:true}
I0218 11:16:20.727862   22675 container_manager_linux.go:267] Creating device plugin manager: true
I0218 11:16:20.727938   22675 state_mem.go:36] [cpumanager] initializing new in-memory state store
I0218 11:16:20.728028   22675 state_mem.go:84] [cpumanager] updated default cpuset: ""
I0218 11:16:20.728043   22675 state_mem.go:92] [cpumanager] updated cpuset assignments: "map[]"
I0218 11:16:20.728221   22675 kubelet.go:299] Watching apiserver
I0218 11:16:20.749497   22675 client.go:75] Connecting to docker on unix:///var/run/docker.sock
I0218 11:16:20.749540   22675 client.go:104] Start docker client with request timeout=2m0s
W0218 11:16:20.752947   22675 docker_service.go:545] Hairpin mode set to "promiscuous-bridge" but kubenet is not enabled, falling back to "hairpin-veth"
I0218 11:16:20.752989   22675 docker_service.go:238] Hairpin mode set to "hairpin-veth"
I0218 11:16:20.780638   22675 docker_service.go:253] Docker cri networking managed by kubernetes.io/no-op
I0218 11:16:20.939375   22675 docker_service.go:258] Docker Info: &{ID:RS55:WJBO:XXTM:PPAJ:HLUV:UBH7:ZWFK:WERN:ZIHT:PAJ6:2RWI:7WOA Containers:429 ContainersRunning:302 ContainersPaused:0 ContainersStopped:127 Images:59 Driver:devicemapper DriverStatus:[[Pool Name docker-253:0-67351869-pool] [Pool Blocksize 65.54kB] [Base Device Size 10.74GB] [Backing Filesystem xfs] [Udev Sync Supported true] [Data file /dev/loop0] [Metadata file /dev/loop1] [Data loop file /var/lib/docker/devicemapper/devicemapper/data] [Metadata loop file /var/lib/docker/devicemapper/devicemapper/metadata] [Data Space Used 23.34GB] [Data Space Total 107.4GB] [Data Space Available 84.03GB] [Metadata Space Used 62.43MB] [Metadata Space Total 2.147GB] [Metadata Space Available 2.085GB] [Thin Pool Minimum Free Space 10.74GB] [Deferred Removal Enabled true] [Deferred Deletion Enabled true] [Deferred Deleted Device Count 0] [Library Version 1.02.158-RHEL7 (2019-05-13)]] SystemStatus:[] Plugins:{Volume:[local] Network:[bridge host macvlan null overlay] Authorization:[] Log:[awslogs fluentd gcplogs gelf journald json-file logentries splunk syslog]} MemoryLimit:true SwapLimit:true KernelMemory:true CPUCfsPeriod:true CPUCfsQuota:true CPUShares:true CPUSet:true IPv4Forwarding:true BridgeNfIptables:true BridgeNfIP6tables:true Debug:false NFd:1358 OomKillDisable:true NGoroutines:1195 SystemTime:2020-02-18T11:16:20.857237756+01:00 LoggingDriver:json-file CgroupDriver:cgroupfs NEventsListener:1 KernelVersion:3.10.0-1062.9.1.el7.x86_64 OperatingSystem:CentOS Linux 7 (Core) OSType:linux Architecture:x86_64 IndexServerAddress:https://index.docker.io/v1/ RegistryConfig:0xc42042c070 NCPU:16 MemTotal:67385786368 GenericResources:[] DockerRootDir:/var/lib/docker HTTPProxy: HTTPSProxy: NoProxy: Name:lgn-test-cp65.intranet.novaliance.com Labels:[] ExperimentalBuild:false ServerVersion:18.06.3-ce ClusterStore: ClusterAdvertise: Runtimes:map[runc:{Path:docker-runc Args:[]}] DefaultRuntime:runc Swarm:{NodeID: NodeAddr: LocalNodeState:inactive ControlAvailable:false Error: RemoteManagers:[] Nodes:0 Managers:0 Cluster:<nil>} LiveRestoreEnabled:false Isolation: InitBinary:docker-init ContainerdCommit:{ID:468a545b9edcd5932818eb9de8e72413e616e86e Expected:468a545b9edcd5932818eb9de8e72413e616e86e} RuncCommit:{ID:a592beb5bc4c4092b1b1bac971afed27687340c5 Expected:a592beb5bc4c4092b1b1bac971afed27687340c5} InitCommit:{ID:fec3683 Expected:fec3683} SecurityOptions:[name=seccomp,profile=default]}
I0218 11:16:20.939536   22675 docker_service.go:271] Setting cgroupDriver to cgroupfs
I0218 11:16:21.050308   22675 kuberuntime_manager.go:186] Container runtime docker initialized, version: 18.06.3-ce, apiVersion: 1.38.0
I0218 11:16:21.050912   22675 csi_plugin.go:138] kubernetes.io/csi: plugin initializing...
E0218 11:16:21.056297   22675 kubelet.go:1252] Image garbage collection failed once. Stats initialization may not have completed yet: failed to get imageFs info: unable to find data for container /
I0218 11:16:21.057696   22675 server.go:129] Starting to listen on 0.0.0.0:10250
I0218 11:16:21.058671   22675 server.go:302] Adding debug handlers to kubelet server.
F0218 11:16:21.059593   22675 server.go:141] listen tcp 0.0.0.0:10250: bind: address already in use
</code>```

thanks for your help. I already made the config file and it's not working.

```<code>[root@lgn-test-cp65 ~]# kubelet --config=maxpod.yaml --kubeconfig=/root/.kube/config
I0218 13:50:09.199888   26656 server.go:408] Version: v1.11.9
I0218 13:50:09.200319   26656 plugins.go:97] No cloud provider specified.
I0218 13:50:09.374179   26656 server.go:648] --cgroups-per-qos enabled, but --cgroup-root was not specified.  defaulting to /
I0218 13:50:09.393932   26656 container_manager_linux.go:243] container manager verified user specified cgroup-root exists: []
I0218 13:50:09.393977   26656 container_manager_linux.go:248] Creating Container Manager object based on Node Config: {RuntimeCgroupsName: SystemCgroupsName: KubeletCgroupsName: ContainerRuntime:docker CgroupsPerQOS:true CgroupRoot:/ CgroupDriver:cgroupfs KubeletRootDir:/var/lib/kubelet ProtectKernelDefaults:false NodeAllocatableConfig:{KubeReservedCgroupName: SystemReservedCgroupName: EnforceNodeAllocatable:map[pods:{}] KubeReserved:map[] SystemReserved:map[] HardEvictionThresholds:[{Signal:nodefs.inodesFree Operator:LessThan Value:{Quantity:<nil> Percentage:0.05} GracePeriod:0s MinReclaim:<nil>} {Signal:imagefs.available Operator:LessThan Value:{Quantity:<nil> Percentage:0.15} GracePeriod:0s MinReclaim:<nil>} {Signal:memory.available Operator:LessThan Value:{Quantity:100Mi Percentage:0} GracePeriod:0s MinReclaim:<nil>} {Signal:nodefs.available Operator:LessThan Value:{Quantity:<nil> Percentage:0.1} GracePeriod:0s MinReclaim:<nil>}]} QOSReserved:map[] ExperimentalCPUManagerPolicy:none ExperimentalCPUManagerReconcilePeriod:10s ExperimentalPodPidsLimit:-1 EnforceCPULimits:true}
I0218 13:50:09.394140   26656 container_manager_linux.go:267] Creating device plugin manager: true
I0218 13:50:09.394223   26656 state_mem.go:36] [cpumanager] initializing new in-memory state store
I0218 13:50:09.394326   26656 state_mem.go:84] [cpumanager] updated default cpuset: ""
I0218 13:50:09.394343   26656 state_mem.go:92] [cpumanager] updated cpuset assignments: "map[]"
I0218 13:50:09.394518   26656 kubelet.go:299] Watching apiserver
I0218 13:50:09.399816   26656 client.go:75] Connecting to docker on unix:///var/run/docker.sock
I0218 13:50:09.399857   26656 client.go:104] Start docker client with request timeout=2m0s
W0218 13:50:09.402418   26656 docker_service.go:545] Hairpin mode set to "promiscuous-bridge" but kubenet is not enabled, falling back to "hairpin-veth"
I0218 13:50:09.402466   26656 docker_service.go:238] Hairpin mode set to "hairpin-veth"
I0218 13:50:09.408834   26656 docker_service.go:253] Docker cri networking managed by kubernetes.io/no-op
I0218 13:50:09.464778   26656 docker_service.go:258] Docker Info: &{ID:RS55:WJBO:XXTM:PPAJ:HLUV:UBH7:ZWFK:WERN:ZIHT:PAJ6:2RWI:7WOA Containers:424 ContainersRunning:333 ContainersPaused:0 ContainersStopped:91 Images:59 Driver:devicemapper DriverStatus:[[Pool Name docker-253:0-67351869-pool] [Pool Blocksize 65.54kB] [Base Device Size 10.74GB] [Backing Filesystem xfs] [Udev Sync Supported true] [Data file /dev/loop0] [Metadata file /dev/loop1] [Data loop file /var/lib/docker/devicemapper/devicemapper/data] [Metadata loop file /var/lib/docker/devicemapper/devicemapper/metadata] [Data Space Used 23.05GB] [Data Space Total 107.4GB] [Data Space Available 84.32GB] [Metadata Space Used 62.6MB] [Metadata Space Total 2.147GB] [Metadata Space Available 2.085GB] [Thin Pool Minimum Free Space 10.74GB] [Deferred Removal Enabled true] [Deferred Deletion Enabled true] [Deferred Deleted Device Count 0] [Library Version 1.02.158-RHEL7 (2019-05-13)]] SystemStatus:[] Plugins:{Volume:[local] Network:[bridge host macvlan null overlay] Authorization:[] Log:[awslogs fluentd gcplogs gelf journald json-file logentries splunk syslog]} MemoryLimit:true SwapLimit:true KernelMemory:true CPUCfsPeriod:true CPUCfsQuota:true CPUShares:true CPUSet:true IPv4Forwarding:true BridgeNfIptables:true BridgeNfIP6tables:true Debug:false NFd:1231 OomKillDisable:true NGoroutines:933 SystemTime:2020-02-18T13:50:09.448721588+01:00 LoggingDriver:json-file CgroupDriver:cgroupfs NEventsListener:1 KernelVersion:3.10.0-1062.9.1.el7.x86_64 OperatingSystem:CentOS Linux 7 (Core) OSType:linux Architecture:x86_64 IndexServerAddress:https://index.docker.io/v1/ RegistryConfig:0xc4204089a0 NCPU:16 MemTotal:67385786368 GenericResources:[] DockerRootDir:/var/lib/docker HTTPProxy: HTTPSProxy: NoProxy: Name:lgn-test-cp65.intranet.novaliance.com Labels:[] ExperimentalBuild:false ServerVersion:18.06.3-ce ClusterStore: ClusterAdvertise: Runtimes:map[runc:{Path:docker-runc Args:[]}] DefaultRuntime:runc Swarm:{NodeID: NodeAddr: LocalNodeState:inactive ControlAvailable:false Error: RemoteManagers:[] Nodes:0 Managers:0 Cluster:<nil>} LiveRestoreEnabled:false Isolation: InitBinary:docker-init ContainerdCommit:{ID:468a545b9edcd5932818eb9de8e72413e616e86e Expected:468a545b9edcd5932818eb9de8e72413e616e86e} RuncCommit:{ID:a592beb5bc4c4092b1b1bac971afed27687340c5 Expected:a592beb5bc4c4092b1b1bac971afed27687340c5} InitCommit:{ID:fec3683 Expected:fec3683} SecurityOptions:[name=seccomp,profile=default]}
I0218 13:50:09.464926   26656 docker_service.go:271] Setting cgroupDriver to cgroupfs
I0218 13:50:09.506807   26656 kuberuntime_manager.go:186] Container runtime docker initialized, version: 18.06.3-ce, apiVersion: 1.38.0
I0218 13:50:09.507488   26656 csi_plugin.go:138] kubernetes.io/csi: plugin initializing...
I0218 13:50:09.508605   26656 server.go:129] Starting to listen on 0.0.0.0:10250
E0218 13:50:09.508656   26656 kubelet.go:1252] Image garbage collection failed once. Stats initialization may not have completed yet: failed to get imageFs info: unable to find data for container /
I0218 13:50:09.508868   26656 server.go:986] Started kubelet
E0218 13:50:09.509041   26656 server.go:733] Starting health server failed: listen tcp 127.0.0.1:10248: bind: address already in use
I0218 13:50:09.509923   26656 server.go:302] Adding debug handlers to kubelet server.
F0218 13:50:09.510787   26656 server.go:141] listen tcp 0.0.0.0:10250: bind: address already in use
</code>```

maxpod.yaml

```<code>apiVersion: kubelet.config.k8s.io/v1beta1
kind: KubeletConfiguration
maxPods: 200
</code>```

答:
Flag --max-pods  should be set via the config file specified by the Kubelet's --config flag.

You have to create specific kubelet configuration.

```<code>apiVersion: kubelet.config.k8s.io/v1beta1
kind: KubeletConfiguration
maxPods: 200
</code>```

Save file and apply changes.

```<code>$ kubelet --config=your-kubelet-conf.yaml --kubeconfig=/root/.kube/config
</code>```

Remember that the configuration file must be a JSON or YAML representation of the parameters in this struct. Make sure the Kubelet has read permissions on the file.

You can also change a Node’s configSource using several different mechanisms. Example use of kubectl patch:

```<code>$ kubectl patch node ${NODE_NAME} -p "{\"spec\":{\"configSource\":{\"configMap\":{\"name\":\"${CONFIG_MAP_NAME}\",\"namespace\":\"kube-system\",\"kubeletConfigKey\":\"kubelet\"}}}}"
</code>```

Take a look here: configmap-kubelet, kubelet-configuration.

ContentLicense: CC BY-SA 4.0

Title: Increase max pod on Node

Body:
docker info : Server Version: 18.06.3-ce

[root@lgn-test-cp65 ~]# kubectl version
Client Version: version.Info{Major:"1", Minor:"11", GitVersion:"v1.11.9", GitCommit:"16236ce91790d4c75b79f6ce96841db1c843e7d2", GitTreeState:"clean", BuildDate:"2019-03-25T06:40:24Z", GoVersion:"go1.10.8", Compiler:"gc", Platform:"linux/amd64"}
Server Version: version.Info{Major:"1", Minor:"11", GitVersion:"v1.11.9", GitCommit:"16236ce91790d4c75b79f6ce96841db1c843e7d2", GitTreeState:"clean", BuildDate:"2019-03-25T06:30:48Z", GoVersion:"go1.10.8", Compiler:"gc", Platform:"linux/amd64"}

I'm trying to increase MaxPods in Node but it's not working.
I would like to increase MaxPods from 110 to 200

My command

kubelet --max-pods=200 --kubeconfig=/root/.kube/config

And result

[root@lgn-test-cp65 ~]# kubelet --max-pods=200 --kubeconfig=/root/.kube/config
Flag --max-pods has been deprecated, This parameter should be set via the config file specified by the Kubelet's --config flag. See https://kubernetes.io/docs/tasks/administer-cluster/kubelet-config-file/ for more information.
I0218 11:16:09.655793   22675 server.go:408] Version: v1.11.9
I0218 11:16:09.656132   22675 plugins.go:97] No cloud provider specified.
W0218 11:16:19.708398   22675 manager.go:251] Timeout trying to communicate with docker during initialization, will retry
I0218 11:16:20.723226   22675 server.go:648] --cgroups-per-qos enabled, but --cgroup-root was not specified.  defaulting to /
I0218 11:16:20.727579   22675 container_manager_linux.go:243] container manager verified user specified cgroup-root exists: []
I0218 11:16:20.727635   22675 container_manager_linux.go:248] Creating Container Manager object based on Node Config: {RuntimeCgroupsName: SystemCgroupsName: KubeletCgroupsName: ContainerRuntime:docker CgroupsPerQOS:true CgroupRoot:/ CgroupDriver:cgroupfs KubeletRootDir:/var/lib/kubelet ProtectKernelDefaults:false NodeAllocatableConfig:{KubeReservedCgroupName: SystemReservedCgroupName: EnforceNodeAllocatable:map[pods:{}] KubeReserved:map[] SystemReserved:map[] HardEvictionThresholds:[{Signal:memory.available Operator:LessThan Value:{Quantity:100Mi Percentage:0} GracePeriod:0s MinReclaim:<nil>} {Signal:nodefs.available Operator:LessThan Value:{Quantity:<nil> Percentage:0.1} GracePeriod:0s MinReclaim:<nil>} {Signal:nodefs.inodesFree Operator:LessThan Value:{Quantity:<nil> Percentage:0.05} GracePeriod:0s MinReclaim:<nil>} {Signal:imagefs.available Operator:LessThan Value:{Quantity:<nil> Percentage:0.15} GracePeriod:0s MinReclaim:<nil>}]} QOSReserved:map[] ExperimentalCPUManagerPolicy:none ExperimentalCPUManagerReconcilePeriod:10s ExperimentalPodPidsLimit:-1 EnforceCPULimits:true}
I0218 11:16:20.727862   22675 container_manager_linux.go:267] Creating device plugin manager: true
I0218 11:16:20.727938   22675 state_mem.go:36] [cpumanager] initializing new in-memory state store
I0218 11:16:20.728028   22675 state_mem.go:84] [cpumanager] updated default cpuset: ""
I0218 11:16:20.728043   22675 state_mem.go:92] [cpumanager] updated cpuset assignments: "map[]"
I0218 11:16:20.728221   22675 kubelet.go:299] Watching apiserver
I0218 11:16:20.749497   22675 client.go:75] Connecting to docker on unix:///var/run/docker.sock
I0218 11:16:20.749540   22675 client.go:104] Start docker client with request timeout=2m0s
W0218 11:16:20.752947   22675 docker_service.go:545] Hairpin mode set to "promiscuous-bridge" but kubenet is not enabled, falling back to "hairpin-veth"
I0218 11:16:20.752989   22675 docker_service.go:238] Hairpin mode set to "hairpin-veth"
I0218 11:16:20.780638   22675 docker_service.go:253] Docker cri networking managed by kubernetes.io/no-op
I0218 11:16:20.939375   22675 docker_service.go:258] Docker Info: &{ID:RS55:WJBO:XXTM:PPAJ:HLUV:UBH7:ZWFK:WERN:ZIHT:PAJ6:2RWI:7WOA Containers:429 ContainersRunning:302 ContainersPaused:0 ContainersStopped:127 Images:59 Driver:devicemapper DriverStatus:[[Pool Name docker-253:0-67351869-pool] [Pool Blocksize 65.54kB] [Base Device Size 10.74GB] [Backing Filesystem xfs] [Udev Sync Supported true] [Data file /dev/loop0] [Metadata file /dev/loop1] [Data loop file /var/lib/docker/devicemapper/devicemapper/data] [Metadata loop file /var/lib/docker/devicemapper/devicemapper/metadata] [Data Space Used 23.34GB] [Data Space Total 107.4GB] [Data Space Available 84.03GB] [Metadata Space Used 62.43MB] [Metadata Space Total 2.147GB] [Metadata Space Available 2.085GB] [Thin Pool Minimum Free Space 10.74GB] [Deferred Removal Enabled true] [Deferred Deletion Enabled true] [Deferred Deleted Device Count 0] [Library Version 1.02.158-RHEL7 (2019-05-13)]] SystemStatus:[] Plugins:{Volume:[local] Network:[bridge host macvlan null overlay] Authorization:[] Log:[awslogs fluentd gcplogs gelf journald json-file logentries splunk syslog]} MemoryLimit:true SwapLimit:true KernelMemory:true CPUCfsPeriod:true CPUCfsQuota:true CPUShares:true CPUSet:true IPv4Forwarding:true BridgeNfIptables:true BridgeNfIP6tables:true Debug:false NFd:1358 OomKillDisable:true NGoroutines:1195 SystemTime:2020-02-18T11:16:20.857237756+01:00 LoggingDriver:json-file CgroupDriver:cgroupfs NEventsListener:1 KernelVersion:3.10.0-1062.9.1.el7.x86_64 OperatingSystem:CentOS Linux 7 (Core) OSType:linux Architecture:x86_64 IndexServerAddress:https://index.docker.io/v1/ RegistryConfig:0xc42042c070 NCPU:16 MemTotal:67385786368 GenericResources:[] DockerRootDir:/var/lib/docker HTTPProxy: HTTPSProxy: NoProxy: Name:lgn-test-cp65.intranet.novaliance.com Labels:[] ExperimentalBuild:false ServerVersion:18.06.3-ce ClusterStore: ClusterAdvertise: Runtimes:map[runc:{Path:docker-runc Args:[]}] DefaultRuntime:runc Swarm:{NodeID: NodeAddr: LocalNodeState:inactive ControlAvailable:false Error: RemoteManagers:[] Nodes:0 Managers:0 Cluster:<nil>} LiveRestoreEnabled:false Isolation: InitBinary:docker-init ContainerdCommit:{ID:468a545b9edcd5932818eb9de8e72413e616e86e Expected:468a545b9edcd5932818eb9de8e72413e616e86e} RuncCommit:{ID:a592beb5bc4c4092b1b1bac971afed27687340c5 Expected:a592beb5bc4c4092b1b1bac971afed27687340c5} InitCommit:{ID:fec3683 Expected:fec3683} SecurityOptions:[name=seccomp,profile=default]}
I0218 11:16:20.939536   22675 docker_service.go:271] Setting cgroupDriver to cgroupfs
I0218 11:16:21.050308   22675 kuberuntime_manager.go:186] Container runtime docker initialized, version: 18.06.3-ce, apiVersion: 1.38.0
I0218 11:16:21.050912   22675 csi_plugin.go:138] kubernetes.io/csi: plugin initializing...
E0218 11:16:21.056297   22675 kubelet.go:1252] Image garbage collection failed once. Stats initialization may not have completed yet: failed to get imageFs info: unable to find data for container /
I0218 11:16:21.057696   22675 server.go:129] Starting to listen on 0.0.0.0:10250
I0218 11:16:21.058671   22675 server.go:302] Adding debug handlers to kubelet server.
F0218 11:16:21.059593   22675 server.go:141] listen tcp 0.0.0.0:10250: bind: address already in use

thanks for your help. I already made the config file and it's not working.

[root@lgn-test-cp65 ~]# kubelet --config=maxpod.yaml --kubeconfig=/root/.kube/config
I0218 13:50:09.199888   26656 server.go:408] Version: v1.11.9
I0218 13:50:09.200319   26656 plugins.go:97] No cloud provider specified.
I0218 13:50:09.374179   26656 server.go:648] --cgroups-per-qos enabled, but --cgroup-root was not specified.  defaulting to /
I0218 13:50:09.393932   26656 container_manager_linux.go:243] container manager verified user specified cgroup-root exists: []
I0218 13:50:09.393977   26656 container_manager_linux.go:248] Creating Container Manager object based on Node Config: {RuntimeCgroupsName: SystemCgroupsName: KubeletCgroupsName: ContainerRuntime:docker CgroupsPerQOS:true CgroupRoot:/ CgroupDriver:cgroupfs KubeletRootDir:/var/lib/kubelet ProtectKernelDefaults:false NodeAllocatableConfig:{KubeReservedCgroupName: SystemReservedCgroupName: EnforceNodeAllocatable:map[pods:{}] KubeReserved:map[] SystemReserved:map[] HardEvictionThresholds:[{Signal:nodefs.inodesFree Operator:LessThan Value:{Quantity:<nil> Percentage:0.05} GracePeriod:0s MinReclaim:<nil>} {Signal:imagefs.available Operator:LessThan Value:{Quantity:<nil> Percentage:0.15} GracePeriod:0s MinReclaim:<nil>} {Signal:memory.available Operator:LessThan Value:{Quantity:100Mi Percentage:0} GracePeriod:0s MinReclaim:<nil>} {Signal:nodefs.available Operator:LessThan Value:{Quantity:<nil> Percentage:0.1} GracePeriod:0s MinReclaim:<nil>}]} QOSReserved:map[] ExperimentalCPUManagerPolicy:none ExperimentalCPUManagerReconcilePeriod:10s ExperimentalPodPidsLimit:-1 EnforceCPULimits:true}
I0218 13:50:09.394140   26656 container_manager_linux.go:267] Creating device plugin manager: true
I0218 13:50:09.394223   26656 state_mem.go:36] [cpumanager] initializing new in-memory state store
I0218 13:50:09.394326   26656 state_mem.go:84] [cpumanager] updated default cpuset: ""
I0218 13:50:09.394343   26656 state_mem.go:92] [cpumanager] updated cpuset assignments: "map[]"
I0218 13:50:09.394518   26656 kubelet.go:299] Watching apiserver
I0218 13:50:09.399816   26656 client.go:75] Connecting to docker on unix:///var/run/docker.sock
I0218 13:50:09.399857   26656 client.go:104] Start docker client with request timeout=2m0s
W0218 13:50:09.402418   26656 docker_service.go:545] Hairpin mode set to "promiscuous-bridge" but kubenet is not enabled, falling back to "hairpin-veth"
I0218 13:50:09.402466   26656 docker_service.go:238] Hairpin mode set to "hairpin-veth"
I0218 13:50:09.408834   26656 docker_service.go:253] Docker cri networking managed by kubernetes.io/no-op
I0218 13:50:09.464778   26656 docker_service.go:258] Docker Info: &{ID:RS55:WJBO:XXTM:PPAJ:HLUV:UBH7:ZWFK:WERN:ZIHT:PAJ6:2RWI:7WOA Containers:424 ContainersRunning:333 ContainersPaused:0 ContainersStopped:91 Images:59 Driver:devicemapper DriverStatus:[[Pool Name docker-253:0-67351869-pool] [Pool Blocksize 65.54kB] [Base Device Size 10.74GB] [Backing Filesystem xfs] [Udev Sync Supported true] [Data file /dev/loop0] [Metadata file /dev/loop1] [Data loop file /var/lib/docker/devicemapper/devicemapper/data] [Metadata loop file /var/lib/docker/devicemapper/devicemapper/metadata] [Data Space Used 23.05GB] [Data Space Total 107.4GB] [Data Space Available 84.32GB] [Metadata Space Used 62.6MB] [Metadata Space Total 2.147GB] [Metadata Space Available 2.085GB] [Thin Pool Minimum Free Space 10.74GB] [Deferred Removal Enabled true] [Deferred Deletion Enabled true] [Deferred Deleted Device Count 0] [Library Version 1.02.158-RHEL7 (2019-05-13)]] SystemStatus:[] Plugins:{Volume:[local] Network:[bridge host macvlan null overlay] Authorization:[] Log:[awslogs fluentd gcplogs gelf journald json-file logentries splunk syslog]} MemoryLimit:true SwapLimit:true KernelMemory:true CPUCfsPeriod:true CPUCfsQuota:true CPUShares:true CPUSet:true IPv4Forwarding:true BridgeNfIptables:true BridgeNfIP6tables:true Debug:false NFd:1231 OomKillDisable:true NGoroutines:933 SystemTime:2020-02-18T13:50:09.448721588+01:00 LoggingDriver:json-file CgroupDriver:cgroupfs NEventsListener:1 KernelVersion:3.10.0-1062.9.1.el7.x86_64 OperatingSystem:CentOS Linux 7 (Core) OSType:linux Architecture:x86_64 IndexServerAddress:https://index.docker.io/v1/ RegistryConfig:0xc4204089a0 NCPU:16 MemTotal:67385786368 GenericResources:[] DockerRootDir:/var/lib/docker HTTPProxy: HTTPSProxy: NoProxy: Name:lgn-test-cp65.intranet.novaliance.com Labels:[] ExperimentalBuild:false ServerVersion:18.06.3-ce ClusterStore: ClusterAdvertise: Runtimes:map[runc:{Path:docker-runc Args:[]}] DefaultRuntime:runc Swarm:{NodeID: NodeAddr: LocalNodeState:inactive ControlAvailable:false Error: RemoteManagers:[] Nodes:0 Managers:0 Cluster:<nil>} LiveRestoreEnabled:false Isolation: InitBinary:docker-init ContainerdCommit:{ID:468a545b9edcd5932818eb9de8e72413e616e86e Expected:468a545b9edcd5932818eb9de8e72413e616e86e} RuncCommit:{ID:a592beb5bc4c4092b1b1bac971afed27687340c5 Expected:a592beb5bc4c4092b1b1bac971afed27687340c5} InitCommit:{ID:fec3683 Expected:fec3683} SecurityOptions:[name=seccomp,profile=default]}
I0218 13:50:09.464926   26656 docker_service.go:271] Setting cgroupDriver to cgroupfs
I0218 13:50:09.506807   26656 kuberuntime_manager.go:186] Container runtime docker initialized, version: 18.06.3-ce, apiVersion: 1.38.0
I0218 13:50:09.507488   26656 csi_plugin.go:138] kubernetes.io/csi: plugin initializing...
I0218 13:50:09.508605   26656 server.go:129] Starting to listen on 0.0.0.0:10250
E0218 13:50:09.508656   26656 kubelet.go:1252] Image garbage collection failed once. Stats initialization may not have completed yet: failed to get imageFs info: unable to find data for container /
I0218 13:50:09.508868   26656 server.go:986] Started kubelet
E0218 13:50:09.509041   26656 server.go:733] Starting health server failed: listen tcp 127.0.0.1:10248: bind: address already in use
I0218 13:50:09.509923   26656 server.go:302] Adding debug handlers to kubelet server.
F0218 13:50:09.510787   26656 server.go:141] listen tcp 0.0.0.0:10250: bind: address already in use

maxpod.yaml

apiVersion: kubelet.config.k8s.io/v1beta1
kind: KubeletConfiguration
maxPods: 200

Body:
Flag --max-pods  should be set via the config file specified by the Kubelet's --config flag.

You have to create specific kubelet configuration.

apiVersion: kubelet.config.k8s.io/v1beta1
kind: KubeletConfiguration
maxPods: 200

Save file and apply changes.

$ kubelet --config=your-kubelet-conf.yaml --kubeconfig=/root/.kube/config

Remember that the configuration file must be a JSON or YAML representation of the parameters in this struct. Make sure the Kubelet has read permissions on the file.

You can also change a Node’s configSource using several different mechanisms. Example use of kubectl patch:

$ kubectl patch node ${NODE_NAME} -p "{\"spec\":{\"configSource\":{\"configMap\":{\"name\":\"${CONFIG_MAP_NAME}\",\"namespace\":\"kube-system\",\"kubeletConfigKey\":\"kubelet\"}}}}"

Take a look here: configmap-kubelet, kubelet-configuration.


问:
Missing levels when weightig (raking) data using ANESRake
I have a survey data set and some quotes:

The population quotes are:

```<code>(1 = up to 29 years 0,00%)

2 = 30 to 39 years 18,10%

3 = 40 to 49 years 28,77%

4 = 50 to 59 years 33,11%

5 = 60 and more years 20,01%
</code>```

In the data set, I have to weight category 5 is missing. Here are the stats of the variable in the data set:

```<code>2 = 32,33%
3 = 36,56%
4 = 31,12%
</code>```

If I perform the raking I get the following error:

```<code>library(anesrake)

r = anesrake(list_weights,
             d,
             verbose = FALSE,
             caseid =  d$RESPID,
             maxit = 1500,
             cap = 5,
             choosemethod = "max",
             type = "nolim")

Error in rakeonvar.default(mat[, i], inputter[[i]], weightvec) : variables must be coded continuously from 1 to n with no missing values
</code>```

Any Idea how to deal with missing levels in the data?

Here is a dput of the quotes

```<code>list(Rec_Age = c(`2` = 0.181, `3` = 0.2877, `4` = 0.3311))
</code>```

and a small dput of the data

```<code>structure(list(RESPID = structure(c(459, 311, 223, 60, 613, 495,
300, 273, 78, 170, 217, 61, 175, 619, 270, 218, 453, 492, 23,
65, 33, 113, 532, 26, 119, 49, 208, 102, 200, 165, 435, 298,
593, 220, 111, 53, 494, 271, 305, 420, 323, 607, 105, 19, 426,
171, 330, 201, 332, 277), label = "RESPID - Respondent ID", format.spss = "F10.0", display_width = 0L),
    Rec_Age = structure(c(4, 2, 4, 3, 4, 4, 4, 3, 2, 2, 3, 2,
    3, 4, 4, 2, 4, 4, 2, 3, 2, 2, 2, 3, 3, 2, 2, 2, 2, 3, 2,
    3, 2, 3, 4, 3, 4, 3, 2, 3, 3, 3, 4, 4, 4, 2, 2, 3, 4, 3), label = "Rec_Age - Recode Age")), row.names = c(NA,
-50L), class = "data.frame")
</code>```

@Yuriy Saraykin

You are right there ist no error right now but all weights are at 1 after raking if I use your code. So something did must go wrong.

I don´t understand the reason for this. If I use the list with all levels like you I get this error (I tried it before).

```<code>Error in rakeonvar.default(mat[, i], inputter[[i]], weightvec) : you cannot rake any variable category to 0 or a negative number
</code>```

What is the difference between your list and mine (even if your code don´t provide the desired result)?

Your list:

```<code>your_list

[[1]]
        1         2         3         4         5
0.0000000 0.1810181 0.2877288 0.3311331 0.2001200
dput(your_list)

list(Rec_Age = c(`1` = 0, `2` = 0.181, `3` = 0.2877, `4` = 0.3311,
`5` = 0.2001))
</code>```

My list:

```<code>My_list

    my_list:
    $Rec_Age
         1      2      3      4      5
    0.0000 0.1810 0.2877 0.3311 0.2001

    dput(my_list)
     list(Rec_Age = c(`1` = 0, `2` = 0.181, `3` = 0.2877, `4` = 0.3311, `5` =
     0.2001))
</code>```

My list was generated like:

```<code>REC_age =  c(0, 0.181, 0.2877, 0.3311, 0.2001)

names(REC_age) = c(1, 2, 3, 4, 5)
</code>```

答:
Try it like this. It seems to me that you can include information about the population in the sample.
Here is a good article on the topic.
https://www.r-bloggers.com/survey-raking-an-illustration/</p>

```<code>library(anesrake)
library(weights)
library(tidiverse)

d <- d %>% mutate(Rec_Age = as.factor(Rec_Age))

population <- data.frame(Rec_Age = c("2", "3", "4"),
                         fraction = c(0.181, 0.2877, 0.3311))

list_weights <- with(population,
                     list(Rec_Age = wpct(Rec_Age, fraction)))

r <- anesrake(list_weights,
              d,
              caseid =  d$RESPID,
              maxit = 1500,
              cap = 5,
              choosemethod = "max",
              type = "nolim")
</code>```

Body:
I have a survey data set and some quotes:

The population quotes are:

(1 = up to 29 years 0,00%)

2 = 30 to 39 years 18,10%

3 = 40 to 49 years 28,77%

4 = 50 to 59 years 33,11%

5 = 60 and more years 20,01%

In the data set, I have to weight category 5 is missing. Here are the stats of the variable in the data set:

2 = 32,33%
3 = 36,56%
4 = 31,12%

If I perform the raking I get the following error:

library(anesrake)

r = anesrake(list_weights,
             d,
             verbose = FALSE,
             caseid =  d$RESPID,
             maxit = 1500,
             cap = 5,
             choosemethod = "max",
             type = "nolim")

Error in rakeonvar.default(mat[, i], inputter[[i]], weightvec) : variables must be coded continuously from 1 to n with no missing values

Any Idea how to deal with missing levels in the data?

Here is a dput of the quotes

list(Rec_Age = c(`2` = 0.181, `3` = 0.2877, `4` = 0.3311))

and a small dput of the data

structure(list(RESPID = structure(c(459, 311, 223, 60, 613, 495,
300, 273, 78, 170, 217, 61, 175, 619, 270, 218, 453, 492, 23,
65, 33, 113, 532, 26, 119, 49, 208, 102, 200, 165, 435, 298,
593, 220, 111, 53, 494, 271, 305, 420, 323, 607, 105, 19, 426,
171, 330, 201, 332, 277), label = "RESPID - Respondent ID", format.spss = "F10.0", display_width = 0L),
    Rec_Age = structure(c(4, 2, 4, 3, 4, 4, 4, 3, 2, 2, 3, 2,
    3, 4, 4, 2, 4, 4, 2, 3, 2, 2, 2, 3, 3, 2, 2, 2, 2, 3, 2,
    3, 2, 3, 4, 3, 4, 3, 2, 3, 3, 3, 4, 4, 4, 2, 2, 3, 4, 3), label = "Rec_Age - Recode Age")), row.names = c(NA,
-50L), class = "data.frame")

@Yuriy Saraykin

You are right there ist no error right now but all weights are at 1 after raking if I use your code. So something did must go wrong.

I don´t understand the reason for this. If I use the list with all levels like you I get this error (I tried it before).

Error in rakeonvar.default(mat[, i], inputter[[i]], weightvec) : you cannot rake any variable category to 0 or a negative number

What is the difference between your list and mine (even if your code don´t provide the desired result)?

Your list:

your_list

[[1]]
        1         2         3         4         5
0.0000000 0.1810181 0.2877288 0.3311331 0.2001200
dput(your_list)

list(Rec_Age = c(`1` = 0, `2` = 0.181, `3` = 0.2877, `4` = 0.3311,
`5` = 0.2001))

My list:

My_list

    my_list:
    $Rec_Age
         1      2      3      4      5
    0.0000 0.1810 0.2877 0.3311 0.2001

    dput(my_list)
     list(Rec_Age = c(`1` = 0, `2` = 0.181, `3` = 0.2877, `4` = 0.3311, `5` =
     0.2001))

My list was generated like:

REC_age =  c(0, 0.181, 0.2877, 0.3311, 0.2001)

names(REC_age) = c(1, 2, 3, 4, 5)

Body:
Try it like this. It seems to me that you can include information about the population in the sample.
Here is a good article on the topic.
https://www.r-bloggers.com/survey-raking-an-illustration/

library(anesrake)
library(weights)
library(tidiverse)

d <- d %>% mutate(Rec_Age = as.factor(Rec_Age))

population <- data.frame(Rec_Age = c("2", "3", "4"),
                         fraction = c(0.181, 0.2877, 0.3311))

list_weights <- with(population,
                     list(Rec_Age = wpct(Rec_Age, fraction)))

r <- anesrake(list_weights,
              d,
              caseid =  d$RESPID,
              maxit = 1500,
              cap = 5,
              choosemethod = "max",
              type = "nolim")


问:
Is there a way to control who the last modified person is on a sharepoint list item
For example: If Bob is a content owner and needs to open the item to view more detailed information for example, when Bob closes that item his name should not replace the name of the non-content owner who last modified that item.</p>

答: Filter the view and checkout metadata. You can see who modified last.</p>


问:
Is it valid to reuse the same React-Redux's useDispatch on multiple components?
I have multiple modals and the conditions for showing and hiding them are stored in a Redux store. To avoid typos I export the actions like this...

```<code>//reduxStuff.js

export const modalNameHide = () => {
  return { type: "MODALNAMEHIDE" };
};

export const modalNameShow = () => {
  return { type: "MODALNAMESHOW" };
};
</code>```

Then when I need the functionality for hiding a modal I do this...

```<code>//HideModalButton.js

import { modalNameHide } from "reduxStuff";
import { useDispatch } from "react-redux";

const HideModalNameButton = () => {
    const dispatch = useDispatch();

    return <button onClick = {() => { dispatch(modalNameHide()) }>Close Modal<button>
}
</code>```

As you can see for every component that needs to update the store, 2 imports must be done, one for useDispatch and one for the needed action (modalNameHide in this example).

So my question boils down to this: Can I import useDispatch in reduxStuff.js and export useDispatch and modalNameHide together?

Something like this...

```<code>//reduxStuff.js

import { useDispatch } from "react-redux";

export const modalNameHide = () => {
  let dispatch = useDispatch();
  dispatch({ type: "MODALNAMEHIDE" });
};

export const modalNameShow = () => {
  let dispatch = useDispatch();
  dispatch({ type: "MODALNAMESHOW" });
};
</code>```

Now when I need to close a modal I would just do one import like this...

```<code>//HideModalButton.js

import { modalNameHide } from "reduxStuff";

const HideModalNameButton = () => {
    return <button onClick = {() => { modalNameHide() }>Close Modal<button>
}
</code>```

答:
No, this is not valid.

In your first case, you're doing useDispatch() during render, and then you call dispatch(modalNameHide()) during onClick. This is valid and correct usage of useDispatch.

In your theoretical second case, you're doing modalNameHide() during onClick, and this means that useDispatch() will also be used during onClick instead of render (which is incorrect usage of useDispatch).

useDispatch is a react hook, and you're breaking the Rules of Hooks. Read more here: https://reactjs.org/docs/hooks-rules.html

Body:
I have multiple modals and the conditions for showing and hiding them are stored in a Redux store. To avoid typos I export the actions like this...

//reduxStuff.js

export const modalNameHide = () => {
  return { type: "MODALNAMEHIDE" };
};

export const modalNameShow = () => {
  return { type: "MODALNAMESHOW" };
};

Then when I need the functionality for hiding a modal I do this...

//HideModalButton.js

import { modalNameHide } from "reduxStuff";
import { useDispatch } from "react-redux";

const HideModalNameButton = () => {
    const dispatch = useDispatch();

    return <button onClick = {() => { dispatch(modalNameHide()) }>Close Modal<button>
}

As you can see for every component that needs to update the store, 2 imports must be done, one for useDispatch and one for the needed action (modalNameHide in this example).

So my question boils down to this: Can I import useDispatch in reduxStuff.js and export useDispatch and modalNameHide together?

Something like this...

//reduxStuff.js

import { useDispatch } from "react-redux";

export const modalNameHide = () => {
  let dispatch = useDispatch();
  dispatch({ type: "MODALNAMEHIDE" });
};

export const modalNameShow = () => {
  let dispatch = useDispatch();
  dispatch({ type: "MODALNAMESHOW" });
};

Now when I need to close a modal I would just do one import like this...

//HideModalButton.js

import { modalNameHide } from "reduxStuff";

const HideModalNameButton = () => {
    return <button onClick = {() => { modalNameHide() }>Close Modal<button>
}


问:
Do something if nth number
I need to create a celery task that runs some background stuff if the column in the DB value is a 'fifth number'. I'm not sure what to call it, but

```<code>if the number is 5 -> Do something
if the number is 10 -> Do something
if the number is 15 -> Do something
if the number is 20 -> Do something
if the number is 25 -> Do something
</code>```

and so on. The functions should only check if the current value is a 'fifth number' so the code only runs once. How would I go on about creating this kind of checker? I'd appreciate any kind of resource I can check out

答:
```<code>i=5 #Your number
if i%5==0:
    print('Hello') #Do Something
</code>```

Title: Do something if nth number

Body:
I need to create a celery task that runs some background stuff if the column in the DB value is a 'fifth number'. I'm not sure what to call it, but

if the number is 5 -> Do something
if the number is 10 -> Do something
if the number is 15 -> Do something
if the number is 20 -> Do something
if the number is 25 -> Do something

and so on. The functions should only check if the current value is a 'fifth number' so the code only runs once. How would I go on about creating this kind of checker? I'd appreciate any kind of resource I can check out


问:
Maria DB change datadir on windows server
I installed MariaDB on my windows server and saw it defaults the datadir where the databases are stored to C:\Program Files\MariaDB 10.2\data

I wanted it moved the the E: disk that's dedicated to database stuff.

I thought copying the datadir and then modifying the my.ini in the C:\Program Files\MariaDB 10.2\data datadir would solve it, but when I tried to restart the service it wouldn't start.
I also tried setting the folder permissions to network service but that didn't seem to help.

What do I have to do to move my datadir on windows?

答:
After some confusion with this error I can recommend that you:

Use slashes in Windows paths, for example C:/MariaDB/DB.

Experiment with adequate permissions. This seems to work:

```<code>cacls Path_to_MariaDB_DBData /E /T /P "Network Service":F
</code>```

ContentLicense: CC BY-SA 3.0

Body:
After some confusion with this error I can recommend that you:

Use slashes in Windows paths, for example C:/MariaDB/DB.

Experiment with adequate permissions. This seems to work:

cacls Path_to_MariaDB_DBData /E /T /P "Network Service":F


问:
How to user super() in Django views.py
I have this class in my views.py

```<code>class ThreadView(LoginRequiredMixin, FormMixin, DetailView):
    template_name = 'chat/thread.html'
    form_class = ComposeForm
    success_url = './'
    def form_valid(self, form):
        thread = self.get_object()
        user = self.request.user
        message = form.cleaned_data.get("message")
        print(user, thread, message)
        ChatMessage.objects.create(user=user, thread=thread, message=message)
        print()
        return super().form_valid(form)
</code>```

I am using python3 return super().form_valid(form) and the error says Python version 2.7 does not support this syntax. super() should have arguments in python 2,
any ideas?

Title: How to user super() in Django views.py

Body:
I have this class in my views.py

class ThreadView(LoginRequiredMixin, FormMixin, DetailView):
    template_name = 'chat/thread.html'
    form_class = ComposeForm
    success_url = './'
    def form_valid(self, form):
        thread = self.get_object()
        user = self.request.user
        message = form.cleaned_data.get("message")
        print(user, thread, message)
        ChatMessage.objects.create(user=user, thread=thread, message=message)
        print()
        return super().form_valid(form)

I am using python3 return super().form_valid(form) and the error says Python version 2.7 does not support this syntax. super() should have arguments in python 2,
any ideas?

Body: use super(ThreadView, self).form_valid(form)


问:
Error format doest not support 32-bit absolute addresses
I'm working on a project in ASM x86-64 on a mac with the last version of catalina. When I try to compile it, I got tihs error error: Macho-O 64-bit format doest not support 32-bit absolute adresses. I got this when I try to move an adress in the stack frame.

Example:

```<code>my_fnc:
    push rbp
    mov rbp, rsp
    sub rsp, 64
    mov qword [rbp - 8], __zpair
....
....
....

section .rodata

__zpair:
    db "pair", 0
</code>```

答:
There's only space for 32 bits in most immediate operands.  __zpair, being a 64 bit address, might not fit† which is why the assembler rejects this code.  Use

```<code>lea rax, [rel __zpair]  ; load the address of __zpair
mov [rbp - 8], rax      ; write address to stack
</code>```

to first load the address using a rip-relative addressing mode and then write it into the stack frame.

† Contrary to other platforms, macOS does not guarantee that your executable will be loaded into the first 2 GB of memory.  In fact, it will never do so unless specifically configured.

Body:
I'm working on a project in ASM x86-64 on a mac with the last version of catalina. When I try to compile it, I got tihs error error: Macho-O 64-bit format doest not support 32-bit absolute adresses. I got this when I try to move an adress in the stack frame.

Example:

my_fnc:
    push rbp
    mov rbp, rsp
    sub rsp, 64
    mov qword [rbp - 8], __zpair
....
....
....

section .rodata

__zpair:
    db "pair", 0

Body:
There's only space for 32 bits in most immediate operands.  __zpair, being a 64 bit address, might not fit† which is why the assembler rejects this code.  Use

lea rax, [rel __zpair]  ; load the address of __zpair
mov [rbp - 8], rax      ; write address to stack

to first load the address using a rip-relative addressing mode and then write it into the stack frame.

† Contrary to other platforms, macOS does not guarantee that your executable will be loaded into the first 2 GB of memory.  In fact, it will never do so unless specifically configured.


问:
Why can't you store an extremely large single value in a dynamically allocated block of memory?
Why can't I store a large integer in this allocated block of memory?

```<code>int *dyn = malloc(16);
*dyn = 9999999999;

printf("%lli\n", *dyn);

free(dyn);
</code>```

At compile-time, GCC warns me that an integer overflow will occur. And sure enough, when printed out, it has overflowed.

Why can't I use the entire block of memory to store a single value?

答:
Why can't I use the entire block of memory to store a single value?

Because the size of int is almost certainly not 16 bytes, and when you de-reference a int pointer in the *dyn = 9999999999; expression, that access is limited to the size of int, which is likely 2^31 - 1.

Please note that the integer constant 9999999999 has a type too, which is dynamically determined by the compiler depending on the number's size. In this case, very likely long long. So the actual bug here is your attempt to do int x = 9999999999; which isn't the slightest related to malloc or pointers. It's a simple overflow.

To use numbers larger than 2.14 billion, you must use a 64 bit type instead. Use int64_t/uint64_t from stdint.h.

You cannot allocate 16 bytes, memcpy som value in there and then access the data through pointers to some arbitrary integer type. This is because of the somewhat dysfunctional C type system. Simplified explanation: the chunk of data returned from malloc has no type internally, until you store something there. Then it gets the type you used when storing, and all subsequent access have to use that same type too, everything else invokes undefined behavior according to "the strict aliasing rule".

Body:
Why can't I store a large integer in this allocated block of memory?

int *dyn = malloc(16);
*dyn = 9999999999;

printf("%lli\n", *dyn);

free(dyn);

At compile-time, GCC warns me that an integer overflow will occur. And sure enough, when printed out, it has overflowed.

Why can't I use the entire block of memory to store a single value?


问:
Duplicate pods / Pods creating without deploy existing
I'm running into an issue managing my Kubernetes pods.

I had a deploy instance which I removed and created a new one. The pod tied to that deploy instance shut down as expected and a new one came up when I created a new deploy, as expected.

However, once I changed the deploy, a second pod began running. I tried to "kubectl delete pod pod-id" but it would just recreate itself again.

I went through the same process again and now I'm stuck with 3 pods, and no deploy. I removed the deploy completely, and I try to delete the pods but they keep recreating themselves. This is an issue because I am exhausting the resources available on my Kubernetes.

Does anyone know how to force remove these pods? I do not know how they are recreating themselves if there's no deploy to go by.

答: The root cause could be either an existing deployment, replicaset, daemonset, statefulset or a static pod. Check if any of these exist in the affected namespace using kubectl get <RESOURCE-TYPE>


问:
c++ move semantics when using pointers
How do I use the move assignment operator when working with raw pointers.

Is there any other way than doing something like:

```<code>void Function(T* dest)
{
    T* src = LoadT();
    (*dest) = std::move(*src);
    delete src;
}
</code>```

答: Unless you reference the objects in a temporary variable you are out of luck. Technically (not sure if illegal) you are allowed to provide your own specialization of move in which you can hide that behavior. But at one point or another, you have to dereference those pointers.

Title: c++ move semantics when using pointers

Body:
How do I use the move assignment operator when working with raw pointers.

Is there any other way than doing something like:

void Function(T* dest)
{
    T* src = LoadT();
    (*dest) = std::move(*src);
    delete src;
}


问:
Merging two dataframes with pd.NA in merge column yields 'TypeError: boolean value of NA is ambiguous'
With Pandas 1.0.1, I'm unable to merge if the

```<code>df = df.merge(df2, on=some_column)
</code>```

yields

```<code>File /home/torstein/code/fintechdb/Sheets/sheets/gild.py, line 42, in gild
    df = df.merge(df2, on=some_column)
File /home/torstein/anaconda3/lib/python3.7/site-packages/pandas/core/frame.py, line 7297, in merge
    validate=validate,
File /home/torstein/anaconda3/lib/python3.7/site-packages/pandas/core/reshape/merge.py, line 88, in merge
    return op.get_result()
File /home/torstein/anaconda3/lib/python3.7/site-packages/pandas/core/reshape/merge.py, line 643, in get_result
    join_index, left_indexer, right_indexer = self._get_join_info()
File /home/torstein/anaconda3/lib/python3.7/site-packages/pandas/core/reshape/merge.py, line 862, in _get_join_info
    (left_indexer, right_indexer) = self._get_join_indexers()
File /home/torstein/anaconda3/lib/python3.7/site-packages/pandas/core/reshape/merge.py, line 841, in _get_join_indexers
    self.left_join_keys, self.right_join_keys, sort=self.sort, how=self.how
File /home/torstein/anaconda3/lib/python3.7/site-packages/pandas/core/reshape/merge.py, line 1311, in _get_join_indexers
    zipped = zip(*mapped)
File /home/torstein/anaconda3/lib/python3.7/site-packages/pandas/core/reshape/merge.py, line 1309, in <genexpr>
    for n in range(len(left_keys))
File /home/torstein/anaconda3/lib/python3.7/site-packages/pandas/core/reshape/merge.py, line 1918, in _factorize_keys
    rlab = rizer.factorize(rk)
File pandas/_libs/hashtable.pyx, line 77, in pandas._libs.hashtable.Factorizer.factorize
File pandas/_libs/hashtable_class_helper.pxi, line 1817, in pandas._libs.hashtable.PyObjectHashTable.get_labels
File pandas/_libs/hashtable_class_helper.pxi, line 1732, in pandas._libs.hashtable.PyObjectHashTable._unique
File pandas/_libs/missing.pyx, line 360, in pandas._libs.missing.NAType.__bool__

TypeError: boolean value of NA is ambiguous
</code>```

while this works:

```<code>df[some_column].fillna(np.nan, inplace=True)
df2[some_column].fillna(np.nan, inplace=True)
df = df.merge(df2, on=some_column)
# Works
</code>```

If instead, I do

```<code>df[some_column].fillna(pd.NA, inplace=True)
</code>```

then the error returns.

答:
This has to do with pd.NA being implemented in pandas 1.0.0 and how the pandas team decided it should work in a boolean context. Also, you take into account it is an experimental feature, hence it shouldn't be used for anything but experimenting:

Warning Experimental: the behaviour of pd.NA can still change without warning.

In another link of pandas documentation, where it covers working with missing values, is where I believe the reason and the answer you are looking for can be found:

NA in a boolean context:
  Since the actual value of an NA is unknown, it is ambiguous to convert NA to a boolean value. The following raises an error: TypeError: boolean value of NA is ambiguous

Furthermore, it provides a valuable piece of advise:

"This also means that pd.NA cannot be used in a context where it is evaluated to a boolean, such as if condition: ... where condition can potentially be pd.NA. In such cases, isna() can be used to check for pd.NA or condition being pd.NA can be avoided, for example by filling missing values beforehand."

Body:
With Pandas 1.0.1, I'm unable to merge if the

df = df.merge(df2, on=some_column)

yields

File /home/torstein/code/fintechdb/Sheets/sheets/gild.py, line 42, in gild
    df = df.merge(df2, on=some_column)
File /home/torstein/anaconda3/lib/python3.7/site-packages/pandas/core/frame.py, line 7297, in merge
    validate=validate,
File /home/torstein/anaconda3/lib/python3.7/site-packages/pandas/core/reshape/merge.py, line 88, in merge
    return op.get_result()
File /home/torstein/anaconda3/lib/python3.7/site-packages/pandas/core/reshape/merge.py, line 643, in get_result
    join_index, left_indexer, right_indexer = self._get_join_info()
File /home/torstein/anaconda3/lib/python3.7/site-packages/pandas/core/reshape/merge.py, line 862, in _get_join_info
    (left_indexer, right_indexer) = self._get_join_indexers()
File /home/torstein/anaconda3/lib/python3.7/site-packages/pandas/core/reshape/merge.py, line 841, in _get_join_indexers
    self.left_join_keys, self.right_join_keys, sort=self.sort, how=self.how
File /home/torstein/anaconda3/lib/python3.7/site-packages/pandas/core/reshape/merge.py, line 1311, in _get_join_indexers
    zipped = zip(*mapped)
File /home/torstein/anaconda3/lib/python3.7/site-packages/pandas/core/reshape/merge.py, line 1309, in <genexpr>
    for n in range(len(left_keys))
File /home/torstein/anaconda3/lib/python3.7/site-packages/pandas/core/reshape/merge.py, line 1918, in _factorize_keys
    rlab = rizer.factorize(rk)
File pandas/_libs/hashtable.pyx, line 77, in pandas._libs.hashtable.Factorizer.factorize
File pandas/_libs/hashtable_class_helper.pxi, line 1817, in pandas._libs.hashtable.PyObjectHashTable.get_labels
File pandas/_libs/hashtable_class_helper.pxi, line 1732, in pandas._libs.hashtable.PyObjectHashTable._unique
File pandas/_libs/missing.pyx, line 360, in pandas._libs.missing.NAType.__bool__

TypeError: boolean value of NA is ambiguous

while this works:

df[some_column].fillna(np.nan, inplace=True)
df2[some_column].fillna(np.nan, inplace=True)
df = df.merge(df2, on=some_column)
# Works

If instead, I do

df[some_column].fillna(pd.NA, inplace=True)

then the error returns.


问:
How to send props in class component to functional component?
I am beginner to reactjs. need to know how to send the props values in one page to another page. Props are on the first page I can get the class component value how to get the values in another page. Thanks in advance

wallcolor.jsx

```<code>import React, { Component } from "react";
import { SketchPicker } from 'react-color';
import WallFactory from "../../wall-factory-3d";
export default class WallColor extends Component {

  constructor(props) {
    super(props);
    this.state = {
        background: '#d3d3d3',
    };
  }

 handleChangeComplete(e){
    this.setState({ background: e.hex },()=>{
        return <WallFactory background={this.state.background}/>
    });
  };

  render() {
    return (
  <SketchPicker color={ this.state.background } onChangeComplete={(e)=>this.handleChangeComplete(e)}  />
  );
  }
}
</code>```

Another page is wall-factory-3d.js

```<code>import  { handleChangeComplete } from "../../components/toolbar/wallcolor";
import * as SharedStyle from '../../shared-style';

 function get_color(props){
   console.log(props.background);
}
</code>```

I tried this but not get output.

答:
opinion, but this is i would've done it... :)

```<code>this.state = {
 background: 'color',
 pickedWall: false,
}

const handleChangeComplete = (e) => {
 this.setState(prevState => ({
  ...prevState,
  pickedWall: true,
  background: e.target.value,
 }))
}

render() {
 const { x, y } = this.props
 const { background, pickedWall } = this.state
 const { handleChangeComplete } = this

 return <SketchPicker {...{ x, y, background, handleChangeComplete, pickedWall }} />
}
</code>```

and in your component...

```<code>const SketchPicker = ({
 x,
 y,
 background,
 pickedWall,
 handleChangeComplete,
}) => {
 return (
  <div>
   <SomeDiv onClick={(e) => handleChangeComplete(e)}>
    ...your code
   </SomeDiv>
   <Fragment>
    {pickedWall && <WallPicker {...{ x, y, background }} />}
   </Fragment>
  </div>
 )
}
</code>```

Body:
I am beginner to reactjs. need to know how to send the props values in one page to another page. Props are on the first page I can get the class component value how to get the values in another page. Thanks in advance

wallcolor.jsx

import React, { Component } from "react";
import { SketchPicker } from 'react-color';
import WallFactory from "../../wall-factory-3d";
export default class WallColor extends Component {

  constructor(props) {
    super(props);
    this.state = {
        background: '#d3d3d3',
    };
  }

 handleChangeComplete(e){
    this.setState({ background: e.hex },()=>{
        return <WallFactory background={this.state.background}/>
    });
  };

  render() {
    return (
  <SketchPicker color={ this.state.background } onChangeComplete={(e)=>this.handleChangeComplete(e)}  />
  );
  }
}

Another page is wall-factory-3d.js

import  { handleChangeComplete } from "../../components/toolbar/wallcolor";
import * as SharedStyle from '../../shared-style';

 function get_color(props){
   console.log(props.background);
}

I tried this but not get output.

Body:
opinion, but this is i would've done it... :)

this.state = {
 background: 'color',
 pickedWall: false,
}

const handleChangeComplete = (e) => {
 this.setState(prevState => ({
  ...prevState,
  pickedWall: true,
  background: e.target.value,
 }))
}

render() {
 const { x, y } = this.props
 const { background, pickedWall } = this.state
 const { handleChangeComplete } = this

 return <SketchPicker {...{ x, y, background, handleChangeComplete, pickedWall }} />
}

and in your component...

const SketchPicker = ({
 x,
 y,
 background,
 pickedWall,
 handleChangeComplete,
}) => {
 return (
  <div>
   <SomeDiv onClick={(e) => handleChangeComplete(e)}>
    ...your code
   </SomeDiv>
   <Fragment>
    {pickedWall && <WallPicker {...{ x, y, background }} />}
   </Fragment>
  </div>
 )
}


问:
Create pdf of tableview all data
I have create pdf of tableview all cells. but i have create the pdf it does not show all data of tableview & also when pdf page height set according to cells data. I dont know how to resolve this issue. I am using this code for create pdf.please help me.</p>

```<code>  let _: NSData!
        do {
            let priorBounds = table_view.bounds
            let fittedSize = table_view.sizeThatFits(CGSizeMake(priorBounds.size.width, .infinity))
            table_view.bounds = CGRectMake(0, 0, fittedSize.width, fittedSize.height)
            let pdfPageBounds = CGRectMake(0, 0, 612, 800)
            let pdfData = NSMutableData()
            UIGraphicsBeginPDFContextToData(pdfData, pdfPageBounds, nil)
            do {
                var pageOriginY = 0
                while pageOriginY < Int(fittedSize.height)  {
                    UIGraphicsBeginPDFPageWithInfo(pdfPageBounds, nil)
                    CGContextSaveGState(UIGraphicsGetCurrentContext()!)
                    do {
                        CGContextTranslateCTM(UIGraphicsGetCurrentContext()!, 0, -CGFloat(pageOriginY))
                        table_view.layer.renderInContext(UIGraphicsGetCurrentContext()!)
                    }
                    CGContextRestoreGState(UIGraphicsGetCurrentContext()!)
                    pageOriginY += Int(pdfPageBounds.size.height)
                }
            }
            UIGraphicsEndPDFContext()
            table_view.bounds = priorBounds
            if let documentDirectories = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first {
                let documentsFileName = documentDirectories + "/" + (filename as String)
                debugPrint(documentsFileName)
                pdfData.writeToFile(documentsFileName, atomically: true)
            }
        }
</code>```

答:
Create PDF of tableview using this way</p>
```<code>       @IBAction func onClickBtnGeneratePDF(_ sender: Any) {
        if enterPDFNAME.text?.isEmpty() == true{
         Utility.showToast(message: "Please Enter PDF name")
        }else{
            self.viewOverlaySavePDF.isHidden = true
            Utility.showLoading()
            let pdfFilePath = tableview.exportAsPdfFromTable(pdfName: enterPDFNAME.text!)
            if pdfFilePath != nil {

                self.enterPDFNAME.text = ""
                Utility.showToast(message: "Your PDF file saved")
                Utility.hideLoading()
            }
            print(pdfFilePath)
        }
    }

}

</code>```
```<code>extension UITableView {

    // Export pdf from UITableView and save pdf in drectory and return pdf file path
    func exportAsPdfFromTable(pdfName:String) -> String {

        /*  let html = "<b>Hello <i>World!</i></b> <p>Generate PDF file from HTML in Swift</p>"
         let fmt = UIMarkupTextPrintFormatter(markupText: html)

         // 2. Assign print formatter to UIPrintPageRenderer

         let render = UIPrintPageRenderer()
         render.addPrintFormatter(fmt, startingAtPageAt: 0)

         // 3. Assign paperRect and printableRect

         let page = CGRect(x: 0, y: 0, width: 595.2, height: 841.8) // A4, 72 dpi
         let printable = page.insetBy(dx: 0, dy: 0)

         render.setValue(NSValue(cgRect: page), forKey: "paperRect")
         render.setValue(NSValue(cgRect: printable), forKey: "printableRect")

         // 4. Create PDF context and draw

         let pdfData = NSMutableData()
         UIGraphicsBeginPDFContextToData(pdfData, .zero, nil)

         for i in 1...render.numberOfPages {
         UIGraphicsBeginPDFPage();
         let bounds = UIGraphicsGetPDFContextBounds()
         render.drawPage(at: i - 1, in: bounds)
         }

         UIGraphicsEndPDFContext();
         */
        let originalBounds = self.bounds
        self.bounds = CGRect(x:originalBounds.origin.x, y: originalBounds.origin.y, width: self.contentSize.width, height: self.contentSize.height)
        let pdfPageFrame = CGRect(x: 0, y: 0, width: self.bounds.size.width, height: self.contentSize.height)

        let pdfData = NSMutableData()
        UIGraphicsBeginPDFContextToData(pdfData, pdfPageFrame, nil)
        UIGraphicsBeginPDFPageWithInfo(pdfPageFrame, nil)
        guard let pdfContext = UIGraphicsGetCurrentContext() else { return "" }
        self.layer.render(in: pdfContext)
        UIGraphicsEndPDFContext()
        self.bounds = originalBounds
        // Save pdf data
        return self.saveTablePdf(data: pdfData,name:pdfName)

    }

    // Save pdf file in document directory
    func saveTablePdf(data: NSMutableData,name:String) -> String {

        let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
        let docDirectoryPath = paths[0]
        let pdfPath = docDirectoryPath.appendingPathComponent("\(name).pdf")
        if data.write(to: pdfPath, atomically: true) {
            return pdfPath.path
        } else {
            return ""
        }
    }
}
</code>```

Title: Create pdf of tableview all data

Body:
I have create pdf of tableview all cells. but i have create the pdf it does not show all data of tableview & also when pdf page height set according to cells data. I dont know how to resolve this issue. I am using this code for create pdf.please help me.

  let _: NSData!
        do {
            let priorBounds = table_view.bounds
            let fittedSize = table_view.sizeThatFits(CGSizeMake(priorBounds.size.width, .infinity))
            table_view.bounds = CGRectMake(0, 0, fittedSize.width, fittedSize.height)
            let pdfPageBounds = CGRectMake(0, 0, 612, 800)
            let pdfData = NSMutableData()
            UIGraphicsBeginPDFContextToData(pdfData, pdfPageBounds, nil)
            do {
                var pageOriginY = 0
                while pageOriginY < Int(fittedSize.height)  {
                    UIGraphicsBeginPDFPageWithInfo(pdfPageBounds, nil)
                    CGContextSaveGState(UIGraphicsGetCurrentContext()!)
                    do {
                        CGContextTranslateCTM(UIGraphicsGetCurrentContext()!, 0, -CGFloat(pageOriginY))
                        table_view.layer.renderInContext(UIGraphicsGetCurrentContext()!)
                    }
                    CGContextRestoreGState(UIGraphicsGetCurrentContext()!)
                    pageOriginY += Int(pdfPageBounds.size.height)
                }
            }
            UIGraphicsEndPDFContext()
            table_view.bounds = priorBounds
            if let documentDirectories = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first {
                let documentsFileName = documentDirectories + "/" + (filename as String)
                debugPrint(documentsFileName)
                pdfData.writeToFile(documentsFileName, atomically: true)
            }
        }

Body:
Create PDF of tableview using this way

       @IBAction func onClickBtnGeneratePDF(_ sender: Any) {
        if enterPDFNAME.text?.isEmpty() == true{
         Utility.showToast(message: "Please Enter PDF name")
        }else{
            self.viewOverlaySavePDF.isHidden = true
            Utility.showLoading()
            let pdfFilePath = tableview.exportAsPdfFromTable(pdfName: enterPDFNAME.text!)
            if pdfFilePath != nil {

                self.enterPDFNAME.text = ""
                Utility.showToast(message: "Your PDF file saved")
                Utility.hideLoading()
            }
            print(pdfFilePath)
        }
    }

}

extension UITableView {

    // Export pdf from UITableView and save pdf in drectory and return pdf file path
    func exportAsPdfFromTable(pdfName:String) -> String {

        /*  let html = "<b>Hello <i>World!</i></b> <p>Generate PDF file from HTML in Swift</p>"
         let fmt = UIMarkupTextPrintFormatter(markupText: html)

         // 2. Assign print formatter to UIPrintPageRenderer

         let render = UIPrintPageRenderer()
         render.addPrintFormatter(fmt, startingAtPageAt: 0)

         // 3. Assign paperRect and printableRect

         let page = CGRect(x: 0, y: 0, width: 595.2, height: 841.8) // A4, 72 dpi
         let printable = page.insetBy(dx: 0, dy: 0)

         render.setValue(NSValue(cgRect: page), forKey: "paperRect")
         render.setValue(NSValue(cgRect: printable), forKey: "printableRect")

         // 4. Create PDF context and draw

         let pdfData = NSMutableData()
         UIGraphicsBeginPDFContextToData(pdfData, .zero, nil)

         for i in 1...render.numberOfPages {
         UIGraphicsBeginPDFPage();
         let bounds = UIGraphicsGetPDFContextBounds()
         render.drawPage(at: i - 1, in: bounds)
         }

         UIGraphicsEndPDFContext();
         */
        let originalBounds = self.bounds
        self.bounds = CGRect(x:originalBounds.origin.x, y: originalBounds.origin.y, width: self.contentSize.width, height: self.contentSize.height)
        let pdfPageFrame = CGRect(x: 0, y: 0, width: self.bounds.size.width, height: self.contentSize.height)

        let pdfData = NSMutableData()
        UIGraphicsBeginPDFContextToData(pdfData, pdfPageFrame, nil)
        UIGraphicsBeginPDFPageWithInfo(pdfPageFrame, nil)
        guard let pdfContext = UIGraphicsGetCurrentContext() else { return "" }
        self.layer.render(in: pdfContext)
        UIGraphicsEndPDFContext()
        self.bounds = originalBounds
        // Save pdf data
        return self.saveTablePdf(data: pdfData,name:pdfName)

    }

    // Save pdf file in document directory
    func saveTablePdf(data: NSMutableData,name:String) -> String {

        let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
        let docDirectoryPath = paths[0]
        let pdfPath = docDirectoryPath.appendingPathComponent("\(name).pdf")
        if data.write(to: pdfPath, atomically: true) {
            return pdfPath.path
        } else {
            return ""
        }
    }
}


问:
Download a zip file in reactjs without any plugins
I am getting a response from a rest api whose Content-Type is text/html and Content-Encoding is gzip.

I tried to download it using blob

```<code>const blob = new Blob([res], { type: 'application/gzip' });
const downloadUrl = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = downloadUrl;
document.body.appendChild(a);
a.click();
</code>```

But the downloaded gz file was not able to open (seems to be corrupted).
can some one help me with downloading zip file in reactjs.

Edit: require a solution without using any external plugins

答:
you can use jszip npm module.

For example:

```<code>var zip = new JSZip();

zip.file("Hello.txt", "Hello World\n");
var img = zip.folder("images"); //images is the folder which will be zip

img.file("smile.gif", imgData, {base64: true});

zip.generateAsync({type:"blob"}).then(function(content) {

    saveAs(content, "example.zip");
});
</code>```

To use it without jszip, you can try the following code:

```<code>function str2bytes (str) {
    var bytes = new Uint8Array(str.length);
    for (var i=0; i<str.length; i++) {
        bytes[i] = str.charCodeAt(i);
    }
    return bytes;
}
</code>```

and its usage:

```<code>var blob = new Blob([str2bytes(myData)], {type: "application/zip"});
saveAs(blob, "data.zip");
</code>```

But jszip is a better alternative approach.

Body:
I am getting a response from a rest api whose Content-Type is text/html and Content-Encoding is gzip.

I tried to download it using blob

const blob = new Blob([res], { type: 'application/gzip' });
const downloadUrl = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = downloadUrl;
document.body.appendChild(a);
a.click();

But the downloaded gz file was not able to open (seems to be corrupted).
can some one help me with downloading zip file in reactjs.

Edit: require a solution without using any external plugins

Body:
you can use jszip npm module.

For example:

var zip = new JSZip();

zip.file("Hello.txt", "Hello World\n");
var img = zip.folder("images"); //images is the folder which will be zip

img.file("smile.gif", imgData, {base64: true});

zip.generateAsync({type:"blob"}).then(function(content) {

    saveAs(content, "example.zip");
});

To use it without jszip, you can try the following code:

function str2bytes (str) {
    var bytes = new Uint8Array(str.length);
    for (var i=0; i<str.length; i++) {
        bytes[i] = str.charCodeAt(i);
    }
    return bytes;
}

and its usage:

var blob = new Blob([str2bytes(myData)], {type: "application/zip"});
saveAs(blob, "data.zip");

But jszip is a better alternative approach.


问:
Change the label notation styles in cut functions?
I'm using the set of ggplot2 functions for creating some binned data in R. The notation style is "(a,b]". I know that's possible to use pre-specified labels. But I like the idea of using the returned numeric labels provided in the default. However, I'd like to change the notation style to something like "a - b". Is this possible?

Body:
You can rename the levels from cut automatically using regex

x = runif(100, 0,100)
y = cut(x, breaks = (0:10)*10)
levels(y)
# [1] "(0,10]"   "(10,20]"  "(20,30]"  "(30,40]"  "(40,50]"  "(50,60]"  "(60,70]"  "(70,80]"
# [9] "(80,90]"  "(90,100]"
levels(y) = sub(".(.+),(.+).", "\\1-\\2"  , levels(y))
# [1] "0-10"   "10-20"  "20-30"  "30-40"  "40-50"  "50-60"  "60-70"  "70-80"  "80-90"  "90-100"


问:
What does "CONST func(arg);" mean in C language?
This is a c program demonstrating some basic usage of the libxml2 library.  Below is quoted from the main function:

```<code>LIBXML_TEST_VERSION example1Func(argv[1]);
</code>```

What does this statement stand for?

I can only tell that LIBXML_TEST_VERSION is obviously a constant, and after that is a function call, that function returns nothing (void). But I've no idea what it means the statement in whole.

答:
LIBXML_TEST_VERSION is not a constant - it's a macro - see the documentation here:

```<code>Macro: LIBXML_TEST_VERSION

#define LIBXML_TEST_VERSION
Macro to check that the libxml version in use is compatible with the version the software has been compiled against
</code>```

It's also nothing to do with the call to example1func() - the code should look like this (comments are mine):

```<code>LIBXML_TEST_VERSION    // test libxml version

example1func();        // call example1func
</code>```

Body:
This is a c program demonstrating some basic usage of the libxml2 library.  Below is quoted from the main function:

LIBXML_TEST_VERSION example1Func(argv[1]);

What does this statement stand for?

I can only tell that LIBXML_TEST_VERSION is obviously a constant, and after that is a function call, that function returns nothing (void). But I've no idea what it means the statement in whole.

Body:
LIBXML_TEST_VERSION is not a constant - it's a macro - see the documentation here:

Macro: LIBXML_TEST_VERSION

#define LIBXML_TEST_VERSION
Macro to check that the libxml version in use is compatible with the version the software has been compiled against

It's also nothing to do with the call to example1func() - the code should look like this (comments are mine):

LIBXML_TEST_VERSION    // test libxml version

example1func();        // call example1func


问:
React Native - Multiple countdown timers in one view with out re-rendering
I am building an app that has a screen in a stack navigator that renders multiple touchableOpacity's, all with an independent and unique countdown timer in seconds.

Each TouchableOpacity displays the remaining seconds in the count by subtracting the difference of the unique time and current time.
The current time is stored as a state variable and when the component mounts, the function below is called.

```<code>    initTime() {
        setInterval( () => {
            this.setState({
                currentTime : new Date()
            })
          },1000)
    }
</code>```

My issue is mainly performance, the view needs to re-render every second which causes older devices to really struggle with the constant rendering.

Is there any way I can achieve this without needing to re-render every second?

答: Simply create a count down component separately and import it anywhere. this component only updates himself and has not any issue on the parent view. I checked this method for about 100 components in one view and has not any problem.</p>

Body:
I am building an app that has a screen in a stack navigator that renders multiple touchableOpacity's, all with an independent and unique countdown timer in seconds.

Each TouchableOpacity displays the remaining seconds in the count by subtracting the difference of the unique time and current time.
The current time is stored as a state variable and when the component mounts, the function below is called.

    initTime() {
        setInterval( () => {
            this.setState({
                currentTime : new Date()
            })
          },1000)
    }

My issue is mainly performance, the view needs to re-render every second which causes older devices to really struggle with the constant rendering.

Is there any way I can achieve this without needing to re-render every second?


问:
Elif and range functions for progressive taxation calculation in percentage
I am creating a program where user puts yearly income as an input and the income taxation rate would scale according to percentage thresholds (see picture at the end of this post for income range vs. percentage thresholds). For example from 100,000 euro income 50% would be paid from income exceeding 60001 (as according in the table below). 40% betweeen 45000-60000, 20% between 15000-30000 and 10% between 0-10000. Equation should go something like 0.5* 40 000 + 0.4 * 150 00 + 0.3 * 15 000 + 0.2 * 15 000 + 0.1 * 10000 = 35 000.

Outputs should be something like:
Give your yearly income: 100000 You pay taxes 35000.0 euro. Your taxation percent is: 35.0 %.
Give your yearly income: 54000 You pay taxes 12600.0 euroa. Your taxation percent is: 23.333333333333332 %.

This is what I've tried:

```<code>yearly = int(input("Tell your yearly income:"))
one = 0.1
two = 0.2
three = 0.3
four = 0.4
five = 0.5
if yearly in range(1,15000):
    print("You pay taxes in total:",yearly*one)
if yearly in range(15001,30000):
    print("You pay taxes in total:",yearly*two)
if yearly in range(30001,45000):
    print("You pay taxes in total:",yearly*three)
if yearly in range(45001,60000):
    print("You pay taxes in total:",yearly*four)
if yearly > 60000:
    print("You pay taxes in total:",yearly*five)
</code>```

The taxation percent doesn't scale like I'd like it to. I assumption is that this should get done by elif and range functions. Maybe min and max values of percentages would help, but I don't know how to turn outputs into percentages. Please note that I might have some comprehension problems here, math is not my strongest gamem but I did my absolute best to describe the problem...

Here is a table of income count vs. taxation percentage used.
Income vs. taxation percentage

答:
Optimized way :

Here is a more-optimized way to do it (see at bottom for a non-optimized way with enumeration). I store the percents and thresholds in lists, and taxes is incremented during a loop :

```<code>yearly = int(input("Tell your yearly income:"))

percents = [0.1, 0.2, 0.3, 0.4, 0.5]
thresholds = [0, 15000, 30000, 45000, 60000]

taxes = 0
for i in range(len(percents)):
    if i == len(thresholds) - 1 or yearly < thresholds[i+1]:
        taxes += (yearly - thresholds[i]) * percents[i]
        break
    else:
        taxes += (thresholds[i+1] - thresholds[i]) * percents[i]

print("You pay {} taxes".format(taxes))
print("Your taxation percent is: {}%".format(taxes/yearly*100))
</code>```

Examples of outputs :

```<code># Test 1
Tell your yearly income:100000
You pay 35000.0 taxes
Your taxation percent is: 35.0%

# Test 2
Tell your yearly income:54000
You pay 12600.0 taxes
Your taxation percent is: 23.333333333333332%
</code>```

Non-optimized way :

Here the key is to have a variable temp (initialized with temp = yearly that decreases when you apply the taxes :

```<code>yearly = int(input("Tell your yearly income:"))

one = 0.1
two = 0.2
three = 0.3
four = 0.4
five = 0.5

diff = 15000

temp = yearly
taxes = 0
if yearly in range(1,15000):
    taxes += temp * one
else:
    taxes += diff * one
    temp -= diff
if yearly in range(15001,30000):
    taxes += temp * two
else:
    taxes += diff * two
    temp -= diff
if yearly in range(30001,45000):
    taxes += temp * three
else:
    taxes += diff * three
    temp -= diff
if yearly in range(45001,60000):
    taxes += temp * four
else:
    taxes += diff * four
    temp -= diff
if yearly > 60000:
    taxes += temp * five

print("You pay {} taxes".format(taxes))
print("Your taxation percent is: {}%".format(taxes/yearly*100))
</code>```

Body:
I am creating a program where user puts yearly income as an input and the income taxation rate would scale according to percentage thresholds (see picture at the end of this post for income range vs. percentage thresholds). For example from 100,000 euro income 50% would be paid from income exceeding 60001 (as according in the table below). 40% betweeen 45000-60000, 20% between 15000-30000 and 10% between 0-10000. Equation should go something like 0.5* 40 000 + 0.4 * 150 00 + 0.3 * 15 000 + 0.2 * 15 000 + 0.1 * 10000 = 35 000.

Outputs should be something like:
Give your yearly income: 100000 You pay taxes 35000.0 euro. Your taxation percent is: 35.0 %.
Give your yearly income: 54000 You pay taxes 12600.0 euroa. Your taxation percent is: 23.333333333333332 %.

This is what I've tried:

yearly = int(input("Tell your yearly income:"))
one = 0.1
two = 0.2
three = 0.3
four = 0.4
five = 0.5
if yearly in range(1,15000):
    print("You pay taxes in total:",yearly*one)
if yearly in range(15001,30000):
    print("You pay taxes in total:",yearly*two)
if yearly in range(30001,45000):
    print("You pay taxes in total:",yearly*three)
if yearly in range(45001,60000):
    print("You pay taxes in total:",yearly*four)
if yearly > 60000:
    print("You pay taxes in total:",yearly*five)

The taxation percent doesn't scale like I'd like it to. I assumption is that this should get done by elif and range functions. Maybe min and max values of percentages would help, but I don't know how to turn outputs into percentages. Please note that I might have some comprehension problems here, math is not my strongest gamem but I did my absolute best to describe the problem...

Here is a table of income count vs. taxation percentage used.
Income vs. taxation percentage

Body:
Optimized way :

Here is a more-optimized way to do it (see at bottom for a non-optimized way with enumeration). I store the percents and thresholds in lists, and taxes is incremented during a loop :

yearly = int(input("Tell your yearly income:"))

percents = [0.1, 0.2, 0.3, 0.4, 0.5]
thresholds = [0, 15000, 30000, 45000, 60000]

taxes = 0
for i in range(len(percents)):
    if i == len(thresholds) - 1 or yearly < thresholds[i+1]:
        taxes += (yearly - thresholds[i]) * percents[i]
        break
    else:
        taxes += (thresholds[i+1] - thresholds[i]) * percents[i]

print("You pay {} taxes".format(taxes))
print("Your taxation percent is: {}%".format(taxes/yearly*100))

Examples of outputs :

# Test 1
Tell your yearly income:100000
You pay 35000.0 taxes
Your taxation percent is: 35.0%

# Test 2
Tell your yearly income:54000
You pay 12600.0 taxes
Your taxation percent is: 23.333333333333332%

Non-optimized way :

Here the key is to have a variable temp (initialized with temp = yearly that decreases when you apply the taxes :

yearly = int(input("Tell your yearly income:"))

one = 0.1
two = 0.2
three = 0.3
four = 0.4
five = 0.5

diff = 15000

temp = yearly
taxes = 0
if yearly in range(1,15000):
    taxes += temp * one
else:
    taxes += diff * one
    temp -= diff
if yearly in range(15001,30000):
    taxes += temp * two
else:
    taxes += diff * two
    temp -= diff
if yearly in range(30001,45000):
    taxes += temp * three
else:
    taxes += diff * three
    temp -= diff
if yearly in range(45001,60000):
    taxes += temp * four
else:
    taxes += diff * four
    temp -= diff
if yearly > 60000:
    taxes += temp * five

print("You pay {} taxes".format(taxes))
print("Your taxation percent is: {}%".format(taxes/yearly*100))


问:
Server is unwilling to process the request - Active Directory - Add User via C#
I used the example in this page to add a user to an Active Directory group, but I get an exception with the message "Server is unwilling to process the request" when executing

dirEntry.Properties["member"].Add(userDn);

答:
ldapwiki.com describes potential causes for "The server is unwilling to process the request". Check ExtendedErrorMessage property of your exception to figure out what applies. In my case "00002145: SvcErr: DSID-031A1254, problem 5003 (WILL_NOT_PERFORM)". The following line resolved the issue:

```<code>ent.Properties["groupType"].Value = 8;
</code>```

I had missed to set groupType and so attempted to nest a universal group in a global group. Find more information on groupType attribute in ldapwiki.com

Body:
ldapwiki.com describes potential causes for "The server is unwilling to process the request". Check ExtendedErrorMessage property of your exception to figure out what applies. In my case "00002145: SvcErr: DSID-031A1254, problem 5003 (WILL_NOT_PERFORM)". The following line resolved the issue:

ent.Properties["groupType"].Value = 8;

I had missed to set groupType and so attempted to nest a universal group in a global group. Find more information on groupType attribute in ldapwiki.com


问:
Access public final static field from tml page
I have a grid where I would like to load the data from method. This method is taking String as a parameter and produce necessary List as output.
For example, it can look like this:

```<code>public List<SomeObject> getContactBasedOnType(final String type)
    {
        final List<SomeObject> returnList = new ArrayList<>();
        ...//based on "type" list will be populated by different data
        return returnList;
    }
</code>```

and then in my tml page I will use it as follows:

```<code><t:grid t:source="getSomeData('STRING')"...
>...</t:grid>
</code>```

Now, I would like to replace 'STRING' with a public static String field from a class other than component class, for example:

```<code><t:grid t:source="getSomeData(com.example.Class.STATIC_FINAL_FIELD)"...
>...</t:grid>
</code>```

Is there any way I can do that directly? So without using any additional methods in a component class or annotated fields?

答:
There is a way to achieve what you asked, but it's an awful hack.

```<code><t:grid
t:source="getSomeData(getClass().getClassLoader().loadClass('com.example.Class').getField('STATIC_FINAL_FIELD').get(getClass().getClassLoader().loadClass('com.example.Class').getField('STATIC_FINAL_FIELD').getType().newInstance()))">
...
</t:grid>
</code>```

Note that, in your question, the method in the component class is named getContactBasedOnType while in your tmls you are referencing getSomeData. The method names must match, of course.

Again, the above is a terrible hack, but the only solution I got to work under the constraint that the component class may not be touched.

Making the list a property of the component class and populating it in the setupRender() method would be a much better design.

Body:
I have a grid where I would like to load the data from method. This method is taking String as a parameter and produce necessary List as output.
For example, it can look like this:

public List<SomeObject> getContactBasedOnType(final String type)
    {
        final List<SomeObject> returnList = new ArrayList<>();
        ...//based on "type" list will be populated by different data
        return returnList;
    }

and then in my tml page I will use it as follows:

<t:grid t:source="getSomeData('STRING')"...
>...</t:grid>

Now, I would like to replace 'STRING' with a public static String field from a class other than component class, for example:

<t:grid t:source="getSomeData(com.example.Class.STATIC_FINAL_FIELD)"...
>...</t:grid>

Is there any way I can do that directly? So without using any additional methods in a component class or annotated fields?

Body:
There is a way to achieve what you asked, but it's an awful hack.

<t:grid
t:source="getSomeData(getClass().getClassLoader().loadClass('com.example.Class').getField('STATIC_FINAL_FIELD').get(getClass().getClassLoader().loadClass('com.example.Class').getField('STATIC_FINAL_FIELD').getType().newInstance()))">
...
</t:grid>

Note that, in your question, the method in the component class is named getContactBasedOnType while in your tmls you are referencing getSomeData. The method names must match, of course.

Again, the above is a terrible hack, but the only solution I got to work under the constraint that the component class may not be touched.

Making the list a property of the component class and populating it in the setupRender() method would be a much better design.


问:
How to get the value of a jquery slider to follow the handle, but not all the way?
I have a jQuery slider that is supposed to be placed in a narrow column on a page. The idea is that the value should follow the handle in a tooltip like fashion underneath the slider. I've gotten that to work pretty good by using the pageX attribute of the "event object" in the jquery slider slide event.

```<code>$(element).css("left", event.pageX - ($(element).width() / 2)).text(ui.value);
</code>```

But the problem is that due to the fact that the column in quite narrow so when I drag the slider to max the displayed value will be placed outside the column. Or a part of it will anyway.

The solution I've come up with is either make the slider shorter. But my designer will probably complain. The other solution is to make sure that the value I'm displaying have a narrower field of movement than the slider. But I'm not sure how to accomplish this.

Any suggestions on how I can get my value to neatly follow the handle. But in a way that it won't "fall out"?

EDIT:
Here is a jsFiddle that explains how my situation looks today. The value that follows along on the bottom ends up outside the width of the column. That I've represented with a blue box.

http://jsfiddle.net/nuPYa/2/

答:
When calculating the position, you can easily force limits:

```<code>// Caching jQuery objects
var $element = $(element).text(ui.value);
var $container = $element.parent();

// Calculating new position
var newpos = event.pageX - $element.width() / 2;
newpos = Math.max(newpos, 0);
newpos = Math.min(newpos, $container.innerWidth() - $element.outerWidth());

$element.css('left', newpos);
</code>```

The calculation was broken up for readability. The code above assumes that the main column container is the parent of your element.

Body:
I have a jQuery slider that is supposed to be placed in a narrow column on a page. The idea is that the value should follow the handle in a tooltip like fashion underneath the slider. I've gotten that to work pretty good by using the pageX attribute of the "event object" in the jquery slider slide event.

$(element).css("left", event.pageX - ($(element).width() / 2)).text(ui.value);

But the problem is that due to the fact that the column in quite narrow so when I drag the slider to max the displayed value will be placed outside the column. Or a part of it will anyway.

The solution I've come up with is either make the slider shorter. But my designer will probably complain. The other solution is to make sure that the value I'm displaying have a narrower field of movement than the slider. But I'm not sure how to accomplish this.

Any suggestions on how I can get my value to neatly follow the handle. But in a way that it won't "fall out"?

EDIT:
Here is a jsFiddle that explains how my situation looks today. The value that follows along on the bottom ends up outside the width of the column. That I've represented with a blue box.

http://jsfiddle.net/nuPYa/2/

Body:
When calculating the position, you can easily force limits:

// Caching jQuery objects
var $element = $(element).text(ui.value);
var $container = $element.parent();

// Calculating new position
var newpos = event.pageX - $element.width() / 2;
newpos = Math.max(newpos, 0);
newpos = Math.min(newpos, $container.innerWidth() - $element.outerWidth());

$element.css('left', newpos);

The calculation was broken up for readability. The code above assumes that the main column container is the parent of your element.


问:
constrOptim initial values
I'm attempting to use the constrOptim() function in R to optimise:

2x + 2y + 3z

subject to:

-2x + y + z <= 1

4x - y + 3z <= 3

x, y, z >= 0

What I have so far is this:

```<code>ui = matrix(c(2,-1,-1,-4, 1,-3, 1, 0, 0, 0, 1, 0, 0, 0, 1),
                     nrow = 5,
                     byrow = T)

ci = c(-1, -3, 0, 0, 0)
theta = c(0, 1, 0)

constrOptim(
  theta = theta,
  f = func,
  ui = ui,
  ci = ci)
</code>```

This gives me the error that "initial value is not in the interior of the feasible region". However, if I run the following as a test:

```<code>ui = matrix(c(2,-1,-1,-4, 1,-3, 1, 0, 0, 0, 1, 0, 0, 0, 1),
                     nrow = 5,
                     byrow = T)

ci = c(-1, -3, 0, 0, 0)
theta = c(0, 1, 0)

ui %*% theta - ci
</code>```

I get (0  4  0  1  0), which is definitely >=0.

My question is why do I get an error telling me that ui %*% theta - ci is not >= 0, when it clearly is? What am I missing?

Edit: managed to sort it out thanks to Stéphane Laurent.

Any ideas how best to plot the feasible region in R? Any useful packages?

答:
The cause of error has been explained from the answer by Stéphane Laurent.

An alternative of constrOptim is to use fmincon from package pracma, and you can run the code without any error even with initial values on the boundary, i.e., theta = c(0,1,0)

```<code>ui = matrix(c(2,-1,-1,-4, 1,-3, 1, 0, 0, 0, 1, 0, 0, 0, 1),
            nrow = 5,
            byrow = T)
ci = c(-1, -3, 0, 0, 0)
theta = c(0, 1, 0)
func <- function(v) crossprod(c(2,2,3),v)

res <- pracma::fmincon(theta,
                       f = func,
                       A = -ui,
                       b = -ci)
</code>```

such that

```<code>> res
$par
[1] 0 0 0

$value
     [,1]
[1,]    0

$convergence
[1] 0

$info
$info$lambda
$info$lambda$lower
     [,1]
[1,]    0
[2,]    0
[3,]    0

$info$lambda$upper
     [,1]
[1,]    0
[2,]    0
[3,]    0

$info$lambda$ineqlin
[1] 0 0 2 2 3

$info$grad
     [,1]
[1,]    2
[2,]    2
[3,]    3

$info$hessian
     [,1] [,2] [,3]
[1,]    1 0.00    0
[2,]    0 0.03    0
[3,]    0 0.00    1
</code>```

Title: constrOptim initial values

Body:
I'm attempting to use the constrOptim() function in R to optimise:

2x + 2y + 3z

subject to:

-2x + y + z <= 1

4x - y + 3z <= 3

x, y, z >= 0

What I have so far is this:

ui = matrix(c(2,-1,-1,-4, 1,-3, 1, 0, 0, 0, 1, 0, 0, 0, 1),
                     nrow = 5,
                     byrow = T)

ci = c(-1, -3, 0, 0, 0)
theta = c(0, 1, 0)

constrOptim(
  theta = theta,
  f = func,
  ui = ui,
  ci = ci)

This gives me the error that "initial value is not in the interior of the feasible region". However, if I run the following as a test:

ui = matrix(c(2,-1,-1,-4, 1,-3, 1, 0, 0, 0, 1, 0, 0, 0, 1),
                     nrow = 5,
                     byrow = T)

ci = c(-1, -3, 0, 0, 0)
theta = c(0, 1, 0)

ui %*% theta - ci

I get (0  4  0  1  0), which is definitely >=0.

My question is why do I get an error telling me that ui %*% theta - ci is not >= 0, when it clearly is? What am I missing?

Edit: managed to sort it out thanks to Stéphane Laurent.

Any ideas how best to plot the feasible region in R? Any useful packages?

Body:
The cause of error has been explained from the answer by Stéphane Laurent.

An alternative of constrOptim is to use fmincon from package pracma, and you can run the code without any error even with initial values on the boundary, i.e., theta = c(0,1,0)

ui = matrix(c(2,-1,-1,-4, 1,-3, 1, 0, 0, 0, 1, 0, 0, 0, 1),
            nrow = 5,
            byrow = T)
ci = c(-1, -3, 0, 0, 0)
theta = c(0, 1, 0)
func <- function(v) crossprod(c(2,2,3),v)

res <- pracma::fmincon(theta,
                       f = func,
                       A = -ui,
                       b = -ci)

such that

> res
$par
[1] 0 0 0

$value
     [,1]
[1,]    0

$convergence
[1] 0

$info
$info$lambda
$info$lambda$lower
     [,1]
[1,]    0
[2,]    0
[3,]    0

$info$lambda$upper
     [,1]
[1,]    0
[2,]    0
[3,]    0

$info$lambda$ineqlin
[1] 0 0 2 2 3

$info$grad
     [,1]
[1,]    2
[2,]    2
[3,]    3

$info$hessian
     [,1] [,2] [,3]
[1,]    1 0.00    0
[2,]    0 0.03    0
[3,]    0 0.00    1