问:
Excel VBA Msxml2.XMLHTTP.6.0 vs Msxml2.ServerXMLHTTP.6.0
I am a self-taught, amateur programmer, and I am new to this forum. Please bear with me.

About two years ago, I wrote a simple Excel vba program to login in to a website and grab a customer statement in the form of a .csv file. My program utilizes GET and POST requests. This program worked perfectly (for my needs) until about three weeks ago, when it unfortunately broke on me. The program could not get through the initial GET request. Specifically, it would break on the getReq.send line.

I came across this post:
Login into website using MSXML2.XMLHTTP instead of InternetExplorer.Application with VBA

Here, I learned that you can use "Msxml2.XMLHTTP.6.0" instead of "Msxml2.ServerXMLHTTP.6.0". I modified my code accordingly, eliminating the need to parse cookies after the Get request, and it worked! But I have no idea. Even though I got it to work, I do not feel like I have learned much in the process.

Some information to note:

My original program broke on my work computer (WindowsXP).

Figuring that it may be an XP issue, and in the market for a new machine anyway, I updated to a new computer running Windows7. The program still did not work, though I received a different error message.

I ran my code on a Windows10 computer and it worked fine.

I use identical code to connect to various other websites and it works fine, regardless of what operating system.

So, my specific questions:

Why might the code work with Msxml2.XMLHTTP.6.0 but not Msxml2.ServerXMLHTTP.6.0?

And why might the code have broken in the first place?

Why would the code work on one particular website, but no another?

Any insight would be greatly appreciated. I have attached my code (with login info X'd out).

```<code>Sub RCGInquiry()

    Dim postReq, getReq, cookies
    Dim p0 As Integer, p1 As Integer, temp As String
    Dim result As String, respHead As String

    Set getReq = CreateObject("Msxml2.ServerXMLHTTP.6.0")
    'Set getReq = CreateObject("Msxml2.XMLHTTP.6.0")

    ' Visit homepage so we can find the cookies
    getReq.Open "GET", "https://www.rcginquiry.com/sfs/Entry", False
    getReq.send

    respHead = getReq.getAllResponseHeaders

     Debug.Print respHead

    ' Need to parse the cookie from Respone Headers
    cookies = ""
    p0 = 1
    Do While InStr(p0, respHead, "Set-Cookie:") > 0
        p0 = InStr(p0, respHead, "Set-Cookie:") + 11
        p1 = InStr(p0, respHead, Chr(10))
        temp = Trim(Mid(respHead, p0, p1 - p0))
        cookies = cookies & temp & "; "
    Loop
    cookies = Left(cookies, Len(cookies) - 2)

    ' Debug.Print cookies

    ' Login
    Set postReq = CreateObject("Msxml2.ServerXMLHTTP.6.0")
    'Set postReq = CreateObject("Msxml2.XMLHTTP.6.0")
    postReq.Open "POST", "https://www.rcginquiry.com/sfs/Entry", False
    postReq.setRequestHeader "Cookie", cookies
    postReq.setRequestHeader "Content-type", "application/x-www-form-urlencoded" 'send appropriate Headers
    postReq.send "Usrid=XXXX&Psswd=XXXX" ' send login info

    '-------------------------------------------------------------------------------

    '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
    Dim FSO As Object
    Dim myFile As Object
    Dim path As String
    Dim y As Integer

    curDate = Format(Date, "mm_dd_yy")

    ' Download CSV
    postReq.Open "POST", "https://www.rcginquiry.com/sfs/Downloads/tmp.csv?filetype=POS&format=MFA20&heading=true&allaccts=true&junk=tmp.csv", False
    postReq.setRequestHeader "Cookie", cookies 'must resend cookies so it knows i am logged in
    postReq.setRequestHeader "Content-type", "application/x-www-form-urlencoded"
    postReq.send "filetype=POS&format=MFA20&heading=true&allaccts=true&junk=temp.csv" 'url query parameters

    ' Writes responseText to a .csv file
    Set FSO = CreateObject("Scripting.FileSystemObject")
    Set myFile = FSO.createtextfile("C:\Users\Adam\Desktop\POSITION\" & curDate & ".csv", True)
    myFile.write (postReq.responseText)
    myFile.Close

    Set FSO = Nothing
    Set myFile = Nothing

End Sub
</code>```

答: This blog post says that ServerXLMHTTP will not work through a proxy on the client, but XMLHTTP will.  In Excel VBA I was using ServerXLMHTTP.6.0, and it was failing for some clients inside corporate networks, whereas XMLHTTP worked.</p>

Body:
I am a self-taught, amateur programmer, and I am new to this forum. Please bear with me.

About two years ago, I wrote a simple Excel vba program to login in to a website and grab a customer statement in the form of a .csv file. My program utilizes GET and POST requests. This program worked perfectly (for my needs) until about three weeks ago, when it unfortunately broke on me. The program could not get through the initial GET request. Specifically, it would break on the getReq.send line.

I came across this post:
Login into website using MSXML2.XMLHTTP instead of InternetExplorer.Application with VBA

Here, I learned that you can use "Msxml2.XMLHTTP.6.0" instead of "Msxml2.ServerXMLHTTP.6.0". I modified my code accordingly, eliminating the need to parse cookies after the Get request, and it worked! But I have no idea. Even though I got it to work, I do not feel like I have learned much in the process.

Some information to note:

My original program broke on my work computer (WindowsXP).

Figuring that it may be an XP issue, and in the market for a new machine anyway, I updated to a new computer running Windows7. The program still did not work, though I received a different error message.

I ran my code on a Windows10 computer and it worked fine.

I use identical code to connect to various other websites and it works fine, regardless of what operating system.

So, my specific questions:

Why might the code work with Msxml2.XMLHTTP.6.0 but not Msxml2.ServerXMLHTTP.6.0?

And why might the code have broken in the first place?

Why would the code work on one particular website, but no another?

Any insight would be greatly appreciated. I have attached my code (with login info X'd out).

Sub RCGInquiry()

    Dim postReq, getReq, cookies
    Dim p0 As Integer, p1 As Integer, temp As String
    Dim result As String, respHead As String

    Set getReq = CreateObject("Msxml2.ServerXMLHTTP.6.0")
    'Set getReq = CreateObject("Msxml2.XMLHTTP.6.0")

    ' Visit homepage so we can find the cookies
    getReq.Open "GET", "https://www.rcginquiry.com/sfs/Entry", False
    getReq.send

    respHead = getReq.getAllResponseHeaders

     Debug.Print respHead

    ' Need to parse the cookie from Respone Headers
    cookies = ""
    p0 = 1
    Do While InStr(p0, respHead, "Set-Cookie:") > 0
        p0 = InStr(p0, respHead, "Set-Cookie:") + 11
        p1 = InStr(p0, respHead, Chr(10))
        temp = Trim(Mid(respHead, p0, p1 - p0))
        cookies = cookies & temp & "; "
    Loop
    cookies = Left(cookies, Len(cookies) - 2)

    ' Debug.Print cookies

    ' Login
    Set postReq = CreateObject("Msxml2.ServerXMLHTTP.6.0")
    'Set postReq = CreateObject("Msxml2.XMLHTTP.6.0")
    postReq.Open "POST", "https://www.rcginquiry.com/sfs/Entry", False
    postReq.setRequestHeader "Cookie", cookies
    postReq.setRequestHeader "Content-type", "application/x-www-form-urlencoded" 'send appropriate Headers
    postReq.send "Usrid=XXXX&Psswd=XXXX" ' send login info

    '-------------------------------------------------------------------------------

    '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
    Dim FSO As Object
    Dim myFile As Object
    Dim path As String
    Dim y As Integer

    curDate = Format(Date, "mm_dd_yy")

    ' Download CSV
    postReq.Open "POST", "https://www.rcginquiry.com/sfs/Downloads/tmp.csv?filetype=POS&format=MFA20&heading=true&allaccts=true&junk=tmp.csv", False
    postReq.setRequestHeader "Cookie", cookies 'must resend cookies so it knows i am logged in
    postReq.setRequestHeader "Content-type", "application/x-www-form-urlencoded"
    postReq.send "filetype=POS&format=MFA20&heading=true&allaccts=true&junk=temp.csv" 'url query parameters

    ' Writes responseText to a .csv file
    Set FSO = CreateObject("Scripting.FileSystemObject")
    Set myFile = FSO.createtextfile("C:\Users\Adam\Desktop\POSITION\" & curDate & ".csv", True)
    myFile.write (postReq.responseText)
    myFile.Close

    Set FSO = Nothing
    Set myFile = Nothing

End Sub


来源: stackexchange

问:
neo4j get parent of a node of a given id
I have this Neo4J database and I have the id of the nodes of interest. I need to find the parent of those nodes.
How can I do this?
I am using py2neo and I have a neo4j object.

Problem is I don't know Cypher at all and not even Gremlin.
What cypher query will give me the result?

答:
Since you are not sharing your data model I'm assuming you have nodes with :PARENT_OF relationship between them. Something like (:Node)-[:PARENT_OF]->(:Node).

If you have the internal id of the node of interest, you should use the id() function:

```<code>MATCH (nodeOfInterest:Node)<-[:PARENT_OF]-(parent:Parent)
WHERE id(nodeOfInterest) = 10
RETURN parent
</code>```

If the id you have is a property, then you can directly use it in the pattern matching:

```<code>MATCH (nodeOfInterest:Node {id : 10})<-[:PARENT_OF]-(parent:Parent)
RETURN parent
</code>```

I suggest you to take a look in these links:

Neo4j Developer Manual - Introduction

Neo4j free e-books

Neo4j Free Online Training

ContentLicense: CC BY-SA 3.0

Body:
Since you are not sharing your data model I'm assuming you have nodes with :PARENT_OF relationship between them. Something like (:Node)-[:PARENT_OF]->(:Node).

If you have the internal id of the node of interest, you should use the id() function:

MATCH (nodeOfInterest:Node)<-[:PARENT_OF]-(parent:Parent)
WHERE id(nodeOfInterest) = 10
RETURN parent

If the id you have is a property, then you can directly use it in the pattern matching:

MATCH (nodeOfInterest:Node {id : 10})<-[:PARENT_OF]-(parent:Parent)
RETURN parent

I suggest you to take a look in these links:

Neo4j Developer Manual - Introduction

Neo4j free e-books

Neo4j Free Online Training


答:
1) data.frame Create a grouping variable g and perform the na.locf separately on each group of rows separately.

```<code>library(zoo)

g <- DF$time > "16:00:00"
replace(DF, -1, do.call("rbind", by(DF[-1], g, na.locf, na.rm = FALSE)))
</code>```

giving:

```<code>      time  A  B
1 15:58:00 23 24
2 15:59:00 22 23
3 16:00:00 20 22
4 17:01:00 NA NA
5 17:02:00 NA 30
6 17:03:00 25 30
7 17:04:00 26 31
8 17:05:00 26 31
</code>```

2) data.table If speed is an issue try data.table using g from above:

```<code>library(data.table)

DT <- as.data.table(DF)
DT[, cbind(.SD[, 1], na.locf(.SD)[, -1]), by = g][, -1]
</code>```

3) zoo series With zoo objects it simplifies:

