问:
Bison & flex error
I'm not very experienced in bison and flex and i need some help.

i have some errors in my .y file.

syntax wise its fine and it compiles when i "bison -d" it
but when i try to compile with gcc it gives me some errors that im not sure how to solve(total noob here):

https://i.stack.imgur.com/fUeR7.png

the .lex file:

```<code>%{
#include "meals.tab.h"
#include <string.h>

extern void exit(int);
int line = 1;

#define VEGETABLE 1
#define FRUIT 2
#define BREAD 3
#define MEAT 4
#define CAKE 5
#define CHOCOLATE_ICE_CREAM 6
#define VANILLA_ICE_CREAM 7
#define BEGIN_MEAL 100
#define END_MEAL 101

%}

%option noyywrap

%%

"<meal>"    {return BEGIN_MEAL;}
"</meal>"   {return END_MEAL;}

"broccoli"      {return VEGETABLE;}
"lettuce"       {return VEGETABLE;}
"tomato"        {return VEGETABLE;}
"cucumber"  {return VEGETABLE;}
"orange"        {return FRUIT;}
"apple"     {return FRUIT;}
"strawberry"    {return FRUIT;}
"watermelon"    {return FRUIT;}
"chicken"       {return MEAT;}
"beef"      {return MEAT;}
"bread"     {return BREAD;}
"cake"      {return CAKE}
"chocolate ice cream"   {return CHOCOLATE_ICE_CREAM ;}
"vanilla ice cream"     {return VANILLA_ICE_CREAM ;}

","     /* skip comma */
[\t ]+      /* skip white space */
\n         { line++; }
.   { fprintf (stderr, "line %d: unrecognized token %c\n",
                               line, yytext[0]);
                exit(1);
            }

%%
</code>```

the .y file:

```<code>%code {

#include <stdio.h>

extern int yylex (void);
void yyerror (const char *s);

struct diet
}

%code requires {
    struct diet {
        int veg_fruit, dessert, calories, isDesertFine, isVeggieFine;
    };
}
%union {
    struct diet _diet;
}

%token BEGIN_MEAL END_MEAL VEGETABLE FRUIT MEAT BREAD CAKE CHOCOLATE_ICE_CREAM VANILLA_ICE_CREAM
%type <_diet> list_of_meals meal list_of_servings serving

%error-verbose

%%

day: list_of_meals{
                    if(($1.calories <= 18) && ($1.isDesertFine == 0) && ($1.isVeggieFine == 0))
                    printf ("everything is OK\n");
                    else if($1.calories <= 18 && $1.isDesertFine == 0)
                    printf ("Not enough veggies/fruits\n");
                    else if($1.calories <= 18 && $1.isVeggieFine == 0)
                    printf ("Too many desserts\n");
                    else if($1.isDesertFine == 0 && $1.isVeggieFine == 0)
                    printf ("Too many calories: total is $1.calories\n");
                    else if($1.calories <= 18){
                    printf ("Too many desserts\n");
                    printf ("Not enough veggies/fruits\n");
                    }
                    else if($1.isDesertFine == 0){
                    printf ("Too many calories: total is $1.calories\n");
                    printf ("Not enough veggies/fruits\n");
                    }
                    else if($1.isVeggieFine == 0){
                    printf ("Too many desserts\n");
                    printf ("Too many calories: total is $1.calories\n");
                    }
                    else{
                    printf ("Too many calories: total is $1.calories\n");
                    printf ("Too many desserts\n");
                    printf ("Not enough veggies/fruits\n");
                    }
                    };

list_of_meals: list_of_meals meal {$$.calories = $1.calories + $2.calories;
                                    $$.isDesertFine = $1.isDesertFine + $2.isDesertFine;
                                    $$.isVeggieFine = $1.isVeggieFine + $2.isVeggieFine;};

list_of_meals:  /*empty*/ {$$.calories = -1;
                                $$.veg_fruit = -1;
                                $$.dessert = -1;
                                $$.isVeggieFine = 1;
                                };
meal: BEGIN_MEAL list_of_servings END_MEAL {if($2.calories > 18)
                                            printf ("Meal : too many calories\n");
                                            if($2.veg_fruit < 2){
                                            printf ("Meal : not enough veggies/fruit\n");
                                            $$.isVeggieFine = 1;
                                            }else{ $$.isVeggieFine = 0;}
                                            if($2.dessert > 1){
                                            printf ("Meal : too many desserts\n");
                                            $$.isDesertFine = 1;
                                            }else{ $$.isDesertFine = 0;}

                                            $$.calories = $2.calories;
                                            };

list_of_servings: list_of_servings ',' serving {$$.calories = $1.calories + $3.calories;
                                                $$.veg_fruit = $1.veg_fruit + $3.veg_fruit;
                                                $$.dessert = $1.dessert + $3.dessert;};

list_of_servings: serving {$$.calories = $1.calories;
                            $$.veg_fruit = $1.veg_fruit;
                            $$.dessert = $1.dessert;};

serving:  VEGETABLE {$$.calories = 1; $$.veg_fruit = 1;}
        | FRUIT {$$.calories = 2; $$.veg_fruit = 1;}
        | MEAT {$$.calories = 3;}
        | BREAD {$$.calories = 4;}
        | CAKE{$$.calories = 5; $$.dessert = 1;}
        | CHOCOLATE_ICE_CREAM{$$.calories = 6; $$.dessert = 1;}
        | VANILLA_ICE_CREAM {$$.calories = 7; $$.dessert = 1;}
        ;

%%

#include <stdio.h>
#include <stdlib.h>

main (int argc, char **argv)
{
  extern FILE *yyin;
  if (argc != 2) {
     fprintf (stderr, "Usage: %s <input-file-name>\n", argv[0]);
     return 1;
  }
  yyin = fopen (argv [1], "r");
  if (yyin == NULL) {
       fprintf (stderr, "failed to open %s\n", argv[1]);
       return 2;
  }

  yyparse ();

  fclose (yyin);
  return 0;
}

void yyerror (const char *s)
{
  extern int line;
  fprintf (stderr, "line %d: %s\n", line, s);
}
</code>```

Thanks!

答:
The problem is the C syntax error in the first %code section in your bison file:

```<code>struct diet
</code>```

That's missing a semicolon, and will create a variety of unpredictable compile errors when eventually passed to a C compiler.

However, the declaration is unnecessary, and should simply be removed.

There are also some issues with your flex file:

Don't do this:

```<code>#define VEGETABLE 1
#define FRUIT 2
...
</code>```

The correct token definitions are in the header file created by bison, which you have already included. The values you provide are incorrect and will cause parsing to fail.

Don't do this either:

```<code>extern void exit(int);
</code>```

exit is declared in the standard header stdlib.h; you should include that header file instead of second-guessing its contents:

```<code>#include <stdlib.h>
#include <string.h>
#include "meals.tab.h"
</code>```

Note that it is conventional to include system headers before including your own headers (such as the one generated by bison).

Finally, I strongly recommend that you remove your own attempt to track line numbers in line, and instead just let flex do it:

```<code>%option yylineno
</code>```

will cause flex to insert efficient code to maintain the current line number in the variable yylineno. Furthermore, it will maintain the line number correctly, since it understands all the corner cases. (Unless you sidestep flex processing by using input() to directly read from yyin.)

Title: Bison & flex error

Body:
I'm not very experienced in bison and flex and i need some help.

i have some errors in my .y file.

syntax wise its fine and it compiles when i "bison -d" it
but when i try to compile with gcc it gives me some errors that im not sure how to solve(total noob here):

https://i.stack.imgur.com/fUeR7.png

the .lex file:

%{
#include "meals.tab.h"
#include <string.h>

extern void exit(int);
int line = 1;

#define VEGETABLE 1
#define FRUIT 2
#define BREAD 3
#define MEAT 4
#define CAKE 5
#define CHOCOLATE_ICE_CREAM 6
#define VANILLA_ICE_CREAM 7
#define BEGIN_MEAL 100
#define END_MEAL 101

%}

%option noyywrap

%%

"<meal>"    {return BEGIN_MEAL;}
"</meal>"   {return END_MEAL;}

