问:
Disable Hover Effects on resize using jQuery
Ok so Im new to jQuery and a little confused how to achieve my goal here. The goal is whenever the browser is less than 780px wide I want to disable all hover effects. So I did a lot of research and still cant figure out a specific way that works for me, though I have come close. Below is the jQuery and HTML. So the class .allHover is what is triggering the hover effects. So I thought to remove the hover effect when the browser is less than 780px I would use a .removeClass method which would break the hover effect. The jQuery code below works, however when I resize the window to less than 780 px then refresh my browser the hover effect comes back and I dont want that. Is there something I can add to ensure the class .allHover doesnt come back when the page is less than 780px wide and the page is refreshed? Thank you in advance.

CHOOSE FROM
1000+Insert designs...

as low as $<?=($prod[1]->sale_price ?: $prod[1]->aslow_price);?>

```

答:
A CSS only approach would be to add your :hover CSS in a @media query with min-width: 780px since you want :hover effects to fire when the window is > 780px.

  @media (min-width: 780px) {
    div.allHover:hover .stockDesign_image,
    div.allHover:hover .customDesign_image {
      width: 360px;
    }
    div.allHover:hover .prodBoxes_header {
      background-color: #5E3EA6;
    }
    div.allHover:hover .prodBoxes_headerright {
      background-color: #fb8332;
    }
    div.allHover:hover .viewAll_button {
      background-position: 0 -34px;
    }
  }
  .stockDesign_image, .customDesign_image {
    width: 340px;
    height: 382px;
    margin: 30px auto;
    transition: all 0.2s ease-in-out;
  }

  .prodBoxes_header {
    background-color: #4c2e90;
  }

  .prodBoxes_headerright {
    background-color: #ff6600;
  }

  .viewAll_button {
    background-image: url(images/VIEW-ALL.png);
    width: 141px;
    height: 34px;
    float: right;
    overflow: hidden;
    position: relative;
    margin: 8px 5px 0 0;
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="allHover">
  <div class="prodBoxes_header">
    <p class="medalHeader_text">CHOOSE FROM<br>1000+Insert designs...</p>
  </div>
  <div class="stockDesign_image"></div>
  <div class="prodBoxes_footer">
    <p class="footer_asLOWas">as low as <span class="asLOWas_price">$<?=($prod[1]->sale_price ?: $prod[1]->aslow_price);?></span></p>
    <div class="viewAll_button"></div>
  </div>
</div></code>```

Body:
A CSS only approach would be to add your :hover CSS in a @media query with min-width: 780px since you want :hover effects to fire when the window is > 780px.

  @media (min-width: 780px) {
    div.allHover:hover .stockDesign_image,
    div.allHover:hover .customDesign_image {
      width: 360px;
    }
    div.allHover:hover .prodBoxes_header {
      background-color: #5E3EA6;
    }
    div.allHover:hover .prodBoxes_headerright {
      background-color: #fb8332;
    }
    div.allHover:hover .viewAll_button {
      background-position: 0 -34px;
    }
  }
  .stockDesign_image, .customDesign_image {
    width: 340px;
    height: 382px;
    margin: 30px auto;
    transition: all 0.2s ease-in-out;
  }

  .prodBoxes_header {
    background-color: #4c2e90;
  }

  .prodBoxes_headerright {
    background-color: #ff6600;
  }

  .viewAll_button {
    background-image: url(images/VIEW-ALL.png);
    width: 141px;
    height: 34px;
    float: right;
    overflow: hidden;
    position: relative;
    margin: 8px 5px 0 0;
  }

<div class="allHover">
  <div class="prodBoxes_header">
    <p class="medalHeader_text">CHOOSE FROM<br>1000+Insert designs...</p>
  </div>
  <div class="stockDesign_image"></div>
  <div class="prodBoxes_footer">
    <p class="footer_asLOWas">as low as <span class="asLOWas_price">$<?=($prod[1]->sale_price ?: $prod[1]->aslow_price);?></span></p>
    <div class="viewAll_button"></div>
  </div>
</div>


来源: stackexchange

问:
How to determine the date passing the Week Number and Day Number (Week) in java
I need to get the date by passing these parameters

year

week number (in a month) i.e. 1,2,3,4,5

day number (in a week) 0 (Sunday) to 6 (Saturday)

Month

I looked for a constructor in Calendar class but does not contain these parameters.

答:
As @Ole V.V. explained, you need to define in what day the week starts, and how many days it must have to be considered the first week.

For example, the ISO-8601 standard considers:

Monday to be the first day-of-week.

The minimal number of days in the first week: the standard counts the first week as needing at least 4 days

The month is divided into periods where each period starts on the defined first day-of-week. The earliest period in the same month is referred to as week 0 if it has less than the minimal number of days and week 1 if it has at least the minimal number of days.

Depending on how you define those, you can have different results. Consider the calendar for July 2017:

```<code>     July 2017
Su Mo Tu We Th Fr Sa
                   1
 2  3  4  5  6  7  8
 9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31
</code>```

If we consider ISO's definition, we have:

week zero - 2017-07-01 to 2017-07-02

week 1: from 2017-07-03 to 2017-07-09

week 2: from 2017-07-10 to 2017-07-16

week 3: from 2017-07-17 to 2017-07-22

week 4: from 2017-07-23 to 2017-07-30

week 5: 2017-07-31

If we consider first day of week as Sunday and minimal number of days in the first week as 1, we have:

week 1: 2017-07-01

week 2: from 2017-07-02 to 2017-07-08

week 3: from 2017-07-09 to 2017-07-15

week 4: from 2017-07-16 to 2017-07-21

week 5: from 2017-07-22 to 2017-07-29

week 6: from 2017-07-30 to 2017-07-31

As a solution with Calendar was already posted, I'm gonna write one using the new API. If you're using Java 8, consider using the new java.time API. It's easier, less bugged and less error-prone than the old APIs.

If you're using Java <= 7, you can use the ThreeTen Backport, a great backport for Java 8's new date/time classes. And for Android, there's the ThreeTenABP (more on how to use it here).