```<code>library(chron)
library(zoo)

z <- read.zoo(DF, FUN = times)  # test input

g <- time(z) > "16:00:00"
do.call("rbind", lapply(split(z, g), na.locf, na.rm = FALSE))
</code>```

3a) Another way to do this using z is the following.

```<code>pre4 <- time(z) <= "16:00:00"
rbind( na.locf(z[pre4, ], na.rm = FALSE),
       na.locf(z[!pre4, ], na.rm = FALSE))
</code>```

3b) or using pre4 from above:

```<code>zz <- z
zz[pre4, ] <- na.locf(z[pre4, ], na.rm = FALSE)
zz[!pre4, ] <- na.locf(z[!pre4, ], na.rm = FALSE)
</code>```

Note: The input in reproducible form is:

```<code>Lines <- "
time       A    B
15:58:00   23   24
15:59:00   22   23
16:00:00   20   22
17:01:00   NA   NA
17:02:00   NA   30
17:03:00   25   NA
17:04:00   26   31
17:05:00   NA   31"
DF <- read.table(text = Lines, header = TRUE, as.is = TRUE)
</code>```

Title: How to use na.locf with time limits to avoid filling across market close?

Body:
I am working with futures contracts which close at 4 PM or 16:00 Central Time and re-open at 5 PM or or possibly later. I can filter the data for when it is closed, but when I do na.locf it still fills in data from 4 PM on.

Here is a small example and how I generated the xts data including 2 days:

days1 <- c("2017-05-05 15:58","2017-05-05 15:59","2017-05-05 16:00","2017-05-05 17:01","2017-05-05 17:02","2017-05-05 17:03","2017-05-05 17:04","2017-05-05 17:05")
test2 = xts(as.numeric(c(24,23,22,"NA","30","NA",31,"31")),order.by = as.POSIXct(days1, tz = "America/Chicago"))
test2 = xts(as.numeric(c(24,23,22,"NA","30","NA",31,"31")),order.by = as.POSIXct(days1, tz = "America/Chicago"))
t1 <- cbind(test1,test2)
t2 <- t1
index(t2) = index(t1)+(60*60*24)
DF <-rbind(t1,t2)
colnames(DF) <- c("Bid","Ask")

> DF
                    Bid Ask
2017-05-05 15:58:00  23  24
2017-05-05 15:59:00  22  23
2017-05-05 16:00:00  20  22
2017-05-05 17:01:00  NA  NA
2017-05-05 17:02:00  NA  30
2017-05-05 17:03:00  25  NA
2017-05-05 17:04:00  26  31
2017-05-05 17:05:00  NA  31
2017-05-06 15:58:00  23  24
2017-05-06 15:59:00  22  23
2017-05-06 16:00:00  20  22
2017-05-06 17:01:00  NA  NA
2017-05-06 17:02:00  NA  30
2017-05-06 17:03:00  25  NA
2017-05-06 17:04:00  26  31
2017-05-06 17:05:00  NA  31

And the desired result on the new data.

                    Bid Ask
2017-05-05 15:58:00  23  24
2017-05-05 15:59:00  22  23
2017-05-05 16:00:00  20  22
2017-05-05 17:01:00  NA  NA
2017-05-05 17:02:00  NA  30
2017-05-05 17:03:00  25  30
2017-05-05 17:04:00  26  31
2017-05-05 17:05:00  26  31
2017-05-06 15:58:00  23  24
2017-05-06 15:59:00  22  23
2017-05-06 16:00:00  20  22
2017-05-06 17:01:00  NA  NA
2017-05-06 17:02:00  NA  30
2017-05-06 17:03:00  25  30
2017-05-06 17:04:00  26  31
2017-05-06 17:05:00  26  31

I updated the sample data with an xts object. I am sure there is an easier and faster way to make one, but that would be another question.

Normal na.locf will fill the na's at 17:01 and 17:02 which would result in bad data. But filling the data past 17:00 is perfectly fine.

I don't think maxgap would work as I might not have a small gap, and still not want to fill.

I can see two ways of doing this. One is to have na.locf not fill if the difference in time-stamps is greater than one hour.
Or it may be even better to simply never fill past a certain time such as 16:00 in this case.

This should be fast so I would like to avoid any loops such as spiting the data by days and then re-merging unless it is with a quick vectorized method.

I would also be ok with an Rcpp solution if it can correctly handle the timestamps.
Update:
This is my rcpp code which works where the differance between rows is beyond a threshold.

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
Rcpp::NumericMatrix naLocf(const Rcpp::NumericMatrix& DataMatrix, int maxDiffSeconds = 0)
{
  Rcpp::NumericMatrix res = clone(DataMatrix);
  Rcpp::NumericVector Index = res.attr("index");
  int numRow = res.nrow();
  int numCol = res.ncol();
  for (int ii = 1;ii<numRow;ii++)
  {
    if(maxDiffSeconds == 0 || Index(ii)-Index(ii-1) < maxDiffSeconds)
    {
      for (int jj = 0;jj<numCol;jj++)
      {
        if(Rcpp::NumericMatrix::is_na(res(ii,jj)))
        {
          res(ii,jj) = res(ii-1,jj);
        }
      }
    }
  }
  return res;
}

And to execute:

DF2 = naLocf(DF,60*60)

It works because the xts index is a number in seconds from 1970-01-01. So if the difference is beyond the values of 3600 or one hour, I don't replace the NAs.

As far as part 2 the time specific stop at "16:00" can basically done with GMT the time value is direct so the time value modulo 86400 and 16:00 is 57600 of the remainder.
But with different time zones, the time value changes, but by different amounts based on daylight savings so I have been unable to get a consistent time to work.

Body:
1) data.frame Create a grouping variable g and perform the na.locf separately on each group of rows separately.

library(zoo)

g <- DF$time > "16:00:00"
replace(DF, -1, do.call("rbind", by(DF[-1], g, na.locf, na.rm = FALSE)))

giving:

      time  A  B
1 15:58:00 23 24
2 15:59:00 22 23
3 16:00:00 20 22
4 17:01:00 NA NA
5 17:02:00 NA 30
6 17:03:00 25 30
7 17:04:00 26 31
8 17:05:00 26 31

2) data.table If speed is an issue try data.table using g from above:

library(data.table)

DT <- as.data.table(DF)
DT[, cbind(.SD[, 1], na.locf(.SD)[, -1]), by = g][, -1]

3) zoo series With zoo objects it simplifies:

library(chron)
library(zoo)

z <- read.zoo(DF, FUN = times)  # test input

g <- time(z) > "16:00:00"
do.call("rbind", lapply(split(z, g), na.locf, na.rm = FALSE))

3a) Another way to do this using z is the following.

pre4 <- time(z) <= "16:00:00"
rbind( na.locf(z[pre4, ], na.rm = FALSE),
       na.locf(z[!pre4, ], na.rm = FALSE))

3b) or using pre4 from above:

zz <- z
zz[pre4, ] <- na.locf(z[pre4, ], na.rm = FALSE)
zz[!pre4, ] <- na.locf(z[!pre4, ], na.rm = FALSE)

Note: The input in reproducible form is:

Lines <- "
time       A    B
15:58:00   23   24
15:59:00   22   23
16:00:00   20   22
17:01:00   NA   NA
17:02:00   NA   30
17:03:00   25   NA
17:04:00   26   31
17:05:00   NA   31"
DF <- read.table(text = Lines, header = TRUE, as.is = TRUE)


问:
open function python not working in __main__.py
I would like to use the __main__.py file to run code from. Only the code won't open() files in de dir.
I used a core.py file that did work with the following code:

```<code>with open("data/netlist.txt") as f:
    self.list = f.read()
</code>```

In the new main file the error is:

```<code>with open("data/netlist.txt") as f:
FileNotFoundError: [Errno 2] No such file or directory: 'data/netlist.txt'
</code>```

The folder looks like this:

答:
The solution was simple the path changes when using a __main__.py instead of a core.py.</p>

```<code>with open("sample/data/netlist.txt") as f:
    self.list = f.read()
</code>```

Body:
I would like to use the __main__.py file to run code from. Only the code won't open() files in de dir.
I used a core.py file that did work with the following code:

with open("data/netlist.txt") as f:
    self.list = f.read()

In the new main file the error is:

with open("data/netlist.txt") as f:
FileNotFoundError: [Errno 2] No such file or directory: 'data/netlist.txt'

The folder looks like this:

Body:
The solution was simple the path changes when using a __main__.py instead of a core.py.

with open("sample/data/netlist.txt") as f:
    self.list = f.read()


问:
how to compile shader in swift, location always return -1

I have written a piece of code to compile a shader.

```<code>class DFShader {
    let ID: GLuint

    init(vPath: String, fPath: String) {
        ID = glCreateProgram()
        let vertex = compile(type: GLenum(GL_VERTEX_SHADER), path: vPath)
        let fragment = compile(type: GLenum(GL_FRAGMENT_SHADER), path: fPath)

        var success: GLint = 1
        glAttachShader(ID, vertex)
        glAttachShader(ID, fragment)
        glLinkProgram(ID)
        glGetProgramiv(ID, GLenum(GL_LINK_STATUS), &success)
        if success == GL_FALSE {
            let infoLog = UnsafeMutablePointer<GLchar>.allocate(capacity: 512)
            glGetProgramInfoLog(ID, 512, nil, infoLog)
            print("link program error. \(String.init(cString: infoLog))")
        }
        glDeleteShader(vertex)
        glDeleteShader(fragment)

        //log
        print("model", glGetUniformLocation(ID, "model")) // print 4
        print("projection", glGetUniformLocation(ID, "projection")) // print 0
        print(ID.description)
    }

    private func compile(type: GLenum, path: String) -> GLuint {
        let shader = glCreateShader(type)
        var success: GLint = 1
        do {
            let source = try String.init(contentsOfFile: path, encoding: String.Encoding.utf8).cString(using: String.Encoding.utf8)
            var castSource = UnsafePointer<GLchar>(source)
            glShaderSource(shader, 1, &castSource, nil)
            glCompileShader(shader)
            glGetShaderiv(shader, GLenum(GL_COMPILE_STATUS), &success)
            if success == GL_FALSE {
                let infoLog = UnsafeMutablePointer<GLchar>.allocate(capacity: 512)
                glGetShaderInfoLog(shader, 512, nil, &infoLog.pointee)
                print("compile error. \(String.init(cString: infoLog))")
            }
        } catch {
            print("failed to read from shader source file.")
        }
        return shader
    }

    func use() {
        glUseProgram(ID)
    }
}

//vertex shader code
#version 300 es
layout(location = 0) in vec2 position;
out vec4 VertexColor;
uniform mat4 model;
uniform mat4 projection;
uniform float pointSize;
uniform vec4 color;
void main() {
    VertexColor = color;
    gl_Position = projection * model * vec4(position, 0.0, 1.0);
gl_PointSize = 10.0f;
}

//fragment shader code
#version 300 es
precision mediump float;
out vec4 FragColor;
in vec4 VertexColor;
void main() {
    FragColor = VertexColor;
}

//In the view
...
func setupShaders() {
    shader.use()
    let projection = GLKMatrix4MakeOrtho(0, Float(width), 0, Float(height), -1, 1)
    shader.setMat4(name: "projection", value: projection)
    print("projection", glGetUniformLocation(shader.ID, "projection")) // print -1.

...
}
</code>```

