问:
LDLt factorization using SciPy's Python bindings to LAPACK
I am trying to get the LDLt factorization of a given symmetric matrix with SciPy's Python bindings to LAPACK using the dsysv routine which actually solves linear systems using this matrix factorization.

I have tried the following:

```<code>import numpy as np
from scipy.linalg.lapack import dsysv

A = np.random.randint(1, 1000, size=(5, 5))
A = (A + A.T)
b = np.random.randn(5)
lult, piv, x, _ = dsysv(A, b, lower=1)
</code>```

Where x would be the solution for the above linear system and lult and piv contain information about the factorization.

How can I reconstruct LDLt from it? Sometimes negative values are contained in piv and from the docs I was not able to understand their meaning.

LAPACK's sytrf actually computes this factorization (without solving any linear system) but it does not seem available via SciPy.

There is an example here with the output I am interested in (see eq. 3-23).

答:
All the required information is found in the documentation of systrf. But admittedly, it is a somewhat verbose.

So just give me the code:

```<code>import numpy as np
from scipy.linalg.lapack import dsysv

def swapped(i, k, n):
    """identity matrix where ith row and column are swappend with kth row and column"""
    P = np.eye(n)
    P[i, i] = 0
    P[k, k] = 0
    P[i, k] = 1
    P[k, i] = 1
    return P

# example

n = 5

A = np.random.rand(n, n)
A = (A + A.T)
b = np.random.randn(n)
lult, piv, x, _ = dsysv(A, b, lower=1)

# reconstruct L and D

D = np.zeros_like(A, dtype=float)
L = np.eye(n)

k = 0
while k < n:
    i = piv[k]

    if i < 0:
        s = 2
    else:
        s = 1

    if s == 1:
        i = i - 1
        D[k, k] = lult[k, k]  # D(k) overwrites A(k,k)
        Pk = swapped(k, i, n)
        v = lult[k+1:n, k]  # v overwrites A(k+1:n,k)
        Lk = np.eye(n)
        Lk[k+1:n, k] = v
    else:
        m = -i - 1
        D[k:k+2, k:k+2] = lult[k:k+2, k:k+2]  #  the lower triangle of D(k) overwrites A(k,k), A(k+1,k), and A(k+1,k+1)
        D[k, k+1] = D[k+1, k]  # D is symmeric
        Pk = swapped(k+1, m, n)
        v = lult[k+2:n, k:k+2]  # v overwrites A(k+2:n,k:k+1)
        Lk = np.eye(n)
        Lk[k+2:n, k:k+2] = v

    L = L.dot(Pk).dot(Lk)

    if s == 1:
        k += 1
    else:
        k += 2

print(np.max(np.abs(A - L.dot(D).dot(L.T))))  # should be close to 0
</code>```

The snipped above reconstructs L and D from the decomposition (it would need to be adapted to reconstruct U from an UDUt decomposition). I will try to explain below. First a quote from the documentation:

... additional row interchanges are required to recover U or L explicitly (which is seldom necessary).

Reconstructing L (or U) requires a number of iterations with row exchanging operations and matrix multiplication. This is not very efficient (less so when done in Python) but luckily this reconstruction is seldom necessary. So make sure you really have to do this!

We reconstruct L from L = P(1)*L(1)* ... *P(k)*L(k)*...,. (Fortran indices are 1-based). So we need to iterate k from 0 to n, obtain K and L in each step and multiply them.

P is a permutation matrix, defined by piv. A positive value of piv is straight-forward (i = piv[k]). It means that the ith and kth row/column were swapped in A before performing the operation. In this case the kth diagonal element of lult corresponds to the kth diagonal element of D. L(k) contains the kth column of the lower diagonal matrix - after the swapping.

A negative value of piv means that the corresponding element of D is a 2x2 block instead of just one element, and L(k) corresponds to two columns of the lower diagonal matrix.

Now for each step in k we obtain L(k), apply the swapping operation P(k), and combine it with the existing L. We also obtain the 1x1 or 2x2 block of D and correspondingly increase k by 1 or 2 for the next step.

I won't blame anyone for not comprehending my explanation. I simply wrote it down as I figured it out... Hopefully, the combination of the code snippet, the description, and the original documentation prove useful :)

Body:
I am trying to get the LDLt factorization of a given symmetric matrix with SciPy's Python bindings to LAPACK using the dsysv routine which actually solves linear systems using this matrix factorization.

I have tried the following:

import numpy as np
from scipy.linalg.lapack import dsysv

A = np.random.randint(1, 1000, size=(5, 5))
A = (A + A.T)
b = np.random.randn(5)
lult, piv, x, _ = dsysv(A, b, lower=1)

Where x would be the solution for the above linear system and lult and piv contain information about the factorization.

How can I reconstruct LDLt from it? Sometimes negative values are contained in piv and from the docs I was not able to understand their meaning.

LAPACK's sytrf actually computes this factorization (without solving any linear system) but it does not seem available via SciPy.

There is an example here with the output I am interested in (see eq. 3-23).

Body:
All the required information is found in the documentation of systrf. But admittedly, it is a somewhat verbose.

So just give me the code:

import numpy as np
from scipy.linalg.lapack import dsysv

def swapped(i, k, n):
    """identity matrix where ith row and column are swappend with kth row and column"""
    P = np.eye(n)
    P[i, i] = 0
    P[k, k] = 0
    P[i, k] = 1
    P[k, i] = 1
    return P

# example

n = 5

A = np.random.rand(n, n)
A = (A + A.T)
b = np.random.randn(n)
lult, piv, x, _ = dsysv(A, b, lower=1)

# reconstruct L and D

D = np.zeros_like(A, dtype=float)
L = np.eye(n)

k = 0
while k < n:
    i = piv[k]

    if i < 0:
        s = 2
    else:
        s = 1

    if s == 1:
        i = i - 1
        D[k, k] = lult[k, k]  # D(k) overwrites A(k,k)
        Pk = swapped(k, i, n)
        v = lult[k+1:n, k]  # v overwrites A(k+1:n,k)
        Lk = np.eye(n)
        Lk[k+1:n, k] = v
    else:
        m = -i - 1
        D[k:k+2, k:k+2] = lult[k:k+2, k:k+2]  #  the lower triangle of D(k) overwrites A(k,k), A(k+1,k), and A(k+1,k+1)
        D[k, k+1] = D[k+1, k]  # D is symmeric
        Pk = swapped(k+1, m, n)
        v = lult[k+2:n, k:k+2]  # v overwrites A(k+2:n,k:k+1)
        Lk = np.eye(n)
        Lk[k+2:n, k:k+2] = v

    L = L.dot(Pk).dot(Lk)

    if s == 1:
        k += 1
    else:
        k += 2

print(np.max(np.abs(A - L.dot(D).dot(L.T))))  # should be close to 0

The snipped above reconstructs L and D from the decomposition (it would need to be adapted to reconstruct U from an UDUt decomposition). I will try to explain below. First a quote from the documentation:

... additional row interchanges are required to recover U or L explicitly (which is seldom necessary).

Reconstructing L (or U) requires a number of iterations with row exchanging operations and matrix multiplication. This is not very efficient (less so when done in Python) but luckily this reconstruction is seldom necessary. So make sure you really have to do this!

We reconstruct L from L = P(1)*L(1)* ... *P(k)*L(k)*...,. (Fortran indices are 1-based). So we need to iterate k from 0 to n, obtain K and L in each step and multiply them.

P is a permutation matrix, defined by piv. A positive value of piv is straight-forward (i = piv[k]). It means that the ith and kth row/column were swapped in A before performing the operation. In this case the kth diagonal element of lult corresponds to the kth diagonal element of D. L(k) contains the kth column of the lower diagonal matrix - after the swapping.

A negative value of piv means that the corresponding element of D is a 2x2 block instead of just one element, and L(k) corresponds to two columns of the lower diagonal matrix.

Now for each step in k we obtain L(k), apply the swapping operation P(k), and combine it with the existing L. We also obtain the 1x1 or 2x2 block of D and correspondingly increase k by 1 or 2 for the next step.

I won't blame anyone for not comprehending my explanation. I simply wrote it down as I figured it out... Hopefully, the combination of the code snippet, the description, and the original documentation prove useful :)


来源: stackexchange

问:
Using this keyword on constructor's parameters
```<code>name: string;

constructor(private value: string) {
  this.name = value;
  // or
  this.name = this.value;
}
</code>```

Which of these options are better. Why have I an option to use this prefix on value? Is it valid to use this keyword on constructor's parameters?

I've used an noUnusedParameters, noUnusedLocals in tsconfig and tslint to make sure that there is no unused variables in my program. Unfortunately tslint reports constructor's parameters if there is no this before them (marks them as unused which is weird).

答:
You can use this.value because you are assigning it when you declare it in the constructor with an access modifier as private value: string.

If you do not intend to use value in other functions, it is better to just inject it, without giving it and access modifier.

```<code>name: string;

constructor(value: string) {
  this.name = value;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
name: string;

constructor(private value: string) {
  this.name = value;
  // or
  this.name = this.value;
}

Which of these options are better. Why have I an option to use this prefix on value? Is it valid to use this keyword on constructor's parameters?

I've used an noUnusedParameters, noUnusedLocals in tsconfig and tslint to make sure that there is no unused variables in my program. Unfortunately tslint reports constructor's parameters if there is no this before them (marks them as unused which is weird).

Body:
You can use this.value because you are assigning it when you declare it in the constructor with an access modifier as private value: string.

If you do not intend to use value in other functions, it is better to just inject it, without giving it and access modifier.

name: string;

constructor(value: string) {
  this.name = value;
}


问:
Automatically save user scope settings ON CHANGE in VB.NET
I often find myself doing this for user scope settings:

My.Settings.MySetting = MyValue
My.Settings.Save()

Granted, user scope settings in VB.NET are saved automatically on exit, but still, it's safer to save on change in case of unexpected termination or session crashes occur.

My question: Is there a way that I'm not aware of to let changes in settings automatically trigger the saving mechanism?

答:
As jmcilhinney said:

```<code>Imports System.ComponentModel

