问:
Initializing an empty DataFrame and appending rows
Different from creating an empty dataframe and populating rows later , I have many many dataframes that needs to be concatenated.

If there were only two data frames, I can do this:

```<code>df1 = pd.DataFrame([[1, 2], [3, 4]], columns=list('AB'))
df2 = pd.DataFrame([[5, 6], [7, 8]], columns=list('AB'))

df1.append(df2, ignore_index=True)
</code>```

Imagine I have millions of df that needs to be appended/concatenated each time I read a new file into a DataFrame object.

But when I tried to initialize an empty dataframe and then adding the new dataframes through a loop:

```<code>import pandas as pd
alldf = pd.DataFrame(, columns=list('AB'))
for filename in os.listdir(indir):
    df = pd.read_csv(indir+filename, delimiter=' ')
    alldf.append(df, ignore_index=True)
</code>```

This would return an empty alldf with only the header row, e.g.

```<code>alldf = pd.DataFrame(columns=list('AB'))
df1 = pd.DataFrame([[1, 2], [3, 4]], columns=list('AB'))
df2 = pd.DataFrame([[5, 6], [7, 8]], columns=list('AB'))
for df in [df1, df2]:
    alldf.append(df, ignore_index=True)
</code>```

答:
From @DSM comment, this works:</p>

```<code>import pandas as pd
dfs = []
for filename in os.listdir(indir):
    df = pd.read_csv(indir+filename, delimiter=' ')
    dfs(df)

alldf = pd.concat(dfs)
</code>```

Body:
Different from creating an empty dataframe and populating rows later , I have many many dataframes that needs to be concatenated.

If there were only two data frames, I can do this:

df1 = pd.DataFrame([[1, 2], [3, 4]], columns=list('AB'))
df2 = pd.DataFrame([[5, 6], [7, 8]], columns=list('AB'))

df1.append(df2, ignore_index=True)

Imagine I have millions of df that needs to be appended/concatenated each time I read a new file into a DataFrame object.

But when I tried to initialize an empty dataframe and then adding the new dataframes through a loop:

import pandas as pd
alldf = pd.DataFrame(, columns=list('AB'))
for filename in os.listdir(indir):
    df = pd.read_csv(indir+filename, delimiter=' ')
    alldf.append(df, ignore_index=True)

This would return an empty alldf with only the header row, e.g.

alldf = pd.DataFrame(columns=list('AB'))
df1 = pd.DataFrame([[1, 2], [3, 4]], columns=list('AB'))
df2 = pd.DataFrame([[5, 6], [7, 8]], columns=list('AB'))
for df in [df1, df2]:
    alldf.append(df, ignore_index=True)

Body:
From @DSM comment, this works:

import pandas as pd
dfs = []
for filename in os.listdir(indir):
    df = pd.read_csv(indir+filename, delimiter=' ')
    dfs(df)

alldf = pd.concat(dfs)


来源: stackexchange

问:
Can’t access cross-origin response header from frontend JavaScript
I am building a simple web app using ReactJS and create-react-app.

I have a backend API set up on Heroku where I can make POST requests. Everything works fine, except:

When I make a POST request using fetch API, the response is 100% correct but it only gives me 2 standard headers. I want to get my custom header. I have added expose header in my response and here's the plot twist: When I view the headers from Chrome Inspection Tool or Postman (API tool), it shows all the headers, including my custom one. Here is the fetch code I'm using -

```<code>fetch(theUrl, {
  method: 'POST',
  body: JSON.stringify({
    "placeholder": "placeholder"
  })
})
.then(function(res) {
  console.log(res.headers.get('CUSTOM_HEADER_NAME'));
})
</code>```

If it makes any difference, this fetch method is called from a function outside the main body of the ReactJS component.

The name of the custom header is Image-Identification-Path, and the header in my response header is Access-Control-Expose-Headers for Image-Identification-Path.

Summary: How do I get my custom header using fetch?

答:
You must configure the server to which the request is sent, such that its response has an Access-Control-Expose-Headers header that has the name of your custom response header.

Otherwise, if your browser doesn’t see the name of your custom header in that Access-Control-Expose-Headers header, it won’t let you access the value of your custom header.

In such a case it’s expected that you’d still be able to see the custom header if you look at the response in Postman or even in your browser devtools.

But just because the browser gets the custom header in the response doesn’t mean the browser will expose it to your frontend JavaScript code.

For cross-origin requests, browsers will only expose that custom response header to your frontend code if that header name is in the Access-Control-Expose-Headers value.

ContentLicense: CC BY-SA 4.0

Body:
I am building a simple web app using ReactJS and create-react-app.

I have a backend API set up on Heroku where I can make POST requests. Everything works fine, except:

When I make a POST request using fetch API, the response is 100% correct but it only gives me 2 standard headers. I want to get my custom header. I have added expose header in my response and here's the plot twist: When I view the headers from Chrome Inspection Tool or Postman (API tool), it shows all the headers, including my custom one. Here is the fetch code I'm using -

fetch(theUrl, {
  method: 'POST',
  body: JSON.stringify({
    "placeholder": "placeholder"
  })
})
.then(function(res) {
  console.log(res.headers.get('CUSTOM_HEADER_NAME'));
})

If it makes any difference, this fetch method is called from a function outside the main body of the ReactJS component.

The name of the custom header is Image-Identification-Path, and the header in my response header is Access-Control-Expose-Headers for Image-Identification-Path.

Summary: How do I get my custom header using fetch?


问:
Removing link reference in browser
I am using the following code to toggle my mobile navigation

html

```<code><a href="#" class="toggle-nav"><p>toggle</p></a>
</code>```

I have a function which attaches the proper code/css and just need it to act as a button but not go anywhere (hence the '#').

However I want nothing to show up when it clicks/hover, since the browser usually indicates where the link is going, I don't want that (or anything else) to show

答:
As Michael suggested, why not try using a button instead? Your code would look like this

```<code><button class="toggle-nav"><p>toggle</p></button>
</code>```

All you'd have to do is change any CSS/JS you have to reference the button instead of an a tag.

ContentLicense: CC BY-SA 3.0

Title: Removing link reference in browser

Body:
I am using the following code to toggle my mobile navigation

html

toggle

I have a function which attaches the proper code/css and just need it to act as a button but not go anywhere (hence the '#').

However I want nothing to show up when it clicks/hover, since the browser usually indicates where the link is going, I don't want that (or anything else) to show

Body:
As Michael suggested, why not try using a button instead? Your code would look like this

<button class="toggle-nav"><p>toggle</p></button>

All you'd have to do is change any CSS/JS you have to reference the button instead of an a tag.


问:
Unexpected value null imported by the module t
I got this strange issue when deploying my  app (a fork of angular2-express-starter) to Heroku. https://totalautosapp.herokuapp.com/
At first i thought it was Heroku, but I've deployed it to netlify and same happens.

It says:

```<code>Error: Unexpected value 'null' imported by the module 't'
</code>```

Yes, there are a lot of similar questions that allowed me to understand the issue a lot better, but what blinds me is the module 't'. What module is it referring to?

And most of the questions state that the unexpected value is 'undefined', not 'null'. which brings me the idea that it is importing a null module, but still don't know which one is doing that, even when it works in devEnvironment.

Here's my app.module.ts

```<code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { AppComponent } from './app.component';
import { routing } from './app.router';
import { effects, store, instrumentation } from './store';
import { SharedModule } from './shared/shared.module';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    SharedModule,
    FormsModule,
    HttpModule,
    store,
    effects,
    routing,
    instrumentation
  ],
   bootstrap: [
    AppComponent
  ]
})
export class AppModule {}
</code>```

And if anyone would take a deep look, here's my shared module: https://codeshare.io/adKKz5

Any help would be well appreciated.

EDIT:

Using console.log I was able to compare outputs from my local build and the heroku one. So I detected that the null module is StoreDevToolsModule from ngrx/store-devtools.

This output is from local run in the line console.log(instrumentation)

```<code>Object { ngModule: StoreDevtoolsModule(), providers: Array[3] }
</code>```

And this one from heroku

```<code>null  main.d61dd7a248d9bbd30ca6.bundle.js:1:5868
</code>```

Error: Unexpected value 'null' imported by the module 't'

答: I was having the same issue, it was caused because my NgModules classes had the "export default" modifier. Look if your modules had the export default and remove the "default" modifier as it's not supported by ngc.</p>

Body:
I got this strange issue when deploying my  app (a fork of angular2-express-starter) to Heroku. https://totalautosapp.herokuapp.com/
At first i thought it was Heroku, but I've deployed it to netlify and same happens.

It says:

Error: Unexpected value 'null' imported by the module 't'

Yes, there are a lot of similar questions that allowed me to understand the issue a lot better, but what blinds me is the module 't'. What module is it referring to?

And most of the questions state that the unexpected value is 'undefined', not 'null'. which brings me the idea that it is importing a null module, but still don't know which one is doing that, even when it works in devEnvironment.

Here's my app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { AppComponent } from './app.component';
import { routing } from './app.router';
import { effects, store, instrumentation } from './store';
import { SharedModule } from './shared/shared.module';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    SharedModule,
    FormsModule,
    HttpModule,
    store,
    effects,
    routing,
    instrumentation
  ],
   bootstrap: [
    AppComponent
  ]
})
export class AppModule {}

And if anyone would take a deep look, here's my shared module: https://codeshare.io/adKKz5

Any help would be well appreciated.

EDIT:

Using console.log I was able to compare outputs from my local build and the heroku one. So I detected that the null module is StoreDevToolsModule from ngrx/store-devtools.

This output is from local run in the line console.log(instrumentation)

Object { ngModule: StoreDevtoolsModule(), providers: Array[3] }

And this one from heroku

null  main.d61dd7a248d9bbd30ca6.bundle.js:1:5868

Error: Unexpected value 'null' imported by the module 't'


问:
bash scripting: How to test list membership
(This is debian squeeze amd64)

I need to test if a file is a member of a list of files.
So long my (test) script is:

```<code>set -x
array=$( ls )
echo $array
FILE=log.out
# This line gives error!
if $FILE in $array
then   echo "success!"
else  echo "bad!"
fi
exit 0
</code>```

¿Any ideas?

Thanks for all the responses. To clarify: The script given is only an example, the actual problem is more complex. In the final solution, it will be done within a loop, so I need the file(name) to be tested for to be in a variable.

Thanks again. No my test-script works, and reads:
```</p>

<code>  in_list() {
       local search="$1"
       shift
       local list=("$@")
       for file in "${list[@]}" ; do
           [[ "$file" == "$search" ]] && return 0
       done
       return 1
    }
    #
    # set -x
    array=( * )  # Array of files in current dir
    # echo $array
    FILE="log.out"
    if in_list "$FILE" "${array[@]}"
    then   echo "success!"
    else  echo "bad!"
    fi
    exit 0
</code>```

答:
```<code>if ls | grep -q -x t1 ; then
  echo Success
else
  echo Failure
fi
</code>```

grep -x matches full lines only, so ls | grep -x only returns something if the file exists.

ContentLicense: CC BY-SA 2.5

Body:
(This is debian squeeze amd64)

I need to test if a file is a member of a list of files.
So long my (test) script is:

set -x
array=$( ls )
echo $array
FILE=log.out
# This line gives error!
if $FILE in $array
then   echo "success!"
else  echo "bad!"
fi
exit 0