I want to get the right location of all uniform and attribute value.

But the uniform location I get from DFShader instance is -1. And I only get the right location in

```<code>init(vPath: String, fPath: String)
</code>```

, which print 0 and 4 in the code above.
However, when I get location in

```<code>setupShaders()
</code>```

it return -1. I get location with shader.ID at any other place, I am also given -1.

答:
Shader objects don't have uniform locations. Only program objects do.

A shader object is nothing more than an intermediary between textual shaders and the final program. They don't actually do much. They don't have state to query.

Body:
I have written a piece of code to compile a shader.

class DFShader {
    let ID: GLuint

    init(vPath: String, fPath: String) {
        ID = glCreateProgram()
        let vertex = compile(type: GLenum(GL_VERTEX_SHADER), path: vPath)
        let fragment = compile(type: GLenum(GL_FRAGMENT_SHADER), path: fPath)

        var success: GLint = 1
        glAttachShader(ID, vertex)
        glAttachShader(ID, fragment)
        glLinkProgram(ID)
        glGetProgramiv(ID, GLenum(GL_LINK_STATUS), &success)
        if success == GL_FALSE {
            let infoLog = UnsafeMutablePointer<GLchar>.allocate(capacity: 512)
            glGetProgramInfoLog(ID, 512, nil, infoLog)
            print("link program error. \(String.init(cString: infoLog))")
        }
        glDeleteShader(vertex)
        glDeleteShader(fragment)

        //log
        print("model", glGetUniformLocation(ID, "model")) // print 4
        print("projection", glGetUniformLocation(ID, "projection")) // print 0
        print(ID.description)
    }

    private func compile(type: GLenum, path: String) -> GLuint {
        let shader = glCreateShader(type)
        var success: GLint = 1
        do {
            let source = try String.init(contentsOfFile: path, encoding: String.Encoding.utf8).cString(using: String.Encoding.utf8)
            var castSource = UnsafePointer<GLchar>(source)
            glShaderSource(shader, 1, &castSource, nil)
            glCompileShader(shader)
            glGetShaderiv(shader, GLenum(GL_COMPILE_STATUS), &success)
            if success == GL_FALSE {
                let infoLog = UnsafeMutablePointer<GLchar>.allocate(capacity: 512)
                glGetShaderInfoLog(shader, 512, nil, &infoLog.pointee)
                print("compile error. \(String.init(cString: infoLog))")
            }
        } catch {
            print("failed to read from shader source file.")
        }
        return shader
    }

    func use() {
        glUseProgram(ID)
    }
}

//vertex shader code
#version 300 es
layout(location = 0) in vec2 position;
out vec4 VertexColor;
uniform mat4 model;
uniform mat4 projection;
uniform float pointSize;
uniform vec4 color;
void main() {
    VertexColor = color;
    gl_Position = projection * model * vec4(position, 0.0, 1.0);
gl_PointSize = 10.0f;
}

//fragment shader code
#version 300 es
precision mediump float;
out vec4 FragColor;
in vec4 VertexColor;
void main() {
    FragColor = VertexColor;
}

//In the view
...
func setupShaders() {
    shader.use()
    let projection = GLKMatrix4MakeOrtho(0, Float(width), 0, Float(height), -1, 1)
    shader.setMat4(name: "projection", value: projection)
    print("projection", glGetUniformLocation(shader.ID, "projection")) // print -1.

...
}

I want to get the right location of all uniform and attribute value.

But the uniform location I get from DFShader instance is -1. And I only get the right location in

init(vPath: String, fPath: String)

, which print 0 and 4 in the code above.
However, when I get location in

setupShaders()

it return -1. I get location with shader.ID at any other place, I am also given -1.


问:
retrofit2 okhttp3 android multipart socket tomeout error
I am trying to upload a file with Retrofit 2 and it is giving me
"socket timed connection out" error every time even after adding the timeout limits. Any suggestions on how to fix this -

My Rest client setup -

```<code>private static void setupRestClient() {
        if(LoginToken != null && !LoginToken.isEmpty()) {
            OkHttpClient httpClient = new OkHttpClient();
            httpClient.interceptors().add(new Interceptor() {
                @Override
                public Response intercept(Chain chain) throws IOException {
                    Request request = chain.request().newBuilder().addHeader("Authorization", "Bearer "+ LoginToken).build();
                    return chain.proceed(request);
                }
            });
            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .client(httpClient)
                    .build();
            REST_CLIENT = retrofit.create(Api.class);
        } else {
            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
            REST_CLIENT = retrofit.create(Api.class);
        }
    }
</code>```

After reading several answers on SO, I also tried -

```<code>OkHttpClient httpClient = new OkHttpClient.Builder()
                    .connectTimeout(12, TimeUnit.MINUTES)
                    .readTimeout(12, TimeUnit.MINUTES)
                    .writeTimeout(12, TimeUnit.MINUTES).build();
</code>```

But, got the same timeout error with this also.
File upload starting intent -

```<code>Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if(takePictureIntent.resolveActivity(EduwiserMainActivity.this.getPackageManager()) != null){
            File photoFile = null;
            try{
                photoFile = createImageFile();
                takePictureIntent.putExtra("PhotoPath", mCM);
            } catch(IOException ex){
                Log.e("Error:", "Image file creation failed", ex);
            }
            if(photoFile != null){
                dfCM = "file:" + photoFile.getAbsolutePath();
                mCM = photoFile.getPath();
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
            } else {
                takePictureIntent = null;
            }
        }
        Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
        contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
        contentSelectionIntent.setType("image/*");
        Intent[] intentArray;
        if(takePictureIntent != null){
            intentArray = new Intent[]{takePictureIntent};
        } else {
            intentArray = new Intent[0];
        }

        Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
        chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
        chooserIntent.putExtra(Intent.EXTRA_TITLE, "Choose image");
        chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
        startActivityForResult(chooserIntent, FCR);
</code>```

on intent activity result -

```<code>if(requestCode == FCR && resultCode == -1){
            try {
                File file = null;
                String[] proj = { MediaStore.Images.Media.DATA };
                String localPath = mCM != null && !mCM.isEmpty() ? mCM.replace("file:", "") : null;
                if(data == null || data.getData() == null){
                    //Capture Photo if no image available
                    if(localPath != null){
                        file = new File(localPath);
                    }
                } else {
                    String dataString = data.getDataString();
                    if(dataString != null){
                        try {
                            file = new File(PathUtil.getPath(this, Uri.parse(dataString)));
                        } catch (Exception e){
                            Log.e("error", e.toString());
                        }
                    }
                }
                final File newFile = file;
                defaultPd = new ProgressDialog(EduwiserMainActivity.this);
                if(token != null && !token.isEmpty() && newFile != null && documentUploadFileType != null && !documentUploadFileType.isEmpty()){
                    try {
                        if(defaultPd != null && !defaultPd.isShowing()) {
                            defaultPd.show();
                            defaultPd.setMessage("Uploading file...");
                        }
                        RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), newFile);
                        MultipartBody.Part body = MultipartBody.Part.createFormData(!Objects.equals(documentUploadFileType, "profile") ? documentUploadFileType + "_file":
                                documentUploadFileType, documentUploadFileType + ".jpg", requestFile);
                        documentUploadFileType = null;
                        Call<LocalAuthResponse> call = RestClient.get(getApplicationContext()).uploadTeacherDocuments("Bearer " + token, body);
                        call.enqueue(new Callback<LocalAuthResponse>() {
                            @Override
                            public void onResponse(Call<LocalAuthResponse> call, Response<LocalAuthResponse> response) {
                                try {
                                    if(defaultPd != null && defaultPd.isShowing()) {
                                        defaultPd.dismiss();
                                    }
                                } catch (Exception e){}
                                try {
                                    if(response.body() != null && response.body().getSuccess()) {
                                        mWebView.evaluateJavascript("var event = new CustomEvent('refresh_userdata');document.dispatchEvent(event);", null);
                                    }
                                } catch (Exception e){
//                                mWebView.evaluateJavascript("var event = new CustomEvent('refresh_userdata');document.dispatchEvent(event);", null);
                                }
                            }

                            @Override
                            public void onFailure(Call<LocalAuthResponse> call, Throwable t) {
                                Toast.makeText(getApplicationContext(), "Error Uploading Documents. Please try again.", Toast.LENGTH_LONG).show();
                                try {
                                    if(defaultPd != null && defaultPd.isShowing()) {
                                        defaultPd.dismiss();
                                    }
                                } catch (Exception e){}
                                mWebView.evaluateJavascript("var event = new CustomEvent('fail_attachment');document.dispatchEvent(event);", null);
                            }
                        });
                    } catch (Exception e){
                        Log.e("error", e.toString());
                    }
                }
            } catch(Exception e){
                Log.e("error", e.toString());
            }
        } else if(requestCode == FCR){
            mWebView.evaluateJavascript("var event = new CustomEvent('fail_attachment');document.dispatchEvent(event);", null);
        }
</code>```

Now, I am getting "socket timeout error exception" in the onFailure block.
Now, this might be an entirely different error which is throwing socket timeout exception or this is actually because of timeout.
Either way, any suggestions as to how to debug or fix this ?

答:
I am assuming you are getting the valid image file so lets come to upload section

```<code>@Multipart
@POST("api/image/upload")
Call<String> imageUpload(@Part MultipartBody.Part image, @Part("name") RequestBody name);
</code>```

and the upload function

```<code>    private void uploadImage(File file) {
    try {
        if (file.exists()) {
            RequestBody reqFile = RequestBody.create(MediaType.parse("image/*"), file);
            MultipartBody.Part body = MultipartBody.Part.createFormData("upload", file.getName(), reqFile);
            RequestBody name = RequestBody.create(MediaType.parse("text/plain"), "upload_test");
            RestClient.getService().imageUpload(body, name).enqueue(new Callback<String>() {
                @Override
                public void onResponse(@NonNull Call<String> call, @NonNull final Response<String> response) {
                    newImageUrl = response.body();
                }

                @Override
                public void onFailure(@NonNull Call<String> call, @NonNull Throwable t) {

                }
            });
        }
    } catch (Exception e) {
        toast("Please try again");
    }
}
</code>```

and my retrofit looks like this

```<code>new Retrofit.Builder().baseUrl(ConfigHelper.DataServiceUrl)
                .addConverterFactory(converterFactory)
                .client(client
                        .addInterceptor(new Interceptor() {
                            public Response intercept(@NonNull Chain chain) throws IOException {
                                return chain.proceed(chain.request().newBuilder().addHeader("access_key", finalToken).build());
                            }
                        })
                        .addInterceptor(logging)
                        .build()).build();
</code>```

Happy Coding :)

Body:
I am trying to upload a file with Retrofit 2 and it is giving me
"socket timed connection out" error every time even after adding the timeout limits. Any suggestions on how to fix this -

My Rest client setup -

