问:
How to concat two dataframes and then show the difference between the two frames on the visualisation?
Hi there (sorry this is probably really basic but I'm still learning)
I'm trying to merge two dataframes together (one from 2016 and one from 2012) so that I can show a barchart of the differences. However when I merge them the barchart doesn't show the years or the differences between the datasets. Is there a way to merge (or another method) two dataframes and show which year / dataframe they are from on the x axis? </p>

答:
```<code>df_2012['year'] = 2012
df_2016['year'] = 2016

df_2012_2016 = pandas.concat([df_2012, df_2016])
</code>```

Then use seaborn with hue parameter set to year, e.g. in case of categorical columns for plotting:
seaborn.barplot(x="Categorical_column", y="Value_to_plot", data=df_2012_2016, hue='year')

Body:
df_2012['year'] = 2012
df_2016['year'] = 2016

df_2012_2016 = pandas.concat([df_2012, df_2016])

Then use seaborn with hue parameter set to year, e.g. in case of categorical columns for plotting:
seaborn.barplot(x="Categorical_column", y="Value_to_plot", data=df_2012_2016, hue='year')


来源: stackexchange

问:
How to match and remove any line containing a specific string?
I have a huge directory list of URLs from my Web site. Example:

```<code>/folder/folder2/folder3/page.htm
/folder/folder2/folder3/page2.htm
/folder/folder2/folder3/page3.htm
/folder/folder2/folder3/page4.htm
</code>```

I want to clean this list of all items that have /folder2 in the path. I need a regular expression to perform a find and replace for everything that uses /folder2/ and delete those lines from my list. So find/replace it with blank.

Does anyone know what the proper regular expression for this would be? I should specify I am using Dreamweaver as my editor, which may use different regular expressions.

答:
In Python that would be:</p>

```<code>import re
regex = re.compile('.*/folder2/.*')
f = open("filtered_file.txt", "w")
map(lambda x: f.write(x), filter(lambda x: not regex.match(x), open("input.txt")))
f.close()
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a huge directory list of URLs from my Web site. Example:

/folder/folder2/folder3/page.htm
/folder/folder2/folder3/page2.htm
/folder/folder2/folder3/page3.htm
/folder/folder2/folder3/page4.htm

I want to clean this list of all items that have /folder2 in the path. I need a regular expression to perform a find and replace for everything that uses /folder2/ and delete those lines from my list. So find/replace it with blank.

Does anyone know what the proper regular expression for this would be? I should specify I am using Dreamweaver as my editor, which may use different regular expressions.

Body:
In Python that would be:

import re
regex = re.compile('.*/folder2/.*')
f = open("filtered_file.txt", "w")
map(lambda x: f.write(x), filter(lambda x: not regex.match(x), open("input.txt")))
f.close()

ContentLicense: CC BY-SA 2.5


问:
Excel VBA Compare value from two workbooks then copy data
I'm looking for a VBA script that compare column D on workbook1 with column A on workbook2.
If it is a match I would like data from workbook2 column G to be copied to woksbook1 column E.

I´ve found this script:

```<code>Sub UpdateW2()

Dim w1 As Worksheet, w2 As Worksheet
Dim c As Range, FR As Long

Application.ScreenUpdating = False

Set w1 = Workbooks("Excel VBA Test.xlsm").Worksheets("Blad1")
Set w2 = Workbooks("Excel VBA Test Backbone.xlsx").Worksheets("Blad1")

For Each c In w1.Range("D2", w1.Range("D" & Rows.Count).End(xlUp))
    FR = 0
    On Error Resume Next
    FR = Application.Match(c, w2.Columns("A"), 0)
    On Error GoTo 0
    If FR <> 0 Then w1.Range("C" & FR).Value = c.Offset(, -3)
Next c
Application.ScreenUpdating = True
End Sub
</code>```

It is simple and does almost what I want but into wrong worksheet.
I doesn´t manage to switch which worksheet to copy data too.
Any help would be most helpful.

答:
Is that what you need? Think you were copying the wrong way round and your offset wasn't quite right.</p>

```<code>Sub UpdateW2()

Dim w1 As Worksheet, w2 As Worksheet
Dim c As Range, FR As Variant

Application.ScreenUpdating = False

Set w1 = Workbooks("Excel VBA Test.xlsm").Worksheets("Blad1")
Set w2 = Workbooks("Excel VBA Test Backbone.xlsx").Worksheets("Blad1")

For Each c In w1.Range("D2", w1.Range("D" & Rows.Count).End(xlUp))
    FR = Application.Match(c, w2.Columns("A"), 0)
    If IsNumeric(FR) Then c.Offset(, 1).Value = w2.Range("G" & FR).Value
Next c

Application.ScreenUpdating = True

End Sub
</code>```

Body:
I'm looking for a VBA script that compare column D on workbook1 with column A on workbook2.
If it is a match I would like data from workbook2 column G to be copied to woksbook1 column E.

I´ve found this script:

Sub UpdateW2()

Dim w1 As Worksheet, w2 As Worksheet
Dim c As Range, FR As Long

Application.ScreenUpdating = False

Set w1 = Workbooks("Excel VBA Test.xlsm").Worksheets("Blad1")
Set w2 = Workbooks("Excel VBA Test Backbone.xlsx").Worksheets("Blad1")

For Each c In w1.Range("D2", w1.Range("D" & Rows.Count).End(xlUp))
    FR = 0
    On Error Resume Next
    FR = Application.Match(c, w2.Columns("A"), 0)
    On Error GoTo 0
    If FR <> 0 Then w1.Range("C" & FR).Value = c.Offset(, -3)
Next c
Application.ScreenUpdating = True
End Sub

It is simple and does almost what I want but into wrong worksheet.
I doesn´t manage to switch which worksheet to copy data too.
Any help would be most helpful.

Body:
Is that what you need? Think you were copying the wrong way round and your offset wasn't quite right.

Sub UpdateW2()

Dim w1 As Worksheet, w2 As Worksheet
Dim c As Range, FR As Variant

Application.ScreenUpdating = False

Set w1 = Workbooks("Excel VBA Test.xlsm").Worksheets("Blad1")
Set w2 = Workbooks("Excel VBA Test Backbone.xlsx").Worksheets("Blad1")

For Each c In w1.Range("D2", w1.Range("D" & Rows.Count).End(xlUp))
    FR = Application.Match(c, w2.Columns("A"), 0)
    If IsNumeric(FR) Then c.Offset(, 1).Value = w2.Range("G" & FR).Value
Next c

Application.ScreenUpdating = True

End Sub


问:
Attempting to remove "www" and force "https" on domain and trying to make it do both
```<code>RewriteEngine On
    #Remove www
    RewriteCond %{HTTP_HOST} ^www\.(.+)
    RewriteCond %{HTTPS}s/%1 ^(on(s)|offs)/(.+)
    RewriteRule ^ http%2://%3%{REQUEST_URI} [L,R=301]
    #force https
    RewriteCond %{HTTPS} off
    RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
    #ignore folder for removing slash & removing .html
    RewriteRule ^(whmcs) - [L]
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)/$ /$1 [L,R]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^([^\.]+)$ $1.html [NC,L]
</code>```

So this is my current code. Here is my results:

website.com --> https://website.com

http://website.com --> https://website.com

www.website.com --> https://website.com

http://www.website.com --> https://website.com

All good except...

https://www.website.com --> https://www.website.com <--No good.

I have been researching and attempting to rewrite this to no success. Please any help and if you would be so kind to leave documentation so I could read further. Either way I need a solution. Thank you!

答:
You have written so many re-writing conditions to remove www and force https. If they not any other specific needs then you can just try this simple solution

```<code>RewriteRule (.*) https://website.com/$1 [R=301,L]
</code>```

Body:
RewriteEngine On
    #Remove www
    RewriteCond %{HTTP_HOST} ^www\.(.+)
    RewriteCond %{HTTPS}s/%1 ^(on(s)|offs)/(.+)
    RewriteRule ^ http%2://%3%{REQUEST_URI} [L,R=301]
    #force https
    RewriteCond %{HTTPS} off
    RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
    #ignore folder for removing slash & removing .html
    RewriteRule ^(whmcs) - [L]
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)/$ /$1 [L,R]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^([^\.]+)$ $1.html [NC,L]

So this is my current code. Here is my results:

website.com --> https://website.com

http://website.com --> https://website.com

www.website.com --> https://website.com

http://www.website.com --> https://website.com

All good except...

https://www.website.com --> https://www.website.com <--No good.

I have been researching and attempting to rewrite this to no success. Please any help and if you would be so kind to leave documentation so I could read further. Either way I need a solution. Thank you!

Body:
You have written so many re-writing conditions to remove www and force https. If they not any other specific needs then you can just try this simple solution

RewriteRule (.*) https://website.com/$1 [R=301,L]


问:
Xamarin ListView Issue
I am beginer on Xamarin. What did I do wrong here. I am trying to add Conext Menu to ListView and compiler is not happy with this. </p>

```<code><ListView x:Name="VehicleList">
<ListView.ItemTemplate>
<DataTemplate>
    <ImageCell
            ImageSource="152x152@1x.png"
            Text="{Binding Title}"
            Detail="{Binding SubTitle}"
            TextColor="#f35e20"
            DetailColor="#503026" />

        <!--  adding this caused error
        <ViewCell>
            <ViewCell.ContextActions>
                <MenuItem Clicked="OnDelete" CommandParameter="{Binding .}"
                Text="Archive"
                IsDestructive="True" />
            </ViewCell.ContextActions>
        </ViewCell>
        -->