¿Any ideas?

Thanks for all the responses. To clarify: The script given is only an example, the actual problem is more complex. In the final solution, it will be done within a loop, so I need the file(name) to be tested for to be in a variable.

Thanks again. No my test-script works, and reads:

  in_list() {
       local search="$1"
       shift
       local list=("$@")
       for file in "${list[@]}" ; do
           [[ "$file" == "$search" ]] && return 0
       done
       return 1
    }
    #
    # set -x
    array=( * )  # Array of files in current dir
    # echo $array
    FILE="log.out"
    if in_list "$FILE" "${array[@]}"
    then   echo "success!"
    else  echo "bad!"
    fi
    exit 0

Body:
if ls | grep -q -x t1 ; then
  echo Success
else
  echo Failure
fi

grep -x matches full lines only, so ls | grep -x only returns something if the file exists.


问:
Adding appointment to outlook default appointment folder as well as shared folder
I would like to add an appointment to the users outlook calendar using VBA, which both shows on the outlook application calendar from which the macro is executed, and also exists in the users shared folder on the exchange server (so that it is displayed on the user's smartphone calendar etc).

At the moment I can achieve either/or:

```<code>Set myOlApp = Application
Set myNamespace = myOlApp.GetNamespace("MAPI")
Set myFolder = myNamespace.GetDefaultFolder(olFolderCalendar)
Set exchFolder = myNamespace.GetSharedDefaultFolder(myOlApp.Session.CurrentUser, olFolderCalendar)
...

Set myAppointment = myOlApp.CreateItem(olAppointmentItem) 'shows in the executing application calendar
'OR
Set myAppointment = exchFolder.items.add(olAppointmentItem) 'shows in the smartphone calendar
'then set whatever details we want for the appointment
With myAppointment
    .ReminderSet = False
    .AllDayEvent = False
    .Sensitivity = olNormal
    .Subject = "on call"
    .Start = onCall(i).Begin
    .Duration = onCall(i).Duration
    .Save
End With
</code>```

Of course, the macro could loop through and create new appointments in both the default calendar folder and also the exchange server folder. However, given each appointment is assigned its own unique ID, this would be a real hack (that is, we end up with 2 appointments representing the same event, but each with a different unique ID).

Is there a way to have the same appointment instance added to the folders collection of both the defaultFolder and the sharedDefaultFolder? If not, is there a good way to ensure both versions of the appointment are exact clones, with the same unique identifiers etc?

答:
The appointment item in outlook has a CopyTo method I was not aware of, so after the save, calling this method and copying to the exchange folder seems to have solved my issues

```<code>Set myAppointment = myOlApp.CreateItem(olAppointmentItem)
With myAppointment
    'all the properties we wish to assign here
    .Save
    .CopyTo exchFolder, olCreateAppointment
End With
</code>```

this answer originally had the olCopyAsAccept option, but I have since discovered this will create a sent mail item for each appointment created by the macro

Body:
I would like to add an appointment to the users outlook calendar using VBA, which both shows on the outlook application calendar from which the macro is executed, and also exists in the users shared folder on the exchange server (so that it is displayed on the user's smartphone calendar etc).

At the moment I can achieve either/or:

Set myOlApp = Application
Set myNamespace = myOlApp.GetNamespace("MAPI")
Set myFolder = myNamespace.GetDefaultFolder(olFolderCalendar)
Set exchFolder = myNamespace.GetSharedDefaultFolder(myOlApp.Session.CurrentUser, olFolderCalendar)
...

Set myAppointment = myOlApp.CreateItem(olAppointmentItem) 'shows in the executing application calendar
'OR
Set myAppointment = exchFolder.items.add(olAppointmentItem) 'shows in the smartphone calendar
'then set whatever details we want for the appointment
With myAppointment
    .ReminderSet = False
    .AllDayEvent = False
    .Sensitivity = olNormal
    .Subject = "on call"
    .Start = onCall(i).Begin
    .Duration = onCall(i).Duration
    .Save
End With

Of course, the macro could loop through and create new appointments in both the default calendar folder and also the exchange server folder. However, given each appointment is assigned its own unique ID, this would be a real hack (that is, we end up with 2 appointments representing the same event, but each with a different unique ID).

Is there a way to have the same appointment instance added to the folders collection of both the defaultFolder and the sharedDefaultFolder? If not, is there a good way to ensure both versions of the appointment are exact clones, with the same unique identifiers etc?

Body:
The appointment item in outlook has a CopyTo method I was not aware of, so after the save, calling this method and copying to the exchange folder seems to have solved my issues

Set myAppointment = myOlApp.CreateItem(olAppointmentItem)
With myAppointment
    'all the properties we wish to assign here
    .Save
    .CopyTo exchFolder, olCreateAppointment
End With

this answer originally had the olCopyAsAccept option, but I have since discovered this will create a sent mail item for each appointment created by the macro


问:
How to call node js function from node js client side
I am playing around with an html template and I have noticed that the developer doesn't use RequireJS or anything else to require and call different functions from other node files. Instead, they used this in the html file to initialise and call the function:

```<code><script src="../../assets.js/test.js"></script>

<script type="text/javascript">
        $(document).ready(function(){
            test.initSomeFunction();
        });
    </script>
</code>```

And I've got the below code in assets/js/test.js which defines initSomeFunction in javascript:

```<code>test = {
  initSomeFunction: function() {
     //Some code
  }

  initAnotherFunction: function() {
     //More code
  }
}
</code>```

(It would be helpful if someone can tell me what this method is called so that I can research it more.)

My problem arises when I try to do the same thing in my node app in the home directory /main.js. The node app works fine on its own but when I add something like this:

```<code>test2 = {
  initMyFunction: function() {
    console.log("I finally decided to work! Good luck...");
  }
}
</code>```

and modify my html file like this:

```<code><script src="../../main.js"></script>

<script type="text/javascript">
        $(document).ready(function(){
            test.initSomeFunction();
            test2.initMyFunction();

        });
    </script>
</code>```

then it won't work. Can someone please point me to the right direction as I don't even know what to Google. I am trying to avoid using RequireJS or anything else as I am a total beginner and the method that the developer used sounds so simple and tempting.

答:
I wish this answer will help you:

I am using express, so I do this to solved your problem!

main.js file's position:

modify app.js add:

```<code>      app.use(express.static(path.join(__dirname, '/')));
</code>```

Then, in the view file:

```<code>         <html>
         <head>
         <script src="public/javascripts/jquery-1.10.2.min.js">       </script>
         <script src="main.js"></script>
         </head>
         <body>

         <script>
          $(function () {
          //test.initSomeFunction();
           test2.initMyFunction();

          })
         </script>
         </body>
         </html>
</code>```

Open the chrome Developer Tools. You will see the result.

Body:
I am playing around with an html template and I have noticed that the developer doesn't use RequireJS or anything else to require and call different functions from other node files. Instead, they used this in the html file to initialise and call the function:

And I've got the below code in assets/js/test.js which defines initSomeFunction in javascript:

test = {
  initSomeFunction: function() {
     //Some code
  }

  initAnotherFunction: function() {
     //More code
  }
}

(It would be helpful if someone can tell me what this method is called so that I can research it more.)

My problem arises when I try to do the same thing in my node app in the home directory /main.js. The node app works fine on its own but when I add something like this:

test2 = {
  initMyFunction: function() {
    console.log("I finally decided to work! Good luck...");
  }
}

and modify my html file like this:

then it won't work. Can someone please point me to the right direction as I don't even know what to Google. I am trying to avoid using RequireJS or anything else as I am a total beginner and the method that the developer used sounds so simple and tempting.

Body:
I wish this answer will help you:

I am using express, so I do this to solved your problem!

main.js file's position:

modify app.js add:

      app.use(express.static(path.join(__dirname, '/')));

Then, in the view file:

         <html>
         <head>
         <script src="public/javascripts/jquery-1.10.2.min.js">       </script>
         <script src="main.js"></script>
         </head>
         <body>

         <script>
          $(function () {
          //test.initSomeFunction();
           test2.initMyFunction();

          })
         </script>
         </body>
         </html>

Open the chrome Developer Tools. You will see the result.


问:
Printing multiple lines with the same "largest" value using awk
I have a file that looks like this:

```<code>3, abc, x
2, def, y
3, ghi, z
</code>```

I want to find the highest value in $1 and print all rows that contain this highest value in $1.

```<code>sort -t, -k1,1n| tail -n1
</code>```

would just give one of the rows that contain 3 in $1, but I need both.

Any suggestions are appreciated (:

答:
I’m not sure if this is the nicest way to get lines while they have the same value with awk, but:

```<code>awk 'NR == 1 { t = $1; print } NR > 1 { if (t != $1) { exit; } print }'
</code>```

which can be combined with sort as follows:

```<code>sort -t, -k1,1nr | awk 'NR == 1 { t = $1; print } NR > 1 { if (t != $1) { exit; } print }'
</code>```

There’s also this, but it does unnecessary work:

```<code>sort -t, -k1,1nr | awk 'NR == 1 { t = $1 } t == $1 { print }'
</code>```

Body:
I have a file that looks like this:

3, abc, x
2, def, y
3, ghi, z

I want to find the highest value in $1 and print all rows that contain this highest value in $1.

sort -t, -k1,1n| tail -n1

would just give one of the rows that contain 3 in $1, but I need both.

Any suggestions are appreciated (:

Body:
I’m not sure if this is the nicest way to get lines while they have the same value with awk, but:

awk 'NR == 1 { t = $1; print } NR > 1 { if (t != $1) { exit; } print }'

which can be combined with sort as follows:

sort -t, -k1,1nr | awk 'NR == 1 { t = $1; print } NR > 1 { if (t != $1) { exit; } print }'

There’s also this, but it does unnecessary work:

sort -t, -k1,1nr | awk 'NR == 1 { t = $1 } t == $1 { print }'


问:
node deprecation warning: Calling an asynchronous function without callback is deprecated
I have a problem trying to run my project on localhost:8080 with reload. So when I try and start my project on localhost it gives me this error:

Deprecation Error

This is not a problem with my project, this exact project was working last week and now none of my projects can run properly. To make sure it wasn't my project I went into the file explorer and opened the index.html file with chrome and it only ran the index.html none of my script being brought in were working. I don't know what to do to fix this. If anyone can help that would be great.

答: I had node v7.8.0 installed which was causing me problems. I uninstalled that version and installed node v6.10.1 which fixed this weird issue. </p>


问:
Python print adds new line and 0
Here's my issue. I'm trying to ssh to Cisco devices and pull information off. When I run my code, the print statement adds a new line with a 0 in it to the bottom of the output. Here is the output of the code followed by the output of the plink CLI input:

```<code>C:\Python30>python PLINKSSHtest.py
Enter your username: josh
Password:
plink -pw nowayjose -ssh nope@1.1.1.1 "show run | inc hostname"
hostname net-R2
0  <------------MY ISSUE

C:\Python30>plink -pw nowayjose -ssh nope@1.1.1.1 "show run | inc hostname"
hostname net-R2
  <------------WHAT I EXPECT
</code>```

Here is my code:

```<code>def read_dev():
    # Print statement here for debugging
    print ("plink -pw " + password + " -ssh " + user + "@" + HOST + " " + command)
    cur_dev = os.system("plink -pw " + password + " -ssh " + user + "@" + HOST + " " + command)
    return(cur_dev)

HOST = None
user = input("Enter your username: ")
password = getpass.getpass()
command = '"show run | inc hostname"'
HOST = '1.1.1.1'
print (read_dev())
</code>```

答: If you want to explicitly set the exit code use sys.exit(cur_dev). Simply using a return value from a function does not do what you want it to.

Title: Python print adds new line and 0

Body:
Here's my issue. I'm trying to ssh to Cisco devices and pull information off. When I run my code, the print statement adds a new line with a 0 in it to the bottom of the output. Here is the output of the code followed by the output of the plink CLI input:

C:\Python30>python PLINKSSHtest.py
Enter your username: josh
Password:
plink -pw nowayjose -ssh nope@1.1.1.1 "show run | inc hostname"
hostname net-R2
0  <------------MY ISSUE

C:\Python30>plink -pw nowayjose -ssh nope@1.1.1.1 "show run | inc hostname"
hostname net-R2
  <------------WHAT I EXPECT

Here is my code:

def read_dev():
    # Print statement here for debugging
    print ("plink -pw " + password + " -ssh " + user + "@" + HOST + " " + command)
    cur_dev = os.system("plink -pw " + password + " -ssh " + user + "@" + HOST + " " + command)
    return(cur_dev)

HOST = None
user = input("Enter your username: ")
password = getpass.getpass()
command = '"show run | inc hostname"'
HOST = '1.1.1.1'
print (read_dev())


问:
C++ do I have to initialize public instance member variable in constructor?
my class has function pointer public instance member variable.(_base_func_ptr)
do I have to initialize '_base_func_ptr' in constructor?
or just skip initialize? </p>

```<code>    class base_cls {
    public:
    #ifdef WHICH_ONE_IS_CORRECT

        base_cls():_base_func_ptr(nullptr), _some1(0), _some2(0) {}

    #else ifdef INITIALIZE_ORDER_IS_REVERSE

        base_cls():_some1(0), _some2(0), _base_func_ptr(nullptr) {}

    #else ifdef JUST_SKIP_INITIALIZE_PUBLIC_MEMBER

        base_cls():_some1(0), _some2(0){}

    #endif

        void (*_base_func_ptr)(void);
    private:
        int _some1;
        int _some2;
    };
</code>```

答: You don't have to initialize it in the constructor but you must initialize it before the variable is used. Otherwise, your program will have undefined behavior.

Body:
my class has function pointer public instance member variable.(_base_func_ptr)
do I have to initialize '_base_func_ptr' in constructor?
or just skip initialize?

    class base_cls {
    public:
    #ifdef WHICH_ONE_IS_CORRECT

        base_cls():_base_func_ptr(nullptr), _some1(0), _some2(0) {}

    #else ifdef INITIALIZE_ORDER_IS_REVERSE

        base_cls():_some1(0), _some2(0), _base_func_ptr(nullptr) {}

    #else ifdef JUST_SKIP_INITIALIZE_PUBLIC_MEMBER

        base_cls():_some1(0), _some2(0){}

    #endif

        void (*_base_func_ptr)(void);
    private:
        int _some1;
        int _some2;
    };


问:
Java Swing/JFrame Listeners
I'm new to Java and I'm trying to make a
simple beginners program that takes in the users
 input of the temperature and outputs it converted
 into celsius. I think I have something hooked up wrong
 with the listeners though because it gives an output but
 it's always zero. I'm not really sure what I did wrong
with the listeners and the action events.

```<code>import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class TemperatureConversionJFrame extends JFrame{
private final JTextField temperatureF;
private final JLabel result;
public int fahrenheit = 0;

public TemperatureConversionJFrame(){
    super("Celsius Conversion");
    setLayout(new FlowLayout());
    temperatureF = new JTextField("Enter temperature in fahrenheit to be converted");
    add(temperatureF);
    result = new JLabel("Result in Celsius");
    add(result);

    TextFieldHandler handler = new TextFieldHandler();

    temperatureF.addActionListener(handler);

}

private class TextFieldHandler implements ActionListener{

 @Override
    public void actionPerformed(java.awt.event.ActionEvent evt){
        int F;
    int results;
            F = Integer.parseInt(temperatureF.getText());
            results = 5/9 * (F - 32);
result.setText(String.valueOf(results));
    }
}

import javax.swing.JFrame;

public class TemperatureConversionJFrameTest
{
public static void main(String[] args)
{
  TemperatureConversionJFrame temperatureConversionJFrame = new  TemperatureConversionJFrame();
            temperatureConversionJFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 temperatureConversionJFrame.setSize(275, 100);
 temperatureConversionJFrame.setVisible(true);
}
</code>```

答:
I think I have something hooked up wrong with the listeners

Well the first thing to do is add a System.out.println(...) to the listener code so see if the listener is invoked.

Assuming it is invoked then I would guess the problem is:

```<code>results = 5/9 * (F - 32);
</code>```

You are doing integer division so 5/9 is always 0.

One fix is to use something like:

```<code>results = (F - 32) * 5 / 9;
</code>```

Also, an ActionListener on the text field is only invoked when the Enter key is pressed.

You may want to consider using a DocumentListener. This is invoked whenever text is added or removed in the text field.

Read the section from the Swing tutorial on How to Write a DocumentListener for more information and examples.

Title: Java Swing/JFrame Listeners

Body:
I'm new to Java and I'm trying to make a
simple beginners program that takes in the users
 input of the temperature and outputs it converted
 into celsius. I think I have something hooked up wrong
 with the listeners though because it gives an output but
 it's always zero. I'm not really sure what I did wrong
with the listeners and the action events.

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class TemperatureConversionJFrame extends JFrame{
private final JTextField temperatureF;
private final JLabel result;
public int fahrenheit = 0;

public TemperatureConversionJFrame(){
    super("Celsius Conversion");
    setLayout(new FlowLayout());
    temperatureF = new JTextField("Enter temperature in fahrenheit to be converted");
    add(temperatureF);
    result = new JLabel("Result in Celsius");
    add(result);

    TextFieldHandler handler = new TextFieldHandler();

    temperatureF.addActionListener(handler);

}

private class TextFieldHandler implements ActionListener{

 @Override
    public void actionPerformed(java.awt.event.ActionEvent evt){
        int F;
    int results;
            F = Integer.parseInt(temperatureF.getText());
            results = 5/9 * (F - 32);
result.setText(String.valueOf(results));
    }
}

import javax.swing.JFrame;

public class TemperatureConversionJFrameTest
{
public static void main(String[] args)
{
  TemperatureConversionJFrame temperatureConversionJFrame = new  TemperatureConversionJFrame();
            temperatureConversionJFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 temperatureConversionJFrame.setSize(275, 100);
 temperatureConversionJFrame.setVisible(true);
}

Body:
I think I have something hooked up wrong with the listeners

Well the first thing to do is add a System.out.println(...) to the listener code so see if the listener is invoked.

Assuming it is invoked then I would guess the problem is:

results = 5/9 * (F - 32);

You are doing integer division so 5/9 is always 0.

One fix is to use something like:

results = (F - 32) * 5 / 9;

Also, an ActionListener on the text field is only invoked when the Enter key is pressed.

You may want to consider using a DocumentListener. This is invoked whenever text is added or removed in the text field.

Read the section from the Swing tutorial on How to Write a DocumentListener for more information and examples.


问:
Preemption to avoid deadlock
I understand the process of using preemption to avoid deadlocks but I'm having a hard time trying to put it in code.

My understanding of preemption to avoid deadlock using threads t1, t2 and resources w, x, y is:

thread t1 -> has resource X. request resource W

thread t2 -> has resources W, Y. request resource X

t1 checks if resource W is free. if it's not free, don't acquire resource X or release it.

t2 executes. Releases resources W, Y, X

t1 executes

How should I go about implementing something like I described above in c++? Any help is appreciated.

答:
One way is through numbering the resources (look at 7.4.4 here):

```<code>w = 1
y = 2
x = 3
</code>```

Then a simple rule: A thread can get a resource only in increasing order.

In other words, in order to request resource Rj, a process must first release all Ri such that i >= j.

thread t1 -> has resource X (value is 3). request resource W (value is 1)  ==> it needs to release X first

thread t2 -> has resources W (value is 1), Y (value is 2). request resource X (value is 3) ==> gets it right after t1 released it

Title: Preemption to avoid deadlock

Body:
One way is through numbering the resources (look at 7.4.4 here):

w = 1
y = 2
x = 3

Then a simple rule: A thread can get a resource only in increasing order.

In other words, in order to request resource Rj, a process must first release all Ri such that i >= j.

thread t1 -> has resource X (value is 3). request resource W (value is 1)  ==> it needs to release X first

thread t2 -> has resources W (value is 1), Y (value is 2). request resource X (value is 3) ==> gets it right after t1 released it


问:
Hibernate ILLEGAL ACCESS ERROR Maria DB Connection
Im trying to Connect to Maria DB from JBOSS Web app.

Im using Datasource for the connection.

my hibernate.cfg file

```<code>    <property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
    <property name="hibernate.connection.driver_class">org.mariadb.jdbc.Driver</property>
 <property name="hibernate.connection.datasource">java:/datasources/KDCDBM</property>
    <property name="hibernate.current_session_context_class">thread</property>
    <property name="hibernate.show_sql">true</property>
    <property name="show_sql">true</property>
    <property name="hbm2dll.auto">update</property>
    <property name="transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>

    <mapping resource="com/mycompany/Contact.hbm.xml"/>
</code>```

When i bring up my app and try to connect . Im getting following error

```<code>13:07:01,387 INFO  [org.hibernate.validator.internal.util.Version] (ServerService Thread Pool -- 60) HV000001: Hibernate Validator 4.3.3.Final-redhat-1
13:07:01,391 ERROR [stderr] (ServerService Thread Pool -- 60) org.hibernate.HibernateException: Error applying BeanValidation relational constraints
13:07:01,391 ERROR [stderr] (ServerService Thread Pool -- 60)   at org.hibernate.cfg.beanvalidation.BeanValidationIntegrator.applyRelationalConstraints(BeanValidationIntegrator.java:219)
13:07:01,391 ERROR [stderr] (ServerService Thread Pool -- 60)   at org.hibernate.cfg.beanvalidation.BeanValidationIntegrator.integrate(BeanValidationIntegrator.java:126)
13:07:01,391 ERROR [stderr] (ServerService Thread Pool -- 60)   at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:301)
13:07:01,392 ERROR [stderr] (ServerService Thread Pool -- 60)   at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1744)
13:07:01,392 ERROR [stderr] (ServerService Thread Pool -- 60)   at com.kony.p2p.services.integration.serviceimpl.batch.CronJobsImpl.startCronJob(CronJobsImpl.java:136)
13:07:01,392 ERROR [stderr] (ServerService Thread Pool -- 60)   at com.kony.p2p.servlet.DBSBatchJobServlet.invokeCronJobs(DBSBatchJobServlet.java:66)
13:07:01,392 ERROR [stderr] (ServerService Thread Pool -- 60)   at com.kony.p2p.servlet.DBSBatchJobServlet.contextInitialized(DBSBatchJobServlet.java:39)
13:07:01,392 ERROR [stderr] (ServerService Thread Pool -- 60)   at org.apache.catalina.core.StandardContext.contextListenerStart(StandardContext.java:3339)
13:07:01,392 ERROR [stderr] (ServerService Thread Pool -- 60)   at org.apache.catalina.core.StandardContext.start(StandardContext.java:3780)
13:07:01,392 ERROR [stderr] (ServerService Thread Pool -- 60)   at org.jboss.as.web.deployment.WebDeploymentService.doStart(WebDeploymentService.java:163)
13:07:01,392 ERROR [stderr] (ServerService Thread Pool -- 60)   at org.jboss.as.web.deployment.WebDeploymentService.access$000(WebDeploymentService.java:61)
13:07:01,392 ERROR [stderr] (ServerService Thread Pool -- 60)   at org.jboss.as.web.deployment.WebDeploymentService$1.run(WebDeploymentService.java:96)
13:07:01,392 ERROR [stderr] (ServerService Thread Pool -- 60)   at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
13:07:01,392 ERROR [stderr] (ServerService Thread Pool -- 60)   at java.util.concurrent.FutureTask.run(FutureTask.java:266)
13:07:01,392 ERROR [stderr] (ServerService Thread Pool -- 60)   at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
13:07:01,393 ERROR [stderr] (ServerService Thread Pool -- 60)   at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
13:07:01,393 ERROR [stderr] (ServerService Thread Pool -- 60)   at java.lang.Thread.run(Thread.java:745)
13:07:01,393 ERROR [stderr] (ServerService Thread Pool -- 60)   at org.jboss.threads.JBossThread.run(JBossThread.java:122)
13:07:01,393 ERROR [stderr] (ServerService Thread Pool -- 60) Caused by: java.lang.reflect.InvocationTargetException
13:07:01,393 ERROR [stderr] (ServerService Thread Pool -- 60)   at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
13:07:01,393 ERROR [stderr] (ServerService Thread Pool -- 60)   at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
13:07:01,393 ERROR [stderr] (ServerService Thread Pool -- 60)   at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
13:07:01,393 ERROR [stderr] (ServerService Thread Pool -- 60)   at java.lang.reflect.Method.invoke(Method.java:498)
13:07:01,393 ERROR [stderr] (ServerService Thread Pool -- 60)   at org.hibernate.cfg.beanvalidation.BeanValidationIntegrator.applyRelationalConstraints(BeanValidationIntegrator.java:208)
13:07:01,393 ERROR [stderr] (ServerService Thread Pool -- 60)   ... 17 more
13:07:01,393 ERROR [stderr] (ServerService Thread Pool -- 60) Caused by: java.lang.IllegalAccessError: tried to access class javax.persistence.Persistence$1 from class javax.persistence.Persistence
13:07:01,394 ERROR [stderr] (ServerService Thread Pool -- 60)   at javax.persistence.Persistence.<clinit>(Persistence.java:87)
13:07:01,394 ERROR [stderr] (ServerService Thread Pool -- 60)   at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
13:07:01,394 ERROR [stderr] (ServerService Thread Pool -- 60)   at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
13:07:01,394 ERROR [stderr] (ServerService Thread Pool -- 60)   at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
13:07:01,394 ERROR [stderr] (ServerService Thread Pool -- 60)   at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
13:07:01,394 ERROR [stderr] (ServerService Thread Pool -- 60)   at java.lang.Class.newInstance(Class.java:442)
13:07:01,394 ERROR [stderr] (ServerService Thread Pool -- 60)   at org.hibernate.validator.internal.util.privilegedactions.NewInstance.run(NewInstance.java:48)
13:07:01,394 ERROR [stderr] (ServerService Thread Pool -- 60)   at org.hibernate.validator.internal.engine.resolver.DefaultTraversableResolver.run(DefaultTraversableResolver.java:156)
13:07:01,394 ERROR [stderr] (ServerService Thread Pool -- 60)   at org.hibernate.validator.internal.engine.resolver.DefaultTraversableResolver.detectJPA(DefaultTraversableResolver.java:101)
13:07:01,394 ERROR [stderr] (ServerService Thread Pool -- 60)   at org.hibernate.validator.internal.engine.resolver.DefaultTraversableResolver.<init>(DefaultTraversableResolver.java:67)
13:07:01,394 ERROR [stderr] (ServerService Thread Pool -- 60)   at org.hibernate.validator.internal.engine.ConfigurationImpl.<init>(ConfigurationImpl.java:74)
13:07:01,394 ERROR [stderr] (ServerService Thread Pool -- 60)   at org.hibernate.validator.HibernateValidator.createGenericConfiguration(HibernateValidator.java:41)
13:07:01,394 ERROR [stderr] (ServerService Thread Pool -- 60)   at javax.validation.Validation$GenericBootstrapImpl.configure(Validation.java:269)
13:07:01,395 ERROR [stderr] (ServerService Thread Pool -- 60)   at javax.validation.Validation.buildDefaultValidatorFactory(Validation.java:111)
13:07:01,395 ERROR [stderr] (ServerService Thread Pool -- 60)   at org.hibernate.cfg.beanvalidation.TypeSafeActivator.getValidatorFactory(TypeSafeActivator.java:521)
13:07:01,395 ERROR [stderr] (ServerService Thread Pool -- 60)   at org.hibernate.cfg.beanvalidation.TypeSafeActivator.applyDDL(TypeSafeActivator.java:119)
13:07:01,395 ERROR [stderr] (ServerService Thread Pool -- 60)   ... 22 more
</code>```

答:
This property Fixed my issue ..

none

Body:
Im trying to Connect to Maria DB from JBOSS Web app.

Im using Datasource for the connection.

my hibernate.cfg file

    <property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
    <property name="hibernate.connection.driver_class">org.mariadb.jdbc.Driver</property>
 <property name="hibernate.connection.datasource">java:/datasources/KDCDBM</property>
    <property name="hibernate.current_session_context_class">thread</property>
    <property name="hibernate.show_sql">true</property>
    <property name="show_sql">true</property>
    <property name="hbm2dll.auto">update</property>
    <property name="transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>

    <mapping resource="com/mycompany/Contact.hbm.xml"/>

When i bring up my app and try to connect . Im getting following error

13:07:01,387 INFO  [org.hibernate.validator.internal.util.Version] (ServerService Thread Pool -- 60) HV000001: Hibernate Validator 4.3.3.Final-redhat-1
13:07:01,391 ERROR [stderr] (ServerService Thread Pool -- 60) org.hibernate.HibernateException: Error applying BeanValidation relational constraints
13:07:01,391 ERROR [stderr] (ServerService Thread Pool -- 60)   at org.hibernate.cfg.beanvalidation.BeanValidationIntegrator.applyRelationalConstraints(BeanValidationIntegrator.java:219)
13:07:01,391 ERROR [stderr] (ServerService Thread Pool -- 60)   at org.hibernate.cfg.beanvalidation.BeanValidationIntegrator.integrate(BeanValidationIntegrator.java:126)
13:07:01,391 ERROR [stderr] (ServerService Thread Pool -- 60)   at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:301)
13:07:01,392 ERROR [stderr] (ServerService Thread Pool -- 60)   at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1744)
13:07:01,392 ERROR [stderr] (ServerService Thread Pool -- 60)   at com.kony.p2p.services.integration.serviceimpl.batch.CronJobsImpl.startCronJob(CronJobsImpl.java:136)
13:07:01,392 ERROR [stderr] (ServerService Thread Pool -- 60)   at com.kony.p2p.servlet.DBSBatchJobServlet.invokeCronJobs(DBSBatchJobServlet.java:66)
13:07:01,392 ERROR [stderr] (ServerService Thread Pool -- 60)   at com.kony.p2p.servlet.DBSBatchJobServlet.contextInitialized(DBSBatchJobServlet.java:39)
13:07:01,392 ERROR [stderr] (ServerService Thread Pool -- 60)   at org.apache.catalina.core.StandardContext.contextListenerStart(StandardContext.java:3339)
13:07:01,392 ERROR [stderr] (ServerService Thread Pool -- 60)   at org.apache.catalina.core.StandardContext.start(StandardContext.java:3780)
13:07:01,392 ERROR [stderr] (ServerService Thread Pool -- 60)   at org.jboss.as.web.deployment.WebDeploymentService.doStart(WebDeploymentService.java:163)
13:07:01,392 ERROR [stderr] (ServerService Thread Pool -- 60)   at org.jboss.as.web.deployment.WebDeploymentService.access$000(WebDeploymentService.java:61)
13:07:01,392 ERROR [stderr] (ServerService Thread Pool -- 60)   at org.jboss.as.web.deployment.WebDeploymentService$1.run(WebDeploymentService.java:96)
13:07:01,392 ERROR [stderr] (ServerService Thread Pool -- 60)   at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
13:07:01,392 ERROR [stderr] (ServerService Thread Pool -- 60)   at java.util.concurrent.FutureTask.run(FutureTask.java:266)
13:07:01,392 ERROR [stderr] (ServerService Thread Pool -- 60)   at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
13:07:01,393 ERROR [stderr] (ServerService Thread Pool -- 60)   at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
13:07:01,393 ERROR [stderr] (ServerService Thread Pool -- 60)   at java.lang.Thread.run(Thread.java:745)
13:07:01,393 ERROR [stderr] (ServerService Thread Pool -- 60)   at org.jboss.threads.JBossThread.run(JBossThread.java:122)
13:07:01,393 ERROR [stderr] (ServerService Thread Pool -- 60) Caused by: java.lang.reflect.InvocationTargetException
13:07:01,393 ERROR [stderr] (ServerService Thread Pool -- 60)   at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
13:07:01,393 ERROR [stderr] (ServerService Thread Pool -- 60)   at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
13:07:01,393 ERROR [stderr] (ServerService Thread Pool -- 60)   at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
13:07:01,393 ERROR [stderr] (ServerService Thread Pool -- 60)   at java.lang.reflect.Method.invoke(Method.java:498)
13:07:01,393 ERROR [stderr] (ServerService Thread Pool -- 60)   at org.hibernate.cfg.beanvalidation.BeanValidationIntegrator.applyRelationalConstraints(BeanValidationIntegrator.java:208)
13:07:01,393 ERROR [stderr] (ServerService Thread Pool -- 60)   ... 17 more
13:07:01,393 ERROR [stderr] (ServerService Thread Pool -- 60) Caused by: java.lang.IllegalAccessError: tried to access class javax.persistence.Persistence$1 from class javax.persistence.Persistence
13:07:01,394 ERROR [stderr] (ServerService Thread Pool -- 60)   at javax.persistence.Persistence.<clinit>(Persistence.java:87)
13:07:01,394 ERROR [stderr] (ServerService Thread Pool -- 60)   at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
13:07:01,394 ERROR [stderr] (ServerService Thread Pool -- 60)   at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
13:07:01,394 ERROR [stderr] (ServerService Thread Pool -- 60)   at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
13:07:01,394 ERROR [stderr] (ServerService Thread Pool -- 60)   at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
13:07:01,394 ERROR [stderr] (ServerService Thread Pool -- 60)   at java.lang.Class.newInstance(Class.java:442)
13:07:01,394 ERROR [stderr] (ServerService Thread Pool -- 60)   at org.hibernate.validator.internal.util.privilegedactions.NewInstance.run(NewInstance.java:48)
13:07:01,394 ERROR [stderr] (ServerService Thread Pool -- 60)   at org.hibernate.validator.internal.engine.resolver.DefaultTraversableResolver.run(DefaultTraversableResolver.java:156)
13:07:01,394 ERROR [stderr] (ServerService Thread Pool -- 60)   at org.hibernate.validator.internal.engine.resolver.DefaultTraversableResolver.detectJPA(DefaultTraversableResolver.java:101)
13:07:01,394 ERROR [stderr] (ServerService Thread Pool -- 60)   at org.hibernate.validator.internal.engine.resolver.DefaultTraversableResolver.<init>(DefaultTraversableResolver.java:67)
13:07:01,394 ERROR [stderr] (ServerService Thread Pool -- 60)   at org.hibernate.validator.internal.engine.ConfigurationImpl.<init>(ConfigurationImpl.java:74)
13:07:01,394 ERROR [stderr] (ServerService Thread Pool -- 60)   at org.hibernate.validator.HibernateValidator.createGenericConfiguration(HibernateValidator.java:41)
13:07:01,394 ERROR [stderr] (ServerService Thread Pool -- 60)   at javax.validation.Validation$GenericBootstrapImpl.configure(Validation.java:269)
13:07:01,395 ERROR [stderr] (ServerService Thread Pool -- 60)   at javax.validation.Validation.buildDefaultValidatorFactory(Validation.java:111)
13:07:01,395 ERROR [stderr] (ServerService Thread Pool -- 60)   at org.hibernate.cfg.beanvalidation.TypeSafeActivator.getValidatorFactory(TypeSafeActivator.java:521)
13:07:01,395 ERROR [stderr] (ServerService Thread Pool -- 60)   at org.hibernate.cfg.beanvalidation.TypeSafeActivator.applyDDL(TypeSafeActivator.java:119)
13:07:01,395 ERROR [stderr] (ServerService Thread Pool -- 60)   ... 22 more

Body:
This property Fixed my issue ..

none


问:
Why do we need curies in Spring HATEOAS
I have basic understanding of what Spring's HATEOAS is, and also those basic HETEOAS links, like:

```<code> _links : {
     self: { href: "http://myhost/person/1" }
}
</code>```

I tried to search online but i can't really get a grasp of what curies is in HATEOAS. I can't understand the need of its existence. Why is it needed?

```<code>  curies: {
     name: "ex",
     href: "http://example.com/rels/{rel}",
     templated: true
},
</code>```

答:
CURIEs provide a shortcut or template for linking to API documentation within a HAL based API response.

Read more at https://www.mikestowe.com/blog/2015/01/what-the-heck-are-curies.php

Title: Why do we need curies in Spring HATEOAS

Body:
I have basic understanding of what Spring's HATEOAS is, and also those basic HETEOAS links, like:

 _links : {
     self: { href: "http://myhost/person/1" }
}

I tried to search online but i can't really get a grasp of what curies is in HATEOAS. I can't understand the need of its existence. Why is it needed?

  curies: {
     name: "ex",
     href: "http://example.com/rels/{rel}",
     templated: true
},


问:
execute javascript after focused on an element
I need to run execFunc(); not only when the user moves onto the next field, but also runs when the user remains focused on the same field for 5 seconds.

```<code>$('input[name="email"]').bind('blur', function () {
 execFunc();
});
</code>```

答:
```<code>var timer = null;
$('input[name="email"]').blur(function(e){
  if (timer) clearTimeout(timer);
  execFunc();
}).focus(function(e){
  timer = setTimeout(execFunc, 5000);
});
</code>```

If you're doing form validation, there are better ways of doing this.

Body:
I need to run execFunc(); not only when the user moves onto the next field, but also runs when the user remains focused on the same field for 5 seconds.

$('input[name="email"]').bind('blur', function () {
 execFunc();
});

Body:
var timer = null;
$('input[name="email"]').blur(function(e){
  if (timer) clearTimeout(timer);
  execFunc();
}).focus(function(e){
  timer = setTimeout(execFunc, 5000);
});

If you're doing form validation, there are better ways of doing this.


问:
Function definition not found?
I'm trying to define the function "getCurSize" but for some reason even though I define it below it, it is not recognizing the definition and is underlined in green. (Beginner here so patience appreciated)</p>

```<code>template<class ItemType>
class FDHPolynomial
{
private:
    FDHNode<ItemType>* headPtr;
    int itemcount;
    FDHNode<ItemType>* getPointedTo(const ItemType& nodenum) const;

public:
    FDHPolynomial();
    FDHPolynomial(const FDHPolynomial <ItemType>& aPoly);
    virtual ~FDHPolynomial();

    int getCurSize() const;
    bool isEmpty() const;
    bool add(const ItemType& newCoeffi, const ItemType& newExpon);
    bool remove(const ItemType& anExpon);
    void clear();
    bool contains(const ItemType& aExpon) const;
    ItemType degree() const;
    ItemType coefficient(const ItemType& power) const;
    void changeCoefficient(const ItemType& newCoeffi, const ItemType&power);
    std::vector<ItemType> toVector() const;

void print();

};

template<class ItemType>
int Polynomial<ItemType>::getCurSize() const
{
    return itemCount;
}
</code>```

答:
Your scope operator (::) cannot match Polynomial<ItemType>::getCurSize() const to any function declared, because Polynomial does not exist as a class. Because class FDHPolynomial has a getCurSize() const function, change your definition to this:

```<code>template<class ItemType>
int FDHPolynomial<ItemType>::getCurSize() const {
    return itemCount;
}
</code>```

Title: Function definition not found?

Body:
I'm trying to define the function "getCurSize" but for some reason even though I define it below it, it is not recognizing the definition and is underlined in green. (Beginner here so patience appreciated)

template<class ItemType>
class FDHPolynomial
{
private:
    FDHNode<ItemType>* headPtr;
    int itemcount;
    FDHNode<ItemType>* getPointedTo(const ItemType& nodenum) const;

public:
    FDHPolynomial();
    FDHPolynomial(const FDHPolynomial <ItemType>& aPoly);
    virtual ~FDHPolynomial();

    int getCurSize() const;
    bool isEmpty() const;
    bool add(const ItemType& newCoeffi, const ItemType& newExpon);
    bool remove(const ItemType& anExpon);
    void clear();
    bool contains(const ItemType& aExpon) const;
    ItemType degree() const;
    ItemType coefficient(const ItemType& power) const;
    void changeCoefficient(const ItemType& newCoeffi, const ItemType&power);
    std::vector<ItemType> toVector() const;

void print();

};

template<class ItemType>
int Polynomial<ItemType>::getCurSize() const
{
    return itemCount;
}

Body:
Your scope operator (::) cannot match Polynomial<ItemType>::getCurSize() const to any function declared, because Polynomial does not exist as a class. Because class FDHPolynomial has a getCurSize() const function, change your definition to this:

template<class ItemType>
int FDHPolynomial<ItemType>::getCurSize() const {
    return itemCount;
}


问:
Adding a complete row to a table from a DAO.Recordset
I have an access table containing product information with 100 Columns (it is a bought system so not of my creation). I want to be able to copy a row and insert it as a new row with 3 fields updated. I am using VBA on an access DB.

I am selecting the row I want to copy (Select Product.* FROM .....) and putting it into a DAO.Recordset. This works fine. I then want to insert this data back into the table as a new row with all the same data apart from the Product ID (key) and the Product short description.

As there is 100 columns I am trying to avoid typing in all the column names and assigning the values individually. Is there a way to insert from a DAO.Recordset so I can avoid typing in all the columns?  if not is there another way to avoid typing in all the columns and all the values? It would save me a very big insert statement!

Many thanks

Tony

答:
If you are trying to insert it back into the same table then you can do it without puling it into a recordset at all.

You just need to write the correct SQL query and execute it.

The data that you select will be the recordset that you are already pulling with the updated values.

For instance:

```<code>INSERT INTO tableX(field1, productId, productDesc)
SELECT field1, 777 as productId, "NewString" as productDesc
FROM tableX
WHERE productId=7
</code>```

Another approach which I mentioned in comments would be to loop through each of the fields to build your string used as the SQL command, the execution of this would be a lot faster then processing record by record. (such as inserting a new product for each order in an orders table where another product has already been ordered, which could have 10s of 1000s of orders)

```<code>'Edited the code supplied by another response above'
Sub CopyProductRow()

    Dim sFld, iField, sqlQuery As String

    i= "INSERT INTO products("
    s= "SELECT "
    w= "WHERE ProductID = 7"
    For Each fld In rsSrc.Fields
        Select Case fld.Name 'Check the field name'
            ' special cases'
            Case "ProductID": 'If field is Product ID'
                  iFld = "777 as ProductID" '777 will be the product id returned by the select query (therefore inserted)'
            Case "ProductDesc": 'If field is Product Description '
                         'The description below will be selected / inserted instead.'
                  iFld = "'New Product Description' as ProductDesc"
            Case Else:
                  iFld = fld.Name 'No change just select the field and insert as is.'
        End Select

        i = i & ", " & fld.Name
        s = s & ", " & iFld
    Next fld

    'Build complete query (removing the first comma in the select statement)'
    sqlQuery = i & ") " & replace(s, "SELECT ,", "SELECT ") & " " &w

    'Resulting in a string such as the following'
    'INSERT INTO products(field1,field2, productId, productDesc, field5, ...)'
    'SELECT field1, field2, 777 as ProductID, 'New Product Description' as ProductDesc, field5, ...'
    'FROM tableX'
    'WHERE productId=7'

    'Print the query to immediate window
    Debug.print sqlQuery

    'Execute the query'
    currentdb.execute sqlQuery
End Sub
</code>```

Body:
If you are trying to insert it back into the same table then you can do it without puling it into a recordset at all.

You just need to write the correct SQL query and execute it.

The data that you select will be the recordset that you are already pulling with the updated values.

For instance:

INSERT INTO tableX(field1, productId, productDesc)
SELECT field1, 777 as productId, "NewString" as productDesc
FROM tableX
WHERE productId=7

Another approach which I mentioned in comments would be to loop through each of the fields to build your string used as the SQL command, the execution of this would be a lot faster then processing record by record. (such as inserting a new product for each order in an orders table where another product has already been ordered, which could have 10s of 1000s of orders)

'Edited the code supplied by another response above'
Sub CopyProductRow()

    Dim sFld, iField, sqlQuery As String

    i= "INSERT INTO products("
    s= "SELECT "
    w= "WHERE ProductID = 7"
    For Each fld In rsSrc.Fields
        Select Case fld.Name 'Check the field name'
            ' special cases'
            Case "ProductID": 'If field is Product ID'
                  iFld = "777 as ProductID" '777 will be the product id returned by the select query (therefore inserted)'
            Case "ProductDesc": 'If field is Product Description '
                         'The description below will be selected / inserted instead.'
                  iFld = "'New Product Description' as ProductDesc"
            Case Else:
                  iFld = fld.Name 'No change just select the field and insert as is.'
        End Select

        i = i & ", " & fld.Name
        s = s & ", " & iFld
    Next fld

    'Build complete query (removing the first comma in the select statement)'
    sqlQuery = i & ") " & replace(s, "SELECT ,", "SELECT ") & " " &w

    'Resulting in a string such as the following'
    'INSERT INTO products(field1,field2, productId, productDesc, field5, ...)'
    'SELECT field1, field2, 777 as ProductID, 'New Product Description' as ProductDesc, field5, ...'
    'FROM tableX'
    'WHERE productId=7'

    'Print the query to immediate window
    Debug.print sqlQuery

    'Execute the query'
    currentdb.execute sqlQuery
End Sub


问:
C++ Issue Using Getline
I'm trying to create a program in which the user can enter a series of player names and scores and read them back. However, I'm having trouble storing their input using getline. On getline in the InputData function, visual studio states, "Error: no instance of overloaded function "getline" matches the argument list          argument types are: (std::istream, char)", and on ==, it says, "Error: operand types are incompatible ("char" and "const char *")". Here is my code: </p>

```<code>#include <iostream>
#include <string>

using namespace std;

int InputData(string [], int [], int);
void DisplayPlayerData(string [], int [], int);

void main()
{
    string playerNames[100];
    int scores[100];

    int sizeOfArray = sizeof(scores);
    int sizeOfEachElement = sizeof(scores[0]);
    int numberOfElements = sizeOfArray / sizeOfEachElement;

    cout << numberOfElements;

    int numberEntered = InputData(playerNames, scores, numberOfElements);

    DisplayPlayerData(playerNames, scores, numberOfElements);

    cin.ignore();
    cin.get();
}

int InputData(string playerNames, int scores[], int size)
{
    int index;

    for (index = 0; index < size; index++)
    {
        cout << "Enter Player Name (Q to quit): ";
        getline(cin, playerNames[index]);
        if (playerNames[index] == "Q")
        {
            break;
        }
        cout << "Enter score: ";
        cin >> scores[index];
    }

    return index;
}
</code>```

答:
Error: no instance of overloaded function "getline" matches the argument list argument types are: (std::istream, char)"

This means that you are passing a single char value to getline() instead of the entire string. You do this in:

```<code>getline(cin, playerNames[index])
</code>```

You pass playernames as a string variable instead of a sting[] array. So, when you do playernames[index], you are trying to pass a single char value to the function.

Judging from the code in your main() function, you want to pass an array of strings to the function, not just an individual string.

Therefore, change the arguments of InputData()

```<code>int InputData(string playerNames, int scores[], int size)
</code>```

To:

```<code>int InputData(string playerNames[], int scores[], int size)
</code>```

**@Pinky beat me to posting the answer first :), but I wanted to provide some more details, so I've posted my answer.

Another thing, aside from your main question that I wanted to just point out, you should change the return data type of your main() function to int main() from void main().

Title: C++ Issue Using Getline

Body:
I'm trying to create a program in which the user can enter a series of player names and scores and read them back. However, I'm having trouble storing their input using getline. On getline in the InputData function, visual studio states, "Error: no instance of overloaded function "getline" matches the argument list          argument types are: (std::istream, char)", and on ==, it says, "Error: operand types are incompatible ("char" and "const char *")". Here is my code:

#include <iostream>
#include <string>

using namespace std;

int InputData(string [], int [], int);
void DisplayPlayerData(string [], int [], int);

void main()
{
    string playerNames[100];
    int scores[100];

    int sizeOfArray = sizeof(scores);
    int sizeOfEachElement = sizeof(scores[0]);
    int numberOfElements = sizeOfArray / sizeOfEachElement;

    cout << numberOfElements;

    int numberEntered = InputData(playerNames, scores, numberOfElements);

    DisplayPlayerData(playerNames, scores, numberOfElements);

    cin.ignore();
    cin.get();
}

int InputData(string playerNames, int scores[], int size)
{
    int index;

    for (index = 0; index < size; index++)
    {
        cout << "Enter Player Name (Q to quit): ";
        getline(cin, playerNames[index]);
        if (playerNames[index] == "Q")
        {
            break;
        }
        cout << "Enter score: ";
        cin >> scores[index];
    }

    return index;
}

Body:
Error: no instance of overloaded function "getline" matches the argument list argument types are: (std::istream, char)"

This means that you are passing a single char value to getline() instead of the entire string. You do this in:

getline(cin, playerNames[index])

You pass playernames as a string variable instead of a sting[] array. So, when you do playernames[index], you are trying to pass a single char value to the function.

Judging from the code in your main() function, you want to pass an array of strings to the function, not just an individual string.

Therefore, change the arguments of InputData()

int InputData(string playerNames, int scores[], int size)

To:

int InputData(string playerNames[], int scores[], int size)

**@Pinky beat me to posting the answer first :), but I wanted to provide some more details, so I've posted my answer.

Another thing, aside from your main question that I wanted to just point out, you should change the return data type of your main() function to int main() from void main().


问:
Using NSCoding appropriately in a grandparent-parent-child data model relationships
I have a grandparent, parent and child model relationship (the Orchestra class model object, which contains many Sections, and each contains many Players). In other words, the Orchestra object has property called var allSections: [Section], and the Section object has a property called var allPlayers: [Player]

My goal is to persist the data for all three models using NSCoding. I am confused about whether I should conform to NSCoding for (A) all 3 classes, (B) only the child class, or (C) all the classes besides the child class? One source of my confusion is the fact that [NSCoding is recrusive][1].

So far, I have implemented the standard NSCoding protocol methods for Player:

```<code>func encode(with aCoder: NSCoder) {
        aCoder.encode(name, forKey: "playerName")
        aCoder.encode(id, forKey: "playerId")
        aCoder.encode(playerStatus, forKey: "playerStatus")
        aCoder.encode(playerPosition, forKey: "playerPosition")

    }

    required init(coder aDecoder: NSCoder) {

        name = aDecoder.decodeObject(forKey: "playerName") as! String
        id = aDecoder.decodeObject(forKey: "playerId") as! String
        playerStatus = aDecoder.decodeObject(forKey: "playerStatus") as! PlayerStatus
        playerPosition = aDecoder.decodeObject(forKey: "playerPosition") as! PlayerPosition

        super.init()

    }
</code>```

And in the init method for Section I will call:

```<code>if let archivedItems = NSKeyedUnarchiver.unarchiveObject(withFile: itemArchivalURL.path) as? [Item] {
            allPlayers = archivedItems
        }
</code>```

答:
All 3 must conform to NSCoding if you wish to archive an instance of an Orchestra.

If you only want to archive a Section instance that only Section and Player must conform to NSCoding.

Think of it this way. Whatever object you wish to archive must itself conform to NSCoding. And anything you need to encode/decode in that class must also conform to NSCoding. And that needs to hold true all the way for all classes that will ultimately need to be encoded/decoded.

Body:
I have a grandparent, parent and child model relationship (the Orchestra class model object, which contains many Sections, and each contains many Players). In other words, the Orchestra object has property called var allSections: [Section], and the Section object has a property called var allPlayers: [Player]

My goal is to persist the data for all three models using NSCoding. I am confused about whether I should conform to NSCoding for (A) all 3 classes, (B) only the child class, or (C) all the classes besides the child class? One source of my confusion is the fact that [NSCoding is recrusive][1].

So far, I have implemented the standard NSCoding protocol methods for Player:

func encode(with aCoder: NSCoder) {
        aCoder.encode(name, forKey: "playerName")
        aCoder.encode(id, forKey: "playerId")
        aCoder.encode(playerStatus, forKey: "playerStatus")
        aCoder.encode(playerPosition, forKey: "playerPosition")

    }

    required init(coder aDecoder: NSCoder) {

        name = aDecoder.decodeObject(forKey: "playerName") as! String
        id = aDecoder.decodeObject(forKey: "playerId") as! String
        playerStatus = aDecoder.decodeObject(forKey: "playerStatus") as! PlayerStatus
        playerPosition = aDecoder.decodeObject(forKey: "playerPosition") as! PlayerPosition

        super.init()

    }

And in the init method for Section I will call:

if let archivedItems = NSKeyedUnarchiver.unarchiveObject(withFile: itemArchivalURL.path) as? [Item] {
            allPlayers = archivedItems
        }


问:
Configure Android hash for Facebook on Windows for Titanium/ Alloy/ Appcelerator
I am trying to to add Facebook login on Android as described here: https://docs.appcelerator.com/platform/latest/#!/api/Modules.Facebook

I followed the instructions, however when I attempt to login, it say "No Android key hashes are configured".

On the following link: https://github.com/appcelerator-modules/ti.facebook it says to use the following command to create the hash:

```<code>keytool -exportcert -alias androiddebugkey -keystore ~/Library/Application\ Support/Titanium/mobilesdk/osx/6.0.3.GA/dev_keystore | openssl sha1 -binary | openssl base64
</code>```

However, I am using windows, and the above seems suited to OSX.

I believe only the following portions needs to be adjusted:

```<code>-keystore ~/Library/Application\ Support/Titanium/mobilesdk/osx/6.0.3.GA/dev_keystore
</code>```

But it's not clear what they should be changed to.

Therefore my question is how do I configure my Android Hash for Facebook on Windows?

答:
After a lot of research and experimentation I found that the command is actually as follows:

```<code>keytool -exportcert -alias tidev -keystore C:\ProgramData\Titanium\mobilesdk\win32\<version>\android\dev_keystore | openssl sha1 -binary | openssl base64
</code>```

with password tirocks

Note that it should be tidev instead of androiddebugkey.

It should also be C:\ProgramData\Titanium\mobilesdk\win32\<version>\android\dev_keystore instead of ~/Library/Application\ Support/Titanium/mobilesdk/osx/6.0.3.GA/dev_keystore.

Body:
I am trying to to add Facebook login on Android as described here: https://docs.appcelerator.com/platform/latest/#!/api/Modules.Facebook

I followed the instructions, however when I attempt to login, it say "No Android key hashes are configured".

On the following link: https://github.com/appcelerator-modules/ti.facebook it says to use the following command to create the hash:

keytool -exportcert -alias androiddebugkey -keystore ~/Library/Application\ Support/Titanium/mobilesdk/osx/6.0.3.GA/dev_keystore | openssl sha1 -binary | openssl base64

However, I am using windows, and the above seems suited to OSX.

I believe only the following portions needs to be adjusted:

-keystore ~/Library/Application\ Support/Titanium/mobilesdk/osx/6.0.3.GA/dev_keystore

But it's not clear what they should be changed to.

Therefore my question is how do I configure my Android Hash for Facebook on Windows?

Body:
After a lot of research and experimentation I found that the command is actually as follows:

keytool -exportcert -alias tidev -keystore C:\ProgramData\Titanium\mobilesdk\win32\<version>\android\dev_keystore | openssl sha1 -binary | openssl base64

with password tirocks

Note that it should be tidev instead of androiddebugkey.

It should also be C:\ProgramData\Titanium\mobilesdk\win32\<version>\android\dev_keystore instead of ~/Library/Application\ Support/Titanium/mobilesdk/osx/6.0.3.GA/dev_keystore.


问:
When assigning a PHP.ini Firefox 3.6x is not displaying a response page when there is a php exception
I hope I can be brief and still allow you to understand the actual problem.
Here goes:

```<code>[Environment]
Windows 7 Premium 64bit
IIS 7.0
PHP 5.3.3 VC9 Nonthread safe ZIP
mysql 5

[Description of the Problem]
Installed PHP to C:\PHP
</code>```

When no defined "PHP.ini" is set in the C:\PHP folder, Firefox / IE, is able to load PHP files and display PHP exceptions fine.

this is displayed when view phpinfo();

```<code>Configuration File (php.ini)
Path       C:\Windows
Loaded Configuration File       (none)
</code>```

When I modified the PHP.ini-development to PHP.ini -- this is where the problem is.
IE 7, 8 displays PHP exceptions just fine
Firefox displays PHP pages, but not the exceptions... Where there is an exceptions, it just displays blank page or does not load the page at all.
it just looks like the browser is refreshing.

this is what phpinfo(); displays:

```<code>Configuration File (php.ini) Path       C:\Windows
Loaded Configuration File       C:\PHP\php.ini
</code>```

So to reiterate, with PHP.ini loaded, Firefox is not displaying any errors generated by PHP (exceptions and not user generated errors)

I've googled and only found one post about this with no solution or any leads to go on.
https://bugs.launchpad.net/ubuntu/+source/firefox-3.0/+bug/244432

attached is my php.ini file if that matters
as well as IE8 screen and FF screen. (FF screen is blank which is the problem)

[sorry can't post links since i am new]

thanks in advance.

[update 11/30 @ 19:31 ET]
@Viper_SB, you're correct. After taking your suggestion of download HTTP headers, the following is captured:

GET /admin/phperror.php HTTP/1.1
Host: localhost:801
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.12) Gecko/20101026 Firefox/3.6.12 FirePHP/0.5
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 115
Connection: keep-alive
x-insight: activate

HTTP/1.1 500 Internal Server Error
Server: Microsoft-IIS/7.5
X-Powered-By: ASP.NET
Date: Wed, 01 Dec 2010 00:33:36 GMT
Content-Length: 129

But still, nothing is displayed:

答:
I'm going to assume here that you DO have error_reporting enabled and setup correctly in php.ini.

Do you have the FF extension Live HTTP headers? If not install it and open the window, then run the page that doesn't work. Check the headers does it say:

```<code>HTTP/1.1 500 Server Error
</code>```

If so your browser (or some other application) could be hiding the real the problem because it's saying it's an error. A lot of times browsers will try to display a friendly error to you if there is a 500 error (or 404 etc...)

The new AVG toolbar WILL cause this problem, but it'd do it in IE and in FF.

Body:
I hope I can be brief and still allow you to understand the actual problem.
Here goes:

[Environment]
Windows 7 Premium 64bit
IIS 7.0
PHP 5.3.3 VC9 Nonthread safe ZIP
mysql 5

[Description of the Problem]
Installed PHP to C:\PHP

When no defined "PHP.ini" is set in the C:\PHP folder, Firefox / IE, is able to load PHP files and display PHP exceptions fine.

this is displayed when view phpinfo();

Configuration File (php.ini)
Path       C:\Windows
Loaded Configuration File       (none)

When I modified the PHP.ini-development to PHP.ini -- this is where the problem is.
IE 7, 8 displays PHP exceptions just fine
Firefox displays PHP pages, but not the exceptions... Where there is an exceptions, it just displays blank page or does not load the page at all.
it just looks like the browser is refreshing.

this is what phpinfo(); displays:

Configuration File (php.ini) Path       C:\Windows
Loaded Configuration File       C:\PHP\php.ini

So to reiterate, with PHP.ini loaded, Firefox is not displaying any errors generated by PHP (exceptions and not user generated errors)

I've googled and only found one post about this with no solution or any leads to go on.
https://bugs.launchpad.net/ubuntu/+source/firefox-3.0/+bug/244432

attached is my php.ini file if that matters
as well as IE8 screen and FF screen. (FF screen is blank which is the problem)

[sorry can't post links since i am new]

thanks in advance.

[update 11/30 @ 19:31 ET]
@Viper_SB, you're correct. After taking your suggestion of download HTTP headers, the following is captured:

GET /admin/phperror.php HTTP/1.1
Host: localhost:801
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.12) Gecko/20101026 Firefox/3.6.12 FirePHP/0.5
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 115
Connection: keep-alive
x-insight: activate

HTTP/1.1 500 Internal Server Error
Server: Microsoft-IIS/7.5
X-Powered-By: ASP.NET
Date: Wed, 01 Dec 2010 00:33:36 GMT
Content-Length: 129

But still, nothing is displayed:

Body:
I'm going to assume here that you DO have error_reporting enabled and setup correctly in php.ini.

Do you have the FF extension Live HTTP headers? If not install it and open the window, then run the page that doesn't work. Check the headers does it say:

HTTP/1.1 500 Server Error

If so your browser (or some other application) could be hiding the real the problem because it's saying it's an error. A lot of times browsers will try to display a friendly error to you if there is a 500 error (or 404 etc...)

The new AVG toolbar WILL cause this problem, but it'd do it in IE and in FF.


问:
What does the this code in socket.io mean
I am new to real-time programming using socket.io and node.js. I have seen this code from a blog site unfortunately did not post any comment or explanation about the code below:

```<code>socket.on( 'new_message', function( data ) {
  io.sockets.emit( 'new_message', {
    name: data.name,
    address : data.address
 });
});
</code>```

I have checked the socket.io documentation but there are no sufficient explanations in connection with PHP server using XAMMP.

I am using a PHP as my server-side scripting language and the code above communicates with the PHP script, but, I don't know the meaning of those codes.

after socket.on, there is a name 'new_message'. I don't know how it worked.

Also, there are JSON name: data.name , emit function,.. I don't know where did these

exist.Somebody will try to explain what's going on here?

答:
```<code>socket.on( 'new_message', function )
</code>```

When the server receives an event (or message) named new_message from this socket connection,

```<code>io.sockets.emit( 'new_message', data )
</code>```

the server will re emit that message out to all sockets connected to the default namespace.

```<code>{
    name: data.name,
    address : data.address
}
</code>```

The data will contain the same name and address from the original incoming event.

This new message will also go back to the socket that created it, in case that matters.

The socket.io API docs aren't the easiest to read but they do cover most of the API. The socket.io and engine.io git repos cover the rest.

Body:
I am new to real-time programming using socket.io and node.js. I have seen this code from a blog site unfortunately did not post any comment or explanation about the code below:

socket.on( 'new_message', function( data ) {
  io.sockets.emit( 'new_message', {
    name: data.name,
    address : data.address
 });
});

I have checked the socket.io documentation but there are no sufficient explanations in connection with PHP server using XAMMP.

I am using a PHP as my server-side scripting language and the code above communicates with the PHP script, but, I don't know the meaning of those codes.

after socket.on, there is a name 'new_message'. I don't know how it worked.

Also, there are JSON name: data.name , emit function,.. I don't know where did these

exist.Somebody will try to explain what's going on here?

Body:
socket.on( 'new_message', function )

When the server receives an event (or message) named new_message from this socket connection,

io.sockets.emit( 'new_message', data )

the server will re emit that message out to all sockets connected to the default namespace.

{
    name: data.name,
    address : data.address
}

The data will contain the same name and address from the original incoming event.

This new message will also go back to the socket that created it, in case that matters.

The socket.io API docs aren't the easiest to read but they do cover most of the API. The socket.io and engine.io git repos cover the rest.


问:
Python divide a list of ints on every recurring specific int in list
How can I change a list like

[30,20,0,48,20,10,20,0,30]

to:

[[30,20],[48,20,10,20],[30]]

by dividing it everytime there is a 0 in the list? I have tried many ways but they all take up too much lines to make sense (10 lines). I have looked at many list-splitting questions on stack overflow and I cant find anything that works.

EDIT:

I was asking if there was any way to do list.split(0) or something like that, but it appears that the answer is that there is no way to do that. I wanted to know if I can do it in one line or if there is any way I can use a common module. I have already tried doing it in multiple lines, it has worked, but I think it is inconvenient.

EDIT 2:

The code I tried was:

```<code>list = [30,20,0,48,20,10,20,0,30]  #1, 1 list
newlist = []                       #2, 2 lists
addinglist = []                    #3, 3 lists
for x in list:                     #4
    if x == 0:                     #5
        newlist.append(addinglist) #6
        addinglist = []            #7
    else:                          #8
        addinglist.append(x)       #9
newlist.append(addinglist)         #10
list = newlist                     #11 lines, 3 lists.
print(addinglist)
</code>```

The code requires 11 lines and 3 lists (one getting modified and the other two are useless).

答:
This works:

```<code>x=[10,20,30,0,4,5,6,0,1,1,1,1,1,1,0,1]

output=[]
temp=[]
for i in x:
    if i==0:
        output.append(temp)
        temp=[]
    else:
        temp.append(i)
output.append(temp)
</code>```

Where output is:

```<code>[[10, 20, 30], [4, 5, 6], [1, 1, 1, 1, 1, 1], [1]]
</code>```

The code quite short, but I'm sure there are solutions that are more succinct.

Body:
How can I change a list like

[30,20,0,48,20,10,20,0,30]

to:

[[30,20],[48,20,10,20],[30]]

by dividing it everytime there is a 0 in the list? I have tried many ways but they all take up too much lines to make sense (10 lines). I have looked at many list-splitting questions on stack overflow and I cant find anything that works.

EDIT:

I was asking if there was any way to do list.split(0) or something like that, but it appears that the answer is that there is no way to do that. I wanted to know if I can do it in one line or if there is any way I can use a common module. I have already tried doing it in multiple lines, it has worked, but I think it is inconvenient.

EDIT 2:

The code I tried was:

list = [30,20,0,48,20,10,20,0,30]  #1, 1 list
newlist = []                       #2, 2 lists
addinglist = []                    #3, 3 lists
for x in list:                     #4
    if x == 0:                     #5
        newlist.append(addinglist) #6
        addinglist = []            #7
    else:                          #8
        addinglist.append(x)       #9
newlist.append(addinglist)         #10
list = newlist                     #11 lines, 3 lists.
print(addinglist)

The code requires 11 lines and 3 lists (one getting modified and the other two are useless).

Body:
This works:

x=[10,20,30,0,4,5,6,0,1,1,1,1,1,1,0,1]

output=[]
temp=[]
for i in x:
    if i==0:
        output.append(temp)
        temp=[]
    else:
        temp.append(i)
output.append(temp)

Where output is:

[[10, 20, 30], [4, 5, 6], [1, 1, 1, 1, 1, 1], [1]]

The code quite short, but I'm sure there are solutions that are more succinct.


问:
Add text inside doughnut chart from chart js-2 in react
i want to add a text message inside my doughnut pie chart. To be more specific i want something like this:

I came across the same issue here in stack overflow by they use chart js in jquery and since i'm new to javascript i got confused. This is how i define my pie chart:

```<code><Doughnut
            data={sectorsData}
            width={250}
            height={250}
            options={{
              legend: {
                display: false
              },
              maintainAspectRatio: false,
              responsive: true,
              cutoutPercentage: 60
            }}
          />
</code>```

答:
My example uses the property text on the data to specify the inner text:

```<code>const data = {
  labels: [...],
  datasets: [...],
  text: '23%'
};
</code>```

import React from 'react';
import ReactDOM from 'react-dom';
import {Doughnut} from 'react-chartjs-2';

// some of this code is a variation on https://jsfiddle.net/cmyker/u6rr5moq/
var originalDoughnutDraw = Chart.controllers.doughnut.prototype.draw;
Chart.helpers.extend(Chart.controllers.doughnut.prototype, {
  draw: function() {
    originalDoughnutDraw.apply(this, arguments);

    var chart = this.chart.chart;
    var ctx = chart.ctx;
    var width = chart.width;
    var height = chart.height;

    var fontSize = (height / 114).toFixed(2);
    ctx.font = fontSize + "em Verdana";
    ctx.textBaseline = "middle";

    var text = chart.config.data.text,
        textX = Math.round((width - ctx.measureText(text).width) / 2),
        textY = height / 2;

    ctx.fillText(text, textX, textY);
  }
});

const data = {
 labels: [
  'Red',
  'Green',
  'Yellow'
 ],
 datasets: [{
  data: [300, 50, 100],
  backgroundColor: [
  '#FF6384',
  '#36A2EB',
  '#FFCE56'
  ],
  hoverBackgroundColor: [
  '#FF6384',
  '#36A2EB',
  '#FFCE56'
  ]
 }],
  text: '23%'
};

class DonutWithText extends React.Component {

  render() {
    return (

React Doughnut with Text Example

        <Doughnut data={data} />

    );
  }
};

ReactDOM.render(
  <DonutWithText />,
  document.getElementById('root')
);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://gor181.github.io/react-chartjs-2/common.js"></script>
<script src="https://gor181.github.io/react-chartjs-2/bundle.js"></script>

<div id="root">
</div></code>```

You'll have to scroll down a bit to see in when running the CodeSnippet due to some weird console error.

It works properly in CodePen though, where I wrote it: http://codepen.io/anon/pen/OpdBOq?editors=1010

Body:
i want to add a text message inside my doughnut pie chart. To be more specific i want something like this:

I came across the same issue here in stack overflow by they use chart js in jquery and since i'm new to javascript i got confused. This is how i define my pie chart:

<Doughnut
            data={sectorsData}
            width={250}
            height={250}
            options={{
              legend: {
                display: false
              },
              maintainAspectRatio: false,
              responsive: true,
              cutoutPercentage: 60
            }}
          />

Body:
My example uses the property text on the data to specify the inner text:

const data = {
  labels: [...],
  datasets: [...],
  text: '23%'
};

import React from 'react';
import ReactDOM from 'react-dom';
import {Doughnut} from 'react-chartjs-2';

// some of this code is a variation on https://jsfiddle.net/cmyker/u6rr5moq/
var originalDoughnutDraw = Chart.controllers.doughnut.prototype.draw;
Chart.helpers.extend(Chart.controllers.doughnut.prototype, {
  draw: function() {
    originalDoughnutDraw.apply(this, arguments);

    var chart = this.chart.chart;
    var ctx = chart.ctx;
    var width = chart.width;
    var height = chart.height;

    var fontSize = (height / 114).toFixed(2);
    ctx.font = fontSize + "em Verdana";
    ctx.textBaseline = "middle";

    var text = chart.config.data.text,
        textX = Math.round((width - ctx.measureText(text).width) / 2),
        textY = height / 2;

    ctx.fillText(text, textX, textY);
  }
});

const data = {
 labels: [
  'Red',
  'Green',
  'Yellow'
 ],
 datasets: [{
  data: [300, 50, 100],
  backgroundColor: [
  '#FF6384',
  '#36A2EB',
  '#FFCE56'
  ],
  hoverBackgroundColor: [
  '#FF6384',
  '#36A2EB',
  '#FFCE56'
  ]
 }],
  text: '23%'
};

class DonutWithText extends React.Component {

  render() {
    return (
      <div>
        <h2>React Doughnut with Text Example</h2>
        <Doughnut data={data} />
      </div>
    );
  }
};

ReactDOM.render(
  <DonutWithText />,
  document.getElementById('root')
);

<script src="https://gor181.github.io/react-chartjs-2/common.js"></script>
<script src="https://gor181.github.io/react-chartjs-2/bundle.js"></script>

<div id="root">
</div>

You'll have to scroll down a bit to see in when running the CodeSnippet due to some weird console error.

It works properly in CodePen though, where I wrote it: http://codepen.io/anon/pen/OpdBOq?editors=1010


问:
Can I access Android HCE application if device is turned off?
I'm currently write Android HCE application. And I want to use my HCE application when the device is turned off. I found a way to "Access HCE when Screen off", but no information of power off status.

Is there any way to use HCE application when phone is turned off?

答:
No you can't access because of security reason
One correction also its not accessible if screen is off as mentioned in provided link.

Current Android implementations turn the NFC controller and the application processor off completely when the screen of the device is turned off. HCE services will therefore not work when the screen is off.

It may work on some devices only if vendor implements the OS customized.


问:
How to debug PHP with netbeans and Xdebug
I have recently tried to get going with Netbeans 6.5 after it rated so highly in the IDE review by Smashing magazine. http://www.smashingmagazine.com/2009/02/11/the-big-php-ides-test-why-use-oneand-which-to-choose/

My main reason for switching from Notepad++ is that I'd like to be able to debug my code and set through it.

I have followed the instructions about how to install xdebug from both the vendor http://xdebug.org/ and the netbeans web site. http://www.netbeans.org/kb/docs/php/debugging.html#gettingReady but to no avail.

How is it done, has anyone else got debugging working in netbeans?

(My setup is: Windows XP, Wamp server 2.0, PHP 5, Netbeans 6.5.1)

答:
You can see here:
http://ruilima.com/2010/11/ambiente_de_desenvolvimento_php_netbeans_xdebug/
is in Portuguese, but there is a pre configured virtual machine with Ubuntu 10.10, netbeans, php, mysql, xdebug, ready to use. take a look</p>

OwnerDisplayName: Jon


问:
Getting minimatch issue at the time of installing ionic
I have installed nodejs version 7.3.0 after that I am trying to install ionic by CLI but I am getting below error :

npm WARN deprecated minimatch@0.2.14: Please update to minimatch 3.0.2 or higher to avoid a RegExp DoS issue

After exploring I got 2 answers from stack to run npm update minimatch and npm install -g minimatch@3.0.2 but the issue is not getting resolved.

But after that it stops automatically.

So please help in solving this issue.

答:
```<code>    npm install -g minimatch uuid ionic
</code>```

Body: npm install -g minimatch uuid ionic


问:
How to convert marathi data from pdf to excel in proper format
I am converting Marathi data from PDF to excel or word but it is not getting proper format.
I have copied some data from PDF and pasted in word document but it was not getting proper format.
 e.g. प्रविण सुधाकर शिरवाडकर this line is in PDF
 but when i copied and pasted in word it has been getting
 -प्रववर् सुधाकर शिरवाडकर
what should i do for this?
anyone please help me.

thank you in advance

答:
There seem to be problems in the way PDF stores unicode devnagri text. Try this alternative route: convert your PDF to an image. Can use an online tool or downloaded, or if on linux use this command in terminal:

```<code>for f in *.pdf; do convert -density 200 "$f" "${f}_200dpi.jpg"; done
</code>```

change the density from 200 to other as per need. Each page from your document should be converted into an image file. For a windows tool, try https://www.pdfill.com/pdf_tools_free.html

Then, go to  http://www.i2ocr.com/free-online-hindi-ocr, upload the image and convert. That uses OCR (optical character recognition).

Body:
There seem to be problems in the way PDF stores unicode devnagri text. Try this alternative route: convert your PDF to an image. Can use an online tool or downloaded, or if on linux use this command in terminal:

for f in *.pdf; do convert -density 200 "$f" "${f}_200dpi.jpg"; done

change the density from 200 to other as per need. Each page from your document should be converted into an image file. For a windows tool, try https://www.pdfill.com/pdf_tools_free.html

Then, go to  http://www.i2ocr.com/free-online-hindi-ocr, upload the image and convert. That uses OCR (optical character recognition).


问:
java hibernate storing sql queries in xml file
I am trying to place all sql queries in xml file.I am using Spring boot and hibernate with native sqls

Can someone provide me the example how to load and get the query string from xml  file in  spring boot and hibernate.

I am using java based configuration in the application.

The configuration file looks like below:

```<code>@SpringBootApplication
@PropertySources({
        @PropertySource(value = "classpath:application.properties")
})

@EnableAutoConfiguration`enter code here`
@Configuration
public class BootApplication extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(BootApplication.class);
    }

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

    @Bean
    public SessionFactory sessionFactory(HibernateEntityManagerFactory hemf) {
        return hemf.getSessionFactory();
    }
}
</code>```

xml file is below:

```<code><?xml version="1.0" encoding="UTF-8"?>
<properties>
    <entry key="getUsersById">
        <![CDATA[
        Select * From User
        Where id =?
    ]]>

    </entry>
    <entry key="getPersonBySSN">
        <![CDATA[
    ]]>
    </entry>