private static void setupRestClient() {
        if(LoginToken != null && !LoginToken.isEmpty()) {
            OkHttpClient httpClient = new OkHttpClient();
            httpClient.interceptors().add(new Interceptor() {
                @Override
                public Response intercept(Chain chain) throws IOException {
                    Request request = chain.request().newBuilder().addHeader("Authorization", "Bearer "+ LoginToken).build();
                    return chain.proceed(request);
                }
            });
            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .client(httpClient)
                    .build();
            REST_CLIENT = retrofit.create(Api.class);
        } else {
            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
            REST_CLIENT = retrofit.create(Api.class);
        }
    }

After reading several answers on SO, I also tried -

OkHttpClient httpClient = new OkHttpClient.Builder()
                    .connectTimeout(12, TimeUnit.MINUTES)
                    .readTimeout(12, TimeUnit.MINUTES)
                    .writeTimeout(12, TimeUnit.MINUTES).build();

But, got the same timeout error with this also.
File upload starting intent -

Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if(takePictureIntent.resolveActivity(EduwiserMainActivity.this.getPackageManager()) != null){
            File photoFile = null;
            try{
                photoFile = createImageFile();
                takePictureIntent.putExtra("PhotoPath", mCM);
            } catch(IOException ex){
                Log.e("Error:", "Image file creation failed", ex);
            }
            if(photoFile != null){
                dfCM = "file:" + photoFile.getAbsolutePath();
                mCM = photoFile.getPath();
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
            } else {
                takePictureIntent = null;
            }
        }
        Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
        contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
        contentSelectionIntent.setType("image/*");
        Intent[] intentArray;
        if(takePictureIntent != null){
            intentArray = new Intent[]{takePictureIntent};
        } else {
            intentArray = new Intent[0];
        }

        Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
        chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
        chooserIntent.putExtra(Intent.EXTRA_TITLE, "Choose image");
        chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
        startActivityForResult(chooserIntent, FCR);

on intent activity result -

if(requestCode == FCR && resultCode == -1){
            try {
                File file = null;
                String[] proj = { MediaStore.Images.Media.DATA };
                String localPath = mCM != null && !mCM.isEmpty() ? mCM.replace("file:", "") : null;
                if(data == null || data.getData() == null){
                    //Capture Photo if no image available
                    if(localPath != null){
                        file = new File(localPath);
                    }
                } else {
                    String dataString = data.getDataString();
                    if(dataString != null){
                        try {
                            file = new File(PathUtil.getPath(this, Uri.parse(dataString)));
                        } catch (Exception e){
                            Log.e("error", e.toString());
                        }
                    }
                }
                final File newFile = file;
                defaultPd = new ProgressDialog(EduwiserMainActivity.this);
                if(token != null && !token.isEmpty() && newFile != null && documentUploadFileType != null && !documentUploadFileType.isEmpty()){
                    try {
                        if(defaultPd != null && !defaultPd.isShowing()) {
                            defaultPd.show();
                            defaultPd.setMessage("Uploading file...");
                        }
                        RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), newFile);
                        MultipartBody.Part body = MultipartBody.Part.createFormData(!Objects.equals(documentUploadFileType, "profile") ? documentUploadFileType + "_file":
                                documentUploadFileType, documentUploadFileType + ".jpg", requestFile);
                        documentUploadFileType = null;
                        Call<LocalAuthResponse> call = RestClient.get(getApplicationContext()).uploadTeacherDocuments("Bearer " + token, body);
                        call.enqueue(new Callback<LocalAuthResponse>() {
                            @Override
                            public void onResponse(Call<LocalAuthResponse> call, Response<LocalAuthResponse> response) {
                                try {
                                    if(defaultPd != null && defaultPd.isShowing()) {
                                        defaultPd.dismiss();
                                    }
                                } catch (Exception e){}
                                try {
                                    if(response.body() != null && response.body().getSuccess()) {
                                        mWebView.evaluateJavascript("var event = new CustomEvent('refresh_userdata');document.dispatchEvent(event);", null);
                                    }
                                } catch (Exception e){
//                                mWebView.evaluateJavascript("var event = new CustomEvent('refresh_userdata');document.dispatchEvent(event);", null);
                                }
                            }

                            @Override
                            public void onFailure(Call<LocalAuthResponse> call, Throwable t) {
                                Toast.makeText(getApplicationContext(), "Error Uploading Documents. Please try again.", Toast.LENGTH_LONG).show();
                                try {
                                    if(defaultPd != null && defaultPd.isShowing()) {
                                        defaultPd.dismiss();
                                    }
                                } catch (Exception e){}
                                mWebView.evaluateJavascript("var event = new CustomEvent('fail_attachment');document.dispatchEvent(event);", null);
                            }
                        });
                    } catch (Exception e){
                        Log.e("error", e.toString());
                    }
                }
            } catch(Exception e){
                Log.e("error", e.toString());
            }
        } else if(requestCode == FCR){
            mWebView.evaluateJavascript("var event = new CustomEvent('fail_attachment');document.dispatchEvent(event);", null);
        }

Now, I am getting "socket timeout error exception" in the onFailure block.
Now, this might be an entirely different error which is throwing socket timeout exception or this is actually because of timeout.
Either way, any suggestions as to how to debug or fix this ?

Body:
I am assuming you are getting the valid image file so lets come to upload section

@Multipart
@POST("api/image/upload")
Call<String> imageUpload(@Part MultipartBody.Part image, @Part("name") RequestBody name);

and the upload function

    private void uploadImage(File file) {
    try {
        if (file.exists()) {
            RequestBody reqFile = RequestBody.create(MediaType.parse("image/*"), file);
            MultipartBody.Part body = MultipartBody.Part.createFormData("upload", file.getName(), reqFile);
            RequestBody name = RequestBody.create(MediaType.parse("text/plain"), "upload_test");
            RestClient.getService().imageUpload(body, name).enqueue(new Callback<String>() {
                @Override
                public void onResponse(@NonNull Call<String> call, @NonNull final Response<String> response) {
                    newImageUrl = response.body();
                }

                @Override
                public void onFailure(@NonNull Call<String> call, @NonNull Throwable t) {

                }
            });
        }
    } catch (Exception e) {
        toast("Please try again");
    }
}

and my retrofit looks like this

new Retrofit.Builder().baseUrl(ConfigHelper.DataServiceUrl)
                .addConverterFactory(converterFactory)
                .client(client
                        .addInterceptor(new Interceptor() {
                            public Response intercept(@NonNull Chain chain) throws IOException {
                                return chain.proceed(chain.request().newBuilder().addHeader("access_key", finalToken).build());
                            }
                        })
                        .addInterceptor(logging)
                        .build()).build();

Happy Coding :)


问:
Suggestions for Python debugging tools?
Yesterday I made a simulation using Python. I had a few difficulties with variables and debugging.

Is there any software for Python, which provides a decent debugger?

Related question: What is the best way to debug my Python code?

答: You can check out the python debugger pdb, which is included in the standard library: http://docs.python.org/library/pdb.html</p>

OwnerDisplayName: Masi

ContentLicense: CC BY-SA 2.5

Title: Suggestions for Python debugging tools?

LastEditorDisplayName: J.F. Sebastian

OwnerDisplayName: sykora


问:
Object oriented coding in a multi threaded request environment - PHP
I am writing a web application in an object oriented design. This application would be interacting with the database pretty often. A few regular operations are verifying a user's ACL permissions for the function/method requested, performing certain functions etc. In a nutshell, the database would be used a lot. So my question here is, if I do develop my application using OOP, and declare class level variables which would be used to set the input coming in, and if there is any parallel or concurrent request coming in from another user, would the input data be changed??

Would I have to do something separate to make sure that the application is multi-threaded and the input coming in be not changed until the process isn't finished??

ex:

```<code>class myProces{
var $input1;
var $input2;

    function process1($ip1, $ip2){
      $this->input1 = $ip1;
      $this->input2 = $ip2;
      $this->getDataDB();
    }

    function getDataDB(){
     //do some database activity with the class level variables;
     // I would pass the values in the class level variables;
    $query = "select column from table where col1 = $this->input1 and col2= $this->input2";

    mysql_query($query);

    return something;
    }

}
</code>```

Now if I have two users hitting my application at the same time, and make a call to the functions in this class

user1:
$obj = new myProces();
$obj->process1(1,2);

user2:
$obj = new myProces();
$obj->process1(5,6);

Now if I do have class level variables, would they have changed values when concurrent requests come in?? Would PHP doing any kind of handling for multi threading? I am not sure if Apache can act as a message queue, where requests can be queued.

Can anybody explain if OOP for web applications with heavy number of users is good or if any kind of multithreading has to be done by developers??

答:
A couple of things:

This has nothing to do with OOP.

PHP doesn't support user threads

Each request will be using its own memory, so you don't have to worry about concurrent usage updating variables behind your back.

However, you do have to take care when dealing with data from a database. User 1 may read something, then User 2 may read the same thing and update it before User 1 finishes. Then when User 1 updates it, he may be accidentally overwriting something User 2 did.

These sorts of things can be handled with transactions, locks, etc. Again, it has nothing to do with OOP or multithreading.

Body:
I am writing a web application in an object oriented design. This application would be interacting with the database pretty often. A few regular operations are verifying a user's ACL permissions for the function/method requested, performing certain functions etc. In a nutshell, the database would be used a lot. So my question here is, if I do develop my application using OOP, and declare class level variables which would be used to set the input coming in, and if there is any parallel or concurrent request coming in from another user, would the input data be changed??

Would I have to do something separate to make sure that the application is multi-threaded and the input coming in be not changed until the process isn't finished??

ex:

class myProces{
var $input1;
var $input2;

    function process1($ip1, $ip2){
      $this->input1 = $ip1;
      $this->input2 = $ip2;
      $this->getDataDB();
    }

    function getDataDB(){
     //do some database activity with the class level variables;
     // I would pass the values in the class level variables;
    $query = "select column from table where col1 = $this->input1 and col2= $this->input2";

    mysql_query($query);

    return something;
    }

}

Now if I have two users hitting my application at the same time, and make a call to the functions in this class

user1:
$obj = new myProces();
$obj->process1(1,2);

user2:
$obj = new myProces();
$obj->process1(5,6);

Now if I do have class level variables, would they have changed values when concurrent requests come in?? Would PHP doing any kind of handling for multi threading? I am not sure if Apache can act as a message queue, where requests can be queued.

Can anybody explain if OOP for web applications with heavy number of users is good or if any kind of multithreading has to be done by developers??


问:
Unable to autowire the service inside my authentication filter in Spring
I am trying to authenticate user by token, But when i try to auto wire one my services inside the AuthenticationTokenProcessingFilter i get null pointer exception. because autowired service is null , how can i fix this issue ?

My AuthenticationTokenProcessingFilter class

