问:
How to split a string with multiple delimiters in vba excel?
I want to split a string with multiple delimiters using Excel VBA.  One of the strings is:

```<code>d1-d2 d3 d4
</code>```

We have a dash and a space as two delimiters. I tried the split function but it only does it with one delimiter.

答:
I'll add that I had a quick look at Chip Pearson's answer, and thought it could be improved a little in terms of performance, so I wrote my own which appears to be about 40% faster (feel free to test yourself). It's faster (1.0E-5 vs 1.7E-5 seconds per cycle) because it uses byte arrays rather than actual characters to compare values. Here's the function which returns a string array like Chip Pearson's:

```<code>Function SplitMultiDelims2(Text As String, DelimChars As String) As String()
    '''
    'Function to split a string at multiple charachters
    'Use like SplitMultiDelims2("This:is-a,test string", ":-,")
    'Returns an array, in that example SplitMultiDelims2("This:is-a,test string", ":-,")(4) would be "test string"
    '''
    Dim bytes() As Byte
    Dim delims() As Byte
    Dim i As Long, aub As Long, ub As Long
    Dim stack As String
    Dim t() As String
    Dim tLen As Long
    tLen = Len(Text)
    If tLen = 0 Then
        Exit Function
    End If
    ReDim t(1 To tLen)                           'oversize array to avoid Redim Preserve too often
    bytes = StrConv(Text, vbFromUnicode)
    delims = StrConv(DelimChars, vbFromUnicode)
    ub = UBound(bytes)
    For i = 0 To ub
        If Contains(delims, bytes(i)) Then
            aub = aub + 1
            t(aub) = stack
            stack = ""
        Else
            stack = stack & Chr(bytes(i))
        End If
    Next i
    t(aub + 1) = stack
    ReDim Preserve t(1 To aub + 1)               'Works marginally faster if you delete this line,
    'however it returns an oversized array (which is a problem if you use UBOUND of the result,
    'but fine if you are just looking up an indexed value like the 5th string)
    SplitMultiDelims2 = t
End Function

'and a 2nd function called by the first one
Function Contains(arr, v As Byte) As Boolean     'checks if Byte v is contained in Byte array arr
    Dim rv As Boolean, lb As Long, ub As Long, i As Long
    lb = LBound(arr)
    ub = UBound(arr)
    For i = lb To ub
        If arr(i) = v Then
            rv = True
            Exit For
        End If
    Next i
    Contains = rv
End Function
</code>```

Here's the test log (his is SplitMultiDelims, mine is SplitMultiDelims2)

```<code>> SplitMultiDelims: 1.76105267188204E-05s per cycle 'this is the important figure
> i = 568064 iterations in 10.00390625 seconds
>Test completed: 08/06/2017 10:23:22
> SplitMultiDelims2: 1.05756701906142E-05s per cycle
>i = 947044 iterations in 10.015625 seconds
>Test completed: 08/06/2017 10:23:32
> SplitMultiDelims2: 1.04176859354441E-05s per cycle
>i = 960656 iterations in 10.0078125 seconds
>Test completed: 08/06/2017 10:23:54
> SplitMultiDelims: 1.76228941673255E-05s per cycle
>i = 567887 iterations in 10.0078125 seconds
>Test completed: 08/06/2017 10:24:04
</code>```

Run in both directions to avoid memory writing handicaps

Test code below uses Timer so not overly precise, but good enough to demonstrate the difference

```<code>Sub testSplit()
    Dim t As Double, dt As Double
    Dim s As String
    Dim i As Long
    t = Timer: i = 0: dt = 0: s = ""
    Do Until dt > 10                             'loop for 10 seconds
        s = SplitMultiDelims("This:is-a,test string", ":-,")(1)
        dt = Timer - t
        i = i + 1
    Loop
    Debug.Print "SplitMultiDelims: " & dt / i & "s per cycle" & vbCrLf & "i = " & i; " iterations in " & dt; " seconds" & vbCrLf & "Test completed: " & Now
    t = Timer: i = 0: dt = 0: s = ""
    Do Until dt > 10                             'loop for 10 seconds
        s = SplitMultiDelims2("This:is-a,test string", ":-,")(1)
        dt = Timer - t
        i = i + 1
    Loop
    Debug.Print "SplitMultiDelims2: " & dt / i & "s per cycle" & vbCrLf & "i = " & i; " iterations in " & dt; " seconds" & vbCrLf & "Test completed: " & Now
End Sub
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to split a string with multiple delimiters using Excel VBA.  One of the strings is:

d1-d2 d3 d4

We have a dash and a space as two delimiters. I tried the split function but it only does it with one delimiter.

Body:
I'll add that I had a quick look at Chip Pearson's answer, and thought it could be improved a little in terms of performance, so I wrote my own which appears to be about 40% faster (feel free to test yourself). It's faster (1.0E-5 vs 1.7E-5 seconds per cycle) because it uses byte arrays rather than actual characters to compare values. Here's the function which returns a string array like Chip Pearson's:

Function SplitMultiDelims2(Text As String, DelimChars As String) As String()
    '''
    'Function to split a string at multiple charachters
    'Use like SplitMultiDelims2("This:is-a,test string", ":-,")
    'Returns an array, in that example SplitMultiDelims2("This:is-a,test string", ":-,")(4) would be "test string"
    '''
    Dim bytes() As Byte
    Dim delims() As Byte
    Dim i As Long, aub As Long, ub As Long
    Dim stack As String
    Dim t() As String
    Dim tLen As Long
    tLen = Len(Text)
    If tLen = 0 Then
        Exit Function
    End If
    ReDim t(1 To tLen)                           'oversize array to avoid Redim Preserve too often
    bytes = StrConv(Text, vbFromUnicode)
    delims = StrConv(DelimChars, vbFromUnicode)
    ub = UBound(bytes)
    For i = 0 To ub
        If Contains(delims, bytes(i)) Then
            aub = aub + 1
            t(aub) = stack
            stack = ""
        Else
            stack = stack & Chr(bytes(i))
        End If
    Next i
    t(aub + 1) = stack
    ReDim Preserve t(1 To aub + 1)               'Works marginally faster if you delete this line,
    'however it returns an oversized array (which is a problem if you use UBOUND of the result,
    'but fine if you are just looking up an indexed value like the 5th string)
    SplitMultiDelims2 = t
End Function

'and a 2nd function called by the first one
Function Contains(arr, v As Byte) As Boolean     'checks if Byte v is contained in Byte array arr
    Dim rv As Boolean, lb As Long, ub As Long, i As Long
    lb = LBound(arr)
    ub = UBound(arr)
    For i = lb To ub
        If arr(i) = v Then
            rv = True
            Exit For
        End If
    Next i
    Contains = rv
End Function

Here's the test log (his is SplitMultiDelims, mine is SplitMultiDelims2)

> SplitMultiDelims: 1.76105267188204E-05s per cycle 'this is the important figure
> i = 568064 iterations in 10.00390625 seconds
>Test completed: 08/06/2017 10:23:22
> SplitMultiDelims2: 1.05756701906142E-05s per cycle
>i = 947044 iterations in 10.015625 seconds
>Test completed: 08/06/2017 10:23:32
> SplitMultiDelims2: 1.04176859354441E-05s per cycle
>i = 960656 iterations in 10.0078125 seconds
>Test completed: 08/06/2017 10:23:54
> SplitMultiDelims: 1.76228941673255E-05s per cycle
>i = 567887 iterations in 10.0078125 seconds
>Test completed: 08/06/2017 10:24:04

Run in both directions to avoid memory writing handicaps

Test code below uses Timer so not overly precise, but good enough to demonstrate the difference

Sub testSplit()
    Dim t As Double, dt As Double
    Dim s As String
    Dim i As Long
    t = Timer: i = 0: dt = 0: s = ""
    Do Until dt > 10                             'loop for 10 seconds
        s = SplitMultiDelims("This:is-a,test string", ":-,")(1)
        dt = Timer - t
        i = i + 1
    Loop
    Debug.Print "SplitMultiDelims: " & dt / i & "s per cycle" & vbCrLf & "i = " & i; " iterations in " & dt; " seconds" & vbCrLf & "Test completed: " & Now
    t = Timer: i = 0: dt = 0: s = ""
    Do Until dt > 10                             'loop for 10 seconds
        s = SplitMultiDelims2("This:is-a,test string", ":-,")(1)
        dt = Timer - t
        i = i + 1
    Loop
    Debug.Print "SplitMultiDelims2: " & dt / i & "s per cycle" & vbCrLf & "i = " & i; " iterations in " & dt; " seconds" & vbCrLf & "Test completed: " & Now
End Sub


来源: stackexchange

问:
Jenkins pipeline exception java.io.NotSerializableException: hudson.model.FreeStyleProject
I create Job pipeline, and I try get all jobs which matches regexp, and after parallel start. I get exception: java.io.NotSerializableException: hudson.model.FreeStyleProject
Jenkins v 2.5

```<code>node {
    stage('deploy') {
        def branches = [:]
        def theJobs = Jenkins.instance.getAllItems(Job);
        for(int i = 0; i < theJobs.size; i++)
        {
            def jobName= theJobs[i].getName();
            if( jobName =~ /server\-[0-9][0-9]\..*/)
            {
                branches[i] = {
                    build job : "${jobName}", parameters: [[$class: 'StringParameterValue', name: 'BRANCH', value: "${BRANCH}"] ]
                }
            }
            jobName = null
        }
        parallel branches
    }
}
</code>```

Full text exception:

```<code>java.io.NotSerializableException: hudson.model.FreeStyleProject
at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:860)
at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:569)
at org.jboss.marshalling.river.BlockMarshaller.doWriteObject(BlockMarshaller.java:65)
at org.jboss.marshalling.river.BlockMarshaller.writeObject(BlockMarshaller.java:56)
at org.jboss.marshalling.MarshallerObjectOutputStream.writeObjectOverride(MarshallerObjectOutputStream.java:50)
at org.jboss.marshalling.river.RiverObjectOutputStream.writeObjectOverride(RiverObjectOutputStream.java:179)
at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:344)
at java.util.HashMap.internalWriteEntries(HashMap.java:1777)
at java.util.HashMap.writeObject(HashMap.java:1354)
at sun.reflect.GeneratedMethodAccessor277.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.jboss.marshalling.reflect.SerializableClass.callWriteObject(SerializableClass.java:271)
at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:976)
at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:854)
at org.jboss.marshalling.river.RiverMarshaller.doWriteFields(RiverMarshaller.java:1032)
at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:988)
at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:854)
at org.jboss.marshalling.river.RiverMarshaller.doWriteFields(RiverMarshaller.java:1032)
at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:988)
at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:967)
at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:967)
at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:854)
at org.jboss.marshalling.river.RiverMarshaller.doWriteFields(RiverMarshaller.java:1032)
at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:988)
at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:967)
at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:854)
at org.jboss.marshalling.river.RiverMarshaller.doWriteFields(RiverMarshaller.java:1032)
at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:988)
at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:967)
at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:854)
at org.jboss.marshalling.river.RiverMarshaller.doWriteFields(RiverMarshaller.java:1032)
at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:988)
at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:967)
at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:854)
at org.jboss.marshalling.river.RiverMarshaller.doWriteFields(RiverMarshaller.java:1032)
at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:988)
at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:854)
at org.jboss.marshalling.river.RiverMarshaller.doWriteFields(RiverMarshaller.java:1032)
at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:988)
at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:967)
at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:854)
at org.jboss.marshalling.river.BlockMarshaller.doWriteObject(BlockMarshaller.java:65)
at org.jboss.marshalling.river.BlockMarshaller.writeObject(BlockMarshaller.java:56)
at org.jboss.marshalling.MarshallerObjectOutputStream.writeObjectOverride(MarshallerObjectOutputStream.java:50)
at org.jboss.marshalling.river.RiverObjectOutputStream.writeObjectOverride(RiverObjectOutputStream.java:179)
at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:344)
at java.util.HashMap.internalWriteEntries(HashMap.java:1777)
at java.util.HashMap.writeObject(HashMap.java:1354)
at sun.reflect.GeneratedMethodAccessor277.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.jboss.marshalling.reflect.SerializableClass.callWriteObject(SerializableClass.java:271)
at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:976)
at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:854)
at org.jboss.marshalling.river.RiverMarshaller.doWriteFields(RiverMarshaller.java:1032)
at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:988)
at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:854)
at org.jboss.marshalling.AbstractObjectOutput.writeObject(AbstractObjectOutput.java:58)
at org.jboss.marshalling.AbstractMarshaller.writeObject(AbstractMarshaller.java:111)
at org.jenkinsci.plugins.workflow.support.pickles.serialization.RiverWriter.writeObject(RiverWriter.java:140)
at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.saveProgram(CpsThreadGroup.java:453)
at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.saveProgram(CpsThreadGroup.java:427)
at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.saveProgramIfPossible(CpsThreadGroup.java:415)
at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.run(CpsThreadGroup.java:360)
at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.access$100(CpsThreadGroup.java:80)
at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup$2.call(CpsThreadGroup.java:240)
at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup$2.call(CpsThreadGroup.java:228)
at org.jenkinsci.plugins.workflow.cps.CpsVmExecutorService$2.call(CpsVmExecutorService.java:64)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at hudson.remoting.SingleLaneExecutorService$1.run(SingleLaneExecutorService.java:112)
at jenkins.util.ContextResettingExecutorService$1.run(ContextResettingExecutorService.java:28)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: an exception which occurred:
in field locals
in field parent
in field parent
in field parent
in field parent
in field capture
in field def
in field closures
in object org.jenkinsci.plugins.workflow.cps.CpsThreadGroup@112faaa9
</code>```

Finished: FAILURE

答:
A Jenkins Pipeline has been made so robust that it can resume in various failure scenarios, like a master or agent going down. To be able to do this, every intermediate step of the Pipeline is stored, so the Pipeline know where to resume in case of a failure.

To store the Pipeline steps, they must be Serializable. In your case def theJobs = Jenkins.instance.getAllItems(Job); is not serializable since an entry in the list is a FreeStyleProject and that does not implements Serializable.

A way to workaround this is to move all code that uses non-serializable steps into a method and annotate that method with @NonCPS. That signals to the Pipeline to not try and store the result of this method, so it needs not serialize it. Should a failure occur and and the result from this method be needed in a yet to execute step, then this method will be executed again.

In your example:

```<code>node {
    stage('deploy') {
        parallel getBranches()
    }
}

