问:
Kubernetes repeatedly pull image and stay stuck at containercreating
I'm trying to create a Single-Instance Stateful Application along the lines of https://kubernetes.io/docs/tasks/run-application/run-single-instance-stateful-application/, with the exception that I would like to use an Oracle database.

I run W10 and use Minikube to set up the cluster, Hyper-V as the driver and I also created a Virtual switch for Minikube.

I edited the deployment YAML accordingly to use Oracle DB image and ports, as well as added a pull secret for Docker Hub (as Oracle wants you to log in to pull the inmage).

The final YAML:

```<code>apiVersion: v1
kind: Service
metadata:
  name: orcldb
spec:
  ports:
  - port: 1521
    name: sqlnet
  - port: 5500
    name: oraclexml
  selector:
    app: orcldb
  clusterIP: None
---
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: orcldb-pv-claim
spec:
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      storage: 5Gi
---
apiVersion: apps/v1beta2
kind: Deployment
metadata:
  name: orcldb
spec:
  selector:
    matchLabels:
      app: orcldb
  strategy:
    type: Recreate
  template:
    metadata:
      labels:
        app: orcldb
    spec:
      containers:
      - image: store/oracle/database-enterprise:12.2.0.1
        name: orcldb
        ports:
        - containerPort: 1521
          name: sqlnet
        - containerPort: 5500
          name: oraclexml
        volumeMounts:
        - name: orcldb-persistent-storage
          mountPath: /var/lib/orcldb
      imagePullSecrets:
      - name: dockerhubkey
      volumes:
      - name: orcldb-persistent-storage
        persistentVolumeClaim:
          claimName: orcldb-pv-claim
</code>```

So after I run kubectl create -f deployment.yaml, everything is created accordingly:

```<code>service "orcldb" created
persistentvolumeclaim "orcldb-pv-claim" created
deployment "orcldb" created
</code>```

But then, if I run kubectl describe pods orcldb, I see this in the events:

```<code>Type     Reason                 Age              From               Message
  ----     ------                 ----             ----               -------
  Warning  FailedScheduling       1h (x2 over 1h)  default-scheduler  PersistentVolumeClaim is not bound: "orcldb-pv-claim"
  Normal   Scheduled              1h               default-scheduler  Successfully assigned orcldb-7d96df68c8-bjwql to minikube
  Normal   SuccessfulMountVolume  1h               kubelet, minikube  MountVolume.SetUp succeeded for volume "pvc-c91fd4a0-c3da-11e7-9300-00155d050c0a"
  Normal   SuccessfulMountVolume  1h               kubelet, minikube  MountVolume.SetUp succeeded for volume "default-token-rszmg"
  Normal   Pulling                1h               kubelet, minikube  pulling image "store/oracle/database-enterprise:12.2.0.1"
  Normal   SuccessfulMountVolume  1h               kubelet, minikube  MountVolume.SetUp succeeded for volume "pvc-c91fd4a0-c3da-11e7-9300-00155d050c0a"
  Normal   SuccessfulMountVolume  1h               kubelet, minikube  MountVolume.SetUp succeeded for volume "default-token-rszmg"
  Normal   Pulling                1h               kubelet, minikube  pulling image "store/oracle/database-enterprise:12.2.0.1"
  Normal   SuccessfulMountVolume  43m              kubelet, minikube  MountVolume.SetUp succeeded for volume "pvc-c91fd4a0-c3da-11e7-9300-00155d050c0a"
  Normal   SuccessfulMountVolume  43m              kubelet, minikube  MountVolume.SetUp succeeded for volume "default-token-rszmg"
  Normal   Pulling                43m              kubelet, minikube  pulling image "store/oracle/database-enterprise:12.2.0.1"
  Normal   SuccessfulMountVolume  32m              kubelet, minikube  MountVolume.SetUp succeeded for volume "pvc-c91fd4a0-c3da-11e7-9300-00155d050c0a"
  Normal   SuccessfulMountVolume  32m              kubelet, minikube  MountVolume.SetUp succeeded for volume "default-token-rszmg"
  Normal   Pulling                32m              kubelet, minikube  pulling image "store/oracle/database-enterprise:12.2.0.1"
</code>```

Also, the minikube cluster sometimes stops (?) / refuses connection, I usually restart minikube after that, but once I left it be and it came back up afte a while (with the repeating pulling process still going on).

I haven't been able to find anyone facing this kind of issue, so I would greatly appreciate any insigh as to why this might be happening.

Part of the minikube logs with errors about disk:

```<code>Nov 07 18:37:22 minikube localkube[16252]: E1107 18:37:22.727122   16252 fsHandler.go:121] failed to collect filesystem stats - rootDiskErr: du command failed on /var/lib/docker/overlay2/611dbda511b2771528eff890891445fe89fdd171e6e1e944596b82b5a031d4c6 with output stdout: , stderr: du: cannot access '/var/lib/docker/overlay2/611dbda511b2771528eff890891445fe89fdd171e6e1e944596b82b5a031d4c6': No such file or directory
Nov 07 18:37:22 minikube localkube[16252]:  - exit status 1, rootInodeErr: cmd [find /var/lib/docker/overlay2/611dbda511b2771528eff890891445fe89fdd171e6e1e944596b82b5a031d4c6 -xdev -printf .] failed. stderr: find: '/var/lib/docker/overlay2/611dbda511b2771528eff890891445fe89fdd171e6e1e944596b82b5a031d4c6': No such file or directory
Nov 07 18:37:22 minikube localkube[16252]: ; err: exit status 1, extraDiskErr: du command failed on /var/lib/docker/containers/97fc2e9f49de23415fe6494bf3684672aeb1213930de02314b1f2ce411f4dc6a with output stdout: , stderr: du: cannot access '/var/lib/docker/containers/97fc2e9f49de23415fe6494bf3684672aeb1213930de02314b1f2ce411f4dc6a': No such file or directory
</code>```

答:
I moved away from the huge official images by Oracle and used a custom made image of the Oracle Express 11g database. The image is now pulled and container started without any problems.

Also, the issue where Minikube would stop responding after a while was solved by disabling dynamic memory in Hyper-V, as described in this github issue.

Body:
I'm trying to create a Single-Instance Stateful Application along the lines of https://kubernetes.io/docs/tasks/run-application/run-single-instance-stateful-application/, with the exception that I would like to use an Oracle database.

I run W10 and use Minikube to set up the cluster, Hyper-V as the driver and I also created a Virtual switch for Minikube.

I edited the deployment YAML accordingly to use Oracle DB image and ports, as well as added a pull secret for Docker Hub (as Oracle wants you to log in to pull the inmage).

The final YAML:

apiVersion: v1
kind: Service
metadata:
  name: orcldb
spec:
  ports:
  - port: 1521
    name: sqlnet
  - port: 5500
    name: oraclexml
  selector:
    app: orcldb
  clusterIP: None
---
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: orcldb-pv-claim
spec:
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      storage: 5Gi
---
apiVersion: apps/v1beta2
kind: Deployment
metadata:
  name: orcldb
spec:
  selector:
    matchLabels:
      app: orcldb
  strategy:
    type: Recreate
  template:
    metadata:
      labels:
        app: orcldb
    spec:
      containers:
      - image: store/oracle/database-enterprise:12.2.0.1
        name: orcldb
        ports:
        - containerPort: 1521
          name: sqlnet
        - containerPort: 5500
          name: oraclexml
        volumeMounts:
        - name: orcldb-persistent-storage
          mountPath: /var/lib/orcldb
      imagePullSecrets:
      - name: dockerhubkey
      volumes:
      - name: orcldb-persistent-storage
        persistentVolumeClaim:
          claimName: orcldb-pv-claim

So after I run kubectl create -f deployment.yaml, everything is created accordingly:

service "orcldb" created
persistentvolumeclaim "orcldb-pv-claim" created
deployment "orcldb" created

But then, if I run kubectl describe pods orcldb, I see this in the events:

Type     Reason                 Age              From               Message
  ----     ------                 ----             ----               -------
  Warning  FailedScheduling       1h (x2 over 1h)  default-scheduler  PersistentVolumeClaim is not bound: "orcldb-pv-claim"
  Normal   Scheduled              1h               default-scheduler  Successfully assigned orcldb-7d96df68c8-bjwql to minikube
  Normal   SuccessfulMountVolume  1h               kubelet, minikube  MountVolume.SetUp succeeded for volume "pvc-c91fd4a0-c3da-11e7-9300-00155d050c0a"
  Normal   SuccessfulMountVolume  1h               kubelet, minikube  MountVolume.SetUp succeeded for volume "default-token-rszmg"
  Normal   Pulling                1h               kubelet, minikube  pulling image "store/oracle/database-enterprise:12.2.0.1"
  Normal   SuccessfulMountVolume  1h               kubelet, minikube  MountVolume.SetUp succeeded for volume "pvc-c91fd4a0-c3da-11e7-9300-00155d050c0a"
  Normal   SuccessfulMountVolume  1h               kubelet, minikube  MountVolume.SetUp succeeded for volume "default-token-rszmg"
  Normal   Pulling                1h               kubelet, minikube  pulling image "store/oracle/database-enterprise:12.2.0.1"
  Normal   SuccessfulMountVolume  43m              kubelet, minikube  MountVolume.SetUp succeeded for volume "pvc-c91fd4a0-c3da-11e7-9300-00155d050c0a"
  Normal   SuccessfulMountVolume  43m              kubelet, minikube  MountVolume.SetUp succeeded for volume "default-token-rszmg"
  Normal   Pulling                43m              kubelet, minikube  pulling image "store/oracle/database-enterprise:12.2.0.1"
  Normal   SuccessfulMountVolume  32m              kubelet, minikube  MountVolume.SetUp succeeded for volume "pvc-c91fd4a0-c3da-11e7-9300-00155d050c0a"
  Normal   SuccessfulMountVolume  32m              kubelet, minikube  MountVolume.SetUp succeeded for volume "default-token-rszmg"
  Normal   Pulling                32m              kubelet, minikube  pulling image "store/oracle/database-enterprise:12.2.0.1"

Also, the minikube cluster sometimes stops (?) / refuses connection, I usually restart minikube after that, but once I left it be and it came back up afte a while (with the repeating pulling process still going on).

I haven't been able to find anyone facing this kind of issue, so I would greatly appreciate any insigh as to why this might be happening.

Part of the minikube logs with errors about disk:

Nov 07 18:37:22 minikube localkube[16252]: E1107 18:37:22.727122   16252 fsHandler.go:121] failed to collect filesystem stats - rootDiskErr: du command failed on /var/lib/docker/overlay2/611dbda511b2771528eff890891445fe89fdd171e6e1e944596b82b5a031d4c6 with output stdout: , stderr: du: cannot access '/var/lib/docker/overlay2/611dbda511b2771528eff890891445fe89fdd171e6e1e944596b82b5a031d4c6': No such file or directory
Nov 07 18:37:22 minikube localkube[16252]:  - exit status 1, rootInodeErr: cmd [find /var/lib/docker/overlay2/611dbda511b2771528eff890891445fe89fdd171e6e1e944596b82b5a031d4c6 -xdev -printf .] failed. stderr: find: '/var/lib/docker/overlay2/611dbda511b2771528eff890891445fe89fdd171e6e1e944596b82b5a031d4c6': No such file or directory
Nov 07 18:37:22 minikube localkube[16252]: ; err: exit status 1, extraDiskErr: du command failed on /var/lib/docker/containers/97fc2e9f49de23415fe6494bf3684672aeb1213930de02314b1f2ce411f4dc6a with output stdout: , stderr: du: cannot access '/var/lib/docker/containers/97fc2e9f49de23415fe6494bf3684672aeb1213930de02314b1f2ce411f4dc6a': No such file or directory