```<code>@ComponentScan(basePackages = {"com.marketplace"})
public class AuthenticationTokenProcessingFilter extends GenericFilterBean {

    @Autowired
    @Qualifier("myServices")
    private MyServices service;

    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
        @SuppressWarnings("unchecked")
        Map<String, String[]> parms = request.getParameterMap();

        if (parms.containsKey("token")) {
            try {
                String strToken = parms.get("token")[0]; // grab the first "token" parameter

                User user = service.getUserByToken(strToken);
                System.out.println("Token: " + strToken);

                DateTime dt = new DateTime();
                DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
                DateTime createdDate = fmt.parseDateTime(strToken);
                Minutes mins = Minutes.minutesBetween(createdDate, dt);

                if (user != null && mins.getMinutes() <= 30) {
                    System.out.println("valid token found");

                    List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
                    authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));

                    UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(user.getEmailId(), user.getPassword());
                    token.setDetails(new WebAuthenticationDetails((HttpServletRequest) request));
                    Authentication authentication = new UsernamePasswordAuthenticationToken(user.getEmailId(), user.getPassword(), authorities); //this.authenticationProvider.authenticate(token);

                    SecurityContextHolder.getContext().setAuthentication(authentication);
                }else{
                    System.out.println("invalid token");
                }
            } catch(Exception e) {
                e.printStackTrace();
            }
        } else {
            System.out.println("no token found");
        }
        // continue thru the filter chain
        chain.doFilter(request, response);
    }
}
</code>```

I Tried adding follwing in my AppConfig

```<code>@Bean(name="myServices")
    public MyServices stockService() {
        return new MyServiceImpl();
    }
</code>```

My AppConfig Annotations are

```<code>@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.marketplace")
public class AppConfig extends WebMvcConfigurerAdapter {
</code>```

答:
If your filter class extends GenericFilterBean you can get a reference to a bean in your app context this way:

```<code>public void initFilterBean() throws ServletException {

@Override
public void initFilterBean() throws ServletException {

        WebApplicationContext webApplicationContext =
            WebApplicationContextUtils.getWebApplicationContext(getServletContext());
        //reference to bean from app context
        yourBeanToInject = webApplicationContext.getBean(yourBeanToInject.class);

        //do something with your bean
        propertyValue = yourBeanToInject.getValue("propertyName");
}
</code>```

And here is less explicit way for those who doesn't like hardcoding bean names or need to inject more than one bean reference into the filter:

```<code>@Autowired
private YourBeanToInject yourBeanToInject;

@Override
public void initFilterBean() throws ServletException{

    SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this, getServletContext());

    //do something with your bean
    propertyValue = yourBeanToInject.getValue("propertyName");
}
</code>```

Body:
I am trying to authenticate user by token, But when i try to auto wire one my services inside the AuthenticationTokenProcessingFilter i get null pointer exception. because autowired service is null , how can i fix this issue ?

My AuthenticationTokenProcessingFilter class

@ComponentScan(basePackages = {"com.marketplace"})
public class AuthenticationTokenProcessingFilter extends GenericFilterBean {

    @Autowired
    @Qualifier("myServices")
    private MyServices service;

    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
        @SuppressWarnings("unchecked")
        Map<String, String[]> parms = request.getParameterMap();

        if (parms.containsKey("token")) {
            try {
                String strToken = parms.get("token")[0]; // grab the first "token" parameter

                User user = service.getUserByToken(strToken);
                System.out.println("Token: " + strToken);

                DateTime dt = new DateTime();
                DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
                DateTime createdDate = fmt.parseDateTime(strToken);
                Minutes mins = Minutes.minutesBetween(createdDate, dt);

                if (user != null && mins.getMinutes() <= 30) {
                    System.out.println("valid token found");

                    List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
                    authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));

                    UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(user.getEmailId(), user.getPassword());
                    token.setDetails(new WebAuthenticationDetails((HttpServletRequest) request));
                    Authentication authentication = new UsernamePasswordAuthenticationToken(user.getEmailId(), user.getPassword(), authorities); //this.authenticationProvider.authenticate(token);

                    SecurityContextHolder.getContext().setAuthentication(authentication);
                }else{
                    System.out.println("invalid token");
                }
            } catch(Exception e) {
                e.printStackTrace();
            }
        } else {
            System.out.println("no token found");
        }
        // continue thru the filter chain
        chain.doFilter(request, response);
    }
}

I Tried adding follwing in my AppConfig

@Bean(name="myServices")
    public MyServices stockService() {
        return new MyServiceImpl();
    }

