问:
Callback is null on delete method
I'm trying to send a string message from my spring back-end to my angular front-end when a object's been deleted.

```<code>@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public @ResponseBody String deleteMovie(@PathVariable("id") Integer id){
    return "String";
}
</code>```

This code does nothing but return a string.

In the angular app I have this function in the controller:

```<code>deleteMovie(id: number): void {
  this._dataService.deleteMovie(id)
  .subscribe((data) => {
    console.log(data);
    this.movies = this.movies.filter(movie => movie.id !== id);
  },
  error => () => {
      'something went wrong';
  },
  () => {
    // console.log(this.movies);
  });
}
</code>```

And this is the service:

```<code>public deleteMovie(id: number) {
    return this.http.get('/api/movies/' + id, {headers: this.getToken()});
}
</code>```

When I run the code the console logs null. When I check the network tab I can see that the delete return doesn't have a request payload so I think that's why the console logs null.

// why is the question getting downvoted? :/

答:
Did the deleteMovie in spring is hitting? Put break point and check.  If yes then you should be use <code>.map();</code> because of subscription. </p>

```<code> return this.http.get('/api/movies/' + id)
            .map((res: Any) => {
                return res;
            })
            .catch(error => {
                return Observable.throw(error);
            });
</code>```

Title: Callback is null on delete method

Body:
I'm trying to send a string message from my spring back-end to my angular front-end when a object's been deleted.

@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public @ResponseBody String deleteMovie(@PathVariable("id") Integer id){
    return "String";
}

This code does nothing but return a string.

In the angular app I have this function in the controller:

deleteMovie(id: number): void {
  this._dataService.deleteMovie(id)
  .subscribe((data) => {
    console.log(data);
    this.movies = this.movies.filter(movie => movie.id !== id);
  },
  error => () => {
      'something went wrong';
  },
  () => {
    // console.log(this.movies);
  });
}

And this is the service:

public deleteMovie(id: number) {
    return this.http.get('/api/movies/' + id, {headers: this.getToken()});
}

When I run the code the console logs null. When I check the network tab I can see that the delete return doesn't have a request payload so I think that's why the console logs null.

// why is the question getting downvoted? :/

Body:
Did the deleteMovie in spring is hitting? Put break point and check.  If yes then you should be use .map(); because of subscription.

 return this.http.get('/api/movies/' + id)
            .map((res: Any) => {
                return res;
            })
            .catch(error => {
                return Observable.throw(error);
            });


来源: stackexchange

问:
Running python in php for image processing

hi everyone
I want to run a python script through php in which i've to do image processing and update a database and then use that database in same php program.
Is it feasible ?
If yes then how ?
I am a beginner so apology if the question isn't up to the mark.
Please help me making my first project :)

答:
I've used php to call python machine learning script.Try this

Example for Ubuntu

```<code>$values=shell_exec('/usr/bin/python two.py '.$ing.'');
</code>```

Example for Windows

```<code>$values=shell_exec('C:\Python27\python two.py '.$ing.'');
</code>```

$ing is the variable passed to the script. Remember to give the absolute path of python. It was pretty feasible for me. But performance mostly depends on your python script as the php just executes the python code

ContentLicense: CC BY-SA 3.0

Body:
I've used php to call python machine learning script.Try this

Example for Ubuntu

$values=shell_exec('/usr/bin/python two.py '.$ing.'');

Example for Windows

$values=shell_exec('C:\Python27\python two.py '.$ing.'');

$ing is the variable passed to the script. Remember to give the absolute path of python. It was pretty feasible for me. But performance mostly depends on your python script as the php just executes the python code


问:
How to integrate Skype for business functionality in ASP.NET MVC
i have a requirement from my client that we need to add an option like Skype for business, and this conferencing info is sent automatically if they have a static url for conferences or phone information.  The end user could always update meeting with Skype for business info.

i am quite new to sdks Microsoft offers for this, Can anyone suggest example code samples to achieve it

Thanks in advance!

答:
Buy Office 365 Yearly Subscription , Create an Account for you
Link : https://products.office.com/en-us/business/office-365-business-premium

Setup your Domain and Users
Link:https://support.office.com/en-us/article/Add-a-domain-and-users-to-Office-365-6383f56d-3d09-4dcb-9b41-b5f5a5efd611?ui=en-US&rs=en-US&ad=US
3.Install Skype in your Device , login with mentioned credentials and can chat with other users

Ref Link : https://support.office.com/en-us/article/Set-up-Skype-for-Business-Online-40296968-e779-4259-980b-c2de1c044c6e


问:
Laravel Echo error handling (with Pusher)
Is there any guide about this topic? I have read the pusher documentation and it seems fairly easy to manage a disconnect with a code similar to the following:

```<code>pusher.connection.bind('disconnected', function() {
    // Do Something
})
</code>```

I'm not sure how to integrate it with Echo, since my code is as follows:

```<code>window.EchoConnection = new Echo({
    broadcaster: 'pusher',
    key: window.EchoKey,
    cluster: 'eu',
    encrypted: true
});
</code>```

EDIT: in order to check a disconnect event, run window.EchoConnection.connector.pusher.connection.disconnect() in your console

答:
I haven't tried it yet, but according to the github repo this should work for pusher:

window.EchoConnection is an Echo Object. When you create a new pusher instance with echo, the connector variable will be a PusherConnector:

```<code>if (this.options.broadcaster == 'pusher') {
   this.connector = new PusherConnector(this.options);
}
</code>```

Over this variable you can find the Pusher instance that is created:

```<code>connect(): void {
    this.pusher = new Pusher(this.options.key, this.options);
}
</code>```

The theoretical solution for binding events to the pusher would be:

```<code>window.EchoConnection.connector.pusher.connection.bind('disconnected', function() {
    // Do Something
})
</code>```

Body:
Is there any guide about this topic? I have read the pusher documentation and it seems fairly easy to manage a disconnect with a code similar to the following:

pusher.connection.bind('disconnected', function() {
    // Do Something
})

I'm not sure how to integrate it with Echo, since my code is as follows:

window.EchoConnection = new Echo({
    broadcaster: 'pusher',
    key: window.EchoKey,
    cluster: 'eu',
    encrypted: true
});

EDIT: in order to check a disconnect event, run window.EchoConnection.connector.pusher.connection.disconnect() in your console

Body:
I haven't tried it yet, but according to the github repo this should work for pusher:

window.EchoConnection is an Echo Object. When you create a new pusher instance with echo, the connector variable will be a PusherConnector:

if (this.options.broadcaster == 'pusher') {
   this.connector = new PusherConnector(this.options);
}

Over this variable you can find the Pusher instance that is created:

connect(): void {
    this.pusher = new Pusher(this.options.key, this.options);
}

The theoretical solution for binding events to the pusher would be:

window.EchoConnection.connector.pusher.connection.bind('disconnected', function() {
    // Do Something
})


问:
SharedPreferences & variables swap
Basically I'm getting an int and a String everyday, that I save into SharedPreferences

What I want is those variables to change their values on each new day, passing from CurrentDay > Day+1 > Day+2 > Day+3 etc... and I need to save them.

For instance, let's say today's color is RED

```<code>// Not actual coding
DAY            -         STATE
Today : Red > 0 > 0 > 0
Tomorrow : NewColor1 > Red > 0 > 0
2 days later : NewColor2 > NewColor1 > Red > 0
3 days later : NewColor3 > NewColor2 > NewColor1 > Red
4 days later : NewColor4 > NewColor3 > NewColor2 > NewColor1 (Red is gone, overwritten by NewColor1)
</code>```

For example:

```<code>SharedPreferences mPreferences;

private String mTextA, mTextB, mTextC;
private int mColor1, mColor2, mColor3;

private String mCurrentText, mYesterdayText, mTwoDaysAgoText, mThreeDaysAgoText;
private int mCurrentColor, mYesterdayColor, mTwoDaysAgoColor, mThreeDaysAgoColor;

//String keys for SharedPreferences storage (int values)
private static final String CURRENT_COLOR = "CURRENT_COLOR";
private static final String YESTERDAY_COLOR = "YESTERDAY_COLOR";
private static final String TWO_DAYS_AGO__COLOR = "TWO_DAYS_AGO_COLOR";
private static final String THREE_DAYS_AGO_COLOR = "THREE_DAYS_AGO_COLOR";

//String keys for SharedPreferences storage (String values)
private static final String CURRENT_TEXT = "CURRENT_TEXT";
private static final String YESTERDAY_TEXT = "YESTERDAY_TEXT";
private static final String TWO_DAYS_AGO_TEXT = "TWO_DAYS_AGO_TEXT";
private static final String THREE_DAYS_AGO_TEXT = "THREE_DAYS_AGO_TEXT";

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

mPreferences = getPreferences(MODE_PRIVATE);
mPreferences.edit().putInt(CURRENT_COLOR, mCurrentColor).apply();
mPreferences.edit().putInt(CURRENT_TEXT, mCurrentText).apply();

// This is where I'm having troubles with the logic

     if (newday == true) {

            // Day 3
            mThreeDaysAgoColor = getPreferences(MODE_PRIVATE).getInt(TWO_DAYS_AGO_COLOR, 0);
            mThreeDaysAgoText = getPreferences(MODE_PRIVATE).getString(TWO_DAYS_AGO_TEXT, null);

            // Day 2
            mTwoDaysAgoColor = getPreferences(MODE_PRIVATE).getInt(YESTERDAY_COLOR, 0);
            mTwoDaysAgoText = getPreferences(MODE_PRIVATE).getString(YESTERDAY_TEXT, null);

            // Yesterday
            mCurrentColor = getPreferences(MODE_PRIVATE).getInt(CURRENT_COLOR, 0);
            mCurrentText = getPreferences(MODE_PRIVATE).getString(CURRENT_TEXT, null);

            mPreferences.edit().putInt(YESTERDAY_COLOR, mYesterdayColor).apply();
            mPreferences.edit().putInt(TWO_DAYS_AGO_COLOR, m2DaysAgoColor).apply();
            mPreferences.edit().putInt(THREE_DAYS_AGO_COLOR, m3DaysAgoColor).apply();

            mPreferences.edit().putString(YESTERDAY_TEXT, mYesterdayText).apply();
            mPreferences.edit().putString(TWO_DAYS_AGO_TEXT, m2DaysAgoText).apply();
            mPreferences.edit().putString(THREE_DAYS_AGO_TEXT, m3DaysAgoText).apply();
</code>```