"broccoli"      {return VEGETABLE;}
"lettuce"       {return VEGETABLE;}
"tomato"        {return VEGETABLE;}
"cucumber"  {return VEGETABLE;}
"orange"        {return FRUIT;}
"apple"     {return FRUIT;}
"strawberry"    {return FRUIT;}
"watermelon"    {return FRUIT;}
"chicken"       {return MEAT;}
"beef"      {return MEAT;}
"bread"     {return BREAD;}
"cake"      {return CAKE}
"chocolate ice cream"   {return CHOCOLATE_ICE_CREAM ;}
"vanilla ice cream"     {return VANILLA_ICE_CREAM ;}

","     /* skip comma */
[\t ]+      /* skip white space */
\n         { line++; }
.   { fprintf (stderr, "line %d: unrecognized token %c\n",
                               line, yytext[0]);
                exit(1);
            }

%%

the .y file:

%code {

#include <stdio.h>

extern int yylex (void);
void yyerror (const char *s);

struct diet
}

%code requires {
    struct diet {
        int veg_fruit, dessert, calories, isDesertFine, isVeggieFine;
    };
}
%union {
    struct diet _diet;
}

%token BEGIN_MEAL END_MEAL VEGETABLE FRUIT MEAT BREAD CAKE CHOCOLATE_ICE_CREAM VANILLA_ICE_CREAM
%type <_diet> list_of_meals meal list_of_servings serving

%error-verbose

%%

day: list_of_meals{
                    if(($1.calories <= 18) && ($1.isDesertFine == 0) && ($1.isVeggieFine == 0))
                    printf ("everything is OK\n");
                    else if($1.calories <= 18 && $1.isDesertFine == 0)
                    printf ("Not enough veggies/fruits\n");
                    else if($1.calories <= 18 && $1.isVeggieFine == 0)
                    printf ("Too many desserts\n");
                    else if($1.isDesertFine == 0 && $1.isVeggieFine == 0)
                    printf ("Too many calories: total is $1.calories\n");
                    else if($1.calories <= 18){
                    printf ("Too many desserts\n");
                    printf ("Not enough veggies/fruits\n");
                    }
                    else if($1.isDesertFine == 0){
                    printf ("Too many calories: total is $1.calories\n");
                    printf ("Not enough veggies/fruits\n");
                    }
                    else if($1.isVeggieFine == 0){
                    printf ("Too many desserts\n");
                    printf ("Too many calories: total is $1.calories\n");
                    }
                    else{
                    printf ("Too many calories: total is $1.calories\n");
                    printf ("Too many desserts\n");
                    printf ("Not enough veggies/fruits\n");
                    }
                    };

list_of_meals: list_of_meals meal {$$.calories = $1.calories + $2.calories;
                                    $$.isDesertFine = $1.isDesertFine + $2.isDesertFine;
                                    $$.isVeggieFine = $1.isVeggieFine + $2.isVeggieFine;};

list_of_meals:  /*empty*/ {$$.calories = -1;
                                $$.veg_fruit = -1;
                                $$.dessert = -1;
                                $$.isVeggieFine = 1;
                                };
meal: BEGIN_MEAL list_of_servings END_MEAL {if($2.calories > 18)
                                            printf ("Meal : too many calories\n");
                                            if($2.veg_fruit < 2){
                                            printf ("Meal : not enough veggies/fruit\n");
                                            $$.isVeggieFine = 1;
                                            }else{ $$.isVeggieFine = 0;}
                                            if($2.dessert > 1){
                                            printf ("Meal : too many desserts\n");
                                            $$.isDesertFine = 1;
                                            }else{ $$.isDesertFine = 0;}

                                            $$.calories = $2.calories;
                                            };

list_of_servings: list_of_servings ',' serving {$$.calories = $1.calories + $3.calories;
                                                $$.veg_fruit = $1.veg_fruit + $3.veg_fruit;
                                                $$.dessert = $1.dessert + $3.dessert;};

list_of_servings: serving {$$.calories = $1.calories;
                            $$.veg_fruit = $1.veg_fruit;
                            $$.dessert = $1.dessert;};

serving:  VEGETABLE {$$.calories = 1; $$.veg_fruit = 1;}
        | FRUIT {$$.calories = 2; $$.veg_fruit = 1;}
        | MEAT {$$.calories = 3;}
        | BREAD {$$.calories = 4;}
        | CAKE{$$.calories = 5; $$.dessert = 1;}
        | CHOCOLATE_ICE_CREAM{$$.calories = 6; $$.dessert = 1;}
        | VANILLA_ICE_CREAM {$$.calories = 7; $$.dessert = 1;}
        ;

%%

#include <stdio.h>
#include <stdlib.h>

main (int argc, char **argv)
{
  extern FILE *yyin;
  if (argc != 2) {
     fprintf (stderr, "Usage: %s <input-file-name>\n", argv[0]);
     return 1;
  }
  yyin = fopen (argv [1], "r");
  if (yyin == NULL) {
       fprintf (stderr, "failed to open %s\n", argv[1]);
       return 2;
  }

  yyparse ();

  fclose (yyin);
  return 0;
}

void yyerror (const char *s)
{
  extern int line;
  fprintf (stderr, "line %d: %s\n", line, s);
}

Thanks!

Body:
The problem is the C syntax error in the first %code section in your bison file:

struct diet

That's missing a semicolon, and will create a variety of unpredictable compile errors when eventually passed to a C compiler.

However, the declaration is unnecessary, and should simply be removed.

There are also some issues with your flex file:

Don't do this:

#define VEGETABLE 1
#define FRUIT 2
...

The correct token definitions are in the header file created by bison, which you have already included. The values you provide are incorrect and will cause parsing to fail.

Don't do this either:

extern void exit(int);

exit is declared in the standard header stdlib.h; you should include that header file instead of second-guessing its contents:

#include <stdlib.h>
#include <string.h>
#include "meals.tab.h"

Note that it is conventional to include system headers before including your own headers (such as the one generated by bison).

Finally, I strongly recommend that you remove your own attempt to track line numbers in line, and instead just let flex do it:

%option yylineno

will cause flex to insert efficient code to maintain the current line number in the variable yylineno. Furthermore, it will maintain the line number correctly, since it understands all the corner cases. (Unless you sidestep flex processing by using input() to directly read from yyin.)


来源: stackexchange

问:
join table with itself and save result in view in sql
I'm new to SQL and I've been trying to do this for a while now but it's not working for me.
I have a table with 2 columns,for example something like this:

tbl

```<code>source | destination
  0    |     1
  1    |     2
  3    |     7
  9    |     10
</code>```

I'm trying to join the table with itself,where there exists a destination that's equal to a source, rename it's 2 columns to S0,S1, take only the destination column from the right joined table and rename it as S2, then save the result in a view.

On the example table, running the query should have this view:

```<code>S0   | S1  |  S2
0    | 1   |  2
</code>```

I tried doing something like this:

```<code>CREATE VIEW V1 AS
SELECT tbl.source as S0,tbl.destination as S1 FROM tbl
JOIN
SELECT Hops.destination as S2 FROM Hops
ON tbl.S1=Hops.source
</code>```

but it's not working. I'd appreciate any help :)

答:
I think that the first thing to understand is how a join works.  In general, when you select from 2 tables joined together, you will have only one select statement.  Something like this:

```<code>SELECT *
FROM Table1 AS T1
INNER JOIN Table2 AS T2
  ON T1.Col1=T2.Col1
</code>```

Note that the * in this statement is selecting every column from both tables.  You could also specify columns as T1.*, T2.*, or more appropriately in most cases, T1.Col1, T1.Col2, T2.Col2 or something along those lines.

I don't know the specifics of what you're trying to achieve, but I assume you want something like this:

```<code>SELECT T1.Source AS S0, T2.Source AS S1, T2.Destination AS S2
FROM tbl AS T1
INNER JOIN tbl AS T2
  ON T1.Destination=T2.Source
</code>```

Alternately, if you want to include records where Destination does not match any Sources, you might try

```<code>SELECT T1.Source AS S0, ISNULL(T2.Source, T1.Destination) AS S1, T2.Destination AS S2
FROM tbl AS T1
LEFT OUTER JOIN tbl AS T2
  ON T1.Destination=T2.Source
</code>```