Public Class Form1
    Private WithEvents MySettings As My.MySettings = My.Settings

    Private Sub MySettings_PropertyChanged(sender As Object, e As PropertyChangedEventArgs) Handles MySettings.PropertyChanged
        MySettings.Save()
    End Sub
End Class
</code>```

If you want to know which setting was changed, use e.PropertyName

Body:
As jmcilhinney said:

Imports System.ComponentModel

Public Class Form1
    Private WithEvents MySettings As My.MySettings = My.Settings

    Private Sub MySettings_PropertyChanged(sender As Object, e As PropertyChangedEventArgs) Handles MySettings.PropertyChanged
        MySettings.Save()
    End Sub
End Class

If you want to know which setting was changed, use e.PropertyName


问:
How can I make “gradle --console=rich” the default?
Along the lines of this answer (which works for me, BTW) and the javadocs, I tried

```<code>gradle.startParameter.consoleOutput = org.gradle.api.logging.configuration.ConsoleOutput.Rich
</code>```

in my ~/.gradle/init.gradle. However, I still need --console=rich to get color output. Why?

Tested with Gradle 2.14.1 and 3.2.1.

Terminal is cygwin urxvt with TERM variable set to rxvt-unicode-256color.

答:
If you are on Linux/Mac set

```<code>alias gradle='gradle --console rich'
</code>```

in your ~/.bashrc.

Body:
Along the lines of this answer (which works for me, BTW) and the javadocs, I tried

gradle.startParameter.consoleOutput = org.gradle.api.logging.configuration.ConsoleOutput.Rich

in my ~/.gradle/init.gradle. However, I still need --console=rich to get color output. Why?

Tested with Gradle 2.14.1 and 3.2.1.

Terminal is cygwin urxvt with TERM variable set to rxvt-unicode-256color.

Body:
If you are on Linux/Mac set

alias gradle='gradle --console rich'

in your ~/.bashrc.


问:
What is faster? Refresh the whole table with constant freq. or refresh necessary rows with same freq
For example, I have a table with N rows.

The table is attached to WebSocket. Let it be a quotes table.

There are two ways.

1) Update the whole table when any quote received, but limit updates to 1 per second.

2) Update only the row that represent the quote, but limit the frequency to 1 per second for any particular row.

In first case I have fixed amount of redraws per second. But each redraw takes more time while table grows.

In second case I have fixed time per redraw of a single row. But the amount of redraws grow when the table grows.

What is better?

Important to say, that I use a cluster of DIVs instead of table element to represent the data. I'm not sure may it also affect the result or not.

答:
Changing a particular row is much faster than redrawing the whole table. Redrawing a small part of the dom is much more efficient than re-drawing the whole thing.

This is why the concept of Virtual DOM is a thing (like in react and vue).

DOM manipulation is the heart of the modern, interactive web. Unfortunately, it is also a lot slower than most JavaScript operations.

As an example, let's say that you have a list that contains ten items. You check off the first item. Most JavaScript frameworks would rebuild the entire list. That's ten times more work than necessary! Only one item changed, but the remaining nine get rebuilt exactly how they were before.

https://www.codecademy.com/articles/react-virtual-dom

Using something like react as a framework will abstract these problems from you, so you dont have to worry what you are updating, react will update only what is needed. Doing it manually is also possible but might be tiresome.

The bottomline is that changing the smallest parts of the dom is better than redrawing the whole thing.


问:
Grails log4J Logging question on linux
I have been very frustrated about this.

I am trying to do the following:

Log all application related logs in application.log that are INFO or above

Understand what controls the configuration for catalina.out

Log only WARN to catalina.out

I am running my server on ubuntu and I have the default configuration for tomcat which includes a conf directory with a logging.properties.  I renamed this file to l.p so it wouldn't conflict.  (Not sure if this is a good idea)

In my config file, I have:

```<code>def catalinaBase = System.properties.getProperty('catalina.base')
if (!catalinaBase) catalinaBase = '.'   // just in case
def logDirectory = "${catalinaBase}${File.separator}logs"
println "Log Directory: ${logDirectory}"

log4j = {

  appenders {
    rollingFile name: 'applog', file: "${logDirectory}${File.separator}application.log", layout: pattern(conversionPattern: '%d{dd-MM-yyyy HH:mm:ss,SSS} %5p %c{1} - %m%n'), maxFileSize: 1024
  }

  error 'org.codehaus.groovy.grails.web.servlet',  //  controllers
          'org.codehaus.groovy.grails.web.pages', //  GSP
          'org.codehaus.groovy.grails.web.sitemesh', //  layouts
          'org.codehaus.groovy.grails.web.mapping.filter', // URL mapping
          'org.codehaus.groovy.grails.web.mapping', // URL mapping
          'org.codehaus.groovy.grails.commons', // core / classloading
          'org.codehaus.groovy.grails.plugins', // plugins
          'org.codehaus.groovy.grails.orm.hibernate', // hibernate integration
          'org.springframework',
          'org.hibernate',
          'net.sf.ehcache.hibernate'

  warn 'org.mortbay.log'

  info applog: 'grails.app'
  root {
   info 'applog'
  }

}
</code>```

As a result, I am getting three logs:

```<code>catalina.2011-01-17.log  catalina.out  localhost.2011-01-17.log
</code>```

The catalina.out has the following output:

```<code>Log Directory: /var/lib/tomcat6/logs
log4j:WARN No appenders could be found for logger (org.apache.commons.beanutils.PropertyUtils).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
log4j:ERROR WARNING: Exception occured configuring log4j logging: Cannot invoke org.apache.log4j.FileAppender.setFile - argument type mismatch
</code>```

I do NOT see the application.log in the log file directory.  Any help would be appreciated I am really frustrated about this.

One more thing, in windows everything come out to the console and the application.log is created in the .grails\1.3.5\projects\<appnmae>\tomcat directory

答:
Your problem is obviously that there's a type mismatch. Specifically, log4j is expecting a String when you're giving it a GString. Try replacing:

```<code>"${logDirectory}${File.separator}application.log"
</code>```

With this:

```<code>"${logDirectory}${File.separator}application.log".toString()
</code>```

EDIT: Please read this BUG

ContentLicense: CC BY-SA 2.5

Title: Grails log4J Logging question on linux

Body:
I have been very frustrated about this.

I am trying to do the following:

Log all application related logs in application.log that are INFO or above

Understand what controls the configuration for catalina.out

Log only WARN to catalina.out

I am running my server on ubuntu and I have the default configuration for tomcat which includes a conf directory with a logging.properties.  I renamed this file to l.p so it wouldn't conflict.  (Not sure if this is a good idea)

In my config file, I have:

def catalinaBase = System.properties.getProperty('catalina.base')
if (!catalinaBase) catalinaBase = '.'   // just in case
def logDirectory = "${catalinaBase}${File.separator}logs"
println "Log Directory: ${logDirectory}"

log4j = {

  appenders {
    rollingFile name: 'applog', file: "${logDirectory}${File.separator}application.log", layout: pattern(conversionPattern: '%d{dd-MM-yyyy HH:mm:ss,SSS} %5p %c{1} - %m%n'), maxFileSize: 1024
  }

  error 'org.codehaus.groovy.grails.web.servlet',  //  controllers
          'org.codehaus.groovy.grails.web.pages', //  GSP
          'org.codehaus.groovy.grails.web.sitemesh', //  layouts
          'org.codehaus.groovy.grails.web.mapping.filter', // URL mapping
          'org.codehaus.groovy.grails.web.mapping', // URL mapping
          'org.codehaus.groovy.grails.commons', // core / classloading
          'org.codehaus.groovy.grails.plugins', // plugins
          'org.codehaus.groovy.grails.orm.hibernate', // hibernate integration
          'org.springframework',
          'org.hibernate',
          'net.sf.ehcache.hibernate'

  warn 'org.mortbay.log'

  info applog: 'grails.app'
  root {
   info 'applog'
  }

}

As a result, I am getting three logs:

catalina.2011-01-17.log  catalina.out  localhost.2011-01-17.log

The catalina.out has the following output:

Log Directory: /var/lib/tomcat6/logs
log4j:WARN No appenders could be found for logger (org.apache.commons.beanutils.PropertyUtils).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
log4j:ERROR WARNING: Exception occured configuring log4j logging: Cannot invoke org.apache.log4j.FileAppender.setFile - argument type mismatch

I do NOT see the application.log in the log file directory.  Any help would be appreciated I am really frustrated about this.

One more thing, in windows everything come out to the console and the application.log is created in the .grails\1.3.5\projects\<appnmae>\tomcat directory

Body:
Your problem is obviously that there's a type mismatch. Specifically, log4j is expecting a String when you're giving it a GString. Try replacing:

"${logDirectory}${File.separator}application.log"

With this:

"${logDirectory}${File.separator}application.log".toString()

EDIT: Please read this BUG


问:
GLSL Unsupported Version
I'm trying to compile GLSL shaders for use in LWJGL with OpenGL. I'm on macOS Sierra.

I get the following error when trying to compile the shaders:

```<code>ERROR: 0:1: '' :  version '400' is not supported
ERROR: 0:1: '' : syntax error: #version
</code>```

The shader code works on Windows, but when testing on macOS it doesn't.
Here's the shader code:

```<code>#version 400 core