</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</code>```

答:
You are defining two viewcells in one data template. this is not possible!

You should create a DataTemplateSelector and declare the ViewCells in separate classes. Then you can make the selector choose a viewcell based on the logic implemented in the DataTemplateSelector. The xamarin documentation has a nice explanation: https://developer.xamarin.com/guides/xamarin-forms/application-fundamentals/templates/data-templates/selector/

Title: Xamarin ListView Issue

Body:
I am beginer on Xamarin. What did I do wrong here. I am trying to add Conext Menu to ListView and compiler is not happy with this.

<ListView x:Name="VehicleList">
<ListView.ItemTemplate>
<DataTemplate>
    <ImageCell
            ImageSource="152x152@1x.png"
            Text="{Binding Title}"
            Detail="{Binding SubTitle}"
            TextColor="#f35e20"
            DetailColor="#503026" />

</DataTemplate>
</ListView.ItemTemplate>
</ListView>


问:
SharePoint Requirements
I am new to SharePoint. I need a workflow portal web application. Please someone guide in intalling the sharepoint and what are the hardware and software requirements for working
in SharePoint.

Please let me know which is better either Windows SharePoint Services or MOSS2007 for creating web application portal

答:
Here are some very good articles I've come across:

Miscrosft's SharePoint Capacity Planning Tool Executive Overview (this one is very nice!)

Dell's SharePoint 2007 Sizing Guide (PDF) (very nice)

SharePoint Capacity Planning Key Info (by Joel Oleson with lots of links)

SharePoint 2007 Hardware Specifications and Server Sizing

Determine hardware and software requirements (Office SharePoint Server)

OwnerDisplayName: balaweblog

Title: SharePoint Requirements

LastEditorDisplayName: balaweblog

OwnerDisplayName: Tom Winter

ContentLicense: CC BY-SA 4.0


问:
JavaScript associative array to JSON
How can I convert a JavaScript associative array into JSON?

I have tried the following:

```<code>var AssocArray = new Array();

AssocArray["a"] = "The letter A"

console.log("a = " + AssocArray["a"]);

// result: "a = The letter A"

JSON.stringify(AssocArray);

// result: "[]"
</code>```

答:
Agreed that it is probably best practice to keep Objects as objects and Arrays as arrays. However, if you have an Object with named properties that you are treating as an array, here is how it can be done:</p>

```<code>let tempArr = [];
Object.keys(objectArr).forEach( (element) => {
    tempArr.push(objectArr[element]);
});

let json = JSON.stringify(tempArr);
</code>```

Title: JavaScript associative array to JSON

Body:
How can I convert a JavaScript associative array into JSON?

I have tried the following:

var AssocArray = new Array();

AssocArray["a"] = "The letter A"

console.log("a = " + AssocArray["a"]);

// result: "a = The letter A"

JSON.stringify(AssocArray);

// result: "[]"

Body:
Agreed that it is probably best practice to keep Objects as objects and Arrays as arrays. However, if you have an Object with named properties that you are treating as an array, here is how it can be done:

let tempArr = [];
Object.keys(objectArr).forEach( (element) => {
    tempArr.push(objectArr[element]);
});

let json = JSON.stringify(tempArr);


问:
Why won't a JavaScript alarm work when not in an active tab?

I have been trying to create a JavaScript alarm for a school schedule. The alarm works perfectly when I am on that CodePen tab, but does not execute when I am on a different tab(still in that window). A codepen is here. It uses the date object in JavaScript. The variable day is for different schedules- we have an abbreviated schedule on certain days and the alarm is set up to deal with that.</p>

```<code>    var day;
  function choose(choice){
    day=choice;
  }
function startTime() {
    var today = new Date();
    var h = today.getHours();
    var m = today.getMinutes();
    var s = today.getSeconds();
    m = checkTime(m);
    s = checkTime(s);
    document.getElementById('txt').innerHTML =
    h + ":" + m + ":" + s;
    var t = setTimeout(startTime, 500);
}
function checkTime(i) {
    if (i < 10) {i = "0" + i};  // add zero in front of numbers < 10
    return i;
}
   var x=1;