To clarify:

mCurrentText can be mTextA, mTextB or mTextC

mCurrentColor can be mColor1, mColor2, or mColor3

Whenever my app detects a new day >

mCurrentText is saved as mYesterdayText

mCurrentColor is saved as mYesterdayColor

then it becomes Day+2, Day+3 etc, everything moves from one row, until Day+4 when Day+3 gets overwritten.

As a final result, I want to be able to read & save the values of mYesterdayText/mYesterdayColor, mTwoDaysAgoText/mTwoDaysAgoColor & mThreeDaysAgoText/mThreeDaysAgoColor for each new day.

I don't know if I'm going the wrong way or not. Please I need some help, I'm a newbie :(

答:
I get your problem, you want to shift the values of colors:

```<code>Today's launch : Red > 0 > 0 > 0
Tomorrow's launch : NewColor1 > Red > 0 > 0
2 days later's launch : NewColor2 > NewColor1 > Red > 0
3 days later's launch : NewColor3 > NewColor2 > NewColor1 > Red
4 days later's launch : NewColor4 > NewColor3 > NewColor2 > NewColor1 (Red is gone, overwritten by NewColor1)
</code>```

For this, you don't need to change the mCurrentText at all.
Have the following variables in shared pref (explaining just for TEXT):

```<code>CURRENT_TEXT, YESTERDAY_TEXT, TWO_DAYS_AGO_TEXT, THREE_DAYS_AGO_TEXT
</code>```

initialize each with empty or default values you want.

Now whenever theres a new day, you just need to overwite the values as follows:

```<code>putInt(THREE_DAYS_AGO_TEXT, {get value from shared pref of TWO_DAYS_AGO_TEXT})
putInt(TWO_DAYS_AGO_TEXT, {get value from shared pref of YESTERDAY_TEXT})
putInt(YESTERDAY_TEXT, {get value from shared pref of CURRENT_TEXT})
putInt(CURRENT_TEXT, {get value of new text for today})
</code>```

...and you will have the desired output.

Title: SharedPreferences & variables swap

Body:
Basically I'm getting an int and a String everyday, that I save into SharedPreferences

What I want is those variables to change their values on each new day, passing from CurrentDay > Day+1 > Day+2 > Day+3 etc... and I need to save them.

For instance, let's say today's color is RED

// Not actual coding
DAY            -         STATE
Today : Red > 0 > 0 > 0
Tomorrow : NewColor1 > Red > 0 > 0
2 days later : NewColor2 > NewColor1 > Red > 0
3 days later : NewColor3 > NewColor2 > NewColor1 > Red
4 days later : NewColor4 > NewColor3 > NewColor2 > NewColor1 (Red is gone, overwritten by NewColor1)

For example:

SharedPreferences mPreferences;

private String mTextA, mTextB, mTextC;
private int mColor1, mColor2, mColor3;

private String mCurrentText, mYesterdayText, mTwoDaysAgoText, mThreeDaysAgoText;
private int mCurrentColor, mYesterdayColor, mTwoDaysAgoColor, mThreeDaysAgoColor;

//String keys for SharedPreferences storage (int values)
private static final String CURRENT_COLOR = "CURRENT_COLOR";
private static final String YESTERDAY_COLOR = "YESTERDAY_COLOR";
private static final String TWO_DAYS_AGO__COLOR = "TWO_DAYS_AGO_COLOR";
private static final String THREE_DAYS_AGO_COLOR = "THREE_DAYS_AGO_COLOR";

//String keys for SharedPreferences storage (String values)
private static final String CURRENT_TEXT = "CURRENT_TEXT";
private static final String YESTERDAY_TEXT = "YESTERDAY_TEXT";
private static final String TWO_DAYS_AGO_TEXT = "TWO_DAYS_AGO_TEXT";
private static final String THREE_DAYS_AGO_TEXT = "THREE_DAYS_AGO_TEXT";

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

mPreferences = getPreferences(MODE_PRIVATE);
mPreferences.edit().putInt(CURRENT_COLOR, mCurrentColor).apply();
mPreferences.edit().putInt(CURRENT_TEXT, mCurrentText).apply();

