问:
Session Handling in servlet using JSESSIONID cookie not getting session
I read that to persist session in servlet a cookie gets saved at client side with the name of JSESSIONID.

I checked it also and I found the cookie of localhost with the name of JSESSIONID with some random String value.

So I tried to create the session manually by creating the JSESSIONID cookie in the servlet but when I am trying to get the session it's not working.

What is happening here?

Is there anything else other than cookie(JSESSIONID) that gets stored soomewhere for the session creation?

If not why I'm not able to get the session ?

Please Help.

Code that I used to create the cookie and get the session

```<code>package sessionHandling;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebServlet("/sessionhandling")
public class SessionHandling extends HttpServlet {

private static final long serialVersionUID = 1L;

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    ServletOutputStream out = response.getOutputStream();
    out.print("Hello Mr.! How are you?");
    HttpSession session = request.getSession(false);
    if(session != null){
        out.println("You are logged in.");

        out.println("session found with "+session.getId());
        out.println("session found with "+session.getLastAccessedTime());

    }else{
        //session = request.getSession(true);
        Cookie JSESSIONID = new Cookie("JSESSIONID", "12345");
        JSESSIONID.setMaxAge(-1);
        response.addCookie(JSESSIONID);
        System.out.println("Cookie Created");

        out.print("You are not logged in");
    }
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    doGet(request, response);
}

}
</code>```

答:
You're not responsible for creating or tracking the cookie. The servlet container looks after this for you.

As soon as you invoke:

```<code>   HttpSession session = request.getSession(true);
</code>```

or

```<code>   HttpSession session = request.getSession();
</code>```

then the servlet container will start maintaining the session for you (and generate the cookie as needed).

The HttpSession object is maintained in server memory between requests and is usually looked up by the session id. If you create the cookie yourself the server will not know anything about it or any associated HttpSession.

Body:
I read that to persist session in servlet a cookie gets saved at client side with the name of JSESSIONID.

I checked it also and I found the cookie of localhost with the name of JSESSIONID with some random String value.

So I tried to create the session manually by creating the JSESSIONID cookie in the servlet but when I am trying to get the session it's not working.

What is happening here?

Is there anything else other than cookie(JSESSIONID) that gets stored soomewhere for the session creation?

If not why I'm not able to get the session ?

Please Help.

Code that I used to create the cookie and get the session

package sessionHandling;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebServlet("/sessionhandling")
public class SessionHandling extends HttpServlet {

private static final long serialVersionUID = 1L;

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    ServletOutputStream out = response.getOutputStream();
    out.print("Hello Mr.! How are you?");
    HttpSession session = request.getSession(false);
    if(session != null){
        out.println("You are logged in.");

        out.println("session found with "+session.getId());
        out.println("session found with "+session.getLastAccessedTime());

    }else{
        //session = request.getSession(true);
        Cookie JSESSIONID = new Cookie("JSESSIONID", "12345");
        JSESSIONID.setMaxAge(-1);
        response.addCookie(JSESSIONID);
        System.out.println("Cookie Created");

        out.print("You are not logged in");
    }
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    doGet(request, response);
}

}

Body:
You're not responsible for creating or tracking the cookie. The servlet container looks after this for you.

As soon as you invoke:

   HttpSession session = request.getSession(true);

or

   HttpSession session = request.getSession();

then the servlet container will start maintaining the session for you (and generate the cookie as needed).

The HttpSession object is maintained in server memory between requests and is usually looked up by the session id. If you create the cookie yourself the server will not know anything about it or any associated HttpSession.


来源: stackexchange

问:
Can't resolve all parameters for StateService
I'm trying to develop the app using Angular 2 with Ionic 2 and instead of NavController I want to try routing with ui-router-ng2.

Login.ts:

```<code>import { Component } from '@angular/core';
import { NavController, MenuController } from 'ionic-angular';

import { AlertController } from 'ionic-angular';

import { StateService } from "ui-router-ng2";

import { DashboardPage } from '../dashboard/dashboard';

@Component({
  selector: 'page-login',
  templateUrl: 'login.html',
  providers: [StateService]
})

export class LoginPage {

  username: string;
  password: string;

  constructor(public navCtrl: NavController, public menu: MenuController, public alertCtrl: AlertController, public state: StateService) {

    this.menu.enable(false, 'sidenav')

  }

  login() {

    if (this.username == "admin" && this.password == "admin") {
      // this.navCtrl.setRoot(DashboardPage, { username: this.username });
      this.state.go(DashboardPage);
    } else {
      let alert = this.alertCtrl.create({
        title: 'Incorrect Credentials!',
        subTitle: 'Your username and password are incorrect. Hint: admin',
        buttons: ['Login Again']
      });
      alert.present();
    }

  }

}
</code>```

I have imported StateService from "ui-router-ng2". I got the error, Can't resolve all parameters for StateService:

Please help me in sorting this issue.

答:
I had the same problem and I resolved it by @Injectable() before my service.

Like that:

```<code>import {Http} from '@angular/http';
import {Observable} from 'rxjs/Observable';
import {Injectable} from '@angular/core';

@Injectable()
export class StatService {
    private ressourceInterneUrl = 'api/interne/stat';

    constructor(private http: Http) {}

    addStatValues (viewName: string): Observable <any> {
        return this.http.get(`${this.ressourceInterneUrl}/${viewName}`).map((res: any) => {
            return res.json();
        });
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to develop the app using Angular 2 with Ionic 2 and instead of NavController I want to try routing with ui-router-ng2.

Login.ts:

import { Component } from '@angular/core';
import { NavController, MenuController } from 'ionic-angular';

import { AlertController } from 'ionic-angular';

import { StateService } from "ui-router-ng2";

import { DashboardPage } from '../dashboard/dashboard';

@Component({
  selector: 'page-login',
  templateUrl: 'login.html',
  providers: [StateService]
})

export class LoginPage {

  username: string;
  password: string;

  constructor(public navCtrl: NavController, public menu: MenuController, public alertCtrl: AlertController, public state: StateService) {

    this.menu.enable(false, 'sidenav')

  }

  login() {

    if (this.username == "admin" && this.password == "admin") {
      // this.navCtrl.setRoot(DashboardPage, { username: this.username });
      this.state.go(DashboardPage);
    } else {
      let alert = this.alertCtrl.create({
        title: 'Incorrect Credentials!',
        subTitle: 'Your username and password are incorrect. Hint: admin',
        buttons: ['Login Again']
      });
      alert.present();
    }

  }

}

I have imported StateService from "ui-router-ng2". I got the error, Can't resolve all parameters for StateService:

Please help me in sorting this issue.

Body:
I had the same problem and I resolved it by @Injectable() before my service.

Like that:

import {Http} from '@angular/http';
import {Observable} from 'rxjs/Observable';
import {Injectable} from '@angular/core';

@Injectable()
export class StatService {
    private ressourceInterneUrl = 'api/interne/stat';

    constructor(private http: Http) {}

    addStatValues (viewName: string): Observable <any> {
        return this.http.get(`${this.ressourceInterneUrl}/${viewName}`).map((res: any) => {
            return res.json();
        });
    }
}


问:
bash: npm: command not found
When I check the version of Node, it says

```<code>v8.0.0
</code>```

but when I check the version of NPM, it says

```<code>bash: npm: command not found
</code>```

Previously, my action was

npm install -g "@angular/cli"

That's when it consistently shows the npm: command not found message.

I tried searching for possible solutions but none worked like the brew and others.

答:
Solved with this:

npm config set prefix /usr/local

Title: bash: npm: command not found

Body:
When I check the version of Node, it says

v8.0.0

but when I check the version of NPM, it says

bash: npm: command not found

Previously, my action was

npm install -g "@angular/cli"

That's when it consistently shows the npm: command not found message.

I tried searching for possible solutions but none worked like the brew and others.


问:
Need to generate a 2D python list with each column having 2 possibilities, for each row
I need to generate a two-dimensional python list. It would consist of 10 columns, with each column value being either '1' or '0'. Given these conditions, my list needs to be an exhaustive list of all the combinations that can be formed in this way. It'd naturally end up being 1024 rows long (2^10). However, I have no clue where to get started on this. Can anyone help?</p>

答:
So this is how I worked through this problem. First I saw that we wanted to loop over all 1024 combinations of 0s and 1s. This is essentially counting from 0 to 1023 in binary. So I made a for loop from 0 to 1023 and at each iteration, I converted the iteration variable i into binary with format(i, 'b') and then turned it into a list with the list method. In the case of a number like 1, this gets converted into ['1'] but we want to convert that into ['0', '0', '0', '0', '0', '0', '0', '0', '0', '1'] which is what line
4 does. Finally, we append each result into the 'table' variable.

```<code>table=[]
for i in range(1024):
     binaryRepresentation = list(format(i, 'b'))
     finalRepresentation = ['0']*(10-len(binaryRepresentation)) + binaryRepresentation
     table.append(finalRepresentation)