window.setInterval(function(){ // Set interval for checking
    var date = new Date(); // Create a Date object to find out what time it is
if(day==1){
     document.body.style.background ="black";
  document.getElementById("number2").style.display="none";
  document.getElementById("number1").style.display="block";
if(date.getHours()===8 && date.getMinutes
()===16&&date.getSeconds()==0){
 window.open("https://www.youtube.com/watch?v=iNpXCzaWW1s");

}
  if(date.getHours()===9 && date.getMinutes
()===10&&date.getSeconds()==0){
 window.open("https://www.youtube.com/watch?v=iNpXCzaWW1s");

}
   if(date.getHours()===10 && date.getMinutes
()===04&&date.getSeconds()==18){
 window.open("https://www.youtube.com/watch?v=iNpXCzaWW1s");

}
     if(date.getHours()===11 && date.getMinutes
()===36&&date.getSeconds()==0){
 window.open("https://www.youtube.com/watch?v=iNpXCzaWW1s");

}
  if(date.getHours()===12 && date.getMinutes
()===42&&date.getSeconds()==0){
  window.open("https://www.youtube.com/watch?v=iNpXCzaWW1s");

}
    if(date.getHours()===1 && date.getMinutes
()===24&&date.getSeconds()==0){
 window.open("https://www.youtube.com/watch?v=iNpXCzaWW1s");

}
    if(date.getHours()===2 && date.getMinutes
()===18&&date.getSeconds()==0){
  window.open("https://www.youtube.com/watch?v=iNpXCzaWW1s");

}}
  else if(day==0){
     document.getElementById("number1").style.display="none";
  document.getElementById("number2").style.display="block";
    document.body.style.background ="white";
    if(date.getHours()===8 && date.getMinutes
()===9&&date.getSeconds()==0){
  window.open("https://www.youtube.com/watch?v=iNpXCzaWW1s");

}
  if(date.getHours()===8 && date.getMinutes
()===56&&date.getSeconds()==0){
   window.open("https://www.youtube.com/watch?v=iNpXCzaWW1s");

}
   if(date.getHours()===9 && date.getMinutes
()===45&&date.getSeconds()==0){
  window.open("https://www.youtube.com/watch?v=iNpXCzaWW1s");

}
     if(date.getHours()===10 && date.getMinutes
()===17&&date.getSeconds()==0){
 window.open("https://www.youtube.com/watch?v=iNpXCzaWW1s");

}
  if(date.getHours()===11 && date.getMinutes
()===08&&date.getSeconds()==0){
  window.open("https://www.youtube.com/watch?v=iNpXCzaWW1s");

}
    if(date.getHours()===11 && date.getMinutes
()===59&&date.getSeconds()==0){
 window.open("https://www.youtube.com/watch?v=iNpXCzaWW1s");
}
    if(date.getHours()===12 && date.getMinutes
()===46&&date.getSeconds()==0){
   window.open("https://www.youtube.com/watch?v=iNpXCzaWW1s");

}
</code>```

答:
Browsers aggressively block window.open, to prevent spam/popups/etc.

This might help you though:

https://stackoverflow.com/a/11821617/3650835

Body:
I have been trying to create a JavaScript alarm for a school schedule. The alarm works perfectly when I am on that CodePen tab, but does not execute when I am on a different tab(still in that window). A codepen is here. It uses the date object in JavaScript. The variable day is for different schedules- we have an abbreviated schedule on certain days and the alarm is set up to deal with that.

    var day;
  function choose(choice){
    day=choice;
  }
function startTime() {
    var today = new Date();
    var h = today.getHours();
    var m = today.getMinutes();
    var s = today.getSeconds();
    m = checkTime(m);
    s = checkTime(s);
    document.getElementById('txt').innerHTML =
    h + ":" + m + ":" + s;
    var t = setTimeout(startTime, 500);
}
function checkTime(i) {
    if (i < 10) {i = "0" + i};  // add zero in front of numbers < 10
    return i;
}
   var x=1;

window.setInterval(function(){ // Set interval for checking
    var date = new Date(); // Create a Date object to find out what time it is
if(day==1){
     document.body.style.background ="black";
  document.getElementById("number2").style.display="none";
  document.getElementById("number1").style.display="block";
if(date.getHours()===8 && date.getMinutes
()===16&&date.getSeconds()==0){
 window.open("https://www.youtube.com/watch?v=iNpXCzaWW1s");

}
  if(date.getHours()===9 && date.getMinutes
()===10&&date.getSeconds()==0){
 window.open("https://www.youtube.com/watch?v=iNpXCzaWW1s");

}
   if(date.getHours()===10 && date.getMinutes
()===04&&date.getSeconds()==18){
 window.open("https://www.youtube.com/watch?v=iNpXCzaWW1s");

}
     if(date.getHours()===11 && date.getMinutes
()===36&&date.getSeconds()==0){
 window.open("https://www.youtube.com/watch?v=iNpXCzaWW1s");

}
  if(date.getHours()===12 && date.getMinutes
()===42&&date.getSeconds()==0){
  window.open("https://www.youtube.com/watch?v=iNpXCzaWW1s");

}
    if(date.getHours()===1 && date.getMinutes
()===24&&date.getSeconds()==0){
 window.open("https://www.youtube.com/watch?v=iNpXCzaWW1s");

}
    if(date.getHours()===2 && date.getMinutes
()===18&&date.getSeconds()==0){
  window.open("https://www.youtube.com/watch?v=iNpXCzaWW1s");

}}
  else if(day==0){
     document.getElementById("number1").style.display="none";
  document.getElementById("number2").style.display="block";
    document.body.style.background ="white";
    if(date.getHours()===8 && date.getMinutes
()===9&&date.getSeconds()==0){
  window.open("https://www.youtube.com/watch?v=iNpXCzaWW1s");

}
  if(date.getHours()===8 && date.getMinutes
()===56&&date.getSeconds()==0){
   window.open("https://www.youtube.com/watch?v=iNpXCzaWW1s");

}
   if(date.getHours()===9 && date.getMinutes
()===45&&date.getSeconds()==0){
  window.open("https://www.youtube.com/watch?v=iNpXCzaWW1s");

}
     if(date.getHours()===10 && date.getMinutes
()===17&&date.getSeconds()==0){
 window.open("https://www.youtube.com/watch?v=iNpXCzaWW1s");

}
  if(date.getHours()===11 && date.getMinutes
()===08&&date.getSeconds()==0){
  window.open("https://www.youtube.com/watch?v=iNpXCzaWW1s");

}
    if(date.getHours()===11 && date.getMinutes
()===59&&date.getSeconds()==0){
 window.open("https://www.youtube.com/watch?v=iNpXCzaWW1s");
}
    if(date.getHours()===12 && date.getMinutes
()===46&&date.getSeconds()==0){
   window.open("https://www.youtube.com/watch?v=iNpXCzaWW1s");

}


问:
Extract file creation date via Python
I ran into an issue when trying to extract file creation date via Python. I am using Python3.6 on 64bit Windows7.

I have a number of pictures (jpeg) that were taken [I should use "created" instead] in the past and uploaded to an on-line album on the same day. [Note: These JPEGs are not 'fresh' off the camera, some of them have been processed by other software and then "saved as"; Some of them are actually cellphone screenshots. So the EXIF Info may not be available] For example one of them were taken [or a better example cellphone screenshot created] and uploaded on 1/1/2016. I downloaded it from the on-line album on 11/1/2017. When this jpeg file is listed in Win7 file explorer’s “details” view, under “date” column it is showing 1/1/2016.  When I try to use Python to extract the creation date info, all three ways (st_atime, st_mtime, st_ctime) gave me 11/1/2017.  I then right click the file and view its property, there “created”, “modified”, and “accessed” all pointed to 11/1/2017.

I am wondering if there is still a Python way to get the original creation date, i.e. 1/1/2016, from this file? On my windows screen I clearly see that date "1/1/2016" Why I could not retrieve it? That's thing really drives me to ask this question

Thank you!

答:
You've merged some dates, so let's clarify which one you want.  Consider this sequence:

photographer (perhaps you) takes photo on 04 Jan;

uploads to photographer's computer on 05 Jan;

uploads to on-line album on 07 Jan.

You find the file on 09 Jan and download to your album.

Now, which date do you want to extract?  BTW, the 05 Jan date is almost certainly unavailable, unless you have access to the photographer's disk.

The 04 Jan date is available as shown in the link @EsotericVoid gave you; in that case, we should remove this question as a duplicate.

09 Jan is already available to you -- as you've lamented.  :-)

For 07 Jan, you'll need to look up how to preserve dates in whatever download command you're using; most have an option that will keep the dates from the file source (creation, modification, and access).

Update per OP's clarification

Understood: you need the original photo date.  That will be recorded only in the original image file.  Since you have different file formats, you'll need to write code that will first determine the format, and then extract the date per that particular format.  You now have a link to the EXIF solution.

Title: Extract file creation date via Python


问:
How to test Rails 3 Engines with Cucumber & Rspec?
I apologize if this question is slightly subjective... I am trying to figure out the best way to test Rails 3 Engines with Cucumber & Rspec.  In order to test the engine a rails 3 app is necessary.  Here is what I am currently doing:

Add a rails test app to the root of the gem (myengine) by running:  rails new /myengine/rails_app

Add Cucumber to /myengine/rails_app/features as you would in a normal Rails app

Require the Rails Engine Gem (using :path=>"/myengine") in /myengine/rails_app/Gemfile

Add spec to the root directory of the gem: /myengine/spec

Include the fixtures in /myengine/spec/fixtures and I add the following to my cuc env.rb:

env.rb:

```<code>Fixtures.reset_cache
fixtures_folder = File.join(Rails.root, 'spec', 'fixtures')
fixtures = Dir[File.join(fixtures_folder, '*.yml')].map {|f| File.basename(f, '.yml') }
Fixtures.create_fixtures(fixtures_folder, fixtures)
</code>```

Do you see any problems with setting it up like this?  The tests run fine, but I am a bit hesitant to put the features inside the test rails app.  I originally tried putting the features in the root of the gem and I created the test rails app inside features/support, but for some reason my engine would not initialize when I ran the tests, even though I could see the app loading everything else when cuc ran.

If anyone is working with Rails Engines and is using cuc and rspec for testing, I would be interested to hear your setup.

**UPDATE

I changed my setup a bit since I wrote this question.  I decided to get rid of the spec directory under the root of the engine.  Now I just create a rails app named "test_app" and setup cuc and rspec inside that app like I would normally do in a rails app.  Then I include the gem like I did in step #3 above.  Since the engine is a sub-app, I guess its just best to test it like it was a normal rails app.  I am still interested in hearing if anyone has a different setup.

答:
Rails 3.1 (will) generate a pretty good scaffold for engines. I'd recommend using RVM to create a new gemset called edge and switch to it:

```<code>rvm gemset create edge
rvm use @edge
</code>```

Then install edge rails:

```<code>git clone git://github.com/rails/rails.git
cd rails
rake install
</code>```

From there, you can follow Piotr Sarnacki's mountable app tutorial, replacing calls such as:

```<code>bundle exec ./bin/rails plugin new ../blog --edge --mountable
</code>```

With simply:

```<code>rails plugin new blog --mountable --full
</code>```

The mountable option makes the application mountable, whilst the full option makes it an engine with tests already built-in. To test the engine, this generator generates a folder in test called dummy which contains a small Rails application. You can see how this is loaded in test/test_helper.rb.

Then it's up to you to massage the data to do what it needs to in order to work. I would recommend copying over the cucumber files from a standard rails g cucumber:install into the project and then messing about with it until it works. I've done this once before so  I know it's possible, but I cannot find the code right now.

Let me know how you go.

Body:
I apologize if this question is slightly subjective... I am trying to figure out the best way to test Rails 3 Engines with Cucumber & Rspec.  In order to test the engine a rails 3 app is necessary.  Here is what I am currently doing:

Add a rails test app to the root of the gem (myengine) by running:  rails new /myengine/rails_app

Add Cucumber to /myengine/rails_app/features as you would in a normal Rails app

Require the Rails Engine Gem (using :path=>"/myengine") in /myengine/rails_app/Gemfile

Add spec to the root directory of the gem: /myengine/spec

Include the fixtures in /myengine/spec/fixtures and I add the following to my cuc env.rb:

env.rb:

Fixtures.reset_cache
fixtures_folder = File.join(Rails.root, 'spec', 'fixtures')
fixtures = Dir[File.join(fixtures_folder, '*.yml')].map {|f| File.basename(f, '.yml') }
Fixtures.create_fixtures(fixtures_folder, fixtures)

Do you see any problems with setting it up like this?  The tests run fine, but I am a bit hesitant to put the features inside the test rails app.  I originally tried putting the features in the root of the gem and I created the test rails app inside features/support, but for some reason my engine would not initialize when I ran the tests, even though I could see the app loading everything else when cuc ran.

If anyone is working with Rails Engines and is using cuc and rspec for testing, I would be interested to hear your setup.

**UPDATE

I changed my setup a bit since I wrote this question.  I decided to get rid of the spec directory under the root of the engine.  Now I just create a rails app named "test_app" and setup cuc and rspec inside that app like I would normally do in a rails app.  Then I include the gem like I did in step #3 above.  Since the engine is a sub-app, I guess its just best to test it like it was a normal rails app.  I am still interested in hearing if anyone has a different setup.

Body:
Rails 3.1 (will) generate a pretty good scaffold for engines. I'd recommend using RVM to create a new gemset called edge and switch to it:

rvm gemset create edge
rvm use @edge

Then install edge rails:

git clone git://github.com/rails/rails.git
cd rails
rake install

From there, you can follow Piotr Sarnacki's mountable app tutorial, replacing calls such as:

bundle exec ./bin/rails plugin new ../blog --edge --mountable

With simply:

rails plugin new blog --mountable --full

The mountable option makes the application mountable, whilst the full option makes it an engine with tests already built-in. To test the engine, this generator generates a folder in test called dummy which contains a small Rails application. You can see how this is loaded in test/test_helper.rb.

Then it's up to you to massage the data to do what it needs to in order to work. I would recommend copying over the cucumber files from a standard rails g cucumber:install into the project and then messing about with it until it works. I've done this once before so  I know it's possible, but I cannot find the code right now.

Let me know how you go.


问:
What usage does savedInstanceState have in super.onCreate(savedInstanceState)?
So, I am trying to understand the inner workings of Android and I haven't found an in depth explanation of what I am looking for. For my simple program:

```<code>public class MainActivity extends AppCompatActivity {

   @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}
</code>```

What is the difference in using null instead of savedInstanceState in super.onCreate()? I have tried both and there was no difference for my program.

If there is a difference, in which ways will the usage of savedInstanceState affect my program, as opposed to using null?

答:
The linked question/answer in @sasikumar's comment is good, and answers why you must call super.onCreate(), but it does not answer why you must pass the Bundle savedInstanceState parameter to the super call (as opposed to a new Bundle() or null).

The simple answer is that the savedInstanceState bundle contains information recorded by the Android framework that the super method will then use to restore state. For instance, any EditText with an android:id attribute will automatically save whatever the user has typed into it, and that information will be inside the savedInstanceState bundle. If you pass null, this automatic restoration is impossible.

Note that the savedInstanceState parameter will actually be null the very first time your activity is created. It will only be non-null when your activity has been destroyed and re-created (usually in response to a configuration change like the rotation of your phone, but there are many other scenarios as well).

Update

My example of automatic state restoration was incorrect. The EditText automatic restoration happens in the onRestoreInstanceState(Bundle savedInstanceState) callback, not in onCreate. Unfortunately, you can't simply pass null to that super method to see what happens (your app will crash).

However, this example will show what I meant. Assume your activity_main has some FrameLayout with an id of @+id/content, and assume you have some Fragment subclass that displays anything visible to the user. Try this:

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    if (savedInstanceState == null) {
        getSupportFragmentManager()
                .beginTransaction()
                .add(R.id.content, new MyFragment(), "MyFragment")
                .commit();
    }
}
</code>```

As is, this will display your fragment on first launch, and will continue to display the fragment after you rotate your device back and forth. This is because the FragmentManager uses the savedInstanceState bundle to save/restore fragments, and that is done in super.onCreate.

If you change the super call to super.onCreate(null), you'll still see the fragment the first time your activity starts up (since we're manually adding it at that point). But if you rotate the device, the fragment will disappear.

Body:
So, I am trying to understand the inner workings of Android and I haven't found an in depth explanation of what I am looking for. For my simple program:

public class MainActivity extends AppCompatActivity {

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

What is the difference in using null instead of savedInstanceState in super.onCreate()? I have tried both and there was no difference for my program.

If there is a difference, in which ways will the usage of savedInstanceState affect my program, as opposed to using null?

Body:
The linked question/answer in @sasikumar's comment is good, and answers why you must call super.onCreate(), but it does not answer why you must pass the Bundle savedInstanceState parameter to the super call (as opposed to a new Bundle() or null).

The simple answer is that the savedInstanceState bundle contains information recorded by the Android framework that the super method will then use to restore state. For instance, any EditText with an android:id attribute will automatically save whatever the user has typed into it, and that information will be inside the savedInstanceState bundle. If you pass null, this automatic restoration is impossible.

Note that the savedInstanceState parameter will actually be null the very first time your activity is created. It will only be non-null when your activity has been destroyed and re-created (usually in response to a configuration change like the rotation of your phone, but there are many other scenarios as well).

Update

My example of automatic state restoration was incorrect. The EditText automatic restoration happens in the onRestoreInstanceState(Bundle savedInstanceState) callback, not in onCreate. Unfortunately, you can't simply pass null to that super method to see what happens (your app will crash).

However, this example will show what I meant. Assume your activity_main has some FrameLayout with an id of @+id/content, and assume you have some Fragment subclass that displays anything visible to the user. Try this:

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

    if (savedInstanceState == null) {
        getSupportFragmentManager()
                .beginTransaction()
                .add(R.id.content, new MyFragment(), "MyFragment")
                .commit();
    }
}

As is, this will display your fragment on first launch, and will continue to display the fragment after you rotate your device back and forth. This is because the FragmentManager uses the savedInstanceState bundle to save/restore fragments, and that is done in super.onCreate.

If you change the super call to super.onCreate(null), you'll still see the fragment the first time your activity starts up (since we're manually adding it at that point). But if you rotate the device, the fragment will disappear.


问:
Cannot enqueue Query after invoking quit error
I am trying to query my AWS RDS database by getting a value I submit in an html form to pass to the backend and use it in a SQL statement. This is my form:

```<code>        Show all
        <form method="GET" action="/all">
          <select name="all">
            <option value="crimes">Crimes</option>
            <option value="schools">Schools</option>
            <option value="walkscore">Walkscore</option>
          </select>
            data
          <input type="submit" value="GO!">
        </form>
</code>```

This is my JS code:

```<code>app.get('/all',function(req,res){
    var table = req.query['all'];
    connection.query('SELECT * from ' + table, function(err, rows, fields) {
        if(err) {
          console.log(err);
          res.send(500);
        }
        console.log('The solution is: ', rows);
        connection.end();
        res.send(rows);
    });
});
</code>```

When I do this, it prints in my console after a long time with a list of RowDataPackets, but then it errors out with

Cannot enqueue Query after invoking quit

and

Cannot enqueue Quit after invoking quit.

Clearly it is connecting to the db because I am getting rows. However, it hangs in my browser and gives an internal server error.

How do I fix this to send the response data to the same html page I have my form on for front end parsing?

答:
You're end()ing the connection in your route handler.

That means you can't use the connection anymore.

You should make a new connection every time.

Body:
I am trying to query my AWS RDS database by getting a value I submit in an html form to pass to the backend and use it in a SQL statement. This is my form:

        Show all
        <form method="GET" action="/all">
          <select name="all">
            <option value="crimes">Crimes</option>
            <option value="schools">Schools</option>
            <option value="walkscore">Walkscore</option>
          </select>
            data
          <input type="submit" value="GO!">
        </form>

This is my JS code:

app.get('/all',function(req,res){
    var table = req.query['all'];
    connection.query('SELECT * from ' + table, function(err, rows, fields) {
        if(err) {
          console.log(err);
          res.send(500);
        }
        console.log('The solution is: ', rows);
        connection.end();
        res.send(rows);
    });
});

When I do this, it prints in my console after a long time with a list of RowDataPackets, but then it errors out with

Cannot enqueue Query after invoking quit

and

Cannot enqueue Quit after invoking quit.

Clearly it is connecting to the db because I am getting rows. However, it hangs in my browser and gives an internal server error.

How do I fix this to send the response data to the same html page I have my form on for front end parsing?


问:
get the min value from a count subquery
I working on 2 tables in a trial database stock and sales, I am trying to find the stock item(s) that have had the least number of sales.

The sales table has the following fields: sales_id, transaction_id, stock_id, amount
The stock table has : sid, upc, name, description, amount, price
when I run the following SQL:

```<code>  SELECT st.name,
    COUNT( s.stock_id ) AS num_of_individual_sales
    FROM sales AS s
    JOIN stock as st
    ON st.sid = s.stock_id
    GROUP BY s.stock_id
</code>```

I get:

```<code>banana  7
mars bar    4
fiery hot monster munch 2
WWII hand grenade   4
cheese toastie  2
fish paste  3
belly fluff 2
Unicorn tears   2
spag sauce  4
cooking oil 2
</code>```

So I then try and wrap it up as a sub query:

```<code>SELECT ans.name, MIN(ans.num_of_individual_sales)
FROM
(

SELECT st.name,
COUNT( s.stock_id ) AS num_of_individual_sales
FROM sales AS s
JOIN stock as st
ON st.sid = s.stock_id
GROUP BY s.stock_id

) AS ans
</code>```

The result I'm getting is

banana 2

which even with my non-functioning brain is wrong, I was expecting to get a a recordset with all the 2's (monstermuch, cheese toastie etc)

I have tried loads of different combos but this seems to give the nearest result just not the one I want...

where am I going wrong?

cheers

Zen

UPDATE
worked out at about the same time as Bill Karwin posted that my understanding of the MIN and MAX commands was inaccurate.

I already understood the idea of using an ORDER BY ASC and then I could have used PHP to cut off the data when the COUNT value changed but I'm kind of doing this as a learning exercise so although there may be an easier route I was hoping that it was still possible to do it via the MIN command, I think I need to do a double sub query but have got lost somewhere, this is the newest variant.

```<code>SELECT st.name, st.price,
s.sales_id
From stock AS st
JOIN sales AS s
ON  st.sid = s.stock_id
WHERE COUNT(s.stock_id)=(

SELECT MIN(ans.num_of_individual_sales)
FROM
(

SELECT st.name,
COUNT( s.stock_id ) AS num_of_individual_sales
FROM sales AS s
JOIN stock as st
ON st.sid = s.stock_id
GROUP BY s.stock_id

) AS ans
)GROUP BY s.stock_id
</code>```

but I am getting an invalid group function error

答:
In your query, the value of name does not necessarily come from the same row where the MIN(num_of_individual_sales) is found.

Consider this query:

```<code>SELECT ans.name, MIN(ans.num_of_individual_sales),
  MAX(ans.num_of_individual_sales)
FROM
(
  ...
) AS ans
</code>```

In this example, which name should be output? The one with the min sales or the one with the max sales? What if there are multiple different names that are tied for min or max?

Or this query:

```<code>SELECT ans.name, AVG(ans.num_of_individual_sales)
FROM
(
  ...
) AS ans
</code>```

Which name should be returned if there is no single row returned by the subquery that has exactly the average number of sales? Or more than one row that is the average, but with different names?

The answer to all these questions is: non-aggregated columns return ambiguous results if you are doing an aggregated query. When using strict mode (like in MySQL 5.7 by default), this query will cause an error.

Here's a different solution to get both the min value of sales and the name from the corresponding row:

```<code>SELECT ans.name, ans.num_of_individual_sales
FROM
(
  ...
) AS ans
ORDER BY ans.num_of_individual_sales ASC
LIMIT 1;
</code>```

Title: get the min value from a count subquery

Body:
I working on 2 tables in a trial database stock and sales, I am trying to find the stock item(s) that have had the least number of sales.

The sales table has the following fields: sales_id, transaction_id, stock_id, amount
The stock table has : sid, upc, name, description, amount, price
when I run the following SQL:

  SELECT st.name,
    COUNT( s.stock_id ) AS num_of_individual_sales
    FROM sales AS s
    JOIN stock as st
    ON st.sid = s.stock_id
    GROUP BY s.stock_id

I get:

banana  7
mars bar    4
fiery hot monster munch 2
WWII hand grenade   4
cheese toastie  2
fish paste  3
belly fluff 2
Unicorn tears   2
spag sauce  4
cooking oil 2

So I then try and wrap it up as a sub query:

SELECT ans.name, MIN(ans.num_of_individual_sales)
FROM
(

SELECT st.name,
COUNT( s.stock_id ) AS num_of_individual_sales
FROM sales AS s
JOIN stock as st
ON st.sid = s.stock_id
GROUP BY s.stock_id

) AS ans

The result I'm getting is

banana 2

which even with my non-functioning brain is wrong, I was expecting to get a a recordset with all the 2's (monstermuch, cheese toastie etc)

I have tried loads of different combos but this seems to give the nearest result just not the one I want...

where am I going wrong?

cheers

Zen

UPDATE
worked out at about the same time as Bill Karwin posted that my understanding of the MIN and MAX commands was inaccurate.

I already understood the idea of using an ORDER BY ASC and then I could have used PHP to cut off the data when the COUNT value changed but I'm kind of doing this as a learning exercise so although there may be an easier route I was hoping that it was still possible to do it via the MIN command, I think I need to do a double sub query but have got lost somewhere, this is the newest variant.

SELECT st.name, st.price,
s.sales_id
From stock AS st
JOIN sales AS s
ON  st.sid = s.stock_id
WHERE COUNT(s.stock_id)=(

SELECT MIN(ans.num_of_individual_sales)
FROM
(

SELECT st.name,
COUNT( s.stock_id ) AS num_of_individual_sales
FROM sales AS s
JOIN stock as st
ON st.sid = s.stock_id
GROUP BY s.stock_id

) AS ans
)GROUP BY s.stock_id

but I am getting an invalid group function error

Body:
In your query, the value of name does not necessarily come from the same row where the MIN(num_of_individual_sales) is found.

Consider this query:

SELECT ans.name, MIN(ans.num_of_individual_sales),
  MAX(ans.num_of_individual_sales)
FROM
(
  ...
) AS ans

In this example, which name should be output? The one with the min sales or the one with the max sales? What if there are multiple different names that are tied for min or max?

Or this query:

SELECT ans.name, AVG(ans.num_of_individual_sales)
FROM
(
  ...
) AS ans

Which name should be returned if there is no single row returned by the subquery that has exactly the average number of sales? Or more than one row that is the average, but with different names?

The answer to all these questions is: non-aggregated columns return ambiguous results if you are doing an aggregated query. When using strict mode (like in MySQL 5.7 by default), this query will cause an error.

Here's a different solution to get both the min value of sales and the name from the corresponding row:

SELECT ans.name, ans.num_of_individual_sales
FROM
(
  ...
) AS ans
ORDER BY ans.num_of_individual_sales ASC
LIMIT 1;


问:
What is value of 'if not' in the code?
I'm learning Python and a bit confused what if not doing in the below code? I presume if not is like else statement. But it turns out I'm wrong.  What is the value of if not exists in this code? Also another naive question, the variable exists is defined within a for loop, why is it available globally?

```<code>import scrabble
import string

for letter in string.ascii_lowercase:
    for word in scrabble.wordlist:
        exists = False
        if letter * 2 in word:
            exists = True
            break
    if not exists:
        print(letter)

print(exists) # Globally exists = True
</code>```

答: In python not flips the value of a boolean (true or false) expression. if not x can be read as "if x is false", so the statements inside the if block will execute if exists is equal to False, that is, if no repeat letters have been found.

Title: What is value of 'if not' in the code?

Body:
I'm learning Python and a bit confused what if not doing in the below code? I presume if not is like else statement. But it turns out I'm wrong.  What is the value of if not exists in this code? Also another naive question, the variable exists is defined within a for loop, why is it available globally?

import scrabble
import string

for letter in string.ascii_lowercase:
    for word in scrabble.wordlist:
        exists = False
        if letter * 2 in word:
            exists = True
            break
    if not exists:
        print(letter)

print(exists) # Globally exists = True


问:
Converting Bytes from SQL Server Database to Image in C#
When trying to convert Bytes in my database to an Image to display, when reaching this line:

```<code>Image image = Image.FromStream(ms);
</code>```

The code will jump to a form load in a different form. Any reason why this would be?

Rest of code:

```<code>    private void dataGridView2_SelectionChanged(object sender, EventArgs e)
    {
        //try
        //{

            if (dataGridView2.SelectedCells.Count > 0)
            {
                int selectrowindex = dataGridView2.SelectedCells[0].RowIndex;
                DataGridViewRow selectrow = dataGridView2.Rows[selectrowindex];

                productID = Convert.ToString(selectrow.Cells[0].Value);
                productName.Text = Convert.ToString(selectrow.Cells[1].Value);
                productDetails.Text = ("Desc: " + Convert.ToString(selectrow.Cells[2].Value));
                productPrice.Text = (Convert.ToString(selectrow.Cells[4].Value));
                productStock.Text = Convert.ToString(selectrow.Cells[5].Value);

                db_connection();

                SqlCommand cmd = new SqlCommand("SELECT Image FROM PRODUCTS WHERE ProductID = @ProductID", connect);
                cmd.Parameters.AddWithValue("ProductID", productID);

                SqlDataReader reader = cmd.ExecuteReader();

                reader.Read();

                if (reader.HasRows)
                {
                    byte[] img = (byte[])(reader[0]);
                    if (img == null)
                    {
                        MessageBox.Show("Theres no image");
                        productPictureDisplay.Image = null;
                    }
                    else
                    {
                        MemoryStream ms = new MemoryStream(img);
                        Image image = Image.FromStream(ms);
                        productPictureDisplay.Image = image;
                    }
                }

                connect.Close();

            }
    }
</code>```

答:
try as below , and start making use of using in your code so things get dispose by it (you connection object, memory stream)

```<code>public Image byteArrayToImage(byte[] byteArrayIn)
{
    try
    {
       var ms = new MemoryStream(byteArrayIn);;
          return Image.FromStream(ms);
     }
    catch(Exception ex)
    { console.WriteLine(ex.Tostring()); }
    return returnImage;
}
</code>```

Body:
When trying to convert Bytes in my database to an Image to display, when reaching this line:

Image image = Image.FromStream(ms);

The code will jump to a form load in a different form. Any reason why this would be?

Rest of code:

    private void dataGridView2_SelectionChanged(object sender, EventArgs e)
    {
        //try
        //{

            if (dataGridView2.SelectedCells.Count > 0)
            {
                int selectrowindex = dataGridView2.SelectedCells[0].RowIndex;
                DataGridViewRow selectrow = dataGridView2.Rows[selectrowindex];

                productID = Convert.ToString(selectrow.Cells[0].Value);
                productName.Text = Convert.ToString(selectrow.Cells[1].Value);
                productDetails.Text = ("Desc: " + Convert.ToString(selectrow.Cells[2].Value));
                productPrice.Text = (Convert.ToString(selectrow.Cells[4].Value));
                productStock.Text = Convert.ToString(selectrow.Cells[5].Value);

                db_connection();

                SqlCommand cmd = new SqlCommand("SELECT Image FROM PRODUCTS WHERE ProductID = @ProductID", connect);
                cmd.Parameters.AddWithValue("ProductID", productID);

                SqlDataReader reader = cmd.ExecuteReader();

                reader.Read();

                if (reader.HasRows)
                {
                    byte[] img = (byte[])(reader[0]);
                    if (img == null)
                    {
                        MessageBox.Show("Theres no image");
                        productPictureDisplay.Image = null;
                    }
                    else
                    {
                        MemoryStream ms = new MemoryStream(img);
                        Image image = Image.FromStream(ms);
                        productPictureDisplay.Image = image;
                    }
                }

                connect.Close();

            }
    }

Body:
try as below , and start making use of using in your code so things get dispose by it (you connection object, memory stream)

public Image byteArrayToImage(byte[] byteArrayIn)
{
    try
    {
       var ms = new MemoryStream(byteArrayIn);;
          return Image.FromStream(ms);
     }
    catch(Exception ex)
    { console.WriteLine(ex.Tostring()); }
    return returnImage;
}


问:
PersistenceUnit: default Unable to build Hibernate SessionFactory Spring JPA
I have a class Failure, that should represent a table in the mysql database, but for some reason the table cannot be created. Before I added the class, it worked all perfect, but now I get the following error:

```<code>org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1628) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1078) ~[spring-context-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:857) ~[spring-context-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543) ~[spring-context-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) ~[spring-boot-1.5.8.RELEASE.jar:1.5.8.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:693) [spring-boot-1.5.8.RELEASE.jar:1.5.8.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:360) [spring-boot-1.5.8.RELEASE.jar:1.5.8.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:303) [spring-boot-1.5.8.RELEASE.jar:1.5.8.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1118) [spring-boot-1.5.8.RELEASE.jar:1.5.8.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1107) [spring-boot-1.5.8.RELEASE.jar:1.5.8.RELEASE]
    at com.projekat.kts.KtsApplication.main(KtsApplication.java:10) [classes/:na]
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.persistenceException(EntityManagerFactoryBuilderImpl.java:954) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:882) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
    at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:60) ~[spring-orm-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:353) ~[spring-orm-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:370) ~[spring-orm-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:359) ~[spring-orm-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    ... 16 common frames omitted
Caused by: org.hibernate.tool.schema.spi.SchemaManagementException: Unable to execute schema management to JDBC target [create table failure (id bigint not null auto_increment, date_created datetime, date_solved datetime, desc varchar(255), name varchar(255), solved bit not null, building_id bigint, institution_id bigint, app_user_id bigint, primary key (id))]
    at org.hibernate.tool.schema.internal.TargetDatabaseImpl.accept(TargetDatabaseImpl.java:59) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.tool.schema.internal.SchemaMigratorImpl.applySqlString(SchemaMigratorImpl.java:431) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.tool.schema.internal.SchemaMigratorImpl.applySqlStrings(SchemaMigratorImpl.java:420) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.tool.schema.internal.SchemaMigratorImpl.createTable(SchemaMigratorImpl.java:236) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.tool.schema.internal.SchemaMigratorImpl.doMigrationToTargets(SchemaMigratorImpl.java:167) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.tool.schema.internal.SchemaMigratorImpl.doMigration(SchemaMigratorImpl.java:60) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.tool.hbm2ddl.SchemaUpdate.execute(SchemaUpdate.java:134) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.tool.hbm2ddl.SchemaUpdate.execute(SchemaUpdate.java:101) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:472) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:444) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:879) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
    ... 22 common frames omitted
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'desc varchar(255), name varchar(255), solved bit not null, building_id bigint, i' at line 1
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:1.8.0_151]
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source) ~[na:1.8.0_151]
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source) ~[na:1.8.0_151]
    at java.lang.reflect.Constructor.newInstance(Unknown Source) ~[na:1.8.0_151]
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:425) ~[mysql-connector-java-5.1.44.jar:5.1.44]
    at com.mysql.jdbc.Util.getInstance(Util.java:408) ~[mysql-connector-java-5.1.44.jar:5.1.44]
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:943) ~[mysql-connector-java-5.1.44.jar:5.1.44]
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3973) ~[mysql-connector-java-5.1.44.jar:5.1.44]
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3909) ~[mysql-connector-java-5.1.44.jar:5.1.44]
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2527) ~[mysql-connector-java-5.1.44.jar:5.1.44]
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2680) ~[mysql-connector-java-5.1.44.jar:5.1.44]
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2483) ~[mysql-connector-java-5.1.44.jar:5.1.44]
    at com.mysql.jdbc.StatementImpl.executeUpdateInternal(StatementImpl.java:1552) ~[mysql-connector-java-5.1.44.jar:5.1.44]
    at com.mysql.jdbc.StatementImpl.executeLargeUpdate(StatementImpl.java:2607) ~[mysql-connector-java-5.1.44.jar:5.1.44]
    at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1480) ~[mysql-connector-java-5.1.44.jar:5.1.44]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_151]
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_151]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_151]
    at java.lang.reflect.Method.invoke(Unknown Source) ~[na:1.8.0_151]
    at org.apache.tomcat.jdbc.pool.StatementFacade$StatementProxy.invoke(StatementFacade.java:114) ~[tomcat-jdbc-8.5.23.jar:na]
    at com.sun.proxy.$Proxy86.executeUpdate(Unknown Source) ~[na:na]
    at org.hibernate.tool.schema.internal.TargetDatabaseImpl.accept(TargetDatabaseImpl.java:56) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    ... 32 common frames omitted
</code>```

The class looks like this:

```<code>@Entity
public class Failure implements Serializable {

    /**
     *
     */
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private String name;
    private String desc; // Opis kvara

    @Temporal(TemporalType.TIMESTAMP)
    private Date dateCreated; // Datum i vreme kada je kvar kreiran

    @Temporal(TemporalType.TIMESTAMP)
    private Date dateSolved; // Datum i vreme kada je kvar popravljen

    private boolean solved; // Da li je kvar popravljen

    @ManyToOne
    @JoinColumn(name = "app_user_id")
    @JsonIgnoreProperties(value = {"failures"}, allowSetters=true)
    private AppUser worker; // Radnik koji je zaduzen za kvar

    @ManyToOne
    @JoinColumn(name = "institution_id")
    @JsonIgnoreProperties(value = {"failures"}, allowSetters=true)
    private Institution institution; // Institucija kojoj je kvar prijavljen

    @ManyToOne
    @JoinColumn(name = "building_id")
    @JsonIgnoreProperties(value = {"failures"}, allowSetters=true)
    private Building building; // Zgrada u kojoj je kvar nastao

    public Failure(){}

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDesc() {
        return desc;
    }

    public void setDesc(String desc) {
        this.desc = desc;
    }

    public Date getDateCreated() {
        return dateCreated;
    }

    public void setDateCreated(Date dateCreated) {
        this.dateCreated = dateCreated;
    }

    public Date getDateSolved() {
        return dateSolved;
    }

    public void setDateSolved(Date dateSolved) {
        this.dateSolved = dateSolved;
    }

    public boolean isSolved() {
        return solved;
    }

    public void setSolved(boolean solved) {
        this.solved = solved;
    }

    public AppUser getWorker() {
        return worker;
    }

    public void setWorker(AppUser worker) {
        this.worker = worker;
    }

    public Institution getInstitution() {
        return institution;
    }

    public void setInstitution(Institution institution) {
        this.institution = institution;
    }

    public Building getBuilding() {
        return building;
    }

    public void setBuilding(Building building) {
        this.building = building;
    }
}
</code>```

I built all the other classes the same way and it worked perfect, but when I added this class for some reason it won't work anymore. I tried to change

```<code>spring.jpa.hibernate.ddl-auto=update
</code>```

to:

```<code>spring.jpa.hibernate.ddl-auto=create
</code>```

And in that case I don't the error but the table failure is not created at all.
I really can't figure it out, I would appreciate your help. Thank you in advance.

答:
Don't use desc as a column name. It's a SQL keyword. And description is much clearer anyway.

Note: I just had to read the error to find out the problem:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'desc varchar(255) ...

Body:
I have a class Failure, that should represent a table in the mysql database, but for some reason the table cannot be created. Before I added the class, it worked all perfect, but now I get the following error:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1628) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1078) ~[spring-context-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:857) ~[spring-context-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543) ~[spring-context-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) ~[spring-boot-1.5.8.RELEASE.jar:1.5.8.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:693) [spring-boot-1.5.8.RELEASE.jar:1.5.8.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:360) [spring-boot-1.5.8.RELEASE.jar:1.5.8.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:303) [spring-boot-1.5.8.RELEASE.jar:1.5.8.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1118) [spring-boot-1.5.8.RELEASE.jar:1.5.8.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1107) [spring-boot-1.5.8.RELEASE.jar:1.5.8.RELEASE]
    at com.projekat.kts.KtsApplication.main(KtsApplication.java:10) [classes/:na]
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.persistenceException(EntityManagerFactoryBuilderImpl.java:954) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:882) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
    at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:60) ~[spring-orm-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:353) ~[spring-orm-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:370) ~[spring-orm-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:359) ~[spring-orm-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    ... 16 common frames omitted
Caused by: org.hibernate.tool.schema.spi.SchemaManagementException: Unable to execute schema management to JDBC target [create table failure (id bigint not null auto_increment, date_created datetime, date_solved datetime, desc varchar(255), name varchar(255), solved bit not null, building_id bigint, institution_id bigint, app_user_id bigint, primary key (id))]
    at org.hibernate.tool.schema.internal.TargetDatabaseImpl.accept(TargetDatabaseImpl.java:59) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.tool.schema.internal.SchemaMigratorImpl.applySqlString(SchemaMigratorImpl.java:431) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.tool.schema.internal.SchemaMigratorImpl.applySqlStrings(SchemaMigratorImpl.java:420) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.tool.schema.internal.SchemaMigratorImpl.createTable(SchemaMigratorImpl.java:236) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.tool.schema.internal.SchemaMigratorImpl.doMigrationToTargets(SchemaMigratorImpl.java:167) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.tool.schema.internal.SchemaMigratorImpl.doMigration(SchemaMigratorImpl.java:60) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.tool.hbm2ddl.SchemaUpdate.execute(SchemaUpdate.java:134) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.tool.hbm2ddl.SchemaUpdate.execute(SchemaUpdate.java:101) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:472) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:444) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:879) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
    ... 22 common frames omitted
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'desc varchar(255), name varchar(255), solved bit not null, building_id bigint, i' at line 1
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:1.8.0_151]
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source) ~[na:1.8.0_151]
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source) ~[na:1.8.0_151]
    at java.lang.reflect.Constructor.newInstance(Unknown Source) ~[na:1.8.0_151]
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:425) ~[mysql-connector-java-5.1.44.jar:5.1.44]
    at com.mysql.jdbc.Util.getInstance(Util.java:408) ~[mysql-connector-java-5.1.44.jar:5.1.44]
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:943) ~[mysql-connector-java-5.1.44.jar:5.1.44]
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3973) ~[mysql-connector-java-5.1.44.jar:5.1.44]
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3909) ~[mysql-connector-java-5.1.44.jar:5.1.44]
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2527) ~[mysql-connector-java-5.1.44.jar:5.1.44]
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2680) ~[mysql-connector-java-5.1.44.jar:5.1.44]
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2483) ~[mysql-connector-java-5.1.44.jar:5.1.44]
    at com.mysql.jdbc.StatementImpl.executeUpdateInternal(StatementImpl.java:1552) ~[mysql-connector-java-5.1.44.jar:5.1.44]
    at com.mysql.jdbc.StatementImpl.executeLargeUpdate(StatementImpl.java:2607) ~[mysql-connector-java-5.1.44.jar:5.1.44]
    at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1480) ~[mysql-connector-java-5.1.44.jar:5.1.44]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_151]
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_151]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_151]
    at java.lang.reflect.Method.invoke(Unknown Source) ~[na:1.8.0_151]
    at org.apache.tomcat.jdbc.pool.StatementFacade$StatementProxy.invoke(StatementFacade.java:114) ~[tomcat-jdbc-8.5.23.jar:na]
    at com.sun.proxy.$Proxy86.executeUpdate(Unknown Source) ~[na:na]
    at org.hibernate.tool.schema.internal.TargetDatabaseImpl.accept(TargetDatabaseImpl.java:56) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    ... 32 common frames omitted