来源: stackexchange

问:
Clone Node true only one level
I want to clone a Node with only level 1 of children, so no children of children.

```<code><div data-a>
 <div> data-a1>
  <div data-a11>
   <p> fdsafdsafds</p>
  </div>
 </div>
</div>
</code>```

If I have the last level as target

target.parentNode.parentNode.cloneNode(true) will clone all levels, I want data-a to be cloned including data-a1 but data-a1 no have no children.

It is possible to remove/add children cloned or not, bases on depth level or their attributes(clone the parent with only children that have or not a specified attribute) ?

I thing based on attributes if I will have something with more depth levels, instead just parentNode.parentNode using recursion.

答:
Just try to remove the innerHTML of the first children

```<code>var dupeNode = target.parentNode.parentNode.cloneNode(true);
dupeNode.children[0].innerHTML = "";
</code>```

Demo

var target = document.querySelector( "p" );
var dupeNode = target.parentNode.parentNode.parentNode.cloneNode(true);
dupeNode.children[0].innerHTML = "";
//console.log(dupeNode.outerHTML);
document.querySelector( "#container" ).appendChild( dupeNode );```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="container">
  <div data-a=""> data-a level text to be cloned
    <div data-a1="">
      <div data-a11="">
        <p> fdsafdsafds</p>
      </div>
    </div>
  </div>
</div></code>```

ContentLicense: CC BY-SA 3.0

Title: Clone Node true only one level

Body:
I want to clone a Node with only level 1 of children, so no children of children.

 data-a1>

 fdsafdsafds

If I have the last level as target

target.parentNode.parentNode.cloneNode(true) will clone all levels, I want data-a to be cloned including data-a1 but data-a1 no have no children.

It is possible to remove/add children cloned or not, bases on depth level or their attributes(clone the parent with only children that have or not a specified attribute) ?

I thing based on attributes if I will have something with more depth levels, instead just parentNode.parentNode using recursion.

Body:
Just try to remove the innerHTML of the first children

var dupeNode = target.parentNode.parentNode.cloneNode(true);
dupeNode.children[0].innerHTML = "";

Demo

var target = document.querySelector( "p" );
var dupeNode = target.parentNode.parentNode.parentNode.cloneNode(true);
dupeNode.children[0].innerHTML = "";
//console.log(dupeNode.outerHTML);
document.querySelector( "#container" ).appendChild( dupeNode );

<div id="container">
  <div data-a=""> data-a level text to be cloned
    <div data-a1="">
      <div data-a11="">
        <p> fdsafdsafds</p>
      </div>
    </div>
  </div>
</div>


问:
Electron - Resize Window from renderer process
I am working on an Electron app and as part of the interface I want to increase the size of the window once something has happened (I have bound this to a button for now) so I can display additional data. I have attempted to do this with the following code that is activated on a onclick=resize():

```<code>require('./renderer.js');

let remote = require('electron').remote;
function resize() {
    let win = remote.getCurrentWindow().setBounds({
        height: 1000
    });
}
</code>```

However, I am getting the following error in the window/browser console:

```<code>Uncaught Error: Could not call remote function 'setBounds'. Check that the function signature is correct. Underlying error: Error processing argument at index 0, conversion failure from #<Object>
Error: Could not call remote function 'setBounds'. Check that the function signature is correct. Underlying error: Error processing argument at index 0, conversion failure from #<Object>
    at callFunction (C:\Users\Thomas\AppData\Roaming\npm\node_modules\electron\dist\resources\electron.asar\browser\rpc-server.js:257:11)
    at EventEmitter.<anonymous> (C:\Users\Thomas\AppData\Roaming\npm\node_modules\electron\dist\resources\electron.asar\browser\rpc-server.js:357:5)
    at emitMany (events.js:127:13)
    at EventEmitter.emit (events.js:204:7)
    at WebContents.<anonymous> (C:\Users\Thomas\AppData\Roaming\npm\node_modules\electron\dist\resources\electron.asar\browser\api\web-contents.js:256:13)
    at emitTwo (events.js:106:13)
    at WebContents.emit (events.js:194:7)
    at callFunction (C:\Users\Thomas\AppData\Roaming\npm\node_modules\electron\dist\resources\electron.asar\browser\rpc-server.js:257:11)
    at EventEmitter.<anonymous> (C:\Users\Thomas\AppData\Roaming\npm\node_modules\electron\dist\resources\electron.asar\browser\rpc-server.js:357:5)
    at emitMany (events.js:127:13)
    at EventEmitter.emit (events.js:204:7)
    at WebContents.<anonymous> (C:\Users\Thomas\AppData\Roaming\npm\node_modules\electron\dist\resources\electron.asar\browser\api\web-contents.js:256:13)
    at emitTwo (events.js:106:13)
    at WebContents.emit (events.js:194:7)
    at metaToValue (C:\Users\Thomas\AppData\Roaming\npm\node_modules\electron\dist\resources\electron.asar\renderer\api\remote.js:234:13)
    at Object.remoteMemberFunction (C:\Users\Thomas\AppData\Roaming\npm\node_modules\electron\dist\resources\electron.asar\renderer\api\remote.js:118:18)
    at resize (file:///D:/Documents/Development/Projects/ShortenMeURL/V1/index.html:41:45)
    at HTMLButtonElement.onclick (file:///D:/Documents/Development/Projects/ShortenMeURL/V1/index.html:22:86)
</code>```

Any suggestions on how I can fix this?

答:
Just use plain old javascript from the renderer, I would not add an unnecessary messaging between main and renderer process if it is just a resize ;)</p>

```<code>window.resizeTo(1000,900);
</code>```

Body:
I am working on an Electron app and as part of the interface I want to increase the size of the window once something has happened (I have bound this to a button for now) so I can display additional data. I have attempted to do this with the following code that is activated on a onclick=resize():

require('./renderer.js');

let remote = require('electron').remote;
function resize() {
    let win = remote.getCurrentWindow().setBounds({
        height: 1000
    });
}

However, I am getting the following error in the window/browser console:

Uncaught Error: Could not call remote function 'setBounds'. Check that the function signature is correct. Underlying error: Error processing argument at index 0, conversion failure from #<Object>
Error: Could not call remote function 'setBounds'. Check that the function signature is correct. Underlying error: Error processing argument at index 0, conversion failure from #<Object>
    at callFunction (C:\Users\Thomas\AppData\Roaming\npm\node_modules\electron\dist\resources\electron.asar\browser\rpc-server.js:257:11)
    at EventEmitter.<anonymous> (C:\Users\Thomas\AppData\Roaming\npm\node_modules\electron\dist\resources\electron.asar\browser\rpc-server.js:357:5)
    at emitMany (events.js:127:13)
    at EventEmitter.emit (events.js:204:7)
    at WebContents.<anonymous> (C:\Users\Thomas\AppData\Roaming\npm\node_modules\electron\dist\resources\electron.asar\browser\api\web-contents.js:256:13)
    at emitTwo (events.js:106:13)
    at WebContents.emit (events.js:194:7)
    at callFunction (C:\Users\Thomas\AppData\Roaming\npm\node_modules\electron\dist\resources\electron.asar\browser\rpc-server.js:257:11)
    at EventEmitter.<anonymous> (C:\Users\Thomas\AppData\Roaming\npm\node_modules\electron\dist\resources\electron.asar\browser\rpc-server.js:357:5)
    at emitMany (events.js:127:13)
    at EventEmitter.emit (events.js:204:7)
    at WebContents.<anonymous> (C:\Users\Thomas\AppData\Roaming\npm\node_modules\electron\dist\resources\electron.asar\browser\api\web-contents.js:256:13)
    at emitTwo (events.js:106:13)
    at WebContents.emit (events.js:194:7)
    at metaToValue (C:\Users\Thomas\AppData\Roaming\npm\node_modules\electron\dist\resources\electron.asar\renderer\api\remote.js:234:13)
    at Object.remoteMemberFunction (C:\Users\Thomas\AppData\Roaming\npm\node_modules\electron\dist\resources\electron.asar\renderer\api\remote.js:118:18)
    at resize (file:///D:/Documents/Development/Projects/ShortenMeURL/V1/index.html:41:45)
    at HTMLButtonElement.onclick (file:///D:/Documents/Development/Projects/ShortenMeURL/V1/index.html:22:86)

Any suggestions on how I can fix this?

Body:
Just use plain old javascript from the renderer, I would not add an unnecessary messaging between main and renderer process if it is just a resize ;)

window.resizeTo(1000,900);


问:
Column wise correspondence values in data frame
Given a dataframe, with Age as basis, I need to get the correspondence values from other columns (Sport, Mode). Could someone help with R/python code?

.

In fact, it will be helpful if I could get for age 15, 2 baseball with 2 play; age 19 1 golf and 1 play.

 the output should look like the below with Age as base variable

Further on with Sport as base variable, the mode should have a similar summary. Thank you

答:
```<code>df = data.frame(Age = c(15,15,16,17,18,18,19,20),
                Sport = c("Baseball","Baseball","Baseball","Baseball","Baseball","Golf","Golf","Golf"),
                Mode = c("Play","Play","Play","Watch","Watch","Play","Play","Watch"),
                stringsAsFactors = F)

library(dplyr)
library(tidyr)

df %>%
  count(Age, Sport) %>%
  spread(Sport, n, fill = 0)

# # A tibble: 6 x 3
#     Age Baseball  Golf
# * <dbl>    <dbl> <dbl>
# 1    15        2     0
# 2    16        1     0
# 3    17        1     0
# 4    18        1     1
# 5    19        0     1
# 6    20        0     1

df %>%
  count(Age, Mode) %>%
  spread(Mode, n, fill = 0)

# # A tibble: 6 x 3
#     Age  Play Watch
# * <dbl> <dbl> <dbl>
# 1    15     2     0
# 2    16     1     0
# 3    17     0     1
# 4    18     1     1
# 5    19     1     0
# 6    20     0     1
</code>```

If you want to produce a single output you can use this:

```<code>df = data.frame(Age = c(15,15,16,17,18,18,19,20),
                Sport = c("Baseball","Baseball","Baseball","Baseball","Baseball","Golf","Golf","Golf"),
                Mode = c("Play","Play","Play","Watch","Watch","Play","Play","Watch"),
                stringsAsFactors = F)

library(dplyr)
library(tidyr)
library(purrr)

# function that reshapes data based on a column name
# (uses Age column as an identifier/key)
f = function(x) {
df %>%
  group_by_("Age",x) %>%
  summarise(n = n()) %>%
  spread_(x, "n", fill = 0) %>%
  ungroup()
}

names(df)[names(df) != "Age"] %>%   # get all column names (different than Age)
  map(f) %>%                        # apply function to each column name
  reduce(left_join, by="Age")       # join datasets sequentially

# # A tibble: 6 x 5
#     Age Baseball  Golf  Play Watch
#   <dbl>    <dbl> <dbl> <dbl> <dbl>
# 1    15        2     0     2     0
# 2    16        1     0     1     0
# 3    17        1     0     0     1
# 4    18        1     1     1     1
# 5    19        0     1     1     0
# 6    20        0     1     0     1
</code>```

Body:
df = data.frame(Age = c(15,15,16,17,18,18,19,20),
                Sport = c("Baseball","Baseball","Baseball","Baseball","Baseball","Golf","Golf","Golf"),
                Mode = c("Play","Play","Play","Watch","Watch","Play","Play","Watch"),
                stringsAsFactors = F)

library(dplyr)
library(tidyr)

df %>%
  count(Age, Sport) %>%
  spread(Sport, n, fill = 0)

# # A tibble: 6 x 3
#     Age Baseball  Golf
# * <dbl>    <dbl> <dbl>
# 1    15        2     0
# 2    16        1     0
# 3    17        1     0
# 4    18        1     1
# 5    19        0     1
# 6    20        0     1

df %>%
  count(Age, Mode) %>%
  spread(Mode, n, fill = 0)

# # A tibble: 6 x 3
#     Age  Play Watch
# * <dbl> <dbl> <dbl>
# 1    15     2     0
# 2    16     1     0
# 3    17     0     1
# 4    18     1     1
# 5    19     1     0
# 6    20     0     1

If you want to produce a single output you can use this:

df = data.frame(Age = c(15,15,16,17,18,18,19,20),
                Sport = c("Baseball","Baseball","Baseball","Baseball","Baseball","Golf","Golf","Golf"),
                Mode = c("Play","Play","Play","Watch","Watch","Play","Play","Watch"),
                stringsAsFactors = F)

library(dplyr)
library(tidyr)
library(purrr)

# function that reshapes data based on a column name
# (uses Age column as an identifier/key)
f = function(x) {
df %>%
  group_by_("Age",x) %>%
  summarise(n = n()) %>%
  spread_(x, "n", fill = 0) %>%
  ungroup()
}

names(df)[names(df) != "Age"] %>%   # get all column names (different than Age)
  map(f) %>%                        # apply function to each column name
  reduce(left_join, by="Age")       # join datasets sequentially

# # A tibble: 6 x 5
#     Age Baseball  Golf  Play Watch
#   <dbl>    <dbl> <dbl> <dbl> <dbl>
# 1    15        2     0     2     0
# 2    16        1     0     1     0
# 3    17        1     0     0     1
# 4    18        1     1     1     1
# 5    19        0     1     1     0
# 6    20        0     1     0     1


答:
It can be done with a simple pivot_table i.e

```<code>ndf = df[df['Type'].eq('Data')].pivot_table(columns=['Receiver'],values='Retry',
             index=pd.Grouper(key='Index',freq='s'), aggfunc='sum',fill_value=0)

Receiver             R1  R2
Index
1970-01-01 00:00:00   1   0
1970-01-01 00:00:01   0   1
1970-01-01 00:00:02   1   2
1970-01-01 00:00:03   0   1
</code>```

Title: Using pandas' TimeGrouper() to find column counts by intervals of 1 second

Body:
Consider the dataframe "data" indexed by Timestamp as follow:

Index                                Receiver     Type         Retry
1970-01-01 00:00:00.000000000         R1          Data         1
1970-01-01 00:00:00.800000000         R1          Non-Data     1
1970-01-01 00:00:01.000287000         R2          Data         0
1970-01-01 00:00:01.600896000         R2          Data         1
1970-01-01 00:00:02.001388000         R1          Data         1
1970-01-01 00:00:02.004698000         R1          Non-Data     1
1970-01-01 00:00:02.006706000         R2          Data         1
1970-01-01 00:00:02.501351000         R2          Data         1
1970-01-01 00:00:02.810382000         R1          Data         0
1970-01-01 00:00:03.001981000         R1          Data         0
1970-01-01 00:00:03.377116000         R1          Data         0
1970-01-01 00:00:03.701811000         R2          Data         1
1970-01-01 00:00:03.910326000         R2          Data         0
1970-01-01 00:00:03.951355000         R2          Non-Data     1

I want to find all rows where Type is "Data" and Retry equals 1 and then group the index in intervals of 1 second to find counts for each Receiver type.

Desired Output as df2:

Index                        R1   R2
1970-01-01 00:00:00          1    0
1970-01-01 00:00:01          0    1
1970-01-01 00:00:02          1    2
1970-01-01 00:00:03          0    1

Body:
It can be done with a simple pivot_table i.e

ndf = df[df['Type'].eq('Data')].pivot_table(columns=['Receiver'],values='Retry',
             index=pd.Grouper(key='Index',freq='s'), aggfunc='sum',fill_value=0)

Receiver             R1  R2
Index
1970-01-01 00:00:00   1   0
1970-01-01 00:00:01   0   1
1970-01-01 00:00:02   1   2
1970-01-01 00:00:03   0   1


问:
How to set cell height in UITableView?
```<code>override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    let height = self.navigationController?.navigationBar.frame.size.height
    return view.frame.size.height - height!
}
</code>```

I want to change the cell size — I use only one cell.

My purpose is to fit the screen. However, in my case, the cell is scrolled.

I think it is necessary to calculate the safe area. What if I do not have a smaller or larger screen?

答:
Please calculate like below for height, includes safe area code.</p>

```<code>override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    let height = view.bounds.height -  view.safeAreaInsets.top - view.safeAreaInsets.bottom
    return  height!
}
</code>```

Title: How to set cell height in UITableView?

Body:
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    let height = self.navigationController?.navigationBar.frame.size.height
    return view.frame.size.height - height!
}

I want to change the cell size — I use only one cell.

My purpose is to fit the screen. However, in my case, the cell is scrolled.

I think it is necessary to calculate the safe area. What if I do not have a smaller or larger screen?

Body:
Please calculate like below for height, includes safe area code.

override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    let height = view.bounds.height -  view.safeAreaInsets.top - view.safeAreaInsets.bottom
    return  height!
}


问:
Cannot register a build agent in VSTS
I am trying to register a build agent with VSTS by following the instructions here. I created a PAT token in my Security settings and used it to register the agent. I used the following PS command to register the agent:

```<code>PS>.\config.cmd --url 'https://[account].visualstudio.com/' --auth 'PAT' --token '[Token]' --pool '[Pool Name]' --agent '[Agent Name]'
</code>```

I get the following information on the output:

```<code>>> Connect:

Connecting to server ...

>> Register Agent:

Scanning for tool capabilities.
Connecting to the server.
Successfully added the agent
Testing agent connection.
</code>```

But it then gets stuck on this step and never completes. When I look at the agent pool in VSTS I see the new agent, but it's state is 'Offline'.

I looked in the _diag folder and checked the latest log. There is an error there:

```<code>[2017-07-11 12:32:10Z WARN VisualStudioServices] Authentication failed with status code 401.
Date: Tue, 11 Jul 2017 12:32:10 GMT
P3P: CP="CAO DSP COR ADMa DEV CONo TELo CUR PSA PSD TAI IVDo OUR SAMi BUS DEM NAV STA UNI COM INT PHY ONL FIN PUR LOC CNT"
Server: Microsoft-IIS/10.0
WWW-Authenticate: Bearer authorization_uri=https://login.microsoftonline.com/b8f712c7-d223-4cfb-b165-6267fc789086, Basic realm="https://tfsprodweu2.app.visualstudio.com/", TFS-Federated
X-TFS-ProcessId: f4c5d148-0e01-488f-ab27-69c753e38911
Strict-Transport-Security: max-age=31536000; includeSubDomains
ActivityId: b85558aa-d41a-4763-a311-f2498ddb2dc0
X-TFS-Session: 8242b35d-d5e9-4242-8f52-b7c1f14c451c
X-VSS-E2EID: 6494b165-d486-4064-a5fd-92ae7f201867
X-FRAME-OPTIONS: SAMEORIGIN
X-TFS-FedAuthRealm: https://tfsprodweu2.app.visualstudio.com/
X-TFS-FedAuthIssuer: https://rr-ffes.visualstudio.com/
X-VSS-ResourceTenant: b8f712c7-d223-4cfb-b165-6267fc789086
X-TFS-SoapException: %3C%3Fxml%20version%3D%221.0%22%20encoding%3D%22utf-8%22%3F%3E%3Csoap%3AEnvelope%20xmlns%3Asoap%3D%22http%3A%2F%2Fwww.w3.org%2F2003%2F05%2Fsoap-envelope%22%3E%3Csoap%3ABody%3E%3Csoap%3AFault%3E%3Csoap%3ACode%3E%3Csoap%3AValue%3Esoap%3AReceiver%3C%2Fsoap%3AValue%3E%3Csoap%3ASubcode%3E%3Csoap%3AValue%3EUnauthorizedRequestException%3C%2Fsoap%3AValue%3E%3C%2Fsoap%3ASubcode%3E%3C%2Fsoap%3ACode%3E%3Csoap%3AReason%3E%3Csoap%3AText%20xml%3Alang%3D%22en%22%3ETF400813%3A%20Resource%20not%20available%20for%20anonymous%20access.%20Client%20authentication%20required.%3C%2Fsoap%3AText%3E%3C%2Fsoap%3AReason%3E%3C%2Fsoap%3AFault%3E%3C%2Fsoap%3ABody%3E%3C%2Fsoap%3AEnvelope%3E
X-TFS-ServiceError: TF400813%3A%20Resource%20not%20available%20for%20anonymous%20access.%20Client%20authentication%20required.
X-VSS-S2STargetService: 00000002-0000-8888-8000-000000000000/visualstudio.com
X-TFS-FedAuthRedirect: https://app.vssps.visualstudio.com/_signin?realm=rr-ffes.visualstudio.com&reply_to=https%3A%2F%2Frr-ffes.visualstudio.com%2F_apis%2FconnectionData%3FconnectOptions%3D1%26lastChangeId%3D-1%26lastChangeId64%3D-1&redirect=1&context=eyJodCI6MiwiaGlkIjoiNDEzNzE0YzItZWQ2OS00MWRkLWJmMTItNzc0ZTI1ZGEzOTdmIiwicXMiOnt9LCJyciI6IiIsInZoIjoiIiwiY3YiOiIiLCJjcyI6IiJ90#ctx=eyJTaWduSW5Db29raWVEb21haW5zIjpbImh0dHBzOi8vbG9naW4ubWljcm9zb2Z0b25saW5lLmNvbSIsImh0dHBzOi8vbG9naW4ubWljcm9zb2Z0b25saW5lLmNvbSJdfQ2
X-Powered-By: ASP.NET
X-Content-Type-Options: nosniff
</code>```

I am sure I correctly entered the PAT access token, so what is the problem?

答:
I just want to share our story we had the same Exception but my log was different.

[2017-12-04 11:20:37Z WARN VisualStudioServices] Authentication failed
  with status code 401.

And after struggling around we figured out that the ApplicationPools that running the TFS should have administration level to be able to access Certificate Management

Title: Cannot register a build agent in VSTS

Body:
I am trying to register a build agent with VSTS by following the instructions here. I created a PAT token in my Security settings and used it to register the agent. I used the following PS command to register the agent:

PS>.\config.cmd --url 'https://[account].visualstudio.com/' --auth 'PAT' --token '[Token]' --pool '[Pool Name]' --agent '[Agent Name]'

I get the following information on the output:

>> Connect:

Connecting to server ...

>> Register Agent:

Scanning for tool capabilities.
Connecting to the server.
Successfully added the agent
Testing agent connection.