</code>```

Body:
So this is how I worked through this problem. First I saw that we wanted to loop over all 1024 combinations of 0s and 1s. This is essentially counting from 0 to 1023 in binary. So I made a for loop from 0 to 1023 and at each iteration, I converted the iteration variable i into binary with format(i, 'b') and then turned it into a list with the list method. In the case of a number like 1, this gets converted into ['1'] but we want to convert that into ['0', '0', '0', '0', '0', '0', '0', '0', '0', '1'] which is what line
4 does. Finally, we append each result into the 'table' variable.

table=[]
for i in range(1024):
     binaryRepresentation = list(format(i, 'b'))
     finalRepresentation = ['0']*(10-len(binaryRepresentation)) + binaryRepresentation
     table.append(finalRepresentation)


问:
WebSphere Server V.8.5 troubles with Eclipse project

I'm trying to create an IBM WebSphere V.8.5 web app using Eclipse.

I downloaded and installed all the IBM packages needed and followed the official guide to create server and project.
Then I created an index.jsp under WebContent folder with just some HTML/CSS tags to print a static "Hello world".
Visiting http://localhost:9080/project_name/index.jsp I get the following:

Error message: JSPG0036E: Unable to find resource
  /project_name/index.jsp

I've already search for the error but ant solution was valid for my case.
The error continues...

Root cause: java.io.FileNotFoundException: JSPG0036E: Unable to find
  resource /project_name/index.jsp  at
  com.ibm.ws.jsp.webcontainerext.AbstractJSPExtensionProcessor.findWrapper(AbstractJSPExtensionProcessor.java:447)
    at
  com.ibm.ws.jsp.webcontainerext.AbstractJSPExtensionProcessor.getServletWrapper(AbstractJSPExtensionProcessor.java:338)
    at
  com.ibm.ws.webcontainer.filter.WebAppFilterManager.invokeFilters(WebAppFilterManager.java:1010)
    at
  com.ibm.ws.webcontainer.webapp.WebApp.handleRequest(WebApp.java:3980)
    at
  com.ibm.ws.webcontainer.webapp.WebGroup.handleRequest(WebGroup.java:304)
    at

...

答:
Eclipse doesn't provide an automatic build and launch of the web project so you have to export an EAR file (not WAR!) and import it into WebSphere Control Panel as WebSphere Enterprise Application.
Then just leave the options as they are and click "next" as many time as needed; in the WebSphere Enterprise Application panel you have to select the app just added and click "Launch"; it should work and then you can visit the URL http://hostname:9080/project_name/your_page.jsp.


问:
how to create a string like regex
i am new in C# language, i am trying to create a new desktop app.

but i am confuse to create a string like this..

```<code>private string getResult(int x){
    string results = "";

    return results
}
</code>```

so when i use getResult(1), it will return 0001

if i use getResults(111), it will return 0111

if i use getResults(10), it will return 0010.

something like this, i am confuse to create a string like this.

答:
You can simple use ToString with parameter:

```<code>private string getResult(int x)
{
    return x.ToString("0000");
}
</code>```

from @Dmitry Bychenko :

You can also use "D4" as parameter instead of "0000" with same results.

This solution also works with negative numbers instead of PadLeft method.

Title: how to create a string like regex

Body:
i am new in C# language, i am trying to create a new desktop app.

but i am confuse to create a string like this..

private string getResult(int x){
    string results = "";

    return results
}

so when i use getResult(1), it will return 0001

if i use getResults(111), it will return 0111

if i use getResults(10), it will return 0010.

something like this, i am confuse to create a string like this.

Body:
You can simple use ToString with parameter:

private string getResult(int x)
{
    return x.ToString("0000");
}

from @Dmitry Bychenko :

You can also use "D4" as parameter instead of "0000" with same results.

This solution also works with negative numbers instead of PadLeft method.


问:
how to import dojo modules in es6
I'm developing a library that uses ArcGIS which based on dojo framework.

ArcGIS has main file that we include in the

答:
for using dojo's require we need simply to write window.require and it will work.

without writing window. it is failing in the build process Can't resolve 'esri/Map'

For esri users who wants to use some nice loader - check out this one

code example:

```<code>export default class myMap {
     constructor(div) {
        window.require(['esri/Map', 'esri/views/MapView'], (esriMap, esriMapView) => {
            const map = new esriMap({
                basemap: "streets"
            });

            const view = new esriMapView({
                container: div,
                map: map,
                zoom: 4,
                center: [15, 65]
            });
        });
    }
}
</code>```

Title: how to import dojo modules in es6

Body:
for using dojo's require we need simply to write window.require and it will work.

without writing window. it is failing in the build process Can't resolve 'esri/Map'

For esri users who wants to use some nice loader - check out this one

code example:

export default class myMap {
     constructor(div) {
        window.require(['esri/Map', 'esri/views/MapView'], (esriMap, esriMapView) => {
            const map = new esriMap({
                basemap: "streets"
            });

            const view = new esriMapView({
                container: div,
                map: map,
                zoom: 4,
                center: [15, 65]
            });
        });
    }
}


问:
pass value to Redirect in mvc5
```<code>    [HttpPost]
    public ActionResult Welcome(FormCollection frm)
    {

        frm["parameter1"] = "Welcome1";
        frm["parameter2"] = "Welcome2";
        frm["parameter3"] = "Welcome3";
        frm["parameter4"] = "Welcome4";
        return Redirect("https://www.example.com");
    }
</code>```

Question :

I want to pass FormCollection Object when redirect to separate domain like "https://www.example.com"

Is this possible or not ?

Thanks in advance

答: Redirecting is HTTPGET request type, but you want to send data with your request, so it isn't redirecting process, you can use HttpClient class for posting data, refer to this question.

Title: pass value to Redirect in mvc5

Body:
    [HttpPost]
    public ActionResult Welcome(FormCollection frm)
    {

        frm["parameter1"] = "Welcome1";
        frm["parameter2"] = "Welcome2";
        frm["parameter3"] = "Welcome3";
        frm["parameter4"] = "Welcome4";
        return Redirect("https://www.example.com");
    }

Question :

I want to pass FormCollection Object when redirect to separate domain like "https://www.example.com"

Is this possible or not ?

Thanks in advance


问:
How to update the TTL on a collection?
Using NodeJS + MongoJS, I have connection to a mongo DB.

I set a TTL on a collection with:

```<code>myCollection.createIndex({createdAt: 1}, {expireAfterSeconds: 60 * 30})
</code>```

Is it now possible to update the value for expireAfterSeconds ?
If so, what's the policy for already existing items in the collection, ie : are their TTL updated automatically or are they left untouched ?

答:
Apart of the @Neil answer above, the documentation states, that

You cannot use createIndex() to change the value of expireAfterSeconds of an existing index. Instead use the collMod database command in conjunction with the index collection flag. Otherwise, to change the value of the option of an existing index, you must drop the index first and recreate.

So

db.runCommand({
  "collMod": <collection>,
  "index": {
    keyPattern: <index_spec>,
    expireAfterSeconds: <seconds>
  }
})
```

should work fine too.

Title: How to update the TTL on a collection?

Body:
Using NodeJS + MongoJS, I have connection to a mongo DB.

I set a TTL on a collection with:

myCollection.createIndex({createdAt: 1}, {expireAfterSeconds: 60 * 30})

Is it now possible to update the value for expireAfterSeconds ?
If so, what's the policy for already existing items in the collection, ie : are their TTL updated automatically or are they left untouched ?

Body:
Apart of the @Neil answer above, the documentation states, that

You cannot use createIndex() to change the value of expireAfterSeconds of an existing index. Instead use the collMod database command in conjunction with the index collection flag. Otherwise, to change the value of the option of an existing index, you must drop the index first and recreate.

So

db.runCommand({
  "collMod": <collection>,
  "index": {
    keyPattern: <index_spec>,
    expireAfterSeconds: <seconds>
  }
})

should work fine too.

ContentLicense: CC BY-SA 4.0


问:
ComboBox displays duplicate values
I want to the add the item of ComboBox. I has been successful in adding items but the ComboBox has duplicate items. Why?

This is my code:

```<code>Public Sub load_consigneecode()
    Dim con As OleDbConnection = New OleDbConnection(constring)
    con.Open()
    Dim sql As String = "select con_code from TblConsignee order by con_code"
    Dim cmd As New OleDbCommand(sql, con)
    Dim myreader As OleDbDataReader = cmd.ExecuteReader()

    While myreader.Read()
        cmbCode.Items.Add(myreader(0).ToString)
    End While

    myreader.Close()
    con.Close()
End Sub
</code>```

This is the result:

In my table:

答:
```<code>Public Sub load_consigneecode()
    Dim con As OleDbConnection = New OleDbConnection(constring)
    con.Open()
    Dim sql As String = "select con_code from TblConsignee order by con_code"
    Dim cmd As New OleDbCommand(sql, con)
    Dim myreader As OleDbDataReader = cmd.ExecuteReader()

    'add this in code
    cmbCode.Items.Clear();
    While myreader.Read()
        cmbCode.Items.Add(myreader(0).ToString)
    End While

    myreader.Close()
    con.Close()
End Sub
</code>```

Else use distinct in your SQL query

Title: ComboBox displays duplicate values

Body:
I want to the add the item of ComboBox. I has been successful in adding items but the ComboBox has duplicate items. Why?

This is my code:

Public Sub load_consigneecode()
    Dim con As OleDbConnection = New OleDbConnection(constring)
    con.Open()
    Dim sql As String = "select con_code from TblConsignee order by con_code"
    Dim cmd As New OleDbCommand(sql, con)
    Dim myreader As OleDbDataReader = cmd.ExecuteReader()

    While myreader.Read()
        cmbCode.Items.Add(myreader(0).ToString)
    End While

    myreader.Close()
    con.Close()
End Sub

This is the result:

In my table:

Body:
Public Sub load_consigneecode()
    Dim con As OleDbConnection = New OleDbConnection(constring)
    con.Open()
    Dim sql As String = "select con_code from TblConsignee order by con_code"
    Dim cmd As New OleDbCommand(sql, con)
    Dim myreader As OleDbDataReader = cmd.ExecuteReader()

    'add this in code
    cmbCode.Items.Clear();
    While myreader.Read()
        cmbCode.Items.Add(myreader(0).ToString)
    End While

    myreader.Close()
    con.Close()
End Sub

Else use distinct in your SQL query


问:
C# same namespace in different files
I tried to move implementation to other file and got Error in Form1.cs "OpenPort doesn't exist in the curent context"
Any suggestions, please?</p>

```<code>Form1.cs

namespace MyApp
{
    void Form1Load(object sender, EventArgs e)
    {
        OpenPort();
    }
}

Port.cs

namespace MyApp
{
    public static void OpenPort();
}
</code>```

答:
Think of a namespace like a container. Just like any other container you can put stuff in it. An advantage of namespaces is that they can group functionality together without you needing to put everything in the same file - of particular use when programs get large. Namespaces are also a way of keeping names separate. Think of roads - both London Road and High Street may both have a number 18 but 18 London Road and 18 High Street are different and distinguishable.

For example, MyNamespace contains MyClass and MyClass contains MyMethod

```<code>namespace MyNamespace
{
    class MyClass
    {
        void MyMethod() {}
    }
}
</code>```

To use MyMethod from another namespace you need to add a using statement for MyNamespace.

Taking this a step further imagine MyOtherNamespace contains MyClass and MyClass contains MyMethod
MyOtherNamespace also contains MyClass and MyClass also contains MyMethod

```<code>namespace MyOtherNamespace
{
    class MyClass
    {
        void MyMethod() {}
    }
}
</code>```

As before, to use MyMethod from another namespace you need to add a using statement for MyOtherNamespace.

If you want to use MyMethod from both MyNamespace and MyOtherNamespace you must tell your program which one to use by adding the Namespace name to the call like this

```<code>MyNamespace.MyClass.MyMethod();
MyOtherNamespace.MyClass.MyMethod();
</code>```

The same rule applies if you've got multiple classes with the same method in the same namespace - the difference being you don't need to include the namespace

```<code>MyFirstClass.MyMethod();
MySecondClass.MyMethod();
</code>```

On a related note, you can also split a class between multiple files using the partial keyword. For example, you could turn this

```<code>namespace MyNamespace
{
    class MyClass
    {
        void MyMethod() {}
        void MyOtherMethod() {}
    }
}
</code>```

Into this

```<code>namespace MyNamespace
{
    partial class MyClass
    {
        void MyMethod() {}
    }

    partial class MyClass
    {
        void MyOtherMethod() {}
    }
}
</code>```

Functionally they're the same and in both cases you'd call the methods like this

```<code>MyClass.MyMethod();
MyClass.MyOtherMethod();
</code>```

Title: C# same namespace in different files

Body:
I tried to move implementation to other file and got Error in Form1.cs "OpenPort doesn't exist in the curent context"
Any suggestions, please?