My AppConfig Annotations are

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.marketplace")
public class AppConfig extends WebMvcConfigurerAdapter {

Body:
If your filter class extends GenericFilterBean you can get a reference to a bean in your app context this way:

public void initFilterBean() throws ServletException {

@Override
public void initFilterBean() throws ServletException {

        WebApplicationContext webApplicationContext =
            WebApplicationContextUtils.getWebApplicationContext(getServletContext());
        //reference to bean from app context
        yourBeanToInject = webApplicationContext.getBean(yourBeanToInject.class);

        //do something with your bean
        propertyValue = yourBeanToInject.getValue("propertyName");
}

And here is less explicit way for those who doesn't like hardcoding bean names or need to inject more than one bean reference into the filter:

@Autowired
private YourBeanToInject yourBeanToInject;

@Override
public void initFilterBean() throws ServletException{

    SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this, getServletContext());

    //do something with your bean
    propertyValue = yourBeanToInject.getValue("propertyName");
}


问:
Time diff between AudioOutputUnitStart() and render callbackm for RemoteIO
This is a pretty "minutia" question regarding timing...

I'm using iOS's RemoteIO audio unit to do things. Just wonder how exactly system handles the timing: after calling AudioOutputUnitStart(), the unit should on "on", then render callbacks will be pulled by downstream units. Allow me to guess:

Possibility 1: the next render callback happens right after the execution of AudioOutputUnitStart(), then it goes on

Possibility 2: the system has its own render callback rhythm. After calling AudioOutputUnitStart(), the next render callback catches on one of the system's "next" tick, then start from there

1 or 2? or there's 3? Thanks in advance!

答:
The audio latency seems to depend on the specific device model, audio session and options, requested sample rate and buffer size, and whether any other audio (background or recently closed app) is or has recently been playing or recording on the system.  Whether or not the internal audio amplifier circuits (etc.) need to be powered up or are already turned on may make the biggest difference.  Requesting certain sample rates seems to also cause extra time due to the buffering potentially needed by the OS resampling and mixer code.

So likely (2) or (3).

The best way to minimize latency when using RemoteIO is to request very short buffers (1 to 6 mS) in the audio session setup, start the audio session and Audio Unit way ahead of time (at app startup, view load, etc.), then fill the callback buffers with zeros (or discard recorded callback data) until you need sound.


问:
Exclude a list of tests with py.test but on the command line?
I would like to exclude a list (about 5 items) of tests with py.test.

I would like to give this list to py.test via the command line.

I would like to avoid to modify the source.

How to do that?

答:
You could use tests selecting expression, option is -k. If you have following tests:

```<code>def test_spam():
    pass

def test_ham():
    pass

def test_eggs():
    pass
</code>```

invoke pytest with:

```<code>pytest -v -k 'not spam and not ham' tests.py
</code>```

you will get:

```<code>collected 3 items

pytest_skip_tests.py::test_eggs PASSED             [100%]

=================== 2 tests deselected ===================
========= 1 passed, 2 deselected in 0.01 seconds =========
</code>```

Body:
You could use tests selecting expression, option is -k. If you have following tests:

def test_spam():
    pass

def test_ham():
    pass

def test_eggs():
    pass

invoke pytest with:

pytest -v -k 'not spam and not ham' tests.py

you will get:

collected 3 items

pytest_skip_tests.py::test_eggs PASSED             [100%]

=================== 2 tests deselected ===================
========= 1 passed, 2 deselected in 0.01 seconds =========


答:
One approach could be as follows:

```<code>function calculate_rotation(arr){
    var N = arr.length;

    if(!N) return;

    var xmin = arr[0][0];
    var ymin = arr[0][1];
    var A = arr[0];
    var P = arr[0];

    for(var i = 0; i < N; ++i){
        var x = arr[i][0];
        var y = arr[i][1];

        if(x < xmin || (x == xmin && y < A[1])){
            xmin = x;
            A = [x, y];
        }
        if(y < ymin || (y == ymin && x > P[0])){
            ymin = y;
            P = [x, y];
        }
    }

    return Math.atan2(P[1] - A[1], P[0] - A[0])*180/Math.PI;
}
</code>```

The idea is to identify the left-most (A) and bottom-most (P) points. The rotation angle is then calculated with respect to the point A. Alternatively, one could do a second pass through the array, identify all points which are on the line segment connecting A and P and do a linear fit in order to obtain the slope.

Title: Calculate rectangles angle knowing the outline positions (x/y)

Body:
I got an matrix of ones and zeros like this (& I hope you can get the rectangle of ones):

And I'd like to calculate the rectangles rotation angle.

So what I'm starting with: I now all of the positions (x/y-coordinates) of the rectangles outline (symbolized with ' ' (spaces) in the image above) and got them in an array like this:

var outline_positions = [[120,22],[122,22],...,[94,119],[93,119]]

So now my question: How is it possible to calculate the rectangles rotation-angle to the X-axis, knowing that the long side of the rectangle at angle 0° is parallel to the X-asis?

Because I got now idea how to start this code is all that I got so far:

var positions = [[120,22],[122,22],[120,22],[121,22],[122,22],[119,23],[125,23],[119,24],[127,24],[118,25],[129,25],[118,26],[131,26],[117,27],[132,27],[117,28],[134,28],[117,29],[137,29],[116,30],[139,30],[115,31],[141,31],[115,32],[142,32],[114,33],[142,33],[113,34],[142,34],[113,35],[142,35],[112,36],[141,36],[111,37],[140,37],[111,38],[140,38],[110,39],[139,39],[109,40],[139,40],[109,41],[138,41],[108,42],[138,42],[108,43],[137,43],[106,44],[137,44],[106,45],[136,45],[105,46],[136,46],[105,47],[135,47],[104,48],[135,48],[103,49],[134,49],[103,50],[134,50],[103,51],[133,51],[102,52],[132,52],[101,53],[132,53],[100,54],[131,54],[100,55],[131,55],[99,56],[130,56],[98,57],[129,57],[97,58],[128,58],[97,59],[128,59],[96,60],[127,60],[95,61],[127,61],[95,62],[126,62],[94,63],[126,63],[94,64],[125,64],[93,65],[124,65],[92,66],[124,66],[92,67],[124,67],[91,68],[123,68],[91,69],[122,69],[90,70],[121,70],[89,71],[121,71],[89,72],[120,72],[88,73],[120,73],[87,74],[119,74],[87,75],[118,75],[86,76],[118,76],[86,77],[116,77],[85,78],[116,78],[85,79],[116,79],[83,80],[115,80],[83,81],[115,81],[82,82],[115,82],[81,83],[114,83],[81,84],[113,84],[80,85],[113,85],[80,86],[112,86],[79,87],[112,87],[78,88],[112,88],[78,89],[111,89],[78,90],[110,90],[77,91],[110,91],[76,92],[109,92],[76,93],[109,93],[75,94],[108,94],[74,95],[107,95],[74,96],[107,96],[73,97],[106,97],[73,98],[105,98],[72,99],[105,99],[72,100],[104,100],[71,101],[104,101],[70,102],[103,102],[70,103],[103,103],[69,104],[102,104],[70,105],[102,105],[72,106],[101,106],[73,107],[101,107],[75,108],[100,108],[76,109],[100,109],[77,110],[99,110],[80,111],[98,111],[81,112],[98,112],[83,113],[97,113],[84,114],[96,114],[86,115],[96,115],[88,116],[96,116],[90,117],[95,117],[91,118],[94,118],[93,119],[94,119],[94,119],[93,119]]

Array.prototype.calculate_rotation = function() {
 var array=this
 var max_x = array.filter(e => e[0] === Math.max(... array.map(e => e[0])))[0];
 var min_x = array.filter(e => e[0] === Math.min(... array.map(e => e[0])))[0]
return max_x[1]-min_x[1]
}

console.log(positions.calculate_rotation());

Body:
One approach could be as follows:

function calculate_rotation(arr){
    var N = arr.length;

    if(!N) return;

    var xmin = arr[0][0];
    var ymin = arr[0][1];
    var A = arr[0];
    var P = arr[0];

    for(var i = 0; i < N; ++i){
        var x = arr[i][0];
        var y = arr[i][1];

        if(x < xmin || (x == xmin && y < A[1])){
            xmin = x;
            A = [x, y];
        }
        if(y < ymin || (y == ymin && x > P[0])){
            ymin = y;
            P = [x, y];
        }
    }

    return Math.atan2(P[1] - A[1], P[0] - A[0])*180/Math.PI;
}

The idea is to identify the left-most (A) and bottom-most (P) points. The rotation angle is then calculated with respect to the point A. Alternatively, one could do a second pass through the array, identify all points which are on the line segment connecting A and P and do a linear fit in order to obtain the slope.


问:
spring-boot-starter-quartz jdbc example
Starting with spring-boot 2.x.x they started offering spring-boot-starter-quartz which is great! Out of the box it does an in-memory store. I want to change it to be a clustered environment but I'm having issues with the configuration I think mostly because I need to put the qrtz_ tables in a different schema than my default data source. Does anyone have an example of using an alternate datasource? I'm currently attempting to set the properties field (as you can see below) but its like they are not being picked up by the configuration bean. Any help is appreciated.

Configuration

```<code>spring:
  quartz:
    job-store-type: jdbc
    jdbc:
      initialize-schema: never
    properties:
      scheduler:
        instanceName : MyClusteredScheduler
        instanceId : AUTO
      threadPool:
        class : org.quartz.simpl.SimpleThreadPool
        threadCount : 25
        threadPriority : 5
      jobStore:
        misfireThreshold : 60000
        class : org.quartz.impl.jdbcjobstore.JobStoreTX
        driverDelegateClass : org.quartz.impl.jdbcjobstore.StdJDBCDelegate
        useProperties : false
        dataSource : myDS
        tablePrefix : QRTZ_
        isClustered : true
        clusterCheckinInterval : 20000
      dataSource:
        myDS:
          driver : com.mysql.jdbc.Driver
          URL : jdbc:mysql://127.0.0.1:3306/quartz
          user : removed
          password : removed
          maxConnections : 5
          validationQuery : select 0 from dual
</code>```

Output from log

```<code>2017-11-06 13:33:02.853  INFO 7082 --- [           main] org.quartz.core.QuartzScheduler          : Quartz Scheduler v.2.3.0 created.
2017-11-06 13:33:02.856  INFO 7082 --- [           main] o.s.s.quartz.LocalDataSourceJobStore     : Using db table-based data access locking (synchronization).
2017-11-06 13:33:02.858  INFO 7082 --- [           main] o.s.s.quartz.LocalDataSourceJobStore     : JobStoreCMT initialized.
2017-11-06 13:33:02.859  INFO 7082 --- [           main] org.quartz.core.QuartzScheduler          : Scheduler meta-data: Quartz Scheduler (v2.3.0) 'quartzScheduler' with instanceId 'NON_CLUSTERED'
Scheduler class: 'org.quartz.core.QuartzScheduler' - running locally.
NOT STARTED.
Currently in standby mode.
Number of jobs executed: 0
Using thread pool 'org.quartz.simpl.SimpleThreadPool' - with 10 threads.
Using job-store 'org.springframework.scheduling.quartz.LocalDataSourceJobStore' - which supports persistence. and is not clustered.

2017-11-06 13:33:02.859  INFO 7082 --- [           main] org.quartz.impl.StdSchedulerFactory      : Quartz scheduler 'quartzScheduler' initialized from an externally provided properties instance.
2017-11-06 13:33:02.860  INFO 7082 --- [           main] org.quartz.impl.StdSchedulerFactory      : Quartz scheduler version: 2.3.0
2017-11-06 13:33:02.860  INFO 7082 --- [           main] org.quartz.core.QuartzScheduler          : JobFactory set to: org.springframework.boot.autoconfigure.quartz.AutowireCapableBeanJobFactory@21132086
2017-11-06 13:33:03.214  INFO 7082 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2017-11-06 13:33:03.216  INFO 7082 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Bean with name 'dataSource' has been autodetected for JMX exposure
2017-11-06 13:33:03.223  INFO 7082 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Located MBean 'dataSource': registering with JMX server as MBean [com.zaxxer.hikari:name=dataSource,type=HikariDataSource]
2017-11-06 13:33:03.227  INFO 7082 --- [           main] o.s.c.support.DefaultLifecycleProcessor  : Starting beans in phase 2147483647
2017-11-06 13:33:03.227  INFO 7082 --- [           main] o.s.s.quartz.SchedulerFactoryBean        : Starting Quartz Scheduler now
2017-11-06 13:33:05.250  WARN 7082 --- [           main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.context.ApplicationContextException: Failed to start bean 'quartzScheduler'; nested exception is org.springframework.scheduling.SchedulingException: Could not start Quartz Scheduler; nested exception is org.quartz.SchedulerConfigException: Failure occured during job recovery. [See nested exception: org.quartz.impl.jdbcjobstore.LockException: Failure obtaining db row lock: No database selected [See nested exception: java.sql.SQLException: No database selected]]
2017-11-06 13:33:05.250  INFO 7082 --- [           main] o.s.s.quartz.SchedulerFactoryBean        : Shutting down Quartz Scheduler
2017-11-06 13:33:05.251  INFO 7082 --- [           main] org.quartz.core.QuartzScheduler          : Scheduler quartzScheduler_$_NON_CLUSTERED shutting down.
2017-11-06 13:33:05.251  INFO 7082 --- [           main] org.quartz.core.QuartzScheduler          : Scheduler quartzScheduler_$_NON_CLUSTERED paused.
2017-11-06 13:33:05.251  INFO 7082 --- [           main] org.quartz.core.QuartzScheduler          : Scheduler quartzScheduler_$_NON_CLUSTERED shutdown complete.
2017-11-06 13:33:05.252  INFO 7082 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Unregistering JMX-exposed beans on shutdown
2017-11-06 13:33:05.253  INFO 7082 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Unregistering JMX-exposed beans
2017-11-06 13:33:05.254  INFO 7082 --- [           main] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2017-11-06 13:33:05.255  INFO 7082 --- [           main] com.zaxxer.hikari.HikariDataSource       : testdb - Shutdown initiated...
2017-11-06 13:33:05.264  INFO 7082 --- [           main] com.zaxxer.hikari.HikariDataSource       : testdb - Shutdown completed.
2017-11-06 13:33:05.265  INFO 7082 --- [           main] o.apache.catalina.core.StandardService   : Stopping service [Tomcat]
2017-11-06 13:33:05.283  INFO 7082 --- [           main] utoConfigurationReportLoggingInitializer :

Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
2017-11-06 13:33:05.293 ERROR 7082 --- [           main] o.s.boot.SpringApplication               : Application startup failed

org.springframework.context.ApplicationContextException: Failed to start bean 'quartzScheduler'; nested exception is org.springframework.scheduling.SchedulingException: Could not start Quartz Scheduler; nested exception is org.quartz.SchedulerConfigException: Failure occured during job recovery. [See nested exception: org.quartz.impl.jdbcjobstore.LockException: Failure obtaining db row lock: No database selected [See nested exception: java.sql.SQLException: No database selected]]
at org.springframework.context.support.DefaultLifecycleProcessor.doStart(DefaultLifecycleProcessor.java:186) ~[spring-context-5.0.0.RELEASE.jar:5.0.0.RELEASE]
at org.springframework.context.support.DefaultLifecycleProcessor.access$200(DefaultLifecycleProcessor.java:52) ~[spring-context-5.0.0.RELEASE.jar:5.0.0.RELEASE]
at org.springframework.context.support.DefaultLifecycleProcessor$LifecycleGroup.start(DefaultLifecycleProcessor.java:358) ~[spring-context-5.0.0.RELEASE.jar:5.0.0.RELEASE]
at org.springframework.context.support.DefaultLifecycleProcessor.startBeans(DefaultLifecycleProcessor.java:159) ~[spring-context-5.0.0.RELEASE.jar:5.0.0.RELEASE]
at org.springframework.context.support.DefaultLifecycleProcessor.onRefresh(DefaultLifecycleProcessor.java:123) ~[spring-context-5.0.0.RELEASE.jar:5.0.0.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishRefresh(AbstractApplicationContext.java:884) ~[spring-context-5.0.0.RELEASE.jar:5.0.0.RELEASE]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.finishRefresh(ServletWebServerApplicationContext.java:143) ~[spring-boot-2.0.0.M5.jar:2.0.0.M5]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:552) ~[spring-context-5.0.0.RELEASE.jar:5.0.0.RELEASE]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:122) ~[spring-boot-2.0.0.M5.jar:2.0.0.M5]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:750) [spring-boot-2.0.0.M5.jar:2.0.0.M5]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:386) [spring-boot-2.0.0.M5.jar:2.0.0.M5]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:327) [spring-boot-2.0.0.M5.jar:2.0.0.M5]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1245) [spring-boot-2.0.0.M5.jar:2.0.0.M5]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1233) [spring-boot-2.0.0.M5.jar:2.0.0.M5]
at com.tci.reader.incident.parser.IncidentParserApplication.main(IncidentParserApplication.java:18) [classes/:na]
Caused by: org.springframework.scheduling.SchedulingException: Could not start Quartz Scheduler; nested exception is org.quartz.SchedulerConfigException: Failure occured during job recovery. [See nested exception: org.quartz.impl.jdbcjobstore.LockException: Failure obtaining db row lock: No database selected [See nested exception: java.sql.SQLException: No database selected]]
at org.springframework.scheduling.quartz.SchedulerFactoryBean.start(SchedulerFactoryBean.java:738) ~[spring-context-support-5.0.0.RELEASE.jar:5.0.0.RELEASE]
at org.springframework.context.support.DefaultLifecycleProcessor.doStart(DefaultLifecycleProcessor.java:183) ~[spring-context-5.0.0.RELEASE.jar:5.0.0.RELEASE]
... 14 common frames omitted
Caused by: org.quartz.SchedulerConfigException: Failure occured during job recovery.
at org.quartz.impl.jdbcjobstore.JobStoreSupport.schedulerStarted(JobStoreSupport.java:697) ~[quartz-2.3.0.jar:na]
at org.quartz.core.QuartzScheduler.start(QuartzScheduler.java:539) ~[quartz-2.3.0.jar:na]
at org.quartz.impl.StdScheduler.start(StdScheduler.java:142) ~[quartz-2.3.0.jar:na]
at org.springframework.scheduling.quartz.SchedulerFactoryBean.startScheduler(SchedulerFactoryBean.java:664) ~[spring-context-support-5.0.0.RELEASE.jar:5.0.0.RELEASE]
at org.springframework.scheduling.quartz.SchedulerFactoryBean.start(SchedulerFactoryBean.java:735) ~[spring-context-support-5.0.0.RELEASE.jar:5.0.0.RELEASE]
... 15 common frames omitted
Caused by: org.quartz.impl.jdbcjobstore.LockException: Failure obtaining db row lock: No database selected
at org.quartz.impl.jdbcjobstore.StdRowLockSemaphore.executeSQL(StdRowLockSemaphore.java:157) ~[quartz-2.3.0.jar:na]
at org.quartz.impl.jdbcjobstore.DBSemaphore.obtainLock(DBSemaphore.java:113) ~[quartz-2.3.0.jar:na]
at org.quartz.impl.jdbcjobstore.JobStoreSupport.executeInNonManagedTXLock(JobStoreSupport.java:3842) ~[quartz-2.3.0.jar:na]
at org.quartz.impl.jdbcjobstore.JobStoreSupport.recoverJobs(JobStoreSupport.java:839) ~[quartz-2.3.0.jar:na]
at org.quartz.impl.jdbcjobstore.JobStoreSupport.schedulerStarted(JobStoreSupport.java:695) ~[quartz-2.3.0.jar:na]
... 19 common frames omitted
Caused by: java.sql.SQLException: No database selected
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:964) ~[mysql-connector-java-5.1.44.jar:5.1.44]
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3973) ~[mysql-connector-java-5.1.44.jar:5.1.44]
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3909) ~[mysql-connector-java-5.1.44.jar:5.1.44]
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2527) ~[mysql-connector-java-5.1.44.jar:5.1.44]
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2680) ~[mysql-connector-java-5.1.44.jar:5.1.44]
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2487) ~[mysql-connector-java-5.1.44.jar:5.1.44]
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1858) ~[mysql-connector-java-5.1.44.jar:5.1.44]
at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:1966) ~[mysql-connector-java-5.1.44.jar:5.1.44]
at com.zaxxer.hikari.pool.ProxyPreparedStatement.executeQuery(ProxyPreparedStatement.java:52) ~[HikariCP-2.7.2.jar:na]
at com.zaxxer.hikari.pool.HikariProxyPreparedStatement.executeQuery(HikariProxyPreparedStatement.java) ~[HikariCP-2.7.2.jar:na]
at org.quartz.impl.jdbcjobstore.StdRowLockSemaphore.executeSQL(StdRowLockSemaphore.java:96) ~[quartz-2.3.0.jar:na]
... 23 common frames omitted
</code>```

答:
Application.yml file:

```<code>spring:
  jpa:
    hibernate:
      ddl-auto: none
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/Quartz
    username: Your Username
    password: Your Password

quartz:
  scheduler:
    instanceName: Scheduler
  threadPool:
    class: org.quartz.simpl.SimpleThreadPool
    threadCount: 3
  context:
    key:
      QuartzTopic: QuartzPorperties
  jobStore:
    driver: com.mysql.jdbc.Driver
    class: org.quartz.impl.jdbcjobstore.JobStoreTX
    driverDelegateClass: org.quartz.impl.jdbcjobstore.StdJDBCDelegate
    misfireThreshold: 6000
    tablePrefix: QRTZ_
</code>```

Next create a Configuration class which reads these properties from the yml file and then creates a Scheduler Bean:

```<code>@Configuration
public class SchedulerConfig {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Value("${quartz.scheduler.instanceName}")
    private String instanceName;
    @Value("${quartz.threadPool.class}")
    private String threadClass;
    @Value("${quartz.threadPool.threadCount}")
    private String threadCount;
    @Value("${quartz.context.key.QuartzTopic}")
    private String quartzTopic;
    @Value("${quartz.jobStore.class}")
    private String jobStoreClass;
    @Value("${quartz.jobStore.driverDelegateClass}")
    private String driverDelegateClass;
    @Value("${quartz.jobStore.misfireThreshold}")
    private String misfireThreshold;
    @Value("${quartz.jobStore.tablePrefix}")
    private String tablePrefix;
    @Value("${quartz.jobStore.driver}")
    private String dataSourceDriver;
    @Value("${spring.datasource.url}")
    private String dataSourceUrl;
    @Value("${spring.datasource.username}")
    private String dataSourceUsername;
    @Value("${spring.datasource.password}")
    private String databasePassword;

    @Bean({"Scheduler"})
    public Scheduler getScheduler() {
        Scheduler scheduler = null;
        try {
            StdSchedulerFactory factory = new StdSchedulerFactory();
            Properties props = new Properties();
            props.put("org.quartz.scheduler.instanceName", instanceName);
            props.put("org.quartz.threadPool.class", threadClass);
            props.put("org.quartz.threadPool.threadCount", threadCount);
            props.put("org.quartz.context.key.QuartzTopic", quartzTopic);
            props.put("org.quartz.jobStore.class", jobStoreClass);
            props.put("org.quartz.jobStore.driverDelegateClass", driverDelegateClass);
            props.put("quartz.jobStore.misfireThreshold", misfireThreshold);
            props.put("org.quartz.jobStore.tablePrefix", tablePrefix);
            props.put("org.quartz.jobStore.dataSource", "myDS");
            props.put("org.quartz.dataSource.myDS.driver", dataSourceDriver);
            props.put("org.quartz.dataSource.myDS.URL", dataSourceUrl);
            props.put("org.quartz.dataSource.myDS.user", dataSourceUsername);
            props.put("org.quartz.dataSource.myDS.password", databasePassword);
            props.put("org.quartz.dataSource.myDS.maxConnections", "10");
            factory.initialize(props);
            scheduler = factory.getScheduler();
            scheduler.start();
            scheduler.resumeAll(); // This is to resume the entire scheduler when a new build is deployed
        } catch (Exception e) {
            logger.error("{} - SchedulerConfig class - getScheduler() - Error creating Scheduler instance: {}",
                    appName, e);
        }
        return scheduler;
    }
}
</code>```

Finally, use the Bean as below in any class you want:

```<code>@Autowired
    private Scheduler scheduler;
</code>```

Title: spring-boot-starter-quartz jdbc example

Body:
Starting with spring-boot 2.x.x they started offering spring-boot-starter-quartz which is great! Out of the box it does an in-memory store. I want to change it to be a clustered environment but I'm having issues with the configuration I think mostly because I need to put the qrtz_ tables in a different schema than my default data source. Does anyone have an example of using an alternate datasource? I'm currently attempting to set the properties field (as you can see below) but its like they are not being picked up by the configuration bean. Any help is appreciated.

Configuration

spring:
  quartz:
    job-store-type: jdbc
    jdbc:
      initialize-schema: never
    properties:
      scheduler:
        instanceName : MyClusteredScheduler
        instanceId : AUTO
      threadPool:
        class : org.quartz.simpl.SimpleThreadPool
        threadCount : 25
        threadPriority : 5
      jobStore:
        misfireThreshold : 60000
        class : org.quartz.impl.jdbcjobstore.JobStoreTX
        driverDelegateClass : org.quartz.impl.jdbcjobstore.StdJDBCDelegate
        useProperties : false
        dataSource : myDS
        tablePrefix : QRTZ_
        isClustered : true
        clusterCheckinInterval : 20000
      dataSource:
        myDS:
          driver : com.mysql.jdbc.Driver
          URL : jdbc:mysql://127.0.0.1:3306/quartz
          user : removed
          password : removed
          maxConnections : 5
          validationQuery : select 0 from dual

Output from log

2017-11-06 13:33:02.853  INFO 7082 --- [           main] org.quartz.core.QuartzScheduler          : Quartz Scheduler v.2.3.0 created.
2017-11-06 13:33:02.856  INFO 7082 --- [           main] o.s.s.quartz.LocalDataSourceJobStore     : Using db table-based data access locking (synchronization).
2017-11-06 13:33:02.858  INFO 7082 --- [           main] o.s.s.quartz.LocalDataSourceJobStore     : JobStoreCMT initialized.
2017-11-06 13:33:02.859  INFO 7082 --- [           main] org.quartz.core.QuartzScheduler          : Scheduler meta-data: Quartz Scheduler (v2.3.0) 'quartzScheduler' with instanceId 'NON_CLUSTERED'
Scheduler class: 'org.quartz.core.QuartzScheduler' - running locally.
NOT STARTED.
Currently in standby mode.
Number of jobs executed: 0
Using thread pool 'org.quartz.simpl.SimpleThreadPool' - with 10 threads.
Using job-store 'org.springframework.scheduling.quartz.LocalDataSourceJobStore' - which supports persistence. and is not clustered.

2017-11-06 13:33:02.859  INFO 7082 --- [           main] org.quartz.impl.StdSchedulerFactory      : Quartz scheduler 'quartzScheduler' initialized from an externally provided properties instance.
2017-11-06 13:33:02.860  INFO 7082 --- [           main] org.quartz.impl.StdSchedulerFactory      : Quartz scheduler version: 2.3.0
2017-11-06 13:33:02.860  INFO 7082 --- [           main] org.quartz.core.QuartzScheduler          : JobFactory set to: org.springframework.boot.autoconfigure.quartz.AutowireCapableBeanJobFactory@21132086
2017-11-06 13:33:03.214  INFO 7082 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2017-11-06 13:33:03.216  INFO 7082 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Bean with name 'dataSource' has been autodetected for JMX exposure
2017-11-06 13:33:03.223  INFO 7082 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Located MBean 'dataSource': registering with JMX server as MBean [com.zaxxer.hikari:name=dataSource,type=HikariDataSource]
2017-11-06 13:33:03.227  INFO 7082 --- [           main] o.s.c.support.DefaultLifecycleProcessor  : Starting beans in phase 2147483647
2017-11-06 13:33:03.227  INFO 7082 --- [           main] o.s.s.quartz.SchedulerFactoryBean        : Starting Quartz Scheduler now
2017-11-06 13:33:05.250  WARN 7082 --- [           main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.context.ApplicationContextException: Failed to start bean 'quartzScheduler'; nested exception is org.springframework.scheduling.SchedulingException: Could not start Quartz Scheduler; nested exception is org.quartz.SchedulerConfigException: Failure occured during job recovery. [See nested exception: org.quartz.impl.jdbcjobstore.LockException: Failure obtaining db row lock: No database selected [See nested exception: java.sql.SQLException: No database selected]]
2017-11-06 13:33:05.250  INFO 7082 --- [           main] o.s.s.quartz.SchedulerFactoryBean        : Shutting down Quartz Scheduler
2017-11-06 13:33:05.251  INFO 7082 --- [           main] org.quartz.core.QuartzScheduler          : Scheduler quartzScheduler_$_NON_CLUSTERED shutting down.
2017-11-06 13:33:05.251  INFO 7082 --- [           main] org.quartz.core.QuartzScheduler          : Scheduler quartzScheduler_$_NON_CLUSTERED paused.
2017-11-06 13:33:05.251  INFO 7082 --- [           main] org.quartz.core.QuartzScheduler          : Scheduler quartzScheduler_$_NON_CLUSTERED shutdown complete.
2017-11-06 13:33:05.252  INFO 7082 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Unregistering JMX-exposed beans on shutdown
2017-11-06 13:33:05.253  INFO 7082 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Unregistering JMX-exposed beans
2017-11-06 13:33:05.254  INFO 7082 --- [           main] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2017-11-06 13:33:05.255  INFO 7082 --- [           main] com.zaxxer.hikari.HikariDataSource       : testdb - Shutdown initiated...
2017-11-06 13:33:05.264  INFO 7082 --- [           main] com.zaxxer.hikari.HikariDataSource       : testdb - Shutdown completed.
2017-11-06 13:33:05.265  INFO 7082 --- [           main] o.apache.catalina.core.StandardService   : Stopping service [Tomcat]
2017-11-06 13:33:05.283  INFO 7082 --- [           main] utoConfigurationReportLoggingInitializer :

Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
2017-11-06 13:33:05.293 ERROR 7082 --- [           main] o.s.boot.SpringApplication               : Application startup failed

org.springframework.context.ApplicationContextException: Failed to start bean 'quartzScheduler'; nested exception is org.springframework.scheduling.SchedulingException: Could not start Quartz Scheduler; nested exception is org.quartz.SchedulerConfigException: Failure occured during job recovery. [See nested exception: org.quartz.impl.jdbcjobstore.LockException: Failure obtaining db row lock: No database selected [See nested exception: java.sql.SQLException: No database selected]]
at org.springframework.context.support.DefaultLifecycleProcessor.doStart(DefaultLifecycleProcessor.java:186) ~[spring-context-5.0.0.RELEASE.jar:5.0.0.RELEASE]
at org.springframework.context.support.DefaultLifecycleProcessor.access$200(DefaultLifecycleProcessor.java:52) ~[spring-context-5.0.0.RELEASE.jar:5.0.0.RELEASE]
at org.springframework.context.support.DefaultLifecycleProcessor$LifecycleGroup.start(DefaultLifecycleProcessor.java:358) ~[spring-context-5.0.0.RELEASE.jar:5.0.0.RELEASE]
at org.springframework.context.support.DefaultLifecycleProcessor.startBeans(DefaultLifecycleProcessor.java:159) ~[spring-context-5.0.0.RELEASE.jar:5.0.0.RELEASE]
at org.springframework.context.support.DefaultLifecycleProcessor.onRefresh(DefaultLifecycleProcessor.java:123) ~[spring-context-5.0.0.RELEASE.jar:5.0.0.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishRefresh(AbstractApplicationContext.java:884) ~[spring-context-5.0.0.RELEASE.jar:5.0.0.RELEASE]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.finishRefresh(ServletWebServerApplicationContext.java:143) ~[spring-boot-2.0.0.M5.jar:2.0.0.M5]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:552) ~[spring-context-5.0.0.RELEASE.jar:5.0.0.RELEASE]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:122) ~[spring-boot-2.0.0.M5.jar:2.0.0.M5]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:750) [spring-boot-2.0.0.M5.jar:2.0.0.M5]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:386) [spring-boot-2.0.0.M5.jar:2.0.0.M5]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:327) [spring-boot-2.0.0.M5.jar:2.0.0.M5]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1245) [spring-boot-2.0.0.M5.jar:2.0.0.M5]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1233) [spring-boot-2.0.0.M5.jar:2.0.0.M5]
at com.tci.reader.incident.parser.IncidentParserApplication.main(IncidentParserApplication.java:18) [classes/:na]
Caused by: org.springframework.scheduling.SchedulingException: Could not start Quartz Scheduler; nested exception is org.quartz.SchedulerConfigException: Failure occured during job recovery. [See nested exception: org.quartz.impl.jdbcjobstore.LockException: Failure obtaining db row lock: No database selected [See nested exception: java.sql.SQLException: No database selected]]
at org.springframework.scheduling.quartz.SchedulerFactoryBean.start(SchedulerFactoryBean.java:738) ~[spring-context-support-5.0.0.RELEASE.jar:5.0.0.RELEASE]
at org.springframework.context.support.DefaultLifecycleProcessor.doStart(DefaultLifecycleProcessor.java:183) ~[spring-context-5.0.0.RELEASE.jar:5.0.0.RELEASE]
... 14 common frames omitted
Caused by: org.quartz.SchedulerConfigException: Failure occured during job recovery.
at org.quartz.impl.jdbcjobstore.JobStoreSupport.schedulerStarted(JobStoreSupport.java:697) ~[quartz-2.3.0.jar:na]
at org.quartz.core.QuartzScheduler.start(QuartzScheduler.java:539) ~[quartz-2.3.0.jar:na]
at org.quartz.impl.StdScheduler.start(StdScheduler.java:142) ~[quartz-2.3.0.jar:na]
at org.springframework.scheduling.quartz.SchedulerFactoryBean.startScheduler(SchedulerFactoryBean.java:664) ~[spring-context-support-5.0.0.RELEASE.jar:5.0.0.RELEASE]
at org.springframework.scheduling.quartz.SchedulerFactoryBean.start(SchedulerFactoryBean.java:735) ~[spring-context-support-5.0.0.RELEASE.jar:5.0.0.RELEASE]
... 15 common frames omitted
Caused by: org.quartz.impl.jdbcjobstore.LockException: Failure obtaining db row lock: No database selected
at org.quartz.impl.jdbcjobstore.StdRowLockSemaphore.executeSQL(StdRowLockSemaphore.java:157) ~[quartz-2.3.0.jar:na]
at org.quartz.impl.jdbcjobstore.DBSemaphore.obtainLock(DBSemaphore.java:113) ~[quartz-2.3.0.jar:na]
at org.quartz.impl.jdbcjobstore.JobStoreSupport.executeInNonManagedTXLock(JobStoreSupport.java:3842) ~[quartz-2.3.0.jar:na]
at org.quartz.impl.jdbcjobstore.JobStoreSupport.recoverJobs(JobStoreSupport.java:839) ~[quartz-2.3.0.jar:na]
at org.quartz.impl.jdbcjobstore.JobStoreSupport.schedulerStarted(JobStoreSupport.java:695) ~[quartz-2.3.0.jar:na]
... 19 common frames omitted
Caused by: java.sql.SQLException: No database selected
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:964) ~[mysql-connector-java-5.1.44.jar:5.1.44]
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3973) ~[mysql-connector-java-5.1.44.jar:5.1.44]
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3909) ~[mysql-connector-java-5.1.44.jar:5.1.44]
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2527) ~[mysql-connector-java-5.1.44.jar:5.1.44]
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2680) ~[mysql-connector-java-5.1.44.jar:5.1.44]
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2487) ~[mysql-connector-java-5.1.44.jar:5.1.44]
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1858) ~[mysql-connector-java-5.1.44.jar:5.1.44]
at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:1966) ~[mysql-connector-java-5.1.44.jar:5.1.44]
at com.zaxxer.hikari.pool.ProxyPreparedStatement.executeQuery(ProxyPreparedStatement.java:52) ~[HikariCP-2.7.2.jar:na]
at com.zaxxer.hikari.pool.HikariProxyPreparedStatement.executeQuery(HikariProxyPreparedStatement.java) ~[HikariCP-2.7.2.jar:na]
at org.quartz.impl.jdbcjobstore.StdRowLockSemaphore.executeSQL(StdRowLockSemaphore.java:96) ~[quartz-2.3.0.jar:na]
... 23 common frames omitted