But it then gets stuck on this step and never completes. When I look at the agent pool in VSTS I see the new agent, but it's state is 'Offline'.

I looked in the _diag folder and checked the latest log. There is an error there:

[2017-07-11 12:32:10Z WARN VisualStudioServices] Authentication failed with status code 401.
Date: Tue, 11 Jul 2017 12:32:10 GMT
P3P: CP="CAO DSP COR ADMa DEV CONo TELo CUR PSA PSD TAI IVDo OUR SAMi BUS DEM NAV STA UNI COM INT PHY ONL FIN PUR LOC CNT"
Server: Microsoft-IIS/10.0
WWW-Authenticate: Bearer authorization_uri=https://login.microsoftonline.com/b8f712c7-d223-4cfb-b165-6267fc789086, Basic realm="https://tfsprodweu2.app.visualstudio.com/", TFS-Federated
X-TFS-ProcessId: f4c5d148-0e01-488f-ab27-69c753e38911
Strict-Transport-Security: max-age=31536000; includeSubDomains
ActivityId: b85558aa-d41a-4763-a311-f2498ddb2dc0
X-TFS-Session: 8242b35d-d5e9-4242-8f52-b7c1f14c451c
X-VSS-E2EID: 6494b165-d486-4064-a5fd-92ae7f201867
X-FRAME-OPTIONS: SAMEORIGIN
X-TFS-FedAuthRealm: https://tfsprodweu2.app.visualstudio.com/
X-TFS-FedAuthIssuer: https://rr-ffes.visualstudio.com/
X-VSS-ResourceTenant: b8f712c7-d223-4cfb-b165-6267fc789086
X-TFS-SoapException: %3C%3Fxml%20version%3D%221.0%22%20encoding%3D%22utf-8%22%3F%3E%3Csoap%3AEnvelope%20xmlns%3Asoap%3D%22http%3A%2F%2Fwww.w3.org%2F2003%2F05%2Fsoap-envelope%22%3E%3Csoap%3ABody%3E%3Csoap%3AFault%3E%3Csoap%3ACode%3E%3Csoap%3AValue%3Esoap%3AReceiver%3C%2Fsoap%3AValue%3E%3Csoap%3ASubcode%3E%3Csoap%3AValue%3EUnauthorizedRequestException%3C%2Fsoap%3AValue%3E%3C%2Fsoap%3ASubcode%3E%3C%2Fsoap%3ACode%3E%3Csoap%3AReason%3E%3Csoap%3AText%20xml%3Alang%3D%22en%22%3ETF400813%3A%20Resource%20not%20available%20for%20anonymous%20access.%20Client%20authentication%20required.%3C%2Fsoap%3AText%3E%3C%2Fsoap%3AReason%3E%3C%2Fsoap%3AFault%3E%3C%2Fsoap%3ABody%3E%3C%2Fsoap%3AEnvelope%3E
X-TFS-ServiceError: TF400813%3A%20Resource%20not%20available%20for%20anonymous%20access.%20Client%20authentication%20required.
X-VSS-S2STargetService: 00000002-0000-8888-8000-000000000000/visualstudio.com
X-TFS-FedAuthRedirect: https://app.vssps.visualstudio.com/_signin?realm=rr-ffes.visualstudio.com&reply_to=https%3A%2F%2Frr-ffes.visualstudio.com%2F_apis%2FconnectionData%3FconnectOptions%3D1%26lastChangeId%3D-1%26lastChangeId64%3D-1&redirect=1&context=eyJodCI6MiwiaGlkIjoiNDEzNzE0YzItZWQ2OS00MWRkLWJmMTItNzc0ZTI1ZGEzOTdmIiwicXMiOnt9LCJyciI6IiIsInZoIjoiIiwiY3YiOiIiLCJjcyI6IiJ90#ctx=eyJTaWduSW5Db29raWVEb21haW5zIjpbImh0dHBzOi8vbG9naW4ubWljcm9zb2Z0b25saW5lLmNvbSIsImh0dHBzOi8vbG9naW4ubWljcm9zb2Z0b25saW5lLmNvbSJdfQ2
X-Powered-By: ASP.NET
X-Content-Type-Options: nosniff

I am sure I correctly entered the PAT access token, so what is the problem?


问:
Java exception in Mathematica while trying to access MS Access
I'm trying to make "Wolfram Mathematica" to manipulate a *.accdb file. I already established a connection (to a file with an empty "table1"):

```<code>Needs["DatabaseLink`"]
conn = OpenSQLConnection[]
</code>```

Source: http://reference.wolfram.com/language/DatabaseLink/ref/SQLInsert.html

It works fine. If I make:

```<code>SQLSelect[conn, "table1"]
</code>```

I get

```<code> {}
</code>```

Now I want to create a table with:

```<code>SQLCreateTable[conn,
  SQLTable["TEST"], {SQLColumn["COL1", "DataTypeName" -> "INTEGER"],
   SQLColumn["COL2", "DataTypeName" -> "DOUBLE"]}];
</code>```

I get the exception:

Java::excptn: A Java exception occurred:
  java.lang.NullPointerException    at
  net.ucanaccess.jdbc.UcanaccessPreparedStatement.clearParameters(UcanaccessPreparedStatement.java:214)
    at
  com.wolfram.databaselink.SQLStatementProcessor.processSQLStatement(SQLStatementProcessor.java:311).

Sorry for bad english (but I tried).

Thank you guys!

答:
Sometimes if you "open the same connection" many times Mathematica doesn't understand what to do. Just

```<code>Quit
</code>```

the Kernel and re-establish the connection. SQL will work properly.

Body:
I'm trying to make "Wolfram Mathematica" to manipulate a *.accdb file. I already established a connection (to a file with an empty "table1"):

Needs["DatabaseLink`"]
conn = OpenSQLConnection[]

Source: http://reference.wolfram.com/language/DatabaseLink/ref/SQLInsert.html

It works fine. If I make:

SQLSelect[conn, "table1"]

I get

 {}

Now I want to create a table with:

SQLCreateTable[conn,
  SQLTable["TEST"], {SQLColumn["COL1", "DataTypeName" -> "INTEGER"],
   SQLColumn["COL2", "DataTypeName" -> "DOUBLE"]}];

I get the exception:

Java::excptn: A Java exception occurred:
  java.lang.NullPointerException    at
  net.ucanaccess.jdbc.UcanaccessPreparedStatement.clearParameters(UcanaccessPreparedStatement.java:214)
    at
  com.wolfram.databaselink.SQLStatementProcessor.processSQLStatement(SQLStatementProcessor.java:311).

Sorry for bad english (but I tried).

Thank you guys!

Body:
Sometimes if you "open the same connection" many times Mathematica doesn't understand what to do. Just

Quit

the Kernel and re-establish the connection. SQL will work properly.


问:
My posts not updating in my RSS APP
I created an android app to read feed from my blog, but when I added a new post in the blog it is not changing in the app after refresh action.

This is my refresh menu button code, it is working fine but giving the same old data no mater how many times I hit refresh.

```<code>@Override
  public boolean onOptionsItemSelected(MenuItem item) {
    if(item.getItemId()== R.id.menu_refresh) {
        mdialog = new ProgressDialog(this);
        mdialog.setMessage("Loading Content Please Wait...");
        mdialog.show();

        JsonParse();

//I even specified DatasetChanged(); and still it is not working

        itemsAdapter.notifyDataSetChanged();

        mqueue.addRequestFinishedListener(new
        RequestQueue.RequestFinishedListener<String>() {
            @Override
            public void onRequestFinished(Request request) {
                mdialog.dismiss();
            }
        });

    }

    return true;
}
</code>```

This is my Volley JSON Parsing Code

```<code>private void JsonParse() {

String url = "https://api.rss2json.com/v1/api.json?rss_url=http://itzmydarz.blogspot.com/atom.xml";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {

        @Override
        public void onResponse(JSONObject response) {
            try {
                JSONArray jsonArray = response.getJSONArray("items");
                for(int i =0; i<jsonArray.length();i++){
                    JSONObject items = jsonArray.getJSONObject(i);
                    String title = items.getString("title");
                    String date = items.getString("pubDate");
                    String data= items.getString("description");
                   // String imageurl= items.getString("url");
                    webPageItemsList.add(new WebPageItems(data,title,date));

                }

itemsAdapter = new ItemsAdapter(MainActivity.this,webPageItemsList);
                recyclerView.setAdapter(itemsAdapter);

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            error.printStackTrace();
        }
    });

    mqueue.add(request);

}
</code>```

}

答: because your Jsonparse not call that's why</p>

Title: My posts not updating in my RSS APP

Body:
I created an android app to read feed from my blog, but when I added a new post in the blog it is not changing in the app after refresh action.

This is my refresh menu button code, it is working fine but giving the same old data no mater how many times I hit refresh.

@Override
  public boolean onOptionsItemSelected(MenuItem item) {
    if(item.getItemId()== R.id.menu_refresh) {
        mdialog = new ProgressDialog(this);
        mdialog.setMessage("Loading Content Please Wait...");
        mdialog.show();

        JsonParse();

//I even specified DatasetChanged(); and still it is not working

        itemsAdapter.notifyDataSetChanged();

        mqueue.addRequestFinishedListener(new
        RequestQueue.RequestFinishedListener<String>() {
            @Override
            public void onRequestFinished(Request request) {
                mdialog.dismiss();
            }
        });

    }

    return true;
}

This is my Volley JSON Parsing Code

private void JsonParse() {

String url = "https://api.rss2json.com/v1/api.json?rss_url=http://itzmydarz.blogspot.com/atom.xml";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {

        @Override
        public void onResponse(JSONObject response) {
            try {
                JSONArray jsonArray = response.getJSONArray("items");
                for(int i =0; i<jsonArray.length();i++){
                    JSONObject items = jsonArray.getJSONObject(i);
                    String title = items.getString("title");
                    String date = items.getString("pubDate");
                    String data= items.getString("description");
                   // String imageurl= items.getString("url");
                    webPageItemsList.add(new WebPageItems(data,title,date));

                }

itemsAdapter = new ItemsAdapter(MainActivity.this,webPageItemsList);
                recyclerView.setAdapter(itemsAdapter);

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            error.printStackTrace();
        }
    });

    mqueue.add(request);

}

}


问:
how to add default option value from dropdown using mvc?
In dropdown am fetching the value from the database i't is working fine ..i need to add <option value='-1'>Root</option> by manually which is not present in the database.

```<code><div class="col-lg-4">
   <fieldset class="form-group">
    <label class="form-label" for="exampleInput">Domain Name</label>
      @Html.DropDownList("DomainID", null, "--- Select Domain Name ---", new { @class = "select2-arrow" })
       @Html.ValidationMessageFor(model => Model.DomainID, null, new { @style = "color: red" })
    </fieldset>
   </div>
 <div class="col-lg-4">
     <fieldset class="form-group">
       <label class="form-label" for="exampleInput">Parent Module</label>
          <select id="ParentModuleID" class="select2-arrow" name="ParentModuleID"></select>
           @Html.ValidationMessageFor(model => Model.ParentModuleID, null, new { @style = "color: red" })
     </fieldset>
 </div>
</code>```

Jquery:

```<code>$("#DomainID").change(function () {
        var id = $(this).val();
        $("#ParentModuleID").empty();
        $.get("ParentModule_Bind", { DomainID: id }, function (data) {
            var v = "<option>--- Select Domain Name ---</option>";
            $.each(data, function (i, v1) {
                v += "<option value=" + v1.Value + ">" + v1.Text + "</option>";
            });
            $("#ParentModuleID").html(v);

        });
    });
</code>```

in above jquery <option>--- Select Domain Name ---</option> i need to add root with value of -1

```<code>public JsonResult ParentModule_Bind(string DomainID)
        {
            userType type = new userType();
            DataSet ds = type.ParentModule_Bind(DomainID);
            List<SelectListItem> statelist = new List<SelectListItem>();
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                statelist.Add(new SelectListItem { Text = dr["ModuleName"].ToString(), Value = dr["ModuleID"].ToString() });
            }
            return Json(statelist, JsonRequestBehavior.AllowGet);
        }
</code>```

答:
You can either add a line in jQuesry like this

```<code>v += "<option value='-1'>root</option>";
</code>```

or add a line in controller above foreach like this

```<code>statelist.Add(new SelectListItem { Text = "root", Value = "-1" });
</code>```

to achieve the result.

Body:
In dropdown am fetching the value from the database i't is working fine ..i need to add <option value='-1'>Root</option> by manually which is not present in the database.

   <fieldset class="form-group">
    Domain Name
      @Html.DropDownList("DomainID", null, "--- Select Domain Name ---", new { @class = "select2-arrow" })
       @Html.ValidationMessageFor(model => Model.DomainID, null, new { @style = "color: red" })
    </fieldset>

     <fieldset class="form-group">
       Parent Module
          <select id="ParentModuleID" class="select2-arrow" name="ParentModuleID"></select>
           @Html.ValidationMessageFor(model => Model.ParentModuleID, null, new { @style = "color: red" })
     </fieldset>

Jquery:

$("#DomainID").change(function () {
        var id = $(this).val();
        $("#ParentModuleID").empty();
        $.get("ParentModule_Bind", { DomainID: id }, function (data) {
            var v = "<option>--- Select Domain Name ---</option>";
            $.each(data, function (i, v1) {
                v += "<option value=" + v1.Value + ">" + v1.Text + "</option>";
            });
            $("#ParentModuleID").html(v);

        });
    });

in above jquery <option>--- Select Domain Name ---</option> i need to add root with value of -1

public JsonResult ParentModule_Bind(string DomainID)
        {
            userType type = new userType();
            DataSet ds = type.ParentModule_Bind(DomainID);
            List<SelectListItem> statelist = new List<SelectListItem>();
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                statelist.Add(new SelectListItem { Text = dr["ModuleName"].ToString(), Value = dr["ModuleID"].ToString() });
            }
            return Json(statelist, JsonRequestBehavior.AllowGet);
        }

Body:
You can either add a line in jQuesry like this

v += "<option value='-1'>root</option>";

or add a line in controller above foreach like this

statelist.Add(new SelectListItem { Text = "root", Value = "-1" });

to achieve the result.


问:
Spring Security Concurrent Session : failed to make "max-sessions" field configurable
I have a requirement to allow Concurrent-session control in my web app and make configurable field "max-sessions". My configuration looks like:

```<code><security:session-management>
    <security:concurrency-control max-sessions="${maxConcurrentSessionsCount}" session-registry-ref="sessionRegistry" expired-url="/handleInvalidatedSession.gs4tr"/>
</security:session-management>`
</code>```

As you can guess, in "services.properties" file there should be "maxConcurrentSessionsCount" field which clients would set by their will.
But I'm getting next warning in Intelij:

```<code>"attribute 'max-sessions' on element 'security:concurrency-control' is not valid with respect to its type, 'positiveInteger'".
</code>```

I successfully configure many others things, like "token-validity-seconds" and "remember-me-cookie" in "remember-me", etc.
Any idea how to solve a problem? Search couple of days over internet for help, but failed.

EDIT:
In "services.properties" is configured:
"maxConcurrentSessionsCount=2"

On start application, it throws next error:

```<code>No, it doesn't. It throws next ERROR on starting app:
</code>```

017-09-14 15:46:47,724 ERROR [org.gs4tr.projectdirector.service.context.ContextLoaderListener][localhost-startStop-1][user:] -
org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 75 in XML document from class path resource [org/gs4tr/foundation/modules/webmvc/spring/applicationContext-security-default.xml] is invalid; nested exception is org.xml.sax.SAXParseException; lineNumber: 75; columnNumber: 72; cvc-datatype-valid.1.2.1: '${maxConcurrentSessionsCount}' is not a valid value for 'integer'.
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:399)
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:336)
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:304)
    at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:181)
    at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:217)
    at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:188)
    at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:125)
    at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:94)
    at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:129)
    at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:537)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:452)
    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:403)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106)
    at org.gs4tr.projectdirector.service.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:73)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4811)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5251)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:147)

答:
This is the definition of max-session attribute:

```<code><xs:attribute name="max-sessions" type="xs:positiveInteger">
<xs:annotation>
<xs:documentation>
The maximum number of sessions a single authenticated user can have open at the same time. Defaults to "1".
</xs:documentation>
</xs:annotation>
</xs:attribute>
</code>```

As you can see, the type of the attribute is positiveInteger and you are not allowed to use SpEL.

SpEL (e.g. getting property value) is an string and in some cases you are allowed to use SpEL:

A property or constructor-arg value can be set using expressions as shown below

Body:
I have a requirement to allow Concurrent-session control in my web app and make configurable field "max-sessions". My configuration looks like:

<security:session-management>
    <security:concurrency-control max-sessions="${maxConcurrentSessionsCount}" session-registry-ref="sessionRegistry" expired-url="/handleInvalidatedSession.gs4tr"/>
</security:session-management>`

As you can guess, in "services.properties" file there should be "maxConcurrentSessionsCount" field which clients would set by their will.
But I'm getting next warning in Intelij:

"attribute 'max-sessions' on element 'security:concurrency-control' is not valid with respect to its type, 'positiveInteger'".

I successfully configure many others things, like "token-validity-seconds" and "remember-me-cookie" in "remember-me", etc.
Any idea how to solve a problem? Search couple of days over internet for help, but failed.

EDIT:
In "services.properties" is configured:
"maxConcurrentSessionsCount=2"

On start application, it throws next error:

No, it doesn't. It throws next ERROR on starting app:

017-09-14 15:46:47,724 ERROR [org.gs4tr.projectdirector.service.context.ContextLoaderListener][localhost-startStop-1][user:] -
org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 75 in XML document from class path resource [org/gs4tr/foundation/modules/webmvc/spring/applicationContext-security-default.xml] is invalid; nested exception is org.xml.sax.SAXParseException; lineNumber: 75; columnNumber: 72; cvc-datatype-valid.1.2.1: '${maxConcurrentSessionsCount}' is not a valid value for 'integer'.
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:399)
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:336)
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:304)
    at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:181)
    at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:217)
    at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:188)
    at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:125)
    at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:94)
    at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:129)
    at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:537)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:452)
    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:403)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106)
    at org.gs4tr.projectdirector.service.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:73)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4811)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5251)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:147)

Body:
This is the definition of max-session attribute:

<xs:attribute name="max-sessions" type="xs:positiveInteger">
<xs:annotation>
<xs:documentation>
The maximum number of sessions a single authenticated user can have open at the same time. Defaults to "1".
</xs:documentation>
</xs:annotation>
</xs:attribute>

As you can see, the type of the attribute is positiveInteger and you are not allowed to use SpEL.

SpEL (e.g. getting property value) is an string and in some cases you are allowed to use SpEL:

A property or constructor-arg value can be set using expressions as shown below


问:
how to use date mutator for laravel date conversion
I have a problem with inserting date formate
laravel use 'Y-m-d H:i:s' formate

whereas I have this format coming from admin panel m/d/Y

now, how can I convert date coming m/d/Y format to 'Y-m-d H:i:s' formate.

答:
This should work, assuming a $request is passed from form submit.

```<code>  $date = Carbon\Carbon::createFromFormat('m/d/Y', $request->date_field)->format('Y-m-d H:i:s');
</code>```

Body:
This should work, assuming a $request is passed from form submit.

  $date = Carbon\Carbon::createFromFormat('m/d/Y', $request->date_field)->format('Y-m-d H:i:s');


问:
disable and enable click?
I have Splash Screen and button . i want if app install users click in start button and go to main activity . the problem after run app if app install go direct to main activity .. i want only check if app install enable click and if not install disable click  </p>

```<code>  Button start = (Button) findViewById(R.id.bt_start);
    boolean isAppInstalled = appInstalledOrNot("com.facebook.android");
    if(isAppInstalled) {
        start.setEnabled(true);

        Intent Start_screen = new Intent(SplashScreen.this, MainActivity.class);
        startActivity(Start_screen);

    } else {

        start.setEnabled(false);

    }
}

private boolean appInstalledOrNot(String uri) {
    PackageManager pm = getPackageManager();
    try {
        pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES);
        return true;
    } catch (PackageManager.NameNotFoundException e) {
    }

    return false;
}
</code>```

答:
i want if app install users click in start button

Your startActivity event is not in the click listener of the enabled button, therefore it immediately goes to the next Activity

Try start.setOnClickListener, and then check if the app is installed.

Title: disable and enable click?

Body:
I have Splash Screen and button . i want if app install users click in start button and go to main activity . the problem after run app if app install go direct to main activity .. i want only check if app install enable click and if not install disable click

  Button start = (Button) findViewById(R.id.bt_start);
    boolean isAppInstalled = appInstalledOrNot("com.facebook.android");
    if(isAppInstalled) {
        start.setEnabled(true);

        Intent Start_screen = new Intent(SplashScreen.this, MainActivity.class);
        startActivity(Start_screen);

    } else {

        start.setEnabled(false);

    }
}

private boolean appInstalledOrNot(String uri) {
    PackageManager pm = getPackageManager();
    try {
        pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES);
        return true;
    } catch (PackageManager.NameNotFoundException e) {
    }

    return false;
}


问:
How do i set DB parameters separately for different databases in PostgreSQL
I am trying to set different values for same parameter in two different databases in Postgres,using below command.

```<code>alter system set work_mem = "100MB"; #DB1
alter system set work_mem = "20MB"; #DB2
</code>```

However value set for the second databases is showing for both DB's after updating.

Please guide me how to set parameters at databases level.

Postgres Version: 9.6
Environment: testing

答:
https://www.postgresql.org/docs/current/static/sql-alterdatabase.html

ALTER DATABASE name SET configuration_parameter { TO | = } { value |
  DEFAULT }

and example:

```<code>t=# alter database t set work_mem to '1MB';
ALTER DATABASE
t=# alter database o set work_mem to '2MB';
ALTER DATABASE
t=# \c o
You are now connected to database "o" as user "postgres".
o=# show work_mem ;
 work_mem
----------
 2MB
(1 row)

o=# \c t
You are now connected to database "t" as user "postgres".
t=# show work_mem ;
 work_mem
----------
 1MB
(1 row)
</code>```

Body:
I am trying to set different values for same parameter in two different databases in Postgres,using below command.

alter system set work_mem = "100MB"; #DB1
alter system set work_mem = "20MB"; #DB2

However value set for the second databases is showing for both DB's after updating.

Please guide me how to set parameters at databases level.

Postgres Version: 9.6
Environment: testing