// This is where I'm having troubles with the logic

     if (newday == true) {

            // Day 3
            mThreeDaysAgoColor = getPreferences(MODE_PRIVATE).getInt(TWO_DAYS_AGO_COLOR, 0);
            mThreeDaysAgoText = getPreferences(MODE_PRIVATE).getString(TWO_DAYS_AGO_TEXT, null);

            // Day 2
            mTwoDaysAgoColor = getPreferences(MODE_PRIVATE).getInt(YESTERDAY_COLOR, 0);
            mTwoDaysAgoText = getPreferences(MODE_PRIVATE).getString(YESTERDAY_TEXT, null);

            // Yesterday
            mCurrentColor = getPreferences(MODE_PRIVATE).getInt(CURRENT_COLOR, 0);
            mCurrentText = getPreferences(MODE_PRIVATE).getString(CURRENT_TEXT, null);

            mPreferences.edit().putInt(YESTERDAY_COLOR, mYesterdayColor).apply();
            mPreferences.edit().putInt(TWO_DAYS_AGO_COLOR, m2DaysAgoColor).apply();
            mPreferences.edit().putInt(THREE_DAYS_AGO_COLOR, m3DaysAgoColor).apply();

            mPreferences.edit().putString(YESTERDAY_TEXT, mYesterdayText).apply();
            mPreferences.edit().putString(TWO_DAYS_AGO_TEXT, m2DaysAgoText).apply();
            mPreferences.edit().putString(THREE_DAYS_AGO_TEXT, m3DaysAgoText).apply();

To clarify:

mCurrentText can be mTextA, mTextB or mTextC

mCurrentColor can be mColor1, mColor2, or mColor3

Whenever my app detects a new day >

mCurrentText is saved as mYesterdayText

mCurrentColor is saved as mYesterdayColor

then it becomes Day+2, Day+3 etc, everything moves from one row, until Day+4 when Day+3 gets overwritten.

As a final result, I want to be able to read & save the values of mYesterdayText/mYesterdayColor, mTwoDaysAgoText/mTwoDaysAgoColor & mThreeDaysAgoText/mThreeDaysAgoColor for each new day.

I don't know if I'm going the wrong way or not. Please I need some help, I'm a newbie :(

Body:
I get your problem, you want to shift the values of colors:

Today's launch : Red > 0 > 0 > 0
Tomorrow's launch : NewColor1 > Red > 0 > 0
2 days later's launch : NewColor2 > NewColor1 > Red > 0
3 days later's launch : NewColor3 > NewColor2 > NewColor1 > Red
4 days later's launch : NewColor4 > NewColor3 > NewColor2 > NewColor1 (Red is gone, overwritten by NewColor1)

For this, you don't need to change the mCurrentText at all.
Have the following variables in shared pref (explaining just for TEXT):

CURRENT_TEXT, YESTERDAY_TEXT, TWO_DAYS_AGO_TEXT, THREE_DAYS_AGO_TEXT

initialize each with empty or default values you want.

Now whenever theres a new day, you just need to overwite the values as follows:

putInt(THREE_DAYS_AGO_TEXT, {get value from shared pref of TWO_DAYS_AGO_TEXT})
putInt(TWO_DAYS_AGO_TEXT, {get value from shared pref of YESTERDAY_TEXT})
putInt(YESTERDAY_TEXT, {get value from shared pref of CURRENT_TEXT})
putInt(CURRENT_TEXT, {get value of new text for today})

...and you will have the desired output.


问:
How to read a text file in python using open method
I have a text file mycontacts.txt

I need to read content of this file.
Location path is: C:\Users\myusername\Documents\SQL_NeedToKnow\Python
I am using example from here: https://medium.freecodecamp.org/send-emails-using-code-4fcea9df63f

```<code># Function to read the contacts from a given contact file and return a
# list of names and email addresses
def get_contacts(filename):
    names = []
    emails = []
    with open(filename, mode='r', encoding='utf-8') as contacts_file:
        for a_contact in contacts_file:
            names.append(a_contact.split()[0])
            emails.append(a_contact.split()[1])
    return names, emails
</code>```

So for my case, seems like I need to change the directory first.
For that I am using os.chdir method.
Not sure where should I place it exactly, but I dont even have an error.
I am using Jupyter.
I am trying to do this:

```<code># Function to read the contacts from a given contact file and return a
# list of names and email addresses
import os
os.chdir(r'''C:\Users\oserdyuk\Documents\SQL_NeedToKnow\Python''')
def get_contacts(filename):
    names = []
    emails = []
    with open("mycontacts.txt", mode='r', encoding='utf-8') as contacts_file:
        for a_contact in contacts_file:
            names.append(a_contact.split()[0])
            emails.append(a_contact.split()[1])
    return names, emails
</code>```

I also tried usin Open with full path:

```<code># Function to read the contacts from a given contact file and return a
# list of names and email addresses
import os
#os.chdir(r'''C:\Users\oserdyuk\Documents\SQL_NeedToKnow\Python''')
def get_contacts(filename):
    names = []
    emails = []
    with open(r'''C:\Users\oserdyuk\Documents\SQL_NeedToKnow\Python''', mode='r', encoding='utf-8') as contacts_file:
        for a_contact in contacts_file:
            names.append(a_contact.split()[0])
            emails.append(a_contact.split()[1])
    return names, emails
</code>```

答:
With your code I am assuming you're trying to get name and email in two lists from the entries in given file.

So with some edits in your code, try this:

```<code>def get_contacts(filename):
    names = []
    emails = []
    with open(filename, 'r') as contacts_file:
        for row in contacts_file.readlines():  # this is what missing
            name, email = row.split(",")  # split will be with "," delimiter
            names.append(name)
            emails.append(email)
    return names, emails
</code>```

Body:
I have a text file mycontacts.txt

I need to read content of this file.
Location path is: C:\Users\myusername\Documents\SQL_NeedToKnow\Python
I am using example from here: https://medium.freecodecamp.org/send-emails-using-code-4fcea9df63f

# Function to read the contacts from a given contact file and return a
# list of names and email addresses
def get_contacts(filename):
    names = []
    emails = []
    with open(filename, mode='r', encoding='utf-8') as contacts_file:
        for a_contact in contacts_file:
            names.append(a_contact.split()[0])
            emails.append(a_contact.split()[1])
    return names, emails

So for my case, seems like I need to change the directory first.
For that I am using os.chdir method.
Not sure where should I place it exactly, but I dont even have an error.
I am using Jupyter.
I am trying to do this:

# Function to read the contacts from a given contact file and return a
# list of names and email addresses
import os
os.chdir(r'''C:\Users\oserdyuk\Documents\SQL_NeedToKnow\Python''')
def get_contacts(filename):
    names = []
    emails = []
    with open("mycontacts.txt", mode='r', encoding='utf-8') as contacts_file:
        for a_contact in contacts_file:
            names.append(a_contact.split()[0])
            emails.append(a_contact.split()[1])
    return names, emails

I also tried usin Open with full path:

# Function to read the contacts from a given contact file and return a
# list of names and email addresses
import os
#os.chdir(r'''C:\Users\oserdyuk\Documents\SQL_NeedToKnow\Python''')
def get_contacts(filename):
    names = []
    emails = []
    with open(r'''C:\Users\oserdyuk\Documents\SQL_NeedToKnow\Python''', mode='r', encoding='utf-8') as contacts_file:
        for a_contact in contacts_file:
            names.append(a_contact.split()[0])
            emails.append(a_contact.split()[1])
    return names, emails

Body:
With your code I am assuming you're trying to get name and email in two lists from the entries in given file.

So with some edits in your code, try this:

def get_contacts(filename):
    names = []
    emails = []
    with open(filename, 'r') as contacts_file:
        for row in contacts_file.readlines():  # this is what missing
            name, email = row.split(",")  # split will be with "," delimiter
            names.append(name)
            emails.append(email)
    return names, emails


问:
Evaluation order of function declarations
With the following code, which is neither ES6, nor is it in "strict mode", I had expected an outcome of 'b' because the second declaration of foo should overwrite the first one. But the outcome is 'a'!

```<code>{
  function foo() {
    console.log('a');
  }
}

function foo() {
  console.log('b');
}

foo(); // 'a' ? Why not 'b'?
</code>```

When this code is surrounded with additional curly braces, the outcome is the expected 'b'.

```<code>{ // additional curly braces

  {
    function foo() {
      console.log('a');
    }
  }

  function foo() {
    console.log('b');
  }

  foo(); // 'b' as expected!

} // end additional curly braces
</code>```

For further illustration, please consider the following additional example:

```<code>foo('before declaration'); // outcome:  from outside block :before declaration

{
  function foo(s) {
    console.log('from inside block: ' + s);
  }
}

function foo(s) {
  console.log('from outside block :' + s);
}

foo('after declaration'); // outcome:  from inside block: after declaration
</code>```

In my opinion the correct outcome should be:

```<code>// from outside block :before declaration
// from outside block :after declaration
</code>```

I'm unable to spot my misconception here.

If I again enclose the complete last example inside curly brackets like so:

```<code>{
  foo('before declaration'); // outcome:  from outside block :before declaration

  {
    function foo(s) {
      console.log('from inside block: ' + s);
    }
  }

  function foo(s) {
    console.log('from outside block :' + s);
  }

  foo('after declaration'); // outcome:  from outside block: after declaration
}
</code>```

I get the expected outcome.

答:
Having multiple definitions of the same function in a single scope is not supported unless they are at top level.

The reason is that there is a big difference between for example:

```<code>function square(x) { return x*x; }
</code>```

and

```<code>var square = function(x) { return x*x; }
</code>```

where in the first case the name square is bound to the function object at start and not when the definition is "executed" during the normal program flow:

```<code>function foo() {
    console.log(square(12));  // Valid, no prob the function is defined "later"
    function square(x) { return x*x; }
}
</code>```

this however implies that if you place different definitions in the same scope it's not clear what should be done.

The standard describes what should happen only for multiple definitions at top level (last wins).

What to do in nested parts is instead not defined and different implementations (e.g. Firefox and Chrome) do not agree. What is clearly nonsense is for example placing two definitions for the same function in the two branches of an if-else statement (remember that the name binding must happen immediately, before statements in the scope begin execution).

Just don't do that.

ContentLicense: CC BY-SA 4.0

Body:
With the following code, which is neither ES6, nor is it in "strict mode", I had expected an outcome of 'b' because the second declaration of foo should overwrite the first one. But the outcome is 'a'!

{
  function foo() {
    console.log('a');
  }
}

function foo() {
  console.log('b');
}

foo(); // 'a' ? Why not 'b'?

When this code is surrounded with additional curly braces, the outcome is the expected 'b'.

{ // additional curly braces

  {
    function foo() {
      console.log('a');
    }
  }

  function foo() {
    console.log('b');
  }

  foo(); // 'b' as expected!

} // end additional curly braces

For further illustration, please consider the following additional example:

foo('before declaration'); // outcome:  from outside block :before declaration

{
  function foo(s) {
    console.log('from inside block: ' + s);
  }
}

function foo(s) {
  console.log('from outside block :' + s);
}

foo('after declaration'); // outcome:  from inside block: after declaration

In my opinion the correct outcome should be:

// from outside block :before declaration
// from outside block :after declaration

I'm unable to spot my misconception here.

If I again enclose the complete last example inside curly brackets like so:

{
  foo('before declaration'); // outcome:  from outside block :before declaration

  {
    function foo(s) {
      console.log('from inside block: ' + s);
    }
  }

  function foo(s) {
    console.log('from outside block :' + s);
  }

  foo('after declaration'); // outcome:  from outside block: after declaration
}

I get the expected outcome.

Body:
Having multiple definitions of the same function in a single scope is not supported unless they are at top level.

The reason is that there is a big difference between for example:

function square(x) { return x*x; }

and

var square = function(x) { return x*x; }

where in the first case the name square is bound to the function object at start and not when the definition is "executed" during the normal program flow:

function foo() {
    console.log(square(12));  // Valid, no prob the function is defined "later"
    function square(x) { return x*x; }
}

this however implies that if you place different definitions in the same scope it's not clear what should be done.

The standard describes what should happen only for multiple definitions at top level (last wins).

What to do in nested parts is instead not defined and different implementations (e.g. Firefox and Chrome) do not agree. What is clearly nonsense is for example placing two definitions for the same function in the two branches of an if-else statement (remember that the name binding must happen immediately, before statements in the scope begin execution).

Just don't do that.


问:
Inserting data into database but getting an error of MySQLSyntaxErrorException: You have an error in your SQL syntax

I have tried to peek in the query when it ran but all I get was this:

```<code>INSERT INTO tblusers (first_name, middle_initial, last_name, username, password, privilege) VALUES (?,?,?,?,?,?)
</code>```

I cannot see what is wrong with the insertion code that I created and the error is not very helpful to me. Here is my code for reference:

```<code>String query = ("INSERT INTO tblusers (first_name, middle_initial, last_name, username, password, privilege)"
                    + " VALUES (?,?,?,?,?,?)");
            stmt = conn.prepareStatement(query);
            stmt.setObject(1, txtFn.getText());
            stmt.setObject(2, txtMi.getText());
            stmt.setObject(3, txtLn.getText());
            stmt.setObject(4, txtUser.getText());
            stmt.setObject(5, txtPass.getText());
            stmt.setString(6, "'student'");
            System.out.println(query);
            stmt.executeUpdate(query, Statement.RETURN_GENERATED_KEYS);
            ResultSet rs = stmt.getGeneratedKeys();
            Integer result =- 1;

            if (rs.next()) {
                result = rs.getInt(1);
            }

            String query2 = ("INSERT INTO tblcourseinfo (user_id, course_id, school_id) VALUES (?,?,?)");
            stmt.setObject(1, result);
            stmt.setObject(2, cmbCourse.getId());
            stmt.setObject(3, cmbSchool.getId());
            stmt.executeUpdate(query2);
</code>```

How do I get rid of the error and in a glance can anyone tell me what is wrong with my insert statement?

Here is the StackTrace:

```<code>com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'first_name, middle_initial, last_name, username, password, privilege VALUES (?,?' at line 1
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.Util.getInstance(Util.java:386)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1053)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4120)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4052)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2503)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2664)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2788)
at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1816)
at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1904)
at elibraryserver.NewStudentController.registerButtonAction(NewStudentController.java:171)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at sun.reflect.misc.Trampoline.invoke(MethodUtil.java:71)
at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at sun.reflect.misc.MethodUtil.invoke(MethodUtil.java:275)
at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1769)
at javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(FXMLLoader.java:1657)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49)
at javafx.event.Event.fireEvent(Event.java:198)
at javafx.scene.Node.fireEvent(Node.java:8413)
at javafx.scene.control.Button.fire(Button.java:185)
at com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(ButtonBehavior.java:182)
at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:96)
at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:89)
at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:218)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49)
at javafx.event.Event.fireEvent(Event.java:198)
at javafx.scene.Scene$MouseHandler.process(Scene.java:3757)
at javafx.scene.Scene$MouseHandler.access$1500(Scene.java:3485)
at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1762)
at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2494)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:381)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$353(GlassViewEventHandler.java:417)
at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:389)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:416)
at com.sun.glass.ui.View.handleMouseEvent(View.java:555)
at com.sun.glass.ui.View.notifyMouse(View.java:937)
at com.sun.glass.ui.win.WinApplication._enterNestedEventLoopImpl(Native Method)
at com.sun.glass.ui.win.WinApplication._enterNestedEventLoop(WinApplication.java:204)
at com.sun.glass.ui.Application.enterNestedEventLoop(Application.java:511)
at com.sun.glass.ui.EventLoop.enter(EventLoop.java:107)
at com.sun.javafx.tk.quantum.QuantumToolkit.enterNestedEventLoop(QuantumToolkit.java:583)
at javafx.stage.Stage.showAndWait(Stage.java:474)
at elibraryserver.NewStudentController.initRegister(NewStudentController.java:152)
at elibraryserver.serverController.addStudentButtonAction(serverController.java:71)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at sun.reflect.misc.Trampoline.invoke(MethodUtil.java:71)
at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at sun.reflect.misc.MethodUtil.invoke(MethodUtil.java:275)
at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1769)
at javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(FXMLLoader.java:1657)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49)
at javafx.event.Event.fireEvent(Event.java:198)
at javafx.scene.control.MenuItem.fire(MenuItem.java:462)
at com.sun.javafx.scene.control.skin.ContextMenuContent$MenuItemContainer.doSelect(ContextMenuContent.java:1405)
at com.sun.javafx.scene.control.skin.ContextMenuContent$MenuItemContainer.lambda$createChildren$343(ContextMenuContent.java:1358)
at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:218)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
at javafx.event.Event.fireEvent(Event.java:198)
at javafx.scene.Scene$MouseHandler.process(Scene.java:3757)
at javafx.scene.Scene$MouseHandler.access$1500(Scene.java:3485)
at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1762)
at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2494)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:381)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$353(GlassViewEventHandler.java:417)
at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:389)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:416)
at com.sun.glass.ui.View.handleMouseEvent(View.java:555)
at com.sun.glass.ui.View.notifyMouse(View.java:937)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$147(WinApplication.java:177)
at java.lang.Thread.run(Thread.java:748)
</code>```

答:
The line stmt.executeUpdate(query, Statement.RETURN_GENERATED_KEYS); is wrong. It's not intended for PreparedStatement, because it executes the query without the added parameter.

Better use stmt.executeUpdate();

You also need another PreparedStatement for the second query and better use setString() or setInt() instead of setObject(). Since you already use a PreparedStatement you don't need to embed the String student in single quotes, except you need them.

For example:

```<code>String query = ("INSERT INTO tblusers (first_name, middle_initial, last_name, username, password, privilege)"
    + " VALUES (?,?,?,?,?,?)");
PreparedStatement ps1 = conn.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
ps1.setString(1, txtFn.getText());
ps1.setString(2, txtMi.getText());
ps1.setString(3, txtLn.getText());
ps1.setString(4, txtUser.getText());
ps1.setString(5, txtPass.getText());
ps1.setString(6, "student");
ps1.executeUpdate();
ResultSet rs = ps1.getGeneratedKeys();
Integer result =- 1;

if (rs.next()) {
    result = rs.getInt(1);
}

String query2 = "INSERT INTO tblcourseinfo (user_id, course_id, school_id) VALUES (?,?,?)";
PreparedStatement ps2 = con.prepareStatement(query2);
ps2.setInt(1, result);
ps2.setInt(2, cmbCourse.getId());
ps2.setInt(3, cmbSchool.getId());
ps2.executeUpdate();
</code>```

Body:
I have tried to peek in the query when it ran but all I get was this:

INSERT INTO tblusers (first_name, middle_initial, last_name, username, password, privilege) VALUES (?,?,?,?,?,?)

I cannot see what is wrong with the insertion code that I created and the error is not very helpful to me. Here is my code for reference:

String query = ("INSERT INTO tblusers (first_name, middle_initial, last_name, username, password, privilege)"
                    + " VALUES (?,?,?,?,?,?)");
            stmt = conn.prepareStatement(query);
            stmt.setObject(1, txtFn.getText());
            stmt.setObject(2, txtMi.getText());
            stmt.setObject(3, txtLn.getText());
            stmt.setObject(4, txtUser.getText());
            stmt.setObject(5, txtPass.getText());
            stmt.setString(6, "'student'");
            System.out.println(query);
            stmt.executeUpdate(query, Statement.RETURN_GENERATED_KEYS);
            ResultSet rs = stmt.getGeneratedKeys();
            Integer result =- 1;

            if (rs.next()) {
                result = rs.getInt(1);
            }

            String query2 = ("INSERT INTO tblcourseinfo (user_id, course_id, school_id) VALUES (?,?,?)");
            stmt.setObject(1, result);
            stmt.setObject(2, cmbCourse.getId());
            stmt.setObject(3, cmbSchool.getId());
            stmt.executeUpdate(query2);

How do I get rid of the error and in a glance can anyone tell me what is wrong with my insert statement?

Here is the StackTrace:

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'first_name, middle_initial, last_name, username, password, privilege VALUES (?,?' at line 1
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.Util.getInstance(Util.java:386)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1053)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4120)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4052)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2503)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2664)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2788)
at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1816)
at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1904)
at elibraryserver.NewStudentController.registerButtonAction(NewStudentController.java:171)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at sun.reflect.misc.Trampoline.invoke(MethodUtil.java:71)
at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at sun.reflect.misc.MethodUtil.invoke(MethodUtil.java:275)
at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1769)
at javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(FXMLLoader.java:1657)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49)
at javafx.event.Event.fireEvent(Event.java:198)
at javafx.scene.Node.fireEvent(Node.java:8413)
at javafx.scene.control.Button.fire(Button.java:185)
at com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(ButtonBehavior.java:182)
at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:96)
at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:89)
at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:218)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49)
at javafx.event.Event.fireEvent(Event.java:198)
at javafx.scene.Scene$MouseHandler.process(Scene.java:3757)
at javafx.scene.Scene$MouseHandler.access$1500(Scene.java:3485)
at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1762)
at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2494)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:381)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$353(GlassViewEventHandler.java:417)
at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:389)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:416)
at com.sun.glass.ui.View.handleMouseEvent(View.java:555)
at com.sun.glass.ui.View.notifyMouse(View.java:937)
at com.sun.glass.ui.win.WinApplication._enterNestedEventLoopImpl(Native Method)
at com.sun.glass.ui.win.WinApplication._enterNestedEventLoop(WinApplication.java:204)
at com.sun.glass.ui.Application.enterNestedEventLoop(Application.java:511)
at com.sun.glass.ui.EventLoop.enter(EventLoop.java:107)
at com.sun.javafx.tk.quantum.QuantumToolkit.enterNestedEventLoop(QuantumToolkit.java:583)
at javafx.stage.Stage.showAndWait(Stage.java:474)
at elibraryserver.NewStudentController.initRegister(NewStudentController.java:152)
at elibraryserver.serverController.addStudentButtonAction(serverController.java:71)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at sun.reflect.misc.Trampoline.invoke(MethodUtil.java:71)
at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at sun.reflect.misc.MethodUtil.invoke(MethodUtil.java:275)
at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1769)
at javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(FXMLLoader.java:1657)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49)
at javafx.event.Event.fireEvent(Event.java:198)
at javafx.scene.control.MenuItem.fire(MenuItem.java:462)
at com.sun.javafx.scene.control.skin.ContextMenuContent$MenuItemContainer.doSelect(ContextMenuContent.java:1405)
at com.sun.javafx.scene.control.skin.ContextMenuContent$MenuItemContainer.lambda$createChildren$343(ContextMenuContent.java:1358)
at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:218)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
at javafx.event.Event.fireEvent(Event.java:198)
at javafx.scene.Scene$MouseHandler.process(Scene.java:3757)
at javafx.scene.Scene$MouseHandler.access$1500(Scene.java:3485)
at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1762)
at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2494)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:381)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$353(GlassViewEventHandler.java:417)
at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:389)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:416)
at com.sun.glass.ui.View.handleMouseEvent(View.java:555)
at com.sun.glass.ui.View.notifyMouse(View.java:937)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$147(WinApplication.java:177)
at java.lang.Thread.run(Thread.java:748)