Body:
Application.yml file:

spring:
  jpa:
    hibernate:
      ddl-auto: none
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/Quartz
    username: Your Username
    password: Your Password

quartz:
  scheduler:
    instanceName: Scheduler
  threadPool:
    class: org.quartz.simpl.SimpleThreadPool
    threadCount: 3
  context:
    key:
      QuartzTopic: QuartzPorperties
  jobStore:
    driver: com.mysql.jdbc.Driver
    class: org.quartz.impl.jdbcjobstore.JobStoreTX
    driverDelegateClass: org.quartz.impl.jdbcjobstore.StdJDBCDelegate
    misfireThreshold: 6000
    tablePrefix: QRTZ_

Next create a Configuration class which reads these properties from the yml file and then creates a Scheduler Bean:

@Configuration
public class SchedulerConfig {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Value("${quartz.scheduler.instanceName}")
    private String instanceName;
    @Value("${quartz.threadPool.class}")
    private String threadClass;
    @Value("${quartz.threadPool.threadCount}")
    private String threadCount;
    @Value("${quartz.context.key.QuartzTopic}")
    private String quartzTopic;
    @Value("${quartz.jobStore.class}")
    private String jobStoreClass;
    @Value("${quartz.jobStore.driverDelegateClass}")
    private String driverDelegateClass;
    @Value("${quartz.jobStore.misfireThreshold}")
    private String misfireThreshold;
    @Value("${quartz.jobStore.tablePrefix}")
    private String tablePrefix;
    @Value("${quartz.jobStore.driver}")
    private String dataSourceDriver;
    @Value("${spring.datasource.url}")
    private String dataSourceUrl;
    @Value("${spring.datasource.username}")
    private String dataSourceUsername;
    @Value("${spring.datasource.password}")
    private String databasePassword;