The code below works for both.
The only difference is the package names (in Java 8 is java.time and in ThreeTen Backport (or Android's ThreeTenABP) is org.threeten.bp), but the classes and methods names are the same.

I'm using a DateTimeFormatter because it takes all the fields (month, year, day of week and week of month) and resolves the day accordingly, creating a LocalDate (which has the day/month/year fields). I'm also using the WeekFields class, which can be configured to use different week definitions (first day and minimal number of days in first week)

There's also a little adjustment to consider Sunday as zero:

```<code>public LocalDate getDate(int weekOfMonth, int dayOfWeek, int month, int year) {
    // you can customize your week definition (first day of week and mininum days in first week)
    WeekFields wf = WeekFields.of(DayOfWeek.SUNDAY, 2);
    DateTimeFormatter fmt = new DateTimeFormatterBuilder()
        // week of month, using week definition from WeekFields
        .appendValue(wf.weekOfMonth()).appendPattern(" ")
        // day of week
        .appendValue(ChronoField.DAY_OF_WEEK)
        // month and year
        .appendPattern(" M/yyyy")
        // create formatter
        .toFormatter();

    return LocalDate.parse(weekOfMonth + " " +
           // Sunday is 0, adjusting value
           (dayOfWeek == 0 ? 7 : dayOfWeek) + " " + month + "/" + year, fmt);
}
</code>```

Using this code (week starts on Sunday, and 2 days are required to be considered the first week - otherwise week will be zero as in the first example above):

```<code>LocalDate d = getDate(1, 6, 7, 2017);
</code>```

d will be 2017-07-08 (Saturday in the week 1 of July 2017).

If you want to use ISO 8601 definition, use the constant WeekFields.ISO instead of using WeekFields.of() method.

As @Ole V.V. suggested in the comments, it can also be done without creating a formatter: get the first dayOfWeek of the month and adjust it to the desired weekOfMonth:

```<code>public LocalDate getDate(int weekOfMonth, int dayOfWeek, int month, int year) {
    // you can customize your week definition (first day of week and mininum days in first week)
    WeekFields wf = WeekFields.of(DayOfWeek.SUNDAY, 2);

    // Sunday is 0, adjusting value
    DayOfWeek dow = DayOfWeek.of(dayOfWeek == 0 ? 7 : dayOfWeek);

    // get the first weekday of the month
    LocalDate first = LocalDate.of(year, month, 1).with(TemporalAdjusters.nextOrSame(dow));

    // check in which week this date is
    int week = first.get(wf.weekOfMonth());

    // adjust to weekOfMonth
    return first.plusWeeks(weekOfMonth - week);
}
</code>```

This works exactly the same way, but without the need of a formatter - I've tested with dates from year 1600 to 2100 and it gets the same results.

PS: Calendar also has a similar configuration via the methods setFirstDayOfWeek() and setMinimalDaysInFirstWeek(). You can check the default configuration calling the respective get methods.

ContentLicense: CC BY-SA 3.0

Body:
As @Ole V.V. explained, you need to define in what day the week starts, and how many days it must have to be considered the first week.

For example, the ISO-8601 standard considers:

Monday to be the first day-of-week.

The minimal number of days in the first week: the standard counts the first week as needing at least 4 days

The month is divided into periods where each period starts on the defined first day-of-week. The earliest period in the same month is referred to as week 0 if it has less than the minimal number of days and week 1 if it has at least the minimal number of days.

Depending on how you define those, you can have different results. Consider the calendar for July 2017:

     July 2017
Su Mo Tu We Th Fr Sa
                   1
 2  3  4  5  6  7  8
 9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31

If we consider ISO's definition, we have:

week zero - 2017-07-01 to 2017-07-02

week 1: from 2017-07-03 to 2017-07-09

week 2: from 2017-07-10 to 2017-07-16

week 3: from 2017-07-17 to 2017-07-22

week 4: from 2017-07-23 to 2017-07-30

week 5: 2017-07-31

If we consider first day of week as Sunday and minimal number of days in the first week as 1, we have:

week 1: 2017-07-01

week 2: from 2017-07-02 to 2017-07-08

week 3: from 2017-07-09 to 2017-07-15

week 4: from 2017-07-16 to 2017-07-21

week 5: from 2017-07-22 to 2017-07-29

week 6: from 2017-07-30 to 2017-07-31

As a solution with Calendar was already posted, I'm gonna write one using the new API. If you're using Java 8, consider using the new java.time API. It's easier, less bugged and less error-prone than the old APIs.

If you're using Java <= 7, you can use the ThreeTen Backport, a great backport for Java 8's new date/time classes. And for Android, there's the ThreeTenABP (more on how to use it here).

The code below works for both.
The only difference is the package names (in Java 8 is java.time and in ThreeTen Backport (or Android's ThreeTenABP) is org.threeten.bp), but the classes and methods names are the same.

I'm using a DateTimeFormatter because it takes all the fields (month, year, day of week and week of month) and resolves the day accordingly, creating a LocalDate (which has the day/month/year fields). I'm also using the WeekFields class, which can be configured to use different week definitions (first day and minimal number of days in first week)

There's also a little adjustment to consider Sunday as zero:

public LocalDate getDate(int weekOfMonth, int dayOfWeek, int month, int year) {
    // you can customize your week definition (first day of week and mininum days in first week)
    WeekFields wf = WeekFields.of(DayOfWeek.SUNDAY, 2);
    DateTimeFormatter fmt = new DateTimeFormatterBuilder()
        // week of month, using week definition from WeekFields
        .appendValue(wf.weekOfMonth()).appendPattern(" ")
        // day of week
        .appendValue(ChronoField.DAY_OF_WEEK)
        // month and year
        .appendPattern(" M/yyyy")
        // create formatter
        .toFormatter();

    return LocalDate.parse(weekOfMonth + " " +
           // Sunday is 0, adjusting value
           (dayOfWeek == 0 ? 7 : dayOfWeek) + " " + month + "/" + year, fmt);
}

Using this code (week starts on Sunday, and 2 days are required to be considered the first week - otherwise week will be zero as in the first example above):

LocalDate d = getDate(1, 6, 7, 2017);

d will be 2017-07-08 (Saturday in the week 1 of July 2017).

If you want to use ISO 8601 definition, use the constant WeekFields.ISO instead of using WeekFields.of() method.

As @Ole V.V. suggested in the comments, it can also be done without creating a formatter: get the first dayOfWeek of the month and adjust it to the desired weekOfMonth:

public LocalDate getDate(int weekOfMonth, int dayOfWeek, int month, int year) {
    // you can customize your week definition (first day of week and mininum days in first week)
    WeekFields wf = WeekFields.of(DayOfWeek.SUNDAY, 2);

    // Sunday is 0, adjusting value
    DayOfWeek dow = DayOfWeek.of(dayOfWeek == 0 ? 7 : dayOfWeek);

    // get the first weekday of the month
    LocalDate first = LocalDate.of(year, month, 1).with(TemporalAdjusters.nextOrSame(dow));

    // check in which week this date is
    int week = first.get(wf.weekOfMonth());

    // adjust to weekOfMonth
    return first.plusWeeks(weekOfMonth - week);
}

This works exactly the same way, but without the need of a formatter - I've tested with dates from year 1600 to 2100 and it gets the same results.

PS: Calendar also has a similar configuration via the methods setFirstDayOfWeek() and setMinimalDaysInFirstWeek(). You can check the default configuration calling the respective get methods.


问:
Kotlin AAR library w/ proguard: how to keep extension methods?
I'm writing a new Kotlin library module to add commonly used classes and extension methods.  I'm compiling each extensions file (eg BitmapExtensions.kt) into a single file called 'Extensions' using JvmMultifileClass:

```<code>@file:JvmName("Extensions")
@file:JvmMultifileClass

fun Bitmap.crop(cropRect: Rect) = ...
</code>```

As a part of our company's IP policy I need to obfuscate the library via proguard before it makes it to any consumer project.  I therefore need a proguard rule to keep these extension methods so that they are not thrown away.

At first glance the below seems to work, inspecting the generated AAR's classes.jar shows that the extension methods still exist and their internals have been obfusecated.  But when actually compiling in a consumer project, I get unresolved references to any extension method I've referenced.

```<code>-keepclassmembernames class mycompany.kotlin.util.Extensions {
    <methods>;
}
</code>```

When I disable minification, the project builds correctly.

How can I obfuscate my library and keep my kotlin extensions?

edit: It appears that using keep on the entire package, and even specifying -dontshrink is not enough.  The methods simply cannot be referenced in the consumer app.

edit2: I believe I have narrowed this down to the .kotlin_module file under /META-INF/ being removed when minifyEnabled=true.  This appears to be the ONLY difference between my minified and non-minified classes.jar.  Something is removing this file... or preventing its generation.

答: I upgraded to gradle 4.1 milestone 1.  The .kotlin_module metadata file is no longer being stripped when minifyEnabled=true and my consumer app can now use extension methods from the lib correctly.

Body:
I'm writing a new Kotlin library module to add commonly used classes and extension methods.  I'm compiling each extensions file (eg BitmapExtensions.kt) into a single file called 'Extensions' using JvmMultifileClass:

@file:JvmName("Extensions")
@file:JvmMultifileClass

fun Bitmap.crop(cropRect: Rect) = ...

As a part of our company's IP policy I need to obfuscate the library via proguard before it makes it to any consumer project.  I therefore need a proguard rule to keep these extension methods so that they are not thrown away.

At first glance the below seems to work, inspecting the generated AAR's classes.jar shows that the extension methods still exist and their internals have been obfusecated.  But when actually compiling in a consumer project, I get unresolved references to any extension method I've referenced.

-keepclassmembernames class mycompany.kotlin.util.Extensions {
    <methods>;
}

When I disable minification, the project builds correctly.

How can I obfuscate my library and keep my kotlin extensions?

edit: It appears that using keep on the entire package, and even specifying -dontshrink is not enough.  The methods simply cannot be referenced in the consumer app.

edit2: I believe I have narrowed this down to the .kotlin_module file under /META-INF/ being removed when minifyEnabled=true.  This appears to be the ONLY difference between my minified and non-minified classes.jar.  Something is removing this file... or preventing its generation.


问:
reshaping k columns to 2 columns representing sequential pairs of the values of the k variables
I have a data frame like this:

```<code>id y1 y2 y3 y4
--+--+--+--+--
a |12|13|14|
b |12|18|  |
c |13|  |  |
d |13|14|15|16
</code>```

I want to reshape in such a way that I end with two columns. The above example would then become:

```<code>id from to
--+----+---
a |12  |13
a |13  |14
a |14  |
b |12  |18
b |18  |
c |13  |
d |13  |14
d |14  |15
d |15  |16
</code>```

Each id has a 'from' and a 'to' per pair of year values.

Does anybody know of an easy way to do this? I tried using reshape2. I also looked at Combine Multiple Columns Into Tidy Data but I think my case is different.

答:
A solution uses dplyr and tidyr. dt2 is the final output.

```<code># Create example data frame
dt <- data.frame(id = c("a", "b", "c", "d"),
                 y1 = c(12, 12, 13, 13),
                 y2 = c(13, 18, NA, 14),
                 y3 = c(14, NA, NA, 15),
                 y4 = c(NA, NA, NA, 16),
                 stringsAsFactors = FALSE)

# Load packages
library(dplyr)
library(tidyr)

# Process the data
dt2 <- dt %>%
  gather(STEP, from, -id) %>%
  drop_na(from) %>%
  arrange(id, STEP) %>%
  group_by(id) %>%
  mutate(to = lead(from)) %>%
  select(-STEP)
</code>```

Body:
I have a data frame like this:

id y1 y2 y3 y4
--+--+--+--+--
a |12|13|14|
b |12|18|  |
c |13|  |  |
d |13|14|15|16

I want to reshape in such a way that I end with two columns. The above example would then become:

id from to
--+----+---
a |12  |13
a |13  |14
a |14  |
b |12  |18
b |18  |
c |13  |
d |13  |14
d |14  |15
d |15  |16

Each id has a 'from' and a 'to' per pair of year values.

Does anybody know of an easy way to do this? I tried using reshape2. I also looked at Combine Multiple Columns Into Tidy Data but I think my case is different.

Body:
A solution uses dplyr and tidyr. dt2 is the final output.

# Create example data frame
dt <- data.frame(id = c("a", "b", "c", "d"),
                 y1 = c(12, 12, 13, 13),
                 y2 = c(13, 18, NA, 14),
                 y3 = c(14, NA, NA, 15),
                 y4 = c(NA, NA, NA, 16),
                 stringsAsFactors = FALSE)

# Load packages
library(dplyr)
library(tidyr)

# Process the data
dt2 <- dt %>%
  gather(STEP, from, -id) %>%
  drop_na(from) %>%
  arrange(id, STEP) %>%
  group_by(id) %>%
  mutate(to = lead(from)) %>%
  select(-STEP)


问:
split to month and year variables
I have this code that will generate month and year from 2016 to 2017.

How do i simplify this code and separate it to two variables month and year ?

```<code>$start = $month = strtotime('2016-01-01');
$end = strtotime('2017-12-31');
while($month <=$end)
{
     echo date('F Y', $month), PHP_EOL;
     echo "<br />";
     $month = strtotime("+1 month", $month);
}
</code>```

答:
Just call date() twice. Once for the year, once for the month.

```<code>$start = $month = strtotime('2016-01-01');
$end = strtotime('2017-12-31');
while($month <=$end)
{
     echo date('F', $month), ' ', date('Y', $month), PHP_EOL;
     echo "<br />";
     $month = strtotime("+1 month", $month);
}
</code>```

Obviously you can change the formatting to suit your needs.

Title: split to month and year variables

Body:
I have this code that will generate month and year from 2016 to 2017.

How do i simplify this code and separate it to two variables month and year ?

$start = $month = strtotime('2016-01-01');
$end = strtotime('2017-12-31');
while($month <=$end)
{
     echo date('F Y', $month), PHP_EOL;
     echo "
";
     $month = strtotime("+1 month", $month);
}

Body:
Just call date() twice. Once for the year, once for the month.

$start = $month = strtotime('2016-01-01');
$end = strtotime('2017-12-31');
while($month <=$end)
{
     echo date('F', $month), ' ', date('Y', $month), PHP_EOL;
     echo "<br />";
     $month = strtotime("+1 month", $month);
}

Obviously you can change the formatting to suit your needs.


问:
how to set permanent default timezone in mysql server
I am using default_time_zone='+00:00' in my.conf file and restart mysql server. But again default time zone is showing SYSTEM.

答:
I use Ubuntu so on my machine location of the config file is:

```<code>/etc/mysql/mysql.conf.d/mysqld.cnf
</code>```

add the value:

```<code>default_time_zone='+00:00'
</code>```

Body:
I use Ubuntu so on my machine location of the config file is:

/etc/mysql/mysql.conf.d/mysqld.cnf

add the value:

default_time_zone='+00:00'


问:
How to get a different Time value in Python?
I'm trying to get a different time value. For example, I don't want the current time but the time of 6:52 am. I also want to add a various number of minutes and seconds to that time (but I'll figure that part out :)).
I thought this code would give me the desired time but it's not working:

```<code>import time

leave_time = time.struct_time(tm_year=2000, tm_mon=11, tm_mday=30, tm_hour=6, tm_min=52,
                 tm_sec=0, tm_wday=3, tm_yday=335, tm_isdst=-1)
print ("My leave time is %r") %leave_time
</code>```

Also, I don't need the date. Thanks.

答:
Use the datetime module instead:

```<code>import datetime

leave_time = datetime.time(6, 52)
print("My leave time is {}".format(leave_time))  # My leave time is 06:52:00
</code>```

Body:
I'm trying to get a different time value. For example, I don't want the current time but the time of 6:52 am. I also want to add a various number of minutes and seconds to that time (but I'll figure that part out :)).
I thought this code would give me the desired time but it's not working:

import time

leave_time = time.struct_time(tm_year=2000, tm_mon=11, tm_mday=30, tm_hour=6, tm_min=52,
                 tm_sec=0, tm_wday=3, tm_yday=335, tm_isdst=-1)
print ("My leave time is %r") %leave_time

Also, I don't need the date. Thanks.

Body:
Use the datetime module instead:

import datetime

leave_time = datetime.time(6, 52)
print("My leave time is {}".format(leave_time))  # My leave time is 06:52:00


问:
Datetime format in MSSQL
In my aplication I use a DateEdit control and show the date using this format dd/MM/yyyy so the date is save correctly when I use mssql-server 2014 (spanish) but whe I use mssql-server 2008 (english) the date is stored with this fomat MM/dd/yyyy so what I need to know is if there is a way to store the date with the format dd/MM/yyyy no matter the versión of mssql-server I use or the lenguage I use?

EDIT: to explain better this is the problem, this text 03/07/2017 is stored in the sqlserver 2014 as july 3 of 2017 and in the sqlserver 2008 is stored as march 7 of 2017.

答:
Following solution has two options. You can use one as per your requirements.

```<code>DECLARE @Date AS TABLE(val VARCHAR(30));

INSERT INTO @Date VALUES('12/04/2016');
INSERT INTO @Date VALUES('10/01/2015');
INSERT INTO @Date VALUES('17/03/2017');

--Option 1
SELECT TRY_PARSE(val AS DATE USING 'en-gb') 'Option 1' FROM @Date;

--Option 2
SELECT CONVERT(VARCHAR(10),TRY_PARSE(val AS DATE USING 'en-gb'),103) 'Option 2' FROM @Date;
</code>```

And the outputs are:

Title: Datetime format in MSSQL

Body:
Following solution has two options. You can use one as per your requirements.

DECLARE @Date AS TABLE(val VARCHAR(30));

INSERT INTO @Date VALUES('12/04/2016');
INSERT INTO @Date VALUES('10/01/2015');
INSERT INTO @Date VALUES('17/03/2017');

--Option 1
SELECT TRY_PARSE(val AS DATE USING 'en-gb') 'Option 1' FROM @Date;

--Option 2
SELECT CONVERT(VARCHAR(10),TRY_PARSE(val AS DATE USING 'en-gb'),103) 'Option 2' FROM @Date;

And the outputs are:


问:
I am new to cakephp and I am wondering if PhpMyadmin and my cakephp app should be runnning on the same port?
I should be creating a database on phpmyadmin and connecting this database to my cakephp trial project. Should both be running on the same port? (ex:8888) or is it okay that each one of them is running on a different port? Thanks.</p>

答:
phpMyAdmin is a web-based interface to help administrators manage their MySQL databases. It usually runs on whatever port your webserver is using, typically 80 or 443 (for https traffic).

MySQL normally isn't exposed publicly, although your CakePHP application needs to be able to access MySQL directly (either through socket connections or by TCP/IP networking). The default MySQL port is 3306.

I think the CakePHP default is 8765, so your Cake project is probably running its own webserver on that port.

So, by default, none of your applications are conflicting. You don't want anything running on the same port because only one application can use a port at a time. Whichever application grabs the port gets to use it, and the other application probably will fail to start correctly and give an error message.

So it sounds like everything is working correctly.


问:
use tkinter for nltk draw inside of jupyter notebook
I'm trying to draw graph (inline) of nltk inside of jupyter-notebook. But got error:

```<code>TclError: no display name and no $DISPLAY environment variable
</code>```

I have tried to set $DISPLAY to different values:

```<code>$env DISPLAY=0.0
# or
$env DISPLAY=inline
# or
$env DISPLAY=
</code>```

but got error (or similar):

```<code>TclError: couldn't connect to display "0.0"
</code>```

here is my code https://github.com/hyzhak/nltk-experiments/blob/master/main.ipynb the last cell.

Environment: official anaconda3 docker -- continuumio/anaconda3:4.4.0 https://github.com/ContinuumIO/docker-images. With nltk==3.2.3 inside.

```<code>Python 3.6.1 |Anaconda 4.4.0 (64-bit)| (default, May 11 2017, 13:09:58)
Type "copyright", "credits" or "license" for more information.

IPython 5.3.0 -- An enhanced Interactive Python.
</code>```

How could I solve this error and inline nltk graph inside of jupyter notebook?

Update 1

http://www.nltk.org/_modules/nltk/draw/tree.html#draw_trees according to the sources of nltk tree draw it uses tkinter.

Update 2

I have asked the same question in official nltk github repository https://github.com/nltk/nltk/issues/1765

Update 3

I think the reason of error could be the headless host (docker). I have installed xvfb but seems it is note enough.

```<code>RUN apt-get install -y xvfb
</code>```

Solution

I thought that xvfb is launched by default but It should be run explicitly. So after I have launched it I could make screenshots of nltk tree graph.

答:
```<code>import os
import nltk
from IPython.display import Image

chunkGram = r"""Chunk: {<RB.?>*<VB.?>*<NNP>+<NN>?}"""
chunkParser = nltk.RegexpParser(chunkGram)

tagged = [('Tonight', 'NN'), ('we', 'PRP'), ('are', 'VBP'), ('comforted', 'VBN'), ('by', 'IN'), ('the', 'DT'), ('hope', 'NN'), ('of', 'IN'), ('a', 'DT'), ('glad', 'JJ'), ('reunion', 'NN'), ('with', 'IN'), ('the', 'DT'), ('husband', 'NN'), ('who', 'WP'), ('was', 'VBD'), ('taken', 'VBN'), ('so', 'RB'), ('long', 'RB'), ('ago', 'RB'), (',', ','), ('and', 'CC'), ('we', 'PRP'), ('are', 'VBP'), ('grateful', 'JJ'), ('for', 'IN'), ('the', 'DT'), ('good', 'JJ'), ('life', 'NN'), ('of', 'IN'), ('Coretta', 'NNP'), ('Scott', 'NNP'), ('King', 'NNP'), ('.', '.')]
chunked = chunkParser.parse(tagged)
nltk.draw.tree.TreeView(chunked)._cframe.print_to_file('output.ps')
os.system('convert output.ps output.png')

Image(filename='output.png')
</code>```

[out]:

Body:
I'm trying to draw graph (inline) of nltk inside of jupyter-notebook. But got error:

TclError: no display name and no $DISPLAY environment variable

I have tried to set $DISPLAY to different values:

$env DISPLAY=0.0
# or
$env DISPLAY=inline
# or
$env DISPLAY=

but got error (or similar):

TclError: couldn't connect to display "0.0"

here is my code https://github.com/hyzhak/nltk-experiments/blob/master/main.ipynb the last cell.

Environment: official anaconda3 docker -- continuumio/anaconda3:4.4.0 https://github.com/ContinuumIO/docker-images. With nltk==3.2.3 inside.

Python 3.6.1 |Anaconda 4.4.0 (64-bit)| (default, May 11 2017, 13:09:58)
Type "copyright", "credits" or "license" for more information.

IPython 5.3.0 -- An enhanced Interactive Python.

How could I solve this error and inline nltk graph inside of jupyter notebook?

Update 1

http://www.nltk.org/_modules/nltk/draw/tree.html#draw_trees according to the sources of nltk tree draw it uses tkinter.

Update 2

I have asked the same question in official nltk github repository https://github.com/nltk/nltk/issues/1765

Update 3

I think the reason of error could be the headless host (docker). I have installed xvfb but seems it is note enough.

RUN apt-get install -y xvfb

Solution

I thought that xvfb is launched by default but It should be run explicitly. So after I have launched it I could make screenshots of nltk tree graph.

Body:
import os
import nltk
from IPython.display import Image

chunkGram = r"""Chunk: {<RB.?>*<VB.?>*<NNP>+<NN>?}"""
chunkParser = nltk.RegexpParser(chunkGram)

tagged = [('Tonight', 'NN'), ('we', 'PRP'), ('are', 'VBP'), ('comforted', 'VBN'), ('by', 'IN'), ('the', 'DT'), ('hope', 'NN'), ('of', 'IN'), ('a', 'DT'), ('glad', 'JJ'), ('reunion', 'NN'), ('with', 'IN'), ('the', 'DT'), ('husband', 'NN'), ('who', 'WP'), ('was', 'VBD'), ('taken', 'VBN'), ('so', 'RB'), ('long', 'RB'), ('ago', 'RB'), (',', ','), ('and', 'CC'), ('we', 'PRP'), ('are', 'VBP'), ('grateful', 'JJ'), ('for', 'IN'), ('the', 'DT'), ('good', 'JJ'), ('life', 'NN'), ('of', 'IN'), ('Coretta', 'NNP'), ('Scott', 'NNP'), ('King', 'NNP'), ('.', '.')]
chunked = chunkParser.parse(tagged)
nltk.draw.tree.TreeView(chunked)._cframe.print_to_file('output.ps')
os.system('convert output.ps output.png')

Image(filename='output.png')

[out]:


问:
libgdx - Transform/Shear ImageButton
I am currently developing an Android game using libgdx, and want to achieve an effect similar to the "friends leaderboard" from the below screenshot:

[Image source / Run Sackboy! Run, © Media Molecule & Sony Computer Entertainment]

Where libgdx should shear an image and draw sheared text and add an ImageButton accordingly.

When searching across the web for a place to start, I found a handy PDF that explained that transformations in libgdx can be modeled using Matrix4. So, I did just that and wrote something along the lines of:

```<code>// Inside a Screen class

private Matrix4 matrix = new Matrix4().set(new Affine2().shear(0.5f, 0));

public void render(float delta) {
    Gdx.gl.glClearColor(0, 1, 0, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    camera.update();

    batch.setProjectionMatrix(camera.combined);
    batch.setTransformationMatrix(matrix);

    batch.begin();
    // Draw texture and bitmapfont
    batch.end();
}
</code>```

In doing so, the SpriteBatch correctly transformed into the corresponding shear value. However, I had trouble applying this shear transformation to a clickable ImageButton.

I had a look at this post, which suggests to override the draw method and apply an Affine2 in an extended Actor class. Doing such will result in the correct transformation being rendered, however, it is not applicable because I am trying to extend an ImageButton and not a simple Actor, and the ability to get the user's input on the Button is lost.

So my question is: Is there a way to create a function similar to Actor#setRotation which allows an ImageButton to be sheared according to an Affine2 (or Matrix4), while maintaining the ability to click on it?

答: After searching the web for hours, I just don't think this is possible. Instead of doing this I alternatively just sheared the Spritebatch and left the ImageButton alone, using this page as a guide.

Title: libgdx - Transform/Shear ImageButton

Body:
I am currently developing an Android game using libgdx, and want to achieve an effect similar to the "friends leaderboard" from the below screenshot:

[Image source / Run Sackboy! Run, © Media Molecule & Sony Computer Entertainment]

Where libgdx should shear an image and draw sheared text and add an ImageButton accordingly.

When searching across the web for a place to start, I found a handy PDF that explained that transformations in libgdx can be modeled using Matrix4. So, I did just that and wrote something along the lines of:

// Inside a Screen class

private Matrix4 matrix = new Matrix4().set(new Affine2().shear(0.5f, 0));

public void render(float delta) {
    Gdx.gl.glClearColor(0, 1, 0, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    camera.update();

    batch.setProjectionMatrix(camera.combined);
    batch.setTransformationMatrix(matrix);

    batch.begin();
    // Draw texture and bitmapfont
    batch.end();
}

In doing so, the SpriteBatch correctly transformed into the corresponding shear value. However, I had trouble applying this shear transformation to a clickable ImageButton.

I had a look at this post, which suggests to override the draw method and apply an Affine2 in an extended Actor class. Doing such will result in the correct transformation being rendered, however, it is not applicable because I am trying to extend an ImageButton and not a simple Actor, and the ability to get the user's input on the Button is lost.

So my question is: Is there a way to create a function similar to Actor#setRotation which allows an ImageButton to be sheared according to an Affine2 (or Matrix4), while maintaining the ability to click on it?


问:
append a related Model in Phalcon
I wrote a vcard class with Phalcon in PHP. The vCard Model is initialized like this.

```<code>// Inside the BS_VCard class
public function initialize(){
    $this->hasMany("id","BS_VCardElement","vCardId",array(
        "alias" => "elements",
        'foreignKey' => array(
            'action' => Phalcon\Mvc\Model\Relation::ACTION_CASCADE
        )
    ));
}
</code>```

Its elements are initialized like this

```<code>// Inside the BS_VCardElement class
public function initialize(){
    $this->belongsTo("vCardId","BS_VCard","id",array("alias" => "vCard"));
    ...
}
</code>```

If a user reads a vCard and adds another element, it doesn't work as expected. To simplify the use I added some fascade methods like this

```<code>public function addDateOfBirth($date){
    $element = new BS_VCardElement();
    $element->setName("BDAY");
    $element->addValue($date);
    // This doesn't work
    $this->elements[] = $element;
}
</code>```

The Docs/Storing related records do not explain how to append fresh data like this to the related table.

I also tried this

```<code>$this->elements[] = array_merge($this->elements,array($element));
</code>```

But the save method seems to ignore the added element. Save() returns true.

答:
According to the Phalcon source code, the Resultset object is immutible.

```<code>/**
 * Resultsets cannot be changed. It has only been implemented to
 * meet the definition of the ArrayAccess interface
 *
 * @param int index
 * @param \Phalcon\Mvc\ModelInterface value
 */
public function offsetSet(var index, var value)
{
    throw new Exception("Cursor is an immutable ArrayAccess object");
}
</code>```

It appears that replacing the element with an array is the only way to implement an "append" or modification of the resultset (other than delete which IS supported).

Of course this breaks the \Phalcon\Mvc\Model::_preSaveRelatedRecords() because the function ignores the class properties and refetches the related from the Model Manager (and resets the model::$element attribute at the end).

I feel frustrated by this because appending objects to a collection seems like a very common task and not having a clear method in which to add new items to a parent seems like a design flaw.

Title: append a related Model in Phalcon

Body:
I wrote a vcard class with Phalcon in PHP. The vCard Model is initialized like this.

// Inside the BS_VCard class
public function initialize(){
    $this->hasMany("id","BS_VCardElement","vCardId",array(
        "alias" => "elements",
        'foreignKey' => array(
            'action' => Phalcon\Mvc\Model\Relation::ACTION_CASCADE
        )
    ));
}

Its elements are initialized like this

// Inside the BS_VCardElement class
public function initialize(){
    $this->belongsTo("vCardId","BS_VCard","id",array("alias" => "vCard"));
    ...
}

If a user reads a vCard and adds another element, it doesn't work as expected. To simplify the use I added some fascade methods like this

public function addDateOfBirth($date){
    $element = new BS_VCardElement();
    $element->setName("BDAY");
    $element->addValue($date);
    // This doesn't work
    $this->elements[] = $element;
}

The Docs/Storing related records do not explain how to append fresh data like this to the related table.

I also tried this

$this->elements[] = array_merge($this->elements,array($element));

But the save method seems to ignore the added element. Save() returns true.

Body:
According to the Phalcon source code, the Resultset object is immutible.

/**
 * Resultsets cannot be changed. It has only been implemented to
 * meet the definition of the ArrayAccess interface
 *
 * @param int index
 * @param \Phalcon\Mvc\ModelInterface value
 */
public function offsetSet(var index, var value)
{
    throw new Exception("Cursor is an immutable ArrayAccess object");
}

It appears that replacing the element with an array is the only way to implement an "append" or modification of the resultset (other than delete which IS supported).

Of course this breaks the \Phalcon\Mvc\Model::_preSaveRelatedRecords() because the function ignores the class properties and refetches the related from the Model Manager (and resets the model::$element attribute at the end).

I feel frustrated by this because appending objects to a collection seems like a very common task and not having a clear method in which to add new items to a parent seems like a design flaw.


问:
What does the error "JSX element type '...' does not have any construct or call signatures" mean?
I wrote some code:

```<code>function renderGreeting(Elem: React.Component<any, any>) {
    return <span>Hello, <Elem />!</span>;
}
</code>```

I'm getting an error:

JSX element type Elem does not have any construct or call signatures

What does it mean?

答:
If you want to take a component class as a parameter (vs an instance), use React.ComponentClass:

```<code>function renderGreeting(Elem: React.ComponentClass<any>) {
    return <span>Hello, <Elem />!</span>;
}
</code>```

Body:
I wrote some code:

function renderGreeting(Elem: React.Component<any, any>) {
    return Hello, <Elem />!;
}

I'm getting an error:

JSX element type Elem does not have any construct or call signatures

What does it mean?

Body:
If you want to take a component class as a parameter (vs an instance), use React.ComponentClass:

function renderGreeting(Elem: React.ComponentClass<any>) {
    return <span>Hello, <Elem />!</span>;
}


答:
Having a love for Datetime, I would do:</p>

```<code><?php
  $date = new DateTime('2016-01-01');
  $enddate = new DateTime('2017-12-31');
  while($date < $enddate) {
    $month = $date->format('m');
    $year = $date->format('Y');
    echo $year .' '. $month . '<br>'.PHP_EOL;
    $date->modify('+1 Month');
  }
</code>```

Title: split to month and year variables

Body:
Having a love for Datetime, I would do:

<?php
  $date = new DateTime('2016-01-01');
  $enddate = new DateTime('2017-12-31');
  while($date < $enddate) {
    $month = $date->format('m');
    $year = $date->format('Y');
    echo $year .' '. $month . '<br>'.PHP_EOL;
    $date->modify('+1 Month');
  }


问:
Unable to build Hibernate SessionFactory when using Joined inheritance
I have a class that defines an InheritanceType.JOINED from which a couple more classes inherit from:

BaseClass

```<code>@Entity
@Inheritance(strategy = InheritanceType.JOINED)
@DiscriminatorColumn(name = "DISCRIMINATOR")
@Table(name = "BASE_CLASSES", uniqueConstraints =
@UniqueConstraint(columnNames = { "DISCRIMINATOR", "NAME" }))
@Cacheable
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class BaseClass implements Serializable {

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "ID")
protected Long id;

@Length(max = 60)
@NotNull
@Column(name = "NAME", nullable = false)
private String name;
/* Getters and setters omitted for brevity */
</code>```

This class alone causes no problems when trying to run the app with Spring Boot. But if I add the other two classes:

SubClass1

```<code>@Entity
@Table(name = "SUB_CLASS_1")
@DiscriminatorValue("SC1")
@Cacheable
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class SubClass1 extends BaseClass {

private static final long serialVersionUID = 1L;

@OneToMany(mappedBy = "subClass1", fetch = FetchType.LAZY)
private Set<SubClass2> subClass2s;
</code>```

and

SubClass2

```<code>@Entity
@Table(name = "SUB_CLASS_2")
@DiscriminatorValue("SC2")
@Cacheable
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class SubClass2 extends BaseClass {

private static final long serialVersionUID = 1L;

@JoinColumn(name = "SUB_CLASS_1_ID", nullable = true)
@ManyToOne(fetch = FetchType.LAZY, optional = true)
private SubClass1 subClass1;
</code>```

I get the following error: org.hibernate.AssertionFailure: Table example.BASE_CLASSES not found.

The weird thing is (in the real life project I am working on) I can run my test suite (using a custom library based on Unitils) just fine but the app just won't start, with the same kind of error. Because of this I think that the error might be with the way I'm configuring the entity manager factory. I include the full stack trace and the configuration class below.

The full stack trace is:

```<code>12:24:15.278 [main] WARN  net.sf.ehcache.config.ConfigurationFactory - No configuration found. Configuring ehcache from ehcache-failsafe.xml  found in the classpath: jar:file:/C:/Users/crodriguez/.m2/repository/net/sf/ehcache/ehcache-core/2.4.3/ehcache-core-2.4.3.jar!/ehcache-failsafe.xml
12:24:15.470 [main] ERROR org.hibernate.AssertionFailure - HHH000099: an assertion failure occured (this may indicate a bug in Hibernate, but is more likely due to unsafe use of the session): org.hibernate.AssertionFailure: Table example.BASE_CLASSES not found
12:24:15.470 [main] WARN  org.springframework.context.annotation.AnnotationConfigApplicationContext - Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'exampleEntityManagerFactory' defined in class path resource [com/example/demo/configuration/JPAConfiguration.class]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: persistence-unit] Unable to build Hibernate SessionFactory
12:24:15.500 [main] ERROR org.springframework.boot.SpringApplication - Application startup failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'exampleEntityManagerFactory' defined in class path resource [com/example/demo/configuration/JPAConfiguration.class]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: persistence-unit] Unable to build Hibernate SessionFactory
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1583)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1076)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:851)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:541)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:761)
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:371)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:315)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1186)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1175)
    at com.example.demo.JoinedInheritanceErrorDemoApplication.main(JoinedInheritanceErrorDemoApplication.java:10)
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: persistence-unit] Unable to build Hibernate SessionFactory
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.persistenceException(EntityManagerFactoryBuilderImpl.java:954)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:882)
    at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:60)
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:353)
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:373)
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:362)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1642)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1579)
    ... 15 common frames omitted
Caused by: org.hibernate.MappingException: Could not instantiate persister org.hibernate.persister.entity.JoinedSubclassEntityPersister
    at org.hibernate.persister.internal.PersisterFactoryImpl.createEntityPersister(PersisterFactoryImpl.java:112)
    at org.hibernate.persister.internal.PersisterFactoryImpl.createEntityPersister(PersisterFactoryImpl.java:77)
    at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:348)
    at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:444)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:879)
    ... 21 common frames omitted
Caused by: org.hibernate.AssertionFailure: Table example.BASE_CLASSES not found
    at org.hibernate.persister.entity.AbstractEntityPersister.getTableId(AbstractEntityPersister.java:5118)
    at org.hibernate.persister.entity.JoinedSubclassEntityPersister.<init>(JoinedSubclassEntityPersister.java:433)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at org.hibernate.persister.internal.PersisterFactoryImpl.createEntityPersister(PersisterFactoryImpl.java:96)
    ... 25 common frames omitted
</code>```

My Configuration class is:

```<code>@Configuration
@ComponentScan(basePackages = { "com.example.demo" })
@EnableJpaRepositories(basePackages = {
        "com.example.demo" }, entityManagerFactoryRef = JPAConfiguration.ENTITY_MANAGER_NAME, transactionManagerRef = JPAConfiguration.TRANSACTION_MANAGER_NAME)
@PropertySource("classpath:database.properties")
public class JPAConfiguration {

    public static final String ENTITY_MANAGER_NAME = "entityManagerFactory";
    public static final String TRANSACTION_MANAGER_NAME = "transactionManager";
    public static final String PERSITENCE_UNIT_NAME = "persistence-unit";

    private @Value("${example.datasource.url}") String datasourceUrl;
    private @Value("${example.datasource.username}") String username;
    private @Value("${example.datasource.password}") String password;
    private @Value("${example.datasource.driverClassName}") String driverClassName;
    private @Value("${example.datasource.max-active}") Integer maxActive;
    private @Value("${example.datasource.max-idle}") Integer maxIdle;
    private @Value("${example.datasource.min-idle}") Integer minIdle;
    private @Value("${example.datasource.max-wait}") Integer maxWait;
    private @Value("${example.datasource.initial-size}") Integer initialSize;
    private @Value("${example.datasource.schema}") String defaultSchema;

    @Bean
    @Primary
    public DataSource exampleDataSource() {

        PoolProperties properties = new PoolProperties();
        properties.setUrl(datasourceUrl);
        properties.setUsername(username);
        properties.setPassword(password);
        properties.setDriverClassName(driverClassName);
        properties.setInitialSize(initialSize);
        properties.setMaxActive(maxActive);
        properties.setMaxIdle(maxIdle);
        properties.setMaxWait(maxWait);
        properties.setMinIdle(minIdle);

        return new DataSource(properties);

    }

    @Bean
    @Primary
    public LocalContainerEntityManagerFactoryBean exampleEntityManagerFactory() {

        LocalContainerEntityManagerFactoryBean entityManager = new LocalContainerEntityManagerFactoryBean();
        Properties properties = new Properties();
        properties.setProperty("hibernate.cache.provider_class", "org.hibernate.cache.SingletonEhCacheProvider");
        properties.setProperty("hibernate.cache.use_second_level_cache", "true");
        properties.setProperty("hibernate.cache.use_query_cache", "true");
        properties.setProperty("hibernate.cache.use_structured_entries", "true");
        properties.setProperty("hibernate.cache.region.factory_class",
                "org.hibernate.cache.ehcache.EhCacheRegionFactory");
        properties.setProperty("jadira.usertype.autoRegisterUserTypes", "true");
        properties.setProperty("jadira.usertype.databaseZone", "jvm");
        properties.setProperty("javax.persistence.sharedCache.mode", "ENABLE_SELECTIVE");
        properties.setProperty("hibernate.generate_statistics", "false");
        properties.setProperty("hibernate.hbm2ddl.auto", "create");
        properties.setProperty("hibernate.default_schema", defaultSchema);

        entityManager.setPackagesToScan("com.example.demo.model");
        entityManager.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
        entityManager.setPersistenceUnitName(PERSITENCE_UNIT_NAME);
        entityManager.setJpaProperties(properties);
        entityManager.setDataSource(exampleDataSource());

        return entityManager;
    }

    @Bean
    @Primary
    public PlatformTransactionManager defaultTransactionManager() {

        JpaTransactionManager transactionManager = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(exampleEntityManagerFactory().getObject());
        return transactionManager;
    }

}
</code>```

I have uploaded the code to reproduce the error to my GitHub: https://github.com/CarlosR-B/JoinedInheritanceError

EDIT

I tried to find out what was causing the different behaviour between the testing framework and Spring Boot. I found that the error happens when creating an EntityPerister on the Hibernate class MetamodelImpl.

The only thing that I could find was that, when building the EntityPersister, the testing framework is using a null accessStrategy and Spring Boot is using NonstopAwareEntityRegionAccessStrategy.

答:
If you are using MySQL database, you might be facing the following problem: https://hibernate.atlassian.net/browse/HHH-10490

Change the following line:

```<code>properties.setProperty("hibernate.default_schema", defaultSchema);
</code>```

to:

```<code>properties.setProperty("hibernate.default_catalog", defaultSchema);
</code>```

Note that you might want to change the attribute name from "defaultSchema" to "defaultCatalog" as well.

Edit: Note about database.

Body:
I have a class that defines an InheritanceType.JOINED from which a couple more classes inherit from:

BaseClass

@Entity
@Inheritance(strategy = InheritanceType.JOINED)
@DiscriminatorColumn(name = "DISCRIMINATOR")
@Table(name = "BASE_CLASSES", uniqueConstraints =
@UniqueConstraint(columnNames = { "DISCRIMINATOR", "NAME" }))
@Cacheable
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class BaseClass implements Serializable {

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "ID")
protected Long id;

@Length(max = 60)
@NotNull
@Column(name = "NAME", nullable = false)
private String name;
/* Getters and setters omitted for brevity */

This class alone causes no problems when trying to run the app with Spring Boot. But if I add the other two classes:

SubClass1

@Entity
@Table(name = "SUB_CLASS_1")
@DiscriminatorValue("SC1")
@Cacheable
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class SubClass1 extends BaseClass {

private static final long serialVersionUID = 1L;

@OneToMany(mappedBy = "subClass1", fetch = FetchType.LAZY)
private Set<SubClass2> subClass2s;

and

SubClass2

@Entity
@Table(name = "SUB_CLASS_2")
@DiscriminatorValue("SC2")
@Cacheable
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class SubClass2 extends BaseClass {

private static final long serialVersionUID = 1L;

@JoinColumn(name = "SUB_CLASS_1_ID", nullable = true)
@ManyToOne(fetch = FetchType.LAZY, optional = true)
private SubClass1 subClass1;

I get the following error: org.hibernate.AssertionFailure: Table example.BASE_CLASSES not found.

The weird thing is (in the real life project I am working on) I can run my test suite (using a custom library based on Unitils) just fine but the app just won't start, with the same kind of error. Because of this I think that the error might be with the way I'm configuring the entity manager factory. I include the full stack trace and the configuration class below.

The full stack trace is:

12:24:15.278 [main] WARN  net.sf.ehcache.config.ConfigurationFactory - No configuration found. Configuring ehcache from ehcache-failsafe.xml  found in the classpath: jar:file:/C:/Users/crodriguez/.m2/repository/net/sf/ehcache/ehcache-core/2.4.3/ehcache-core-2.4.3.jar!/ehcache-failsafe.xml
12:24:15.470 [main] ERROR org.hibernate.AssertionFailure - HHH000099: an assertion failure occured (this may indicate a bug in Hibernate, but is more likely due to unsafe use of the session): org.hibernate.AssertionFailure: Table example.BASE_CLASSES not found
12:24:15.470 [main] WARN  org.springframework.context.annotation.AnnotationConfigApplicationContext - Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'exampleEntityManagerFactory' defined in class path resource [com/example/demo/configuration/JPAConfiguration.class]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: persistence-unit] Unable to build Hibernate SessionFactory
12:24:15.500 [main] ERROR org.springframework.boot.SpringApplication - Application startup failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'exampleEntityManagerFactory' defined in class path resource [com/example/demo/configuration/JPAConfiguration.class]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: persistence-unit] Unable to build Hibernate SessionFactory
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1583)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1076)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:851)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:541)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:761)
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:371)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:315)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1186)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1175)
    at com.example.demo.JoinedInheritanceErrorDemoApplication.main(JoinedInheritanceErrorDemoApplication.java:10)
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: persistence-unit] Unable to build Hibernate SessionFactory
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.persistenceException(EntityManagerFactoryBuilderImpl.java:954)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:882)
    at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:60)
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:353)
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:373)
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:362)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1642)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1579)
    ... 15 common frames omitted