Form1.cs

namespace MyApp
{
    void Form1Load(object sender, EventArgs e)
    {
        OpenPort();
    }
}

Port.cs

namespace MyApp
{
    public static void OpenPort();
}

Body:
Think of a namespace like a container. Just like any other container you can put stuff in it. An advantage of namespaces is that they can group functionality together without you needing to put everything in the same file - of particular use when programs get large. Namespaces are also a way of keeping names separate. Think of roads - both London Road and High Street may both have a number 18 but 18 London Road and 18 High Street are different and distinguishable.

For example, MyNamespace contains MyClass and MyClass contains MyMethod

namespace MyNamespace
{
    class MyClass
    {
        void MyMethod() {}
    }
}

To use MyMethod from another namespace you need to add a using statement for MyNamespace.

Taking this a step further imagine MyOtherNamespace contains MyClass and MyClass contains MyMethod
MyOtherNamespace also contains MyClass and MyClass also contains MyMethod

namespace MyOtherNamespace
{
    class MyClass
    {
        void MyMethod() {}
    }
}

As before, to use MyMethod from another namespace you need to add a using statement for MyOtherNamespace.

If you want to use MyMethod from both MyNamespace and MyOtherNamespace you must tell your program which one to use by adding the Namespace name to the call like this

MyNamespace.MyClass.MyMethod();
MyOtherNamespace.MyClass.MyMethod();

The same rule applies if you've got multiple classes with the same method in the same namespace - the difference being you don't need to include the namespace

MyFirstClass.MyMethod();
MySecondClass.MyMethod();

On a related note, you can also split a class between multiple files using the partial keyword. For example, you could turn this

namespace MyNamespace
{
    class MyClass
    {
        void MyMethod() {}
        void MyOtherMethod() {}
    }
}

Into this

namespace MyNamespace
{
    partial class MyClass
    {
        void MyMethod() {}
    }

    partial class MyClass
    {
        void MyOtherMethod() {}
    }
}

Functionally they're the same and in both cases you'd call the methods like this

MyClass.MyMethod();
MyClass.MyOtherMethod();


问:
Can't echo value in file python
For example, I have a file python

work1.py

```<code>from time import sleep
while True:
    print "Send 1"
    sleep(2)
    print "Send 2"
    sleep(2)
</code>```

And i have a file php to run file python via shell_exec function

```<code> <?php
$result=shell_exec("sudo python work1.py");
echo $result;
?>
</code>```

But when i run, nothing display. So what's problem? Please help me. Thanks.

答:
Why would the script return some value?
Your python statement will continue to be in execution.
Add break statement in the script

```<code>from time import sleep
while True:
    print "Send 1"
    sleep(2)
    print "Send 2"
    sleep(2)
    break
</code>```

PHP CODE

```<code><?php
    $result=shell_exec('sudo python work1.py');
    echo $result;
    ?>
</code>```

Title: Can't echo value in file python

Body:
For example, I have a file python

work1.py

from time import sleep
while True:
    print "Send 1"
    sleep(2)
    print "Send 2"
    sleep(2)

And i have a file php to run file python via shell_exec function

 <?php
$result=shell_exec("sudo python work1.py");
echo $result;
?>

But when i run, nothing display. So what's problem? Please help me. Thanks.

Body:
Why would the script return some value?
Your python statement will continue to be in execution.
Add break statement in the script

from time import sleep
while True:
    print "Send 1"
    sleep(2)
    print "Send 2"
    sleep(2)
    break

PHP CODE

<?php
    $result=shell_exec('sudo python work1.py');
    echo $result;
    ?>


问:
Android Google Maps GeoJsonLayer OnFeatureClickListener, multiple layers
Please look at my code to create layer from geojson string and add layer to map:

```<code>private GeoJsonLayer createLayerFromGeojson(String json)
    {
        JSONObject ob = null;

        try
        {
            ob = new JSONObject(json);
        }
        catch (JSONException e)
        {
            e.printStackTrace();
        }

        GeoJsonLayer layer = new GeoJsonLayer(googleMap, ob);
        layer.addLayerToMap();

        layer.setOnFeatureClickListener(feature -> Utils.showMessage(getActivity(), "Clicked", feature.getProperty("description").toString()));

        return layer;
    }
</code>```

Next add 2 layers to map:

```<code>String json = /*first geojson string here*/
String json2 = /*another geojson string here*/

createLayerFromGeojson(json);
createLayerFromGeojson(json2);
</code>```

Problem: When I click on marker or pologon, always description taken from second json (json2) is displayed, even if I click on object created from first json, on first layer.

What's wrong? Any ideas?

答:
If you check the documentation for the method setOnFeatureClickListener it says:

Sets a single click listener for the entire GoogleMap object, that will be called with the corresponding Feature object when an object on the map (Polygon, Marker, Polyline) is clicked.

To me, it seems silly that we cannot have multiple layers with information from different GeoJson. It needs to be a MultiPolygon, MultiLineString or MultiPoint.

Reference: https://github.com/googlemaps/android-maps-utils/blob/master/library/src/com/google/maps/android/data/Layer.java#L89

Body:
Please look at my code to create layer from geojson string and add layer to map:

private GeoJsonLayer createLayerFromGeojson(String json)
    {
        JSONObject ob = null;

        try
        {
            ob = new JSONObject(json);
        }
        catch (JSONException e)
        {
            e.printStackTrace();
        }

        GeoJsonLayer layer = new GeoJsonLayer(googleMap, ob);
        layer.addLayerToMap();

        layer.setOnFeatureClickListener(feature -> Utils.showMessage(getActivity(), "Clicked", feature.getProperty("description").toString()));

        return layer;
    }

Next add 2 layers to map:

String json = /*first geojson string here*/
String json2 = /*another geojson string here*/

createLayerFromGeojson(json);
createLayerFromGeojson(json2);

Problem: When I click on marker or pologon, always description taken from second json (json2) is displayed, even if I click on object created from first json, on first layer.

What's wrong? Any ideas?


问:
ORA-01843 "not a valid month" and ORA-01861 "literal does not match format string"
```<code>SQL> select to_timestamp('2010-12-14:09:56:53') - to_timestamp('2010-12-14:09:56:46') from dua
l;
select to_timestamp('2010-12-14:09:56:53') - to_timestamp('2010-12-14:09:56:46') from dual
                    *
ERROR at line 1:
ORA-01843: not a valid month

SQL> select to_date('2010-12-14:09:56:53') - to_date('2010-12-14:09:56:46') from dual;
select to_date('2010-12-14:09:56:53') - to_date('2010-12-14:09:56:46') from dual
               *
ERROR at line 1:
ORA-01861: literal does not match format string
</code>```

What is the correct way to do a

```<code>2010-12-14:09:56:53
minus
2010-12-14:09:56:46
</code>```

in Oracle SQL?

ContentLicense: CC BY-SA 2.5

Body:
SQL> select to_timestamp('2010-12-14:09:56:53') - to_timestamp('2010-12-14:09:56:46') from dua
l;
select to_timestamp('2010-12-14:09:56:53') - to_timestamp('2010-12-14:09:56:46') from dual
                    *
ERROR at line 1:
ORA-01843: not a valid month

SQL> select to_date('2010-12-14:09:56:53') - to_date('2010-12-14:09:56:46') from dual;
select to_date('2010-12-14:09:56:53') - to_date('2010-12-14:09:56:46') from dual
               *
ERROR at line 1:
ORA-01861: literal does not match format string

What is the correct way to do a

2010-12-14:09:56:53
minus
2010-12-14:09:56:46

in Oracle SQL?

Body:
You have to specify format that your timestamp string is in to TO_DATE and TO_TIMESTAMP functions:

select
    to_date('2010-12-14:09:56:53', 'YYYY-MM-DD:HH24:MI:SS') -
    to_date('2010-12-14:09:56:46', 'YYYY-MM-DD:HH24:MI:SS')
from dual;

Result will be in days, which you can multiply by 86,400 to get seconds:

TO_DATE('2010-12-14:09:56:53','YYYY-MM-DD:HH24:MI:SS')-TO_DATE('2010-12-14:09:56
--------------------------------------------------------------------------------
.000081019

Using TO_TIMESTAMP:

select
    to_timestamp('2010-12-14:09:56:53', 'YYYY-MM-DD:HH24:MI:SS') -
    to_timestamp('2010-12-14:09:56:46', 'YYYY-MM-DD:HH24:MI:SS')
from dual;

Result will be in TIMESTAMP format:

TO_TIMESTAMP('2010-12-14:09:56:53','YYYY-MM-DD:HH24:MI:SS')-TO_TIMESTAMP('2
---------------------------------------------------------------------------
+000000000 00:00:07.000000000


问:
Javascript variable checking: (null or undefined) vs boolean
I want to check in an JS object (example: { x:false, y:true } ) if some properties are either boolean or if they are (null || undefined).

Is there an easy way in JS or Underscore to check this without doing

```<code>(obj.x != null || obj.x != undefined)
</code>```

???

答:
In Javascript, undefined is evaluated as false, so you should be able to do</p>

```<code>if (obj.x) {
    // ...
}
</code>```

Body:
I want to check in an JS object (example: { x:false, y:true } ) if some properties are either boolean or if they are (null || undefined).

Is there an easy way in JS or Underscore to check this without doing

(obj.x != null || obj.x != undefined)

???

Body:
In Javascript, undefined is evaluated as false, so you should be able to do

if (obj.x) {
    // ...
}


答:
You could use just the standard typeof operator, which returns 'boolean' if boolean.

console.log(typeof undefined === 'boolean'); // false
console.log(typeof null === 'boolean');      // false
console.log(typeof true === 'boolean');      // true
console.log(typeof false === 'boolean');     // true```

Title: Javascript variable checking: (null or undefined) vs boolean


问:
what is the result inside fft bin at different index?
For example if I have 10 samples in the FFT in a system sampled at 100 Hz. Then how are the results represented in FFT bin output ?
The frequency resolution is going to be how many Hz each DFT bin represents. This is, as you have noted, given by fs/N.  In this case :--

```<code>resolution = 100/10 = 10 hz
</code>```

Definition of FFT states that frequency range [0,fs] is represented by N point.

But when the result comes :--

X[0] is the constant term (also refereed to as DC bias)

X[1] is the 10 hz

X[2] is the 20 hz

X[3] is the 30 hz

X[4] is the 40 hz

X[5] is the 50 hz

X[6] to X[9] are the complex conjugates of X[4] to X[1] respectively.

so my question is :--

X[6] is the 60hz signal & its value will be complex conjugate of 40 hz signal .. is it right ?

Or X[6] does not contains spectral of 60hz but it is only complex conjugate of X[4] ?

Please suggest.

答:
Assuming your input signal is purely real, then X[6] is just the complex conjugate of X[4]. The top half of the spectrum is essentially redundant for real signals. See: this question and answer for further details.

Note that the input signal should be bandwidth-limited to fs / 2, otherwise aliasing will occur, so for a baseband signal there should not be any components >= fs / 2.

Body:
For example if I have 10 samples in the FFT in a system sampled at 100 Hz. Then how are the results represented in FFT bin output ?
The frequency resolution is going to be how many Hz each DFT bin represents. This is, as you have noted, given by fs/N.  In this case :--

resolution = 100/10 = 10 hz

Definition of FFT states that frequency range [0,fs] is represented by N point.

But when the result comes :--

X[0] is the constant term (also refereed to as DC bias)

X[1] is the 10 hz

X[2] is the 20 hz

X[3] is the 30 hz

X[4] is the 40 hz

X[5] is the 50 hz

X[6] to X[9] are the complex conjugates of X[4] to X[1] respectively.

so my question is :--

X[6] is the 60hz signal & its value will be complex conjugate of 40 hz signal .. is it right ?

Or X[6] does not contains spectral of 60hz but it is only complex conjugate of X[4] ?

Please suggest.


问:
Local Playback Security setting in Flash for outside communication with inside as-classes?
I'm using external actionscript files located in the root of my webfolder,
but I also want to communicate with another website.

How should I set my Local playback in publish settings?
Access Local Only? or Access Network Only?

答: as far as i remember if an swf file is located on a webserver it knows it's in the internet (so it has problems with loading files from the web if saved on users' hdd if it isn't allowed in the Global Security Settings panel) - so imho it should be published for web</p>


问:
how to use div in el expression
I need to use a el expression like this :

<c:out value="${list.div}"/>

the 'div' is not  tag, it's one of the column name in my table.
but it doesn't work and causes error because editor consider my div as  tag.

Someone knows how to do this?

Thanks.

答:
EL div (/) is reserved word and should not be used as an identifier.

JSP Reserved Words

Title: how to use div in el expression


答:
You are probably not clearing the items in your ComboBox before adding new ones:

```<code>cmbCode.Items.Clear()
</code>```

That said, you are better binding to the .DataSource of the ComboBox using a DataTable and setting the .DisplayMember and .ValueMember properties.

I would also consider implementing Using:

Sometimes your code requires an unmanaged resource, such as a file handle, a COM wrapper, or a SQL connection. A Using block guarantees the disposal of one or more such resources when your code is finished with them. This makes them available for other code to use.

With the changes you code would look something like this:

```<code>Dim dt As New DataTable
Using con As OleDbConnection New OleDbConnection(constring),
      cmd As New OleDbCommand("SELECT [con_code] FROM [TblConsignee] ORDER BY [con_code]", con)
    con.Open()

    dt.Load(cmd.ExecuteReader())
End Using

cmbCode.DataSource = dt
cmbCode.DisplayMember = "con_code"
cmbCode.ValueMember = "con_code"
</code>```

Title: ComboBox displays duplicate values

Body:
You are probably not clearing the items in your ComboBox before adding new ones:

cmbCode.Items.Clear()

That said, you are better binding to the .DataSource of the ComboBox using a DataTable and setting the .DisplayMember and .ValueMember properties.

I would also consider implementing Using:

Sometimes your code requires an unmanaged resource, such as a file handle, a COM wrapper, or a SQL connection. A Using block guarantees the disposal of one or more such resources when your code is finished with them. This makes them available for other code to use.

With the changes you code would look something like this:

Dim dt As New DataTable
Using con As OleDbConnection New OleDbConnection(constring),
      cmd As New OleDbCommand("SELECT [con_code] FROM [TblConsignee] ORDER BY [con_code]", con)
    con.Open()

    dt.Load(cmd.ExecuteReader())
End Using

cmbCode.DataSource = dt
cmbCode.DisplayMember = "con_code"
cmbCode.ValueMember = "con_code"


问:
Good use of memory
If i create a cell with 1000 matrices ( size of each matrix 800*1280), clearing each matrix after using it will speed up calculations ?

Example

```<code> A=cell(1000,1);
  for i=1:1000
      A{i}=rand(800,1280);
  end
  image=A{1};
  image2=A{2}; % I will use image and image2 with other functions
  A{1}=[];
  A{2}=[];
</code>```

EDIT

The real use of the cell will be like :

```<code>A=cell(1000,1);
parfor i=1:1000
    A{i}=function_that_creates_image(800,1280); % image with size 800*1280 px
end
for i=1:number_of_images   % number_of_images=1000 in this case
image1=A{1};
    image2=A{2};
    A{1}=[];
    A{2}=[];
    % image1 and image 2 will be used then in the next lines
    %next lines of code
end
</code>```

I noticed that calculating components of A in a parfor loop is faster than calculating each component for each loop inside the for

答:
If you want to use less memory and speed up calculations, it's wiser to avoid using cells. Luckily, it's very easy in your case, since all your matrices are the same size, so you could use an ND-array.

```<code>A = zeros(800,1280,1000);
for k = 1:size(A,3)
   A(:,:,k) = function_that_creates_image(800,1280);
end
image = A(:,:,1);
image2 = A(:,:,2); % I will use image and image2 with other functions
</code>```

EDIT:

If you want to further process each image, I would save them to a file within the parfor, so you will have 1000 .mat files at the end of the first loop:

```<code>parfor k = 1:number_of_images
   A = function_that_creates_image(800,1280);
   save(['images_dir\image' num2str(k) '.mat'],'A');
end
</code>```

then you can load them as needed for processing using load:

```<code>for k = 1:number_of_images-1
    image1 = load(['images_dir\image' num2str(k) '.mat']);
    image2 = load(['images_dir\image' num2str(k+1) '.mat'];
    % do what you want with those images...
end
</code>```

This way you only keep 2 images in memory each time, and on the next iteration they a replaced by the next images.

Title: Good use of memory

Body:
If i create a cell with 1000 matrices ( size of each matrix 800*1280), clearing each matrix after using it will speed up calculations ?

Example

 A=cell(1000,1);
  for i=1:1000
      A{i}=rand(800,1280);
  end
  image=A{1};
  image2=A{2}; % I will use image and image2 with other functions
  A{1}=[];
  A{2}=[];

EDIT

The real use of the cell will be like :

A=cell(1000,1);
parfor i=1:1000
    A{i}=function_that_creates_image(800,1280); % image with size 800*1280 px
end
for i=1:number_of_images   % number_of_images=1000 in this case
image1=A{1};
    image2=A{2};
    A{1}=[];
    A{2}=[];
    % image1 and image 2 will be used then in the next lines
    %next lines of code
end

I noticed that calculating components of A in a parfor loop is faster than calculating each component for each loop inside the for

Body:
If you want to use less memory and speed up calculations, it's wiser to avoid using cells. Luckily, it's very easy in your case, since all your matrices are the same size, so you could use an ND-array.

A = zeros(800,1280,1000);
for k = 1:size(A,3)
   A(:,:,k) = function_that_creates_image(800,1280);
end
image = A(:,:,1);
image2 = A(:,:,2); % I will use image and image2 with other functions

EDIT:

If you want to further process each image, I would save them to a file within the parfor, so you will have 1000 .mat files at the end of the first loop:

parfor k = 1:number_of_images
   A = function_that_creates_image(800,1280);
   save(['images_dir\image' num2str(k) '.mat'],'A');
end

then you can load them as needed for processing using load:

for k = 1:number_of_images-1
    image1 = load(['images_dir\image' num2str(k) '.mat']);
    image2 = load(['images_dir\image' num2str(k+1) '.mat'];
    % do what you want with those images...
end

This way you only keep 2 images in memory each time, and on the next iteration they a replaced by the next images.


问:
C program recursive call to main() with and without parameters
Why does it give an error of segmentation fault(core dumped) and gives no output in 1st case ?Can anyone explain how program is program callls main recursively with parameters?

```<code>#include <stdio.h>
int main()
{
    static int i = 2;
    if (i<7)
    {
        main();
        printf("%d ", i);
        i++;
        //main(10);
    }
}
</code>```

-

```<code>#include <stdio.h>
int main()
{
    static int i = 5;
    if (--i)
    {
     //main();
     printf("%d ", i);
     main(10);
    }
}
</code>```

答:
You are calling main() first and then incrementing i

```<code> if (i<7)
    {
        main();           // <-- main called when i still 2
        printf("%d ", i);
        i++;              // <-- statement never reached
        //main(10);
    }
</code>```

Hence, while main() calls main() recursively, the statement i++ is never reached.

You should increment i before calling main()

```<code>if (i<7)
    {
        i++;
        main();
        printf("%d ", i);
        //main(10);
    }
</code>```

Body:
Why does it give an error of segmentation fault(core dumped) and gives no output in 1st case ?Can anyone explain how program is program callls main recursively with parameters?

#include <stdio.h>
int main()
{
    static int i = 2;
    if (i<7)
    {
        main();
        printf("%d ", i);
        i++;
        //main(10);
    }
}

-

#include <stdio.h>
int main()
{
    static int i = 5;
    if (--i)
    {
     //main();
     printf("%d ", i);
     main(10);
    }
}

Body:
You are calling main() first and then incrementing i

 if (i<7)
    {
        main();           // <-- main called when i still 2
        printf("%d ", i);
        i++;              // <-- statement never reached
        //main(10);
    }

Hence, while main() calls main() recursively, the statement i++ is never reached.

You should increment i before calling main()

if (i<7)
    {
        i++;
        main();
        printf("%d ", i);
        //main(10);
    }


问:
Add header to RDD[string] spark scala
hi guys i have an RDD[string] , that i want to add to it a header before saving it to a text file  , here the code i did </p>

```<code>val projectionsTxt = rowMatrix.rows.map(l => l.toString.filter(c => c != '[' & c != ']'))
      val res = projectionsTxt.map(p => {
        var tokens = p.split(",")

        for (i <- 0 to tokens.length - 1) {

          tokens(i) = (BigDecimal(tokens(i)).setScale(2, BigDecimal.RoundingMode.HALF_UP).toDouble).toString()

        }
        tokens.mkString(",")

      })
      val header: RDD[String] = sc.parallelize(Array("col1","col2","col3"))

   header.union(res).saveAsTextFile(strFilePath)
</code>```

<p>any help please i've not been able to get it done .
i would like to get data and their header .Thanks </p>

答:
try : val header: RDD[String] = sc.parallelize(Array("col1,col2,col3"))

The column List must match with a String ( = a line ). You have a RDD[String] .
so you must declare an array of one 'String' element.

Title: Add header to RDD[string] spark scala

Body:
hi guys i have an RDD[string] , that i want to add to it a header before saving it to a text file  , here the code i did

val projectionsTxt = rowMatrix.rows.map(l => l.toString.filter(c => c != '[' & c != ']'))
      val res = projectionsTxt.map(p => {
        var tokens = p.split(",")

        for (i <- 0 to tokens.length - 1) {

          tokens(i) = (BigDecimal(tokens(i)).setScale(2, BigDecimal.RoundingMode.HALF_UP).toDouble).toString()

        }
        tokens.mkString(",")

      })
      val header: RDD[String] = sc.parallelize(Array("col1","col2","col3"))

   header.union(res).saveAsTextFile(strFilePath)

any help please i've not been able to get it done .
i would like to get data and their header .Thanks


答:
The typeof operator can return whether it is boolean or anything else

Reference here


问:
Retry Quartz Scheduler start up on database connection failure
We have a Java application that uses Quartz for scheduling jobs. The version of quartz that we use is: quartz-2.2.1

The quartz configuration uses JDBC job store.

If the database connection is down (due to intermittent network failure) at the time of calling start method on quartz scheduler object, it fails with the following exception:

```<code>2017-05-28 00:05:45 org.quartz.SchedulerConfigException: Failure occured during job recovery. [See nested exception: org.quartz.JobPersistenceException: Couldn't recover jobs: The connection is closed. [See nested exception: com.microsoft.sqlserver.jdbc.SQLServerException: The connection is closed.]]
2017-05-28 00:05:45     at org.quartz.impl.jdbcjobstore.JobStoreSupport.schedulerStarted(JobStoreSupport.java:692)
2017-05-28 00:05:45     at org.quartz.core.QuartzScheduler.start(QuartzScheduler.java:567)
2017-05-28 00:05:45     at org.quartz.impl.StdScheduler.start(StdScheduler.java:142)
</code>```

In order to ensure that quartz scheduler is started successfully, we added retry in our code which makes a call to start method on quartz scheduler object after every 1 second. But when the database connection is up, the call to quartz scheduler start method is successful (it doesn't throw any exception) - but the associated triggers that reside in the database are not started and no job is triggered.

Any idea what could be the issue here? Any help shall be appreciated.

Here is the quartz configuration, please note that we have already enabled validation query to handle crappy connections (due to intermittent network failure)

```<code>#============================================================================
# Configure Main Scheduler Properties
#============================================================================

org.quartz.scheduler.instanceName = TestScheduler
org.quartz.scheduler.instanceId = AUTO
org.quartz.scheduler.skipUpdateCheck=true

#============================================================================
# Configure ThreadPool
#============================================================================

org.quartz.threadPool.class =     org.quartz.simpl.SimpleThreadPool
org.quartz.threadPool.threadCount =  50
org.quartz.threadPool.threadPriority = 5

#============================================================================
# Configure JobStore
#============================================================================

org.quartz.jobStore.misfireThreshold = 60000
org.quartz.jobStore.maxMisfiresToHandleAtATime = 15

org.quartz.jobStore.class =     org.quartz.impl.jdbcjobstore.JobStoreTX
org.quartz.jobStore.driverDelegateClass =     org.quartz.impl.jdbcjobstore.StdJDBCDelegate
org.quartz.jobStore.useProperties = false
org.quartz.jobStore.dataSource = aBPM
org.quartz.jobStore.tablePrefix = ABPM_
org.quartz.jobStore.isClustered = false
org.quartz.jobStore.useDBLocks = false
org.quartz.jobStore.acquireTriggersWithinLock = true

#============================================================================
# Configure Datasources
#============================================================================
org.quartz.dataSource.aBPM.driver = org.hsqldb.jdbcDriver
org.quartz.dataSource.aBPM.URL = jdbc:hsqldb:file:embeddedDb/db/abpmquartz
org.quartz.dataSource.aBPM.user = sa
org.quartz.dataSource.aBPM.encryptPassword = yes
org.quartz.dataSource.aBPM.password = fMFVvEFk3gFmM9ewWQkTNg==
org.quartz.dataSource.aBPM.maxConnections = 55
org.quartz.dataSource.aBPM.validationQuery= SELECT 1
</code>```

答:
You might have an issue with job misfires.

TL;DR: use appropriate misfire instructions when building your triggers, or increase misfireThreshold.

If the Scheduler was down at the time the triggers were supposed to fire, that's a misfire. Once the Scheduler is up, Quartz checks for misfired jobs and looks for instructions about what to do with them. Run them immediately? Wait until their next scheduled fire time?
To let it know what to do, you can either be explicit by using misfire instructions, or just default to Quartz's smart policy, which depends on the trigger type (e.g. CronTrigger has a different default misfire policy than SimpleTrigger).

Sadly, Quartz's cookbook is kind of lacking when it comes to explaining misfire instructions, and tells you to check the JavaDoc for every Trigger subclass if you want to know more.

So this one guy wrote a blog entry with all misfire instructions and default misfire policies explained for your convenience.

You didn't tell us what kind of triggers you are using, but you probably want to include misfire instructions like withMisfireHandlingInstructionFireNow(), which will run your job as soon as the Scheduler is up.

Another option is to set org.quartz.jobStore.misfireThreshold to a value higher than what the Scheduler takes to start.

Right now you have it set to 1 minute. That means that any job firing less than 1 minute later than its expected fire time, will not be considered a misfire and will be run just fine. However, for jobs that were more than 1 minute late, Quartz will check misfiring policy for them.

Say you know the Scheduler always takes less than 5 minutes to come online; you may then try to set org.quartz.jobStore.misfireThreshold = 300000, so when the jobs fire up on scheduler start, Quartz sees that they were late for less than 5 minutes and will just let them execute without checking the misfire policy first.

Body:
We have a Java application that uses Quartz for scheduling jobs. The version of quartz that we use is: quartz-2.2.1

The quartz configuration uses JDBC job store.

If the database connection is down (due to intermittent network failure) at the time of calling start method on quartz scheduler object, it fails with the following exception:

2017-05-28 00:05:45 org.quartz.SchedulerConfigException: Failure occured during job recovery. [See nested exception: org.quartz.JobPersistenceException: Couldn't recover jobs: The connection is closed. [See nested exception: com.microsoft.sqlserver.jdbc.SQLServerException: The connection is closed.]]
2017-05-28 00:05:45     at org.quartz.impl.jdbcjobstore.JobStoreSupport.schedulerStarted(JobStoreSupport.java:692)
2017-05-28 00:05:45     at org.quartz.core.QuartzScheduler.start(QuartzScheduler.java:567)
2017-05-28 00:05:45     at org.quartz.impl.StdScheduler.start(StdScheduler.java:142)

In order to ensure that quartz scheduler is started successfully, we added retry in our code which makes a call to start method on quartz scheduler object after every 1 second. But when the database connection is up, the call to quartz scheduler start method is successful (it doesn't throw any exception) - but the associated triggers that reside in the database are not started and no job is triggered.

Any idea what could be the issue here? Any help shall be appreciated.

Here is the quartz configuration, please note that we have already enabled validation query to handle crappy connections (due to intermittent network failure)

#============================================================================
# Configure Main Scheduler Properties
#============================================================================

org.quartz.scheduler.instanceName = TestScheduler
org.quartz.scheduler.instanceId = AUTO
org.quartz.scheduler.skipUpdateCheck=true

#============================================================================
# Configure ThreadPool
#============================================================================

org.quartz.threadPool.class =     org.quartz.simpl.SimpleThreadPool
org.quartz.threadPool.threadCount =  50
org.quartz.threadPool.threadPriority = 5

#============================================================================
# Configure JobStore
#============================================================================

org.quartz.jobStore.misfireThreshold = 60000
org.quartz.jobStore.maxMisfiresToHandleAtATime = 15

org.quartz.jobStore.class =     org.quartz.impl.jdbcjobstore.JobStoreTX
org.quartz.jobStore.driverDelegateClass =     org.quartz.impl.jdbcjobstore.StdJDBCDelegate
org.quartz.jobStore.useProperties = false
org.quartz.jobStore.dataSource = aBPM
org.quartz.jobStore.tablePrefix = ABPM_
org.quartz.jobStore.isClustered = false
org.quartz.jobStore.useDBLocks = false
org.quartz.jobStore.acquireTriggersWithinLock = true

#============================================================================
# Configure Datasources
#============================================================================
org.quartz.dataSource.aBPM.driver = org.hsqldb.jdbcDriver
org.quartz.dataSource.aBPM.URL = jdbc:hsqldb:file:embeddedDb/db/abpmquartz
org.quartz.dataSource.aBPM.user = sa
org.quartz.dataSource.aBPM.encryptPassword = yes
org.quartz.dataSource.aBPM.password = fMFVvEFk3gFmM9ewWQkTNg==
org.quartz.dataSource.aBPM.maxConnections = 55
org.quartz.dataSource.aBPM.validationQuery= SELECT 1


答:
TL;DR StackOverflow (Pun or no pun, it's true both ways).

First: Some important information

This case has nothing to do with passing an argument to main() or not. Actually, as per the latest C standard, C11, for a hosted environment, the conforming signature of main() is int main(void) and following that, main(10); is wrong, altogether.

Now, coming to the actual problem here,

In the first case, change of i value happens after the call to main(), so in effect, the value of i never get changed because the control never reaches the statement which modifies i. Hence, it's an infinite loop, and because of the recursive call to main(), stack overflow happens.

In later case, i value gets updated before call to main(), so that value actually reflects. Thus, at some point (after 4 occurrences, actually), the if condition meets a FALSE condition and the recursive call ends and the stack unwinds.

Title: C program recursive call to main() with and without parameters


问:
PHP: switch() default for all?
I have this:

```<code>case true:

    echo '<textarea rows="2" cols="35" name="message_friend" id="message_friend"></textarea>';
    break;

    default:
    echo '<textarea rows="2" cols="35" name="message_friend" id="message_friend" readonly="readonly"></textarea>';
    break;
</code>```

I am trying to ONLY if it's true, then show normal else do READONLY.

The switch is checking from a function

```<code>switch( ( check_friend_state($showU["id"], 'friend') ) )
</code>```

And I tried to echo the function, and it returned err2 and not true, so why does it run true?

I also tried if/else

```<code>if(check_friend_state($showU["id"], 'friend') == true){

echo '<textarea rows="2" cols="35" name="message_friend" id="message_friend"></textarea>';
}else{
echo '<textarea rows="2" cols="35" name="message_friend" id="message_friend" readonly="readonly"></textarea>';
}
</code>```

But as said previously it returns "err2" and still it runs true?

My function at the return:

```<code>if($USER == $uID){ // not yourself
return "err1";
}elseif( $checkIsFriend->rowCount() == 1 ){  // already friends
return "err2";
}elseif( $checkAlready->rowCount() == 1 ){ // already send a request
return "err3";
}elseif( $checkBlock->rowCount() == 1 ){ // blocked
return "err4";
}else{
return true;
}
</code>```

答:
This is a modified version of @Webnet's answer.

```<code>echo '<textarea rows="2" cols="35" name="message_friend" id="message_friend"';
if(check_friend_state($showU["id"], 'friend') !== true) {
    echo 'readonly="readonly"';
}
echo '></textarea>';
</code>```

It will work for you because of the !== operator.

Side Note

Your function, check_friend_state is the root of the problem.  You need to restrict its return values to a single type.  If it only returned a boolean, you wouldn't have your current problem.

Rather than developing a single function to handle and return all possible values, you should break it up into multiple functions, each handling a single aspect of the logic.  For example:

```<code>echo '<textarea rows="2" cols="35" name="message_friend" id="message_friend"';
if(!is_friend($showU["id"])) {
    echo 'readonly="readonly"';
}
echo '></textarea>';
</code>```

In that fictional example, the is_friend function only returns a boolean (true/false).  You would have other functions that handle anything else that check_friend_state used to do.

Side note #2

Looking at your function, it seems as though you've halfway grokked the concept of throwing exceptions.  Try reading up here:  http://php.net/manual/en/language.exceptions.php

Title: PHP: switch() default for all?

Body:
I have this:

case true:

    echo '<textarea rows="2" cols="35" name="message_friend" id="message_friend"></textarea>';
    break;

    default:
    echo '<textarea rows="2" cols="35" name="message_friend" id="message_friend" readonly="readonly"></textarea>';
    break;

I am trying to ONLY if it's true, then show normal else do READONLY.

The switch is checking from a function

switch( ( check_friend_state($showU["id"], 'friend') ) )

And I tried to echo the function, and it returned err2 and not true, so why does it run true?

I also tried if/else

if(check_friend_state($showU["id"], 'friend') == true){

echo '<textarea rows="2" cols="35" name="message_friend" id="message_friend"></textarea>';
}else{
echo '<textarea rows="2" cols="35" name="message_friend" id="message_friend" readonly="readonly"></textarea>';
}

But as said previously it returns "err2" and still it runs true?

My function at the return:

if($USER == $uID){ // not yourself
return "err1";
}elseif( $checkIsFriend->rowCount() == 1 ){  // already friends
return "err2";
}elseif( $checkAlready->rowCount() == 1 ){ // already send a request
return "err3";
}elseif( $checkBlock->rowCount() == 1 ){ // blocked
return "err4";
}else{
return true;
}

Body:
This is a modified version of @Webnet's answer.

echo '<textarea rows="2" cols="35" name="message_friend" id="message_friend"';
if(check_friend_state($showU["id"], 'friend') !== true) {
    echo 'readonly="readonly"';
}
echo '></textarea>';

It will work for you because of the !== operator.

Side Note

Your function, check_friend_state is the root of the problem.  You need to restrict its return values to a single type.  If it only returned a boolean, you wouldn't have your current problem.

Rather than developing a single function to handle and return all possible values, you should break it up into multiple functions, each handling a single aspect of the logic.  For example:

echo '<textarea rows="2" cols="35" name="message_friend" id="message_friend"';
if(!is_friend($showU["id"])) {
    echo 'readonly="readonly"';
}
echo '></textarea>';

In that fictional example, the is_friend function only returns a boolean (true/false).  You would have other functions that handle anything else that check_friend_state used to do.

Side note #2

Looking at your function, it seems as though you've halfway grokked the concept of throwing exceptions.  Try reading up here:  http://php.net/manual/en/language.exceptions.php


问:
Lumen 5.4 Helper class not available globally
I have created Helper function in

lumen\app\Helpers\Helpers.php

and added

```<code><?php
if(!function_exists('config_path'))
{
        /**
        * Return the path to config files
        * @param null $path
        * @return string
        */
        function config_path($path=null)
        {
                return app()->getConfigurationPath(rtrim($path, ".php"));
        }
}
</code>```

in compoer.json

```<code>,
    "files": [
        "app/Helpers/Helpers.php"
    ],
</code>```

then ran

```<code>composer dump-autoload -o
composer dump-autoload
</code>```

after that if try to call in web.php

```<code>$app->get('/', function () use ($app) {

  echo config_path();

});
</code>```

Getting following error

Fatal error: Call to undefined function config_path() in
  D:\xampp\htdocs\lumen\routes\web.php on line 17

答:
Looks like web.php is executed before Helpers.php. The best thing you can do is to put any logic into the Controller, Models etc and keep routes only in web.php.

If you don't care about this, you can require() helpers file in index.php, but again, it's a bad practice.

Body:
I have created Helper function in

lumen\app\Helpers\Helpers.php

and added

<?php
if(!function_exists('config_path'))
{
        /**
        * Return the path to config files
        * @param null $path
        * @return string
        */
        function config_path($path=null)
        {
                return app()->getConfigurationPath(rtrim($path, ".php"));
        }
}

in compoer.json

,
    "files": [
        "app/Helpers/Helpers.php"
    ],

then ran

composer dump-autoload -o
composer dump-autoload

after that if try to call in web.php

$app->get('/', function () use ($app) {

  echo config_path();

});

Getting following error

Fatal error: Call to undefined function config_path() in
  D:\xampp\htdocs\lumen\routes\web.php on line 17


问:
how to fetch instagram followed_by count for other users
I want to fetch the instagram followers count for various users from my app using jquery / javascript.
I tried the below code but i see 404 error:

```<code>            var $url = 'https://api.instagram.com/v1/users/'+user_id+'/?access_token='+$access_token;
            $.ajax({
                method: "GET",
                url: $url,
                dataType: "jsonp",
                jsonp : "callback",
                success: function(data) {
                   console.log(data);
                }
            });
</code>```

My access token is created with scope public_content.

Apart from this I also tried fetching the page content as below without access token:

```<code>    $.ajax({
                url: 'https://www.instagram.com/'+user_id+'/?__a=1',
                type: 'GET',
                data: {},
                dataType: jsonp,
                success: function(data) {
                    console.log(data);
                }
            });
</code>```

But this throws CORS error.
Please help.

答: I dont know what the data of instagram api look like but if its related to CORS error, try put https://cors-anywhere.herokuapp.com before your url. This error appears because you are missing headers. You can try searching for CORS topic on SO if you like more information.</p>

Body:
I want to fetch the instagram followers count for various users from my app using jquery / javascript.
I tried the below code but i see 404 error:

            var $url = 'https://api.instagram.com/v1/users/'+user_id+'/?access_token='+$access_token;
            $.ajax({
                method: "GET",
                url: $url,
                dataType: "jsonp",
                jsonp : "callback",
                success: function(data) {
                   console.log(data);
                }
            });

My access token is created with scope public_content.

Apart from this I also tried fetching the page content as below without access token:

    $.ajax({
                url: 'https://www.instagram.com/'+user_id+'/?__a=1',
                type: 'GET',
                data: {},
                dataType: jsonp,
                success: function(data) {
                    console.log(data);
                }
            });

But this throws CORS error.
Please help.


问:
Guard against filtering an empty JS object
I have the following code:

```<code>for (var key in obj) {
  if (obj.hasOwnProperty(key)) {
    if (obj[key].id === foo.id) {
      // do something
    }
  }
}
</code>```

I'm checking whether the object is not empty before doing any functionality, because the array is populated later on user interaction.

For better readability, I want to do something like this:

```<code>const result = obj.filter((item) => item.id === foo.id)
return result[0]
</code>```

This, however, will produce an error: obj.filter is not a function since the object is empty when the page renders and is populated later.
Question is - how do I simplify this and at the same time guard against filtering the empty object in the most simple way?

EDIT: Adding sample data structure for obj

```<code>{
    0: { id: 2, name: 'John', category: 'Repair' },
    1: { id: 3, name: 'William', category: 'Maintenance' }
}
</code>```

答:
var obj = {
  "0": { id: 2, name: 'John', category: 'Repair' },
  "1": { id: 3, name: 'William', category: 'Maintenance' }
};

var keys = Object.keys(obj);

for (var i = 0; i < keys.length; i++) {
  var k = keys[i];
  if (obj.hasOwnProperty(k)) {
    console.log(obj[k].name + ' works in ' + obj[k].category);
  }
}```

Body:
I have the following code:

for (var key in obj) {
  if (obj.hasOwnProperty(key)) {
    if (obj[key].id === foo.id) {
      // do something
    }
  }
}

I'm checking whether the object is not empty before doing any functionality, because the array is populated later on user interaction.

For better readability, I want to do something like this:

const result = obj.filter((item) => item.id === foo.id)
return result[0]

This, however, will produce an error: obj.filter is not a function since the object is empty when the page renders and is populated later.
Question is - how do I simplify this and at the same time guard against filtering the empty object in the most simple way?

EDIT: Adding sample data structure for obj

{
    0: { id: 2, name: 'John', category: 'Repair' },
    1: { id: 3, name: 'William', category: 'Maintenance' }
}


Title: Squeezing spaces between columns in Unix shell

Body:
I want the spaces to be removed between two columns.
After running a sql query from shell, I'm getting the output as below:

23554402243                       0584940772;2TZ0584940772001U;
23554402272                       0423721840;7TT0423721840001B;
23554402303                       0110770863;BBTU500248822001Q;
23554402305                       02311301;BTB02311301001J;
23554402563                       0550503408;PPTU004984208001O;
23554402605                       0457553223;Q0T0457553223001I;
23554367602                       0454542427;TB8U501674990001V;
23554378584                       0383071261;HTHU500374797001Y;
23554404965                       059792244;ST3059792244005C;
23554405503                       0571632586;QTO0571632586001D;

But the desired output should be like below:

23554400043     0117601738;22TU003719388001V;
23554402883     0823973229;TTT0823973229001C;
23554402950     024071080;MNT024071080001D;
23554405827     0415260614;TL20415260614001R;
23554405828     08119270800;TL2U003010407001G;
23554406553     011306895;VBT011306895001E;
23554406557     054121509;TL2054121509001M;
23554406563     065069209;TL2065069209005M;
23554409085     0803434328;QTO0803434328001B;
23553396219     062004063;G6T062004063001C;

Remember, there should be only one tabspace between two columns in the desired output.

Body:
Easy to do using this awk:

awk -v OFS='\t' '{$1=$1} 1' file
23554402243 0584940772;2TZ0584940772001U;
23554402272 0423721840;7TT0423721840001B;
23554402303 0110770863;BBTU500248822001Q;
23554402305 02311301;BTB02311301001J;
23554402563 0550503408;PPTU004984208001O;
23554402605 0457553223;Q0T0457553223001I;
23554367602 0454542427;TB8U501674990001V;
23554378584 0383071261;HTHU500374797001Y;
23554404965 059792244;ST3059792244005C;
23554405503 0571632586;QTO0571632586001D;

Alternatively this tr will also work:

tr -s ' ' < file | tr ' ' '\t'

or this sed:

sed -i.bak $'s/ \{1,\}/\t/g' file


问:
ZF3 - composer require module -> module could not be initialised
I am working with the skeleton-application as a base, using the Vagrant / Composer setup. After the initial install I realised I would need the LDAP module. I then ran composer require zendframework/zend-ldap which ran successfully and I have located the files in ~/vendor/zendframework/zend-ldap.

The issue is when I add 'Zend\Ldap' to my ~/config/modules.config.php I encounter the following error:

```<code>Fatal error: Uncaught Zend\ModuleManager\Exception\RuntimeException: Module (Zend\Ldap) could not be initialized. in /var/www/vendor/zendframework/zend-modulemanager/src/ModuleManager.php:203 Stack trace: #0 /var/www/vendor/zendframework/zend-modulemanager/src/ModuleManager.php(175): Zend\ModuleManager\ModuleManager->loadModuleByName(Object(Zend\ModuleManager\ModuleEvent))
#1 /var/www/vendor/zendframework/zend-modulemanager/src/ModuleManager.php(97): Zend\ModuleManager\ModuleManager->loadModule('Zend\\Ldap') #2 /var/www/vendor/zendframework/zend-eventmanager/src/EventManager.php(322): Zend\ModuleManager\ModuleManager->onLoadModules(Object(Zend\ModuleManager\ModuleEvent))
#3 /var/www/vendor/zendframework/zend-eventmanager/src/EventManager.php(171): Zend\EventManager\EventManager->triggerListeners(Object(Zend\ModuleManager\ModuleEvent))
#4 /var/www/vendor/zendframework/zend-modulemanager/src/ModuleManager.php(120): Zend\EventManager\EventManager->triggerEvent(Object(Zend\ModuleManager\ModuleEvent))
#5 /var/www/vendor/zendfr in /var/www/vendor/zendframework/zend-modulemanager/src/ModuleManager.php on line 203
</code>```

The ~/config/modules.config.php file:

```<code>/**
 * List of enabled modules for this application.
 *
 * This should be an array of module namespaces used in the application.
 */
return [
    'Zend\Session',
    'Zend\Mvc\Plugin\Prg',
    'Zend\Mvc\Plugin\Identity',
    'Zend\Mvc\Plugin\FlashMessenger',
    'Zend\Mvc\Plugin\FilePrg',
    'Zend\Log',
    'Zend\Form',
    'Zend\Db',
    'Zend\Router',
    'Zend\Validator',
    'Zend\Ldap',    // All is well if this is commented out
    'Application',

];
</code>```

and the ~/config/application.config.php file:

```<code>/**
 * If you need an environment-specific system or application configuration,
 * there is an example in the documentation
 * @see https://docs.zendframework.com/tutorials/advanced-config/#environment-specific-system-configuration
 * @see https://docs.zendframework.com/tutorials/advanced-config/#environment-specific-application-configuration
 */
return [
    // Retrieve list of modules used in this application.
    'modules' => require __DIR__ . '/modules.config.php',

    // These are various options for the listeners attached to the ModuleManager
    'module_listener_options' => [
        // This should be an array of paths in which modules reside.
        // If a string key is provided, the listener will consider that a module
        // namespace, the value of that key the specific path to that module's
        // Module class.
        'module_paths' => [
            './module',
            './vendor',
        ],

        // An array of paths from which to glob configuration files after
        // modules are loaded. These effectively override configuration
        // provided by modules themselves. Paths may use GLOB_BRACE notation.
        'config_glob_paths' => [
            realpath(__DIR__) . '/autoload/{{,*.}global,{,*.}local}.php',
        ],

        // Whether or not to enable a configuration cache.
        // If enabled, the merged configuration will be cached and used in
        // subsequent requests.
        'config_cache_enabled' => true,

        // The key used to create the configuration cache file name.
        'config_cache_key' => 'application.config.cache',

        // Whether or not to enable a module class map cache.
        // If enabled, creates a module class map cache which will be used
        // by in future requests, to reduce the autoloading process.
        'module_map_cache_enabled' => true,

        // The key used to create the class map cache file name.
        'module_map_cache_key' => 'application.module.cache',

        // The path in which to cache merged configuration.
        'cache_dir' => 'data/cache/',

        // Whether or not to enable modules dependency checking.
        // Enabled by default, prevents usage of modules that depend on other modules
        // that weren't loaded.
        // 'check_dependencies' => true,
    ],

    // Used to create an own service manager. May contain one or more child arrays.
    // 'service_listener_options' => [
    //     [
    //         'service_manager' => $stringServiceManagerName,
    //         'config_key'      => $stringConfigKey,
    //         'interface'       => $stringOptionalInterface,
    //         'method'          => $stringRequiredMethodName,
    //     ],
    // ],

    // Initial configuration with which to seed the ServiceManager.
    // Should be compatible with Zend\ServiceManager\Config.
    // 'service_manager' => [],
];
</code>```

I have tried removing cache folder, running composer update, restarting Vagrant, adding the full path to the 'modules_path' array in application.config.php but it is always the same error. Interestingly I run into the same issue with 'Zend\View' that was included from the install, but a module such as 'Zend\Session' can be added to the modules.config.php file with no issues (They are all located in the vendor/zendframework directory)

Can anyone point me in the right direction to resolve this issue?

答:
Is zend-ldap included in your project? If not Run in your terminal

```<code>composer require zendframework/zend-ldap
</code>```

And you can disable caching in development process by enabling development mode: composer development-enable

Body:
I am working with the skeleton-application as a base, using the Vagrant / Composer setup. After the initial install I realised I would need the LDAP module. I then ran composer require zendframework/zend-ldap which ran successfully and I have located the files in ~/vendor/zendframework/zend-ldap.

The issue is when I add 'Zend\Ldap' to my ~/config/modules.config.php I encounter the following error:

Fatal error: Uncaught Zend\ModuleManager\Exception\RuntimeException: Module (Zend\Ldap) could not be initialized. in /var/www/vendor/zendframework/zend-modulemanager/src/ModuleManager.php:203 Stack trace: #0 /var/www/vendor/zendframework/zend-modulemanager/src/ModuleManager.php(175): Zend\ModuleManager\ModuleManager->loadModuleByName(Object(Zend\ModuleManager\ModuleEvent))
#1 /var/www/vendor/zendframework/zend-modulemanager/src/ModuleManager.php(97): Zend\ModuleManager\ModuleManager->loadModule('Zend\\Ldap') #2 /var/www/vendor/zendframework/zend-eventmanager/src/EventManager.php(322): Zend\ModuleManager\ModuleManager->onLoadModules(Object(Zend\ModuleManager\ModuleEvent))
#3 /var/www/vendor/zendframework/zend-eventmanager/src/EventManager.php(171): Zend\EventManager\EventManager->triggerListeners(Object(Zend\ModuleManager\ModuleEvent))
#4 /var/www/vendor/zendframework/zend-modulemanager/src/ModuleManager.php(120): Zend\EventManager\EventManager->triggerEvent(Object(Zend\ModuleManager\ModuleEvent))
#5 /var/www/vendor/zendfr in /var/www/vendor/zendframework/zend-modulemanager/src/ModuleManager.php on line 203

The ~/config/modules.config.php file:

/**
 * List of enabled modules for this application.
 *
 * This should be an array of module namespaces used in the application.
 */
return [
    'Zend\Session',
    'Zend\Mvc\Plugin\Prg',
    'Zend\Mvc\Plugin\Identity',
    'Zend\Mvc\Plugin\FlashMessenger',
    'Zend\Mvc\Plugin\FilePrg',
    'Zend\Log',
    'Zend\Form',
    'Zend\Db',
    'Zend\Router',
    'Zend\Validator',
    'Zend\Ldap',    // All is well if this is commented out
    'Application',

];

and the ~/config/application.config.php file:

/**
 * If you need an environment-specific system or application configuration,
 * there is an example in the documentation
 * @see https://docs.zendframework.com/tutorials/advanced-config/#environment-specific-system-configuration
 * @see https://docs.zendframework.com/tutorials/advanced-config/#environment-specific-application-configuration
 */
return [
    // Retrieve list of modules used in this application.
    'modules' => require __DIR__ . '/modules.config.php',

    // These are various options for the listeners attached to the ModuleManager
    'module_listener_options' => [
        // This should be an array of paths in which modules reside.
        // If a string key is provided, the listener will consider that a module
        // namespace, the value of that key the specific path to that module's
        // Module class.
        'module_paths' => [
            './module',
            './vendor',
        ],

        // An array of paths from which to glob configuration files after
        // modules are loaded. These effectively override configuration
        // provided by modules themselves. Paths may use GLOB_BRACE notation.
        'config_glob_paths' => [
            realpath(__DIR__) . '/autoload/{{,*.}global,{,*.}local}.php',
        ],

        // Whether or not to enable a configuration cache.
        // If enabled, the merged configuration will be cached and used in
        // subsequent requests.
        'config_cache_enabled' => true,

        // The key used to create the configuration cache file name.
        'config_cache_key' => 'application.config.cache',

        // Whether or not to enable a module class map cache.
        // If enabled, creates a module class map cache which will be used
        // by in future requests, to reduce the autoloading process.
        'module_map_cache_enabled' => true,

        // The key used to create the class map cache file name.
        'module_map_cache_key' => 'application.module.cache',

        // The path in which to cache merged configuration.
        'cache_dir' => 'data/cache/',

        // Whether or not to enable modules dependency checking.
        // Enabled by default, prevents usage of modules that depend on other modules
        // that weren't loaded.
        // 'check_dependencies' => true,
    ],

    // Used to create an own service manager. May contain one or more child arrays.
    // 'service_listener_options' => [
    //     [
    //         'service_manager' => $stringServiceManagerName,
    //         'config_key'      => $stringConfigKey,
    //         'interface'       => $stringOptionalInterface,
    //         'method'          => $stringRequiredMethodName,
    //     ],
    // ],

    // Initial configuration with which to seed the ServiceManager.
    // Should be compatible with Zend\ServiceManager\Config.
    // 'service_manager' => [],
];

I have tried removing cache folder, running composer update, restarting Vagrant, adding the full path to the 'modules_path' array in application.config.php but it is always the same error. Interestingly I run into the same issue with 'Zend\View' that was included from the install, but a module such as 'Zend\Session' can be added to the modules.config.php file with no issues (They are all located in the vendor/zendframework directory)

Can anyone point me in the right direction to resolve this issue?

Body:
Is zend-ldap included in your project? If not Run in your terminal

composer require zendframework/zend-ldap

And you can disable caching in development process by enabling development mode: composer development-enable


问:
Finding common values from Arraylist in Java?
I have 15 tables in database. All tables have one common row in it. For example every table have entry for "Robin_Ghosh", at least 13 tables have this value. Actually I have connected this with jframe in java and I want that user can only select 5 random tables and result of these 5 selected tables should come into jframe. From there every table should get loaded into array and then I will find out common values from this array using loop.

Anyone can help me to get out of this problem. Thanks in advance for your help. I am badly needed help of yours, because I am running out of time. I have to submit this into my collage.

答:
You can use retainAll in collection framework</p>

```<code>public static void main(String[] args) {
        List<Integer> list1 = new ArrayList();
        list1.add(1);
        list1.add(3);
        list1.add(5);
        List<Integer> list2 = new ArrayList();
        list2.add(1);
        list2.add(6);
        list2.add(7);
        list2.add(9);
        list2.add(3);
        List<Integer> list3 = new ArrayList();
        list3.add(1);
        list3.add(3);
        list3.add(10);
        list3.add(11);

        List<Integer> addresses = new ArrayList();
        addresses.addAll(list1);
        addresses.retainAll(list2);
        addresses.retainAll(list3);
       System.out.println(addresses);
    }
</code>```

Body:
You can use retainAll in collection framework

public static void main(String[] args) {
        List<Integer> list1 = new ArrayList();
        list1.add(1);
        list1.add(3);
        list1.add(5);
        List<Integer> list2 = new ArrayList();
        list2.add(1);
        list2.add(6);
        list2.add(7);
        list2.add(9);
        list2.add(3);
        List<Integer> list3 = new ArrayList();
        list3.add(1);
        list3.add(3);
        list3.add(10);
        list3.add(11);

        List<Integer> addresses = new ArrayList();
        addresses.addAll(list1);
        addresses.retainAll(list2);
        addresses.retainAll(list3);
       System.out.println(addresses);
    }


问:
Can I configure Visual Studio NOT to change StartUp Project every time I open a file from one of the projects?
Let's say that there is a solution that contains two projects (Project1 and Project2).

Project1 is set as a StartUp Project (its name is displayed in a bold font). I double-click some file in Project2 to open it. The file opens, but something else happens too - Project2 gets set as a StartUp Project.

I tried to find an option in configuration to change it, but I found none.

Can this feature (though it's more like a bug to me) be disabled?

答: The way to select a startup project is described in Sara Ford's blog "Visual Studio Tip of the Day" (highly recommended). She has a post there about setting up StartUp projects. Essentially there are 2 ways, the easiest one being right-clicking on the desired project, and choosing "Set As StartUp Project". That prevents other projects from becoming the StartUp project, even if you click on one their files. </p>

LastEditorDisplayName: Keith

LastEditorDisplayName: ShuggyCoUk


问:
How do you generate a random number in C#?
I would like to generate a random floating point number between 2 values.  What is the best way to do this in C#?</p>

答:
How random?  If you can deal with pseudo-random then simply:

```<code>Random randNum = new Random();
randNum. NextDouble(Min, Max);
</code>```

If you want a "better" random number, then you probably should look at the Mersenne Twister algorithm.  Plenty of people hav already implemented it for you though

OwnerDisplayName: Lane

LastEditorDisplayName: MrValdez

Body:
How random?  If you can deal with pseudo-random then simply:

Random randNum = new Random();
randNum. NextDouble(Min, Max);

If you want a "better" random number, then you probably should look at the Mersenne Twister algorithm.  Plenty of people hav already implemented it for you though

OwnerDisplayName: enigmatic

LastEditorDisplayName: enigmatic


问:
Prevent a user from closing a browser window using "X"?
Can I tell, using javascript, whether a user has clicked on the "X" icon on a browser dialog, or the "OK"/"Cancel" buttons? I have code I need to run when the window closes, but it will only run when OK or Cancel are clicked.

I currently capture the onunload event of the window. How can i accomplish this?

```<code>window.onunload = function() { alert("unloading"); }
</code>```

答:
To the best of my knowledge, you can't detect whether the user closed the dialog by clicking the Cancel button or the [x] button, since neither are exposed to you beyond returning the result of the action (e.g., confirm() as true/false).

You can hook into the document.onbeforeunload event to perform whatever cleanup action you require; I've done so myself by sending an asynchronous XMLHTTP request to the server to make sure the user's session gets cleaned up properly.

OwnerDisplayName: Pwninstein

Body:
Can I tell, using javascript, whether a user has clicked on the "X" icon on a browser dialog, or the "OK"/"Cancel" buttons? I have code I need to run when the window closes, but it will only run when OK or Cancel are clicked.

I currently capture the onunload event of the window. How can i accomplish this?

window.onunload = function() { alert("unloading"); }

OwnerDisplayName: Christian Nunciato


问:
How to check if PathVariable in the URI in Spring MVC's request mapping?
In my controller there is such code.

```<code>@RequestMapping(value = "/{scene}/{function}/**")
    public void processProxyCall(@PathVariable("scene") final String scene, @PathVariable("function") final String function,
        final HttpServletRequest request,final HttpServletResponse response) throws IOException {
    ...
}
</code>```

In testing phase, where the possible values of {scene} is "sit" or "uat". And there are some additional logic to handle this variable in the phase.
So it's well fit for such URI "/sit/student/add". The scene is sit, and the function is student.

But in production there isn't any "sit" nor "uat" anymore , the URI in this case will be "/student/add". There is no need to handle the scene variable either.

The question is how to do some checking against the PathVariable "scene" in above code snippet. If production case the scene will be automatically mapped to "student" which is terribly wrong.

I was trying to add another RequestMapping as below to handle the production case, and remain the testing one no change. But got 404...

```<code>@RequestMapping(value = "/{function}/**")
    public void processProxyCall(@PathVariable("function") final String function, final HttpServletRequest request,
            final HttpServletResponse response) throws IOException {
}
</code>```

答:
```<code>@RequestMapping(value = {"/{scene}/{function}/**", "/{function}/**"})
public void processProxyCall(@PathVariable(value="scene", required=false) final String scene, @PathVariable("function") final String function,
        final HttpServletRequest request,final HttpServletResponse response) throws IOException {
    ...
}
</code>```

Define multiple mappings and make scene path variable required=false

UPDATE:

```<code>@RequestMapping(value = "/{scene}/{function}/**")
public void processProxyCall(@PathVariable(value="scene", required=false) final String scene, @PathVariable("function") final String function,
        final HttpServletRequest request,final HttpServletResponse response) throws IOException {
    ...
}

@RequestMapping(value = "/{function}/**")
public void processProxyCallShort(@PathVariable(value="scene", required=false) final String scene, @PathVariable("function") final String function,
        final HttpServletRequest request,final HttpServletResponse response) throws IOException {
    processProxyCall(null, function, request, response);
}
</code>```

Body:
In my controller there is such code.

@RequestMapping(value = "/{scene}/{function}/**")
    public void processProxyCall(@PathVariable("scene") final String scene, @PathVariable("function") final String function,
        final HttpServletRequest request,final HttpServletResponse response) throws IOException {
    ...
}

In testing phase, where the possible values of {scene} is "sit" or "uat". And there are some additional logic to handle this variable in the phase.
So it's well fit for such URI "/sit/student/add". The scene is sit, and the function is student.

But in production there isn't any "sit" nor "uat" anymore , the URI in this case will be "/student/add". There is no need to handle the scene variable either.

The question is how to do some checking against the PathVariable "scene" in above code snippet. If production case the scene will be automatically mapped to "student" which is terribly wrong.

I was trying to add another RequestMapping as below to handle the production case, and remain the testing one no change. But got 404...

@RequestMapping(value = "/{function}/**")
    public void processProxyCall(@PathVariable("function") final String function, final HttpServletRequest request,
            final HttpServletResponse response) throws IOException {
}

Body:
@RequestMapping(value = {"/{scene}/{function}/**", "/{function}/**"})
public void processProxyCall(@PathVariable(value="scene", required=false) final String scene, @PathVariable("function") final String function,
        final HttpServletRequest request,final HttpServletResponse response) throws IOException {
    ...
}

Define multiple mappings and make scene path variable required=false

UPDATE:

@RequestMapping(value = "/{scene}/{function}/**")
public void processProxyCall(@PathVariable(value="scene", required=false) final String scene, @PathVariable("function") final String function,
        final HttpServletRequest request,final HttpServletResponse response) throws IOException {
    ...
}

@RequestMapping(value = "/{function}/**")
public void processProxyCallShort(@PathVariable(value="scene", required=false) final String scene, @PathVariable("function") final String function,
        final HttpServletRequest request,final HttpServletResponse response) throws IOException {
    processProxyCall(null, function, request, response);
}


问:
How to rescale multiple attributes at the same time in R
I have a data set that contains multiple attributes with integer values from 1 to 5 and I would like to rescale these attributes so that their values range from -1 to 1. My current code that I have is

```<code>    newdata$Rats = rescale(newdata$Rats, to = c(-1,1), from=c(1,5))
</code>```

Where newdata is my dataset and Rats is one of my attributes. If I only had a few attributes to change that would be fine, but I have about 30 or so to change. Is there a way to use a for loop to do this or use the select function that R has or possibly another way?

答:
Use lapply():

```<code>newdata[, c(1:30)] <- lapply(newdata[, c(1:30)],
                             function(x) rescale(x, to = c(-1, 1), from = c(1, 5)))
</code>```

For the c(1:30), insert a vector of either positions of your variables within your dataframe, or a vector of the names of your variables as strings.

Body:
I have a data set that contains multiple attributes with integer values from 1 to 5 and I would like to rescale these attributes so that their values range from -1 to 1. My current code that I have is

    newdata$Rats = rescale(newdata$Rats, to = c(-1,1), from=c(1,5))

Where newdata is my dataset and Rats is one of my attributes. If I only had a few attributes to change that would be fine, but I have about 30 or so to change. Is there a way to use a for loop to do this or use the select function that R has or possibly another way?

Body:
Use lapply():

newdata[, c(1:30)] <- lapply(newdata[, c(1:30)],
                             function(x) rescale(x, to = c(-1, 1), from = c(1, 5)))

For the c(1:30), insert a vector of either positions of your variables within your dataframe, or a vector of the names of your variables as strings.


问:
global tool configurations in jenkins through cli?
Is there a way to add global tool configurations for artifactory and aws in jenkins through cli?

I'm trying to write chef cookbook for automating creation of Jenkins job, but I don't know how to add credentials for tools.

答:
Your question is twofold.

Credentials

The Jenkins chef cookbook offers a jenkins_credentials resource, which allows you to pipe credentials (using Jenkins API internally) into your Jenkins instance.

Global Tool Configuration

You can use the jenkins_script resource of the same cookbook to execute any Groovy script. This allows you to configure your Jenkins instance. You now just have to figure out exactly, what the code is to, e.g., select the previously defined credentials. But the code looks similarly to the example given in the cookbook's README.


问:
After dismissing the alert appium is no longer detecting any element on the screen
Basically everything works until a notification is displayed on screen. After i dismiss the alert i, appium is no longer detecting any of my buttons, fields, etc. The only things that works is if i put the app in background and resume it. After resume everything works. (i`m using Appium 1.6.4, with Android 7.0).

Any hint here?

答:
It is known issue in appium project.

Workaround that I use:

get coordinates (x, y) of any element on screen before opening dialog

interact with dialog (e.g. select elements, close etc.)

tap by coordinates (x, y) after closing dialog:

new TouchAction(driver).tap(x, y).perform();

Only after clicking on screen by coordinates it will find elements.