Body:
The line stmt.executeUpdate(query, Statement.RETURN_GENERATED_KEYS); is wrong. It's not intended for PreparedStatement, because it executes the query without the added parameter.

Better use stmt.executeUpdate();

You also need another PreparedStatement for the second query and better use setString() or setInt() instead of setObject(). Since you already use a PreparedStatement you don't need to embed the String student in single quotes, except you need them.

For example:

String query = ("INSERT INTO tblusers (first_name, middle_initial, last_name, username, password, privilege)"
    + " VALUES (?,?,?,?,?,?)");
PreparedStatement ps1 = conn.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
ps1.setString(1, txtFn.getText());
ps1.setString(2, txtMi.getText());
ps1.setString(3, txtLn.getText());
ps1.setString(4, txtUser.getText());
ps1.setString(5, txtPass.getText());
ps1.setString(6, "student");
ps1.executeUpdate();
ResultSet rs = ps1.getGeneratedKeys();
Integer result =- 1;

if (rs.next()) {
    result = rs.getInt(1);
}

String query2 = "INSERT INTO tblcourseinfo (user_id, course_id, school_id) VALUES (?,?,?)";
PreparedStatement ps2 = con.prepareStatement(query2);
ps2.setInt(1, result);
ps2.setInt(2, cmbCourse.getId());
ps2.setInt(3, cmbSchool.getId());
ps2.executeUpdate();