    @Bean({"Scheduler"})
    public Scheduler getScheduler() {
        Scheduler scheduler = null;
        try {
            StdSchedulerFactory factory = new StdSchedulerFactory();
            Properties props = new Properties();
            props.put("org.quartz.scheduler.instanceName", instanceName);
            props.put("org.quartz.threadPool.class", threadClass);
            props.put("org.quartz.threadPool.threadCount", threadCount);
            props.put("org.quartz.context.key.QuartzTopic", quartzTopic);
            props.put("org.quartz.jobStore.class", jobStoreClass);
            props.put("org.quartz.jobStore.driverDelegateClass", driverDelegateClass);
            props.put("quartz.jobStore.misfireThreshold", misfireThreshold);
            props.put("org.quartz.jobStore.tablePrefix", tablePrefix);
            props.put("org.quartz.jobStore.dataSource", "myDS");
            props.put("org.quartz.dataSource.myDS.driver", dataSourceDriver);
            props.put("org.quartz.dataSource.myDS.URL", dataSourceUrl);
            props.put("org.quartz.dataSource.myDS.user", dataSourceUsername);
            props.put("org.quartz.dataSource.myDS.password", databasePassword);
            props.put("org.quartz.dataSource.myDS.maxConnections", "10");
            factory.initialize(props);
            scheduler = factory.getScheduler();
            scheduler.start();
            scheduler.resumeAll(); // This is to resume the entire scheduler when a new build is deployed
        } catch (Exception e) {
            logger.error("{} - SchedulerConfig class - getScheduler() - Error creating Scheduler instance: {}",
                    appName, e);
        }
        return scheduler;
    }
}

Finally, use the Bean as below in any class you want:

@Autowired
    private Scheduler scheduler;