Body:
https://www.postgresql.org/docs/current/static/sql-alterdatabase.html

ALTER DATABASE name SET configuration_parameter { TO | = } { value |
  DEFAULT }

and example:

t=# alter database t set work_mem to '1MB';
ALTER DATABASE
t=# alter database o set work_mem to '2MB';
ALTER DATABASE
t=# \c o
You are now connected to database "o" as user "postgres".
o=# show work_mem ;
 work_mem
----------
 2MB
(1 row)

o=# \c t
You are now connected to database "t" as user "postgres".
t=# show work_mem ;
 work_mem
----------
 1MB
(1 row)


问:
Serializing an object as UTF-8 XML in .NET
Proper object disposal removed for brevity but I'm shocked if this is the simplest way to encode an object as UTF-8 in memory. There has to be an easier way doesn't there?</p>

```<code>var serializer = new XmlSerializer(typeof(SomeSerializableObject));

var memoryStream = new MemoryStream();
var streamWriter = new StreamWriter(memoryStream, System.Text.Encoding.UTF8);

serializer.Serialize(streamWriter, entry);

memoryStream.Seek(0, SeekOrigin.Begin);
var streamReader = new StreamReader(memoryStream, System.Text.Encoding.UTF8);
var utf8EncodedXml = streamReader.ReadToEnd();
</code>```

答:
I found this blog post which explains the problem very well, and defines a few different solutions:

(dead link removed)

I've settled for the idea that the best way to do it is to completely omit the XML declaration when in memory. It actually is UTF-16 at that point anyway, but the XML declaration doesn't seem meaningful until it has been written to a file with a particular encoding; and even then the declaration is not required. It doesn't seem to break deserialization, at least.

As @Jon Hanna mentions, this can be done with an XmlWriter created like this:

```<code>XmlWriter writer = XmlWriter.Create (output, new XmlWriterSettings() { OmitXmlDeclaration = true });
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Proper object disposal removed for brevity but I'm shocked if this is the simplest way to encode an object as UTF-8 in memory. There has to be an easier way doesn't there?

var serializer = new XmlSerializer(typeof(SomeSerializableObject));

var memoryStream = new MemoryStream();
var streamWriter = new StreamWriter(memoryStream, System.Text.Encoding.UTF8);

serializer.Serialize(streamWriter, entry);

memoryStream.Seek(0, SeekOrigin.Begin);
var streamReader = new StreamReader(memoryStream, System.Text.Encoding.UTF8);
var utf8EncodedXml = streamReader.ReadToEnd();

Body:
I found this blog post which explains the problem very well, and defines a few different solutions:

(dead link removed)

I've settled for the idea that the best way to do it is to completely omit the XML declaration when in memory. It actually is UTF-16 at that point anyway, but the XML declaration doesn't seem meaningful until it has been written to a file with a particular encoding; and even then the declaration is not required. It doesn't seem to break deserialization, at least.

As @Jon Hanna mentions, this can be done with an XmlWriter created like this:

XmlWriter writer = XmlWriter.Create (output, new XmlWriterSettings() { OmitXmlDeclaration = true });

ContentLicense: CC BY-SA 4.0


问:
ORDER BY discrepancies with/without ROW_NUMBER()
I am usign: PostgreSQL 9.6.3

Today I've faced a very strange discrepancies in selection result depending on whether ROW_NUMBER() function call present or not present in my query

The first query with output looks like:

```<code>SELECT "users"."id", "users"."ranking" FROM "users" WHERE "users"."mentor" = 't'  ORDER BY "users"."ranking" DESC LIMIT 10;
</code>```

And it's result:

```<code>   id   |     ranking
--------+-----------------
     33 | 4.36852371411504
 320145 | 4.08071526845868
 301573 | 3.98071042776232
  25649 | 3.92019074023998
 159117 | 3.92019074023998
   3218 | 3.86067914389982
 635532 | 3.79788768116942
    559 | 3.73163558856403
 359211 | 3.73163558856403
 635548 | 3.66173214016947
</code>```

The second query is very similar to the first, but I've added ROW_NUMBER() selection:

```<code>SELECT "users"."id", "users"."ranking", ROW_NUMBER() OVER (ORDER BY "users"."ranking" DESC) FROM "users" WHERE "users"."mentor" = 't' ORDER BY "users"."ranking" DESC LIMIT 10;
</code>```

And it's result:

```<code>   id   |     ranking      | row_number
--------+------------------+------------
     33 | 4.36852371411504 |          1
 320145 | 4.08071526845868 |          2
 301573 | 3.98071042776232 |          3
 159117 | 3.92019074023998 |          4
  25649 | 3.92019074023998 |          5
   3218 | 3.86067914389982 |          6
 635532 | 3.79788768116942 |          7
    559 | 3.73163558856403 |          8
 359211 | 3.73163558856403 |          9
 419302 | 3.66173214016947 |         10
</code>```

As you see, it looks like in first case result is sorted by id in ASC order, while in second query it's get sorted by id in DESC order, but my queries are the same. I know HOW to solve this issue, but I want to understand WHY is it happen?

答:
You have multiple rows with the same value in the order by.

In relational databases, sorting is unstable.  When there are ties in the key values, the rows are in an indeterminate order.  This is what you are seeing.

The instability of SQL sorts is a direct result of the fact that relational tables (and result sets) represent unordered sets.  There is no additional ordering.  The solution is simple.  For a stable sort, just add an additional unique key to the order by:

```<code>order by ranking desc, id
</code>```

Body:
I am usign: PostgreSQL 9.6.3

Today I've faced a very strange discrepancies in selection result depending on whether ROW_NUMBER() function call present or not present in my query

The first query with output looks like:

SELECT "users"."id", "users"."ranking" FROM "users" WHERE "users"."mentor" = 't'  ORDER BY "users"."ranking" DESC LIMIT 10;

And it's result:

   id   |     ranking
--------+-----------------
     33 | 4.36852371411504
 320145 | 4.08071526845868
 301573 | 3.98071042776232
  25649 | 3.92019074023998
 159117 | 3.92019074023998
   3218 | 3.86067914389982
 635532 | 3.79788768116942
    559 | 3.73163558856403
 359211 | 3.73163558856403
 635548 | 3.66173214016947

The second query is very similar to the first, but I've added ROW_NUMBER() selection:

SELECT "users"."id", "users"."ranking", ROW_NUMBER() OVER (ORDER BY "users"."ranking" DESC) FROM "users" WHERE "users"."mentor" = 't' ORDER BY "users"."ranking" DESC LIMIT 10;

And it's result:

   id   |     ranking      | row_number
--------+------------------+------------
     33 | 4.36852371411504 |          1
 320145 | 4.08071526845868 |          2
 301573 | 3.98071042776232 |          3
 159117 | 3.92019074023998 |          4
  25649 | 3.92019074023998 |          5
   3218 | 3.86067914389982 |          6
 635532 | 3.79788768116942 |          7
    559 | 3.73163558856403 |          8
 359211 | 3.73163558856403 |          9
 419302 | 3.66173214016947 |         10

As you see, it looks like in first case result is sorted by id in ASC order, while in second query it's get sorted by id in DESC order, but my queries are the same. I know HOW to solve this issue, but I want to understand WHY is it happen?

Body:
You have multiple rows with the same value in the order by.

In relational databases, sorting is unstable.  When there are ties in the key values, the rows are in an indeterminate order.  This is what you are seeing.

The instability of SQL sorts is a direct result of the fact that relational tables (and result sets) represent unordered sets.  There is no additional ordering.  The solution is simple.  For a stable sort, just add an additional unique key to the order by:

order by ranking desc, id


问: How to refresh the page

答: You need to use location.reload(); in your success code/wherever you want to refresh

Title: How to refresh the page


问:
How to map a document list in WEBMethods?
I want to map an array which in WebMethods is a document list. I thought that you could just map that variable over without mapping all of the children. I have done this and nothing shows in the PassArea. (PassArea is the data array that is being sent to a mainframe program afterwards.)

```<code>     A           -->         B
       Field1                 F1
       Field2                 F2
       field3                 F3
</code>```

The document is A and the input document into the Natural program is B. The --> is the link that connects them together.

I don't have an image to show, because that would reveal some company information.

答:
There's a lot ways to map between arrays of documents. But before you create one, consider these writings:

Techcommunity SoftwareAG - performance impact with appendToDocumentList

quest4apps.com - Reason to avoid appendToDocumentList

As hint from #2 said that there's 6 ways they ranked as follows from fastest to slowest (but I'm going to give an example in first three, because the latter three is quite obviously slow, which considered to be avoided):

1. Java Loop: looping done through a Java service.

The easiest way to create java service is to map the input output first.

Right-click and click on "Generate Code" until the dialog box appears
Choose the option "For implementing this service"

And the service is created

Just re-arrange the code into this:

public static final void mappingDocuments(IData pipeline) throws ServiceException {

    // pipeline
    IDataCursor pipelineCursor = pipeline.getCursor();

    // Instantiate input A
    IData[] A = IDataUtil.getIDataArray(pipelineCursor, "A");

    // Initiate output B
    IData[] B = new IData[A.length];

    if (A != null)
    {
        for (int i = 0; i < A.length; i++)
        {
            // Populate the Field in doc A
            IDataCursor ACursor = A[i].getCursor();
            String Field1 = IDataUtil.getString(ACursor, "Field1");
            String Field2 = IDataUtil.getString(ACursor, "Field2");
            String Field3 = IDataUtil.getString(ACursor, "Field3");
            ACursor.destroy();

            // Create IData[i] and cursors finally put all Fields into B[i] variable output
            B[i] = IDataFactory.create();
            IDataCursor BCursor = B[i].getCursor();
            IDataUtil.put(BCursor, "F1", Field1);
            IDataUtil.put(BCursor, "F2", Field2);
            IDataUtil.put(BCursor, "F3", Field3);
            BCursor.destroy();

            // OR JUST USE CLONE BELOW IF YOU DON'T HAVE ANY MODIFICATION INSIDE THE VARIABLE
            // B[i] = IDataUtil.clone(A[i]);
        }
    }
    pipelineCursor.destroy();

    // Finally to put the B Map(IData) to output.
    // Actually you can use only single pipelineCursor throughout all code but it's just for readable
    IDataUtil.put(pipelineCursor, "B", B);
    pipelineCursor.destroy();

}
```

Result

2. Implicit Loop: for simple lists of the same size, you may want to link them directly in a MAP step

Create flow service and input & output document

Create MAP step

Select both document in ForEach loop.

3. Explicit Loop: using a LOOP step and its Output Array.

Create flow service and input & output document

Create LOOP step

Change the properties of LOOP, input array=A; output array=B; and create a map under LOOP step

Map all parameters in A to B

Hope these helps...

Body:
I want to map an array which in WebMethods is a document list. I thought that you could just map that variable over without mapping all of the children. I have done this and nothing shows in the PassArea. (PassArea is the data array that is being sent to a mainframe program afterwards.)

     A           -->         B
       Field1                 F1
       Field2                 F2
       field3                 F3

The document is A and the input document into the Natural program is B. The --> is the link that connects them together.

I don't have an image to show, because that would reveal some company information.

Body:
There's a lot ways to map between arrays of documents. But before you create one, consider these writings:

Techcommunity SoftwareAG - performance impact with appendToDocumentList

quest4apps.com - Reason to avoid appendToDocumentList