The class looks like this:

@Entity
public class Failure implements Serializable {

    /**
     *
     */
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private String name;
    private String desc; // Opis kvara

    @Temporal(TemporalType.TIMESTAMP)
    private Date dateCreated; // Datum i vreme kada je kvar kreiran

    @Temporal(TemporalType.TIMESTAMP)
    private Date dateSolved; // Datum i vreme kada je kvar popravljen

    private boolean solved; // Da li je kvar popravljen

    @ManyToOne
    @JoinColumn(name = "app_user_id")
    @JsonIgnoreProperties(value = {"failures"}, allowSetters=true)
    private AppUser worker; // Radnik koji je zaduzen za kvar

    @ManyToOne
    @JoinColumn(name = "institution_id")
    @JsonIgnoreProperties(value = {"failures"}, allowSetters=true)
    private Institution institution; // Institucija kojoj je kvar prijavljen

    @ManyToOne
    @JoinColumn(name = "building_id")
    @JsonIgnoreProperties(value = {"failures"}, allowSetters=true)
    private Building building; // Zgrada u kojoj je kvar nastao

    public Failure(){}

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDesc() {
        return desc;
    }

    public void setDesc(String desc) {
        this.desc = desc;
    }

    public Date getDateCreated() {
        return dateCreated;
    }