@NonCPS
def getBranches() {
    def branches = [:]
    def theJobs = Jenkins.instance.getAllItems(Job);
    for(int i = 0; i < theJobs.size; i++)
    {
        def jobName= theJobs[i].getName();
        if( jobName =~ /server\-[0-9][0-9]\..*/)
        {
            branches[i] = {
                build job : "${jobName}", parameters: [[$class: 'StringParameterValue', name: 'BRANCH', value: "${BRANCH}"] ]
            }
        }
        jobName = null
    }
    return branches
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I create Job pipeline, and I try get all jobs which matches regexp, and after parallel start. I get exception: java.io.NotSerializableException: hudson.model.FreeStyleProject
Jenkins v 2.5

node {
    stage('deploy') {
        def branches = [:]
        def theJobs = Jenkins.instance.getAllItems(Job);
        for(int i = 0; i < theJobs.size; i++)
        {
            def jobName= theJobs[i].getName();
            if( jobName =~ /server\-[0-9][0-9]\..*/)
            {
                branches[i] = {
                    build job : "${jobName}", parameters: [[$class: 'StringParameterValue', name: 'BRANCH', value: "${BRANCH}"] ]
                }
            }
            jobName = null
        }
        parallel branches
    }
}

Full text exception:

java.io.NotSerializableException: hudson.model.FreeStyleProject
at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:860)
at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:569)
at org.jboss.marshalling.river.BlockMarshaller.doWriteObject(BlockMarshaller.java:65)
at org.jboss.marshalling.river.BlockMarshaller.writeObject(BlockMarshaller.java:56)
at org.jboss.marshalling.MarshallerObjectOutputStream.writeObjectOverride(MarshallerObjectOutputStream.java:50)
at org.jboss.marshalling.river.RiverObjectOutputStream.writeObjectOverride(RiverObjectOutputStream.java:179)
at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:344)
at java.util.HashMap.internalWriteEntries(HashMap.java:1777)
at java.util.HashMap.writeObject(HashMap.java:1354)
at sun.reflect.GeneratedMethodAccessor277.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.jboss.marshalling.reflect.SerializableClass.callWriteObject(SerializableClass.java:271)
at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:976)
at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:854)
at org.jboss.marshalling.river.RiverMarshaller.doWriteFields(RiverMarshaller.java:1032)
at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:988)
at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:854)
at org.jboss.marshalling.river.RiverMarshaller.doWriteFields(RiverMarshaller.java:1032)
at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:988)
at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:967)
at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:967)
at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:854)
at org.jboss.marshalling.river.RiverMarshaller.doWriteFields(RiverMarshaller.java:1032)
at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:988)
at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:967)
at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:854)
at org.jboss.marshalling.river.RiverMarshaller.doWriteFields(RiverMarshaller.java:1032)
at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:988)
at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:967)
at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:854)
at org.jboss.marshalling.river.RiverMarshaller.doWriteFields(RiverMarshaller.java:1032)
at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:988)
at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:967)
at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:854)
at org.jboss.marshalling.river.RiverMarshaller.doWriteFields(RiverMarshaller.java:1032)
at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:988)
at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:854)
at org.jboss.marshalling.river.RiverMarshaller.doWriteFields(RiverMarshaller.java:1032)
at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:988)
at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:967)
at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:854)
at org.jboss.marshalling.river.BlockMarshaller.doWriteObject(BlockMarshaller.java:65)
at org.jboss.marshalling.river.BlockMarshaller.writeObject(BlockMarshaller.java:56)
at org.jboss.marshalling.MarshallerObjectOutputStream.writeObjectOverride(MarshallerObjectOutputStream.java:50)
at org.jboss.marshalling.river.RiverObjectOutputStream.writeObjectOverride(RiverObjectOutputStream.java:179)
at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:344)
at java.util.HashMap.internalWriteEntries(HashMap.java:1777)
at java.util.HashMap.writeObject(HashMap.java:1354)
at sun.reflect.GeneratedMethodAccessor277.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.jboss.marshalling.reflect.SerializableClass.callWriteObject(SerializableClass.java:271)
at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:976)
at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:854)
at org.jboss.marshalling.river.RiverMarshaller.doWriteFields(RiverMarshaller.java:1032)
at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:988)
at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:854)
at org.jboss.marshalling.AbstractObjectOutput.writeObject(AbstractObjectOutput.java:58)
at org.jboss.marshalling.AbstractMarshaller.writeObject(AbstractMarshaller.java:111)
at org.jenkinsci.plugins.workflow.support.pickles.serialization.RiverWriter.writeObject(RiverWriter.java:140)
at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.saveProgram(CpsThreadGroup.java:453)
at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.saveProgram(CpsThreadGroup.java:427)
at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.saveProgramIfPossible(CpsThreadGroup.java:415)
at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.run(CpsThreadGroup.java:360)
at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.access$100(CpsThreadGroup.java:80)
at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup$2.call(CpsThreadGroup.java:240)
at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup$2.call(CpsThreadGroup.java:228)
at org.jenkinsci.plugins.workflow.cps.CpsVmExecutorService$2.call(CpsVmExecutorService.java:64)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at hudson.remoting.SingleLaneExecutorService$1.run(SingleLaneExecutorService.java:112)
at jenkins.util.ContextResettingExecutorService$1.run(ContextResettingExecutorService.java:28)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: an exception which occurred:
in field locals
in field parent
in field parent
in field parent
in field parent
in field capture
in field def
in field closures
in object org.jenkinsci.plugins.workflow.cps.CpsThreadGroup@112faaa9

Finished: FAILURE

Body:
A Jenkins Pipeline has been made so robust that it can resume in various failure scenarios, like a master or agent going down. To be able to do this, every intermediate step of the Pipeline is stored, so the Pipeline know where to resume in case of a failure.

To store the Pipeline steps, they must be Serializable. In your case def theJobs = Jenkins.instance.getAllItems(Job); is not serializable since an entry in the list is a FreeStyleProject and that does not implements Serializable.

A way to workaround this is to move all code that uses non-serializable steps into a method and annotate that method with @NonCPS. That signals to the Pipeline to not try and store the result of this method, so it needs not serialize it. Should a failure occur and and the result from this method be needed in a yet to execute step, then this method will be executed again.

In your example:

node {
    stage('deploy') {
        parallel getBranches()
    }
}

@NonCPS
def getBranches() {
    def branches = [:]
    def theJobs = Jenkins.instance.getAllItems(Job);
    for(int i = 0; i < theJobs.size; i++)
    {
        def jobName= theJobs[i].getName();
        if( jobName =~ /server\-[0-9][0-9]\..*/)
        {
            branches[i] = {
                build job : "${jobName}", parameters: [[$class: 'StringParameterValue', name: 'BRANCH', value: "${BRANCH}"] ]
            }
        }
        jobName = null
    }
    return branches
}


问:
Preventing hardware back button android for React Native
I want to prevent the user from going back to the previous screen. So I added code, but this does not work. Are there any solutions for this? The alert pop up is seen but "return false" does not work.</p>

```<code>componentDidMount() {
   BackAndroid.addEventListener('hardwareBackPress', () => {
     Alert.alert("alert","alert")

      this.props.navigator.pop();

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

答:
If you are using react-natigation then you need to use BackHandler instead of BackAndroid

```<code>import { BackHandler } from 'react-native';

// code

componentDidMount() {
  BackHandler.addEventListener('backPress');
}

// some more code