问:
Disable auto_prepend in subfolder
I'm using auto_prepend in htaccess on my website and I don't want it to be used in subfolder.

For example, in the root folder, the .htaccess have this line

```<code>php_value auto_prepend_file "path/to/file.php"
</code>```

In the admin folder, root/admin, have

```<code>RewriteRule . front-controller.php [L]
</code>```

and here I have some problem because of some class or function loaded twice...

Then how to avoid load auto_prepend in the /admin folder?

答:
To disable auto_prepend in specific folder, just paste this code in the .htaccess file of that specific folder

```<code>php_value auto_prepend_file none
</code>```

For your case, create a .htaccess file under folder root/admin and paste the above code.

Title: Disable auto_prepend in subfolder

Body:
I'm using auto_prepend in htaccess on my website and I don't want it to be used in subfolder.

For example, in the root folder, the .htaccess have this line

php_value auto_prepend_file "path/to/file.php"

In the admin folder, root/admin, have

RewriteRule . front-controller.php [L]

and here I have some problem because of some class or function loaded twice...

Then how to avoid load auto_prepend in the /admin folder?

Body:
To disable auto_prepend in specific folder, just paste this code in the .htaccess file of that specific folder

php_value auto_prepend_file none

For your case, create a .htaccess file under folder root/admin and paste the above code.


问:
if result == 'no' - Invalid syntax
This is my quiz... I am sort of new to python and I am perplexed with this one. At the end, there is a {if result == 'no'} and when I run an error comes you with 'invalid syntax'. I hope it's not a stupid mistake but I'm really confused</p>
```<code>print('What is your name?')
user_name = input('Name: ')
print()

print('Question 1')
age = input('How old are you ' + user_name + '? ')
print()

print('Question 2')
colour = input("What's your favourite colour " + user_name + '?')
print()

print('Question 3')
town = input('What town do you live in ' + user_name + '?')
print()

print('Question 4')
result = input('Do you want to see your results ' + user_name + '? (yes / no)')
print()

if result == 'yes':
    print('Age: ' + age + '\nFavourite Colour: ' + colour + '\nTown of residency: ' + town

if result == 'no':
    print('What ever')
    print('Age: ' + age + '\nFavourite Colour: ' + colour + '\nTown of residency: ' + town)
</code>```

答:
```<code>print('Age: ' + age + '\nFavourite Colour: ' + colour + '\nTown of residency: ' + town
</code>```

You forgot the closing )

Title: if result == 'no' - Invalid syntax

Body:
This is my quiz... I am sort of new to python and I am perplexed with this one. At the end, there is a {if result == 'no'} and when I run an error comes you with 'invalid syntax'. I hope it's not a stupid mistake but I'm really confused

print('What is your name?')
user_name = input('Name: ')
print()

print('Question 1')
age = input('How old are you ' + user_name + '? ')
print()

print('Question 2')
colour = input("What's your favourite colour " + user_name + '?')
print()

print('Question 3')
town = input('What town do you live in ' + user_name + '?')
print()

print('Question 4')
result = input('Do you want to see your results ' + user_name + '? (yes / no)')
print()

if result == 'yes':
    print('Age: ' + age + '\nFavourite Colour: ' + colour + '\nTown of residency: ' + town

if result == 'no':
    print('What ever')
    print('Age: ' + age + '\nFavourite Colour: ' + colour + '\nTown of residency: ' + town)

Body:
print('Age: ' + age + '\nFavourite Colour: ' + colour + '\nTown of residency: ' + town

You forgot the closing )


问:
How to save following screenshot to mysql database with Php

this is Screenshot of my csv file

I want to save this csv file in mysql db with php

答:
if (isset($_POST['submit']))

{

```<code>   $file_name = $_FILES['file']['name'];
   $type = $_FILES['file']['type'];
   $config['allowed_types'] = 'csv';
   $config['upload_path'] = 'upload';
   $this->load->library('upload', $config);
            if (!$this->upload->do_upload('file')) {
                #error in file uploading
            } else {
                $data_array = array("Employee_name" =>
                   "file_name" => $file_name,
                );
                #Pass data to model
                $this->UserModel->insertData($data_array);
            }
 }
</code>```

Body:
if (isset($_POST['submit']))

{

   $file_name = $_FILES['file']['name'];
   $type = $_FILES['file']['type'];
   $config['allowed_types'] = 'csv';
   $config['upload_path'] = 'upload';
   $this->load->library('upload', $config);
            if (!$this->upload->do_upload('file')) {
                #error in file uploading
            } else {
                $data_array = array("Employee_name" =>
                   "file_name" => $file_name,
                );
                #Pass data to model
                $this->UserModel->insertData($data_array);
            }
 }


问:
Display a Window while a button is held pressed, but after a delay (LongPress) on Android Studio
I'm doing a calculator app as a college project. I want the "equals" button to (obviously) calculate the result of the operation, but I also want that button to display the history if you keep the button pressed.

I know how to use OnLongClick but am not sure how to implement this.

答:
Just as with OnClickListener you will have to implement OnLongClickListener and override onLongClick() or use an anonymous inner class for example:

```<code>equalsButton.setOnLongClickListener(new View.OnLongClickListener() {
   @Override public boolean onLongClick(View v) {
           displayHistory();
       return true;
   }
});
</code>```

Unlike onClick(), onLongClick returns a boolean. This is to notify the Android OS if the callback has consumed the event or not. A return value of true indicates to the OS that the event can be discarded and does not have to be passed on to other event listeners registered on the same button.

Body:
Just as with OnClickListener you will have to implement OnLongClickListener and override onLongClick() or use an anonymous inner class for example:

equalsButton.setOnLongClickListener(new View.OnLongClickListener() {
   @Override public boolean onLongClick(View v) {
           displayHistory();
       return true;
   }
});

Unlike onClick(), onLongClick returns a boolean. This is to notify the Android OS if the callback has consumed the event or not. A return value of true indicates to the OS that the event can be discarded and does not have to be passed on to other event listeners registered on the same button.


问:
Reasonable situations to use Kotlin's `let`
In Kotlin, it's common to use let to execute code if an object (let receiver) isn't null, as an alternative to an if != null check, as in the following:

```<code>val nullable: String? = "anything"
nullable?.let {
    println(it)
}
</code>```

In what other situations does it make sense to make use of let?

FYI, let is part of Kotlin's stdlib and is defined as follows:

```<code>@kotlin.internal.InlineOnly
public inline fun <T, R> T.let(block: (T) -> R): R = block(this)
</code>```

答:
scoping capabilities

The stdlib function let enables you to confine a variable's scope to a specific block of code. Shown here:

```<code>compile("a:b:c")
"io.vertx:vertx".let { v->
    compile("$v-lang-kotlin:$vertxVersion")
    compile("$v-lang-kotlin-coroutines:$vertxVersion")
}
compile("x:y:z")
</code>```

We could alternatively define a val v: String = "io.vertx:vertx" which might make the code more readable since that's what we'd do in Java for example. Yet, that val would be accessible throughout the whole method. We just want to have it available for the compile units with vertx involved, thus we confine the variable holding io.vertx:vertx to the let block.

Informations on the different scoping function alternatives can be found in this thread.

Body:
In Kotlin, it's common to use let to execute code if an object (let receiver) isn't null, as an alternative to an if != null check, as in the following:

val nullable: String? = "anything"
nullable?.let {
    println(it)
}

In what other situations does it make sense to make use of let?

FYI, let is part of Kotlin's stdlib and is defined as follows:

@kotlin.internal.InlineOnly
public inline fun <T, R> T.let(block: (T) -> R): R = block(this)

Body:
scoping capabilities

The stdlib function let enables you to confine a variable's scope to a specific block of code. Shown here:

compile("a:b:c")
"io.vertx:vertx".let { v->
    compile("$v-lang-kotlin:$vertxVersion")
    compile("$v-lang-kotlin-coroutines:$vertxVersion")
}
compile("x:y:z")

We could alternatively define a val v: String = "io.vertx:vertx" which might make the code more readable since that's what we'd do in Java for example. Yet, that val would be accessible throughout the whole method. We just want to have it available for the compile units with vertx involved, thus we confine the variable holding io.vertx:vertx to the let block.

Informations on the different scoping function alternatives can be found in this thread.


问:
Is it possible to get an rss feed using javascript client side scripting only?
If I can't do this would the process for getting the data be:
1) Have my server get the rss data from the desired rss feed.
2) Have the server parse the data.  I don't know what rss looks like but I assume some parsing     is needed to display it for a user to read.
3) Send the data to the javascript client.</p>