(Edit: actually, I realize the SELECT clause could be simplified to SELECT T1.Source AS S0, T1.Destination AS S1, T2.Destination AS S2, because we've defined the JOIN such that T1.Destination and T2.Source are equal unless T2.Source is NULL (i.e. no matching record was found), but I will leave it in as illustrative of using ISNULL or COALESCE between two columns with an OUTER JOIN, which can be a useful construct.)

ContentLicense: CC BY-SA 3.0

Body:
I'm new to SQL and I've been trying to do this for a while now but it's not working for me.
I have a table with 2 columns,for example something like this:

tbl

source | destination
  0    |     1
  1    |     2
  3    |     7
  9    |     10

I'm trying to join the table with itself,where there exists a destination that's equal to a source, rename it's 2 columns to S0,S1, take only the destination column from the right joined table and rename it as S2, then save the result in a view.

On the example table, running the query should have this view:

S0   | S1  |  S2
0    | 1   |  2

I tried doing something like this:

CREATE VIEW V1 AS
SELECT tbl.source as S0,tbl.destination as S1 FROM tbl
JOIN
SELECT Hops.destination as S2 FROM Hops
ON tbl.S1=Hops.source

but it's not working. I'd appreciate any help :)

Body:
I think that the first thing to understand is how a join works.  In general, when you select from 2 tables joined together, you will have only one select statement.  Something like this:

SELECT *
FROM Table1 AS T1
INNER JOIN Table2 AS T2
  ON T1.Col1=T2.Col1

Note that the * in this statement is selecting every column from both tables.  You could also specify columns as T1.*, T2.*, or more appropriately in most cases, T1.Col1, T1.Col2, T2.Col2 or something along those lines.

I don't know the specifics of what you're trying to achieve, but I assume you want something like this:

SELECT T1.Source AS S0, T2.Source AS S1, T2.Destination AS S2
FROM tbl AS T1
INNER JOIN tbl AS T2
  ON T1.Destination=T2.Source

Alternately, if you want to include records where Destination does not match any Sources, you might try

SELECT T1.Source AS S0, ISNULL(T2.Source, T1.Destination) AS S1, T2.Destination AS S2
FROM tbl AS T1
LEFT OUTER JOIN tbl AS T2
  ON T1.Destination=T2.Source

(Edit: actually, I realize the SELECT clause could be simplified to SELECT T1.Source AS S0, T1.Destination AS S1, T2.Destination AS S2, because we've defined the JOIN such that T1.Destination and T2.Source are equal unless T2.Source is NULL (i.e. no matching record was found), but I will leave it in as illustrative of using ISNULL or COALESCE between two columns with an OUTER JOIN, which can be a useful construct.)


问:
Language changed but CLLocationManager didn't effected?
I am using localization and cllocationManager

when change the language every thing working well just the country and city name come with the previous language not effected at all with the localization , the only way is to close the app and open it again to come with the new language !!
Any solution to change the country and city without closing the app ?

localization code

```<code>static func setLanguage(lang:String) -> Void {
    UserDefaults.standard.removeObject(forKey: "AppleLanguages")
    UserDefaults.standard.set([lang], forKey: "AppleLanguages")
    UserDefaults.standard.synchronize()

    Bundle.setLanguage(lang)
}
</code>```

CLLocationManager code

```<code>   func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    locValue = manager.location!.coordinate
    print("locations = \(locValue.latitude) \(locValue.longitude)")

    let geoCoder = CLGeocoder()
    let location = CLLocation(latitude: locValue.latitude, longitude: locValue.longitude)

    geoCoder.reverseGeocodeLocation(location, completionHandler: { (placemarks, error) -> Void in

        // Place details
        var placeMark: CLPlacemark!
        placeMark = placemarks?[0]

        if placeMark != nil{
            // City
            if let city = placeMark.addressDictionary!["State"] as? NSString {

                self.locCity = city as String
            }

            // Country
            if let country = placeMark.addressDictionary!["Country"] as? NSString {

                self.locCountry = "\(country)," as String
            }

            self.countryLocation.text = "\(self.locCountry) \(self.locCity)"
            self.locationManager.stopUpdatingLocation()
        }

    })
}
</code>```

答:
You'll have to add an observer on NSLocale.currentLocaleDidChangeNotification to detect any such change.

Something like this:

```<code>NotificationCenter.default.addObserver(self, selector: #selector(MyClass.languageDidChange),
                                               name: NSLocale.currentLocaleDidChangeNotification, object: nil)
</code>```

And languageDidChange method will get called once something gets changed in NSLocale.

Hope this helps.

Body:
I am using localization and cllocationManager

when change the language every thing working well just the country and city name come with the previous language not effected at all with the localization , the only way is to close the app and open it again to come with the new language !!
Any solution to change the country and city without closing the app ?

localization code

static func setLanguage(lang:String) -> Void {
    UserDefaults.standard.removeObject(forKey: "AppleLanguages")
    UserDefaults.standard.set([lang], forKey: "AppleLanguages")
    UserDefaults.standard.synchronize()

    Bundle.setLanguage(lang)
}

CLLocationManager code

   func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    locValue = manager.location!.coordinate
    print("locations = \(locValue.latitude) \(locValue.longitude)")

    let geoCoder = CLGeocoder()
    let location = CLLocation(latitude: locValue.latitude, longitude: locValue.longitude)

    geoCoder.reverseGeocodeLocation(location, completionHandler: { (placemarks, error) -> Void in

        // Place details
        var placeMark: CLPlacemark!
        placeMark = placemarks?[0]

        if placeMark != nil{
            // City
            if let city = placeMark.addressDictionary!["State"] as? NSString {

                self.locCity = city as String
            }

            // Country
            if let country = placeMark.addressDictionary!["Country"] as? NSString {

                self.locCountry = "\(country)," as String
            }

            self.countryLocation.text = "\(self.locCountry) \(self.locCity)"
            self.locationManager.stopUpdatingLocation()
        }

    })
}

Body:
You'll have to add an observer on NSLocale.currentLocaleDidChangeNotification to detect any such change.

Something like this:

NotificationCenter.default.addObserver(self, selector: #selector(MyClass.languageDidChange),
                                               name: NSLocale.currentLocaleDidChangeNotification, object: nil)

And languageDidChange method will get called once something gets changed in NSLocale.

Hope this helps.


问:
How to start a django cms project
I decided to take a look to django-cms. After looking at the docs I cloned the repository using

```<code>git clone https://github.com/divio/django-cms.git
</code>```

Then I installed it using

```<code>sudo python setup.py install
</code>```

I already have django 1.2.3 installed. I moved to the example directory an ran syncdb which created the following tables:

```<code>Creating table auth_permission
Creating table auth_group_permissions
Creating table auth_group
Creating table auth_user_user_permissions
Creating table auth_user_groups
Creating table auth_user
Creating table auth_message
Creating table django_content_type
Creating table django_session
Creating table django_admin_log
Creating table django_site
Creating table sampleapp_category
Creating table sampleapp_picture
Creating table south_migrationhistory

You just installed Django's auth system, which means you don't have any superusers defined.
Would you like to create one now? (yes/no): yes...
</code>```

We can clearly see that the cms tables are not created. I'm obviously facing that problem when running the server and browsing http://localhost:8000/

```<code>DatabaseError: no such table: cms_page
</code>```

I've looked at the docs and seen that I meet the requirements regarding the versions but clearly, I'm doing something wrong. Any help would be greatly appreciated.

答:
django-cms uses South for database migrations. Models handled by South are not synced to the database using syncdb. You have to use manage.py migrate.

Since you don't have any tables and data from django-cms to migrate, a faster solution would be this process:

comment out 'south' in your INSTALLED_APPS

run manage.py syncdb (this will create all the tables from django-cms)

re-enable south in your INSTALLED_APPS

run manage.py migrate --fake

The next time you update django-cms, you can then run manage.py migrate to update your database tables.

ContentLicense: CC BY-SA 2.5

Title: How to start a django cms project

Body:
I decided to take a look to django-cms. After looking at the docs I cloned the repository using

git clone https://github.com/divio/django-cms.git

Then I installed it using

sudo python setup.py install

I already have django 1.2.3 installed. I moved to the example directory an ran syncdb which created the following tables:

Creating table auth_permission
Creating table auth_group_permissions
Creating table auth_group
Creating table auth_user_user_permissions
Creating table auth_user_groups
Creating table auth_user
Creating table auth_message
Creating table django_content_type
Creating table django_session
Creating table django_admin_log
Creating table django_site
Creating table sampleapp_category
Creating table sampleapp_picture
Creating table south_migrationhistory

You just installed Django's auth system, which means you don't have any superusers defined.
Would you like to create one now? (yes/no): yes...

We can clearly see that the cms tables are not created. I'm obviously facing that problem when running the server and browsing http://localhost:8000/

DatabaseError: no such table: cms_page

