问:
How to stop single node kubernetes cluster gracefully
I've set up single node kubernetes  according to [official tutorial][1].

In addition to official documentation I've set-up single node cluster:

```<code>kubectl taint nodes --all node-role.kubernetes.io/master-
</code>```

Disabled eviction limit:

```<code>cat << EOF >> /var/lib/kubelet/config.yaml
evictionHard:
  imagefs.available: 1%
  memory.available: 100Mi
  nodefs.available: 1%
  nodefs.inodesFree: 1%
EOF

systemctl daemon-reload
systemctl restart kubelet
</code>```

And set systemd driver for Docker:

```<code>cat << EOF > /etc/docker/daemon.json
{
  "exec-opts": ["native.cgroupdriver=systemd"],
  "log-driver": "json-file",
  "log-opts": {
    "max-size": "100m"
  },
  "storage-driver": "overlay2"
}
EOF

systemctl daemon-reload
systemctl restart docker
</code>```

How can I temporary stop Kubernetes cluster (including all it's services, podd, etc)? I've issued systemctl stop kubelet but I stil see some kubernetes stuff among processes

```<code>$ ps -elf | grep kube
4 S root       6032   5914  1  80   0 - 2653148 -    Feb17 ?        00:35:10 etcd --advertise-client-urls=https://192.168.1.111:2379 --cert-file=/etc/kubernetes/pki/etcd/server.crt --client-cert-auth=true --data-dir=/var/lib/etcd --initial-advertise-peer-urls=https://192.168.1.111:2380 --initial-cluster=ubuntu=https://192.168.1.111:2380 --key-file=/etc/kubernetes/pki/etcd/server.key --listen-client-urls=https://127.0.0.1:2379,https://192.168.1.111:2379 --listen-metrics-urls=http://127.0.0.1:2381 --listen-peer-urls=https://192.168.1.111:2380 --name=ubuntu --peer-cert-file=/etc/kubernetes/pki/etcd/peer.crt --peer-client-cert-auth=true --peer-key-file=/etc/kubernetes/pki/etcd/peer.key --peer-trusted-ca-file=/etc/kubernetes/pki/etcd/ca.crt --snapshot-count=10000 --trusted-ca-file=/etc/kubernetes/pki/etcd/ca.crt
4 S root       7536   7495  0  80   0 - 35026 -      Feb17 ?        00:01:04 /usr/local/bin/kube-proxy --config=/var/lib/kube-proxy/config.conf --hostname-override=ubuntu
4 S root       9868   9839  0  80   0 - 34463 -      Feb17 ?        00:00:59 /usr/bin/kube-controllers
4 S root      48394  48375  2  80   0 - 36076 -      13:41 ?        00:01:09 kube-scheduler --authentication-kubeconfig=/etc/kubernetes/scheduler.conf --authorization-kubeconfig=/etc/kubernetes/scheduler.conf --bind-address=127.0.0.1 --kubeconfig=/etc/kubernetes/scheduler.conf --leader-elect=true
4 S root      48461  48436  3  80   0 - 52484 -      13:41 ?        00:01:53 kube-controller-manager --allocate-node-cidrs=true --authentication-kubeconfig=/etc/kubernetes/controller-manager.conf --authorization-kubeconfig=/etc/kubernetes/controller-manager.conf --bind-address=127.0.0.1 --client-ca-file=/etc/kubernetes/pki/ca.crt --cluster-cidr=10.244.0.0/16 --cluster-signing-cert-file=/etc/kubernetes/pki/ca.crt --cluster-signing-key-file=/etc/kubernetes/pki/ca.key --controllers=*,bootstrapsigner,tokencleaner --kubeconfig=/etc/kubernetes/controller-manager.conf --leader-elect=true --node-cidr-mask-size=24 --requestheader-client-ca-file=/etc/kubernetes/pki/front-proxy-ca.crt --root-ca-file=/etc/kubernetes/pki/ca.crt --service-account-private-key-file=/etc/kubernetes/pki/sa.key --service-cluster-ip-range=10.96.0.0/12 --use-service-account-credentials=true
4 S root      52675  52586  7  80   0 - 123895 -     14:00 ?        00:02:01 kube-apiserver --advertise-address=192.168.1.111 --allow-privileged=true --authorization-mode=Node,RBAC --client-ca-file=/etc/kubernetes/pki/ca.crt --enable-admission-plugins=NodeRestriction --enable-bootstrap-token-auth=true --etcd-cafile=/etc/kubernetes/pki/etcd/ca.crt --etcd-certfile=/etc/kubernetes/pki/apiserver-etcd-client.crt --etcd-keyfile=/etc/kubernetes/pki/apiserver-etcd-client.key --etcd-servers=https://127.0.0.1:2379 --insecure-port=0 --kubelet-client-certificate=/etc/kubernetes/pki/apiserver-kubelet-client.crt --kubelet-client-key=/etc/kubernetes/pki/apiserver-kubelet-client.key --kubelet-preferred-address-types=InternalIP,ExternalIP,Hostname --proxy-client-cert-file=/etc/kubernetes/pki/front-proxy-client.crt --proxy-client-key-file=/etc/kubernetes/pki/front-proxy-client.key --requestheader-allowed-names=front-proxy-client --requestheader-client-ca-file=/etc/kubernetes/pki/front-proxy-ca.crt --requestheader-extra-headers-prefix=X-Remote-Extra- --requestheader-group-headers=X-Remote-Group --requestheader-username-headers=X-Remote-User --secure-port=6443 --service-account-key-file=/etc/kubernetes/pki/sa.pub --service-cluster-ip-range=10.96.0.0/12 --tls-cert-file=/etc/kubernetes/pki/apiserver.crt --tls-private-key-file=/etc/kubernetes/pki/apiserver.key
</code>```

答:
If you really want to stop everything what is running by kubernetes/docker for what ever reason - you can just stop both kubelet and docker.

Perform these commands on the node you like to stop kubernetes/docker

```<code>systemctl stop kubelet
systemctl stop docker
</code>```

I strongly recommend to drain the node first, but if you just like to kill everything without any caution that would be one way to stop kubernetes and the running containers on the node  :)

once you like to start everything again just start docker and kubelet again or just reboot the machine.

cheers

Body:
I've set up single node kubernetes  according to [official tutorial][1].

In addition to official documentation I've set-up single node cluster:

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

Disabled eviction limit:

cat << EOF >> /var/lib/kubelet/config.yaml
evictionHard:
  imagefs.available: 1%
  memory.available: 100Mi
  nodefs.available: 1%
  nodefs.inodesFree: 1%
EOF

systemctl daemon-reload
systemctl restart kubelet

And set systemd driver for Docker:

cat << EOF > /etc/docker/daemon.json
{
  "exec-opts": ["native.cgroupdriver=systemd"],
  "log-driver": "json-file",
  "log-opts": {
    "max-size": "100m"
  },
  "storage-driver": "overlay2"
}
EOF

systemctl daemon-reload
systemctl restart docker

How can I temporary stop Kubernetes cluster (including all it's services, podd, etc)? I've issued systemctl stop kubelet but I stil see some kubernetes stuff among processes

$ ps -elf | grep kube
4 S root       6032   5914  1  80   0 - 2653148 -    Feb17 ?        00:35:10 etcd --advertise-client-urls=https://192.168.1.111:2379 --cert-file=/etc/kubernetes/pki/etcd/server.crt --client-cert-auth=true --data-dir=/var/lib/etcd --initial-advertise-peer-urls=https://192.168.1.111:2380 --initial-cluster=ubuntu=https://192.168.1.111:2380 --key-file=/etc/kubernetes/pki/etcd/server.key --listen-client-urls=https://127.0.0.1:2379,https://192.168.1.111:2379 --listen-metrics-urls=http://127.0.0.1:2381 --listen-peer-urls=https://192.168.1.111:2380 --name=ubuntu --peer-cert-file=/etc/kubernetes/pki/etcd/peer.crt --peer-client-cert-auth=true --peer-key-file=/etc/kubernetes/pki/etcd/peer.key --peer-trusted-ca-file=/etc/kubernetes/pki/etcd/ca.crt --snapshot-count=10000 --trusted-ca-file=/etc/kubernetes/pki/etcd/ca.crt
4 S root       7536   7495  0  80   0 - 35026 -      Feb17 ?        00:01:04 /usr/local/bin/kube-proxy --config=/var/lib/kube-proxy/config.conf --hostname-override=ubuntu
4 S root       9868   9839  0  80   0 - 34463 -      Feb17 ?        00:00:59 /usr/bin/kube-controllers
4 S root      48394  48375  2  80   0 - 36076 -      13:41 ?        00:01:09 kube-scheduler --authentication-kubeconfig=/etc/kubernetes/scheduler.conf --authorization-kubeconfig=/etc/kubernetes/scheduler.conf --bind-address=127.0.0.1 --kubeconfig=/etc/kubernetes/scheduler.conf --leader-elect=true
4 S root      48461  48436  3  80   0 - 52484 -      13:41 ?        00:01:53 kube-controller-manager --allocate-node-cidrs=true --authentication-kubeconfig=/etc/kubernetes/controller-manager.conf --authorization-kubeconfig=/etc/kubernetes/controller-manager.conf --bind-address=127.0.0.1 --client-ca-file=/etc/kubernetes/pki/ca.crt --cluster-cidr=10.244.0.0/16 --cluster-signing-cert-file=/etc/kubernetes/pki/ca.crt --cluster-signing-key-file=/etc/kubernetes/pki/ca.key --controllers=*,bootstrapsigner,tokencleaner --kubeconfig=/etc/kubernetes/controller-manager.conf --leader-elect=true --node-cidr-mask-size=24 --requestheader-client-ca-file=/etc/kubernetes/pki/front-proxy-ca.crt --root-ca-file=/etc/kubernetes/pki/ca.crt --service-account-private-key-file=/etc/kubernetes/pki/sa.key --service-cluster-ip-range=10.96.0.0/12 --use-service-account-credentials=true
4 S root      52675  52586  7  80   0 - 123895 -     14:00 ?        00:02:01 kube-apiserver --advertise-address=192.168.1.111 --allow-privileged=true --authorization-mode=Node,RBAC --client-ca-file=/etc/kubernetes/pki/ca.crt --enable-admission-plugins=NodeRestriction --enable-bootstrap-token-auth=true --etcd-cafile=/etc/kubernetes/pki/etcd/ca.crt --etcd-certfile=/etc/kubernetes/pki/apiserver-etcd-client.crt --etcd-keyfile=/etc/kubernetes/pki/apiserver-etcd-client.key --etcd-servers=https://127.0.0.1:2379 --insecure-port=0 --kubelet-client-certificate=/etc/kubernetes/pki/apiserver-kubelet-client.crt --kubelet-client-key=/etc/kubernetes/pki/apiserver-kubelet-client.key --kubelet-preferred-address-types=InternalIP,ExternalIP,Hostname --proxy-client-cert-file=/etc/kubernetes/pki/front-proxy-client.crt --proxy-client-key-file=/etc/kubernetes/pki/front-proxy-client.key --requestheader-allowed-names=front-proxy-client --requestheader-client-ca-file=/etc/kubernetes/pki/front-proxy-ca.crt --requestheader-extra-headers-prefix=X-Remote-Extra- --requestheader-group-headers=X-Remote-Group --requestheader-username-headers=X-Remote-User --secure-port=6443 --service-account-key-file=/etc/kubernetes/pki/sa.pub --service-cluster-ip-range=10.96.0.0/12 --tls-cert-file=/etc/kubernetes/pki/apiserver.crt --tls-private-key-file=/etc/kubernetes/pki/apiserver.key

Body:
If you really want to stop everything what is running by kubernetes/docker for what ever reason - you can just stop both kubelet and docker.

Perform these commands on the node you like to stop kubernetes/docker

systemctl stop kubelet
systemctl stop docker

I strongly recommend to drain the node first, but if you just like to kill everything without any caution that would be one way to stop kubernetes and the running containers on the node  :)