componentWillUnmount() {
  BackHandler.removeEventListener('backPress');
}
</code>```

Body:
I want to prevent the user from going back to the previous screen. So I added code, but this does not work. Are there any solutions for this? The alert pop up is seen but "return false" does not work.

componentDidMount() {
   BackAndroid.addEventListener('hardwareBackPress', () => {
     Alert.alert("alert","alert")

      this.props.navigator.pop();

       return false;
   });

Body:
If you are using react-natigation then you need to use BackHandler instead of BackAndroid

import { BackHandler } from 'react-native';

// code

componentDidMount() {
  BackHandler.addEventListener('backPress');
}

// some more code

componentWillUnmount() {
  BackHandler.removeEventListener('backPress');
}


问:
Nativescript RadSideDrawer routing issue
Attempting to use NativeScript RadSideDrawer with angular using this example:
https://gist.github.com/NathanWalker/e8f4f7c42af04fc725764a9867936e3d

The following routing error occurs when I navigate to the route /home/feed:

```<code>JS: Unhandled Promise rejection: Cannot find primary outlet to load 'FeedComponent' ; Zone: <root> ;
Task: Promise.then ; Value: Error: Cannot find primary outlet to load 'FeedComponent' Error: Cannot find primary outlet to load 'FeedComponent'
</code>```

The routes that don't use the side-drawer (IE don't have the 'home' parent) work fine.

app.component.ts (root component)

```<code>import { Component } from '@angular/core';

@Component({
  selector: 'ppc-app',
  template: '<StackLayout><page-router-outlet></page-router-outlet></StackLayout>',
  styleUrls: []
})
export class AppComponent {}
</code>```

app.routes.ts

```<code>export const routes = [
  { path: 'home', component: HomeComponent,
    children: [
      { path: 'feed', component: FeedComponent }  <-- this route fails
    ]
  },
  { path: 'login', children: [
    { path: '', component: LoginComponent },  <-- these routes work
    { path: 'type', component: ChooseTypeComponent }  <-- these routes work
  ]}
];
</code>```

home.component.ts

```<code><ActionBar title="Plant Powered Community">
  <ActionItem (tap)="toggle()">
    <!-- example: using font-awesome for hamburger menu but you can use whatever you'd like -->
    <Button class="fa" text=""></Button>
    <!-- however in your project, would be easier to use this plugin: https://github.com/NathanWalker/nativescript-fonticon -->
  </ActionItem>
</ActionBar>
<RadSideDrawer #drawer [transition]="sideDrawerTransition" selectionBehavior="None">
  <StackLayout tkDrawerContent>
    <!-- anything you want in drawer -->
    <!-- for example: -->
    <!-- you want options {exact: true} on the first one because otherwise it would be considered active when 'Other Page' in active as well -->
    <Button text="Home" [nsRouterLink]="['/home']" nsRouterLinkActive="active" [nsRouterLinkActiveOptions]="{exact:true}"></Button>
    <Button text="Other Page" [nsRouterLink]="['/home/otherPath']" nsRouterLinkActive="active"></Button>
  </StackLayout>
  <StackLayout tkMainContent>
    <router-outlet></router-outlet>
  </StackLayout>