Caused by: org.hibernate.MappingException: Could not instantiate persister org.hibernate.persister.entity.JoinedSubclassEntityPersister
    at org.hibernate.persister.internal.PersisterFactoryImpl.createEntityPersister(PersisterFactoryImpl.java:112)
    at org.hibernate.persister.internal.PersisterFactoryImpl.createEntityPersister(PersisterFactoryImpl.java:77)
    at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:348)
    at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:444)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:879)
    ... 21 common frames omitted
Caused by: org.hibernate.AssertionFailure: Table example.BASE_CLASSES not found
    at org.hibernate.persister.entity.AbstractEntityPersister.getTableId(AbstractEntityPersister.java:5118)
    at org.hibernate.persister.entity.JoinedSubclassEntityPersister.<init>(JoinedSubclassEntityPersister.java:433)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at org.hibernate.persister.internal.PersisterFactoryImpl.createEntityPersister(PersisterFactoryImpl.java:96)
    ... 25 common frames omitted

My Configuration class is:

@Configuration
@ComponentScan(basePackages = { "com.example.demo" })
@EnableJpaRepositories(basePackages = {
        "com.example.demo" }, entityManagerFactoryRef = JPAConfiguration.ENTITY_MANAGER_NAME, transactionManagerRef = JPAConfiguration.TRANSACTION_MANAGER_NAME)