    public void setDateCreated(Date dateCreated) {
        this.dateCreated = dateCreated;
    }

    public Date getDateSolved() {
        return dateSolved;
    }

    public void setDateSolved(Date dateSolved) {
        this.dateSolved = dateSolved;
    }

    public boolean isSolved() {
        return solved;
    }

    public void setSolved(boolean solved) {
        this.solved = solved;
    }

    public AppUser getWorker() {
        return worker;
    }

    public void setWorker(AppUser worker) {
        this.worker = worker;
    }

    public Institution getInstitution() {
        return institution;
    }

    public void setInstitution(Institution institution) {
        this.institution = institution;
    }

    public Building getBuilding() {
        return building;
    }

    public void setBuilding(Building building) {
        this.building = building;
    }
}

I built all the other classes the same way and it worked perfect, but when I added this class for some reason it won't work anymore. I tried to change

spring.jpa.hibernate.ddl-auto=update

to:

spring.jpa.hibernate.ddl-auto=create

And in that case I don't the error but the table failure is not created at all.
I really can't figure it out, I would appreciate your help. Thank you in advance.


问:
Azure Service Fabric : Creating a proxy with the partition key ID (Int64RangePartitionInformation)
I have a little problem to solve at the moment and it seems that I am not finding the right solution for me in the SF Framework. The problem is simple though and consists in:

I have a Int64RangePartition that allows me to find all the partitions of the service through:

_fabricClient.QueryManager.GetPartitionListAsync(_globalStatsSvcUri)

This works fine but unlike the NamedPartitions scheme it seems not possible to create a service proxy (with remoting) to use the service without providing the Int key.

IGlobalStatsSvc globalStatsSvc = ServiceProxy.Create(_globalStatsSvcUri, partitionKey);

My specific case is that I want to be able to scale a parallel statistics computation service but want to be able to keep a connection with the profiles IDs. Therefore I would like to choose the Int64RangePartition scheme.

But when I need to query the global statistics of the system I need to call all the partitions in parallel and then aggregate the Avg, Variance and Std with the Chan' algorithm.

In order to do so, I need to be able to create a proxy without knowing which Int key is mapping to the partition. I need only the partition Key Id.

Sadly, it seems that SF allows only to do the latter in the NamedPartition scheme and not the RangedPartition.

Has anyone a solution for this particular case? Choosing the NamedPartition scheme could work but it is more complicated in the case the stats are modified (need at least to ensure that the random partition name is compatible statistically). The other solution would be to "manually" create the proxy to the service as I should be able to build the URL with the partition ID I resolved. But it is more work and by pass the strongly typed client provided by SF.

It would be much simpler to mix the two behaviours with the RangedPartition scheme, as I would be able to know which partition to modify at edit time and then query all partitions at reading time when I need to do the aggregation.