in vec3 position;
in vec2 textureCoords;

out vec2 pass_textureCoords;

uniform mat4 projectionMatrix;
uniform mat4 viewMatrix;

void main(void)
{
    gl_Position = projectionMatrix * viewMatrix * vec4(position, 1.0);
    pass_textureCoords = textureCoords;
}
</code>```

Here is how i'm loading the shader...

```<code>    private static int loadShader(String file, int type) throws IOException {
        StringBuilder shaderSource = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(
                    ShaderProgram.class.getClassLoader().getResourceAsStream("shaders/" + file))
            )) {

            String line;
            while ((line = reader.readLine()) != null) {
                shaderSource.append(line).append('\n');
            }

            System.out.println(shaderSource.toString());

            int shaderID = GL20.glCreateShader(type);

            GL20.glShaderSource(shaderID, shaderSource);
            GL20.glCompileShader(shaderID);

            if (GL20.glGetShaderi(shaderID, GL20.GL_COMPILE_STATUS) == GL11.GL_FALSE) {
                System.out.println(GL20.glGetShaderInfoLog(shaderID, 500));
                System.err.println("Error compiling shader " + file);
                System.exit(-1);
            }

            return shaderID;
        }
    }
</code>```

The print statement returns the correct output, yet it still gives me the error.

I've searched all over stackoverflow for a solution, yet everyone says that they're compiling it without line breaks, which i have. I'm confused as to why this is occurring.

答:
Hello not an java expert here, i did some experiments using JOGL, so maybe i cant give you a hint to work in the right direction.

An issue with new line on MAC
How to append a newline to StringBuilder

Second:

https://www.khronos.org/registry/OpenGL/specs/gl/GLSLangSpec.4.00.pdf

The #version directive must occur in a shader before anything else, except for comments and white space.

This is what is looks like RAW in JOGL you see the newline is needed is after the version directive , everthing else has an semicolons as statement separators.

```<code>  //
  // create fragment Shader
  int fragShader = gl4.glCreateShader(GL4.GL_FRAGMENT_SHADER);
  gl4.glShaderSource(fragShader, 1,
    new String[]{"#version 420 \n"
    +"out vec4 fragColor;"
    +"void main(void) {"
    +"fragColor = vec4(0.2, 0.2, 0.5, 1.0);}" }, null);
    gl4.glCompileShader(fragShader);
</code>```

Title: GLSL Unsupported Version

Body:
I'm trying to compile GLSL shaders for use in LWJGL with OpenGL. I'm on macOS Sierra.

I get the following error when trying to compile the shaders:

ERROR: 0:1: '' :  version '400' is not supported
ERROR: 0:1: '' : syntax error: #version

The shader code works on Windows, but when testing on macOS it doesn't.
Here's the shader code:

#version 400 core

in vec3 position;
in vec2 textureCoords;

out vec2 pass_textureCoords;

uniform mat4 projectionMatrix;
uniform mat4 viewMatrix;

void main(void)
{
    gl_Position = projectionMatrix * viewMatrix * vec4(position, 1.0);
    pass_textureCoords = textureCoords;
}

Here is how i'm loading the shader...

    private static int loadShader(String file, int type) throws IOException {
        StringBuilder shaderSource = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(
                    ShaderProgram.class.getClassLoader().getResourceAsStream("shaders/" + file))
            )) {

            String line;
            while ((line = reader.readLine()) != null) {
                shaderSource.append(line).append('\n');
            }

            System.out.println(shaderSource.toString());

            int shaderID = GL20.glCreateShader(type);

            GL20.glShaderSource(shaderID, shaderSource);
            GL20.glCompileShader(shaderID);

            if (GL20.glGetShaderi(shaderID, GL20.GL_COMPILE_STATUS) == GL11.GL_FALSE) {
                System.out.println(GL20.glGetShaderInfoLog(shaderID, 500));
                System.err.println("Error compiling shader " + file);
                System.exit(-1);
            }

            return shaderID;
        }
    }

The print statement returns the correct output, yet it still gives me the error.

I've searched all over stackoverflow for a solution, yet everyone says that they're compiling it without line breaks, which i have. I'm confused as to why this is occurring.

Body:
Hello not an java expert here, i did some experiments using JOGL, so maybe i cant give you a hint to work in the right direction.

An issue with new line on MAC
How to append a newline to StringBuilder

Second:

https://www.khronos.org/registry/OpenGL/specs/gl/GLSLangSpec.4.00.pdf

The #version directive must occur in a shader before anything else, except for comments and white space.

This is what is looks like RAW in JOGL you see the newline is needed is after the version directive , everthing else has an semicolons as statement separators.

  //
  // create fragment Shader
  int fragShader = gl4.glCreateShader(GL4.GL_FRAGMENT_SHADER);
  gl4.glShaderSource(fragShader, 1,
    new String[]{"#version 420 \n"
    +"out vec4 fragColor;"
    +"void main(void) {"
    +"fragColor = vec4(0.2, 0.2, 0.5, 1.0);}" }, null);
    gl4.glCompileShader(fragShader);


问:
Pandas - invalid entry in choicelist
I'm trying to filter on a column, and if the column contains a certain string, I'll append a specific value into a new column. Example:

```<code>conditions = [df['columnA'].str.contains('valueA')]
choices    = ['valueB']

df['columnB'] = np.select(conditions,  choices, default = 'default')
</code>```

But when I run this, I get the following error:

```<code>ValueError: invalid entry in choicelist: should be boolean ndarray
</code>```

What am I doing wrong?

答:
You need parameter na=False in str.contains because NaNs in boolean mask as commented unutbu:

```<code>conditions = [df['columnA'].str.contains('valueA', na=False)]
</code>```

Sample:

```<code>df = pd.DataFrame({'columnA':['valueA  ff','ss valueA','valueA 4','w','e',np.nan]})
print (df)
      columnA
0  valueA  ff
1   ss valueA
2    valueA 4
3           w
4           e
5         NaN
</code>```

```<code>print (df['columnA'].str.contains('valueA'))
0     True
1     True
2     True
3    False
4    False
5      NaN
Name: columnA, dtype: object

print (df['columnA'].str.contains('valueA', na=False))
0     True
1     True
2     True
3    False
4    False
5    False
Name: columnA, dtype: bool
</code>```

All together:

```<code>conditions = [df['columnA'].str.contains('valueA', na=False)]
choices    = ['valueB']

df['columnB'] = np.select(conditions,  choices, default = 'default')
print (df)
      columnA  columnB
0  valueA  ff   valueB
1   ss valueA   valueB
2    valueA 4   valueB
3           w  default
4           e  default
5         NaN  default
</code>```

Title: Pandas - invalid entry in choicelist

Body:
I'm trying to filter on a column, and if the column contains a certain string, I'll append a specific value into a new column. Example:

conditions = [df['columnA'].str.contains('valueA')]
choices    = ['valueB']

df['columnB'] = np.select(conditions,  choices, default = 'default')

But when I run this, I get the following error:

ValueError: invalid entry in choicelist: should be boolean ndarray

What am I doing wrong?

Body:
You need parameter na=False in str.contains because NaNs in boolean mask as commented unutbu:

conditions = [df['columnA'].str.contains('valueA', na=False)]

Sample:

df = pd.DataFrame({'columnA':['valueA  ff','ss valueA','valueA 4','w','e',np.nan]})
print (df)
      columnA
0  valueA  ff
1   ss valueA
2    valueA 4
3           w
4           e
5         NaN

print (df['columnA'].str.contains('valueA'))
0     True
1     True
2     True
3    False
4    False
5      NaN
Name: columnA, dtype: object

print (df['columnA'].str.contains('valueA', na=False))
0     True
1     True
2     True
3    False
4    False
5    False
Name: columnA, dtype: bool

All together:

conditions = [df['columnA'].str.contains('valueA', na=False)]
choices    = ['valueB']

df['columnB'] = np.select(conditions,  choices, default = 'default')
print (df)
      columnA  columnB
0  valueA  ff   valueB
1   ss valueA   valueB
2    valueA 4   valueB
3           w  default
4           e  default
5         NaN  default


问:
PHP: Issue while exporting MySQL data into an Excel file
I am exporting MySQL data into an Excel file which contains "Hindi" data but in place of Hindi à¤¨à¤¿à¤®à¥à¤¨ is appearing.

Please help in resolving my issue. My PHP code is:

```<code><?php
    include 'connection.php';
    $filename = "currentaffairquestions";  //your_file_name
    $file_ending = "xls";   //file_extention
    mysqli_set_charset($conn,'utf8');
    header("Content-Type: application/vnd-ms-excel");
    header("Content-Disposition: attachment; filename=$filename.xls");
    header("Pragma: no-cache");
    header("Expires: 0");
    $sep = "\t";
    $sql="SELECT  question_number,question_name,choice1,choice2,choice3,choice4,answer from current_affairs_question_details where id='$_GET[currentaffairid]'";
    $result=mysqli_query($conn,$sql);
    while ($property = mysqli_fetch_field($result)) { //fetch table field name
        echo $property->name."\t";
    }

    print("\n");

    while($row = mysqli_fetch_row($result))  //fetch_table_data
    {
        $schema_insert = "";
        for($j=0; $j< mysqli_num_fields($result);$j++)
        {
            if(!isset($row[$j]))
                $schema_insert .= "NULL".$sep;
            elseif ($row[$j] != "")
                $schema_insert .= "$row[$j]".$sep;
            else
                $schema_insert .= "".$sep;
        }
        $schema_insert = str_replace($sep."$", "", $schema_insert);
        $schema_insert = preg_replace("/\r\n|\n\r|\n|\r/", " ", $schema_insert);
        $schema_insert .= "\t";
        print(trim($schema_insert));
        print "\n";
    }
    ?>