答:
Or you can use the API of Google Feed to load a RSS Feed and parse it as you need. :) I think is a interesting option.

http://code.google.com/intl/es-ES/apis/feed/v1/devguide.html#load_the_javascript_api_and_ajax_search_module

ContentLicense: CC BY-SA 2.5


问:
System.typeInitializationException on Windows phone
I am getting this exception when I am trying to debug my application by connecting a device. It is working fine in the emulator with no exceptions at all.

The InnerException is: Could not load file or assembly 'BouncyCastle.Crypto, Version=1.8.1.0, Culture=neutral, PublicKeyToken=0e99375e54769942' or one of its dependencies. The system cannot find the file specified.

But the file is present with the specific version and token.

In StackTrace it showing that exception is occured here : setDefaultLanguageFromCode(String selectedLanguage)

Here's the code:

```<code> private void Application_Launching(object sender, LaunchingEventArgs e)
    {
     ...//some code

        Utility.setDefaultLanguageFromCode(code);
        Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture;
        LocalizedStringsInCommonDll.LocalizedStringsResource.UpdateLanguage();
    }
</code>```

In Utility Page :

```<code> public static System.Globalization.NumberFormatInfo input = new System.Globalization.NumberFormatInfo();
 public static void setDefaultLanguageFromCode(string selectedLanguage)
    {
        input.NumberDecimalSeparator = ".";//**Exception here**
        input.NumberGroupSeparator = ",";
    ......
    }
</code>```

Is the exception caused due to some settings on device.
I tried google search but nothing helped me..

I am desperately in need of help.. I have already wasted an entire day behind this trying to figure out what is wrong here..

答:
I tried to reinstall BouncyCastle crypto by using this in Package manager console

Install-Package Portable.BouncyCastle -Version 1.8.1.3

and it resolved my issue..

Body:
I am getting this exception when I am trying to debug my application by connecting a device. It is working fine in the emulator with no exceptions at all.

The InnerException is: Could not load file or assembly 'BouncyCastle.Crypto, Version=1.8.1.0, Culture=neutral, PublicKeyToken=0e99375e54769942' or one of its dependencies. The system cannot find the file specified.

But the file is present with the specific version and token.

In StackTrace it showing that exception is occured here : setDefaultLanguageFromCode(String selectedLanguage)

Here's the code:

 private void Application_Launching(object sender, LaunchingEventArgs e)
    {
     ...//some code

        Utility.setDefaultLanguageFromCode(code);
        Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture;
        LocalizedStringsInCommonDll.LocalizedStringsResource.UpdateLanguage();
    }

In Utility Page :

 public static System.Globalization.NumberFormatInfo input = new System.Globalization.NumberFormatInfo();
 public static void setDefaultLanguageFromCode(string selectedLanguage)
    {
        input.NumberDecimalSeparator = ".";//**Exception here**
        input.NumberGroupSeparator = ",";
    ......
    }

Is the exception caused due to some settings on device.
I tried google search but nothing helped me..

I am desperately in need of help.. I have already wasted an entire day behind this trying to figure out what is wrong here..


问:
Destroy the session file in Laravel
As we all know, we can use the function session_destory() to delete the session file in PHP.But I do not know how to delete session file in Laravel due to the reason that the author rewrites the session module. Expecting your answers. </p>

答:
Just use this

```<code>Session::flush();
</code>```

in Laravel to destroy all the session.

Title: Destroy the session file in Laravel

Body:
Just use this

Session::flush();

in Laravel to destroy all the session.


问:
How to check is a string or number?
I have an array ["abc", "94761178","790"]

I want to iterate each and check is a String or an Int?

How to check it?

How to convert "123" to integer 123?

答:
This code works for me for Swift 3/4</p>

```<code>  func isNumber(textField: UITextField) -> Bool {
    let allowedCharacters = CharacterSet.decimalDigits
    let characterSet = CharacterSet(charactersIn: textField.text!)
    return allowedCharacters.isSuperset(of: characterSet)
  //        return true
  }
</code>```

Title: How to check is a string or number?

Body:
This code works for me for Swift 3/4

  func isNumber(textField: UITextField) -> Bool {
    let allowedCharacters = CharacterSet.decimalDigits
    let characterSet = CharacterSet(charactersIn: textField.text!)
    return allowedCharacters.isSuperset(of: characterSet)
  //        return true
  }


问:
How to insert text into the textarea at the current cursor position?
I would like to create a simple function that adds text into a text area at the user's cursor position. It needs to be a clean function. Just the basics. I can figure out the rest.  </p>

答:
```<code>/**
 * Usage "foo baz".insertInside(4, 0, "bar ") ==> "foo bar baz"
 */
String.prototype.insertInside = function(start, delCount, newSubStr) {
    return this.slice(0, start) + newSubStr + this.slice(start + Math.abs(delCount));
};

$('textarea').bind("keydown keypress", function (event) {
    var val = $(this).val();
    var indexOf = $(this).prop('selectionStart');
    if(event.which === 13) {
        val = val.insertInside(indexOf, 0,  "<br>\n");
        $(this).val(val);
        $(this).focus();
    }
});
</code>```


问:
How to configure Xcode 9.1 with Gitlab?
I have created a repo. on BitBucket. then I clone that repo to the Gitlab.now i want to connect Gitlab's repo to the Xcode(9.1).So I can directly push, pull and do all the git stuff from Xcode.

is there any way to do that?

thanks!!!

答:
The best way really is to follow the instructions GitHub gives you:

First, go the correct directory

```<code>cd <directory of your Xcode project>
</code>```

It sound like you've already got a local Git project from Xcode. If that's true, skip this code block.

```<code>git init .
git add .
git commit -s
<type in a commit message>
</code>```

Last, push into your repository. The following is copied directly from my own github account, after I created a new "test" repo. Change the "dhalperi/test" part. Hope its help you.

Title: How to configure Xcode 9.1 with Gitlab?

Body:
The best way really is to follow the instructions GitHub gives you:

First, go the correct directory

cd <directory of your Xcode project>

It sound like you've already got a local Git project from Xcode. If that's true, skip this code block.

git init .
git add .
git commit -s
<type in a commit message>

Last, push into your repository. The following is copied directly from my own github account, after I created a new "test" repo. Change the "dhalperi/test" part. Hope its help you.


问:
How can i create a Post for google plus company pages using APIs

What is the difference between user's profile and user stream?

what does google apps profile mean?

How can I create a Post for regular google plus users or company pages or google apps profile?

what is the difference between google domain apis and directory apis.

It was quite easy to integrate with other social platforms like Facebook or LinkedIn, but here I am very confused with all these terms.

And there are many people in the market (Hootsuite, Buffer etc.) who are able to post directly on regular google plus profile or company pages

Thanks

答:
1: What is the difference between user's profile and user stream?

The users profile describes them as a person name work history.  The stream would be the posts they have made in the past.

2: what does google apps profile mean?

Google Apps or Gsuite is a group of tools from google.  A Google apps profile is not the same as a Google+ Soical media profile it is the users profile from within gsuite.

3: How can I create a Post for regular google plus users or company pages or google apps profile?

You can not post directly to a regular google plus user or company page.   Using the Goolge plus domains api you can post to the Google apps (Gsuite) account, these posts will only been seen by other users on your domain they are not public.

what is the difference between google domain apis and directory apis.

Direcory apis or admin sdk lets you admin the users within the domain account (Gsuite).    Google plus domains api lets you post messages to the users on the domain, like its own social media site.

It was quite easy to integrate with other social platforms like Facebook or LinkedIn, but here I am very confused with all these terms.

Google+ the social media site is not like Facebook or linked-in there is no public write API for it.  You cant post to it programmatic.


问:
Neo4j 3.3.0 community edition Open NLP
Installed Neo4j CE 3.3.0 on windows RAM 8GB. I referred to https://medium.com/@david.allen_3172/using-nlp-in-neo4j-ac40bc92196f for installation of the open NLP and APOC packages.

Plugins were copied to the plugins folder (graphaware-nlp-3.3.0.51.1, graphaware-server-enterprise-all-3.3.0.51 and nlp-opennlp-3.3.0.51.1).

The configuration setting were added to neo4j.conf file as given in  https://github.com/graphaware/neo4j-nlp

When I restart the Neo4j server, it takes a lot of time and then gives me the following error mesasge:

```<code>Caused by: java.lang.OutOfMemoryError: Java heap space Exception in
thread "GraphAware Starter" java.lang.RuntimeException: Error while
initializing model of class: class
 opennlp.tools.namefind.TokenNameFinderModel
    at
 com.graphaware.nlp.processor.opennlp.OpenNLPPipeline.loadModel(OpenNLPPipeline.java:504)
    at
 com.graphaware.nlp.processor.opennlp.OpenNLPPipeline.lambda$loadNamedEntitiesFinders$2(OpenNLPPipeline.java:162)
    at java.util.HashMap$EntrySpliterator.forEachRemaining(Unknown
</code>```

Without the plugins of NLP, Neo4j starts fine. Any help appreciated here on the minimum requirements of RAM/hardware.

答: The language models require memory to be loaded. So I would suggest to use at least 4GB or more. Furthermore you should use Enterprise version not CE.</p>

Title: Neo4j 3.3.0 community edition Open NLP