答:
Found the solution to the problem, I am still pretty new to the SF Framework but when one queries the partitions list of a service, information about the low and high key of the specific partition is given.

Therefore one only needs to pass those IDs before a call to the service via a proxy.

Simple enough:

```<code>var partitionInformation = partition.PartitionInformation as Int64RangePartitionInformation;
var partitionKey = new ServicePartitionKey(partitionInformation.LowKey);
</code>```

Body:
Found the solution to the problem, I am still pretty new to the SF Framework but when one queries the partitions list of a service, information about the low and high key of the specific partition is given.

Therefore one only needs to pass those IDs before a call to the service via a proxy.

Simple enough:

var partitionInformation = partition.PartitionInformation as Int64RangePartitionInformation;
var partitionKey = new ServicePartitionKey(partitionInformation.LowKey);


问:
WebStorm expecting multiple arguments for $.insertBefore()?
I have the following code which is currently working as desired.  It inserts elements into objGrid according to the property loadOrder.

```<code>let $elTileTitle = $('<div/>', { class: 'tileTitle', html: tile.title });

let $elNext;
for (let i = tile.loadOrder; i < objectLength(tiles); i++) {
    let $potentialNext = $(`.tile[data-loadorder="${i}"]`);
    if ($potentialNext.length > 0) {
        $elNext = $potentialNext;
        break;
    }
}
if (typeof $elNext !== 'undefined') {
    $elTile.insertBefore($elNext);
} else {
    let $elPrev;
    for (let i = tile.loadOrder; i < 0; i--) {
        let $potentialPrev = $(`.tile[data-loadorder="${i}"]`);
        if ($potentialPrev.length > 0) {
            $elPrev = $potentialPrev;
            break;
        }
    }
    if (typeof $elPrev !== 'undefined') {
        $elTile.insertAfter($elPrev);
    } else {
        $elTile.appendTo(objGrid);
    }
}
</code>```

As stated, this seems to work well.  But I noticed a warning in my IDE that insertBefore() had an invalid number of arguments.  After viewing the documentation, I replaced that line with this:

```<code>$('#grid').insertBefore($elTile,$elNext);
</code>```

This has presented odd behavior.  After this code runs, $('#grid') is empty.  Oddly, all the tiles exist in the DOM (ie, if I type $('#tile-store') in the console, I get an object back with all the expected properties), however I cannot find them in the HTML ("Elements" tab) and the UI is blank.

Is there something obvious I'm doing wrong? I can provide more information if needed

答:
But I noticed a warning in my IDE that insertBefore() had an invalid number of arguments.

Your IDE is mistaken. It's mistakenly applying the rules for the DOM's insertBefore to your use of jQuery's insertBefore. Your original use of jQuery's is just fine. If you were using the DOM's, you'd need to give it another argument. But they're completely different functions.

Body:
I have the following code which is currently working as desired.  It inserts elements into objGrid according to the property loadOrder.