</code>```

答: mysqli_set_charset($con,"utf8"); immediately after connection</p>

Body:
I am exporting MySQL data into an Excel file which contains "Hindi" data but in place of Hindi à¤¨à¤¿à¤®à¥à¤¨ is appearing.

Please help in resolving my issue. My PHP code is:

<?php
    include 'connection.php';
    $filename = "currentaffairquestions";  //your_file_name
    $file_ending = "xls";   //file_extention
    mysqli_set_charset($conn,'utf8');
    header("Content-Type: application/vnd-ms-excel");
    header("Content-Disposition: attachment; filename=$filename.xls");
    header("Pragma: no-cache");
    header("Expires: 0");
    $sep = "\t";
    $sql="SELECT  question_number,question_name,choice1,choice2,choice3,choice4,answer from current_affairs_question_details where id='$_GET[currentaffairid]'";
    $result=mysqli_query($conn,$sql);
    while ($property = mysqli_fetch_field($result)) { //fetch table field name
        echo $property->name."\t";
    }

    print("\n");

    while($row = mysqli_fetch_row($result))  //fetch_table_data
    {
        $schema_insert = "";
        for($j=0; $j< mysqli_num_fields($result);$j++)
        {
            if(!isset($row[$j]))
                $schema_insert .= "NULL".$sep;
            elseif ($row[$j] != "")
                $schema_insert .= "$row[$j]".$sep;
            else
                $schema_insert .= "".$sep;
        }
        $schema_insert = str_replace($sep."$", "", $schema_insert);
        $schema_insert = preg_replace("/\r\n|\n\r|\n|\r/", " ", $schema_insert);
        $schema_insert .= "\t";
        print(trim($schema_insert));
        print "\n";
    }
    ?>


问:
Is it possible to create a git patch from one directory and apply that patch to the different directory ?,
I am trying to create a patch from one directory and apply that patch to the different directory, provided both the directory contains same files.

For Example:
 Consider, the repo-1 /local/mnt/workspace/New_version/sample_dir/ contains File1, File2 and File3.

Consider, repo-2 /local/mnt/workspace/old_version/ contains same set of files mentioned in repo-1.

Now, I am trying to create a patch set from repo-1 and trying to apply it on the repo-2, which throws error due to path conflicts.

Is there any possible way to meet my requirement? Please help !

答:
You can use -p to remove directories and --directory=<root> for this:

```<code>   -p<n>
       Remove <n> leading slashes from traditional diff paths. The default is 1.

   --directory=<root>
       Prepend <root> to all filenames. If a "-p" argument was also passed, it is applied before prepending the new root.

       For example, a patch that talks about updating a/git-gui.sh to b/git-gui.sh can be applied to the file in the working tree modules/git-gui/git-gui.sh by running git apply --directory=modules/git-gui.
</code>```

Body:
You can use -p to remove directories and --directory=<root> for this:

   -p<n>
       Remove <n> leading slashes from traditional diff paths. The default is 1.

   --directory=<root>
       Prepend <root> to all filenames. If a "-p" argument was also passed, it is applied before prepending the new root.

       For example, a patch that talks about updating a/git-gui.sh to b/git-gui.sh can be applied to the file in the working tree modules/git-gui/git-gui.sh by running git apply --directory=modules/git-gui.


问:
On how many devices can I test an IPhone application
I am currently developping an IPhone application and will need to test it soon. We have 4 testers in our clients office plus me.

So I would like to know if I can test an IPhone application on 5 different devices or if there is a limit.
If there is, what is this limit?

Regards,

答: The device limit for ad-hoc testing your app currently stands at 100 devices. So you'll be well within the limit. </p>


问:
rest controller not working in spring boot
I have checked most similar questions, and don't find the answer.So I can only post a new question.

I can successfully run my application without errors, but the rest api I write can't be access correctly.I have compared my launch log to the official tutorials, then I have found out I don't have the similar  log below:

```<code>2017-11-13 17:37:50.921  INFO 6503 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@2328c243: startup date [Mon Nov 13 17:37:49 CST 2017]; root of context hierarchy
2017-11-13 17:37:51.061  INFO 6503 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/greeting]}" onto public hello.Greeting hello.GreetingController.greeting(java.lang.String)
2017-11-13 17:37:51.066  INFO 6503 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2017-11-13 17:37:51.067  INFO 6503 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2017-11-13 17:37:51.126  INFO 6503 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-11-13 17:37:51.127  INFO 6503 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-11-13 17:37:51.188  INFO 6503 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
</code>```

Here are some my java files, Hope anyone can find some keypoint to solve my problem

the main application file:

```<code>package com.teachermate;

import com.alibaba.druid.pool.DruidDataSource;
import com.teachermate.entites.TeacherMateSettings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;

import javax.sql.DataSource;

@SpringBootApplication
@EnableConfigurationProperties({TeacherMateSettings.class})
public class JobScheduleApplication {

    @Autowired
    private Environment env;

    public static void main(String[] args) {
        SpringApplication.run(JobScheduleApplication.class, args);
    }

    @Bean
    public DataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl(env.getProperty("spring.datasource.url"));
        dataSource.setUsername(env.getProperty("spring.datasource.username"));
        dataSource.setPassword(env.getProperty("spring.datasource.password"));
        dataSource.setInitialSize(2);
        dataSource.setMaxActive(20);
        dataSource.setMinIdle(0);
        dataSource.setMaxWait(60000);
        dataSource.setValidationQuery("SELECT 1");
        dataSource.setTestOnBorrow(false);
        dataSource.setTestWhileIdle(true);
        dataSource.setPoolPreparedStatements(false);
        return dataSource;
    }
}
</code>```

the controller file:

```<code>@RestController
@RequestMapping(path = "/test")
public class TestController {
  @RequestMapping(method = RequestMethod.GET)
    public JSONObject HelloWorld() {
        JSONObject res = new JSONObject();
        LOGGER.info("HelloWorld Test!");
        res.put("data", "hello world!");
        res.put("errCode", 0);
        return res;
    }
}
</code>```

the pom.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.teachermate</groupId>
    <artifactId>job-scheduler</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>jobSchedule</name>
    <description>job schedule for teachermate</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.7.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
            <exclusions>
                <exclusion>
                <groupId>org.apache.tomcat</groupId>
                <artifactId>tomcat-jdbc</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.39</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.30</version>
        </dependency>
        <dependency>
            <groupId>org.quartz-scheduler</groupId>
            <artifactId>quartz</artifactId>
            <version>2.2.1</version>
        </dependency>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>23.2-jre</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.3.6</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.19</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <executable>true</executable>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>
</code>```

BTW, the rest api works fine before I add some code or library(like druid).But I don't know what cause it, can anyone help? Or can anyone show me a way to debug it? Thanks!

If you need any other information, just tell me in the comments.

update

I have modified the controller in official tutorials to

```<code>@RestController
@RequestMapping(path = "/test")
public class GreetingController {

    private static final String template = "Hello, %s!";
    private final AtomicLong counter = new AtomicLong();

    @RequestMapping("/greeting")
    public Greeting greeting(@RequestParam(value="name", defaultValue="World") String name) {
        return new Greeting(counter.incrementAndGet(),
                            String.format(template, name));
    }

    @RequestMapping(method = RequestMethod.GET)
    public JSONObject HelloWorld() {
        JSONObject res = new JSONObject();
        res.put("data", "hello world!");
        res.put("errCode", 0);
        return res;
    }
}
</code>```

it works fine!

答:
I finally figured it out.

I write a while loop in a method which has the @PostConstruct Annotation.It must block the spring main process, causing the rest controller not being loaded.

How foolish am I.

Body:
I have checked most similar questions, and don't find the answer.So I can only post a new question.

I can successfully run my application without errors, but the rest api I write can't be access correctly.I have compared my launch log to the official tutorials, then I have found out I don't have the similar  log below:

2017-11-13 17:37:50.921  INFO 6503 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@2328c243: startup date [Mon Nov 13 17:37:49 CST 2017]; root of context hierarchy
2017-11-13 17:37:51.061  INFO 6503 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/greeting]}" onto public hello.Greeting hello.GreetingController.greeting(java.lang.String)
2017-11-13 17:37:51.066  INFO 6503 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2017-11-13 17:37:51.067  INFO 6503 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2017-11-13 17:37:51.126  INFO 6503 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-11-13 17:37:51.127  INFO 6503 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-11-13 17:37:51.188  INFO 6503 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]

Here are some my java files, Hope anyone can find some keypoint to solve my problem

the main application file:

package com.teachermate;

import com.alibaba.druid.pool.DruidDataSource;
import com.teachermate.entites.TeacherMateSettings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;

import javax.sql.DataSource;

@SpringBootApplication
@EnableConfigurationProperties({TeacherMateSettings.class})
public class JobScheduleApplication {

    @Autowired
    private Environment env;

    public static void main(String[] args) {
        SpringApplication.run(JobScheduleApplication.class, args);
    }