Body:
Installed Neo4j CE 3.3.0 on windows RAM 8GB. I referred to https://medium.com/@david.allen_3172/using-nlp-in-neo4j-ac40bc92196f for installation of the open NLP and APOC packages.

Plugins were copied to the plugins folder (graphaware-nlp-3.3.0.51.1, graphaware-server-enterprise-all-3.3.0.51 and nlp-opennlp-3.3.0.51.1).

The configuration setting were added to neo4j.conf file as given in  https://github.com/graphaware/neo4j-nlp

When I restart the Neo4j server, it takes a lot of time and then gives me the following error mesasge:

Caused by: java.lang.OutOfMemoryError: Java heap space Exception in
thread "GraphAware Starter" java.lang.RuntimeException: Error while
initializing model of class: class
 opennlp.tools.namefind.TokenNameFinderModel
    at
 com.graphaware.nlp.processor.opennlp.OpenNLPPipeline.loadModel(OpenNLPPipeline.java:504)
    at
 com.graphaware.nlp.processor.opennlp.OpenNLPPipeline.lambda$loadNamedEntitiesFinders$2(OpenNLPPipeline.java:162)
    at java.util.HashMap$EntrySpliterator.forEachRemaining(Unknown

Without the plugins of NLP, Neo4j starts fine. Any help appreciated here on the minimum requirements of RAM/hardware.


问:
Swift 4 shouldChangeCharactersIn only show length = 12
I have textfield ,shouldChangeCharactersIn codes im using barcode, system and my barcode codes == 12 characters. I want to show only 12 characters in my string if barcode small 12 characters or big must be return false or clean text field . my codes under below. When I using barcode if my barcodes 12 characters working fine , but if I read 12 character low don't clear textfield ,

How can I fix it ?

My codes under below.

```<code> func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

        let length = (Mytext.text?.characters.count)! - range.length + string.characters.count
        if length == 13 {

            print("Mytext=\(Mytext.text!)")
            Mytext.text = ""

            return true

        }else {

            return true
        }

    }
</code>```

Output when read 12 characters barcode shows success !
When read 12 characters low don't clear Mytext field , and when I read again adding +

答:
you have to set replacement string to "" blank string</p>

```<code>func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

    let length = (Mytext.text?.characters.count)! - range.length + string.characters.count
    if length == 13 {

        print("Mytext=\(Mytext.text!)")
        Mytext.text = ""

        return true

    }else {

        return true
    }

}
</code>```

Body:
I have textfield ,shouldChangeCharactersIn codes im using barcode, system and my barcode codes == 12 characters. I want to show only 12 characters in my string if barcode small 12 characters or big must be return false or clean text field . my codes under below. When I using barcode if my barcodes 12 characters working fine , but if I read 12 character low don't clear textfield ,

How can I fix it ?

My codes under below.

 func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

        let length = (Mytext.text?.characters.count)! - range.length + string.characters.count
        if length == 13 {

            print("Mytext=\(Mytext.text!)")
            Mytext.text = ""

            return true

        }else {

            return true
        }

    }

Output when read 12 characters barcode shows success !
When read 12 characters low don't clear Mytext field , and when I read again adding +

Body:
you have to set replacement string to "" blank string

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

    let length = (Mytext.text?.characters.count)! - range.length + string.characters.count
    if length == 13 {

        print("Mytext=\(Mytext.text!)")
        Mytext.text = ""

        return true

    }else {

        return true
    }

}


问:
Recursive function to add all the digits

I am trying to get the sum of all digits. The only method allowed to solve this question is recursive function. But, the sum is not supposed to exceed 10. For example, if given n is 38, it should return 2. (3+8 = 11, 1+1 =2)

I made the below code. But, it only returns 11. I approached this question in many different ways such as nested if and while loop, but I could not figure it out. Is there any way that I can solve this question using recursive function?

```<code>def digit_sum(n):
    if n//10 <= 0:
        return n%10
    return digit_sum(n//10) + n%10
</code>```

答:
Here is a recursive solution that does not cast to str:

```<code>def digit_sum(n):
    def _digit_sum(n):
        if n == 0:
            return n
        return n % 10 + digit_sum(n//10)
    s = _digit_sum(n)
    if s > 9:
        return digit_sum(s)
    return s
</code>```

some tests:

```<code>def test_digit_sum():
    n = 2
    print(n, digit_sum(n))
    assert digit_sum(n) == 2
    n=10
    print(n, digit_sum(n))
    assert digit_sum(n) == 1
    n=143
    print(n, digit_sum(n))
    assert digit_sum(n) == 8
    n=1434
    print(n, digit_sum(n))
    assert digit_sum(n) == 3
    n=143488837772
    print(n, digit_sum(n))
    assert digit_sum(n) == 8
    print("***all tests pass***")

test_digit_sum()
</code>```

output:

```<code>2 2
10 1
143 8
1434 3
143488837772 8
***all tests pass***
</code>```

Body:
I am trying to get the sum of all digits. The only method allowed to solve this question is recursive function. But, the sum is not supposed to exceed 10. For example, if given n is 38, it should return 2. (3+8 = 11, 1+1 =2)

I made the below code. But, it only returns 11. I approached this question in many different ways such as nested if and while loop, but I could not figure it out. Is there any way that I can solve this question using recursive function?

def digit_sum(n):
    if n//10 <= 0:
        return n%10
    return digit_sum(n//10) + n%10

Body:
Here is a recursive solution that does not cast to str:

def digit_sum(n):
    def _digit_sum(n):
        if n == 0:
            return n
        return n % 10 + digit_sum(n//10)
    s = _digit_sum(n)
    if s > 9:
        return digit_sum(s)
    return s

some tests:

def test_digit_sum():
    n = 2
    print(n, digit_sum(n))
    assert digit_sum(n) == 2
    n=10
    print(n, digit_sum(n))
    assert digit_sum(n) == 1
    n=143
    print(n, digit_sum(n))
    assert digit_sum(n) == 8
    n=1434
    print(n, digit_sum(n))
    assert digit_sum(n) == 3
    n=143488837772
    print(n, digit_sum(n))
    assert digit_sum(n) == 8
    print("***all tests pass***")

test_digit_sum()

output:

2 2
10 1
143 8
1434 3
143488837772 8
***all tests pass***


问:
Laravel update Query not work Call to a member function fill() on null
When i update data with changing user id in my drop down value and allocate a specific venue to user it return error and cannot update data.

Error :Call to a member function fill() on null

Image Added: where client is a users and when i allocate star venue to vinay it returns error

Here is my model function code  which i try

```<code>  public static function saveOrUpdate(Request $request) {
    try {

        $checkBoxes = [
            'is_premium',
            'is_verified',
            'is_outside_catering',
            'is_indoor',
            'is_outdoor',
            'has_parking',
            'has_valet'
        ];
        foreach($checkBoxes as $checkbox) {
            if(!$request->has($checkbox)) {
                $request->merge([$checkbox => 0]);
            }
        }

        $venue = false;

        DB::transaction(function () use ($request, &$venue) {
            $id = $request->get('id', false); // gt id here
            $clientId = $request->get('client_id', false); // gt cleint id here
            $client = Client::findOrFail($clientId);
            $venue = $client->venues()->findOrNew($id); // gt venue data
            // added dd($venue) below
            //dd($request->all()); Added array in below

            $venue->fill($request->all());

            try {
                $venue->save();
                $occasions = $request->get('occasions', []);
                $venue->occasions()->sync($occasions);

                if($id) {
                    // Here I am gtng error
                    $venue->venueParameter->fill($request->all())->save();
                } else {
                    $venue->venueParameter()->create($request->all());
                }
            } catch (\Exception $ex) {
                echo $ex->getMessage();
                dd($ex->getTraceAsString());
            }
        });

        return $venue;
    } catch (\Exception $ex) {
        throw $ex;
    }
}
</code>```

Here is venue model function for parameter

```<code>    public function venueParameter() {
    //dd("Welcome"); gt here successfully
    return $this->hasOne(VenueParameter::class);
}
</code>```

Here is my venueparameter model

```<code><?php

     namespace App;

     use Illuminate\Database\Eloquent\Model;

  class VenueParameter extends Model
  {

    protected $fillable = [

    'venue_id',
    'min_capacity',
    'max_capacity',
    'is_outside_catering',
    'price_list_view',
    'price_details_view',
    'area',
    'is_indoor',
    'indoor_area',
    'is_outdoor',
    'outdoor_area',
    'has_parking',
    'no_of_parkings',
    'has_valet',
    'no_of_rooms',
    'decorator',
];

public $timestamps = false;

const DECORATOR = [
    'Inside' => 'Inside',
    'Outside' => 'Outside',
    'Both' => 'Both'
];

public function venue() {

    return $this->belongsTo(Venue::class);
}
 }
</code>```

Here is what i gt when i dd($request->all())

```<code>                        "_token" => "dJcVc2pP6fGtBD9FUZYFMnKfHf0ArScjy9mLJfcg"
                        "id" => "8"
                        "name" => "test"
                        "client_id" => "2"
                        "logo" => "public/venue-logo/BO7ZuxbZyUZjo7u35WAyx4ReNlBnGxcFIKo77euo.jpeg"
                        "venue_type_id" => "1"
                        "is_premium" => "1"
                        "is_verified" => "1"
                        "tripadvisor_url" => "http://test.com/home"
                        "venue_url" => "http://test.com/home"
                        "status" => "Active"
                        "min_capacity" => "1"
                        "max_capacity" => "1"
                        "price_list_view" => "1"
                        "price_details_view" => ""
                        "area" => "5000"
                        "indoor_area" => "0"
                        "outdoor_area" => "0"
                        "no_of_parkings" => "0"
                        "decorator" => "Inside"
                        "is_outside_catering" => 0
                        "is_indoor" => 0
                        "is_outdoor" => 0
                        "has_parking" => 0
                        "has_valet" => 0
</code>```

Here is what i gt when i dd($venue)

```<code>  #attributes: array:12 [▼
"id" => 11
"client_id" => 1
"name" => "zuber"
"venue_url" => "http://premiumbanquets.com/home"
"logo" => "public/venue-logo/Rkt8SV5OLz8pMW6sFfJJUhUFmhSI2VCfBLvI6STd.jpeg"
"venue_type_id" => 1
"is_premium" => 1
"is_verified" => 1
"tripadvisor_url" => "http://premiumbanquets.com/home"
"status" => "Active"
"created_at" => "2017-12-04 13:19:25"
"updated_at" => "2017-12-04 13:19:25"
</code>```

]

How can i overcome on this problem?

答:
```<code>$venue = $client->venues()->findOrNew($id);
</code>```

This can be an existing record (is in the database, has an 'id', might have relationships as well) or a new instance, no attributes, no 'id', doesn't exist in the database (and therefor couldn't possibly have any existing relationships).  This is NOT the null part. findOrNew does not return a null.