@PropertySource("classpath:database.properties")
public class JPAConfiguration {

    public static final String ENTITY_MANAGER_NAME = "entityManagerFactory";
    public static final String TRANSACTION_MANAGER_NAME = "transactionManager";
    public static final String PERSITENCE_UNIT_NAME = "persistence-unit";

    private @Value("${example.datasource.url}") String datasourceUrl;
    private @Value("${example.datasource.username}") String username;
    private @Value("${example.datasource.password}") String password;
    private @Value("${example.datasource.driverClassName}") String driverClassName;
    private @Value("${example.datasource.max-active}") Integer maxActive;
    private @Value("${example.datasource.max-idle}") Integer maxIdle;
    private @Value("${example.datasource.min-idle}") Integer minIdle;
    private @Value("${example.datasource.max-wait}") Integer maxWait;
    private @Value("${example.datasource.initial-size}") Integer initialSize;
    private @Value("${example.datasource.schema}") String defaultSchema;

    @Bean
    @Primary
    public DataSource exampleDataSource() {

        PoolProperties properties = new PoolProperties();
        properties.setUrl(datasourceUrl);
        properties.setUsername(username);
        properties.setPassword(password);
        properties.setDriverClassName(driverClassName);
        properties.setInitialSize(initialSize);
        properties.setMaxActive(maxActive);
        properties.setMaxIdle(maxIdle);
        properties.setMaxWait(maxWait);
        properties.setMinIdle(minIdle);

        return new DataSource(properties);

    }