    @Bean
    public DataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl(env.getProperty("spring.datasource.url"));
        dataSource.setUsername(env.getProperty("spring.datasource.username"));
        dataSource.setPassword(env.getProperty("spring.datasource.password"));
        dataSource.setInitialSize(2);
        dataSource.setMaxActive(20);
        dataSource.setMinIdle(0);
        dataSource.setMaxWait(60000);
        dataSource.setValidationQuery("SELECT 1");
        dataSource.setTestOnBorrow(false);
        dataSource.setTestWhileIdle(true);
        dataSource.setPoolPreparedStatements(false);
        return dataSource;
    }
}

the controller file:

@RestController
@RequestMapping(path = "/test")
public class TestController {
  @RequestMapping(method = RequestMethod.GET)
    public JSONObject HelloWorld() {
        JSONObject res = new JSONObject();
        LOGGER.info("HelloWorld Test!");
        res.put("data", "hello world!");
        res.put("errCode", 0);
        return res;
    }
}

the pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.teachermate</groupId>
    <artifactId>job-scheduler</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>jobSchedule</name>
    <description>job schedule for teachermate</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.7.RELEASE</version>
        <relativePath/>
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
            <exclusions>
                <exclusion>
                <groupId>org.apache.tomcat</groupId>
                <artifactId>tomcat-jdbc</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.39</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.30</version>
        </dependency>
        <dependency>
            <groupId>org.quartz-scheduler</groupId>
            <artifactId>quartz</artifactId>
            <version>2.2.1</version>
        </dependency>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>23.2-jre</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.3.6</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.19</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <executable>true</executable>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

BTW, the rest api works fine before I add some code or library(like druid).But I don't know what cause it, can anyone help? Or can anyone show me a way to debug it? Thanks!

If you need any other information, just tell me in the comments.

update

I have modified the controller in official tutorials to

@RestController
@RequestMapping(path = "/test")
public class GreetingController {

    private static final String template = "Hello, %s!";
    private final AtomicLong counter = new AtomicLong();

    @RequestMapping("/greeting")
    public Greeting greeting(@RequestParam(value="name", defaultValue="World") String name) {
        return new Greeting(counter.incrementAndGet(),
                            String.format(template, name));
    }

    @RequestMapping(method = RequestMethod.GET)
    public JSONObject HelloWorld() {
        JSONObject res = new JSONObject();
        res.put("data", "hello world!");
        res.put("errCode", 0);
        return res;
    }
}

it works fine!

ContentLicense: CC BY-SA 4.0


问:
Angular 4 get parent, child and next element from html
I am trying to create a button which when pressed returns the parents parents next element. I'm using

```<code><button (click)="onClick(this)">show more</button>
</code>```

in the html file and in the .ts file i got

```<code>onClick(obj) {
    alert(obj.parent().parent().next());
}
</code>```

答:
Try the following :

First create a reference to your button element

```<code><button (click)="onClick()" #btn>show more</button>
</code>```

.ts file

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

@ViewChild('btn') public btn: HTMLButtonElement;

onClick() {
    console.log(this.btn['nativeElement'].parentElement.parentElement.nextSibling);
}
</code>```

Body:
I am trying to create a button which when pressed returns the parents parents next element. I'm using

<button (click)="onClick(this)">show more</button>

in the html file and in the .ts file i got

onClick(obj) {
    alert(obj.parent().parent().next());
}

Body:
Try the following :

First create a reference to your button element

<button (click)="onClick()" #btn>show more</button>

.ts file

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

@ViewChild('btn') public btn: HTMLButtonElement;

onClick() {
    console.log(this.btn['nativeElement'].parentElement.parentElement.nextSibling);
}


问:
Zend Framework Routing: .html extension
I know I've seen this done before but I can't find the information anywhere. I need to be able to route with .html extensions in the Zend Framework.

I.E. /controller/action.html should route to the appropriate controller / action.

We have an idea to throw away the .html extension with our .htaccess file but I think changing the route config would be the better solution.

Any advice is welcome.

答:
The default route (without modules) is:

```<code>:controller/:action
</code>```

Which you can remove by:

```<code>$router->removeDefaultRoutes();
</code>```

Then add your version:

```<code>:controller/:action.html
</code>```

Title: Zend Framework Routing: .html extension

LastEditorDisplayName: Fabian Steeg

Body:
The default route (without modules) is:

:controller/:action

Which you can remove by:

$router->removeDefaultRoutes();

Then add your version:

:controller/:action.html

OwnerDisplayName: Karsten


问:
Unable to load solution after upgrading to Xamarin Studio 6
I recently upgraded Xamarin Studio to the latest version, and now I am unable to load my solution!

Upon opening the solution, the below error is displayed:

I have looked into the logs, and I see the following:

```<code>System.InvalidOperationException: Already bound to project
</code>```

Has anyone seen a similar error, or does anyone have a solution?

Thanks!

答: My xamarin project was made at windows, I copy to Mac. But Couldn't open same error. I solute with doing this. Open solution from windows visual studio. and right click solution then open xxmanager(i don't know english menu name, short cut maybe "o") and check build IOS. and copy to all solutions and project files to MAC. Then retry open solution. good luck</p>

Body:
I recently upgraded Xamarin Studio to the latest version, and now I am unable to load my solution!

Upon opening the solution, the below error is displayed:

I have looked into the logs, and I see the following:

System.InvalidOperationException: Already bound to project

Has anyone seen a similar error, or does anyone have a solution?

Thanks!


问:
Hiding wsdl's xml information in web browser on WCF?
Is there a way to let the clients use the wsdl, however only hide its xml which shows methods when opened in a web browser.

For example, following works very well for asmx:

```<code>  <system.web>
    <webServices>
      <wsdlHelpGenerator href="Blank.aspx"/>
    </webServices>
  </system.web>
</code>```

Is there any alternative of the above for svc?

Removing serviceMetadata or changing httpGetEnabled to false makes wsdl unusable, which is not what I want. I just want to make its contents invisible when opened in a web browser.

答:
if you want redirect user to another address if he/she request your svc file you can use rewrite like:

```<code><system.webServer>
         <rewrite>
             <rules>
                <clear />
                  <rule name="Redirect to Blank" stopProcessing="true">
               <match url="^(.+wsdl.+)/?$" />
                <action type="Redirect" url="http://yourDomain/Blank.aspx" redirectType="Permanent" appendQueryString="false" />
            </rule>
            </rules>
        </rewrite>
  </system.webServer>
</code>```

that should redirect user to yourDomain/Blank.aspx if the wsdl requested
but there should be another ways, but I have tested it on my system it works nice.

just add this configuration in config file of your services (Server-Side).

UPDATE:

you can also use <match url="\b(wsdl|singleWsdl|svc)\b" /> to redirect URL which contains svc or wsdl or singleWsdl.

Body:
Is there a way to let the clients use the wsdl, however only hide its xml which shows methods when opened in a web browser.

For example, following works very well for asmx:

  <system.web>
    <webServices>
      <wsdlHelpGenerator href="Blank.aspx"/>
    </webServices>
  </system.web>

Is there any alternative of the above for svc?

Removing serviceMetadata or changing httpGetEnabled to false makes wsdl unusable, which is not what I want. I just want to make its contents invisible when opened in a web browser.

Body:
if you want redirect user to another address if he/she request your svc file you can use rewrite like:

<system.webServer>
         <rewrite>
             <rules>
                <clear />
                  <rule name="Redirect to Blank" stopProcessing="true">
               <match url="^(.+wsdl.+)/?$" />
                <action type="Redirect" url="http://yourDomain/Blank.aspx" redirectType="Permanent" appendQueryString="false" />
            </rule>
            </rules>
        </rewrite>
  </system.webServer>

that should redirect user to yourDomain/Blank.aspx if the wsdl requested
but there should be another ways, but I have tested it on my system it works nice.

just add this configuration in config file of your services (Server-Side).

UPDATE:

you can also use <match url="\b(wsdl|singleWsdl|svc)\b" /> to redirect URL which contains svc or wsdl or singleWsdl.


问:
Best Laravel Scaffolding Crud Generator?
Adding crud forms manually is very painful for me. Is laravel a good way to do this?</p>

答: Voyager is a really powerful Admin backend panel and working with BREAD on Entities is very easy. Give it a try. Could be working better than a standalone generateor.</p>


问:
Eclipse plugin rt.jar semms not to be in classpath
We've developed a plugin for eclipse (helios) and it works perfectly at the workbench, but when I try to export and deploy it, the follow expcetion is being raised:

```<code>java.lang.ClassNotFoundException: sun.jdbc.odbc.JdbcOdbcDriver
    at org.eclipse.osgi.internal.loader.BundleLoader.findClassInternal(BundleLoader.java:506)
    at org.eclipse.osgi.internal.loader.BundleLoader.findClass(BundleLoader.java:422)
    at org.eclipse.osgi.internal.loader.BundleLoader.findClass(BundleLoader.java:410)
    at org.eclipse.osgi.internal.baseadaptor.DefaultClassLoader.loadClass(DefaultClassLoader.java:107)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:266)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:186)
    at learsoft.system.plugin.handlers.endOracleSession.conect(endOracleSession.java:31)
    at learsoft.system.plugin.handlers.SampleHandler.execute(SampleHandler.java:45)
    at org.eclipse.ui.internal.handlers.HandlerProxy.execute(HandlerProxy.java:293)
    at org.eclipse.core.commands.Command.executeWithChecks(Command.java:476)
    at org.eclipse.core.commands.ParameterizedCommand.executeWithChecks(ParameterizedCommand.java:508)
    at org.eclipse.ui.internal.handlers.HandlerService.executeCommand(HandlerService.java:169)
    at org.eclipse.ui.internal.handlers.SlaveHandlerService.executeCommand(SlaveHandlerService.java:241)
    at org.eclipse.ui.menus.CommandContributionItem.handleWidgetSelection(CommandContributionItem.java:820)
    at org.eclipse.ui.menus.CommandContributionItem.access$19(CommandContributionItem.java:806)
    at org.eclipse.ui.menus.CommandContributionItem$5.handleEvent(CommandContributionItem.java:796)
    at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84)
    at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1258)
    at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:3552)
    at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3171)
    at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:2629)
    at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:2593)
    at org.eclipse.ui.internal.Workbench.access$4(Workbench.java:2427)
    at org.eclipse.ui.internal.Workbench$7.run(Workbench.java:670)
    at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:332)
    at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:663)
    at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:149)
    at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:115)
    at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:110)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:79)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:369)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:179)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:616)
    at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:619)
    at org.eclipse.equinox.launcher.Main.basicRun(Main.java:574)
    at org.eclipse.equinox.launcher.Main.run(Main.java:1407)