</properties>
</code>```

Below is the Java hibernate code without moving sql to xml file.I need to move sqls to xml as there are lot of queries in the application.

```<code>public List<User> getUsers(String id) {
                List<User> users = new ArrayList<User>();
                try {
                    String sql = "Select * From User Where id =?";
                    SQLQuery query = getSession().createSQLQuery(sql);
                    query.setParameter(0, id);                  query.setResultTransformer(Transformers.aliasToBean(User.class))
                    users = (List<User>) query.list();
                } catch (Exception e) {
                    logger.error("Error", e);
                }
                return users;
            }
</code>```

Can someone please provide example to it move the sql queries to xml file and use it java code?

答:
Why just use named query:</p>

```<code><sql-query name="getUsersById">
    <return alias="user" class="your class"/>
    <![CDATA[ Select * From User
        Where id =?]]>
</sql-query>
</code>```

Body:
I am trying to place all sql queries in xml file.I am using Spring boot and hibernate with native sqls

Can someone provide me the example how to load and get the query string from xml  file in  spring boot and hibernate.

I am using java based configuration in the application.

The configuration file looks like below:

@SpringBootApplication
@PropertySources({
        @PropertySource(value = "classpath:application.properties")
})

@EnableAutoConfiguration`enter code here`
@Configuration
public class BootApplication extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(BootApplication.class);
    }

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

    @Bean
    public SessionFactory sessionFactory(HibernateEntityManagerFactory hemf) {
        return hemf.getSessionFactory();
    }
}

xml file is below:

<?xml version="1.0" encoding="UTF-8"?>
<properties>
    <entry key="getUsersById">
        <![CDATA[
        Select * From User
        Where id =?
    ]]>

    </entry>
    <entry key="getPersonBySSN">
        <![CDATA[
    ]]>
    </entry>
</properties>

Below is the Java hibernate code without moving sql to xml file.I need to move sqls to xml as there are lot of queries in the application.

public List<User> getUsers(String id) {
                List<User> users = new ArrayList<User>();
                try {
                    String sql = "Select * From User Where id =?";
                    SQLQuery query = getSession().createSQLQuery(sql);
                    query.setParameter(0, id);                  query.setResultTransformer(Transformers.aliasToBean(User.class))
                    users = (List<User>) query.list();
                } catch (Exception e) {
                    logger.error("Error", e);
                }
                return users;
            }

Can someone please provide example to it move the sql queries to xml file and use it java code?

Body:
Why just use named query:

<sql-query name="getUsersById">
    <return alias="user" class="your class"/>
    <![CDATA[ Select * From User
        Where id =?]]>
</sql-query>