As hint from #2 said that there's 6 ways they ranked as follows from fastest to slowest (but I'm going to give an example in first three, because the latter three is quite obviously slow, which considered to be avoided):

1. Java Loop: looping done through a Java service.

The easiest way to create java service is to map the input output first.

Right-click and click on "Generate Code" until the dialog box appears
Choose the option "For implementing this service"

And the service is created

Just re-arrange the code into this:

public static final void mappingDocuments(IData pipeline) throws ServiceException {

    // pipeline
    IDataCursor pipelineCursor = pipeline.getCursor();

    // Instantiate input A
    IData[] A = IDataUtil.getIDataArray(pipelineCursor, "A");

    // Initiate output B
    IData[] B = new IData[A.length];

    if (A != null)
    {
        for (int i = 0; i < A.length; i++)
        {
            // Populate the Field in doc A
            IDataCursor ACursor = A[i].getCursor();
            String Field1 = IDataUtil.getString(ACursor, "Field1");
            String Field2 = IDataUtil.getString(ACursor, "Field2");
            String Field3 = IDataUtil.getString(ACursor, "Field3");
            ACursor.destroy();

            // Create IData[i] and cursors finally put all Fields into B[i] variable output
            B[i] = IDataFactory.create();
            IDataCursor BCursor = B[i].getCursor();
            IDataUtil.put(BCursor, "F1", Field1);
            IDataUtil.put(BCursor, "F2", Field2);
            IDataUtil.put(BCursor, "F3", Field3);
            BCursor.destroy();

            // OR JUST USE CLONE BELOW IF YOU DON'T HAVE ANY MODIFICATION INSIDE THE VARIABLE
            // B[i] = IDataUtil.clone(A[i]);
        }
    }
    pipelineCursor.destroy();

    // Finally to put the B Map(IData) to output.
    // Actually you can use only single pipelineCursor throughout all code but it's just for readable
    IDataUtil.put(pipelineCursor, "B", B);
    pipelineCursor.destroy();

}

Result

2. Implicit Loop: for simple lists of the same size, you may want to link them directly in a MAP step

Create flow service and input & output document

Create MAP step

Select both document in ForEach loop.

3. Explicit Loop: using a LOOP step and its Output Array.

Create flow service and input & output document

Create LOOP step

Change the properties of LOOP, input array=A; output array=B; and create a map under LOOP step

Map all parameters in A to B

Hope these helps...


问:
How to set property values in new object from object from List and get a new List of the same objects in which properties are set using java 8?
For example here is my code :

```<code>   List<EmployeeDto> employees = new ArrayList<>();
   if(CollectionUtils.isNotEmpty(employeeListFromUI)){
        for(EmployeeVO employee : employeeListFromUI){
            EmployeeDto employeeDto =  new EmployeeDto();
            employeeDto.setName(employee.getName());
            employeeDto.setAddressLine1(employee.getAddressLine1());
            if(employee.getAddressLine2()!=null && employee.getAddressLine2()!=""){
            employeeDto.setAddressLine2(employee.getAddressLine2());
            }
            employeeDto.setCity(employee.getCity());
            employeeDto.setState(employee.getState());
            employeeDto.setZip(employee.getZip());
            employees.add(employeeDto);
        }
    }
</code>```

instead of this much of code using java 8 stream and forEach is it possible to write the above code in few lines.

答:
You could move this:

```<code>EmployeeDto employeeDto =  new EmployeeDto();
employeeDto.setName(employee.getName());
employeeDto.setAddressLine1(employee.getAddressLine1());
if(employee.getAddressLine2()!=null && employee.getAddressLine2()!=""){
   employeeDto.setAddressLine2(employee.getAddressLine2());
}
employeeDto.setCity(employee.getCity());
employeeDto.setState(employee.getState());
employeeDto.setZip(employee.getZip());
employees.add(employeeDto);
</code>```

to a separate method, like :

```<code>private static EmployeeDto transform(EmployeeVO input) {
    // transform and return
}
</code>```

And the use it in the form:

```<code>employeeListFromUI.stream()
                  .map(YourClass::tranform)
                  .collect(Collectors.toList());
</code>```

Body:
For example here is my code :

   List<EmployeeDto> employees = new ArrayList<>();
   if(CollectionUtils.isNotEmpty(employeeListFromUI)){
        for(EmployeeVO employee : employeeListFromUI){
            EmployeeDto employeeDto =  new EmployeeDto();
            employeeDto.setName(employee.getName());
            employeeDto.setAddressLine1(employee.getAddressLine1());
            if(employee.getAddressLine2()!=null && employee.getAddressLine2()!=""){
            employeeDto.setAddressLine2(employee.getAddressLine2());
            }
            employeeDto.setCity(employee.getCity());
            employeeDto.setState(employee.getState());
            employeeDto.setZip(employee.getZip());
            employees.add(employeeDto);
        }
    }

instead of this much of code using java 8 stream and forEach is it possible to write the above code in few lines.

Body:
You could move this:

EmployeeDto employeeDto =  new EmployeeDto();
employeeDto.setName(employee.getName());
employeeDto.setAddressLine1(employee.getAddressLine1());
if(employee.getAddressLine2()!=null && employee.getAddressLine2()!=""){
   employeeDto.setAddressLine2(employee.getAddressLine2());
}
employeeDto.setCity(employee.getCity());
employeeDto.setState(employee.getState());
employeeDto.setZip(employee.getZip());
employees.add(employeeDto);

to a separate method, like :

private static EmployeeDto transform(EmployeeVO input) {
    // transform and return
}

And the use it in the form:

employeeListFromUI.stream()
                  .map(YourClass::tranform)
                  .collect(Collectors.toList());


问:
AWS Deployment issue Error code: HEALTH_CONSTRAINTS (In-place deployment)
i want to Host my website on AWS s3

but when i create code deployment  & i followed this url -> https://aws.amazon.com/getting-started/tutorials/deploy-code-vm/

showing this error ->   Deployment Failed
The overall deployment failed because too many individual instances failed deployment, too few healthy instances are available for deployment, or some instances in your deployment group are experiencing problems. (Error code: HEALTH_CONSTRAINTS)

error Screen shoot -> http://i.prntscr.com/oqr4AxEiThuy823jmMck7A.png

so please Help me

答:
If you want to host your website on S3, you should upload your code into S3 bucket and enable Static Web Hosting for that bucket. If you use CodeDeploy, it will take application code either from S3 bucket or GitHub and host it on EC2 instances.

I will assume that you want to use CodeDeploy to host your website on a group of EC2 instances. The error that you have mentioned could occur if your EC2 instances do not have correct permission through IAM role.

From Documentation

The permissions you add to the service role specify the operations AWS CodeDeploy can perform when it accesses your Amazon EC2 instances and Auto Scaling groups. To add these permissions, attach an AWS-supplied policy, AWSCodeDeployRole, to the service role.

If you are following along the sample deployment from the CodeDeploy wizard make sure you have picked Create A Service Role at the stage that you are required to Select a service role.


问:
How do I concatenate strings in Swift?
How to concatenate string in Swift?

In Objective-C we do like

```<code>NSString *string = @"Swift";
NSString *resultStr = [string stringByAppendingString:@" is a new Programming Language"];
</code>```

or

```<code>NSString *resultStr=[NSString stringWithFormat:@"%@ is a new Programming Language",string];
</code>```

But I want to do this in Swift-language.

答:
I just switched from Objective-C to Swift (4), and I find that I often use:</p>

```<code>let allWords = String(format:"%@ %@ %@",message.body!, message.subject!, message.senderName!)
</code>```

Title: How do I concatenate strings in Swift?

Body:
How to concatenate string in Swift?

In Objective-C we do like

NSString *string = @"Swift";
NSString *resultStr = [string stringByAppendingString:@" is a new Programming Language"];

or

NSString *resultStr=[NSString stringWithFormat:@"%@ is a new Programming Language",string];

But I want to do this in Swift-language.

Body:
I just switched from Objective-C to Swift (4), and I find that I often use:

let allWords = String(format:"%@ %@ %@",message.body!, message.subject!, message.senderName!)


问:
How to add or replace textfield input text to picker view text in Swift 3

I have a picker loaded with an array of strings, I want to change means appending or editing strings by typing in the text field and save in that array and display that changes in that picker view.Thanks in advance.

答:
```<code>extension ViewController: UITextFieldDelegate {
func textFieldDidEndEditing(_ textField: UITextField) {
    addIntoArray(text: textField.text)
}

func addIntoArray(text: String?) {
    guard let text = text, text.count > 0 else {
        //for blannk or nil string
        return
    }

    listArray.append(text)
    //reload the picker
    picker.reloadAllComponents() //picker is the instanc of your pickerView
}
}
</code>```

try this

Body:
extension ViewController: UITextFieldDelegate {
func textFieldDidEndEditing(_ textField: UITextField) {
    addIntoArray(text: textField.text)
}

func addIntoArray(text: String?) {
    guard let text = text, text.count > 0 else {
        //for blannk or nil string
        return
    }

    listArray.append(text)
    //reload the picker
    picker.reloadAllComponents() //picker is the instanc of your pickerView
}
}

try this


问:
How to measure static size beforehand? WINAPI
I am creating a widow with static text, and because of the all 96/120/180 DPI stuff, I need to create a layouting mini-engine.

The dialog is created in code, statics are created in code, fonts are created in code, everything, mostly because resources in .rc have their share of DPI related problems as well and I want a total control.

The problem with all this is that I don't know how to find the length of the text in statics. I need to calculate the initial size of the static control, and also, I need to calculate a padding between different statics in font unit sizes, but since I don't know the size of the previous static, I can't offset the next one.

The biggest problem is that static does the word wrapping, therefore I can't find a text measuring function that would calculate that and a correction for a custom font, italic, bold, oversize...

Anyone have any ideas?

答: I can't think of any compelling reason to do this any differently then the way all other GUI class libraries do it.  Just scale window sizes between the 'design' DPI setting and the target machine DPI setting.  Using DPI-independent constants is pretty painful in MFC since everything is pixel based.  So keep your workstation at the common 96 DPI setting, scale from there on the target machine. You do have to keep a bit of slack because of TrueType hinting.</p>


问:
Only display Woocommerce child product categories
I am currently using the following code to fetch WooCommerce product categories:

```<code><?php
    $orderby = 'name';
    $order = 'asc';
    $hide_empty = false ;
    $cat_args = array(
        'orderby'    => $orderby,
        'order'      => $order,
        'hide_empty' => $hide_empty,
    );

    $product_categories = get_terms( 'product_cat', $cat_args );

    if( !empty($product_categories) ){
        echo '<ul>';
        foreach ($product_categories as $key => $category) {
            echo '<li>';
            echo '<a href="'.get_term_link($category).'" >';
            echo $category->name;
            echo '</a>';
            echo '<li>';
        }
        echo '</ul>';
    }
?>
</code>```

This currently displays all categories, however I wish this to only show the child categories.

For example, if you are on the Category 1 page, it should show all children within that category only.

I've looked at many examples on here but have been unable to find something that works for what I need.

答:
You can add this to woocommerce/archive-product.php file

```<code>$queried_object = get_queried_object();
$parent = $queried_object->term_id;
$categories = get_term_children( $parent, 'product_cat' );
if ( $categories && ! is_wp_error( $category ) ) :

echo '<ul>';

foreach($categories as $category) :

$term = get_term( $category, 'product_cat' );
echo '<li>';
echo '<a href="'.get_term_link($term).'" >';
echo $term->name;
echo '</a>';
echo '</li>';

endforeach;

echo '</ul>';

endif;
</code>```