</code>```

I've setted at the overview tab in plugin configuration to use JavaSE-1.6 and tryed several different configurations.
As far as I know JdbcOjdbcDriver is a class included in rt.jar and seems confusing to me that it is missing.
What am I missing?

Regards,
Fernando

答:
After reading OSGi and Equinox, I have better understanding of OSGi class loader.

Class Lookup Algorithm

Here, we assume that a bundle is trying to load some class C in package P.

if P starts with "java." || P is boot delegated

  return parent.loadClass(C)

if P is imported

  return exporter.loadClass(C)

if P is exported by some required bundles

  for each exporter

    return exporter.loadClass(C) if found

if C is found locally

  return C

if C is found in a fragment

  return C

if P is dynamically imported

  return exporter.loadClass(C)

if buddy loading is enabled for this bundle
  return BuddyLoader.loadClass(C)

throw a ClassNotFoundException

Step 7 is not standard OSGi behavior. Equinox adds this step.

Step 1 ensures that all java.* packages implicitly available to all bundles--they need not be explicitly imported. All other packages from JRE must, however, be explicitly imported. This implies that there is a matching exporter. The OSGi specification states that the System Bundle must export the additional packages from the JRE.

The System Bundle is known as org.eclipse.osgi in Equinox. It maintains a set of profiles that lists the standard API packages available in common JRE class libraries such as J2SE1.4, J2SE1.5, and JCL Foundation. These profiles do not include implementation-specific packages such as com.sun.* and sun.*, as they are not standard and are not available in all JREs.

Step 1 of the class loading algorithm mentions the notion of boot delegation. This is an override mechanism that identifies particular packages whose class loads should come from the parent class loader. This is useful for accesssing packages that are not java.* and are not otherwise exported by a bundle. To get access to such packages, you can either update the JRE profile or use the org.osgi.framework.bootdelegation property in config.ini to list the set of accessible package prefixes as follows:

```<code>org.osgi.framework.bootdelegation=com.sun.*,sun.*
</code>```

Body:
We've developed a plugin for eclipse (helios) and it works perfectly at the workbench, but when I try to export and deploy it, the follow expcetion is being raised:

java.lang.ClassNotFoundException: sun.jdbc.odbc.JdbcOdbcDriver
    at org.eclipse.osgi.internal.loader.BundleLoader.findClassInternal(BundleLoader.java:506)
    at org.eclipse.osgi.internal.loader.BundleLoader.findClass(BundleLoader.java:422)
    at org.eclipse.osgi.internal.loader.BundleLoader.findClass(BundleLoader.java:410)
    at org.eclipse.osgi.internal.baseadaptor.DefaultClassLoader.loadClass(DefaultClassLoader.java:107)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:266)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:186)
    at learsoft.system.plugin.handlers.endOracleSession.conect(endOracleSession.java:31)
    at learsoft.system.plugin.handlers.SampleHandler.execute(SampleHandler.java:45)
    at org.eclipse.ui.internal.handlers.HandlerProxy.execute(HandlerProxy.java:293)
    at org.eclipse.core.commands.Command.executeWithChecks(Command.java:476)
    at org.eclipse.core.commands.ParameterizedCommand.executeWithChecks(ParameterizedCommand.java:508)
    at org.eclipse.ui.internal.handlers.HandlerService.executeCommand(HandlerService.java:169)
    at org.eclipse.ui.internal.handlers.SlaveHandlerService.executeCommand(SlaveHandlerService.java:241)
    at org.eclipse.ui.menus.CommandContributionItem.handleWidgetSelection(CommandContributionItem.java:820)
    at org.eclipse.ui.menus.CommandContributionItem.access$19(CommandContributionItem.java:806)
    at org.eclipse.ui.menus.CommandContributionItem$5.handleEvent(CommandContributionItem.java:796)
    at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84)
    at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1258)
    at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:3552)
    at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3171)
    at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:2629)
    at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:2593)
    at org.eclipse.ui.internal.Workbench.access$4(Workbench.java:2427)
    at org.eclipse.ui.internal.Workbench$7.run(Workbench.java:670)
    at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:332)
    at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:663)
    at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:149)
    at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:115)
    at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:110)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:79)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:369)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:179)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:616)
    at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:619)
    at org.eclipse.equinox.launcher.Main.basicRun(Main.java:574)
    at org.eclipse.equinox.launcher.Main.run(Main.java:1407)

I've setted at the overview tab in plugin configuration to use JavaSE-1.6 and tryed several different configurations.
As far as I know JdbcOjdbcDriver is a class included in rt.jar and seems confusing to me that it is missing.
What am I missing?

Regards,
Fernando

Body:
After reading OSGi and Equinox, I have better understanding of OSGi class loader.

Class Lookup Algorithm

Here, we assume that a bundle is trying to load some class C in package P.

if P starts with "java." || P is boot delegated

  return parent.loadClass(C)

if P is imported

  return exporter.loadClass(C)

if P is exported by some required bundles

  for each exporter

    return exporter.loadClass(C) if found

if C is found locally

  return C

if C is found in a fragment

  return C

if P is dynamically imported

  return exporter.loadClass(C)

if buddy loading is enabled for this bundle
  return BuddyLoader.loadClass(C)

throw a ClassNotFoundException

Step 7 is not standard OSGi behavior. Equinox adds this step.

Step 1 ensures that all java.* packages implicitly available to all bundles--they need not be explicitly imported. All other packages from JRE must, however, be explicitly imported. This implies that there is a matching exporter. The OSGi specification states that the System Bundle must export the additional packages from the JRE.

The System Bundle is known as org.eclipse.osgi in Equinox. It maintains a set of profiles that lists the standard API packages available in common JRE class libraries such as J2SE1.4, J2SE1.5, and JCL Foundation. These profiles do not include implementation-specific packages such as com.sun.* and sun.*, as they are not standard and are not available in all JREs.

Step 1 of the class loading algorithm mentions the notion of boot delegation. This is an override mechanism that identifies particular packages whose class loads should come from the parent class loader. This is useful for accesssing packages that are not java.* and are not otherwise exported by a bundle. To get access to such packages, you can either update the JRE profile or use the org.osgi.framework.bootdelegation property in config.ini to list the set of accessible package prefixes as follows:

org.osgi.framework.bootdelegation=com.sun.*,sun.*


问:
sql server Using IF statment before UNION
I am adding a UNION statement and I need to add an IF statement for the UNION but I get an "Incorrect syntax near 'IF'. Expecting ')', EXCEPT, or SELECT   " error.

To improve processor efficiency, I like to only call the UNION if there is a special character in the variable string. Here is my select statement. Any help is appreciated. Thanks.

```<code>set @DelimitedKeyWord = ( select replace(@KeyWord, '-', '') )
set @DelimiterExists = ( select CHARINDEX('-', @KeyWord) )

select distinct top (@MaxHits)
    results.MYID as ItemId
  , results.Rank0 as [RANK]
from (
  select
      [MYID]
    , [RANK] as Rank0
  from [rcl].[MyTable] rm
    inner join CONTAINSTABLE([MyTable], *, @KeyWord) as CNT
      on CNT.[Key] = rm.RecallID

  if (@DelimiterExists > 0)
    begin
      union
      select
          [MYID]
        , [RANK] as Rank0
      from [rcl].[MyTable] rm
      inner join CONTAINSTABLE([MyTable], *, @DelimitedKeyWord) as DCNT
        on DCNT.[Key] = rm.RecallID
    end
  ) as results
</code>```

答:
SQL doesn't work like that.  One method is to include the condition in the WHERE clause:

```<code>SELECT DISTINCT TOP(@MaxHits) results.MYID AS ItemId, results.Rank0 AS [RANK]
FROM ((SELECT [MYID], [RANK] AS Rank0
       FROM [rcl].[MyTable] rm JOIN
            CONTAINSTABLE ([MyTable], *, @KeyWord) AS CNT
            ON CNT.[Key] = rm.RecallID
      )
      UNION ALL
      (SELECT [MYID], [RANK] AS Rank0
       FROM [rcl].[MyTable] rm JOIN
            CONTAINSTABLE ([MyTable], *, @DelimitedKeyWord) AS DCNT
            ON DCNT.[Key] = rm.RecallID
       WHERE @DelimiterExists > 0
      )
     ) x;