once you like to start everything again just start docker and kubelet again or just reboot the machine.

cheers


来源: stackexchange

问:
Digital root of a number using recursion
I am writing a recursive function to calculate the digital root of a given number:

```<code>def digital_root(num):
    sum = 0
    while num > 0:
        sum += num % 10
        num = num // 10

    while sum > 10:
        sum = digital_root(sum)

    return sum
</code>```

I am not sure if the second while should be replaced with an if statement, and if so, why? (and if not, why not?)

When I try both of the version, the return value is the same.
For example, for the number 10598, the output in both of them is 5.

答:
So, first, please think what you're asking.

If relates to a condition, and while relates to perform a repeated action as long as a certain condition holds.

The digital root recursion stops only when the resulting digit sum is less than 10.

ContentLicense: CC BY-SA 4.0

Body:
I am writing a recursive function to calculate the digital root of a given number:

def digital_root(num):
    sum = 0
    while num > 0:
        sum += num % 10
        num = num // 10

    while sum > 10:
        sum = digital_root(sum)

    return sum

I am not sure if the second while should be replaced with an if statement, and if so, why? (and if not, why not?)

When I try both of the version, the return value is the same.
For example, for the number 10598, the output in both of them is 5.


问:
template class inheritance problem
Can you please tell me, what am I missing?</p>

```<code>template <class T> struct Base
{
    T data;
    Base(const T &_data):data(_data) { }
};

template <class T> struct Derived : Base<T>
{
    Derived():Base(T()) {} //error: class 'Derived<T>' does not have any field named 'Base'
};
</code>```

答:
```<code>template <class T> struct Derived : Base<T>
{
    Derived():Base<T>(T()) {}
};
</code>```

ContentLicense: CC BY-SA 3.0

Title: template class inheritance problem

Body:
Can you please tell me, what am I missing?

template <class T> struct Base
{
    T data;
    Base(const T &_data):data(_data) { }
};

template <class T> struct Derived : Base<T>
{
    Derived():Base(T()) {} //error: class 'Derived<T>' does not have any field named 'Base'
};


问:
Jenkins: set a parameter defaultValue dynamically
I'm trying to set up a multibranch pipeline configuration where the "Deploy" boolean checkbox is defaulted to true on non-production branches, and false on the production build.

```<code>pipeline {
  parameters{
    booleanParam(defaultValue: true, description: 'Do deploy after build', name: 'DEPLOY')
</code>```

Is there some method to conditionally set defaultValue=false when $BRANCH_NAME == "production"?

答:
I think I might have answered my own question through a bunch of experimentation.  This seems crazy simple, but my test between two branches shows the Deploy parameter is properly defaulted on/off depending on the $BRANCH_NAME

```<code>def defaultDeploy = true
if ( BRANCH_NAME == "production" )
{
  defaultDeploy = false
}
pipeline {
  parameters{
    booleanParam(defaultValue: defaultDeploy,
      description: 'Do deploy after build', name: 'DEPLOY')
</code>```

Body:
I'm trying to set up a multibranch pipeline configuration where the "Deploy" boolean checkbox is defaulted to true on non-production branches, and false on the production build.