This will only work on your archives. And categories with children.

It will also output grand child categories.

Hope this helps.

Body:
I am currently using the following code to fetch WooCommerce product categories:

<?php
    $orderby = 'name';
    $order = 'asc';
    $hide_empty = false ;
    $cat_args = array(
        'orderby'    => $orderby,
        'order'      => $order,
        'hide_empty' => $hide_empty,
    );

    $product_categories = get_terms( 'product_cat', $cat_args );

    if( !empty($product_categories) ){
        echo '
';
        foreach ($product_categories as $key => $category) {
            echo '
';
            echo '';
            echo $category->name;
            echo '';
            echo '
';
        }
        echo '
';
    }
?>

This currently displays all categories, however I wish this to only show the child categories.

For example, if you are on the Category 1 page, it should show all children within that category only.

I've looked at many examples on here but have been unable to find something that works for what I need.

Body:
You can add this to woocommerce/archive-product.php file

$queried_object = get_queried_object();
$parent = $queried_object->term_id;
$categories = get_term_children( $parent, 'product_cat' );
if ( $categories && ! is_wp_error( $category ) ) :

echo '<ul>';

foreach($categories as $category) :

$term = get_term( $category, 'product_cat' );
echo '<li>';
echo '<a href="'.get_term_link($term).'" >';
echo $term->name;
echo '</a>';
echo '</li>';

endforeach;

echo '</ul>';

endif;

This will only work on your archives. And categories with children.

It will also output grand child categories.

Hope this helps.


问:
Check if non-valued query string exists in url with C#
I've seen a couple examples of how to check if a query string exists in a url with C#:

www.site.com/index?query=yes

```<code>if(Request.QueryString["query"]=="yes")
</code>```

But how would I check a string without a parameter? I just need to see if it exists.

www.site.com/index?query

```<code>if(Request.QueryString["query"] != null) //why is this always null?
</code>```

I know there's probably a simple answer and I'll feel dumb, but I haven't been able to find it yet. Thanks!

答:
I Prefer to use:</p>

```<code>If(Request.QueryString.AllKeys.Contains("query")
{
    //
}
</code>```

Body:
I've seen a couple examples of how to check if a query string exists in a url with C#:

www.site.com/index?query=yes

if(Request.QueryString["query"]=="yes")

But how would I check a string without a parameter? I just need to see if it exists.

www.site.com/index?query

if(Request.QueryString["query"] != null) //why is this always null?

I know there's probably a simple answer and I'll feel dumb, but I haven't been able to find it yet. Thanks!

Body:
I Prefer to use:

If(Request.QueryString.AllKeys.Contains("query")
{
    //
}


问:
Connect tableau to Google Dataproc
I am wondering how to connect tableau to Google Dataproc via SPARK SQL?

I am trying to connect using External IP address of the master node and port but it does not work.

答:
The following may be useful, it is specific to Hortonworks but the concepts should be the same:

https://community.hortonworks.com/articles/5469/working-with-firewalled-hdp-via-ssh-tunnel-and-soc.html

I assume Tableau is not hosted on GCE?

Title: Connect tableau to Google Dataproc


问:
Log Lazy Loading operations
I use Entity Framework 5 with POCO entities and lazy loading proxies. In most cases I eagerly load all entities required for subsequent operations, but in some cases I rely on lazy loading to retrieve and navigate to related entities. This works well, but I would like to audit my application and make sure that I don't miss opportunities for eager loading optimization (or at least eliminate excessive use of lazy loading).

I currently rely on the SQL Profiler for this purpose, but this is tedious, because it's hard to distinguish between eager/explicit loading and lazy loading queries.

Is it possible to log lazy loading operations? Basically, I would like to Debug.Print whenever a store query is executed, as a result of lazy loading (but not when I explicitly execute a query).

Please don't provide commentary on the merits (or lack thereof) of lazy loading. I am working on a sizable application and switching at this stage would be extremely risky.

答:
I suggest checking out this library: https://github.com/jamesmanning/EntityFramework.LazyLoadLoggingInterceptor

More specifically, this file shows an implementation of an Entity Framework DbCommandInterceptor capable of detecting lazy loading queries. At its core, it implements a ReaderExecuting method containing this hack:

```<code>        // unfortunately not a better way to detect whether the load is lazy or explicit via interceptor
        var stackFrames = new StackTrace(true).GetFrames();
        var stackMethods = stackFrames?.Select(x => x.GetMethod()).ToList();

        var dynamicProxyPropertyGetterMethod = stackMethods?
            .FirstOrDefault(x =>
                x.DeclaringType?.FullName.StartsWith("System.Data.Entity.DynamicProxies") == true &&
                x.Name.StartsWith("get_"));
        if (dynamicProxyPropertyGetterMethod == null)
        {
            // not in a lazy-load context, nothing to do
            return;
        }
</code>```

Title: Log Lazy Loading operations

Body:
I suggest checking out this library: https://github.com/jamesmanning/EntityFramework.LazyLoadLoggingInterceptor

More specifically, this file shows an implementation of an Entity Framework DbCommandInterceptor capable of detecting lazy loading queries. At its core, it implements a ReaderExecuting method containing this hack:

        // unfortunately not a better way to detect whether the load is lazy or explicit via interceptor
        var stackFrames = new StackTrace(true).GetFrames();
        var stackMethods = stackFrames?.Select(x => x.GetMethod()).ToList();

        var dynamicProxyPropertyGetterMethod = stackMethods?
            .FirstOrDefault(x =>
                x.DeclaringType?.FullName.StartsWith("System.Data.Entity.DynamicProxies") == true &&
                x.Name.StartsWith("get_"));
        if (dynamicProxyPropertyGetterMethod == null)
        {
            // not in a lazy-load context, nothing to do
            return;
        }


问:
What kind of database refactoring tools are there?
I am looking for something to integrate to my CI workflow.

I've heard of dbdeploy but I'm looking for something else. The reason I don't like dbdeploy is I don't want to install java on my server.

I would prefer of course that the solution doesn't involve stringing some shell scripts together.

答:
Here is a feature comparison between

Flyway

Liquibase

c5-db-migration

dbdeploy

mybatis

MIGRATEdb

migrate4j

dbmaintain

AutoPatch

OwnerDisplayName: paan

LastEditorDisplayName: mat


问:
How to add a value after being logged in?
I am working in an android studio project and I have a login activity,I created database using SharedPreferences and SQLite;I have created a table which has columns id,email,password,check_in,check_out.

I made it possible to login after I register a user;but I do not know how to insert a data in check_in cell of logged user.

So my problem is that how to make possible to add the time of check_in in table in database after logged in?

And how I can the see the table created using SQLite?

答:
I made it possible to login after I register a user;but I do not know
  how to insert a data in check_in cell of logged user.

You would use the SQLiteDatabase's update method something along the lines of :-

```<code>ContentValues cv = new ContentValues();
cv.put("check_in",System.currentTimeMillis());
SQLiteDatabase db = this.getWritableDatabase();
db.update("your_table_name",cv,"email=? AND user=?",new String[]{email,user});
</code>```

And how I can the see the table created using SQLite?

You can

install a product that provides this ability,

copy the database via adb or tools that utilise adb, so that a product that can look at SQLite databases can access the copied file,

extract a cursor from the table and then use this as the source for displaying the data e.g you could use something like

:-

```<code>SQLiteDatabae db = this.getWriteableDatabase();
Cursor csr = db.query("your_table_name",null,null,null,null,null,null);
Databaseutils.dumpCursor(csr);
csr.close();
</code>```

Body:
I made it possible to login after I register a user;but I do not know
  how to insert a data in check_in cell of logged user.

You would use the SQLiteDatabase's update method something along the lines of :-

ContentValues cv = new ContentValues();
cv.put("check_in",System.currentTimeMillis());
SQLiteDatabase db = this.getWritableDatabase();
db.update("your_table_name",cv,"email=? AND user=?",new String[]{email,user});

And how I can the see the table created using SQLite?

You can

install a product that provides this ability,

copy the database via adb or tools that utilise adb, so that a product that can look at SQLite databases can access the copied file,

extract a cursor from the table and then use this as the source for displaying the data e.g you could use something like

:-

SQLiteDatabae db = this.getWriteableDatabase();
Cursor csr = db.query("your_table_name",null,null,null,null,null,null);
Databaseutils.dumpCursor(csr);
csr.close();


问:
How to call REST with POST in Apache camel?
I want to call a REST API with Apache Camel.

When I do it from Postman I use the following:

```<code>Method: Post
Headers:
Content-Type: application/x-www-form-urlencoded

Body
Check x-www-form-urlencoded option

3 Key value parameters added
Username: ABC
Password: ABC
Country: UK
</code>```

After setting up this configuration I am able to consume my REST API and it responds with an XML.

But I really don't know how to write this on Camel.

答:
Just to add to the @marcin-pietraszek precise answer and based on your last comment:

how can I add Body (Username: ABC, Password: ABC, Country: UK) parameters inside your code have shared

Depends on the services' interface. If it's query parameters, you could use:

```<code>from("direct:start").
    setHeader(Exchange.HTTP_METHOD, constant("POST")).
    setHeader(Exchange.CONTENT_TYPE, constant("application/x-www-form-urlencoded")).
    setHeader(Exchange.HTTP_QUERY, constant("Username=ABC&Password=ABC&Country=UK"))
    to("http://www.google.com");
</code>```

If it's directly in the body you could use:

```<code>from("direct:start").
    setHeader(Exchange.HTTP_METHOD, constant("POST")).
    setHeader(Exchange.CONTENT_TYPE, constant("application/x-www-form-urlencoded")).
    setBody(constant("Username: ABC, Password: ABC, Country: UK"))
    to("http://www.google.com");
</code>```

Remind that you should look into the service you are posting how it expect to receive the body (JSON, XML, CSV, etc.).

Body:
I want to call a REST API with Apache Camel.

When I do it from Postman I use the following:

Method: Post
Headers:
Content-Type: application/x-www-form-urlencoded

Body
Check x-www-form-urlencoded option

3 Key value parameters added
Username: ABC
Password: ABC
Country: UK

After setting up this configuration I am able to consume my REST API and it responds with an XML.

But I really don't know how to write this on Camel.

Body:
Just to add to the @marcin-pietraszek precise answer and based on your last comment:

how can I add Body (Username: ABC, Password: ABC, Country: UK) parameters inside your code have shared

Depends on the services' interface. If it's query parameters, you could use:

from("direct:start").
    setHeader(Exchange.HTTP_METHOD, constant("POST")).
    setHeader(Exchange.CONTENT_TYPE, constant("application/x-www-form-urlencoded")).
    setHeader(Exchange.HTTP_QUERY, constant("Username=ABC&Password=ABC&Country=UK"))
    to("http://www.google.com");

If it's directly in the body you could use:

from("direct:start").
    setHeader(Exchange.HTTP_METHOD, constant("POST")).
    setHeader(Exchange.CONTENT_TYPE, constant("application/x-www-form-urlencoded")).
    setBody(constant("Username: ABC, Password: ABC, Country: UK"))
    to("http://www.google.com");

Remind that you should look into the service you are posting how it expect to receive the body (JSON, XML, CSV, etc.).