let $elTileTitle = $('
', { class: 'tileTitle', html: tile.title });

let $elNext;
for (let i = tile.loadOrder; i < objectLength(tiles); i++) {
    let $potentialNext = $(`.tile[data-loadorder="${i}"]`);
    if ($potentialNext.length > 0) {
        $elNext = $potentialNext;
        break;
    }
}
if (typeof $elNext !== 'undefined') {
    $elTile.insertBefore($elNext);
} else {
    let $elPrev;
    for (let i = tile.loadOrder; i < 0; i--) {
        let $potentialPrev = $(`.tile[data-loadorder="${i}"]`);
        if ($potentialPrev.length > 0) {
            $elPrev = $potentialPrev;
            break;
        }
    }
    if (typeof $elPrev !== 'undefined') {
        $elTile.insertAfter($elPrev);
    } else {
        $elTile.appendTo(objGrid);
    }
}

As stated, this seems to work well.  But I noticed a warning in my IDE that insertBefore() had an invalid number of arguments.  After viewing the documentation, I replaced that line with this:

$('#grid').insertBefore($elTile,$elNext);

This has presented odd behavior.  After this code runs, $('#grid') is empty.  Oddly, all the tiles exist in the DOM (ie, if I type $('#tile-store') in the console, I get an object back with all the expected properties), however I cannot find them in the HTML ("Elements" tab) and the UI is blank.

Is there something obvious I'm doing wrong? I can provide more information if needed


问:
"IndexError: list index out of range" While using recursion on lists
I'm a programming student and I have just recently started working in Python. I started with learning Rackett which has a very different approach. While trying to use recursion in combination with a for statement I ran into "IndexError: list index out of range". This is my code:

```<code>def search_matching_pokemon(p, l):
    lp = []
    for i in range(len(l) - 1):
        if p[-1] == l[i][0]:
            print ('Found one')
            poke = l.pop(i)
            lp = lp + [poke]
            print (f'List is now {lp}')
            search_matching_pokemon(poke, l)    #problem with the range
        else:
            print ('Trying a different pokémon')
    return lp
</code>```

I think my function doesn't take the reduced list when recursing, at least not during the
range(len(l) - 1)
Help would be very much appreciated, thank you in advance.

答: I can't be sure without more information, but it looks like the problem is that you are popping from the list while iterating over it. Again, without more information (like what you are trying to do), I can't be sure how to fix this.</p>

Body:
I'm a programming student and I have just recently started working in Python. I started with learning Rackett which has a very different approach. While trying to use recursion in combination with a for statement I ran into "IndexError: list index out of range". This is my code:

def search_matching_pokemon(p, l):
    lp = []
    for i in range(len(l) - 1):
        if p[-1] == l[i][0]:
            print ('Found one')
            poke = l.pop(i)
            lp = lp + [poke]
            print (f'List is now {lp}')
            search_matching_pokemon(poke, l)    #problem with the range
        else:
            print ('Trying a different pokémon')
    return lp

I think my function doesn't take the reduced list when recursing, at least not during the
range(len(l) - 1)
Help would be very much appreciated, thank you in advance.


问:
Is there a way to search a String of lyrics then substring out the matching phrases
I need to search lyrics for a matching phrase.

For example:

I have song lyrics like these.

"She is the one that I love, I know it something something something something something she loves you and me something something something."

Given this search term below, search the lyrics for the closest match and count the characters in the sub string. My issue is finding the closest match using indexOf returns the first SHE. I need the to be able to sub string out the closes matching phrase.

The results should print :

The closest matching search for 'she loves me' is "she loves you and me".

Index Length: 20

答:
I know its not the most optimized or the efficient one. But, the following code will work for most keywords.

```<code>import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

public class KeywordSearch {

    public static void main(String[] args) {
        System.out.println(getMatchingLyrics("She is the one that I love, "
                + "I know it something something something something something "
                + "she loves you and me something something something.",
                Arrays.asList("she you".toLowerCase().split(" "))));
    }

    private static String getMatchingLyrics(String lyrics, List<String> keywords) {
        String[] lyricWords = lyrics.split(" ");

        // Split and get the word index for keyword matches
        Map<Integer, String> lyricEngine = new TreeMap<>();
        for(int i = 0; i < lyricWords.length; i++) {
            String search = lyricWords[i].toLowerCase().replaceAll("[^a-zA-Z0-9]", "");
            if (keywords.contains(search) && !lyricEngine.values().contains(lyricWords[i])) {
                lyricEngine.put(i, lyricWords[i]);
            }
        }

        Integer min = null;
        Integer max = null;
        if (lyricEngine.size() == 1) {
            return lyricEngine.values().iterator().next();
        } else if (lyricEngine.size() <= keywords.size()) {
            List<Integer> coll = new ArrayList<>(lyricEngine.keySet());
            min = coll.get(0);
            max = coll.get(lyricEngine.size() - 1);
        } else {
            // Prepare the difference between the indexes
            Map<Integer, String> set = new TreeMap<>();
            List<Integer> keys = new ArrayList<>(lyricEngine.keySet());
            for(int i=0; i <= lyricEngine.size() - keywords.size(); i++) {
                int j = i + keywords.size() - 1;
                int diff = keys.get(j);
                StringBuilder str = new StringBuilder(keys.get(j) + "");
                for (j = j - 1; j >= i; j--) {
                    diff -= keys.get(j);
                    str.append(',');
                    str.append(keys.get(j));
                }
                set.put(diff, str.toString());
            }

            // Get the value with minimum difference
            for(String s:set.get(set.keySet().toArray()[0]).split(",")) {
                int x = Integer.parseInt(s);
                if (min == null && max == null) {
                    max = x;
                    min = x;
                } else {
                    if (x > max) {
                        max = x;
                    } else if (x < min) {
                        min = x;
                    }
                }
            }
        }

        // Build the string from indexes
        StringBuilder s = new StringBuilder();
        for (int i = min; i <= max; i++) {
            s.append(lyricWords[i]);
            if (i < max) {
                s.append(" ");
            }
        }
        return s.toString();
    }
}
</code>```

You can build and optimize it as per your need. Explanations are given as comments. If you have any doubt, feel free to ask me in DM or comments.

For different keywords,

```<code>Keyword: she loves me
Output: she loves you and me

Keyword: I love it
Output: I love, I know it

Keyword: she is one love
Output: She is the one that I love,
</code>```

Body:
I know its not the most optimized or the efficient one. But, the following code will work for most keywords.

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

public class KeywordSearch {

    public static void main(String[] args) {
        System.out.println(getMatchingLyrics("She is the one that I love, "
                + "I know it something something something something something "
                + "she loves you and me something something something.",
                Arrays.asList("she you".toLowerCase().split(" "))));
    }

    private static String getMatchingLyrics(String lyrics, List<String> keywords) {
        String[] lyricWords = lyrics.split(" ");

        // Split and get the word index for keyword matches
        Map<Integer, String> lyricEngine = new TreeMap<>();
        for(int i = 0; i < lyricWords.length; i++) {
            String search = lyricWords[i].toLowerCase().replaceAll("[^a-zA-Z0-9]", "");
            if (keywords.contains(search) && !lyricEngine.values().contains(lyricWords[i])) {
                lyricEngine.put(i, lyricWords[i]);
            }
        }

        Integer min = null;
        Integer max = null;
        if (lyricEngine.size() == 1) {
            return lyricEngine.values().iterator().next();
        } else if (lyricEngine.size() <= keywords.size()) {
            List<Integer> coll = new ArrayList<>(lyricEngine.keySet());
            min = coll.get(0);
            max = coll.get(lyricEngine.size() - 1);
        } else {
            // Prepare the difference between the indexes
            Map<Integer, String> set = new TreeMap<>();
            List<Integer> keys = new ArrayList<>(lyricEngine.keySet());
            for(int i=0; i <= lyricEngine.size() - keywords.size(); i++) {
                int j = i + keywords.size() - 1;
                int diff = keys.get(j);
                StringBuilder str = new StringBuilder(keys.get(j) + "");
                for (j = j - 1; j >= i; j--) {
                    diff -= keys.get(j);
                    str.append(',');
                    str.append(keys.get(j));
                }
                set.put(diff, str.toString());
            }

            // Get the value with minimum difference
            for(String s:set.get(set.keySet().toArray()[0]).split(",")) {
                int x = Integer.parseInt(s);
                if (min == null && max == null) {
                    max = x;
                    min = x;
                } else {
                    if (x > max) {
                        max = x;
                    } else if (x < min) {
                        min = x;
                    }
                }
            }
        }

        // Build the string from indexes
        StringBuilder s = new StringBuilder();
        for (int i = min; i <= max; i++) {
            s.append(lyricWords[i]);
            if (i < max) {
                s.append(" ");
            }
        }
        return s.toString();
    }
}

You can build and optimize it as per your need. Explanations are given as comments. If you have any doubt, feel free to ask me in DM or comments.

For different keywords,

Keyword: she loves me
Output: she loves you and me

Keyword: I love it
Output: I love, I know it

Keyword: she is one love
Output: She is the one that I love,


问:
Android Studio - Unable to import class after added dependency in build.gradle
I am unable to import class after added dependency in build.gradle.

```<code>dependencies {
    ...
    compile 'com.mcxiaoke.volley:library:1.0.19'
}
</code>```

Sync it with no error. Did some search about this issue. I found that it may be related to Project Structure -> Project -> Plugin Version. Imported module in Android Studio can't find imported class But I am not sure what version I should use.

My project version

```<code>Gradle version: 4.1
Android Plugin Version 3.0.1
</code>```

答:
mcxiaoke library is  depricated now

```<code>      com.mcxiaoke.volley:library:1.0.19'
</code>```

try official by google

try replacing your compile with this

```<code> compile 'com.android.volley:volley:1.0.0'
</code>```

Body:
I am unable to import class after added dependency in build.gradle.

dependencies {
    ...
    compile 'com.mcxiaoke.volley:library:1.0.19'
}

Sync it with no error. Did some search about this issue. I found that it may be related to Project Structure -> Project -> Plugin Version. Imported module in Android Studio can't find imported class But I am not sure what version I should use.

My project version

Gradle version: 4.1
Android Plugin Version 3.0.1

Body:
mcxiaoke library is  depricated now

      com.mcxiaoke.volley:library:1.0.19'

try official by google

try replacing your compile with this

 compile 'com.android.volley:volley:1.0.0'