The null part is potentially here:

```<code>$venue->venueParameter->fill($request->all())->save();
</code>```

If $venue is a new instance it will not have any relationships setup. Even if it is an existing record, it may not have that relationship in the database. So trying to set a property on a related model via dynamic property for a relationship isn't going to get very far. This is going to try and resolve the venueParameter relationship (load it), which doesn't exist so it returns a null, so:

```<code>null->fill($request->all())->save(); // is what is happening
</code>```

Body:
When i update data with changing user id in my drop down value and allocate a specific venue to user it return error and cannot update data.

Error :Call to a member function fill() on null

Image Added: where client is a users and when i allocate star venue to vinay it returns error

Here is my model function code  which i try

  public static function saveOrUpdate(Request $request) {
    try {

        $checkBoxes = [
            'is_premium',
            'is_verified',
            'is_outside_catering',
            'is_indoor',
            'is_outdoor',
            'has_parking',
            'has_valet'
        ];
        foreach($checkBoxes as $checkbox) {
            if(!$request->has($checkbox)) {
                $request->merge([$checkbox => 0]);
            }
        }

        $venue = false;

        DB::transaction(function () use ($request, &$venue) {
            $id = $request->get('id', false); // gt id here
            $clientId = $request->get('client_id', false); // gt cleint id here
            $client = Client::findOrFail($clientId);
            $venue = $client->venues()->findOrNew($id); // gt venue data
            // added dd($venue) below
            //dd($request->all()); Added array in below

            $venue->fill($request->all());

            try {
                $venue->save();
                $occasions = $request->get('occasions', []);
                $venue->occasions()->sync($occasions);

                if($id) {
                    // Here I am gtng error
                    $venue->venueParameter->fill($request->all())->save();
                } else {
                    $venue->venueParameter()->create($request->all());
                }
            } catch (\Exception $ex) {
                echo $ex->getMessage();
                dd($ex->getTraceAsString());
            }
        });

        return $venue;
    } catch (\Exception $ex) {
        throw $ex;
    }
}

Here is venue model function for parameter

    public function venueParameter() {
    //dd("Welcome"); gt here successfully
    return $this->hasOne(VenueParameter::class);
}

Here is my venueparameter model

<?php

     namespace App;

     use Illuminate\Database\Eloquent\Model;

  class VenueParameter extends Model
  {

    protected $fillable = [

    'venue_id',
    'min_capacity',
    'max_capacity',
    'is_outside_catering',
    'price_list_view',
    'price_details_view',
    'area',
    'is_indoor',
    'indoor_area',
    'is_outdoor',
    'outdoor_area',
    'has_parking',
    'no_of_parkings',
    'has_valet',
    'no_of_rooms',
    'decorator',
];

public $timestamps = false;

const DECORATOR = [
    'Inside' => 'Inside',
    'Outside' => 'Outside',
    'Both' => 'Both'
];

public function venue() {

    return $this->belongsTo(Venue::class);
}
 }

Here is what i gt when i dd($request->all())

                        "_token" => "dJcVc2pP6fGtBD9FUZYFMnKfHf0ArScjy9mLJfcg"
                        "id" => "8"
                        "name" => "test"
                        "client_id" => "2"
                        "logo" => "public/venue-logo/BO7ZuxbZyUZjo7u35WAyx4ReNlBnGxcFIKo77euo.jpeg"
                        "venue_type_id" => "1"
                        "is_premium" => "1"
                        "is_verified" => "1"
                        "tripadvisor_url" => "http://test.com/home"
                        "venue_url" => "http://test.com/home"
                        "status" => "Active"
                        "min_capacity" => "1"
                        "max_capacity" => "1"
                        "price_list_view" => "1"
                        "price_details_view" => ""
                        "area" => "5000"
                        "indoor_area" => "0"
                        "outdoor_area" => "0"
                        "no_of_parkings" => "0"
                        "decorator" => "Inside"
                        "is_outside_catering" => 0
                        "is_indoor" => 0
                        "is_outdoor" => 0
                        "has_parking" => 0
                        "has_valet" => 0

Here is what i gt when i dd($venue)

  #attributes: array:12 [▼
"id" => 11
"client_id" => 1
"name" => "zuber"
"venue_url" => "http://premiumbanquets.com/home"
"logo" => "public/venue-logo/Rkt8SV5OLz8pMW6sFfJJUhUFmhSI2VCfBLvI6STd.jpeg"
"venue_type_id" => 1
"is_premium" => 1
"is_verified" => 1
"tripadvisor_url" => "http://premiumbanquets.com/home"
"status" => "Active"
"created_at" => "2017-12-04 13:19:25"
"updated_at" => "2017-12-04 13:19:25"

]

How can i overcome on this problem?

Body:
$venue = $client->venues()->findOrNew($id);

This can be an existing record (is in the database, has an 'id', might have relationships as well) or a new instance, no attributes, no 'id', doesn't exist in the database (and therefor couldn't possibly have any existing relationships).  This is NOT the null part. findOrNew does not return a null.

The null part is potentially here:

$venue->venueParameter->fill($request->all())->save();

If $venue is a new instance it will not have any relationships setup. Even if it is an existing record, it may not have that relationship in the database. So trying to set a property on a related model via dynamic property for a relationship isn't going to get very far. This is going to try and resolve the venueParameter relationship (load it), which doesn't exist so it returns a null, so:

null->fill($request->all())->save(); // is what is happening


问:
Search for Substrings in Object
I have this code.

```<code>var abc = { QSX: 'V',WRT: 'VC',ETH: 'VC',RHY: 'VC',TFG: 'VC',YKL: 'VC'}
var filtered = _.pick(abc, ['HY', 'H']); //Lodash
console.log(filtered);
</code>```

It should output the following:

filtered = {RHY: 'VC', ETH: 'VC'}

Because those are the only two items that contain the substrings 'HY' and 'H'.
But it outputs just the first item.
Can someone help me figuring out why please?

答:
You can simply do it with punching lodash#pickBy and native filter (however you can again use lodash, but not required), in a one liner.

Have a look:

assume filterWith is the array as filter input

_.pickBy(abc, (v,k) => filterWith.find(f=> k.match(f)));

Here is an working snippet:

var abc = { QSX: 'V',WRT: 'VC',ETH: 'VC',RHY: 'VC',TFG: 'VC',YKL: 'VC'};
var filterWith = ['HY', 'H'];

var filtededData = _.pickBy(abc, (v,k) => filterWith.find(f=> k.match(f)));

console.log(filtededData)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script></code>```

Title: Search for Substrings in Object

Body:
I have this code.

var abc = { QSX: 'V',WRT: 'VC',ETH: 'VC',RHY: 'VC',TFG: 'VC',YKL: 'VC'}
var filtered = _.pick(abc, ['HY', 'H']); //Lodash
console.log(filtered);

It should output the following:

filtered = {RHY: 'VC', ETH: 'VC'}

Because those are the only two items that contain the substrings 'HY' and 'H'.
But it outputs just the first item.
Can someone help me figuring out why please?

Body:
You can simply do it with punching lodash#pickBy and native filter (however you can again use lodash, but not required), in a one liner.

Have a look:

assume filterWith is the array as filter input

_.pickBy(abc, (v,k) => filterWith.find(f=> k.match(f)));

Here is an working snippet:

var abc = { QSX: 'V',WRT: 'VC',ETH: 'VC',RHY: 'VC',TFG: 'VC',YKL: 'VC'};
var filterWith = ['HY', 'H'];

var filtededData = _.pickBy(abc, (v,k) => filterWith.find(f=> k.match(f)));

console.log(filtededData)

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>


问:
How did they do this? [iPhone layout]
checkout this app:

 If you swipe left in main image (the black shoes) you can see another image.

Can anyone try this app (Fashiolista, it's free and signup isn't required) and
say me how can I do an effect like that?

Thank you guys.

答:
I've not tried the app, but the way you usually accomplish that is with UIScrollView. In order to get the swiping-action to work as expected, you have to set pagingEnabled to YES.

The hardest part of implementing something like this is handling limited system resources: you'll run out of memory really quick. So you have to implement a queuing system rather like that used in UITableView. There are a few projects of this sort on GitHub, but I recommend checking out Apple's dev resources on this; I don't remember the link, but I believe in the last WWDC materials, they had info on how to build this properly.

Title: How did they do this? [iPhone layout]