    @Bean
    @Primary
    public LocalContainerEntityManagerFactoryBean exampleEntityManagerFactory() {

        LocalContainerEntityManagerFactoryBean entityManager = new LocalContainerEntityManagerFactoryBean();
        Properties properties = new Properties();
        properties.setProperty("hibernate.cache.provider_class", "org.hibernate.cache.SingletonEhCacheProvider");
        properties.setProperty("hibernate.cache.use_second_level_cache", "true");
        properties.setProperty("hibernate.cache.use_query_cache", "true");
        properties.setProperty("hibernate.cache.use_structured_entries", "true");
        properties.setProperty("hibernate.cache.region.factory_class",
                "org.hibernate.cache.ehcache.EhCacheRegionFactory");
        properties.setProperty("jadira.usertype.autoRegisterUserTypes", "true");
        properties.setProperty("jadira.usertype.databaseZone", "jvm");
        properties.setProperty("javax.persistence.sharedCache.mode", "ENABLE_SELECTIVE");
        properties.setProperty("hibernate.generate_statistics", "false");
        properties.setProperty("hibernate.hbm2ddl.auto", "create");
        properties.setProperty("hibernate.default_schema", defaultSchema);

        entityManager.setPackagesToScan("com.example.demo.model");
        entityManager.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
        entityManager.setPersistenceUnitName(PERSITENCE_UNIT_NAME);
        entityManager.setJpaProperties(properties);
        entityManager.setDataSource(exampleDataSource());

        return entityManager;
    }