I've looked at the docs and seen that I meet the requirements regarding the versions but clearly, I'm doing something wrong. Any help would be greatly appreciated.


问:
Typescript + gulp-sourcemaps generates map but browser DevTools don't recognize it
Using Typescript 1.8, Gulp 3.9.0, gulp-sourcemaps 1.6.0, and a tsconfig.json file.

At one point a long time ago this was working fine. Of late (and I can't pinpoint when), neither Chrome nor Firefox will actually use the sourcemap.

I've enabled sourcemaps on Chrome, and recognizes that there's a sourcemap, telling me in the console:

"Source Map detected. Associated files should be added to the file tree. You can debug these resolved source files as regular JavaScript files. Associated files are available via file tree or Ctrl + P."

However, the source files are not available through either method.

Built File Structure on local build (just using Login as an example):

```<code>build
  |- resources
      |- js
         |- app.js
         |- app.js.map
         |- typescript
              |- app.ts
              |- sections
                    |- login
                         |- LoginService.ts
                         |- LoginDirective.ts
                         |- LoginController.ts
</code>```

However, Chrome only shows this in the file tree:

```<code>build
  |- resources
      |- js
         |- app.js
</code>```

That's it. No Typescript folder, no files. Ctrl-P doesn't find them either. So when I'm debugging, I can only debug the compiled app.js file rather than see the Typescript code.

My gulp file relevant sections:

```<code>var ts = require( 'gulp-typescript' ); // compiles typescript
var tsProject = ts.createProject( 'tsconfig.json' );

gulp.task( 'compile:typescript', function () {
    var tsResult = tsProject
        .src() // instead of gulp.src(...)
        .pipe( sourcemaps.init() )
        .pipe( ts( tsProject ) );

    return tsResult.js
        .pipe( sourcemaps.write( '.',
             {
               includeContent: false,
               sourceRoot: 'typescript'
             })
         )
        .pipe( './build' )
        ;
} );
</code>```

I've looked at various documentation and solutions for similar situations but I'm still not getting Chrome to use the sourcemaps.

https://www.npmjs.com/package/gulp-sourcemaps

https://github.com/ivogabe/gulp-typescript/issues/201

https://github.com/floridoo/gulp-sourcemaps/issues/89#issuecomment-73184103

gulp-typescript: Problems using createProject ... "and much more!"

No idea why this isn't working correctly. Any insight, Stackers?

答:
In chrome dev Tools open settings (F1 in windows).

Make sure that options:

Sources:

Automatically reveal files in navigator

Enable JavaScript source maps

are checked

Body:
Using Typescript 1.8, Gulp 3.9.0, gulp-sourcemaps 1.6.0, and a tsconfig.json file.

At one point a long time ago this was working fine. Of late (and I can't pinpoint when), neither Chrome nor Firefox will actually use the sourcemap.

I've enabled sourcemaps on Chrome, and recognizes that there's a sourcemap, telling me in the console:

"Source Map detected. Associated files should be added to the file tree. You can debug these resolved source files as regular JavaScript files. Associated files are available via file tree or Ctrl + P."

However, the source files are not available through either method.

Built File Structure on local build (just using Login as an example):

build
  |- resources
      |- js
         |- app.js
         |- app.js.map
         |- typescript
              |- app.ts
              |- sections
                    |- login
                         |- LoginService.ts
                         |- LoginDirective.ts
                         |- LoginController.ts

However, Chrome only shows this in the file tree:

build
  |- resources
      |- js
         |- app.js

That's it. No Typescript folder, no files. Ctrl-P doesn't find them either. So when I'm debugging, I can only debug the compiled app.js file rather than see the Typescript code.

My gulp file relevant sections:

var ts = require( 'gulp-typescript' ); // compiles typescript
var tsProject = ts.createProject( 'tsconfig.json' );

gulp.task( 'compile:typescript', function () {
    var tsResult = tsProject
        .src() // instead of gulp.src(...)
        .pipe( sourcemaps.init() )
        .pipe( ts( tsProject ) );

    return tsResult.js
        .pipe( sourcemaps.write( '.',
             {
               includeContent: false,
               sourceRoot: 'typescript'
             })
         )
        .pipe( './build' )
        ;
} );

I've looked at various documentation and solutions for similar situations but I'm still not getting Chrome to use the sourcemaps.

https://www.npmjs.com/package/gulp-sourcemaps

https://github.com/ivogabe/gulp-typescript/issues/201

https://github.com/floridoo/gulp-sourcemaps/issues/89#issuecomment-73184103

gulp-typescript: Problems using createProject ... "and much more!"

No idea why this isn't working correctly. Any insight, Stackers?


问:
Spring boot 1.5 tests don't roll back transaction
I'm starting a simple Spring boot project + JPA + Hibernate + Mysql. Before starting coding I created some very simple tests but unfortunately the behaiour is not that expected. This is my test class:

```<code> @RunWith(SpringRunner.class)
@SpringBootTest
@TestPropertySource(locations = "classpath:test.properties")
@Transactional
public class TenantTest {

    @Autowired
    private TenantRepository tenantRepository;

    @Test
    public void createTenant() {
        Tenant tenant = new Tenant();
        tenant.setAddress("Street n.1");
        tenant.setAlias("tenant");
        tenant.setCity("Milan");
        tenant.setCountry("Italy");
        tenant.setEmail("info@email.com");
        tenant.setLandlinePhone("3902123456");
        tenant.setMobilePhone("39347123456");
        tenant.setName("Tenant 1");
        tenant.setType(TenantType.RESELLER);

        Tenant savedObj = tenantRepository.save(tenant);

        assertNotNull("Tenant null after save!", savedObj);

    }

    @Test
    public void createTenantWithInvalidEmail() {
        Tenant tenant = new Tenant();
        tenant.setAddress("Street n.1");
        tenant.setAlias("tenant");
        tenant.setCity("Milan");
        tenant.setCountry("Italy");
        tenant.setEmail("info@email");
        tenant.setLandlinePhone("3902123456");
        tenant.setMobilePhone("39347123456");
        tenant.setName("Tenant 1");
        tenant.setType(TenantType.RESELLER);

        Tenant savedObj = tenantRepository.save(tenant);

        assertNotNull("Tenant null after save!", savedObj);

    }
</code>```

According to Spring documentation (https://docs.spring.io/spring/docs/current/spring-framework-reference/html/integration-testing.html#testing-tx), each test should be rolled back. Instead in my example this doens't happen. In fact I've this error for the second test:

```<code>    org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [UK_6xsyaq3xonk8dkjed1lmu31ve]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement
    at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:278)
    at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:244)
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:488)
    at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:59)
    at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:213)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:147)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:133)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.data.repository.core.support.SurroundingTransactionDetectorMethodInterceptor.invoke(SurroundingTransactionDetectorMethodInterceptor.java:57)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
    at com.sun.proxy.$Proxy130.save(Unknown Source)
    at com.test.server.TenantTest.createTenantWithInvalidEmail(TenantTest.java:59)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: org.hibernate.exception.ConstraintViolationException: could not execute statement
    at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:59)
    at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:111)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:97)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:208)
    at org.hibernate.dialect.identity.GetGeneratedKeysDelegate.executeAndExtract(GetGeneratedKeysDelegate.java:57)
    at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:42)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2909)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3480)
    at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:81)
    at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:626)
    at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:280)
    at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:261)
    at org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:306)
    at org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:318)
    at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:275)
    at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:182)
    at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:113)
    at org.hibernate.jpa.event.internal.core.JpaPersistEventListener.saveWithGeneratedId(JpaPersistEventListener.java:67)
    at org.hibernate.event.internal.DefaultPersistEventListener.entityIsTransient(DefaultPersistEventListener.java:189)
    at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:132)
    at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:58)
    at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:780)
    at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:765)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:298)
    at com.sun.proxy.$Proxy124.persist(Unknown Source)
    at org.springframework.data.jpa.repository.support.SimpleJpaRepository.save(SimpleJpaRepository.java:508)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.executeMethodOn(RepositoryFactorySupport.java:504)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:489)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:461)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:61)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:282)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)
    ... 39 more
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry 'tenant' for key 'UK_6xsyaq3xonk8dkjed1lmu31ve'
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:425)
    at com.mysql.jdbc.Util.getInstance(Util.java:408)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:935)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3973)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3909)
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2527)
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2680)
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2501)
    at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1858)
    at com.mysql.jdbc.PreparedStatement.executeUpdateInternal(PreparedStatement.java:2079)
    at com.mysql.jdbc.PreparedStatement.executeUpdateInternal(PreparedStatement.java:2013)
    at com.mysql.jdbc.PreparedStatement.executeLargeUpdate(PreparedStatement.java:5104)
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1998)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.tomcat.jdbc.pool.StatementFacade$StatementProxy.invoke(StatementFacade.java:114)
    at com.sun.proxy.$Proxy82.executeUpdate(Unknown Source)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:205)
    ... 80 more
</code>```

This happens obviously because the transaction is not rolled back. I also printed debug log of spring and Spring is saying it is rolling back the transaction:

```<code> 017-06-06 18:29:12.683  INFO 7556 --- [           main] o.s.t.c.transaction.TransactionContext   : Began transaction (1) for test context [DefaultTestContext@3f200884 testClass = TenantTest, testInstance = com.test.server.TenantTest@35fac3ba, testMethod = createTenant@TenantTest, testException = [null], mergedContextConfiguration = [WebMergedContextConfiguration@4d339552 testClass = TenantTest, locations = '{}', classes = '{class com.test.server.TestApplication}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{classpath:test.properties}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.context.SpringBootTestContextCustomizer@5025a98f, org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@192b07fd, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@520a3426], resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]]]; transaction manager [org.springframework.orm.jpa.JpaTransactionManager@7d43f1c9]; rollback [true]
2017-06-06 18:29:12.753  INFO 7556 --- [           main] o.s.t.c.transaction.TransactionContext   : Rolled back transaction for test context [DefaultTestContext@3f200884 testClass = TenantTest, testInstance = com.test.server.TenantTest@35fac3ba, testMethod = createTenant@TenantTest, testException = [null], mergedContextConfiguration = [WebMergedContextConfiguration@4d339552 testClass = TenantTest, locations = '{}', classes = '{class com.test.server.TestApplication}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{classpath:test.properties}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.context.SpringBootTestContextCustomizer@5025a98f, org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@192b07fd, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@520a3426], resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]]].
2017-06-06 18:29:12.756  INFO 7556 --- [           main] o.s.t.c.transaction.TransactionContext   : Began transaction (1) for test context [DefaultTestContext@3f200884 testClass = TenantTest, testInstance = com.test.server.TenantTest@4c599679, testMethod = createTenantWithDuplicatedAlias@TenantTest, testException = [null], mergedContextConfiguration = [WebMergedContextConfiguration@4d339552 testClass = TenantTest, locations = '{}', classes = '{class com.test.server.TestApplication}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{classpath:test.properties}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.context.SpringBootTestContextCustomizer@5025a98f, org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@192b07fd, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@520a3426], resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]]]; transaction manager [org.springframework.orm.jpa.JpaTransactionManager@7d43f1c9]; rollback [true]
2017-06-06 18:29:12.760  WARN 7556 --- [           main] o.h.engine.jdbc.spi.SqlExceptionHelper   : SQL Error: 1062, SQLState: 23000
2017-06-06 18:29:12.760 ERROR 7556 --- [           main] o.h.engine.jdbc.spi.SqlExceptionHelper   : Duplicate entry 'tenant' for key 'UK_6xsyaq3xonk8dkjed1lmu31ve'
2017-06-06 18:29:12.764  INFO 7556 --- [           main] o.s.t.c.transaction.TransactionContext   : Rolled back transaction for test context [DefaultTestContext@3f200884 testClass = TenantTest, testInstance = com.test.server.TenantTest@4c599679, testMethod = createTenantWithDuplicatedAlias@TenantTest, testException = [null], mergedContextConfiguration = [WebMergedContextConfiguration@4d339552 testClass = TenantTest, locations = '{}', classes = '{class com.test.server.TestApplication}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{classpath:test.properties}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.context.SpringBootTestContextCustomizer@5025a98f, org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@192b07fd, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@520a3426], resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]]].
</code>```

Relevant part of my properties configuration:

```<code>spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.database-platform=org.hibernate.dialect.MySQL5Dialect
spring.jpa.hibernate.ddl-auto: create-drop
spring.jpa.hibernate.naming_strategy: org.hibernate.cfg.ImprovedNamingStrategy
spring.jpa.database: mysql
spring.jpa.show-sql: false
spring.jpa.properties.hibernate.max_fetch_depth=3
spring.jpa.properties.hibernate.jdbc.fetch_size=150
spring.jpa.properties.hibernate.jdbc.batch_size=100
spring.jpa.properties.hibernate.cache.use_second_level_cache=true
</code>```

I'm using the annotation @Transaction at level class. I don't see what is wrong with this configuration. Do you have some advice?

答:
There is a difference between committing a transaction and flushing / synchronizing your JPA persistence context. Flushing the peristence context writes the generated SQL to the database. This can happen at any time as determined by the persistence provider by mainly at transaction commit time. However it can also happen when you are using auto generated identifiers that are generated on the database side a.k.a IDENTITY or when executing queries.

So its possible for the ransaction to be rolled back even when the persistence context has been flushed.

Even the Spring log indicates that the test transaction is being rolled back. Try with a record that does not produce an exception and this should be rolled back as well

Body:
I'm starting a simple Spring boot project + JPA + Hibernate + Mysql. Before starting coding I created some very simple tests but unfortunately the behaiour is not that expected. This is my test class:

 @RunWith(SpringRunner.class)
@SpringBootTest
@TestPropertySource(locations = "classpath:test.properties")
@Transactional
public class TenantTest {

    @Autowired
    private TenantRepository tenantRepository;

    @Test
    public void createTenant() {
        Tenant tenant = new Tenant();
        tenant.setAddress("Street n.1");
        tenant.setAlias("tenant");
        tenant.setCity("Milan");
        tenant.setCountry("Italy");
        tenant.setEmail("info@email.com");
        tenant.setLandlinePhone("3902123456");
        tenant.setMobilePhone("39347123456");
        tenant.setName("Tenant 1");
        tenant.setType(TenantType.RESELLER);

        Tenant savedObj = tenantRepository.save(tenant);

        assertNotNull("Tenant null after save!", savedObj);

    }

    @Test
    public void createTenantWithInvalidEmail() {
        Tenant tenant = new Tenant();
        tenant.setAddress("Street n.1");
        tenant.setAlias("tenant");
        tenant.setCity("Milan");
        tenant.setCountry("Italy");
        tenant.setEmail("info@email");
        tenant.setLandlinePhone("3902123456");
        tenant.setMobilePhone("39347123456");
        tenant.setName("Tenant 1");
        tenant.setType(TenantType.RESELLER);

        Tenant savedObj = tenantRepository.save(tenant);

        assertNotNull("Tenant null after save!", savedObj);

    }

According to Spring documentation (https://docs.spring.io/spring/docs/current/spring-framework-reference/html/integration-testing.html#testing-tx), each test should be rolled back. Instead in my example this doens't happen. In fact I've this error for the second test:

    org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [UK_6xsyaq3xonk8dkjed1lmu31ve]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement
    at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:278)
    at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:244)
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:488)
    at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:59)
    at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:213)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:147)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:133)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.data.repository.core.support.SurroundingTransactionDetectorMethodInterceptor.invoke(SurroundingTransactionDetectorMethodInterceptor.java:57)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
    at com.sun.proxy.$Proxy130.save(Unknown Source)
    at com.test.server.TenantTest.createTenantWithInvalidEmail(TenantTest.java:59)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: org.hibernate.exception.ConstraintViolationException: could not execute statement
    at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:59)
    at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:111)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:97)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:208)
    at org.hibernate.dialect.identity.GetGeneratedKeysDelegate.executeAndExtract(GetGeneratedKeysDelegate.java:57)
    at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:42)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2909)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3480)
    at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:81)
    at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:626)
    at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:280)
    at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:261)
    at org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:306)
    at org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:318)
    at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:275)
    at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:182)
    at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:113)
    at org.hibernate.jpa.event.internal.core.JpaPersistEventListener.saveWithGeneratedId(JpaPersistEventListener.java:67)
    at org.hibernate.event.internal.DefaultPersistEventListener.entityIsTransient(DefaultPersistEventListener.java:189)
    at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:132)
    at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:58)
    at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:780)
    at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:765)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:298)
    at com.sun.proxy.$Proxy124.persist(Unknown Source)
    at org.springframework.data.jpa.repository.support.SimpleJpaRepository.save(SimpleJpaRepository.java:508)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.executeMethodOn(RepositoryFactorySupport.java:504)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:489)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:461)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:61)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:282)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)
    ... 39 more
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry 'tenant' for key 'UK_6xsyaq3xonk8dkjed1lmu31ve'
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:425)
    at com.mysql.jdbc.Util.getInstance(Util.java:408)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:935)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3973)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3909)
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2527)
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2680)
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2501)
    at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1858)
    at com.mysql.jdbc.PreparedStatement.executeUpdateInternal(PreparedStatement.java:2079)
    at com.mysql.jdbc.PreparedStatement.executeUpdateInternal(PreparedStatement.java:2013)
    at com.mysql.jdbc.PreparedStatement.executeLargeUpdate(PreparedStatement.java:5104)
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1998)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.tomcat.jdbc.pool.StatementFacade$StatementProxy.invoke(StatementFacade.java:114)
    at com.sun.proxy.$Proxy82.executeUpdate(Unknown Source)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:205)
    ... 80 more