</RadSideDrawer>
</code>```

答:
Probably is the structure in the file app.routes.ts

```<code>export const APP_ROUTES: Routes = [
{
    path: '',
    redirectTo: '/home/feed',
    pathMatch: 'full'
},
{
    path: "home",
    component: HomeComponent,
        children: [
            {path: "login", component: LoginComponent},
            {path: 'type', component: ChooseTypeComponent },
            {path: 'feed', component: FeedComponent }
        ]
},
</code>```

];

I have created a simple RadSideDrawer example, see if it helps.

https://github.com/simonettoa/nativescript-RadSideDrawer

Body:
Attempting to use NativeScript RadSideDrawer with angular using this example:
https://gist.github.com/NathanWalker/e8f4f7c42af04fc725764a9867936e3d

The following routing error occurs when I navigate to the route /home/feed:

JS: Unhandled Promise rejection: Cannot find primary outlet to load 'FeedComponent' ; Zone: <root> ;
Task: Promise.then ; Value: Error: Cannot find primary outlet to load 'FeedComponent' Error: Cannot find primary outlet to load 'FeedComponent'

The routes that don't use the side-drawer (IE don't have the 'home' parent) work fine.

app.component.ts (root component)

import { Component } from '@angular/core';

@Component({
  selector: 'ppc-app',
  template: '<StackLayout><page-router-outlet></page-router-outlet></StackLayout>',
  styleUrls: []
})
export class AppComponent {}

app.routes.ts

export const routes = [
  { path: 'home', component: HomeComponent,
    children: [
      { path: 'feed', component: FeedComponent }  <-- this route fails
    ]
  },
  { path: 'login', children: [
    { path: '', component: LoginComponent },  <-- these routes work
    { path: 'type', component: ChooseTypeComponent }  <-- these routes work
  ]}
];

home.component.ts

<ActionBar title="Plant Powered Community">
  <ActionItem (tap)="toggle()">

    <Button class="fa" text=""></Button>

  </ActionItem>
</ActionBar>
<RadSideDrawer #drawer [transition]="sideDrawerTransition" selectionBehavior="None">
  <StackLayout tkDrawerContent>

    <Button text="Home" [nsRouterLink]="['/home']" nsRouterLinkActive="active" [nsRouterLinkActiveOptions]="{exact:true}"></Button>
    <Button text="Other Page" [nsRouterLink]="['/home/otherPath']" nsRouterLinkActive="active"></Button>
  </StackLayout>
  <StackLayout tkMainContent>
    <router-outlet></router-outlet>
  </StackLayout>
</RadSideDrawer>

Body:
Probably is the structure in the file app.routes.ts

export const APP_ROUTES: Routes = [
{
    path: '',
    redirectTo: '/home/feed',
    pathMatch: 'full'
},
{
    path: "home",
    component: HomeComponent,
        children: [
            {path: "login", component: LoginComponent},
            {path: 'type', component: ChooseTypeComponent },
            {path: 'feed', component: FeedComponent }
        ]
},

];

I have created a simple RadSideDrawer example, see if it helps.

https://github.com/simonettoa/nativescript-RadSideDrawer


问:
How to get all uploaded files size?
I have seven input files to attach the image.when i click the submit button,upload file size will be limited to 10 MB (including all images).</p>

```<code><input name="a" id="file-0" type="file" class="dropify"/>
<input name="b" id="file-0" type="file" class="dropify"/>
<input name="c" id="file-0" type="file" class="dropify"/>
</code>```

答:
```<code>$('form').submit(function( e ) {
    if(!($('#file')[0].files[0].size < 10485760 && get_extension($('#file').val()) == 'jpg')) { // 10 MB (this size is in bytes)
        //Prevent default and display error
        alert("File is wrong type or over 10Mb in size!");
        e.preventDefault();
    }
});
</code>```

OR

```<code><form method="post" enctype="multipart/form-data" action="upload.php">
    <input type="file" name="file" id="file" multiple/>
    <input type="submit" name="submit" value="Submit" />
</form>

<script>
document.forms[0].addEventListener('submit', function( evt ) {
    var file = document.getElementById('file').files[0];

    if(file && file.size < 10485760) { // 10 MB (this size is in bytes)
        //Submit form
    } else {
        //Prevent default and display error
        evt.preventDefault();
    }
}, false);
</script>
</code>```

Fiddle: http://jsfiddle.net/go4vaibhav/msuL0yta/33/

Title: How to get all uploaded files size?

Body:
I have seven input files to attach the image.when i click the submit button,upload file size will be limited to 10 MB (including all images).

<input name="a" id="file-0" type="file" class="dropify"/>
<input name="b" id="file-0" type="file" class="dropify"/>
<input name="c" id="file-0" type="file" class="dropify"/>

Body:
$('form').submit(function( e ) {
    if(!($('#file')[0].files[0].size < 10485760 && get_extension($('#file').val()) == 'jpg')) { // 10 MB (this size is in bytes)
        //Prevent default and display error
        alert("File is wrong type or over 10Mb in size!");
        e.preventDefault();
    }
});

OR

<form method="post" enctype="multipart/form-data" action="upload.php">
    <input type="file" name="file" id="file" multiple/>
    <input type="submit" name="submit" value="Submit" />
</form>

<script>
document.forms[0].addEventListener('submit', function( evt ) {
    var file = document.getElementById('file').files[0];

    if(file && file.size < 10485760) { // 10 MB (this size is in bytes)
        //Submit form
    } else {
        //Prevent default and display error
        evt.preventDefault();
    }
}, false);
</script>

Fiddle: http://jsfiddle.net/go4vaibhav/msuL0yta/33/


问:
Send JSON with PHP
I want to follow with Instagram API in PHP, but it shows an error:

Fatal error: Uncaught Error: Call to undefined function sendPostData() in /storage/h11/133/1908133/public_html/index.php:13 Stack trace: #0 {main} thrown in /storage/h11/133/1908133/public_html/index.php on line 13
```

<p>My code: </p>

```

<title>indexer</title>

<?php
$access = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
$user_id = 'xxxxxxxx';
$url= 'https://api.instagram.com/v1/users/'.$user_id.'/relationship?access_token='.$access;
$data = 'action=follow';
$resultObj = json_decode(sendPostData($url,$data));
print_r($resultObj);
?>
```

答:
You can try this

```<code>$resultObj = json_decode(file_get_contents($url,$data));
</code>```

Hope it will work

Title: Send JSON with PHP

Body:
I want to follow with Instagram API in PHP, but it shows an error:

Fatal error: Uncaught Error: Call to undefined function sendPostData() in /storage/h11/133/1908133/public_html/index.php:13 Stack trace: #0 {main} thrown in /storage/h11/133/1908133/public_html/index.php on line 13

My code:

<title>indexer</title>

<?php
$access = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
$user_id = 'xxxxxxxx';
$url= 'https://api.instagram.com/v1/users/'.$user_id.'/relationship?access_token='.$access;
$data = 'action=follow';
$resultObj = json_decode(sendPostData($url,$data));
print_r($resultObj);
?>

Body:
You can try this

$resultObj = json_decode(file_get_contents($url,$data));

Hope it will work


问:
Vuejs 2 image slider
I have used flexslider in angularjs before. I am working on a laravel 5.3 project with vue.js 2. I have found a way to create a slider like in this jsfiddle but what I want is to have arrows on the images like how flexslider does it.

```<code>    new Vue({
    el: 'image-slider',
    data: {
        images: ['http://i.imgur.com/vYdoAKu.jpg', 'http://i.imgur.com/PUD9HQL.jpg', 'http://i.imgur.com/Lfv18Sb.jpg', 'http://i.imgur.com/tmVJtna.jpg', 'http://i.imgur.com/ZfFAkWZ.jpg'],
        currentNumber: 0,
        timer: null
    },

    ready: function () {
        this.startRotation();
    },

    methods: {
        startRotation: function() {
            this.timer = setInterval(this.next, 3000);
        },

        stopRotation: function() {
            clearTimeout(this.timer);
            this.timer = null;
        },

        next: function() {
            this.currentNumber += 1
        },
        prev: function() {
            this.currentNumber -= 1
        }
    }
    });
</code>```

Is there a package that does this or is there a way to modify the code to allow for that?

答:
At first I used the Zurb Foundation orbit but I encountered issues when passing multiple images from the database. So I ended up using slick carousel

I used npm to install then used require(webpack) like this:
slick = require('slick-carousel');

Then initialised it like this:

```<code>   updated: function () {
        $('.gallery').slick({
            autoplay: true,
            dots: false,
            arrows: true,
            responsive: [{
                breakpoint: 500,
                settings: {
                    dots: false,
                    arrows: true,
                    infinite: true,
                    slidesToShow: 1
                }
            }]
        });
</code>```

Then I had to add the scss files when compiling my SASS files like this:

```<code>  mix.sass([
    'app.scss',
    '../../../node_modules/slick-carousel/slick/slick.scss',
    '../../../node_modules/slick-carousel/slick/slick-theme.scss']);
</code>```

And then just render the images using a v-for loop:

```<code><section class='gallery' v-if="images">
    <div v-for="img in images">
        <img :src="img" class="image">
    </div>
</section>
</code>```

Title: Vuejs 2 image slider

Body:
I have used flexslider in angularjs before. I am working on a laravel 5.3 project with vue.js 2. I have found a way to create a slider like in this jsfiddle but what I want is to have arrows on the images like how flexslider does it.

    new Vue({
    el: 'image-slider',
    data: {
        images: ['http://i.imgur.com/vYdoAKu.jpg', 'http://i.imgur.com/PUD9HQL.jpg', 'http://i.imgur.com/Lfv18Sb.jpg', 'http://i.imgur.com/tmVJtna.jpg', 'http://i.imgur.com/ZfFAkWZ.jpg'],
        currentNumber: 0,
        timer: null
    },

    ready: function () {
        this.startRotation();
    },

    methods: {
        startRotation: function() {
            this.timer = setInterval(this.next, 3000);
        },

        stopRotation: function() {
            clearTimeout(this.timer);
            this.timer = null;
        },

        next: function() {
            this.currentNumber += 1
        },
        prev: function() {
            this.currentNumber -= 1
        }
    }
    });

Is there a package that does this or is there a way to modify the code to allow for that?

Body:
At first I used the Zurb Foundation orbit but I encountered issues when passing multiple images from the database. So I ended up using slick carousel

I used npm to install then used require(webpack) like this:
slick = require('slick-carousel');

Then initialised it like this:

   updated: function () {
        $('.gallery').slick({
            autoplay: true,
            dots: false,
            arrows: true,
            responsive: [{
                breakpoint: 500,
                settings: {
                    dots: false,
                    arrows: true,
                    infinite: true,
                    slidesToShow: 1
                }
            }]
        });

Then I had to add the scss files when compiling my SASS files like this:

  mix.sass([
    'app.scss',
    '../../../node_modules/slick-carousel/slick/slick.scss',
    '../../../node_modules/slick-carousel/slick/slick-theme.scss']);

And then just render the images using a v-for loop:

<section class='gallery' v-if="images">
    <div v-for="img in images">
        <img :src="img" class="image">
    </div>
</section>


问:
What is the best way to fetch mails for a client app?
I'm creating an e-mail client for iOS and before the start of working on it, I want to select the best architecture for it.

For example, at the first stage, I want to connect Gmail. I searched and found that Google has a ready library for doing that, so I can just connect the library and fetch my emails.

Another way of doing that is fetching emails from the API in my web server and later to take these emails from my server.

The main purpose is not just to fetch emails, but to be able later to add some new filtrations to it or some other functionalities, maybe machine learning technologies for better personalisation, etc.

Also, I want to support multiple email servers(Gmail, Yahoo, Hotmail, etc.)

What do you advise me to choose, to fetch from my own server or directly from the email servers? I also understand the security issues in the case of using my own servers.

Your feedbacks will help me a lot! Thanks in advance!

答:
You shouldn't use your own server for this task. You just don't need it. It's less secure and I'm pretty sure, that some of your clients will dislike the fact, that you can store their mails on your own server.

If you want to support multiple email server providers, then you should use IMAP protocol for receiving mails and SMTP for sending. Also, in some cases, you can use OAuth2 as authentication method, so you don't need to ask user to enter his credentials in your application.

I recommend you to use some open source libraries for working with IMAP and SMTP, because implementing this protocols by self can be complicated.


问:
avoiding using .bind with ES6 =>
I'm new to React and the concepts are still new to me. I'm working on this example and I would like to know if it would be possible to re-write it in another way and avoid using .bind altogether. The goal here is just to minimize the code written required as much as possible!

Full example can be found here:

https://codepen.io/akamali/pen/awvqeM

The component simply render a menu list and when you click on an item it highlight the selected text.

ES5

```<code><ul className='languages'>
      {languages.map(function (lang) {
        return (
          <li
            style={lang === this.state.selectedLanguage ? {color: '#d0021b'} : null}
            onClick={this.updateLanguage.bind(null, lang)}
            key={lang}>
              {lang}
          </li>
        )
      }, this)}
    </ul>
</code>```

**ES6 => **

```<code><ul className='languages'>
      {languages.map(lang => {
        return (
          <li
            style={lang === this.state.selectedLanguage ? {color: '#d0021b'} : null}
            onClick={this.updateLanguage.bind(null, lang)}
            key={lang}>
              {lang}
          </li>
        )
      },)}
    </ul>
</code>```

答:
First you bind to null, if updateLanguage has code like this :

```<code>updateLanguage(lang){
    this.x;
}
</code>```

It will throw a null pointer exception, you probably wanted to bind to this.

Now why would anyone bind ? to explain this look at example definition of updateLanguage :

```<code>updateLanguage(lang){
    this.setState({language: lang});
}
</code>```

In this function we want this to be the React component as we're using setState here.

But when you register events with this function then whoever triggers the event will be this inside updateLanguage's body, so this above will be e.g. li which doesn't have setState.

By binding you make sure this will be the component, anyway you can get rid of binding by doing this :

```<code><li
    onClick={() => this.updateLanguage(lang)}
</li>
</code>```

Because when registering it as an arrow function we're actually registering a closure which closes over this which is the component here, I leave it to you whether you like this style or not.

Another way is to use propery syntax initializer e.g. :

```<code>updateLanguage : (lang) => {
}
</code>```

And then

```<code>  <li
      onClick={this.updateLanguage(lang)}
  </li>
</code>```

These ways are mentioned in React Docs by the way, see here :
https://facebook.github.io/react/docs/handling-events.html

Title: avoiding using .bind with ES6 =>

Body:
I'm new to React and the concepts are still new to me. I'm working on this example and I would like to know if it would be possible to re-write it in another way and avoid using .bind altogether. The goal here is just to minimize the code written required as much as possible!

Full example can be found here:

https://codepen.io/akamali/pen/awvqeM

The component simply render a menu list and when you click on an item it highlight the selected text.

ES5

      {languages.map(function (lang) {
        return (

              {lang}

        )
      }, this)}

**ES6 => **

      {languages.map(lang => {
        return (

              {lang}

        )
      },)}

Body:
First you bind to null, if updateLanguage has code like this :

updateLanguage(lang){
    this.x;
}

It will throw a null pointer exception, you probably wanted to bind to this.

Now why would anyone bind ? to explain this look at example definition of updateLanguage :

updateLanguage(lang){
    this.setState({language: lang});
}

In this function we want this to be the React component as we're using setState here.

But when you register events with this function then whoever triggers the event will be this inside updateLanguage's body, so this above will be e.g. li which doesn't have setState.

By binding you make sure this will be the component, anyway you can get rid of binding by doing this :

<li
    onClick={() => this.updateLanguage(lang)}
</li>

Because when registering it as an arrow function we're actually registering a closure which closes over this which is the component here, I leave it to you whether you like this style or not.

Another way is to use propery syntax initializer e.g. :

updateLanguage : (lang) => {
}

And then

  <li
      onClick={this.updateLanguage(lang)}
  </li>

These ways are mentioned in React Docs by the way, see here :
https://facebook.github.io/react/docs/handling-events.html


问:
undefined method `action' for ArticlesController(Table doesn't exist):Class - Ruby on Rails error
I got an error notification but I dont know where to search.
See attachement.

Where's the file with the included error?
I did the following instruction:
http://guides.rubyonrails.org/getting_started.html

Here's my code:

```<code>class ArticlesController < ActiveRecord::Base
  def index
    @articles = Article.all
  end

  def show
    @article = Article.find(params[:id])
  end

  def new
    @article = Article.new
  end

  def edit
    @article = Article.find(params[:id])
  end

  def create
    @article = Article.new(article_params)

    if @article.save
      redirect_to @article
    else
      render 'new'
    end
  end

  def update
    @article = Article.find(params[:id])

    if @article.update(article_params)
      redirect_to @article
    else
      render 'edit'
    end
  end

  def destroy
    @article = Article.find(params[:id])
    @article.destroy

    redirect_to articles_path
  end

  private #description
    def article_params #description
      params.require(:article).permit(:title, :text)
    end #here's the end
end
</code>```

答:
If application_controller.rb is not present in your project, then create one with the following code.

class ApplicationController < ActionController::Base

end

Body:
I got an error notification but I dont know where to search.
See attachement.

Where's the file with the included error?
I did the following instruction:
http://guides.rubyonrails.org/getting_started.html

Here's my code:

class ArticlesController < ActiveRecord::Base
  def index
    @articles = Article.all
  end

  def show
    @article = Article.find(params[:id])
  end

  def new
    @article = Article.new
  end

  def edit
    @article = Article.find(params[:id])
  end

  def create
    @article = Article.new(article_params)

    if @article.save
      redirect_to @article
    else
      render 'new'
    end
  end

  def update
    @article = Article.find(params[:id])

    if @article.update(article_params)
      redirect_to @article
    else
      render 'edit'
    end
  end

  def destroy
    @article = Article.find(params[:id])
    @article.destroy

    redirect_to articles_path
  end

  private #description
    def article_params #description
      params.require(:article).permit(:title, :text)
    end #here's the end
end


问:
JSON Parsing using Swift 3
I am calling a soap service in my application. I am getting this response in JSON from server

```<code>{
  "CustomerName":"Muneer Ahmad/ Ejaz Ahmad (User)  ",
  "IsCorporate":false,
  "ID":48,
  "Name":"Muneer Ahmad/ Ejaz Ahmad (User)  ",
  "GroupID":null,
  "GroupName":null,
  "CustomerID":48
}
</code>```

I have tried what online tutorial suggests but I am not able to parse data. It gives me error that "Invalid value around character 0." My Code is this

```<code> let is_URL: String = "http://labs2.unitedtracker.com/WTService.asmx?op=GetTerminalNumber"

    let lobj_Request = NSMutableURLRequest(url: NSURL(string: is_URL)! as URL)
    let session = URLSession.shared

    lobj_Request.httpMethod = "POST"
    lobj_Request.httpBody = is_SoapMessage.data(using: String.Encoding.utf8)
    lobj_Request.addValue("labs2.unitedtracker.com", forHTTPHeaderField: "Host")
    lobj_Request.addValue("text/xml; charset=utf-8", forHTTPHeaderField: "Content-Type")
    lobj_Request.addValue(String(is_SoapMessage.characters.count), forHTTPHeaderField: "Content-Length")
    lobj_Request.addValue("http://tempuri.org/GetTerminalNumber", forHTTPHeaderField: "SOAPAction")

    let task = session.dataTask(with: lobj_Request as URLRequest, completionHandler: {data, response, error -> Void in

        do {
            if let data = data,
                let json = try JSONSerialization.jsonObject(with: data) as? [String: Any],
                let customerID = json["CustomerID"] as? [[String: Any]] {
                print(customerID)
            }
        } catch {
            print("Error deserializing JSON: \(error)")
        }

        if error != nil
        {
            print("Error: " + String(describing: error))
        }
    })
    task.resume()
</code>```

Can anyone suggest me what is wrong i m doing. And how should be such JSON response from Soap Service should be parsed.

Here is complete response from my Server.

```<code><?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><GetAuthenticateUserResponse xmlns="http://tempuri.org/"><GetAuthenticateUserResult>[{"CustomerName":"Muneer Ahmad/ Ejaz Ahmad (User)  ","IsCorporate":false,"ID":48,"Name":"Muneer Ahmad/ Ejaz Ahmad (User)  ","GroupID":null,"GroupName":null,"CustomerID":48}]</GetAuthenticateUserResult></GetAuthenticateUserResponse></soap:Body></soap:Envelope>
</code>```

答:
```<code>lobj_Request.addValue("text/xml; charset=utf-8", forHTTPHeaderField: "Content-Type")
</code>```

How do you guarantee that server will return json as response ? It seems like that it will return text/xml as response.

About JSON parsing, I suggest SwiftyJSON.

More suggesions

Years ago, I had use a soap client engine, it will parse wsdl to objective-c codes. Today, maybe some tools could help you to generate Swift codes from wsdl in order to communicate with soap server.

About wsdl to swift client generator

https://stackoverflow.com/a/32798709/419348
The author had post answer about wsdltoswift.

http://wsdl2swift.com wsdl2swift url.

Title: JSON Parsing using Swift 3

Body:
I am calling a soap service in my application. I am getting this response in JSON from server

{
  "CustomerName":"Muneer Ahmad/ Ejaz Ahmad (User)  ",
  "IsCorporate":false,
  "ID":48,
  "Name":"Muneer Ahmad/ Ejaz Ahmad (User)  ",
  "GroupID":null,
  "GroupName":null,
  "CustomerID":48
}

I have tried what online tutorial suggests but I am not able to parse data. It gives me error that "Invalid value around character 0." My Code is this

 let is_URL: String = "http://labs2.unitedtracker.com/WTService.asmx?op=GetTerminalNumber"

    let lobj_Request = NSMutableURLRequest(url: NSURL(string: is_URL)! as URL)
    let session = URLSession.shared

    lobj_Request.httpMethod = "POST"
    lobj_Request.httpBody = is_SoapMessage.data(using: String.Encoding.utf8)
    lobj_Request.addValue("labs2.unitedtracker.com", forHTTPHeaderField: "Host")
    lobj_Request.addValue("text/xml; charset=utf-8", forHTTPHeaderField: "Content-Type")
    lobj_Request.addValue(String(is_SoapMessage.characters.count), forHTTPHeaderField: "Content-Length")
    lobj_Request.addValue("http://tempuri.org/GetTerminalNumber", forHTTPHeaderField: "SOAPAction")

    let task = session.dataTask(with: lobj_Request as URLRequest, completionHandler: {data, response, error -> Void in

        do {
            if let data = data,
                let json = try JSONSerialization.jsonObject(with: data) as? [String: Any],
                let customerID = json["CustomerID"] as? [[String: Any]] {
                print(customerID)
            }
        } catch {
            print("Error deserializing JSON: \(error)")
        }

        if error != nil
        {
            print("Error: " + String(describing: error))
        }
    })
    task.resume()

Can anyone suggest me what is wrong i m doing. And how should be such JSON response from Soap Service should be parsed.

Here is complete response from my Server.

<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><GetAuthenticateUserResponse xmlns="http://tempuri.org/"><GetAuthenticateUserResult>[{"CustomerName":"Muneer Ahmad/ Ejaz Ahmad (User)  ","IsCorporate":false,"ID":48,"Name":"Muneer Ahmad/ Ejaz Ahmad (User)  ","GroupID":null,"GroupName":null,"CustomerID":48}]</GetAuthenticateUserResult></GetAuthenticateUserResponse></soap:Body></soap:Envelope>

Body:
lobj_Request.addValue("text/xml; charset=utf-8", forHTTPHeaderField: "Content-Type")

How do you guarantee that server will return json as response ? It seems like that it will return text/xml as response.

About JSON parsing, I suggest SwiftyJSON.

More suggesions

Years ago, I had use a soap client engine, it will parse wsdl to objective-c codes. Today, maybe some tools could help you to generate Swift codes from wsdl in order to communicate with soap server.

About wsdl to swift client generator

https://stackoverflow.com/a/32798709/419348
The author had post answer about wsdltoswift.

http://wsdl2swift.com wsdl2swift url.


问:
Concatenating String in LINQ-to-Entities
This code works if I take out

" " + p.MIDDLE_NAME

Thus the remaining code looks like:

p.FIRST_NAME + " " + p.LAST_NAME

Maybe LINQ-to-Entities just doesn't support concatenating more than two strings at a time?

```<code>    Protected Sub btnFilter_Click(sender As Object, e As EventArgs) Handles btnFilter.Click
    Dim dbContext As Campus6Entities = New Campus6Entities
    Using dbContext
        Dim find_students = From p In dbContext.PEOPLE _
                            Let Full_Name = p.FIRST_NAME + " " + p.MIDDLE_NAME + " " + p.LAST_NAME _
                            Where Full_Name = txtFilterText.Text _
                            Select p.FIRST_NAME, p.MIDDLE_NAME, p.LAST_NAME, p.PEOPLE_CODE_ID

        rptrFilteredStudents.DataSource = find_students
        rptrFilteredStudents.DataBind()
    End Using
End Sub
</code>```

答:
I got something similar working like this - in C# but the solution should work in VB too:

```<code>string.Concat(string.Concat(p.FIRST_NAME, " ", p.MIDDLE_NAME, " "), p.LAST_NAME)
</code>```

It doesn't support over 4 items so you have to nest them.

ContentLicense: CC BY-SA 2.5

Body:
This code works if I take out

" " + p.MIDDLE_NAME

Thus the remaining code looks like:

p.FIRST_NAME + " " + p.LAST_NAME

Maybe LINQ-to-Entities just doesn't support concatenating more than two strings at a time?

    Protected Sub btnFilter_Click(sender As Object, e As EventArgs) Handles btnFilter.Click
    Dim dbContext As Campus6Entities = New Campus6Entities
    Using dbContext
        Dim find_students = From p In dbContext.PEOPLE _
                            Let Full_Name = p.FIRST_NAME + " " + p.MIDDLE_NAME + " " + p.LAST_NAME _
                            Where Full_Name = txtFilterText.Text _
                            Select p.FIRST_NAME, p.MIDDLE_NAME, p.LAST_NAME, p.PEOPLE_CODE_ID

        rptrFilteredStudents.DataSource = find_students
        rptrFilteredStudents.DataBind()
    End Using
End Sub

Body:
I got something similar working like this - in C# but the solution should work in VB too:

string.Concat(string.Concat(p.FIRST_NAME, " ", p.MIDDLE_NAME, " "), p.LAST_NAME)

It doesn't support over 4 items so you have to nest them.


问:
I am using composer to autoload the file but when i run my code he is not able to find the class
When I run this I got error

PHP Fatal error:  Uncaught Error: Class 'ashwini123\queyHelper' not found in /home/ashwinibhandare/dev/training/ComposerBasics/src/queryHelper/ViewCustomerData.php:4

Stack trace:

0 /home/ashwinibhandare/dev/training/ComposerBasics/public/index.php(4): include()

1 {main}

```<code>  thrown in /home/ashwinibhandare/dev/training/ComposerBasics/src/queryHelper/ViewCustomerData.php on line 4
</code>```

In my project there are two folders public and src .in public folder there is index.php file and in src contains one more folder queryHelper which contains database connection file, viewCustomerdata.php file and queryhelper.php file. I have added the namespace to DbConnection.php file. Why do I get this error? As I am using namespace correctly?

composer.json

```<code>{
    "name": "ashwinibhandare/composer-basics",
    "authors": [
        {
            "name": "Ashwini Bhandare",
            "email": "a.bhandare@easternenterprise.com"
        }
    ],

     "require": {},
    "autoload": {
        "psr-4": {"ashwini123\\": "src/queryHelper"}
    }
}
</code>```

index.php

```<code><?php
require_once '../vendor/autoload.php';

include '../src/queryHelper/ViewCustomerData.php';
?>
ViewCustomerData.php
<?php
use ashwini123\queyHelper;

$Crude=new queyHelper();
$sql="select * from users";
$selectData=$Crude->getData($sql);

?>
</code>```

queryHelper.php

```<code><?php
use ashwini123\DbConnection;
class queyHelper extends DbConnection {

    public function __construct()
    {

         parent::__construct();

    }

    public function getData($query)
    {
      try {

            $sql=$this->connection->prepare($query);
            $sql->execute();
            $count = $sql->rowCount();

            if($count)
            {
                $selectData =  $sql->fetchAll(PDO::FETCH_ASSOC);
            }

            return $selectData;
        }
        catch(PDOException $e) {
           die("Failed: " . $e->getMessage());
        }
    }
}
?>
</code>```

DbConnection.php

```<code><?php
namespace ashwini123;
class DbConnection {

    public $connection;

    public function __construct()
    {
        if (!isset($this->connection)) {

            try {
                    $this->connection = new PDO("mysql:host=localhost;dbname=crudOperation",'root', 'root');
                    $this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                    return $this->connection;

                }
                catch(PDOException $e) {

                    die("Failed to connect with MySQL: " . $e->getMessage());

                }

                } else {
                            echo "Connection failed";
                        }
    }
}
?>
</code>```

答:
You have a typo

```<code>ashwini123\queyHelper
</code>```

should be

```<code> ashwini123\queryHelper
</code>```

Moreover modify PSR-4 mapping as follows

```<code>"psr-4": {"ashwini123\\": "src/"}
</code>```

Body:
When I run this I got error

PHP Fatal error:  Uncaught Error: Class 'ashwini123\queyHelper' not found in /home/ashwinibhandare/dev/training/ComposerBasics/src/queryHelper/ViewCustomerData.php:4

Stack trace:

0 /home/ashwinibhandare/dev/training/ComposerBasics/public/index.php(4): include()

1 {main}

  thrown in /home/ashwinibhandare/dev/training/ComposerBasics/src/queryHelper/ViewCustomerData.php on line 4

In my project there are two folders public and src .in public folder there is index.php file and in src contains one more folder queryHelper which contains database connection file, viewCustomerdata.php file and queryhelper.php file. I have added the namespace to DbConnection.php file. Why do I get this error? As I am using namespace correctly?

composer.json

{
    "name": "ashwinibhandare/composer-basics",
    "authors": [
        {
            "name": "Ashwini Bhandare",
            "email": "a.bhandare@easternenterprise.com"
        }
    ],

     "require": {},
    "autoload": {
        "psr-4": {"ashwini123\\": "src/queryHelper"}
    }
}

index.php

<?php
require_once '../vendor/autoload.php';

include '../src/queryHelper/ViewCustomerData.php';
?>
ViewCustomerData.php
<?php
use ashwini123\queyHelper;

$Crude=new queyHelper();
$sql="select * from users";
$selectData=$Crude->getData($sql);

?>

queryHelper.php

<?php
use ashwini123\DbConnection;
class queyHelper extends DbConnection {

    public function __construct()
    {

         parent::__construct();

    }

    public function getData($query)
    {
      try {

            $sql=$this->connection->prepare($query);
            $sql->execute();
            $count = $sql->rowCount();

            if($count)
            {
                $selectData =  $sql->fetchAll(PDO::FETCH_ASSOC);
            }

            return $selectData;
        }
        catch(PDOException $e) {
           die("Failed: " . $e->getMessage());
        }
    }
}
?>

DbConnection.php

<?php
namespace ashwini123;
class DbConnection {

    public $connection;

    public function __construct()
    {
        if (!isset($this->connection)) {

            try {
                    $this->connection = new PDO("mysql:host=localhost;dbname=crudOperation",'root', 'root');
                    $this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                    return $this->connection;

                }
                catch(PDOException $e) {

                    die("Failed to connect with MySQL: " . $e->getMessage());

                }

                } else {
                            echo "Connection failed";
                        }
    }
}
?>

Body:
You have a typo

ashwini123\queyHelper

should be

 ashwini123\queryHelper

Moreover modify PSR-4 mapping as follows

"psr-4": {"ashwini123\\": "src/"}


问:
label_keys type error on DNNCLassifier Tensorflow
I want to embed labels into a DNNClassifier model in Tensorflow.
Unlike the documentation example, here , I get the following error message:

```<code>label_keys_values = ["satan", "ipsweep", "nmap", "portsweep"]
m = tf.contrib.learn.DNNClassifier(model_dir=model_dir,
                                  feature_columns=deep_columns,
                                  n_classes=4,
                                  hidden_units=[12, 4],
                                  label_keys=label_keys_values)
m.fit(input_fn=train_input_fn, steps=200)
</code>```

File "embedding_model_probe.py", line 118, in
      m.fit(input_fn=train_input_fn, steps=200)
    File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/util/deprecation.py", line 281, in new_func
      return func(*args, **kwargs)
    File "/usr/local/lib/python2.7/dist-packages/tensorflow/contrib/learn/python/learn/estimators/estimator.py", line 430, in fit
      loss = self._train_model(input_fn=input_fn, hooks=hooks)
    File "/usr/local/lib/python2.7/dist-packages/tensorflow/contrib/learn/python/learn/estimators/estimator.py", line 927, in _train_model
      model_fn_ops = self._get_train_ops(features, labels)
    File "/usr/local/lib/python2.7/dist-packages/tensorflow/contrib/learn/python/learn/estimators/estimator.py", line 1132, in _get_train_ops
      return self._call_model_fn(features, labels, model_fn_lib.ModeKeys.TRAIN)
    File "/usr/local/lib/python2.7/dist-packages/tensorflow/contrib/learn/python/learn/estimators/estimator.py", line 1103, in _call_model_fn
      model_fn_results = self._model_fn(features, labels, **kwargs)
    File "/usr/local/lib/python2.7/dist-packages/tensorflow/contrib/learn/python/learn/estimators/dnn.py", line 180, in _dnn_model_fn
      logits=logits)
    File "/usr/local/lib/python2.7/dist-packages/tensorflow/contrib/learn/python/learn/estimators/head.py", line 1004, in create_model_fn_ops
      labels = self._transform_labels(mode=mode, labels=labels)
    File "/usr/local/lib/python2.7/dist-packages/tensorflow/contrib/learn/python/learn/estimators/head.py", line 1033, in _transform_labels
      "label_ids": table.lookup(labels_tensor),
    File "/usr/local/lib/python2.7/dist-packages/tensorflow/contrib/lookup/lookup_ops.py", line 179, in lookup
      (self._key_dtype, keys.dtype))
    TypeError: Signature mismatch. Keys must be dtype

< dtype: 'string'>, got < dtype: 'int64'>

On the other hand, if I make the label_key_values column a numpy.array, I will get the following error:

```<code>label_keys_values = np.array(["satan", "ipsweep", "nmap", "portsweep"], dtype='string')
</code>```

Traceback (most recent call last):
    File "embedding_model_probe.py", line 116, in
      label_keys=label_keys_values)
    File "/usr/local/lib/python2.7/dist-packages/tensorflow/contrib/learn/python/learn/estimators/dnn.py", line 337, in init
      label_keys=label_keys),
    File "/usr/local/lib/python2.7/dist-packages/tensorflow/contrib/learn/python/learn/estimators/head.py", line 331, in multi_class_head
      label_keys=label_keys)
    File "/usr/local/lib/python2.7/dist-packages/tensorflow/contrib/learn/python/learn/estimators/head.py", line 986, in init
      if label_keys and len(label_keys) != n_classes:
  ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

答:
I got the solution. As the official documentation says here :

"If the user specifies label_keys in constructor, labels must be strings from the label_keys vocabulary."

In my case, I transformed the label column from the training and testing set into an one-hot vector(integer values) and the values from label_keys_values array did not match with them.

Body:
I want to embed labels into a DNNClassifier model in Tensorflow.
Unlike the documentation example, here , I get the following error message:

label_keys_values = ["satan", "ipsweep", "nmap", "portsweep"]
m = tf.contrib.learn.DNNClassifier(model_dir=model_dir,
                                  feature_columns=deep_columns,
                                  n_classes=4,
                                  hidden_units=[12, 4],
                                  label_keys=label_keys_values)
m.fit(input_fn=train_input_fn, steps=200)

File "embedding_model_probe.py", line 118, in
      m.fit(input_fn=train_input_fn, steps=200)
    File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/util/deprecation.py", line 281, in new_func
      return func(*args, **kwargs)
    File "/usr/local/lib/python2.7/dist-packages/tensorflow/contrib/learn/python/learn/estimators/estimator.py", line 430, in fit
      loss = self._train_model(input_fn=input_fn, hooks=hooks)
    File "/usr/local/lib/python2.7/dist-packages/tensorflow/contrib/learn/python/learn/estimators/estimator.py", line 927, in _train_model
      model_fn_ops = self._get_train_ops(features, labels)
    File "/usr/local/lib/python2.7/dist-packages/tensorflow/contrib/learn/python/learn/estimators/estimator.py", line 1132, in _get_train_ops
      return self._call_model_fn(features, labels, model_fn_lib.ModeKeys.TRAIN)
    File "/usr/local/lib/python2.7/dist-packages/tensorflow/contrib/learn/python/learn/estimators/estimator.py", line 1103, in _call_model_fn
      model_fn_results = self._model_fn(features, labels, **kwargs)
    File "/usr/local/lib/python2.7/dist-packages/tensorflow/contrib/learn/python/learn/estimators/dnn.py", line 180, in _dnn_model_fn
      logits=logits)
    File "/usr/local/lib/python2.7/dist-packages/tensorflow/contrib/learn/python/learn/estimators/head.py", line 1004, in create_model_fn_ops
      labels = self._transform_labels(mode=mode, labels=labels)
    File "/usr/local/lib/python2.7/dist-packages/tensorflow/contrib/learn/python/learn/estimators/head.py", line 1033, in _transform_labels
      "label_ids": table.lookup(labels_tensor),
    File "/usr/local/lib/python2.7/dist-packages/tensorflow/contrib/lookup/lookup_ops.py", line 179, in lookup
      (self._key_dtype, keys.dtype))
    TypeError: Signature mismatch. Keys must be dtype

< dtype: 'string'>, got < dtype: 'int64'>

On the other hand, if I make the label_key_values column a numpy.array, I will get the following error:

label_keys_values = np.array(["satan", "ipsweep", "nmap", "portsweep"], dtype='string')

Traceback (most recent call last):
    File "embedding_model_probe.py", line 116, in
      label_keys=label_keys_values)
    File "/usr/local/lib/python2.7/dist-packages/tensorflow/contrib/learn/python/learn/estimators/dnn.py", line 337, in init
      label_keys=label_keys),
    File "/usr/local/lib/python2.7/dist-packages/tensorflow/contrib/learn/python/learn/estimators/head.py", line 331, in multi_class_head
      label_keys=label_keys)
    File "/usr/local/lib/python2.7/dist-packages/tensorflow/contrib/learn/python/learn/estimators/head.py", line 986, in init
      if label_keys and len(label_keys) != n_classes:
  ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()


问:
How the computer system identify the application is 32-bit or 64-bit
As we know, the 64-bit system (like windows) can run both 32-bit applications or 64-bit applications. Under Windows 64-bit, 32-bit applications run on top of an emulation of a 32-bit operating system that is called Windows 32-bit on Windows 64-bit, or WOW64 for short.

Here, I want to know, how can the 64-bit system knows the application is 32-bit or 64-bit?  So, the windows 64-bit or WOW64 can be chose to run the application correctly.

答: By examining Machine field of the COFF header.


问:
What does this mqtt-connection module used for?
What does this mqtt-connection module in nodejs used for? Does it means with this mqtt-connection then we do not need any broker?
mqtt-connection</p>

答:
You can indeed create a new server listening on MQTT and connect to it using the client version.

For exemple you can run an express app with the following architecture

```<code>-server
   - server.js //Start your server here
-app
   - your client views and controllers go here
</code>```

However, if you are planning to setup a big application, I strongly recommend you to use brokers such as Mosquito or ActiveMQ.

Body:
You can indeed create a new server listening on MQTT and connect to it using the client version.

For exemple you can run an express app with the following architecture

-server
   - server.js //Start your server here
-app
   - your client views and controllers go here

However, if you are planning to setup a big application, I strongly recommend you to use brokers such as Mosquito or ActiveMQ.


问:
Algebraic Data Types in Postgres
Is it possible to create an Algebraic Data Type in Postgres and then use it as a column type?

For example:

```<code>CREATE TYPE hoofed AS ENUM('horse', 'goat');

CREATE TYPE monkey AS ENUM('chimp','macaque');

CREATE TYPE ANIMAL AS ENUM(hoofed, monkey);
</code>```

This fails with:

```<code>syntax error at or near "hoofed"
LINE 1: CREATE TYPE ANIMAL AS ENUM(hoofed, monkey);
</code>```

Is it possible to do something like this?

Ultimately what I would then like to be able to do is something like so:

```<code>CREATE TABLE zoo (
    a ANIMAL,
    name text
);

INSERT INTO zoo(a, name) VALUES('horse', 'bob');
INSERT INTO zoo(a, name) VALUES('macaque', 'jimmy');
</code>```

And for both of the records to be independently valid.

EDIT: @Abihabi87's response below does allow me to create, in effect, a product type, but it still does not allow me to create a union type as desired.

答:
You cant create type enum from others enum type:

you can create ANIMAL that like:

```<code>CREATE TYPE ANIMAL AS (h hoofed,m monkey);
</code>```

Example in use:

```<code>CREATE TABLE your_table
(
    a ANIMAL
);

INSERT INTO your_table(a) select (select ('horse','macaque')::ANIMAL);
</code>```

Title: Algebraic Data Types in Postgres

Body:
Is it possible to create an Algebraic Data Type in Postgres and then use it as a column type?

For example:

CREATE TYPE hoofed AS ENUM('horse', 'goat');

CREATE TYPE monkey AS ENUM('chimp','macaque');

CREATE TYPE ANIMAL AS ENUM(hoofed, monkey);

This fails with:

syntax error at or near "hoofed"
LINE 1: CREATE TYPE ANIMAL AS ENUM(hoofed, monkey);

Is it possible to do something like this?

Ultimately what I would then like to be able to do is something like so:

CREATE TABLE zoo (
    a ANIMAL,
    name text
);

INSERT INTO zoo(a, name) VALUES('horse', 'bob');
INSERT INTO zoo(a, name) VALUES('macaque', 'jimmy');

And for both of the records to be independently valid.

EDIT: @Abihabi87's response below does allow me to create, in effect, a product type, but it still does not allow me to create a union type as desired.

Body:
You cant create type enum from others enum type:

you can create ANIMAL that like:

CREATE TYPE ANIMAL AS (h hoofed,m monkey);

Example in use:

CREATE TABLE your_table
(
    a ANIMAL
);

INSERT INTO your_table(a) select (select ('horse','macaque')::ANIMAL);


问:
How to extract path from Windows shortcut in R?
I have a shortcut to a file (or a folder) under Windows, and I would like to resolve the path name under R and use that info to open a file.

The shortcut is called shortcut.lnk and it is placed in my working directory, and the shortcut is directed to another place, say C:\Users\XX\Desktop\something.txt

I would like to extract the path name of the shortcut to use that info to open the file, something like: read.table(resolved.link). I tried Sys.readlink, but it does not work on Windows.

答:
This could help you : </p>

```<code>library(R.utils)

lnk <- readWindowsShortcut("C:/Users/indi/Desktop/a.lnk")
lnk$pathname
</code>```

<p>More about it here </p>

Body:
This could help you :

library(R.utils)

lnk <- readWindowsShortcut("C:/Users/indi/Desktop/a.lnk")
lnk$pathname

More about it here


问:
Javascript/JQuery - val().length' is null or not an object
I have the error val().length is null or not an object"  from code:

```<code>function size(sender, args) {

    var sizeVariable = $("input[id$='txtHello']");
    if (sizeVariable.val().length == 0)
    {
          args.IsValid = false;
     }
}
</code>```

The error occurs on the "If" statement. I am trying to check if:

the variable exists

if there is something in the variable

I think the problem lies with point (1). How do I check if the text field exists (to hopefully resolve the issue)?

答:
In jQuery you can use:

```<code>if( input.val().length > limit)
</code>```

or if for some reason it didn't work you can use:

```<code>if( ( input.val() ).length > limit )
</code>```

Body:
I have the error val().length is null or not an object"  from code:

function size(sender, args) {

    var sizeVariable = $("input[id$='txtHello']");
    if (sizeVariable.val().length == 0)
    {
          args.IsValid = false;
     }
}

The error occurs on the "If" statement. I am trying to check if:

the variable exists

if there is something in the variable

I think the problem lies with point (1). How do I check if the text field exists (to hopefully resolve the issue)?

Body:
In jQuery you can use:

if( input.val().length > limit)

or if for some reason it didn't work you can use:

if( ( input.val() ).length > limit )


问:
jQuery ajax call fires error event on a 200 success call
I have an ASP.NET Core WebAPI project with the following GET in my controller:

```<code>[HttpGet]
public IEnumerable<string> Get()
{
    return new string[] { "value1", "value2" };
}
</code>```

I'm trying to call this method from jQuery ajax call:

```<code>$.ajax({
    type: "GET",
    url: url,
    async: true,
    dataType: "json",
    success: function (data) {
        setJsonResult(data);
        showResultPane("API request result");
    },
    error: function (obj, textStatus, errorThrown) {
        setHtmlResult("Error returned by API: " + errorThrown);
        showResultPane("Unauthorized request result");
    },
    beforeSend: function (request) {
        if (currentToken) {
            request.setRequestHeader("Authorization", "Bearer " + currentToken);
        }
    }
});
</code>```

I monitor the web traffic with Fiddler and I see that the server returns a 200 Ok response with the following:

```<code>HTTP/1.1 200 OK
Transfer-Encoding: chunked
Content-Type: application/json; charset=utf-8
Server: Kestrel
Access-Control-Allow-Origin: *
X-Powered-By: ASP.NET
Access-Control-Allow-Origin: *
Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type,     Accept, Authorization
Date: Thu, 08 Jun 2017 09:13:18 GMT

13
["value1","value2"]
0
</code>```

The problem is that while the response from the web server is successful, the jQuery ajax error method is still being fired instead of the success method. I've tried playing with the dataType parameter (changing it, removing it) - no effect.

I even tried returning a different value from the API that is just a string and even change dataType to text - still firing error.

What's going on here?

答: This is because you have specified return datatype to be json and the API is not returning a valid json. Try changing the return type of your method to JsonResult and return valid jsonstring from your method. You can also check the response json is valid in this site :https://jsonlint.com/ </p>

Body:
I have an ASP.NET Core WebAPI project with the following GET in my controller:

[HttpGet]
public IEnumerable<string> Get()
{
    return new string[] { "value1", "value2" };
}

I'm trying to call this method from jQuery ajax call:

$.ajax({
    type: "GET",
    url: url,
    async: true,
    dataType: "json",
    success: function (data) {
        setJsonResult(data);
        showResultPane("API request result");
    },
    error: function (obj, textStatus, errorThrown) {
        setHtmlResult("Error returned by API: " + errorThrown);
        showResultPane("Unauthorized request result");
    },
    beforeSend: function (request) {
        if (currentToken) {
            request.setRequestHeader("Authorization", "Bearer " + currentToken);
        }
    }
});

I monitor the web traffic with Fiddler and I see that the server returns a 200 Ok response with the following:

HTTP/1.1 200 OK
Transfer-Encoding: chunked
Content-Type: application/json; charset=utf-8
Server: Kestrel
Access-Control-Allow-Origin: *
X-Powered-By: ASP.NET
Access-Control-Allow-Origin: *
Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type,     Accept, Authorization
Date: Thu, 08 Jun 2017 09:13:18 GMT

13
["value1","value2"]
0

The problem is that while the response from the web server is successful, the jQuery ajax error method is still being fired instead of the success method. I've tried playing with the dataType parameter (changing it, removing it) - no effect.

I even tried returning a different value from the API that is just a string and even change dataType to text - still firing error.

What's going on here?


问:
how to add a circle at the top middle of tab in html?
I am design a circle at the top middle of my tab but my tab will automatic increase based on the content i am using md-tab for creating the tab

I have created a circle  with css

```<code>.bubble_circle {
        width: 20px;
        height: 20px;
        border-radius: 50%;
        font-size: 20px;
        line-height: 15px;
    }
</code>```

Please help me out from this problem .past one day i am trying to set the circle in the top middle of the tab but i am enable to do this .

答:
Use position to get the same

Below an example

.tab {
  width: 100%;
  height: auto; /* You can update it as your need */
  background: tomato;
  position: relative;
  padding:5px;
}

.bubble_circle {
  width: 20px;
  height: 20px;
  border-radius: 50%;
  font-size: 20px;
  line-height: 15px;
  position: absolute;
  background: black;
  top: 0px;
  left: 50%;
  transform: translate(-50%, 0);
  /* z-index: value; if need and change as your need */
}

.bubble_circle + p {
  padding-top:15px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="tab">
  <div class="bubble_circle"></div>
  <p>
  Lorem ipsum dolor sit amet, consectetur adipisicing elit. Minima eaque quae incidunt ab, dolorum perspiciatis odit eius. Non assumenda doloremque in animi, laboriosam quibusdam nulla modi aspernatur sit enim voluptatum.
  </p>
</div></code>```

Body:
I am design a circle at the top middle of my tab but my tab will automatic increase based on the content i am using md-tab for creating the tab

I have created a circle  with css

.bubble_circle {
        width: 20px;
        height: 20px;
        border-radius: 50%;
        font-size: 20px;
        line-height: 15px;
    }

Please help me out from this problem .past one day i am trying to set the circle in the top middle of the tab but i am enable to do this .

Body:
Use position to get the same

Below an example

.tab {
  width: 100%;
  height: auto; /* You can update it as your need */
  background: tomato;
  position: relative;
  padding:5px;
}

.bubble_circle {
  width: 20px;
  height: 20px;
  border-radius: 50%;
  font-size: 20px;
  line-height: 15px;
  position: absolute;
  background: black;
  top: 0px;
  left: 50%;
  transform: translate(-50%, 0);
  /* z-index: value; if need and change as your need */
}

.bubble_circle + p {
  padding-top:15px;
}

<div class="tab">
  <div class="bubble_circle"></div>
  <p>
  Lorem ipsum dolor sit amet, consectetur adipisicing elit. Minima eaque quae incidunt ab, dolorum perspiciatis odit eius. Non assumenda doloremque in animi, laboriosam quibusdam nulla modi aspernatur sit enim voluptatum.
  </p>
</div>


问:
How to merge same years together
I want to take 2 dates from sheet 1 and generate that date range in sheet 2 in terms of months and years. I have a code that does this but I encounter a few problems which I'll explain later. This is what my code does (assuming the 2 dates in sheet 1 are oct-17 and mar-18 in MM-YY format).

My main question is, how do I get the same years to merge together? I want it to look like this.

The first problem I encounter is that I have to run the macro twice for the years format to change. What can I do to fix this?

The second problem is that some times some of the months will not display correctly and will instead show "########" as shown in the first attached picture. I notice this only happens with custom date formats. Why does this happen and how can I fix this?

I would really appreciate any help I can get. The following is my code

```<code>Sub macro3Planning()

Dim ws1 As Worksheet
Dim ws2 As Worksheet

Set ws1 = Sheets(1)
Set ws2 = Sheets(2)

Dim rng As Range
Set rng = ws2.Range("B3").Offset(3, 8)

Dim StartDate As Date
Dim EndDate As Date
Dim NoDays As Integer

StartDate = ws1.Range("D6").Value
EndDate = ws1.Range("D7").Value
NoDays = EndDate - StartDate + 1

'Generates months
With rng
    .Value = StartDate
    .Resize(NoDays).DataSeries Rowcol:=xlRows, Type:=xlChronological, Date:= _
    xlMonth, Step:=1, Stop:=EndDate, Trend:=False
    .VerticalAlignment = xlTop
    .HorizontalAlignment = xlCenter
    .Font.Bold = True
    .Borders.LineStyle = xlContinuous
    .NumberFormat = "mmm"
    .Interior.Pattern = xlSolid
    .Interior.ThemeColor = xlThemeColorDark1
    .Interior.TintAndShade = -0.149998474074526
End With

Set rng = rng.Offset(-1)

'Generates year
With rng
    .Value = StartDate
    .Resize(NoDays).DataSeries Rowcol:=xlRows, Type:=xlChronological, Date:= _
    xlMonth, Step:=1, Stop:=EndDate, Trend:=False
    .VerticalAlignment = xlTop
    .HorizontalAlignment = xlCenter
    .Font.Bold = True
    .Borders.LineStyle = xlContinuous
    .NumberFormat = "yyyy"
    .Interior.Pattern = xlSolid
    .Interior.ThemeColor = xlThemeColorAccent2
    .Interior.TintAndShade = 0.599993896298105
End With

End Sub
</code>```

UPDATE

3 . This happens because the column is not wide enough. I changed the format to "mmm" from "mmmm" so that the resulting months are always short enough to fit inside the column. Thanks @ClementB and @PalimPalim!

1 . I managed to get and modify a code to merge the cells with matching contents from How to merge cells based on similar values - Excel 2010. Now all I need is to extract the years from the date, since I dim'd the years as date, so the actual values behind those 2017s and 2018s are 10/1/2017, 11/1/2017 and so on. Hence, I cant use the merge similar cells macro yet.

I'm thinking of using DatePart("yyyy") with a loop for all the years but I am not sure how as I am still new to excel vb. Please assist.

答:
I just called the following macro right at the end of the above code. The macro is to extract years from the date and then to merge every cell with the same years together. With this, I managed to solve my question 1 and 2. Seems like a long code for just a simple task.</p>

```<code>Sub mergesameyears()

Dim lastCol As Integer
lastCol = Cells.Find("*", SearchOrder:=xlByRows, Searchdirection:=xlPrevious).Column

Dim tosubtract As Integer
'9 is the column J number
tosubtract = 9

'Number of generated years
Dim noyears As Integer
noyears = lastCol - tosubtract

Dim selectyear As Integer

'Set rng to J5 which is first generated year
Dim rng As Range
Set rng = Range("J5")

Dim yearvalue As Integer
Dim asd As Long

For selectyear = 1 To noyears Step 1
    asd = rng.Value
    yearvalue = DatePart("yyyy", asd)
    rng.Clear
    rng.Value = yearvalue
    Set rng = rng.Offset(0, 1)
Next selectyear

Application.DisplayAlerts = False

Dim lastColumn As Range
Set lastColumn = Cells.Find("*", SearchOrder:=xlByRows,     Searchdirection:=xlPrevious)

Dim mergesame As Range, cell As Range
Set mergesame = Range("J5", lastColumn.Offset(-1))

Merge:
    For Each cell In mergesame
        If cell.Value = cell.Offset(, 1).Value And IsEmpty(cell) = False     Then
            With Range(cell, cell.Offset(, 1))
                .Merge
                .HorizontalAlignment = xlCenter
                .VerticalAlignment = xlTop
                .Font.Bold = True
                .Borders.LineStyle = xlContinuous
                .Interior.Pattern = xlSolid
                .Interior.ThemeColor = xlThemeColorAccent2
                .Interior.TintAndShade = 0.599993896298105
            End With
            GoTo Merge
        End If
    Next

Application.DisplayAlerts = True

End Sub
</code>```

Title: How to merge same years together

Body:
I want to take 2 dates from sheet 1 and generate that date range in sheet 2 in terms of months and years. I have a code that does this but I encounter a few problems which I'll explain later. This is what my code does (assuming the 2 dates in sheet 1 are oct-17 and mar-18 in MM-YY format).

My main question is, how do I get the same years to merge together? I want it to look like this.

The first problem I encounter is that I have to run the macro twice for the years format to change. What can I do to fix this?

The second problem is that some times some of the months will not display correctly and will instead show "########" as shown in the first attached picture. I notice this only happens with custom date formats. Why does this happen and how can I fix this?

I would really appreciate any help I can get. The following is my code

Sub macro3Planning()

Dim ws1 As Worksheet
Dim ws2 As Worksheet

Set ws1 = Sheets(1)
Set ws2 = Sheets(2)

Dim rng As Range
Set rng = ws2.Range("B3").Offset(3, 8)

Dim StartDate As Date
Dim EndDate As Date
Dim NoDays As Integer

StartDate = ws1.Range("D6").Value
EndDate = ws1.Range("D7").Value
NoDays = EndDate - StartDate + 1

'Generates months
With rng
    .Value = StartDate
    .Resize(NoDays).DataSeries Rowcol:=xlRows, Type:=xlChronological, Date:= _
    xlMonth, Step:=1, Stop:=EndDate, Trend:=False
    .VerticalAlignment = xlTop
    .HorizontalAlignment = xlCenter
    .Font.Bold = True
    .Borders.LineStyle = xlContinuous
    .NumberFormat = "mmm"
    .Interior.Pattern = xlSolid
    .Interior.ThemeColor = xlThemeColorDark1
    .Interior.TintAndShade = -0.149998474074526
End With

Set rng = rng.Offset(-1)

'Generates year
With rng
    .Value = StartDate
    .Resize(NoDays).DataSeries Rowcol:=xlRows, Type:=xlChronological, Date:= _
    xlMonth, Step:=1, Stop:=EndDate, Trend:=False
    .VerticalAlignment = xlTop
    .HorizontalAlignment = xlCenter
    .Font.Bold = True
    .Borders.LineStyle = xlContinuous
    .NumberFormat = "yyyy"
    .Interior.Pattern = xlSolid
    .Interior.ThemeColor = xlThemeColorAccent2
    .Interior.TintAndShade = 0.599993896298105
End With

End Sub

UPDATE

3 . This happens because the column is not wide enough. I changed the format to "mmm" from "mmmm" so that the resulting months are always short enough to fit inside the column. Thanks @ClementB and @PalimPalim!

1 . I managed to get and modify a code to merge the cells with matching contents from How to merge cells based on similar values - Excel 2010. Now all I need is to extract the years from the date, since I dim'd the years as date, so the actual values behind those 2017s and 2018s are 10/1/2017, 11/1/2017 and so on. Hence, I cant use the merge similar cells macro yet.

I'm thinking of using DatePart("yyyy") with a loop for all the years but I am not sure how as I am still new to excel vb. Please assist.

Body:
I just called the following macro right at the end of the above code. The macro is to extract years from the date and then to merge every cell with the same years together. With this, I managed to solve my question 1 and 2. Seems like a long code for just a simple task.

Sub mergesameyears()

Dim lastCol As Integer
lastCol = Cells.Find("*", SearchOrder:=xlByRows, Searchdirection:=xlPrevious).Column

Dim tosubtract As Integer
'9 is the column J number
tosubtract = 9

'Number of generated years
Dim noyears As Integer
noyears = lastCol - tosubtract

Dim selectyear As Integer

'Set rng to J5 which is first generated year
Dim rng As Range
Set rng = Range("J5")

Dim yearvalue As Integer
Dim asd As Long

For selectyear = 1 To noyears Step 1
    asd = rng.Value
    yearvalue = DatePart("yyyy", asd)
    rng.Clear
    rng.Value = yearvalue
    Set rng = rng.Offset(0, 1)
Next selectyear

Application.DisplayAlerts = False

Dim lastColumn As Range
Set lastColumn = Cells.Find("*", SearchOrder:=xlByRows,     Searchdirection:=xlPrevious)

Dim mergesame As Range, cell As Range
Set mergesame = Range("J5", lastColumn.Offset(-1))

Merge:
    For Each cell In mergesame
        If cell.Value = cell.Offset(, 1).Value And IsEmpty(cell) = False     Then
            With Range(cell, cell.Offset(, 1))
                .Merge
                .HorizontalAlignment = xlCenter
                .VerticalAlignment = xlTop
                .Font.Bold = True
                .Borders.LineStyle = xlContinuous
                .Interior.Pattern = xlSolid
                .Interior.ThemeColor = xlThemeColorAccent2
                .Interior.TintAndShade = 0.599993896298105
            End With
            GoTo Merge
        End If
    Next

Application.DisplayAlerts = True

End Sub


问:
how to solve the error: syntax error near unexpected token `do'
I am trying to read from two files using this way:

```<code>if [[ $COPY_PREV_DEPLOYMENT == true ]]; then
    echo [$JOB_NAME] Copying old environment variables of $OLD_APP app to the new environment variables of $NEW_APP app...
    cf env $NEW_APP | awk '/User-Provided/,/No staging env variables have been set/'| cut -f1 -d":" | tail -n +2 > env_variables.txt
    cf env $OLD_APP | awk '/User-Provided/,/No staging env variables have been set/'| cut -f2 -d":" | tail -n +2 > env_variables_values.txt
    paste env_variables.txt env_variables_values.txt | while read -r VARIABLE VALUE
    do
        cf set-env "$NEW_APP" "$VARIABLE" "$VALUE"
    done
    echo [$JOB_NAME] Done.
fi
</code>```

But I am facing this issue

.....sh: line 61: syntax error near unexpected token do'
  ......sh: line 61:    do ('

can someone help me to solve?

Thanks a lot

答:
You don't use do after an if condition. do... done is mostly use in loops. Also, it doesn't seem like parenthesis would be needed to wrap this single execution statement from the cloudfoundry api.

The code might look like this:

```<code>if [[ $COPY_PREV_DEPLOYMENT == true ]]; then
    echo $JOB_NAME Copying old environment variables of $OLD_APP app to the new environment variables of $NEW_APP app...
    cf env $NEW_APP | awk '/User-Provided/,/No staging env variables have been set/'| cut -f1 -d":" | tail -n +2 > env_variables.txt
    cf env $OLD_APP | awk '/User-Provided/,/No staging env variables have been set/'| cut -f2 -d":" | tail -n +2 > env_variables_values.txt
    paste env_variables.txt env_variables_values.txt | while read -r VARIABLE VALUE; do
        cf set-env "$NEW_APP" "$VARIABLE" "$VALUE"
        done
    echo $JOB_NAME Done.
fi
</code>```

Body:
I am trying to read from two files using this way:

if [[ $COPY_PREV_DEPLOYMENT == true ]]; then
    echo [$JOB_NAME] Copying old environment variables of $OLD_APP app to the new environment variables of $NEW_APP app...
    cf env $NEW_APP | awk '/User-Provided/,/No staging env variables have been set/'| cut -f1 -d":" | tail -n +2 > env_variables.txt
    cf env $OLD_APP | awk '/User-Provided/,/No staging env variables have been set/'| cut -f2 -d":" | tail -n +2 > env_variables_values.txt
    paste env_variables.txt env_variables_values.txt | while read -r VARIABLE VALUE
    do
        cf set-env "$NEW_APP" "$VARIABLE" "$VALUE"
    done
    echo [$JOB_NAME] Done.
fi

But I am facing this issue

.....sh: line 61: syntax error near unexpected token do'
  ......sh: line 61:    do ('

can someone help me to solve?

Thanks a lot

Body:
You don't use do after an if condition. do... done is mostly use in loops. Also, it doesn't seem like parenthesis would be needed to wrap this single execution statement from the cloudfoundry api.

The code might look like this:

if [[ $COPY_PREV_DEPLOYMENT == true ]]; then
    echo $JOB_NAME Copying old environment variables of $OLD_APP app to the new environment variables of $NEW_APP app...
    cf env $NEW_APP | awk '/User-Provided/,/No staging env variables have been set/'| cut -f1 -d":" | tail -n +2 > env_variables.txt
    cf env $OLD_APP | awk '/User-Provided/,/No staging env variables have been set/'| cut -f2 -d":" | tail -n +2 > env_variables_values.txt
    paste env_variables.txt env_variables_values.txt | while read -r VARIABLE VALUE; do
        cf set-env "$NEW_APP" "$VARIABLE" "$VALUE"
        done
    echo $JOB_NAME Done.
fi