    @Bean
    @Primary
    public PlatformTransactionManager defaultTransactionManager() {

        JpaTransactionManager transactionManager = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(exampleEntityManagerFactory().getObject());
        return transactionManager;
    }

}

I have uploaded the code to reproduce the error to my GitHub: https://github.com/CarlosR-B/JoinedInheritanceError

EDIT

I tried to find out what was causing the different behaviour between the testing framework and Spring Boot. I found that the error happens when creating an EntityPerister on the Hibernate class MetamodelImpl.

The only thing that I could find was that, when building the EntityPersister, the testing framework is using a null accessStrategy and Spring Boot is using NonstopAwareEntityRegionAccessStrategy.

Body:
If you are using MySQL database, you might be facing the following problem: https://hibernate.atlassian.net/browse/HHH-10490

Change the following line:

properties.setProperty("hibernate.default_schema", defaultSchema);

to:

properties.setProperty("hibernate.default_catalog", defaultSchema);

Note that you might want to change the attribute name from "defaultSchema" to "defaultCatalog" as well.

Edit: Note about database.


问:
Android SDK installation doesn't find JDK
I'm trying to install the Android SDK on my Windows 7 x64 System.

jdk-6u23-windows-x64.exe is installed, but the Android SDK setup refuses to proceed because it doesn't find the JDK installation.

Is this a known issue? And is there a solution?

答: I had the same problem and solved it by installing the x86 version of the JDK (on Windows XP x64).</p>

ContentLicense: CC BY-SA 4.0


问:
C# return json object
I have what I hope is a fairly straightforward json question.  I have a contact page where I use a jquery function to send data to a c# sendmail method.  That all works.  I am sending info back to the jquery but having trouble.

My c# is:

```<code>if (!ok)
{
    return Json(new { success = false, responseText = "FAIL" },
     JsonRequestBehavior.AllowGet);
 }
else
{
    return Json(new { success = true, responseText = "SENT" },
       JsonRequestBehavior.AllowGet);
}
</code>```

and the ajax part of the jquery is:

```<code>$.ajax({
    type: "POST",
    contentType: "application/json; charset=utf-8",
        processData: false,
        dataType: "json",
        cache:false,
        url: "x/sendEmail",
        dataType: 'json',
        data: JSON.stringify(myData),

        //complete changed to success
        success: function (response) {
            if (response != null && response.success) {
                alert(response.success + " pass" + response.responseText);
            } else {
                alert(response.success + " fail " + response.responseText);
            }
        },
        error: function (response) {
            alert(response.success + " fail2 " + response.responseText);
        }
</code>```

I get the response.success as true or false but response.responseText is always 'undefined'.

Not sure what I am missing

I changed the C# a little but same results

```<code>public class ResponseObject
{
    public bool success { get; set; }
    public string responseText { get; set; }
}

public ActionResult sendEmail(string userName, string userEmail, string
  userPhone, string userAddress,string userSubject, string userMessage, string
  userList)
 {
       ///code to send mail - works no problem

       ResponseObject response;

        if (!ok)
        {
            //  Send "false"
            response = new ResponseObject { success = false, responseText = "FAIL" };
        }
        else
        {
            //  Send "Success"
            response = new ResponseObject { success = true, responseText = "Your message successfuly sent!" };
        }

        return Json(response, JsonRequestBehavior.AllowGet);
}
</code>```