pipeline {
  parameters{
    booleanParam(defaultValue: true, description: 'Do deploy after build', name: 'DEPLOY')

Is there some method to conditionally set defaultValue=false when $BRANCH_NAME == "production"?

Body:
I think I might have answered my own question through a bunch of experimentation.  This seems crazy simple, but my test between two branches shows the Deploy parameter is properly defaulted on/off depending on the $BRANCH_NAME

def defaultDeploy = true
if ( BRANCH_NAME == "production" )
{
  defaultDeploy = false
}
pipeline {
  parameters{
    booleanParam(defaultValue: defaultDeploy,
      description: 'Do deploy after build', name: 'DEPLOY')


问:
MySQL query on sum() while returning detail of a particular row
I've got a table

```<code>id pos status price
1 US 0 0
1 UK 1 0
1 HK 2 100
2 HK 0 0
2 UK 1 200
...
</code>```

and I want to show the sum(price) of each id while showing the pos of the record where status=0

i.e.

```<code>id pos sum(price)
1 US 100
2 HK 200
...
</code>```

Any way to do it without using temp table?

答:
use exists like below

```<code>select id,pos,sum(price)
from table_name t1
where exists ( select 1 from table_name t2 where t1.id=t2.id and t2.status=0)
group by id,pos
</code>```

Body:
I've got a table

id pos status price
1 US 0 0
1 UK 1 0
1 HK 2 100
2 HK 0 0
2 UK 1 200
...

and I want to show the sum(price) of each id while showing the pos of the record where status=0

i.e.

id pos sum(price)
1 US 100
2 HK 200
...

Any way to do it without using temp table?

Body:
use exists like below

select id,pos,sum(price)
from table_name t1
where exists ( select 1 from table_name t2 where t1.id=t2.id and t2.status=0)
group by id,pos


问:
Chrome 80 css grid large descendants cause grid to grow
When a grid has a fixed width and height, and a descendent of the grid has a width or height that is larger than that of the grid, the descendent forces the grid to 'grow' to fit it. In previous versions of Chrome (pre 80), and the latest version of Firefox (73.0 at the time of writing this) the descendants of the grid respected the grid's bounds. I've had a look the release log for this update and can't seem to find any mention of changes to grid or grid-template-rows/columns.

Expected Behaviour (Pre Chrome 80/Firefox)

Actual Behaviour (Chrome 80)

Below is a minimal snippet to reproduce the problem.

```

My question is, is this a chrome bug, or is this chrome aligning to the css grid spec?

答:
The version should be available for download right now that reverts this issue.

I have found the following at google chromium src changes

Revert "[css-grid] Accommodate spanning items crossing flexible tracks"
https://chromium.googlesource.com/chromium/src/+/b1738fb61215bb8610e08f65de4d01681e250f7f

Also two more questions popped up with this same problem for those looking.

grid-template-columns in Chrome 80 inconsistently computed

Why does Chrome 80 cause this grid-template-rows: auto problem

I am new here (answering) so I couldn't comment these under at the accept answer.

Body:
When a grid has a fixed width and height, and a descendent of the grid has a width or height that is larger than that of the grid, the descendent forces the grid to 'grow' to fit it. In previous versions of Chrome (pre 80), and the latest version of Firefox (73.0 at the time of writing this) the descendants of the grid respected the grid's bounds. I've had a look the release log for this update and can't seem to find any mention of changes to grid or grid-template-rows/columns.

Expected Behaviour (Pre Chrome 80/Firefox)

Actual Behaviour (Chrome 80)

Below is a minimal snippet to reproduce the problem.

My question is, is this a chrome bug, or is this chrome aligning to the css grid spec?


问:
ASP.NET Core error on building with NSwag Error MSB3073
When I build the application, I get the following error message

```<code>The command "dotnet "C:\Users\Adminuser\.nuget\packages\nswag.msbuild\13.0.6\build\../tools/NetCore22/dotnet-nswag.dll" run /variables:Configuration=Debug" exited with code
-2147450730.    Northwind.WebUI C:\Users\Adminuser\Documents\Visual Studio 2017\Projects\NorthwindTraders-master\Northwind.WebUI\Northwind.WebUI.csproj 60
</code>```

Any Idea how to fix this issue?

答:
Try to install NSwagStudio then re open your visual studio.
That's should solve your problem.

If it's still not working

give a look about your output console when you try to compile your project, you should see something like this

1>Executing file 'nswag.json' with variables 'Configuration=Debug'...
  1>Launcher directory:
  C:\Users\Shadow.nuget\packages\nswag.msbuild\13.1.6\tools\NetCore30

You should have a file called dotnet-nswag.exe in your c:\user...\tools\netcore30 directory.

Put this exe in your environnement path.

Re open visual studio and your error should be gone.

Body:
When I build the application, I get the following error message

The command "dotnet "C:\Users\Adminuser\.nuget\packages\nswag.msbuild\13.0.6\build\../tools/NetCore22/dotnet-nswag.dll" run /variables:Configuration=Debug" exited with code
-2147450730.    Northwind.WebUI C:\Users\Adminuser\Documents\Visual Studio 2017\Projects\NorthwindTraders-master\Northwind.WebUI\Northwind.WebUI.csproj 60

Any Idea how to fix this issue?


问:
How to shift elements after adding in Doubly Linked List
I have added an element to a specified position in a Doubly Linked List, but I want to shift all the elements that was at that position and after it to the right? Any tips on how to approach this problem?</p>

```<code>public void addFirst(E e){
    DNode<E> headerNext = header.getNext();
    DNode<E> tempN = new DNode <E>(e, header, headerNext);
    headerNext.setPrev(tempN);
    header.setNext(tempN);
    size++;
}
public void add(int pos , E e ){
    DNode<E> ptr = new DNode<E> (e, null, null);
        if(pos == 1){
            addFirst(e);
            return;
        }
    DNode<E> optr = header;
    for (int i = 2; i <= size; i++) {
        if (i == pos) {
            DNode<E> tempN = optr.getNext();
            ptr.setNext(ptr);
            ptr.setPrev(optr);
            ptr.setPrev(tempN);
            tempN.setPrev(ptr);
        }
        ptr = ptr.getNext();
    }
    size++ ;
}
    }
</code>```

答:
Based example in your comment:

You need to update the next pointer of new node to point to element 3's address

Element 3's previous pointer to new node address

New node previous address with element 3's previous address

Lastly Goto element 3's previous address(node) and update its next pointer to new node address.

Body:
I have added an element to a specified position in a Doubly Linked List, but I want to shift all the elements that was at that position and after it to the right? Any tips on how to approach this problem?

public void addFirst(E e){
    DNode<E> headerNext = header.getNext();
    DNode<E> tempN = new DNode <E>(e, header, headerNext);
    headerNext.setPrev(tempN);
    header.setNext(tempN);
    size++;
}
public void add(int pos , E e ){
    DNode<E> ptr = new DNode<E> (e, null, null);
        if(pos == 1){
            addFirst(e);
            return;
        }
    DNode<E> optr = header;
    for (int i = 2; i <= size; i++) {
        if (i == pos) {
            DNode<E> tempN = optr.getNext();
            ptr.setNext(ptr);
            ptr.setPrev(optr);
            ptr.setPrev(tempN);
            tempN.setPrev(ptr);
        }
        ptr = ptr.getNext();
    }
    size++ ;
}
    }


答:
I think you just want aggregation with a conditional expression for pos:

```<code>select id, max(case when status = 0 then pos end) as pos_0, sum(price)
from t
group by id;
</code>```

Title: MySQL query on sum() while returning detail of a particular row

Body:
I think you just want aggregation with a conditional expression for pos:

select id, max(case when status = 0 then pos end) as pos_0, sum(price)
from t
group by id;


问:
javascript regex help
I have this complex question from my customer, I can't find a answer on it so now I will try to ask you guys.

The quest is the following:

I think that one rule might be: Dots
  which appears immediately after a
  number, not counted as sentences. This
  means that sentence present in the
  "8. marts"and "2.567" is not counted as
  word dots. In return, each word dots
  may be overlooked (if now a sentence
  ends with a number: "Vi kommer kl. 8")
  but it's probably after all not quite
  as often.

Another might be: If there is one
  character (a letter or number)
  immediately after a sentence is not a
  phrase sentence. That would make that
  we avoided counting the sentence
  present in the "f.eks.", "bl.a."
  and "cand.mag.".

I hope I can be helped here.

My code:

```<code><script>
function word_count(field, count) {

    var wordsNumberOverSeven = 0;
    var wordsNumber = 0

    var contentText = $(\'#lix_word_count\').val();
    contentText = contentText.replace(\'?\', \'.\');
    contentText = contentText.replace(\'!\', \'.\');
    contentText = contentText.replace(\',\', \'\');
    contentText = contentText.replace(\';\', \'\');
    contentText = contentText.replace(\':\', \'\');
    contentText = contentText.replace(\'\n\', \' \').replace(/^\s+|\s+$/g,\'\').replace(/\s\s+/g,\' \');

    var matchDots = contentText.split(\'.\').length-1;
    var match = contentText.split(\' \');

    $.each(match, function(){
        if ( this.length > 0 )
            wordsNumber += 1;

        if ( this.length >= 7 )
        {
            wordsNumberOverSeven += 1;
        }

    });

    var lixMatWords = wordsNumber / matchDots;
    var lixMatLongWords = ( wordsNumberOverSeven * 100 ) / wordsNumber;

    var lixMatch = Math.round(( lixMatWords + lixMatLongWords ) *100)/100;
    var lixType = \'\';

    if ( lixMatch <= 24 )
        lixType = \'Lixen i din tekst er \'+ lixMatch +\', dvs. at teksten er meget let at læse.\';
    else if ( lixMatch <= 34 )
        lixType = \'Lixen i din tekst er \'+ lixMatch +\', dvs. at teksten er let at læse\';
    else if ( lixMatch <= 44 )
        lixType = \'Lixen i din tekst er \'+ lixMatch +\', dvs. at teksten ligger i midterområdet.\';
    else if ( lixMatch <= 54 )
        lixType = \'Lixen i din tekst er \'+ lixMatch +\', dvs. at teksten er svær at læse.\';
    else
        lixType = \'Lixen i din tekst er \'+ lixMatch +\', dvs. at teksten er meget svær at læse.\';

    /** alert(lixType +\'\nDots: \'+ matchDots +\'\nWords: \'+ wordsNumber +\'\nLangeord: \'+ wordsNumberOverSeven); **/
    alert(lixType);
}
</script>
</code>```

答:
I think we need to see the rest of the rules, or a few more at least.

Perhaps it would be better to describe what you want to include as a sentence, rather than what to exclude. If you are looking for full sentences, then it might be a period preceded by a non-whitespace character and followed by a space or new line or line feed, or some more complex rule set. It may require more than one regular expression with some other logic to sort the more complex cases.

Title: javascript regex help


问:
Bootstrap 4 dropdown not-visible inside datatable
I have seen Bootstrap button drop-down inside responsive table not visible because of scroll and this Bootstrap 4 drop-down menu in table question but the solutions does not work with me because I'm using the DataTables plugin.

The dropdown menu should be above everything, but even after using data-boundary="window" as the Bootstrap 4 documentation tells, it still does not work.

You can see the problem in this JSFiddle.

Without the code of DataTables, it works just fine.

```<code>$(table).DataTable(
{
    'bPaginate'         : true,
    'bLengthChange'     : false,
    'bFilter'           : true,
    'bInfo'             : true,
    'bAutoWidth'        : false,
    'aoColumnDefs'      : [
      {
        'bSortable'     : false,
        'aTargets'      : ['nosorting']
      }],
    'aaSorting'         : [],
})
</code>```

答: You have an overflow on your data table. So to make your dropdown visible, you need to append it to the body. Solution

Body:
I have seen Bootstrap button drop-down inside responsive table not visible because of scroll and this Bootstrap 4 drop-down menu in table question but the solutions does not work with me because I'm using the DataTables plugin.

The dropdown menu should be above everything, but even after using data-boundary="window" as the Bootstrap 4 documentation tells, it still does not work.

You can see the problem in this JSFiddle.

Without the code of DataTables, it works just fine.

$(table).DataTable(
{
    'bPaginate'         : true,
    'bLengthChange'     : false,
    'bFilter'           : true,
    'bInfo'             : true,
    'bAutoWidth'        : false,
    'aoColumnDefs'      : [
      {
        'bSortable'     : false,
        'aTargets'      : ['nosorting']
      }],
    'aaSorting'         : [],
})


问:
Multiple joins off same table
I'm trying to connect two different types of users from the same users data table.

I have a database table with the following schema

agent_relationships

buyer_id

agent_id

I have a table with user data:

users

id

first name

last name

What i want is a data set that has the following:

buyer id first name

buyer id last name

agent id first name

agent id last name

I know im doing this incorrectly, but heres what I've attempted:

This one returns the same data for both buyer and agent, which i expected

select u1.first_name as buyerfirst,u1.last_name as buyerlast,u1.first_name as agentfirst,u1.last_name as agentlast from users u1 left join agent_relationships ar1 on ar1.buyer_id=u1.id left join agent_relationships ar2 on ar2.agent_id=u1.id

This one fails

select u1.first_name as buyerfirst,u1.last_name as buyerlast,u2.first_name as agentfirst,u2.last_name as agentlast from users u1,users u2 left join agent_relationships ar1 on ar1.buyer_id=u1.id left join agent_relationships ar2 on ar2.agent_id=u2.id

答:
```<code>select BU.first_name, BU.last_name, AU.first_name, AU.last_name
from agent_relationships
left join users BU on buyer_id = BU.id
left join users AU on agent_id= AU.id
</code>```

Title: Multiple joins off same table


问:
MinIfs with Array Slice
I assign a range from a table to an 2-D array and then perform some analyses with that array.

The array is of the variant type with columns 3, 4 and 5 containing the Item Name, Date and a value. The layout is similar to the following:

```
Column 3    Column 4    Column 5
Item A      01/09/1987  0
Item A      01/10/1987  0
Item A      01/11/1987  1455
Item A      01/12/1987  1863
Item A      01/01/1988  1882
Item A      01/02/1988  1890
Item A      01/03/1988  0
Item A      01/04/1988  0
Item A      01/05/1988  0
Item B      01/09/1987  0
Item B      01/10/1987  2041
Item B      01/11/1987  1130
Item B      01/12/1987  1452
Item B      01/01/1988  1863
Item B      01/02/1988  1683
Item B      01/03/1988  1605
Item B      01/04/1988  1614
Item B      01/05/1988  1544
```

I create a Temporary Array (the global array is way above the 65k items limit of the functions that I need) assigning the corresponding dates and values for one Item at a time.

I then try using the Minifs function, as follows:

```<code>KPIMat(jCount, 3) = Application.WorksheetFunction.MinIfs( _
    Application.WorksheetFunction.Index(TempArr1, 0, 4), _
    Application.WorksheetFunction.Index(TempArr1, 0, 5), _
    ">0")
</code>```

The KPIMat is an array to store the data KPI.

I get

Run-Time Error 424, Object Required

I think the Minifs function expects a range and I am passing a 1D array.

I have been trying to find a code-based solution, other than writing my own UDF to solve this problem.

答:
As you found MINIFS wants a range and not an array.

Just iterate the Array yourself and use a temp variable:

```<code>Dim minTemp As double
minTemp = 1E+99

Dim i As Long
For i = LBound(TempArr1, 1) To UBound(TempArr1,1)
    If temparr(i, 5) > 0 And temparr(i, 4) < minTemp Then
        minTemp = temparr(i, 4)
    End If
Next i

KPIMat(jCount, 3) = minTemp
</code>```

Title: MinIfs with Array Slice

Body:
I assign a range from a table to an 2-D array and then perform some analyses with that array.

The array is of the variant type with columns 3, 4 and 5 containing the Item Name, Date and a value. The layout is similar to the following:

Column 3    Column 4    Column 5
Item A      01/09/1987  0
Item A      01/10/1987  0
Item A      01/11/1987  1455
Item A      01/12/1987  1863
Item A      01/01/1988  1882
Item A      01/02/1988  1890
Item A      01/03/1988  0
Item A      01/04/1988  0
Item A      01/05/1988  0
Item B      01/09/1987  0
Item B      01/10/1987  2041
Item B      01/11/1987  1130
Item B      01/12/1987  1452
Item B      01/01/1988  1863
Item B      01/02/1988  1683
Item B      01/03/1988  1605
Item B      01/04/1988  1614
Item B      01/05/1988  1544

I create a Temporary Array (the global array is way above the 65k items limit of the functions that I need) assigning the corresponding dates and values for one Item at a time.

I then try using the Minifs function, as follows:

KPIMat(jCount, 3) = Application.WorksheetFunction.MinIfs( _
    Application.WorksheetFunction.Index(TempArr1, 0, 4), _
    Application.WorksheetFunction.Index(TempArr1, 0, 5), _
    ">0")

The KPIMat is an array to store the data KPI.

I get

Run-Time Error 424, Object Required

I think the Minifs function expects a range and I am passing a 1D array.

I have been trying to find a code-based solution, other than writing my own UDF to solve this problem.

Body:
As you found MINIFS wants a range and not an array.

Just iterate the Array yourself and use a temp variable:

Dim minTemp As double
minTemp = 1E+99

Dim i As Long
For i = LBound(TempArr1, 1) To UBound(TempArr1,1)
    If temparr(i, 5) > 0 And temparr(i, 4) < minTemp Then
        minTemp = temparr(i, 4)
    End If
Next i

KPIMat(jCount, 3) = minTemp


问:
"Operation is not allowed when the object is closed" when executing stored procedure
This is my stored procedure, and when I am calling it from my classic ASP code, I am getting the error:

Operation is not allowed when the object is closed.

when I try to do a record count.

Does anyone know what is wrong here?

I am trying to return the table @t.

Thanks.

```<code>USE [Hires_new]
GO
/****** Object:  StoredProcedure [dbo].[sp_selectNewHireWorkPeriodsSQL]    Script Date: 05/13/2013 14:04:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:
-- Create date:
-- Description:
-- =============================================
ALTER PROCEDURE [dbo].[sp_selectNewHireWorkPeriodsSQL]
    -- Add the parameters for the stored procedure here

AS

    declare @t table (HireID int, StartDate datetime, EndDate datetime, date_initiated datetime, date_closed datetime, firmName nvarchar(100), InquiryID int)
    DECLARE @acc INT
    SET @acc = 1
    DECLARE @max INT
    select @max = max(HireID) from NewHire
    WHILE (@acc <= @max)
        BEGIN
            IF (@acc in (select HireID from NewHire))
                BEGIN
                    insert into @t
                        select HireID, StartDate, EndDate, date_initiated, date_closed, firmName, Inquiries.InquiryID
                        from WorkPeriod, Firms, Inquiries
                        where HireID = @acc and WorkPeriod.FirmID = Firms.FirmID and WorkPeriod.InquiryID = Inquiries.InquiryID
                        order by HireID,StartDate DESC
                END
            set @acc = @acc + 1
        END
    select * from @t
</code>```

Asp classic code

```<code>selectNewHireWorkPeriodsSQL = "EXEC sp_selectNewHireWorkPeriodsSQL"
Set rsNewHireWorkPeriods = Server.CreateObject("ADODB.Recordset")
rsNewHireWorkPeriods.Open selectNewHireWorkPeriodsSQL,ConnectionString,adOpenStatic
NumOfNewHireWorkPeriods = rsNewHireWorkPeriods.RecordCount

response.write(NumOfNewHireWorkPeriods)
</code>```

答: This can be caused by a print statement in your stored procedure. I accidently left a few in after some performance debugging....hopefully this helps someone still working in legacy ADO. </p>

Body:
This is my stored procedure, and when I am calling it from my classic ASP code, I am getting the error:

Operation is not allowed when the object is closed.

when I try to do a record count.

Does anyone know what is wrong here?

I am trying to return the table @t.

Thanks.

USE [Hires_new]
GO
/****** Object:  StoredProcedure [dbo].[sp_selectNewHireWorkPeriodsSQL]    Script Date: 05/13/2013 14:04:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:
-- Create date:
-- Description:
-- =============================================
ALTER PROCEDURE [dbo].[sp_selectNewHireWorkPeriodsSQL]
    -- Add the parameters for the stored procedure here

AS

    declare @t table (HireID int, StartDate datetime, EndDate datetime, date_initiated datetime, date_closed datetime, firmName nvarchar(100), InquiryID int)
    DECLARE @acc INT
    SET @acc = 1
    DECLARE @max INT
    select @max = max(HireID) from NewHire
    WHILE (@acc <= @max)
        BEGIN
            IF (@acc in (select HireID from NewHire))
                BEGIN
                    insert into @t
                        select HireID, StartDate, EndDate, date_initiated, date_closed, firmName, Inquiries.InquiryID
                        from WorkPeriod, Firms, Inquiries
                        where HireID = @acc and WorkPeriod.FirmID = Firms.FirmID and WorkPeriod.InquiryID = Inquiries.InquiryID
                        order by HireID,StartDate DESC
                END
            set @acc = @acc + 1
        END
    select * from @t

Asp classic code

selectNewHireWorkPeriodsSQL = "EXEC sp_selectNewHireWorkPeriodsSQL"
Set rsNewHireWorkPeriods = Server.CreateObject("ADODB.Recordset")
rsNewHireWorkPeriods.Open selectNewHireWorkPeriodsSQL,ConnectionString,adOpenStatic
NumOfNewHireWorkPeriods = rsNewHireWorkPeriods.RecordCount

response.write(NumOfNewHireWorkPeriods)


问:
An unhandled exception occurred: Schematic "ng-add" not found in collection "@angular/bazel"
I have an Angular 8 project and I ran

```<code>ng add @angular/bazel
</code>```

on it (as pointed out in the docs).
But then I get this error:

Error

```<code>Unable to find compatible package.  Using 'latest'.
Installing packages for tooling via yarn.
Installed packages for tooling via yarn.
An unhandled exception occurred: Schematic "ng-add" not found in collection "@angular/bazel".
See "/tmp/ng-WJmXSk/angular-errors.log" for further details.
</code>```

Log File

```<code>[error] Error: Schematic "ng-add" not found in collection "@angular/bazel".
    at SchematicEngine.createSchematic (/home/flolu/Desktop/cents-ideas/services/frontend/node_modules/@angular/cli/node_modules/@angular-devkit/schematics/src/engine/engine.js:232:23)
    at CollectionImpl.createSchematic (/home/flolu/Desktop/cents-ideas/services/frontend/node_modules/@angular/cli/node_modules/@angular-devkit/schematics/src/engine/engine.js:69:29)
    at AddCommand.getSchematic (/home/flolu/Desktop/cents-ideas/services/frontend/node_modules/@angular/cli/models/schematic-command.js:135:27)
    at AddCommand.runSchematic (/home/flolu/Desktop/cents-ideas/services/frontend/node_modules/@angular/cli/models/schematic-command.js:291:32)
    at AddCommand.executeSchematic (/home/flolu/Desktop/cents-ideas/services/frontend/node_modules/@angular/cli/commands/add-impl.js:148:31)
    at AddCommand.run (/home/flolu/Desktop/cents-ideas/services/frontend/node_modules/@angular/cli/commands/add-impl.js:45:25)
    at AddCommand.validateAndRun (/home/flolu/Desktop/cents-ideas/services/frontend/node_modules/@angular/cli/models/command.js:134:39)
    at process._tickCallback (internal/process/next_tick.js:68:7)
    at Function.Module.runMain (internal/modules/cjs/loader.js:745:11)
    at startup (internal/bootstrap/node.js:283:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:743:3)
</code>```

You can try it yourself by running

```<code>ng add @angular/bazel
</code>```

in this project. (path: /services/frontend)

答: I seems as if updating the Angular CLI fixed the issue.</p>

Body:
I have an Angular 8 project and I ran

ng add @angular/bazel

on it (as pointed out in the docs).
But then I get this error:

Error

Unable to find compatible package.  Using 'latest'.
Installing packages for tooling via yarn.
Installed packages for tooling via yarn.
An unhandled exception occurred: Schematic "ng-add" not found in collection "@angular/bazel".
See "/tmp/ng-WJmXSk/angular-errors.log" for further details.

Log File

[error] Error: Schematic "ng-add" not found in collection "@angular/bazel".
    at SchematicEngine.createSchematic (/home/flolu/Desktop/cents-ideas/services/frontend/node_modules/@angular/cli/node_modules/@angular-devkit/schematics/src/engine/engine.js:232:23)
    at CollectionImpl.createSchematic (/home/flolu/Desktop/cents-ideas/services/frontend/node_modules/@angular/cli/node_modules/@angular-devkit/schematics/src/engine/engine.js:69:29)
    at AddCommand.getSchematic (/home/flolu/Desktop/cents-ideas/services/frontend/node_modules/@angular/cli/models/schematic-command.js:135:27)
    at AddCommand.runSchematic (/home/flolu/Desktop/cents-ideas/services/frontend/node_modules/@angular/cli/models/schematic-command.js:291:32)
    at AddCommand.executeSchematic (/home/flolu/Desktop/cents-ideas/services/frontend/node_modules/@angular/cli/commands/add-impl.js:148:31)
    at AddCommand.run (/home/flolu/Desktop/cents-ideas/services/frontend/node_modules/@angular/cli/commands/add-impl.js:45:25)
    at AddCommand.validateAndRun (/home/flolu/Desktop/cents-ideas/services/frontend/node_modules/@angular/cli/models/command.js:134:39)
    at process._tickCallback (internal/process/next_tick.js:68:7)
    at Function.Module.runMain (internal/modules/cjs/loader.js:745:11)
    at startup (internal/bootstrap/node.js:283:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:743:3)

You can try it yourself by running

ng add @angular/bazel

in this project. (path: /services/frontend)


问:
Pulling elements from a large string with PHP using CSS style selectors?
I have the following long string returned from a SOAP call into a variable, and I need to find the contents of certain elements within it, namely the .MoreInfoZone .OfferZone #Heading .content and .MoreInfoZone .OfferZone #Description .content.

I can't do it with javascript, as it is for populating metatags for Facebook Open Graph, and their spiders won't run the javascript.

```<code>$soap = '

<?xml version="1.0" encoding="utf-16"?>

    <div class="MoreInfoZone">
      <div class="OfferZone">
        <div id="Heading" class="Group">
          <div class="Label">
            <h3>Activity</h3>
          </div>
          <div class="Content">5-16 Trampoline / Swim Group 5-16 Trampoline / Swim
          Group5-16 Trampoline / Swim Group5-16 Trampolin1</div>
        </div>
        <div id="WhenZone">
          <div id="Date" class="Group">
            <div class="Label">
              <h3>
                <span class="StartDateLabel">Date</span>
              </h3>
            </div>
            <div class="Content">
            <span class="Start Date">21 December 2010</span> to
            <span class="End Date">24 November 2011</span></div>
          </div>
          <div id="Time" class="Group">
            <div class="Label">
              <h3>Time</h3>
            </div>
            <div class="Content">
            <span class="Start Time">10:00am</span> to
            <span class="End Time">12:00am</span></div>
          </div>
          <div id="DaysOfTheWeek" class="Group">
            <div class="Label">
              <h3>
                <span class="DaysOfTheWeekLabel">Days</span>
              </h3>
            </div>
            <div class="Content">
            <span class="weekdays">Monday, Tuesday, Wednesday, Thursday, Friday,</span>
            <span class="weekend">Saturday, Sunday</span></div>
          </div>
        </div>
        <div id="Description" class="Group">
          <div class="Label">
            <h3>Description</h3>
          </div>
          <div class="Content">
            <p>Trampolining5-16 Trampoline / Swim Group 5-16 Trampoline / Swim Group5-16
            Trampoline / Swim Group5-16 Trampolin15-16 Trampoline / Swim Group 5-16
            Trampoline / Swim Group5-16 Trampoline / Swim Group5-16 Trampolin15-16
            Trampoline / Swim Group 5-16 Trampoline / Swim Group5-16 Trampoline / Swim
            Group5-16 Trampolin15-16 Trampoline / Swim Group 5-16 Trampoline / Swim
            Group5-16 Trampoline / Swim Group5-16 Trampolin15-16 Trampoline / Swim Group
            5-16 Trampoline / Swim Group5-16 Trampoline / Swim Group5-16 Trampolin1</p>
          </div>
        </div>
        <div id="Provider" class="Group">
          <div class="Label">
            <h3>Provider</h3>
          </div>
          <div class="Content">
          ProviderXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX1</div>
        </div>
        <div id="Venue" class="Group">
          <div class="Label">
            <h3>Venue</h3>
          </div>
          <div class="Content">Brimble Hill School, Tadpole Lane, RedhouseBrimble Hill
          School, Tadpole Lane, RedhouseBrimble Hill 1
          <br />SN25 2NB</div>
        </div>
        <div id="Ages" class="Group">
          <div class="Label">
            <h3>Ages</h3>
          </div>
          <div class="Content">
          <span class="AgeFrom">5</span> to
          <span class="AgeTo">16</span></div>
        </div>
        <div id="OpenTo" class="Group">
          <div class="Label">
            <h3>Open To</h3>
          </div>
          <div class="Content">All disabled young people aged 5-16, and their friends,
          siblings, relatives.</div>
        </div>
        <div id="InclusiveAccessible" class="Group">
          <div class="Label">
            <h3>Inclusive/accessible for disabled users?</h3>
          </div>
          <div class="Content">Yes</div>
        </div>
        <div id="SuitableForOlderPeople" class="Group">
          <div class="Label">
            <h3>Suitable for older people?</h3>
          </div>
          <div class="Content">No</div>
        </div>
        <div id="Cost" class="Group">
          <div class="Label">
            <h3>Cost</h3>
          </div>
          <div class="Content Free">Free unless xyzxyz</div>
        </div>
        <div id="DiscountAvailable" class="Group">
          <div class="Label">
            <h3>Discount/Leisure cards accepted?</h3>
          </div>
          <div class="Content">Free unless xyzxyz</div>
        </div>
        <div id="MoreInformation" class="Group">
          <div class="Label">
            <h3>More information</h3>
          </div>
          <div class="Content">High demand, must book in advance.</div>
        </div>
        <div id="ContactZone" class="Group">
          <div class="Label">
            <h3>Contact</h3>
          </div>
          <div id="ContactName" class="Group">
            <div class="Label">
              <h3>Contact Name</h3>
            </div>
            <div class="Content">Ben HumphreyBen HumphreyBen HumphreyBen HumphreyBen
            HumphreyBen HumphreyBen HumphreyBen HumphreyBen</div>
          </div>
          <div id="ContactTel" class="Group">
            <div class="Label">
              <h3>Contact Telephone</h3>
            </div>
            <div class="Content">01793 617782 / mobile xxxxx xxxxxx 01793 617782 01793
            617782 / mobile xxxxx xxxxxx 01793 617782 0179</div>
          </div>
          <div id="ContactEmail" class="Group">
            <div class="Label">
              <h3>Contact Email</h3>
            </div>
            <div class="Content">
              <a href="mailto:ABCDEFGHIJKLMNOPQRSTUVWXYZ@swindon.gov.uk">ABCDEFGHIJKLMNOPQRSTUVWXYZ@swindon.gov.uk</a>
            </div>
          </div>
          <div id="ContactWebsite" class="Group">
            <div class="Label">
              <h3>Contact Website</h3>
            </div>
            <div class="Content">
              <a href="http://www.ABCDEFGHIJKLMNOPQRSTUVWXYZ.gov.uk">www.ABCDEFGHIJKLMNOPQRSTUVWXYZ.gov.uk</a>
            </div>
          </div>
        </div>
        <div id="SafetyZone">
          <div class="Title">
            <h2>Safety</h2>
          </div>
          <div id="EnhancedCRB" class="Group">
            <div class="Label">
              <h3>Enhanced CRB disclosure gained</h3>
            </div>
            <div class="Content">All Staff</div>
          </div>
          <div id="ChildProtectionTrained" class="Group">
            <div class="Label">
              <h3>Child Protection trained</h3>
            </div>
            <div class="Content">Some Staff</div>
          </div>
          <div id="SafeguardingPolicy" class="Group">
            <div class="Label">
              <h3>Organisation has safeguarding policy</h3>
            </div>
            <div class="Content">Yes</div>
          </div>
          <div id="FirstAidOnSite" class="Group">
            <div class="Label">
              <h3>First Aid available on site</h3>
            </div>
            <div class="Content"></div>
          </div>
          <div id="AccreditationInsurance" class="Group">
            <div class="Label">
              <h3>Accreditation / Insurance</h3>
            </div>
            <div class="Content">Yes</div>
          </div>
          <div id="SaferRecruitment" class="Group">
            <div class="Label">
              <h3>A member of staff on each recruitment panel trained in Safer
              Recruitment</h3>
            </div>
            <div class="Content">Yes</div>
          </div>
          <div id="RegisteredWithIC" class="Group">
            <div class="Label">
              <h3>Organisation registered with the Information Commissioner</h3>
            </div>
            <div class="Content">Yes</div>
          </div>
          <div id="ExtraSafeguardingInfo" class="Group">
            <div class="Label">
              <h3>Additional Notes on Safeguarding</h3>
            </div>
            <div class="Content">more info ....................</div>
          </div>
        </div>
        <div id="ReviewSummaryZone">
          <div id="RSHeading">
            <div class="Label">
              <h3>Average rating</h3>
            </div>
            <div class="Content">
              <img src="images/1Star.gif" alt="1 Star Rating" />
            </div>
          </div>
          <div id="RSRating">
            <div class="Label">
              <h3>Number of ratings</h3>
            </div>
            <div class="Content">1 rating(s)</div>
          </div>
          <div id="RSNewReview">
            <div class="Content">
              <a href="?Type=CDA1C2A0-0BDC-47FD-B08D-BEDF8A6006DB&Id=CC9488C5-C9A3-4A06-9A13-2BB9A1703157">
              Rate this</a>
            </div>
          </div>
        </div>
        <div id="ReviewZone">
          <div class="Review">
            <div class="User">
              <div class="Label">
                <h3>Name</h3>
              </div>
              <div class="Content">Gary Salter</div>
            </div>
            <div class="ReviewDate">
              <div class="Label">
                <h3>Date</h3>
              </div>
              <div class="Content">17 February 2011</div>
            </div>
            <div class="Comment">
              <div class="Label">
                <h3>Comments</h3>
              </div>
              <div class="Content">Test feedback</div>
            </div>
            <div class="Rating">
              <div class="Label">
                <h3>Rating</h3>
              </div>
              <div class="Content">
                <img src="images/1Star.gif" alt="1 Star Rating" />
              </div>
            </div>
          </div>
        </div>
      </div>
    </div> ';
</code>```

答:
Consider:

http://code.google.com/p/phpquery/

or

http://php.net/manual/en/class.domxpath.php

An XPath example could be:

```<code><?php
$dom = new DOMDocument();
$dom->loadXml($soap);

$xpath = new DOMXPath($dom);

// .MoreInfoZone .OfferZone #Heading .content
$headingContent = $xpath->query('//*[@id="Heading"]//*[contains(@class, "Content")]')->item(0);
if ($headingContent instanceof DOMNode) {
    echo $headingContent->nodeValue;
}

// .MoreInfoZone .OfferZone #Description .content
$descriptionContent = $xpath->query('//*[@id="Description"]//*[contains(@class, "Content")]/p')->item(0);
if ($descriptionContent instanceof DOMNode) {
    echo $descriptionContent->nodeValue;
}
</code>```

as I normally only do stuff like this with xpath, I can't provide a working example with phpquery. Sorry about that.

Body:
I have the following long string returned from a SOAP call into a variable, and I need to find the contents of certain elements within it, namely the .MoreInfoZone .OfferZone #Heading .content and .MoreInfoZone .OfferZone #Description .content.

I can't do it with javascript, as it is for populating metatags for Facebook Open Graph, and their spiders won't run the javascript.

$soap = '

<?xml version="1.0" encoding="utf-16"?>

Activity

5-16 Trampoline / Swim Group 5-16 Trampoline / Swim
          Group5-16 Trampoline / Swim Group5-16 Trampolin1

                Date

            21 December 2010 to
            24 November 2011

Time

            10:00am to
            12:00am

                Days

            Monday, Tuesday, Wednesday, Thursday, Friday,
            Saturday, Sunday

Description

Trampolining5-16 Trampoline / Swim Group 5-16 Trampoline / Swim Group5-16
            Trampoline / Swim Group5-16 Trampolin15-16 Trampoline / Swim Group 5-16
            Trampoline / Swim Group5-16 Trampoline / Swim Group5-16 Trampolin15-16
            Trampoline / Swim Group 5-16 Trampoline / Swim Group5-16 Trampoline / Swim
            Group5-16 Trampolin15-16 Trampoline / Swim Group 5-16 Trampoline / Swim
            Group5-16 Trampoline / Swim Group5-16 Trampolin15-16 Trampoline / Swim Group
            5-16 Trampoline / Swim Group5-16 Trampoline / Swim Group5-16 Trampolin1

Provider

          ProviderXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX1

Venue

Brimble Hill School, Tadpole Lane, RedhouseBrimble Hill
          School, Tadpole Lane, RedhouseBrimble Hill 1

SN25 2NB

Ages

          5 to
          16

Open To

All disabled young people aged 5-16, and their friends,
          siblings, relatives.

Inclusive/accessible for disabled users?

Yes

Suitable for older people?

No

Cost

Free unless xyzxyz

Discount/Leisure cards accepted?

Free unless xyzxyz

More information

High demand, must book in advance.

Contact

Contact Name

Ben HumphreyBen HumphreyBen HumphreyBen HumphreyBen
            HumphreyBen HumphreyBen HumphreyBen HumphreyBen

Contact Telephone

01793 617782 / mobile xxxxx xxxxxx 01793 617782 01793
            617782 / mobile xxxxx xxxxxx 01793 617782 0179

Contact Email

              ABCDEFGHIJKLMNOPQRSTUVWXYZ@swindon.gov.uk

Contact Website

              www.ABCDEFGHIJKLMNOPQRSTUVWXYZ.gov.uk

Safety

Enhanced CRB disclosure gained

All Staff

Child Protection trained

Some Staff

Organisation has safeguarding policy

Yes

First Aid available on site

Accreditation / Insurance

Yes

A member of staff on each recruitment panel trained in Safer
              Recruitment

Yes

Organisation registered with the Information Commissioner

Yes

Additional Notes on Safeguarding

more info ....................

Average rating

Number of ratings

1 rating(s)

              Rate this

Name

Gary Salter

Date

17 February 2011

Comments

Test feedback

Rating

 ';

Body:
Consider:

http://code.google.com/p/phpquery/

or

http://php.net/manual/en/class.domxpath.php

An XPath example could be:

<?php
$dom = new DOMDocument();
$dom->loadXml($soap);

$xpath = new DOMXPath($dom);

// .MoreInfoZone .OfferZone #Heading .content
$headingContent = $xpath->query('//*[@id="Heading"]//*[contains(@class, "Content")]')->item(0);
if ($headingContent instanceof DOMNode) {
    echo $headingContent->nodeValue;
}

// .MoreInfoZone .OfferZone #Description .content
$descriptionContent = $xpath->query('//*[@id="Description"]//*[contains(@class, "Content")]/p')->item(0);
if ($descriptionContent instanceof DOMNode) {
    echo $descriptionContent->nodeValue;
}

as I normally only do stuff like this with xpath, I can't provide a working example with phpquery. Sorry about that.


问:
use different babel preset when running mocha tests
My npm package build runs with babel and I configured a babel preset in my package.json with

"babel": { "presets": ["es2015"] }

I also configured a mocha test script with

"test": "mocha --compilers js:babel-core/register"

However, I would like to run my tests using a different babel preset than that one specified for my build.

Is it possible? I would you achieve that?

答:
The answer about configuring babel in package.json was partially ok.
I needed to add seperate env entries to make it work cause otherwise the config outside env would always run.
So the final configuration example would look like this:

```<code>"babel": {
    "env": {
      "test-console": {
        "presets": ["@babel/preset-env"],
        "plugins": ["@babel/plugin-proposal-class-properties"]
      }
    ,
      "test": {
        "presets": ["@babel/preset-env"],
        "plugins": ["@babel/plugin-proposal-class-properties", "transform-remove-console"]
      }
    }
</code>```

And scripts:

```<code> "scripts": {
    "test-console-log": "BABEL_ENV=test-console mocha || TRUE",
    "test": "BABEL_ENV=test mocha || TRUE"
  }
</code>```

Body:
The answer about configuring babel in package.json was partially ok.
I needed to add seperate env entries to make it work cause otherwise the config outside env would always run.
So the final configuration example would look like this:

"babel": {
    "env": {
      "test-console": {
        "presets": ["@babel/preset-env"],
        "plugins": ["@babel/plugin-proposal-class-properties"]
      }
    ,
      "test": {
        "presets": ["@babel/preset-env"],
        "plugins": ["@babel/plugin-proposal-class-properties", "transform-remove-console"]
      }
    }

And scripts:

 "scripts": {
    "test-console-log": "BABEL_ENV=test-console mocha || TRUE",
    "test": "BABEL_ENV=test mocha || TRUE"
  }


问:
MySQL : delete all records based on an id and other colums content
I got the following table

```<code>+----+---------+---------+
| id |  val1   |  val2   |
+----+---------+---------+
|  1 |  aaaa   |  bbbb   |
|  2 |  cccc   |  dddd   |
|  3 |  aaaa   |  eeee   |
|  4 |  ffff   |  bbbb   |
|  5 |  aaaa   |  bbbb   |
+----+---------+---------+
</code>```

I have identified I need to delete the record with id = 1

But I want also delete all the records having same val1 and val2 as id 1.

In this case, id 5 should also me removed.

I have tried that with no luck

```<code>SELECT id FROM table t1
INNER JOIN table t2
ON t1.val1 = t2.val1
AND t1.val2 = t2.val2
AND t1.id = 1
</code>```

答:
you could use a subquery  </p>

```<code>delete t
from table t
inner join  (
  select val1, val2
  from table
  where id = 1
) s on s.val1 = t.val1
      and s.val2 = t.val2
</code>```

Body:
I got the following table

+----+---------+---------+
| id |  val1   |  val2   |
+----+---------+---------+
|  1 |  aaaa   |  bbbb   |
|  2 |  cccc   |  dddd   |
|  3 |  aaaa   |  eeee   |
|  4 |  ffff   |  bbbb   |
|  5 |  aaaa   |  bbbb   |
+----+---------+---------+

I have identified I need to delete the record with id = 1

But I want also delete all the records having same val1 and val2 as id 1.

In this case, id 5 should also me removed.

I have tried that with no luck

SELECT id FROM table t1
INNER JOIN table t2
ON t1.val1 = t2.val1
AND t1.val2 = t2.val2
AND t1.id = 1

Body:
you could use a subquery

delete t
from table t
inner join  (
  select val1, val2
  from table
  where id = 1
) s on s.val1 = t.val1
      and s.val2 = t.val2


问:
Why does Array(repeating: Dog(), count: 7) make an array of 7 elements pointing to the same Dog instance?
Assuming Dog is a class

```<code>let arr = Array(repeating: Dog(), count: 7)
</code>```

Why do all the elements in the array point to the same dog instance ?
Now, I know to run a normal for loop and create 7 instances like

```<code>var arr = [Dog]()
for i in 1...7 {
   arr[i] = Dog()
}
</code>```

But that's not the point. I wanna understand the init(repeating:count:) function at a deeper level. Please share any insights you have !

答:
If Dog is a struct - the two instances are in fact different:

```<code>struct  Dog  {
    var hungry = true
}

var arr = Array(repeating: Dog(), count: 2) // two hungry dogs
print(arr[0].hungry) // true
print(arr[1].hungry) // true
arr[1].hungry = false // feed second dog
print(arr[0].hungry) // true
print(arr[1].hungry) // false
</code>```

Else if Dog is a class - the two instances are the same (both reference the same object):

```<code>class Dog  {
    var hungry = true
}

var arr = Array(repeating: Dog(), count: 2) // two hungry dogs
print(arr[0].hungry) // true
print(arr[1].hungry) // true
arr[1].hungry = false // feed second dog
print(arr[0].hungry) // false
print(arr[1].hungry) // false
</code>```

Body:
Assuming Dog is a class

let arr = Array(repeating: Dog(), count: 7)

Why do all the elements in the array point to the same dog instance ?
Now, I know to run a normal for loop and create 7 instances like

var arr = [Dog]()
for i in 1...7 {
   arr[i] = Dog()
}

But that's not the point. I wanna understand the init(repeating:count:) function at a deeper level. Please share any insights you have !

Body:
If Dog is a struct - the two instances are in fact different:

struct  Dog  {
    var hungry = true
}

var arr = Array(repeating: Dog(), count: 2) // two hungry dogs
print(arr[0].hungry) // true
print(arr[1].hungry) // true
arr[1].hungry = false // feed second dog
print(arr[0].hungry) // true
print(arr[1].hungry) // false

Else if Dog is a class - the two instances are the same (both reference the same object):

class Dog  {
    var hungry = true
}

var arr = Array(repeating: Dog(), count: 2) // two hungry dogs
print(arr[0].hungry) // true
print(arr[1].hungry) // true
arr[1].hungry = false // feed second dog
print(arr[0].hungry) // false
print(arr[1].hungry) // false


问:
how to replace name with an ID in javascript
I'm working on small programme and trying to make something that user can choose an item from the list "its like a resturant menu where the user choose their foods and it shows the prices and the tax", I used   name="items[]" to get the values i was wondering if there is a way to use ID  or Class instead of the name.Any help would be appreciated in advance .

var count = 0;
var tax = 0.05;

var taxFeild = document.getElementById("Tax");
var checkBoxes = document.getElementById("checkBoxes");
var checks=document.querySelectorAll('.items');
var ItemTotal=document.getElementById('ItemTotal');
var Total=document.getElementById('TotalWithTax');
var btn = document.getElementById("btn");

function Calculate()
{
  initVariable();

 for(var i =0 ;i< checks.length;i++)
   {
     if(checks[i].checked)
       {
         count+=parseFloat(checks[i].value);
       }
   }
  ItemTotal.innerHTML +=count;
  taxFeild.innerHTML+=(parseFloat(tax*count));
  Total.innerHTML+= (tax*count) + count;
}

btn.addEventListener('click',Calculate);

function initVariable()
{
  count =0;
  ItemTotal.innerHTML="Item Total: ";
  taxFeild.innerHTML =" Tax: ";
  Total.innerHTML ="Total with Tax: ";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta charset="utf-8"/>

<head>

<title>Test</title>
</head>

<body>
  <div class = "container">
   <div id="checkBoxes">
  <input type="checkbox" class="items" value='7.99' id="item1">Fried Chicken ($7.99)<br>
  <input type="checkbox" class="items" value='9.99' id="item1"> Fried Halibut ($9.99)<br>
  <input type="checkbox" class="items" value='12.99' id="item1"> Hamburger ($12.99)<br><br>
    </div>
   <button id="btn">Calculate</button>

    <div id="Sums">
      <p id="ItemTotal"> Item Total: </p>
      <p id="Tax"> Tax: </p>
      <p id="TotalWithTax">Total with Tax: </p>

    </div>
  </div>

</body>

</html></code>```

答:
You can select elements by their class. I would recommend using jQuery for this, but it can also be done in pure JavaScript. Let's assuming that we have three basic checkboxes (this is pseudo code):

```<code><input type="checkbox" class="form-control" value="7.99">
<input type="checkbox" class="form-control" value="9.99">
<input type="checkbox" class="form-control" value="8.99">
<button class="btn btn-primary" type="button">
    Calculate
</button>
</code>```

We could use jQuery to iterate over each element with the class name ".form-control" in this scenario:

```<code>$(document).ready(function() {
    const tax = 0.05;
    $('.btn').on('click', function() {
        let total = 0;
        $('.form-control').each(function() {
            if($(this).is(':checked')) {
                let val = parseFloat($(this).val());
                total += val;
            }
        });
        if(total > 0) {
            total += tax;
            alert('Your total is $' + total);
        }
    });
});
</code>```

Without jQuery you would do something such as:

```<code>const checks = document.getElementByClassName('form-control');
</code>```

and then you could run an checks.each();

As a side not, do not give elements the same ID name or else JavaScript will not know which element you are trying to select. If you are going to select elements based on their id, make sure they have different ID's.

Body:
I'm working on small programme and trying to make something that user can choose an item from the list "its like a resturant menu where the user choose their foods and it shows the prices and the tax", I used   name="items[]" to get the values i was wondering if there is a way to use ID  or Class instead of the name.Any help would be appreciated in advance .

var count = 0;
var tax = 0.05;

var taxFeild = document.getElementById("Tax");
var checkBoxes = document.getElementById("checkBoxes");
var checks=document.querySelectorAll('.items');
var ItemTotal=document.getElementById('ItemTotal');
var Total=document.getElementById('TotalWithTax');
var btn = document.getElementById("btn");

function Calculate()
{
  initVariable();

 for(var i =0 ;i< checks.length;i++)
   {
     if(checks[i].checked)
       {
         count+=parseFloat(checks[i].value);
       }
   }
  ItemTotal.innerHTML +=count;
  taxFeild.innerHTML+=(parseFloat(tax*count));
  Total.innerHTML+= (tax*count) + count;
}

btn.addEventListener('click',Calculate);

function initVariable()
{
  count =0;
  ItemTotal.innerHTML="Item Total: ";
  taxFeild.innerHTML =" Tax: ";
  Total.innerHTML ="Total with Tax: ";
}

<!DOCTYPE html>

<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta charset="utf-8"/>

<title>Test</title>

  <input type="checkbox" class="items" value='7.99' id="item1">Fried Chicken ($7.99)

  <input type="checkbox" class="items" value='9.99' id="item1"> Fried Halibut ($9.99)

  <input type="checkbox" class="items" value='12.99' id="item1"> Hamburger ($12.99)

   <button id="btn">Calculate</button>

 Item Total:

 Tax:

Total with Tax:

Body:
You can select elements by their class. I would recommend using jQuery for this, but it can also be done in pure JavaScript. Let's assuming that we have three basic checkboxes (this is pseudo code):

<input type="checkbox" class="form-control" value="7.99">
<input type="checkbox" class="form-control" value="9.99">
<input type="checkbox" class="form-control" value="8.99">
<button class="btn btn-primary" type="button">
    Calculate
</button>

We could use jQuery to iterate over each element with the class name ".form-control" in this scenario:

$(document).ready(function() {
    const tax = 0.05;
    $('.btn').on('click', function() {
        let total = 0;
        $('.form-control').each(function() {
            if($(this).is(':checked')) {
                let val = parseFloat($(this).val());
                total += val;
            }
        });
        if(total > 0) {
            total += tax;
            alert('Your total is $' + total);
        }
    });
});

Without jQuery you would do something such as:

const checks = document.getElementByClassName('form-control');

and then you could run an checks.each();

As a side not, do not give elements the same ID name or else JavaScript will not know which element you are trying to select. If you are going to select elements based on their id, make sure they have different ID's.


问:
Pulp Scheduling Optimization Problem - multiple supply inputs over time
I am currently building a scheduling plan in pulp, however I am struggling to understand how to represent the supply variable for pulp to parse as the data is contained in a multi-index dataframe.

Problem
I am trying to minimise any delta so that supply, by plant, by month, matches demand. Note, not all plants product the required product

Current Supply Data

I am aware that pulp accepts dictionaries of variables as inputs, i.e:

```<code>LpVariable.dicts("Route",(plant, output)
</code>```

however I am unsure of how I can represent supply here as:

(month, plant, product, production_output)

Any help greatly appreciated.

答:
I think what you want to do is have decision variables which are how much to supply of each product in each month, at each plant. In other words you have the indices: (months, plants, products).

This will of course create a total of len(months)*len(plants)*len(products) variables, which in the example is 12*5*4 = 240 variables.

I would handle the case of plants which cannot produce a certain product by setting the capacity for that product from that plant to zero.

```<code>import pulp

months = range(1,12)
plants = ['A', 'B', 'C', 'D', 'E']
products = ['AFS', 'GDF', 'POD', 'PPI']

supply = pulp.LpVariable.dicts("supply", (months, plants, products))
print(supply)
</code>```

This will return variables which can be referenced as, for example: supply[3]['A']['POD']

Body:
I am currently building a scheduling plan in pulp, however I am struggling to understand how to represent the supply variable for pulp to parse as the data is contained in a multi-index dataframe.

Problem
I am trying to minimise any delta so that supply, by plant, by month, matches demand. Note, not all plants product the required product

Current Supply Data

I am aware that pulp accepts dictionaries of variables as inputs, i.e:

LpVariable.dicts("Route",(plant, output)

however I am unsure of how I can represent supply here as:

(month, plant, product, production_output)

Any help greatly appreciated.

Body:
I think what you want to do is have decision variables which are how much to supply of each product in each month, at each plant. In other words you have the indices: (months, plants, products).

This will of course create a total of len(months)*len(plants)*len(products) variables, which in the example is 12*5*4 = 240 variables.

I would handle the case of plants which cannot produce a certain product by setting the capacity for that product from that plant to zero.

import pulp

months = range(1,12)
plants = ['A', 'B', 'C', 'D', 'E']
products = ['AFS', 'GDF', 'POD', 'PPI']

supply = pulp.LpVariable.dicts("supply", (months, plants, products))
print(supply)

This will return variables which can be referenced as, for example: supply[3]['A']['POD']


问:
Timedelta of datetime object and timezone object
I have a string datetime in YY/M/D/H which is already casted to PST timezone and saved. While reading it I am doing the following

```<code>submitted_time = '2020/02/13/11/16'
submitted_datetime = datetime.strptime(submitted_time, '%Y/%m/%d/%H/%M')
</code>```

This time is already in PST timezone and to calculate the timedifference I tried doing the following :

```<code>from pytz import timezone
pacific = timezone('America/Los_Angeles')
today = datetime.now().astimezone(pacific)
</code>```

But today - submitted_datetime won't work.  I get the following error:

*** TypeError: can't subtract offset-naive and offset-aware datetimes

Is there a way I can get this working ? Any help is greatly appreciated.

答:
With the code you provide, I doubt submitted_time will be interpreted as timezone aware, let alone PST. If you do convert it to a timezone aware datetime object, then the substraction works:

```<code>from datetime import datetime
from pytz import timezone
submitted_time = datetime.strptime('2020/02/13/11/16', '%Y/%m/%d/%H/%M')
pacific = timezone('America/Los_Angeles')
today = datetime.now().astimezone(pacific)
submitted_time = submitted_time.astimezone(pacific)
print(today - submitted_time)
</code>```

Output:

```<code>5 days, 4:50:57.251801
</code>```

Body:
I have a string datetime in YY/M/D/H which is already casted to PST timezone and saved. While reading it I am doing the following

submitted_time = '2020/02/13/11/16'
submitted_datetime = datetime.strptime(submitted_time, '%Y/%m/%d/%H/%M')

This time is already in PST timezone and to calculate the timedifference I tried doing the following :

from pytz import timezone
pacific = timezone('America/Los_Angeles')
today = datetime.now().astimezone(pacific)

But today - submitted_datetime won't work.  I get the following error:

*** TypeError: can't subtract offset-naive and offset-aware datetimes

Is there a way I can get this working ? Any help is greatly appreciated.

Body:
With the code you provide, I doubt submitted_time will be interpreted as timezone aware, let alone PST. If you do convert it to a timezone aware datetime object, then the substraction works:

from datetime import datetime
from pytz import timezone
submitted_time = datetime.strptime('2020/02/13/11/16', '%Y/%m/%d/%H/%M')
pacific = timezone('America/Los_Angeles')
today = datetime.now().astimezone(pacific)
submitted_time = submitted_time.astimezone(pacific)
print(today - submitted_time)

Output:

5 days, 4:50:57.251801


问:
Variables are assigned only locally inside a for loop
I am doing the first Kaggle challenge and I am stupified by this behaviour.

combine consists of two pd.DataFrame, one is the training set the other the test set. I wanted to drop two columns so I created a for loop that iterates over the items in combine.

```<code>for dataset in combine:
    dataset = dataset.drop(['Ticket', 'Cabin'], axis=1)
    print(dataset.columns)
for dataset in combine:
    print(dataset.columns)
</code>```

For some reason, the assignment happens only locally and doing another for loop reveals that the actual data has not changed. The output is as follows.

```<code>
Index(['PassengerId', 'Survived', 'Pclass', 'Name', 'Sex', 'Age', 'SibSp',
       'Parch', 'Fare', 'Embarked'],
      dtype='object')
Index(['PassengerId', 'Pclass', 'Name', 'Sex', 'Age', 'SibSp', 'Parch', 'Fare',
       'Embarked'],
      dtype='object')
Index(['PassengerId', 'Survived', 'Pclass', 'Name', 'Sex', 'Age', 'SibSp',
       'Parch', 'Ticket', 'Fare', 'Cabin', 'Embarked'],
      dtype='object')
Index(['PassengerId', 'Pclass', 'Name', 'Sex', 'Age', 'SibSp', 'Parch',
       'Ticket', 'Fare', 'Cabin', 'Embarked'],
      dtype='object')
</code>```

As you can see, in the second for loop the columns are back. Where is the problem? Am I misunderstanding how the for loop works in Python?

edit:

@kaya3 It is not the case with pandas.Series.map

```<code>for dataset in combine:
    dataset['Name'] = dataset['Name'].map(name_map)
    dataset['Name'] = dataset['Name'].fillna(0)
</code>```

This code changes the original dataFrames in combine. The docs say that it returns series (not None). How do I tell whether the function will mutate the value?

答:
When you are in the loop dataset is a copy of the DataFrame in combine, so when you change dataset you aren't changing the actual DataFrame in combine, just the copy. To change the actual  DataFrame in the list try something like this:

```<code>for ii in range(len(combine)):
    combine[ii] = combine[ii].drop(['Ticket', 'Cabin'], axis=1)
</code>```

Now you are changing the variable in the list and not just the copy.

Body:
I am doing the first Kaggle challenge and I am stupified by this behaviour.

combine consists of two pd.DataFrame, one is the training set the other the test set. I wanted to drop two columns so I created a for loop that iterates over the items in combine.

for dataset in combine:
    dataset = dataset.drop(['Ticket', 'Cabin'], axis=1)
    print(dataset.columns)
for dataset in combine:
    print(dataset.columns)

For some reason, the assignment happens only locally and doing another for loop reveals that the actual data has not changed. The output is as follows.

Index(['PassengerId', 'Survived', 'Pclass', 'Name', 'Sex', 'Age', 'SibSp',
       'Parch', 'Fare', 'Embarked'],
      dtype='object')
Index(['PassengerId', 'Pclass', 'Name', 'Sex', 'Age', 'SibSp', 'Parch', 'Fare',
       'Embarked'],
      dtype='object')
Index(['PassengerId', 'Survived', 'Pclass', 'Name', 'Sex', 'Age', 'SibSp',
       'Parch', 'Ticket', 'Fare', 'Cabin', 'Embarked'],
      dtype='object')
Index(['PassengerId', 'Pclass', 'Name', 'Sex', 'Age', 'SibSp', 'Parch',
       'Ticket', 'Fare', 'Cabin', 'Embarked'],
      dtype='object')

As you can see, in the second for loop the columns are back. Where is the problem? Am I misunderstanding how the for loop works in Python?

edit:

@kaya3 It is not the case with pandas.Series.map

for dataset in combine:
    dataset['Name'] = dataset['Name'].map(name_map)
    dataset['Name'] = dataset['Name'].fillna(0)

This code changes the original dataFrames in combine. The docs say that it returns series (not None). How do I tell whether the function will mutate the value?

Body:
When you are in the loop dataset is a copy of the DataFrame in combine, so when you change dataset you aren't changing the actual DataFrame in combine, just the copy. To change the actual  DataFrame in the list try something like this:

for ii in range(len(combine)):
    combine[ii] = combine[ii].drop(['Ticket', 'Cabin'], axis=1)

Now you are changing the variable in the list and not just the copy.


问:
the behavior of the UICollectionViewFlowLayout is not defined, because the cell width is greater than collectionView width

2015-08-18 16:07:51.523 Example[16070:269647] the behavior of the
UICollectionViewFlowLayout is not defined because: 2015-08-18
16:07:51.523

Example[16070:269647] the item width must be less than
the width of the UICollectionView minus the section insets left and
right values, minus the content insets left and right values.

2015-08-18 16:07:51.524 Example[16070:269647] The relevant
UICollectionViewFlowLayout instance is <UICollectionViewFlowLayout:
0x7f24d670>, and it is attached to <UICollectionView: 0x7b377200;
frame = (0 0; 768 1024); clipsToBounds = YES; autoresize = W+H;
gestureRecognizers = <NSArray: 0x7f24ce30>; animations = {
position=<CABasicAnimation: 0x7f279d60>;
bounds.origin=<CABasicAnimation: 0x7f279430>;
bounds.size=<CABasicAnimation: 0x7f279480>; }; layer = <CALayer:
0x7aec9cf0>; contentOffset: {0, 0}; contentSize: {1024, 770}>
collection view layout: <UICollectionViewFlowLayout: 0x7f24d670>.
2015-08-18 16:07:51.524 Example[16070:269647] Make a symbolic
breakpoint at UICollectionViewFlowLayoutBreakForInvalidSizes to catch
this in the debugger.

That is what I get and what I do

```<code>func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
        return CGSizeMake(self.collectionView!.frame.size.width - 20, 66)
    }
</code>```

I rotate from landscape to portrait then the console shows this error message only in iOS 9 if anyone knows what happens and if there is a fix for this?

答: select collectionview in storyboard go to size inspector change estimate size to none</p>

Body:
2015-08-18 16:07:51.523 Example[16070:269647] the behavior of the
UICollectionViewFlowLayout is not defined because: 2015-08-18
16:07:51.523

Example[16070:269647] the item width must be less than
the width of the UICollectionView minus the section insets left and
right values, minus the content insets left and right values.

2015-08-18 16:07:51.524 Example[16070:269647] The relevant
UICollectionViewFlowLayout instance is <UICollectionViewFlowLayout:
0x7f24d670>, and it is attached to <UICollectionView: 0x7b377200;
frame = (0 0; 768 1024); clipsToBounds = YES; autoresize = W+H;
gestureRecognizers = <NSArray: 0x7f24ce30>; animations = {
position=<CABasicAnimation: 0x7f279d60>;
bounds.origin=<CABasicAnimation: 0x7f279430>;
bounds.size=<CABasicAnimation: 0x7f279480>; }; layer = <CALayer:
0x7aec9cf0>; contentOffset: {0, 0}; contentSize: {1024, 770}>
collection view layout: <UICollectionViewFlowLayout: 0x7f24d670>.
2015-08-18 16:07:51.524 Example[16070:269647] Make a symbolic
breakpoint at UICollectionViewFlowLayoutBreakForInvalidSizes to catch
this in the debugger.

That is what I get and what I do

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
        return CGSizeMake(self.collectionView!.frame.size.width - 20, 66)
    }

I rotate from landscape to portrait then the console shows this error message only in iOS 9 if anyone knows what happens and if there is a fix for this?


问:
Environment.getExternalStoragePublicDirectory() in Android 10
how can I get

/storage/emulated/0/Download
```
<p>in android 10</p>
<p>this method:</p>
<pre class="lang-java prettyprint-override"><code>Environment.getExternalStoragePublicDirectory()
</code>```

is deprecated is there an alternative way to get or can I use
hardcoded path or is this not recommended?

答:
See answer in https://stackoverflow.com/a/59873203/2373819 you will not by default to be able to use file paths outside of you App's private directories, you need to use Storage Access Framework

The blog https://commonsware.com/blog/2020/01/11/scoped-storage-stories-diabolical-details-downloads.html has some good details on Download's

With Download manager you don't have to precheck that it exist's just try and download it and then handle the status result that it failed because it already exists.

Body:
how can I get

/storage/emulated/0/Download

in android 10

this method:

Environment.getExternalStoragePublicDirectory()

is deprecated is there an alternative way to get or can I use
hardcoded path or is this not recommended?


问:
why Spring social facebook -2.0.3 using deprecated graph api version 2.5 which is deprecated
We are using spring-social-facebook-2.0.3 latest jar in production environment.

In April 2018 graph api v2.5 is going to shut down. But the spring-social-facebook-2.0.3 latest jar is still using this deprecated graph API internally.

Anyone has any knowledge,

is Spring Team going to release new version of spring-social-facebook till next month (i.e April 2018)?

答:
That project is obselete. They announced the end of life in 2018 to be effective in 2019:
https://spring.io/blog/2018/07/03/spring-social-end-of-life-announcement

They recommand to simply use Spring Security instead.


问:
How can I create a string from just the first line of my UITextView?
I am making a UITextView which is similar to notes.app, where the first line of the textView is used as the title. I need to create a new string which contains only the first line of text. So far I've come up with this:

```<code>NSRange startRange = NSMakeRange(0, 1);
NSRange titleRange = [noteTextView.text lineRangeForRange:startRange];
NSString *titleString = [noteTextView.text substringToIndex:titleRange.length];
NSLog(@"The title is: %@", titleString);
</code>```

The only problem with this is that it relies on the user pressing Return. I've also tried using a loop to find the number of characters in the first line:

```<code>CGSize lineSize = [noteTextView.text sizeWithFont:noteTextView.font
                                constrainedToSize:noteTextView.frame.size
                                    lineBreakMode:UILineBreakModeWordWrap];
int textLength =1;

while ((lineSize.width < noteTextView.frame.size.width) &&
       ([[noteTextView.text substringToIndex:textLength] length] < [noteTextView.text length]))
{
    lineSize = [[noteTextView.text substringToIndex:textLength] sizeWithFont:noteTextView.font
                                                           constrainedToSize:noteTextView.frame.size
                                                               lineBreakMode:UILineBreakModeWordWrap];
    textLength = textLength+1;
}

NSLog(@"Length is %i", textLength);
</code>```

But I've got this wrong somewhere - it returns the total number of characters, instead of the number on the first line.

Does anyone know an easier/better way of doing this?

答:
There is probably a much better way with CoreText, but I'll throw this out there just because it came to mind off the top of my head.

You could add characters one by one to an NSMutableString *title while

```<code>[title sizeWithFont:noteTextView.font].width < noteTextView.frame.size.width
</code>```

then drop the last one, obviously doing the necessary bounds checking along the way and dropping the last added character if necessary.

But sizeWithFont is sloooooow. So if you're doing this often you might want to consider another definition of 'title' - say, at first word break after 20 chars.

But again, CoreText might yield more possibilities.

Body:
I am making a UITextView which is similar to notes.app, where the first line of the textView is used as the title. I need to create a new string which contains only the first line of text. So far I've come up with this:

NSRange startRange = NSMakeRange(0, 1);
NSRange titleRange = [noteTextView.text lineRangeForRange:startRange];
NSString *titleString = [noteTextView.text substringToIndex:titleRange.length];
NSLog(@"The title is: %@", titleString);

The only problem with this is that it relies on the user pressing Return. I've also tried using a loop to find the number of characters in the first line:

CGSize lineSize = [noteTextView.text sizeWithFont:noteTextView.font
                                constrainedToSize:noteTextView.frame.size
                                    lineBreakMode:UILineBreakModeWordWrap];
int textLength =1;

while ((lineSize.width < noteTextView.frame.size.width) &&
       ([[noteTextView.text substringToIndex:textLength] length] < [noteTextView.text length]))
{
    lineSize = [[noteTextView.text substringToIndex:textLength] sizeWithFont:noteTextView.font
                                                           constrainedToSize:noteTextView.frame.size
                                                               lineBreakMode:UILineBreakModeWordWrap];
    textLength = textLength+1;
}

NSLog(@"Length is %i", textLength);

But I've got this wrong somewhere - it returns the total number of characters, instead of the number on the first line.

Does anyone know an easier/better way of doing this?

Body:
There is probably a much better way with CoreText, but I'll throw this out there just because it came to mind off the top of my head.

You could add characters one by one to an NSMutableString *title while

[title sizeWithFont:noteTextView.font].width < noteTextView.frame.size.width

then drop the last one, obviously doing the necessary bounds checking along the way and dropping the last added character if necessary.

But sizeWithFont is sloooooow. So if you're doing this often you might want to consider another definition of 'title' - say, at first word break after 20 chars.

But again, CoreText might yield more possibilities.