</code>```

Note:  Use UNION ALL.  You are already removing duplicates in the outer query.  No need to do that twice.

Body:
I am adding a UNION statement and I need to add an IF statement for the UNION but I get an "Incorrect syntax near 'IF'. Expecting ')', EXCEPT, or SELECT   " error.

To improve processor efficiency, I like to only call the UNION if there is a special character in the variable string. Here is my select statement. Any help is appreciated. Thanks.

set @DelimitedKeyWord = ( select replace(@KeyWord, '-', '') )
set @DelimiterExists = ( select CHARINDEX('-', @KeyWord) )

select distinct top (@MaxHits)
    results.MYID as ItemId
  , results.Rank0 as [RANK]
from (
  select
      [MYID]
    , [RANK] as Rank0
  from [rcl].[MyTable] rm
    inner join CONTAINSTABLE([MyTable], *, @KeyWord) as CNT
      on CNT.[Key] = rm.RecallID

  if (@DelimiterExists > 0)
    begin
      union
      select
          [MYID]
        , [RANK] as Rank0
      from [rcl].[MyTable] rm
      inner join CONTAINSTABLE([MyTable], *, @DelimitedKeyWord) as DCNT
        on DCNT.[Key] = rm.RecallID
    end
  ) as results

Body:
SQL doesn't work like that.  One method is to include the condition in the WHERE clause:

SELECT DISTINCT TOP(@MaxHits) results.MYID AS ItemId, results.Rank0 AS [RANK]
FROM ((SELECT [MYID], [RANK] AS Rank0
       FROM [rcl].[MyTable] rm JOIN
            CONTAINSTABLE ([MyTable], *, @KeyWord) AS CNT
            ON CNT.[Key] = rm.RecallID
      )
      UNION ALL
      (SELECT [MYID], [RANK] AS Rank0
       FROM [rcl].[MyTable] rm JOIN
            CONTAINSTABLE ([MyTable], *, @DelimitedKeyWord) AS DCNT
            ON DCNT.[Key] = rm.RecallID
       WHERE @DelimiterExists > 0
      )
     ) x;

Note:  Use UNION ALL.  You are already removing duplicates in the outer query.  No need to do that twice.


问:
Android lifecycle library: Cannot add the same observer with different lifecycles
I have an app I'm working on that's using the lifecycle library but I'm getting an IllegalArgumentException that says "Cannot add the same observer with different lifecycles" I only add observers in onCreate which I thought would be safe. Most of my observers are added via anonymous classes which I assume can't be the issue here since the observer is never recycled. One is using this:

```<code>private GpsState gpsState;

void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getLifecycle().addObserver(gpsState);
    gpsState.observe(this, (state) -> {
        // ...
    });
}
</code>```

In this example GpsState extends LiveData to provide the current state of the GPS and implements LifecycleObserver to be able to refresh certain values when reaching an ON_RESUME state.

Any idea what I might be doing wrong?

答:
In my case the problem was at lambda method of observer is empty. I just tried to add something to it and problem was solved. For example:

```<code>gpsState.observe(this, (state) -> {
                Log.d(this.getClass().getSimpleName(), BaseNavigationActivity.this.toString());

});
</code>```

Most likely that JVM define anonymous classes that use only static references and for such cases it become kinda singleton, so you will have same instance all the time you reference such class.

Body:
I have an app I'm working on that's using the lifecycle library but I'm getting an IllegalArgumentException that says "Cannot add the same observer with different lifecycles" I only add observers in onCreate which I thought would be safe. Most of my observers are added via anonymous classes which I assume can't be the issue here since the observer is never recycled. One is using this:

private GpsState gpsState;

void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getLifecycle().addObserver(gpsState);
    gpsState.observe(this, (state) -> {
        // ...
    });
}

In this example GpsState extends LiveData to provide the current state of the GPS and implements LifecycleObserver to be able to refresh certain values when reaching an ON_RESUME state.

Any idea what I might be doing wrong?

Body:
In my case the problem was at lambda method of observer is empty. I just tried to add something to it and problem was solved. For example:

gpsState.observe(this, (state) -> {
                Log.d(this.getClass().getSimpleName(), BaseNavigationActivity.this.toString());

});

Most likely that JVM define anonymous classes that use only static references and for such cases it become kinda singleton, so you will have same instance all the time you reference such class.


问:
Group elements from an array with a new element containing group value
I have an array like this one:

```<code>$array = [
     ['Categoria' => 'example', 'Servico' => 'name1'],
     ['Categoria' => 'example', 'Servico' => 'name2'],
     ['Categoria' => 'example', 'Servico' => 'name3'],
     ['Categoria' => 'example2', 'Servico' => 'name4'],
     ['Categoria' => 'example2', 'Servico' => 'name5'],
     ['Categoria' => 'example2', 'Servico' => 'name6'],
     ['Categoria' => 'example3', 'Servico' => 'name7'],
     ['Categoria' => 'example3', 'Servico' => 'name8'],
     ['Categoria' => 'example3', 'Servico' => 'name9']
];
</code>```

I need to transform this on something like:

```<code>[
    [
        'Servico' => 'example',
        'children' => [
            ['Servico' => 'name1'],
            ['Servico' => 'name2'],
            ['Servico' => 'name3'],
        ]
    ],
    [
        'Servico' => 'example2',
        'children' => [
            ['Servico' => 'name4'],
            ['Servico' => 'name5'],
            ['Servico' => 'name6'],
        ]
    ],
    [
        'Servico' => 'example3',
        'children' => [
            ['Servico' => 'name7'],
            ['Servico' => 'name8'],
            ['Servico' => 'name9'],
        ]
    ],
]
</code>```

I have read this topic and I successfully have grouped my array, but I couldn't find a way to format the array in a way I have Servico and children on each object.

Someone have any ideas?

答:
There is no need for multiple loops or conditions or counters here.

Every group's Servico value ($row['Categoria']) can be safely overwritten on each iteration.

Each new $row['Servico'] value is to be unconditionally pushed into the respective children subarray.

After using $row['Categoria'] to provide temporary grouping keys in the result array, re-index the result with array_values().

*Note: I am electing to flatten the data structure of children to be an indexed array.  I don't see any value in creating single-element associative arrays for each entry.  If you DO want that then push ['Servico' => $row['Servico']] into the children.

Functional-style with array_reduce(): (Demo)

```<code>var_export(
    array_values(
        array_reduce(
            $array,
            function ($carry, $row) {
                $carry[$row['Categoria']]['Servico'] = $row['Categoria'];
                $carry[$row['Categoria']]['children'][] = $row['Servico'];
                return $carry;
            }
        )
    )
);
</code>```

Classic foreach(): (Demo)

```<code>$result = [];
foreach ($array as $row) {
    $result[$row['Categoria']]['Servico'] = $row['Categoria'];
    $result[$row['Categoria']]['children'][] = $row['Servico'];
}
var_export(array_values($result));
</code>```

Body:
I have an array like this one:

$array = [
     ['Categoria' => 'example', 'Servico' => 'name1'],
     ['Categoria' => 'example', 'Servico' => 'name2'],
     ['Categoria' => 'example', 'Servico' => 'name3'],
     ['Categoria' => 'example2', 'Servico' => 'name4'],
     ['Categoria' => 'example2', 'Servico' => 'name5'],
     ['Categoria' => 'example2', 'Servico' => 'name6'],
     ['Categoria' => 'example3', 'Servico' => 'name7'],
     ['Categoria' => 'example3', 'Servico' => 'name8'],
     ['Categoria' => 'example3', 'Servico' => 'name9']
];

I need to transform this on something like:

[
    [
        'Servico' => 'example',
        'children' => [
            ['Servico' => 'name1'],
            ['Servico' => 'name2'],
            ['Servico' => 'name3'],
        ]
    ],
    [
        'Servico' => 'example2',
        'children' => [
            ['Servico' => 'name4'],
            ['Servico' => 'name5'],
            ['Servico' => 'name6'],
        ]
    ],
    [
        'Servico' => 'example3',
        'children' => [
            ['Servico' => 'name7'],
            ['Servico' => 'name8'],
            ['Servico' => 'name9'],
        ]
    ],
]

I have read this topic and I successfully have grouped my array, but I couldn't find a way to format the array in a way I have Servico and children on each object.

Someone have any ideas?

Body:
There is no need for multiple loops or conditions or counters here.

Every group's Servico value ($row['Categoria']) can be safely overwritten on each iteration.

Each new $row['Servico'] value is to be unconditionally pushed into the respective children subarray.

After using $row['Categoria'] to provide temporary grouping keys in the result array, re-index the result with array_values().

*Note: I am electing to flatten the data structure of children to be an indexed array.  I don't see any value in creating single-element associative arrays for each entry.  If you DO want that then push ['Servico' => $row['Servico']] into the children.

Functional-style with array_reduce(): (Demo)

var_export(
    array_values(
        array_reduce(
            $array,
            function ($carry, $row) {
                $carry[$row['Categoria']]['Servico'] = $row['Categoria'];
                $carry[$row['Categoria']]['children'][] = $row['Servico'];
                return $carry;
            }
        )
    )
);

Classic foreach(): (Demo)

$result = [];
foreach ($array as $row) {
    $result[$row['Categoria']]['Servico'] = $row['Categoria'];
    $result[$row['Categoria']]['children'][] = $row['Servico'];
}
var_export(array_values($result));


问:
Parse nested data using SCALA
I have the dataframe as follows :

```<code>ColA  ColB     ColC
1     [2,3,4] [5,6,7]
</code>```

I need to convert it to the below

```<code>ColA ColB ColC
1    2    5
1    3    6
1    4    7
</code>```

Can someone please help with the Code in SCALA?

答:
You can zip the two array columns by means of a UDF and explode the zipped column as follows:

```<code>val df = Seq(
  (1, Seq(2, 3, 4), Seq(5, 6, 7))
).toDF("ColA", "ColB", "ColC")