答: Press F12 to open the dev. tools, go to the "Network" tab and make that AJAX call again. Now you should be able to to find the url calling the sendEmail function. Click on it, go to the "Response" tab and see the response being sent by the server. There you'll be able to verify if you're receiving both properties and the format being used (for example, maybe there's a typo in the property name).</p>

Title: C# return json object

Body:
I have what I hope is a fairly straightforward json question.  I have a contact page where I use a jquery function to send data to a c# sendmail method.  That all works.  I am sending info back to the jquery but having trouble.

My c# is:

if (!ok)
{
    return Json(new { success = false, responseText = "FAIL" },
     JsonRequestBehavior.AllowGet);
 }
else
{
    return Json(new { success = true, responseText = "SENT" },
       JsonRequestBehavior.AllowGet);
}

and the ajax part of the jquery is:

$.ajax({
    type: "POST",
    contentType: "application/json; charset=utf-8",
        processData: false,
        dataType: "json",
        cache:false,
        url: "x/sendEmail",
        dataType: 'json',
        data: JSON.stringify(myData),

        //complete changed to success
        success: function (response) {
            if (response != null && response.success) {
                alert(response.success + " pass" + response.responseText);
            } else {
                alert(response.success + " fail " + response.responseText);
            }
        },
        error: function (response) {
            alert(response.success + " fail2 " + response.responseText);
        }

I get the response.success as true or false but response.responseText is always 'undefined'.

Not sure what I am missing

I changed the C# a little but same results

public class ResponseObject
{
    public bool success { get; set; }
    public string responseText { get; set; }
}

public ActionResult sendEmail(string userName, string userEmail, string
  userPhone, string userAddress,string userSubject, string userMessage, string
  userList)
 {
       ///code to send mail - works no problem

       ResponseObject response;

        if (!ok)
        {
            //  Send "false"
            response = new ResponseObject { success = false, responseText = "FAIL" };
        }
        else
        {
            //  Send "Success"
            response = new ResponseObject { success = true, responseText = "Your message successfuly sent!" };
        }

        return Json(response, JsonRequestBehavior.AllowGet);
}


问:
Javascript Echo Result in PHP
Ok so I have some Javascript code that I'm wanting to echo.

Here is the Code im wanting to echo, I'm wanting it to basically print out the response from the generated "hospital" and "scramble" I've got this far just can't echo the result in PHP.

```<code><script language="JavaScript">
<!--
 function hospital() {
  var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
  var string_length = Math.floor(Math.random() * (3000 - 256 + 1)) + 256;
  var prngstring = '';

  for (var i = 0; i < string_length; i++) {
   var rnum = Math.floor(Math.random() * chars.length);
   prngstring += chars.substring(rnum,rnum+1);
  }
  document.theform.hospital.value += prngstring;
 }

 function catchme() {
     var rounds = 812;
        var scramble = "lbwnaoJJgJbQCc1zxfiQugycOhboPrdbciAVBaBeqnzXzhztbPddaBWzNjcrafefibAcnJohbDQDbuaueudckuGvAuccEhPmehbjZdaecgAMphcPAeabFvxsGwteWS";

        for (var i = 0; i <= rounds; i++) {
            scramble = sjcl.codec.hex.fromBits(sjcl.hash.sha256.hash(scramble)).toUpperCase();
        }
        document.theform.waste.value += scramble;
        hospital();
    }
-->
</script>
</code>```

Would appreciate and support.

答:
You have a few options for means of printing javascript code using php. You could do a straight echo "[all of your js goes here]" but this is clunky and will require a lot of escape characters. If you aren't familiar with the concept of escape characters, if I want to include a double quote in a string, I might erroneously write something like this:

```<code>$var = "Foo"Bar";
</code>```

This will cause problems because the interpreter will see

```<code>$var = ["Foo"][Bar]["....]....
</code>```

Where the last bit is all of the text in the php file until the next double quote. Then, it will parse the text after that double quote, which presumably should have been parsed as a string, as code until the closing quote, where it will start parsing your code as a string, etc. etc. So we use the escape character (typically ) to denote when we're using special characters in a string like so:

$var = "Foo\"Bar";

This is time consuming and hard to read if you can avoid it, which you can.

You can use multiple pairs of php tags () in a single php document. Anything written outside of a set of php tags will be printed out, so you could simply close the tag, print out your code, and then open another php tag, if necessary.

See this article for other helpful tips regarding echoing out large blocks of text: http://php.net/manual/en/control-structures.alternative-syntax.php

Title: Javascript Echo Result in PHP

Body:
Ok so I have some Javascript code that I'm wanting to echo.

Here is the Code im wanting to echo, I'm wanting it to basically print out the response from the generated "hospital" and "scramble" I've got this far just can't echo the result in PHP.

Would appreciate and support.

Body:
You have a few options for means of printing javascript code using php. You could do a straight echo "[all of your js goes here]" but this is clunky and will require a lot of escape characters. If you aren't familiar with the concept of escape characters, if I want to include a double quote in a string, I might erroneously write something like this:

$var = "Foo"Bar";

This will cause problems because the interpreter will see

$var = ["Foo"][Bar]["....]....

Where the last bit is all of the text in the php file until the next double quote. Then, it will parse the text after that double quote, which presumably should have been parsed as a string, as code until the closing quote, where it will start parsing your code as a string, etc. etc. So we use the escape character (typically ) to denote when we're using special characters in a string like so:

$var = "Foo\"Bar";

This is time consuming and hard to read if you can avoid it, which you can.

You can use multiple pairs of php tags () in a single php document. Anything written outside of a set of php tags will be printed out, so you could simply close the tag, print out your code, and then open another php tag, if necessary.

See this article for other helpful tips regarding echoing out large blocks of text: http://php.net/manual/en/control-structures.alternative-syntax.php


问:
Confusion about implementing a convolution layer as fully connected layer
I kind of understand how we convert fully-connected to convolutional layer according cs231n:

FC->CONV conversion. Of these two conversions, the ability to convert an FC layer to a CONV layer is particularly useful in practice. Consider a ConvNet architecture that takes a 224x224x3 image, and then uses a series of CONV layers and POOL layers to reduce the image to an activations volume of size 7x7x512 (in an AlexNet architecture that we’ll see later, this is done by use of 5 pooling layers that downsample the input spatially by a factor of two each time, making the final spatial size 224/2/2/2/2/2 = 7). From there, an AlexNet uses two FC layers of size 4096 and finally the last FC layers with 1000 neurons that compute the class scores. We can convert each of these three FC layers to CONV layers as described above: ...

however, I was reading a paper using fully convolutional regression network to predict density map, in their description of the architecture, they claimed that the middle layer(e.g. the top row, A and B are just two different models) from 12x12x128 to 12x12x512 is fully-connected but implemented as convolution:

What I don't understand is, in cs231n, the output of the convolution implementation should be a vector with dimension like 1x1x4096, how can the paper have output dimension like 12x12x512 for their FC as convolution implementation?

答: The second case is not a FC. For a convolutional representation of a fully connected layer, the convolutional kernel should have the same shape as the input. In cs231 case, the input is 7x7x512 convolved with the kernel of shape 7x7x512 and there are 4096 such kernels, so we get 1x1x4096 as output. In the second case, it is just normal convolution: 12x12x128 convolved with 3x3x128 kernels (with padding) and there are 512 such kernels giving an output of size 12x12x512.


问:
Change text in div
Let's say I have following text in my div

Foo

Bar

  change text

```

<p>and on clicking the change text button I want the text to be and on clicking the "change to old" I want it to switch to the old text again.</p>

<pre class="lang-html prettyprint-override"><code><div id="textbox">
  <p>Lorem</p>
  <br>
  <p>Ipsum</p>
  change to old one
<div>
</code>```

Is this actually possible with the current approach with the help of css and javascript or would I have to structure my html differently? If it is possible with the current approach, how so?

答:
```<code><div id="textbox">
  <p id = 'p1'>Foo</p>
  <br>
  <p id = p2>Bar</p>
  <a onclick = "chng();" href= # id ="changetext">change text</a>
  <a onclick = "chngback();" href= # id ="changeback" style = "display:none;">change text back</a>

</div>
<script>
function chng(){
    var x;
    x = document.getElementById('p1');
    x.innerHTML = 'Changed';
    y = document.getElementById('p2');
    y.innerHTML = 'Changed also';
    z = document.getElementById('changetext');
    z.style.display = "none";
    w = document.getElementById('changeback');
    w.style.display = 'block';
}
function chngback(){
    var x;
    x = document.getElementById('p1');
    x.innerHTML = 'Foo';
    y = document.getElementById('p2');
    y.innerHTML = 'Bar';
    z = document.getElementById('changetext');
    z.style.display = "block";
    w = document.getElementById('changeback');
    w.style.display = 'none';
}
</script>
</code>```

You can use this code to change text and change it back as it was before

Title: Change text in div

Body:
Let's say I have following text in my div

Foo

Bar

  change text

and on clicking the change text button I want the text to be and on clicking the "change to old" I want it to switch to the old text again.

Lorem

Ipsum

  change to old one

Is this actually possible with the current approach with the help of css and javascript or would I have to structure my html differently? If it is possible with the current approach, how so?

Body:
<div id="textbox">
  <p id = 'p1'>Foo</p>
  <br>
  <p id = p2>Bar</p>
  <a onclick = "chng();" href= # id ="changetext">change text</a>
  <a onclick = "chngback();" href= # id ="changeback" style = "display:none;">change text back</a>

</div>
<script>
function chng(){
    var x;
    x = document.getElementById('p1');
    x.innerHTML = 'Changed';
    y = document.getElementById('p2');
    y.innerHTML = 'Changed also';
    z = document.getElementById('changetext');
    z.style.display = "none";
    w = document.getElementById('changeback');
    w.style.display = 'block';
}
function chngback(){
    var x;
    x = document.getElementById('p1');
    x.innerHTML = 'Foo';
    y = document.getElementById('p2');
    y.innerHTML = 'Bar';
    z = document.getElementById('changetext');
    z.style.display = "block";
    w = document.getElementById('changeback');
    w.style.display = 'none';
}
</script>

You can use this code to change text and change it back as it was before


问:
find duplicate addresses in database, stop users entering them early?
How do I find duplicate addresses in a database, or better stop people already when filling in the form ? I guess the earlier the better?

Is there any good way of abstracting street, postal code etc so that typos and simple attempts to get 2 registrations can be detected? like:

```<code>Quellenstrasse 66/11
Quellenstr. 66a-11
</code>```

I'm talking German addresses...
Thanks!

答:
In my opinion, assuming that you already had a lot of dirty data in your DB,

You have to do build your "handmade" dirty filter which may detect a maximum of german abreviation ...

But If you treat a lot of data, you will take the risk to find some false-positive and true-negative sample...

Finally a semi automated job (machine with human assist when probability of a case of false-positive or true-negative is too high) will be the best solution.

More you treat "exception" (because human raise exception when filling data), more your "handmade" filter will fit your requierement.

In the other hand, you may also use a germany address verification service on user side, and store only the verified one...

OwnerDisplayName: Johannes

ContentLicense: CC BY-SA 2.5

Body:
How do I find duplicate addresses in a database, or better stop people already when filling in the form ? I guess the earlier the better?

Is there any good way of abstracting street, postal code etc so that typos and simple attempts to get 2 registrations can be detected? like:

Quellenstrasse 66/11
Quellenstr. 66a-11

I'm talking German addresses...
Thanks!

LastEditorDisplayName: Remou


问:
Concurrency in PHP/MYSQL
I have the following situation :

I have a list of items viewed by several users, each item can be acquired by a single user by clicking the button "acquire" in the right of each item, I'm wondering if checking the status of the item (a boolean in items table acquired : true/false) is enough to ensure that an item can't be acquired by more than one user? or is there any practical way to do that in php/mysql ?
Cordially,
Youssef.

答:
I'm wondering if checking the status of the item (a boolean in items table acquired : true/false) is enough to ensure that an item can't be acquired by more than one user?

Depends on how you use it. If your code does something along the lines of this:

```<code>if (current status of item is "free") {
    update status of item to "taken";
}
</code>```

then it won't work, because there's a gap between the "check" and "update" where another process could slip in and take the item for itself! However, if you have a column to indicate which user has claimed an item, something along the lines of this SQL query would work:

```<code>UPDATE items SET claimed_by = :current_user
    WHERE item_id = :id AND claimed_by IS NULL
</code>```

This query will refuse to update an item that's already claimed, and you can check the claimed_by of the item to make sure you got it before proceeding.

Title: Concurrency in PHP/MYSQL

Body:
I'm wondering if checking the status of the item (a boolean in items table acquired : true/false) is enough to ensure that an item can't be acquired by more than one user?

Depends on how you use it. If your code does something along the lines of this:

if (current status of item is "free") {
    update status of item to "taken";
}

then it won't work, because there's a gap between the "check" and "update" where another process could slip in and take the item for itself! However, if you have a column to indicate which user has claimed an item, something along the lines of this SQL query would work:

UPDATE items SET claimed_by = :current_user
    WHERE item_id = :id AND claimed_by IS NULL

This query will refuse to update an item that's already claimed, and you can check the claimed_by of the item to make sure you got it before proceeding.


问:
Is there some usage of monads at .net environment?
I have learned few days ago how about Haskell monads, is there some usage of monads concept at .net environment ?
And is there ways to use this concept at my developments with c#.

Thanks for help.

答:
The Async Monad in F#'s asynchronous
workflows (the async in C# isn't
monadic)

The List comprehension
Monad, in .NET's LinQ


问:
How can I remove the jQuery .css() when clicking other button?
In this jQuery switch, I'm trying to make the button that is currently clicked go back to its original state when the other button is clicked. Also id like the off button to be clicked first automatically when the page is loaded. I've tried many codes but cant seem to get it to work.

HTML:

```<code><!DOCTYPE HTML>
<html>

<head>

    <title>Toggleswitch</title>
    <link rel="stylesheet" type="text/css" href="main.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src='script.js' type='text/javascript'></script>

</head>
<body>

<div class="switchcontainer">
    <button id="darkmodeon">ON</button>
    <button id="darkmodeoff">OFF</button>
</div>

</body>
</html>
</code>```

CSS:

```<code>body{
    background-color: black;
}

.switchcontainer{
    background-color: white;
    display: flex;
    justify-content: space-between;
    border-radius: 50px;
    width: 125px;
    padding: 5px;

}

button{
    width:50px;
    height: 50px;
    border: none;
    border-radius: 50px;
    background-color: #d8d8d8;
    color: #777777;
    font-family: 'calibri light';
    font-size: 17px;
    font-weight: bold;

}
</code>```

jQuery:

```<code>$(document).ready(function(){
    var darkon = '#darkmodeon';
    var darkoff = '#darkmodeoff';

    $(darkon).click(function(){
        $(this).css({
            "background-color": "#85c452",
            "color": "white",
            "transition": "all 0.2s ease"
        });
    });

    $(darkoff).click(function(){
        $(this).css({
            "background-color": "#85c452",
            "color": "white",
            "transition": "all 0.2s ease"
        });

        $(this).off('click',darkon);

    });

});
</code>```

答:
When a button is clicked, you can turn the other button off by setting the CSS properties for that button to inherit. This resets the properties to their default. You can target them with $('#darkmodeoff') and $('#darkmodeon'), just like you are using $(this).

To set the Off button to be selected by default, all you have to do is apply the styles to it in $(document.ready). I've gone with $('#darkmodeoff')[0].style.backgroundColor and $('#darkmodeoff')[0].style.color for this.

Personally, I'd also recommend adding cursor: pointer to the buttons to appear as though you're actually clicking on them, and outline: none to button:hover to remove the blue border that gets generated by default. I've added these to the snippet :)

$(document).ready(function() {
  var darkon = '#darkmodeon';
  var darkoff = '#darkmodeoff';

  // Set the off to clicked by default
  $('#darkmodeoff')[0].style.backgroundColor = "#85c452";
  $('#darkmodeoff')[0].style.color = "white";

  $(darkon).click(function() {
    $(this).css({
      "background-color": "#85c452",
      "color": "white",
      "transition": "all 0.2s ease"
    });
    $('#darkmodeoff').css({
      "background-color": "inherit",
      "color": "inherit",
      "transition": "all 0.2s ease"
    });
  });

  $(darkoff).click(function() {
    $(this).css({
      "background-color": "#85c452",
      "color": "white",
      "transition": "all 0.2s ease"
    });
    $('#darkmodeon').css({
      "background-color": "inherit",
      "color": "inherit",
      "transition": "all 0.2s ease"
    });
  });

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  background-color: black;
}

.switchcontainer {
  background-color: white;
  display: flex;
  justify-content: space-between;
  border-radius: 50px;
  width: 125px;
  padding: 5px;
}

button {
  width: 50px;
  height: 50px;
  border: none;
  border-radius: 50px;
  background-color: #d8d8d8;
  color: #777777;
  font-family: 'calibri light';
  font-size: 17px;
  font-weight: bold;
  cursor: pointer; /* ADDED */
}

button:focus {
  outline: none; /* ADDED */
}</code>```

  <button id="darkmodeon">ON</button>
  <button id="darkmodeoff">OFF</button>

```

Hope this helps! :)

Body:
In this jQuery switch, I'm trying to make the button that is currently clicked go back to its original state when the other button is clicked. Also id like the off button to be clicked first automatically when the page is loaded. I've tried many codes but cant seem to get it to work.

HTML:

<!DOCTYPE HTML>

    <title>Toggleswitch</title>
    <link rel="stylesheet" type="text/css" href="main.css">

    <button id="darkmodeon">ON</button>
    <button id="darkmodeoff">OFF</button>

CSS:

body{
    background-color: black;
}

.switchcontainer{
    background-color: white;
    display: flex;
    justify-content: space-between;
    border-radius: 50px;
    width: 125px;
    padding: 5px;

}

button{
    width:50px;
    height: 50px;
    border: none;
    border-radius: 50px;
    background-color: #d8d8d8;
    color: #777777;
    font-family: 'calibri light';
    font-size: 17px;
    font-weight: bold;

}

jQuery:

$(document).ready(function(){
    var darkon = '#darkmodeon';
    var darkoff = '#darkmodeoff';

    $(darkon).click(function(){
        $(this).css({
            "background-color": "#85c452",
            "color": "white",
            "transition": "all 0.2s ease"
        });
    });

    $(darkoff).click(function(){
        $(this).css({
            "background-color": "#85c452",
            "color": "white",
            "transition": "all 0.2s ease"
        });

        $(this).off('click',darkon);

    });

});

Body:
When a button is clicked, you can turn the other button off by setting the CSS properties for that button to inherit. This resets the properties to their default. You can target them with $('#darkmodeoff') and $('#darkmodeon'), just like you are using $(this).

To set the Off button to be selected by default, all you have to do is apply the styles to it in $(document.ready). I've gone with $('#darkmodeoff')[0].style.backgroundColor and $('#darkmodeoff')[0].style.color for this.

Personally, I'd also recommend adding cursor: pointer to the buttons to appear as though you're actually clicking on them, and outline: none to button:hover to remove the blue border that gets generated by default. I've added these to the snippet :)

$(document).ready(function() {
  var darkon = '#darkmodeon';
  var darkoff = '#darkmodeoff';

  // Set the off to clicked by default
  $('#darkmodeoff')[0].style.backgroundColor = "#85c452";
  $('#darkmodeoff')[0].style.color = "white";

  $(darkon).click(function() {
    $(this).css({
      "background-color": "#85c452",
      "color": "white",
      "transition": "all 0.2s ease"
    });
    $('#darkmodeoff').css({
      "background-color": "inherit",
      "color": "inherit",
      "transition": "all 0.2s ease"
    });
  });

  $(darkoff).click(function() {
    $(this).css({
      "background-color": "#85c452",
      "color": "white",
      "transition": "all 0.2s ease"
    });
    $('#darkmodeon').css({
      "background-color": "inherit",
      "color": "inherit",
      "transition": "all 0.2s ease"
    });
  });

});

body {
  background-color: black;
}

.switchcontainer {
  background-color: white;
  display: flex;
  justify-content: space-between;
  border-radius: 50px;
  width: 125px;
  padding: 5px;
}

button {
  width: 50px;
  height: 50px;
  border: none;
  border-radius: 50px;
  background-color: #d8d8d8;
  color: #777777;
  font-family: 'calibri light';
  font-size: 17px;
  font-weight: bold;
  cursor: pointer; /* ADDED */
}

button:focus {
  outline: none; /* ADDED */
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="switchcontainer">
  <button id="darkmodeon">ON</button>
  <button id="darkmodeoff">OFF</button>
</div>

Hope this helps! :)


问:
Firebase orderByChild with startAt()'s second argument w/ pagination not ordering
I have a Firebase invocation which looks like this,

```<code>      ref.child(`floorPosts/${this.props.floorName}`)
        .orderByChild('numberOfLikes')
        .limitToLast(15)
        .once('value', (snapshot) => {
          var topPosts = [];
          snapshot.forEach((childSnapshot) => {
            var post = childSnapshot.val();
            post.key = childSnapshot.key();
            topPosts.unshift(post);
          });
          this.lastPostKeyTop = topPosts[topPosts.length - 1].key;
          this.setState({
            topPosts,
            isLoading: false
          });
      });
</code>```

Now what I'm trying to do, is when the user scrolls to the bottom of the page, I invoke this function.

```<code>ref.child(`floorPosts/${this.props.floorName}`)
    .orderByChild('numberOfLikes')
    .startAt(null, this.lastPostKeyTop)
    .limitToLast(15)
    .once('value', (snapshot) => {
      var topPosts = [];
      snapshot.forEach((childSnapshot) => {
        var post = childSnapshot.val();
        post.key = childSnapshot.key();
        topPosts.unshift(post);
      });
      this.setState({
        topPosts: this.state.topPosts.concat(topPosts),
        isLoading: false,
      });
  });
</code>```

However, it's concatenating the same first 15 results as it initially did.  .startAt takes in a a second argument, which (I believe) is the key of the last item which was fetched from firebase the initial fetching. However, this doesn't seem to be working in my case. I have a hunch it's something to do with the snapshot.forEach code.

答:
sorry for the incredibly late answer Tyler

The second argument to startAt() is only used to disambiguate between items that match the first argument. So you must pass in both the value of numberOfLikes to start at and the key of the last item on the first page (often referred to as the anchor item).

Also note that this means the first item of the next set of results will be the same as the last item in the previous set of results. So you'll need to retrieve one extra item.

Body:
I have a Firebase invocation which looks like this,

      ref.child(`floorPosts/${this.props.floorName}`)
        .orderByChild('numberOfLikes')
        .limitToLast(15)
        .once('value', (snapshot) => {
          var topPosts = [];
          snapshot.forEach((childSnapshot) => {
            var post = childSnapshot.val();
            post.key = childSnapshot.key();
            topPosts.unshift(post);
          });
          this.lastPostKeyTop = topPosts[topPosts.length - 1].key;
          this.setState({
            topPosts,
            isLoading: false
          });
      });

Now what I'm trying to do, is when the user scrolls to the bottom of the page, I invoke this function.

ref.child(`floorPosts/${this.props.floorName}`)
    .orderByChild('numberOfLikes')
    .startAt(null, this.lastPostKeyTop)
    .limitToLast(15)
    .once('value', (snapshot) => {
      var topPosts = [];
      snapshot.forEach((childSnapshot) => {
        var post = childSnapshot.val();
        post.key = childSnapshot.key();
        topPosts.unshift(post);
      });
      this.setState({
        topPosts: this.state.topPosts.concat(topPosts),
        isLoading: false,
      });
  });

However, it's concatenating the same first 15 results as it initially did.  .startAt takes in a a second argument, which (I believe) is the key of the last item which was fetched from firebase the initial fetching. However, this doesn't seem to be working in my case. I have a hunch it's something to do with the snapshot.forEach code.


答:
Remove $(this).off('click',darkon); and instead add $(darkon).trigger('click'); to the start of your darkoff event handler and $(darkoff).trigger('click'); to the start of your darkon event handler.

Before you close the darkoff event handler, add this }).trigger('click');

I would edit your original code, but I'm on my phone at the moment.

Title: How can I remove the jQuery .css() when clicking other button?


问:
Maven package open a file (as a *File*) inside a jar package
I need to open a file which is inside a maven jar package. It a model configuration for a framework I use and a constructor of a library class requires to pass a object of type File. I can get a path to a configuration file using class loader without any problems. But -- unfortunately -- File can not read a file inside jar. So I get java.io.FileNotFoundException. Now I looking for a solution for this problem. My plan is to decompress the model configuration file and place it in a temporary directory. However, before starting coding, I would like to learn if there is any other solution for such a problem like mine.

UPDATE: I need to read a file in runtime.

答: I think you should use JarInputStream, traversing through JAR entries one by one, until you find what you need. Then just read() content of the found JarEntry.


问:
How can I access command prompt history with Python
On Windows 10, Python 3.6

Let's say I have a command prompt session open (not Python command prompt or Python interactive session) and I've been setting up an environment with a lot of configurations or something of that nature. Is there any way for me to access the history of commands I used in that session with a python module for example?

Ideally, I would like to be able to export this history to a file so I can reuse it in the future.

Example:

Type in command prompt: python savecmd.py
and it saves the history from that session.

答:
You don't need Python at all, use doskey facilities for that, i.e.:

```<code>doskey /history
</code>```

will print out the current session's command history, you can then redirect that to a file if you want to save it:

```<code>doskey /history > saved_commands.txt
</code>```

If you really want to do it from within Python, you can use subprocess.check_output() to capture the command history and then save it to a file:

```<code>import subprocess

cmd_history = subprocess.check_output(["doskey", "/history"])
with open("saved_commands.txt", "wb") as f:
    f.write(cmd_history)
</code>```

Body:
You don't need Python at all, use doskey facilities for that, i.e.:

doskey /history

will print out the current session's command history, you can then redirect that to a file if you want to save it:

doskey /history > saved_commands.txt

If you really want to do it from within Python, you can use subprocess.check_output() to capture the command history and then save it to a file:

import subprocess

cmd_history = subprocess.check_output(["doskey", "/history"])
with open("saved_commands.txt", "wb") as f:
    f.write(cmd_history)