This happens obviously because the transaction is not rolled back. I also printed debug log of spring and Spring is saying it is rolling back the transaction:

 017-06-06 18:29:12.683  INFO 7556 --- [           main] o.s.t.c.transaction.TransactionContext   : Began transaction (1) for test context [DefaultTestContext@3f200884 testClass = TenantTest, testInstance = com.test.server.TenantTest@35fac3ba, testMethod = createTenant@TenantTest, testException = [null], mergedContextConfiguration = [WebMergedContextConfiguration@4d339552 testClass = TenantTest, locations = '{}', classes = '{class com.test.server.TestApplication}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{classpath:test.properties}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.context.SpringBootTestContextCustomizer@5025a98f, org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@192b07fd, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@520a3426], resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]]]; transaction manager [org.springframework.orm.jpa.JpaTransactionManager@7d43f1c9]; rollback [true]
2017-06-06 18:29:12.753  INFO 7556 --- [           main] o.s.t.c.transaction.TransactionContext   : Rolled back transaction for test context [DefaultTestContext@3f200884 testClass = TenantTest, testInstance = com.test.server.TenantTest@35fac3ba, testMethod = createTenant@TenantTest, testException = [null], mergedContextConfiguration = [WebMergedContextConfiguration@4d339552 testClass = TenantTest, locations = '{}', classes = '{class com.test.server.TestApplication}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{classpath:test.properties}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.context.SpringBootTestContextCustomizer@5025a98f, org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@192b07fd, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@520a3426], resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]]].
2017-06-06 18:29:12.756  INFO 7556 --- [           main] o.s.t.c.transaction.TransactionContext   : Began transaction (1) for test context [DefaultTestContext@3f200884 testClass = TenantTest, testInstance = com.test.server.TenantTest@4c599679, testMethod = createTenantWithDuplicatedAlias@TenantTest, testException = [null], mergedContextConfiguration = [WebMergedContextConfiguration@4d339552 testClass = TenantTest, locations = '{}', classes = '{class com.test.server.TestApplication}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{classpath:test.properties}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.context.SpringBootTestContextCustomizer@5025a98f, org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@192b07fd, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@520a3426], resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]]]; transaction manager [org.springframework.orm.jpa.JpaTransactionManager@7d43f1c9]; rollback [true]
2017-06-06 18:29:12.760  WARN 7556 --- [           main] o.h.engine.jdbc.spi.SqlExceptionHelper   : SQL Error: 1062, SQLState: 23000
2017-06-06 18:29:12.760 ERROR 7556 --- [           main] o.h.engine.jdbc.spi.SqlExceptionHelper   : Duplicate entry 'tenant' for key 'UK_6xsyaq3xonk8dkjed1lmu31ve'
2017-06-06 18:29:12.764  INFO 7556 --- [           main] o.s.t.c.transaction.TransactionContext   : Rolled back transaction for test context [DefaultTestContext@3f200884 testClass = TenantTest, testInstance = com.test.server.TenantTest@4c599679, testMethod = createTenantWithDuplicatedAlias@TenantTest, testException = [null], mergedContextConfiguration = [WebMergedContextConfiguration@4d339552 testClass = TenantTest, locations = '{}', classes = '{class com.test.server.TestApplication}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{classpath:test.properties}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.context.SpringBootTestContextCustomizer@5025a98f, org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@192b07fd, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@520a3426], resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]]].

Relevant part of my properties configuration:

spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.database-platform=org.hibernate.dialect.MySQL5Dialect
spring.jpa.hibernate.ddl-auto: create-drop
spring.jpa.hibernate.naming_strategy: org.hibernate.cfg.ImprovedNamingStrategy
spring.jpa.database: mysql
spring.jpa.show-sql: false
spring.jpa.properties.hibernate.max_fetch_depth=3
spring.jpa.properties.hibernate.jdbc.fetch_size=150
spring.jpa.properties.hibernate.jdbc.batch_size=100
spring.jpa.properties.hibernate.cache.use_second_level_cache=true

I'm using the annotation @Transaction at level class. I don't see what is wrong with this configuration. Do you have some advice?


问:
Find way for gathering data and replace with values from another table
I am looking for an Oracle SQL query to find a specific pattern and replace them with values from another table.

Scenario:

Table 1:

```<code>No      column1
-----------------------------------------
12345  user:12345;group:56789;group:6785;...
</code>```

Note: field 1 may be has one or more pattern

Table2 :

```<code>Id     name       type
----------------------
12345  admin      user
56789  testgroup  group
</code>```

Result must be the same

```<code>No        column1
-----------------------------------
12345     user: admin;group:testgroup
</code>```

答:
```<code>with t1 (no, col) as
(
  -- start of test data
  select 1,   'user:12345;group:56789;group:6785;' from dual union all
  select 2,   'user:12345;group:56789;group:6785;' from dual
  -- end of test data
)
  -- the lookup table which has the substitute strings
  -- nid : concatenation of name and id as in table t1 which requires the lookup
  -- tname : required substitute for each nid
, t2 (id, name, type, nid, tname) as
(

  select t.*, type || ':' || id, type || ':' || name from
  (
    select 12345 id,  'admin' name,      'user' type from dual union all
    select 56789,  'testgroup',  'group' from dual
  ) t
)
--select * from t2;
-- cte table calculates the indexes for the substrings (eg, user:12345)
-- no : sequence no in t1
-- col : the input string in t1
-- si : starting index of each substring in the 'col' input string that needs attention later
-- ei : ending index of each substring in the 'col' input string
-- idx : the order of substring to put them together later
,cte (no, col, si, ei, idx) as
(
  select no, col, 1, case when instr(col,';') = 0 then length(col)+1 else instr(col,';') end, 1 from t1 union all
  select no, col, ei+1, case when instr(col,';', ei+1) = 0 then length(col)+1 else instr(col,';', ei+1)  end, idx+1 from cte where ei + 1 <= length(col)
)
,coll(no, col, sstr, idx, newstr) as
(
  select
    a.no, a.col, a.sstr, a.idx,
    -- when a substitute is not found in t2, use the same input substring (eg. group:6785)
    case when t2.tname is null then a.sstr else t2.tname end
  from
    (select cte.*, substr(col, si, ei-si) as sstr from cte) a
    -- we don't want to miss if there is no substitute available in t2 for a substring
    left outer join
    t2
    on (a.sstr = t2.nid)
)
select no, col, listagg(newstr, ';') within group (order by no, col, idx) from coll
group by no, col;
</code>```

Body:
I am looking for an Oracle SQL query to find a specific pattern and replace them with values from another table.

Scenario:

Table 1:

No      column1
-----------------------------------------
12345  user:12345;group:56789;group:6785;...

Note: field 1 may be has one or more pattern

Table2 :

Id     name       type
----------------------
12345  admin      user
56789  testgroup  group

Result must be the same

No        column1
-----------------------------------
12345     user: admin;group:testgroup


问:
Simulate Mouse Click on dropdown
My Wordpress theme interacts with WooCommerce so that when a user selects a specific product variable from a drop-down a particular price is shown for their region.

This works fine when a user manually selects the drop-down, however, I'm trying to speed up the process by pre-selecting the appropriate option for the user based on a browser cookie (or lack of one).

For instance, if the user hasn't entered their region their browser will not have a cookie I've named "pc-entered" and the following jQuery script will run:

```<code>$(function() {
    $('ul li.product').each( function() {
        /*If no region set by cookie*/
        if( document.cookie.indexOf("pc-entered=") < 0) {
            /*Set downdown to generic*/
            $(this).find("#pa_region").val('generic');
        }
    });
});
</code>```

This works, successfully pre-selecting the correct 'generic' dropdown option automatically.

Unfortunately, and this is where I'm stuck - although the dropdown is correct the price isn't auto-populating like it does when a user manually selects their region.

E.g.

1) When auto-populated using my script:

2) When user selected:

I've tried replacing this in my script:

```<code>$(this).find("#pa_region").val('generic');
</code>```

With the options listed on this thread, however, they don't seem to work in this case. I've also tried firing the script after all other scripts on the page and even delaying the script running with a timeout function but nothing seems to be working.

My test site is here.

TLDR - Why is my jQuery script not populating the price?

答:
With $(this).find("#pa_region").val('generic'); you are only changing the HTML value (text) of dropdown.

You need to attach the event handler which will trigger the change to the function where you change the value.

```<code>function changeValue(){
  $("#pa_region").val('generic');
  $("#pa_region").trigger('change');
}

$( "#pa_region" ).change(function() {
  console.log( "Handler for .change() called." );
});
</code>```

This is the way on how to solve it.

I also made a JSFiddle so you can test it.

Title: Simulate Mouse Click on dropdown

Body:
My Wordpress theme interacts with WooCommerce so that when a user selects a specific product variable from a drop-down a particular price is shown for their region.

This works fine when a user manually selects the drop-down, however, I'm trying to speed up the process by pre-selecting the appropriate option for the user based on a browser cookie (or lack of one).

For instance, if the user hasn't entered their region their browser will not have a cookie I've named "pc-entered" and the following jQuery script will run:

$(function() {
    $('ul li.product').each( function() {
        /*If no region set by cookie*/
        if( document.cookie.indexOf("pc-entered=") < 0) {
            /*Set downdown to generic*/
            $(this).find("#pa_region").val('generic');
        }
    });
});

This works, successfully pre-selecting the correct 'generic' dropdown option automatically.

Unfortunately, and this is where I'm stuck - although the dropdown is correct the price isn't auto-populating like it does when a user manually selects their region.

E.g.

1) When auto-populated using my script:

2) When user selected:

I've tried replacing this in my script:

$(this).find("#pa_region").val('generic');

With the options listed on this thread, however, they don't seem to work in this case. I've also tried firing the script after all other scripts on the page and even delaying the script running with a timeout function but nothing seems to be working.

My test site is here.

TLDR - Why is my jQuery script not populating the price?

Body:
With $(this).find("#pa_region").val('generic'); you are only changing the HTML value (text) of dropdown.

You need to attach the event handler which will trigger the change to the function where you change the value.

function changeValue(){
  $("#pa_region").val('generic');
  $("#pa_region").trigger('change');
}

$( "#pa_region" ).change(function() {
  console.log( "Handler for .change() called." );
});

This is the way on how to solve it.

I also made a JSFiddle so you can test it.


问:
JavaScript count items that have been run in an array
I'm very new to Javascript so i'm looking for a bit of help.
I have a webpage that loads a iframe and loops through loads of URLs. This all works after a bit of help.

However i now need a div showing the count of the completed urls, so everytime it does one it increases the count by one.

Any ideads?

答: Create a div with id count1 that has the number 0. Target the div using document.getElementById('count1') as you're already doing. Right below your if statement, target that element and set its innerHTML equal to idx.

ContentLicense: CC BY-SA 4.0


问:
How to stop copyright theft of images?
Is there s a way for anti theft images? I'm not referring to web sites, what I want is if a JPEG is stolen it cannot be manipulated by the thief, only can be used by the owner.</p>

答:
If you host an image on a website then you're stuck with the possibility that someone can download and save it, duplicate it and distribute it.

Some sites use watermarks to mark sample images and then know who they sell the full size images to. This might allow them some legal recourse if the image starts getting distributed.

In practice though this is almost impossible to protect against.

Hope that helps!

Title: How to stop copyright theft of images?


问:
laravel eloquent count with a groupby
If I'd have the following table structure

```<code>ID      name   type
1       John   Admin
2       Johan  Admin
3       Sam    User
4       Rick   User
</code>```

How would I use Laravels Eloquent with a groupBy query, but still grab each record, and also sum up per type how many records each type has?

Example result would be as follow

```<code>[
    'type' => 'Admin',
    'records' => 2
    'data' => [
        0 => [
            'name' => 'John'
        ],
        1 => [
            'name' => 'Johan'
        ]
    ]
],
[
    'type' => 'User',
    'records' => 2
    'data' => [
        0 => [
            'name' => 'Sam'
        ],
        1 => [
            'name' => 'Rick'
        ]
    ]
]
</code>```

答:
Since you are querying all the users you should be doing the grouping after the query instead of grouping in query like:

```<code>$users = User::all()->groupBy('type');
</code>```

Then you can do:

```<code>foreach ($allUsers as $type => $users) {
    $type; // 'Admin'
    $users->count(); // Record Count
    foreach ($users as $user) {
        $user->name; //
    }
}
</code>```

If you want the data EXACTLY like your example then it would be:

```<code>User::all()
    ->groupBy('type')
    ->map(function($users, $type) {
        return [
            'type'    => $type,
            'records' => $users->count(),
            'data'    => $users->pluck('name')
        ];
    })
    ->values();
</code>```

Title: laravel eloquent count with a groupby

Body:
If I'd have the following table structure

ID      name   type
1       John   Admin
2       Johan  Admin
3       Sam    User
4       Rick   User

How would I use Laravels Eloquent with a groupBy query, but still grab each record, and also sum up per type how many records each type has?

Example result would be as follow

[
    'type' => 'Admin',
    'records' => 2
    'data' => [
        0 => [
            'name' => 'John'
        ],
        1 => [
            'name' => 'Johan'
        ]
    ]
],
[
    'type' => 'User',
    'records' => 2
    'data' => [
        0 => [
            'name' => 'Sam'
        ],
        1 => [
            'name' => 'Rick'
        ]
    ]
]

Body:
Since you are querying all the users you should be doing the grouping after the query instead of grouping in query like:

$users = User::all()->groupBy('type');

Then you can do:

foreach ($allUsers as $type => $users) {
    $type; // 'Admin'
    $users->count(); // Record Count
    foreach ($users as $user) {
        $user->name; //
    }
}

If you want the data EXACTLY like your example then it would be:

User::all()
    ->groupBy('type')
    ->map(function($users, $type) {
        return [
            'type'    => $type,
            'records' => $users->count(),
            'data'    => $users->pluck('name')
        ];
    })
    ->values();


问:
React - render() not called with setState with axios
I am trying to fetch an array of movies and after it fetches the list it updates the state and the list should render, but the problem is the render method never calls from inside the axios callback, here is my code below

```<code>export default class Movies extends Component {
    constructor(props){
      super(props);

      this.state={movies:[]};
    }

    componentDidMount(){

      axios.get('URL')
            .then(response => {
              this.setState({movies:response.data});
              console.log("Movies",this.state);// I get the values here see screenshot..

      });
  }

  render(){
    return(
      <div className="row">
        <div className="col-md-3">
          <MovieList movies={this.state.movies}/>
        </div>
        <div className="col-md-6">Movie Details</div>
      </div>
    );
  }
}
</code>```

As you can see the code above, in function componentDidMount in the axios callback I am setting the response values to the state, but it doesn't call the render after doing it, the block does execute well as I get the log properly see screenshot below

I am not understanding why it doesn't call render() ? I have tried couple of solutions available but none works for me, if I hardcode the videos array in default state it works fine, please help if anyone know the solution.

Update(Adding MovieList Code)

```<code>class ListItem extends Component {
  render(){
    return(
      <li className="list-group-item">{this.props.moviename}</li>
    );
  }
}

export default class MoviesList extends Component {
  constructor(props) {
    super(props);
    console.log("Props",props);
    this.state={movies:props.movies};
  }

  renderList(){

    const items=this.state.movies.map((movie) => <ListItem moviename={movie.name} key={movie.name}/>);

    return items;
  }

  render(){
    return(
      <ul className="list-group">
        <li className="list-group-item"><h3>Movies</h3></li>
        {this.renderList()}
      </ul>
    );
  }
}
</code>```

Thanks.

答: Did you added componentWillReceiveProps in MovieList?

Body:
I am trying to fetch an array of movies and after it fetches the list it updates the state and the list should render, but the problem is the render method never calls from inside the axios callback, here is my code below

export default class Movies extends Component {
    constructor(props){
      super(props);

      this.state={movies:[]};
    }

    componentDidMount(){

      axios.get('URL')
            .then(response => {
              this.setState({movies:response.data});
              console.log("Movies",this.state);// I get the values here see screenshot..

      });
  }

  render(){
    return(

          <MovieList movies={this.state.movies}/>

Movie Details

    );
  }
}

As you can see the code above, in function componentDidMount in the axios callback I am setting the response values to the state, but it doesn't call the render after doing it, the block does execute well as I get the log properly see screenshot below

I am not understanding why it doesn't call render() ? I have tried couple of solutions available but none works for me, if I hardcode the videos array in default state it works fine, please help if anyone know the solution.

Update(Adding MovieList Code)

class ListItem extends Component {
  render(){
    return(

{this.props.moviename}

    );
  }
}

export default class MoviesList extends Component {
  constructor(props) {
    super(props);
    console.log("Props",props);
    this.state={movies:props.movies};
  }

  renderList(){

    const items=this.state.movies.map((movie) => <ListItem moviename={movie.name} key={movie.name}/>);

    return items;
  }

  render(){
    return(

Movies

        {this.renderList()}

    );
  }
}

Thanks.


问:
By using c# , how can I make disappear the grey unnecessary zone in my datagridview?
Here is the screenshot of the datagridView, By using c# , how can I make disappear the grey unnecessary zone in my datagridview?

答:
Make reference to this post.

It seems though that this person had the exact same problem as you in some aspect and seemingly got rid of it by means of the top rated answer.

Hope it helps.


问:
Wamp does not recognize projects
I need help on how to setup Wamp. I installed it for a school project but when I wanted to access the project folder it sent me this error: "Server not found".

Find that you have to modify the index.php file is this line: $ suppress_localhost = true; Changing it to false. But now send this error: "The requested URL / other / was not found on this server". Is it necessary to configure something else?

I installed Wamp 3.0.0. Can somebody help me?

答:
Go to wamp folder (wamp/ or wamp64/)

Open wampmanager.conf

Find urlAddLocalhost param and set it on: urlAddLocalhost = "on"
There should not be the need to tweak the index.php in www folder.

Title: Wamp does not recognize projects


问:
Loading two different SQL tables in a single JSP file using spring + hibernate
Sorry, I edited my post due to a misleading error i posted.

I have two tables on MySQL and I am trying to display both of them in a single JSP page.

I am using @RequestMapping to try to achieve this.

```<code>@RequestMapping(value = "/persons", method = RequestMethod.GET)
public String listFolders(Model model) {
    model.addAttribute("folders", new Folders());
    model.addAttribute("listFolders", this.foldersService.listFolders());
    return "person"; //name of the jsp page
}

@RequestMapping(value = "/folders", method = RequestMethod.GET)
public String listPersons(Model model) {
    model.addAttribute("person", new Person());
    model.addAttribute("listPersons", this.personService.listPersons());
    return "person"; //name of the jsp page
}
</code>```

I need to show both tables in the same JSP page, but if i try to access /folders i get erros because it wont recognise the person table.

actions in my JSP file:

```<code><c:if test="${!empty listPersons}">
<table class="tg">
<tr>
    <th width="80">Person ID</th>
    <th width="120">Person Name</th>
    <th width="120">Person Country</th>
</tr>
<c:forEach items="${listPersons}" var="person">
    <tr>
        <td>${person.id} </td>
        <td>${person.name}</td>
        <td>${person.country}</td>

    </tr>
</c:forEach>
</table>
</code>```

And:

```<code>    <c:if test="${!empty listFolders}">
<table class="tg">
<tr>
    <th width="80">Folders ID</th>
    <th width="120">Folders Parent</th>
</tr>
<c:forEach items="${listFolders}" var="person">
    <tr>
        <td>${folders.id} </td>
        <td>${folders.parent}</td>
    </tr>
</c:forEach>
</table>
</code>```

Erros:

```<code>Jun 06, 2017 5:53:07 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [appServlet] in context with path
[/CitelumApp] threw exception [java.lang.IllegalStateException: Neither
BindingResult nor plain target object for bean name 'person' available as
request attribute] with root cause
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'person' available as request attribute
    at org.springframework.web.servlet.support.BindStatus.<init>
</code>```

My question is:
Is there a way to display two different SQL tables on the same JSP page?

答:
Adding on to what Boukobba said, you should really look at the error message. You cannot have two mappings with the same url and same request method. The Dispatcher servlet cant figure out on which one to route your request. Things you may consider changing is your    RequestMethod or your    URL

EDIT

@RequestMapping(value = "/person", method = RequestMethod.GET)
public String listFolders(@ModelAttribute("person") Person person, BindingResult personResult, @ModelAttribute("folders") Folders folders, BindingResult folderError, Model model) {
    // you can access folders and person as new Object in JSP

    model.addAttribute("listPersons", this.personService.listPersons());
    return "person"; //name of the jsp page
}

@RequestMapping(value = "/folders", method = RequestMethod.GET)
public String listFolders(@ModelAttribute("person") Person person, BindingResult personResult, @ModelAttribute("folders") Folders folders, BindingResult folderError, Model model) {
    // you can access folders and person as new Object in JSP

    model.addAttribute("listFolders", this.foldersService.listFolders());

    return "person"; //name of the jsp page
}```

However, there is no point of having two get request serving the same page, generally. You may have a request parameter Boolean which tells you whether the user wants a folder list or person list. In controller you populate based on that parameter. In JSP access the corresponding folder or persons list checking that same parameter.

Body:
Sorry, I edited my post due to a misleading error i posted.

I have two tables on MySQL and I am trying to display both of them in a single JSP page.

I am using @RequestMapping to try to achieve this.

@RequestMapping(value = "/persons", method = RequestMethod.GET)
public String listFolders(Model model) {
    model.addAttribute("folders", new Folders());
    model.addAttribute("listFolders", this.foldersService.listFolders());
    return "person"; //name of the jsp page
}

@RequestMapping(value = "/folders", method = RequestMethod.GET)
public String listPersons(Model model) {
    model.addAttribute("person", new Person());
    model.addAttribute("listPersons", this.personService.listPersons());
    return "person"; //name of the jsp page
}

I need to show both tables in the same JSP page, but if i try to access /folders i get erros because it wont recognise the person table.

actions in my JSP file:

<c:if test="${!empty listPersons}">

    Person ID
    Person Name
    Person Country

<c:forEach items="${listPersons}" var="person">

        ${person.id}
        ${person.name}
        ${person.country}

</c:forEach>

And:

    <c:if test="${!empty listFolders}">

    Folders ID
    Folders Parent

<c:forEach items="${listFolders}" var="person">

        ${folders.id}
        ${folders.parent}

</c:forEach>

Erros:

Jun 06, 2017 5:53:07 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [appServlet] in context with path
[/CitelumApp] threw exception [java.lang.IllegalStateException: Neither
BindingResult nor plain target object for bean name 'person' available as
request attribute] with root cause
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'person' available as request attribute
    at org.springframework.web.servlet.support.BindStatus.<init>

My question is:
Is there a way to display two different SQL tables on the same JSP page?

Body:
Adding on to what Boukobba said, you should really look at the error message. You cannot have two mappings with the same url and same request method. The Dispatcher servlet cant figure out on which one to route your request. Things you may consider changing is your    RequestMethod or your    URL

EDIT

@RequestMapping(value = "/person", method = RequestMethod.GET)
public String listFolders(@ModelAttribute("person") Person person, BindingResult personResult, @ModelAttribute("folders") Folders folders, BindingResult folderError, Model model) {
    // you can access folders and person as new Object in JSP

    model.addAttribute("listPersons", this.personService.listPersons());
    return "person"; //name of the jsp page
}

@RequestMapping(value = "/folders", method = RequestMethod.GET)
public String listFolders(@ModelAttribute("person") Person person, BindingResult personResult, @ModelAttribute("folders") Folders folders, BindingResult folderError, Model model) {
    // you can access folders and person as new Object in JSP

    model.addAttribute("listFolders", this.foldersService.listFolders());

    return "person"; //name of the jsp page
}

However, there is no point of having two get request serving the same page, generally. You may have a request parameter Boolean which tells you whether the user wants a folder list or person list. In controller you populate based on that parameter. In JSP access the corresponding folder or persons list checking that same parameter.