def zip = udf(
  (x: Seq[Int], y: Seq[Int]) => x zip y
)

val df2 = df.select($"ColA", zip($"ColB", $"ColC").as("BzipC")).
  withColumn("BzipC", explode($"BzipC"))

val df3 = df2.select($"ColA", $"BzipC._1".as("ColB"), $"BzipC._2".as("ColC"))

df3.show
+----+----+----+
|ColA|ColB|ColC|
+----+----+----+
|   1|   2|   5|
|   1|   3|   6|
|   1|   4|   7|
+----+----+----+
</code>```

Title: Parse nested data using SCALA

Body:
I have the dataframe as follows :

ColA  ColB     ColC
1     [2,3,4] [5,6,7]

I need to convert it to the below

ColA ColB ColC
1    2    5
1    3    6
1    4    7

Can someone please help with the Code in SCALA?

Body:
You can zip the two array columns by means of a UDF and explode the zipped column as follows:

val df = Seq(
  (1, Seq(2, 3, 4), Seq(5, 6, 7))
).toDF("ColA", "ColB", "ColC")

def zip = udf(
  (x: Seq[Int], y: Seq[Int]) => x zip y
)

val df2 = df.select($"ColA", zip($"ColB", $"ColC").as("BzipC")).
  withColumn("BzipC", explode($"BzipC"))

val df3 = df2.select($"ColA", $"BzipC._1".as("ColB"), $"BzipC._2".as("ColC"))

df3.show
+----+----+----+
|ColA|ColB|ColC|
+----+----+----+
|   1|   2|   5|
|   1|   3|   6|
|   1|   4|   7|
+----+----+----+


问:
Python Monkey Patch shutil
I'm trying to monkey patch shutil.copyfileobj() function, in order to change its default length from 16*1024 to a larger value (128*1024). Internally, other shutil methods like move call the copyfileobj() function, and I want those calls to be affected by the monkey patch as well. This doesn't seem to work:

```<code>import shutil

shutil.copyfileobjOrig = shutil.copyfileobj

def copyfileobjFast(fsrc, fdst, length=16*1024):
    print('COPYING FILE FAST')
    shutil.copyfileobjOrig(fsrc, fdst, length=128*1024)

shutil.copyfileobj = copyfileobjFast

shutil.move('test.txt', 'testmove.txt')
</code>```

I would expect this to print "COPYING FILE FAST" but it doesn't. Is there any way to achieve what I'm trying to do?

答:
My test case was broken. shutil.move() only performs a copy if the source and destination files are on different devices. Here's an updated version that shows the monkey patch worked:</p>

```<code>import shutil

shutil.copyfileobjOrig = shutil.copyfileobj

def copyfileobjFast(fsrc, fdst, length=16*1024):
    print('COPYING FILE FAST')
    shutil.copyfileobjOrig(fsrc, fdst, length=128*1024)

shutil.copyfileobj = copyfileobjFast

shutil.move('/dev1/test.txt', '/dev2/testmove.txt')
</code>```

Title: Python Monkey Patch shutil

Body:
I'm trying to monkey patch shutil.copyfileobj() function, in order to change its default length from 16*1024 to a larger value (128*1024). Internally, other shutil methods like move call the copyfileobj() function, and I want those calls to be affected by the monkey patch as well. This doesn't seem to work:

import shutil

shutil.copyfileobjOrig = shutil.copyfileobj

def copyfileobjFast(fsrc, fdst, length=16*1024):
    print('COPYING FILE FAST')
    shutil.copyfileobjOrig(fsrc, fdst, length=128*1024)

shutil.copyfileobj = copyfileobjFast

shutil.move('test.txt', 'testmove.txt')

I would expect this to print "COPYING FILE FAST" but it doesn't. Is there any way to achieve what I'm trying to do?

Body:
My test case was broken. shutil.move() only performs a copy if the source and destination files are on different devices. Here's an updated version that shows the monkey patch worked:

import shutil

shutil.copyfileobjOrig = shutil.copyfileobj

def copyfileobjFast(fsrc, fdst, length=16*1024):
    print('COPYING FILE FAST')
    shutil.copyfileobjOrig(fsrc, fdst, length=128*1024)

shutil.copyfileobj = copyfileobjFast

shutil.move('/dev1/test.txt', '/dev2/testmove.txt')


问:
Is there a good admin generator for Ruby on Rails?
My current project is in Rails.  Coming from a Symfony (PHP) and Django (Python) background, they both have excellent admin generators.  Seems like this is missing in Rails.

For those who aren't familiar with Symfony or Django, they both allow you to specify some metadata around your models to automatically (dynamically) generate an admin interface to do the common CRUD operations.  You can create an entire Intranet with only a few commands or lines of code.  They have a good appearance and are extensible enough for 99% of your admin needs.

I've looked for something similar for Rails, but all of the projects either have no activity or they died long ago.  Is there anything to generate an intranet/admin site for a rails app other than scaffolding?

答:
rails_admin appears to be the latest-n-greatest free project as of January 2011.

...best of all, there has been a lot of activity in the repository.

OwnerDisplayName: jcoby


问:
How to get email address from the emails inside an Oulook folder via PowerShell?
I have an Outlook folder, let's call it LoremIpsum, where I have more than 1000+ email drafts that I want to enumarate and do some filtering via PowerShell. I can access the folder and see the emails already, using this script:

```<code>Function HandleRemaining {
    [CmdletBinding()]
    Param()

    BEGIN {
        Clear-Host
    }

    PROCESS {
        $outlook = New-Object -ComObject outlook.application
        $mapi = $outlook.getnamespace("MAPI");

        $email = $mapi.Folders.Item(1).Folders.Item('LoremIpsum').Items(1)

        foreach ($recip in $email.Recipients) {
           $recip
        }

        $email.To
        $email.CC
    }

    END {
    }
}

HandleRemaining
</code>```

The problem is that neither $recip nor $email.To return the email address of the To or CC of that email, instead I get the person's resolved name, example:

```<code>Application           : Microsoft.Office.Interop.Outlook.ApplicationClass
Class                 : 4
Session               : Microsoft.Office.Interop.Outlook.NameSpaceClass
Parent                : System.__ComObject
Address               : /o=ExchangeLabs/ou=Exchange Administrative Group (ALPHA-NUMERIC)/cn=Recipients/cn=LONG-ALPHANUMERIC-HERE
AddressEntry          : System.__ComObject
AutoResponse          :
DisplayType           : 0
EntryID               : <snip>
Index                 : 1
MeetingResponseStatus : 0
Name                  : John Walker
Resolved              : True
TrackingStatus        : 0
TrackingStatusTime    : 01-Jan-01 00:00:00
Type                  : 1
PropertyAccessor      : System.__ComObject
Sendable              : True

John Walker
</code>```

I changed the numbers and codes to preserve privacy, but that's the return I get. So, how can I get the proper emaill address of the recipients of a given email draft?

答:
I think you need to use the PropertyAccessor.

```<code>$PR_SMTP_ADDRESS = "http://schemas.microsoft.com/mapi/proptag/0x39FE001E"
$smtpAddress = $recip.PropertyAccessor.GetProperty($PR_SMTP_ADDRESS)
</code>```

See here (Warning! VBA): https://msdn.microsoft.com/en-us/VBA/Outlook-VBA/articles/obtain-the-e-mail-address-of-a-recipient

Body:
I have an Outlook folder, let's call it LoremIpsum, where I have more than 1000+ email drafts that I want to enumarate and do some filtering via PowerShell. I can access the folder and see the emails already, using this script:

Function HandleRemaining {
    [CmdletBinding()]
    Param()

    BEGIN {
        Clear-Host
    }

    PROCESS {
        $outlook = New-Object -ComObject outlook.application
        $mapi = $outlook.getnamespace("MAPI");

        $email = $mapi.Folders.Item(1).Folders.Item('LoremIpsum').Items(1)

        foreach ($recip in $email.Recipients) {
           $recip
        }

        $email.To
        $email.CC
    }

    END {
    }
}

HandleRemaining

The problem is that neither $recip nor $email.To return the email address of the To or CC of that email, instead I get the person's resolved name, example:

Application           : Microsoft.Office.Interop.Outlook.ApplicationClass
Class                 : 4
Session               : Microsoft.Office.Interop.Outlook.NameSpaceClass
Parent                : System.__ComObject
Address               : /o=ExchangeLabs/ou=Exchange Administrative Group (ALPHA-NUMERIC)/cn=Recipients/cn=LONG-ALPHANUMERIC-HERE
AddressEntry          : System.__ComObject
AutoResponse          :
DisplayType           : 0
EntryID               : <snip>
Index                 : 1
MeetingResponseStatus : 0
Name                  : John Walker
Resolved              : True
TrackingStatus        : 0
TrackingStatusTime    : 01-Jan-01 00:00:00
Type                  : 1
PropertyAccessor      : System.__ComObject
Sendable              : True

John Walker

I changed the numbers and codes to preserve privacy, but that's the return I get. So, how can I get the proper emaill address of the recipients of a given email draft?

Body:
I think you need to use the PropertyAccessor.

$PR_SMTP_ADDRESS = "http://schemas.microsoft.com/mapi/proptag/0x39FE001E"
$smtpAddress = $recip.PropertyAccessor.GetProperty($PR_SMTP_ADDRESS)

See here (Warning! VBA): https://msdn.microsoft.com/en-us/VBA/Outlook-VBA/articles/obtain-the-e-mail-address-of-a-recipient