DateTime2 vs DateTime in SQL Server

Question: Which one:

datetime
datetime2

is the recommended way to store date and time in SQL Server 2008+?
I'm aware of differences in precision (and storage space probably), but ignoring those for now, is there a best practice document on when to use what, or maybe we should just use datetime2 only?
Answer: The MSDN documentation for datetime recommends using datetime2. Here is their recommendation:

Use the time, date, datetime2 and
  datetimeoffset data types for new
  work. These types align with the SQL
  Standard. They are more portable.
  time, datetime2 and datetimeoffset
  provide more seconds precision.
  datetimeoffset provides time zone
  support for globally deployed
  applications.

datetime2 has larger date range, a larger default fractional precision, and optional user-specified precision. Also depending on the user-specified precision it may use less storage.
Comment: while there is increased precision with datetime2, some clients doesn't support date, time, or datetime2 and force you to convert to a string literal.  If you're concerned more about compatability than precision, use datetime
Comment: Time zone support with DATETIMEOFFSET is a misnomer. It only stores a UTC offset for a specific instant in time, not a time zone.
Comment: Another option is to use an indexed view with the column converted as a datetime for compatibility. You would need to be able to point the app to the view, however.
Comment: @Porad: What exactly is the benefit in practice of being " "more portable" due to being "SQL Standard"?  That is besides making you write significantly more code that is significantly less readable / maintainable for a "port" to another RDBMS that is likely never to occur for the life of that code.  Other than perhaps Microsoft-provided SQL Server tools and Drivers (if even), are there any apps that actually rely the specific Bit-level representations of the `DateTime2` Type (or any other SQL Server Type for that matter)?  See the Cons in my 7/10/17 Answer below for why I'm asking.
Comment: @Adam Porad: Also, all those benefits are likely unneeded (outside of engineering or scientific apps) and therefore not worth the loss of benefits much, MUCH more likely needed: the much easier (even considering workarounds) ability to implicitly / explicitly convert to a floating-point numeric (# of days incl. if appl., fractional days since min date-time) value for additions, subtractions, minimums, maximums and averages.  See the Cons in my 7/10/17 Answer below for details.
Comment: Who comes up with these function names? Any other decent programming language wouldn't accept a newer version where you add "2" to the name. What's next, datetime3 ?
Comment: @Tom Portability does put you at an advantage for switching vendors rather than being resigned to accepting whatever licensing cost a specific vendor decides to raise you to, it also makes switching to a new model like a cloud-based RDBMS easier. But maybe most importantly, it means you can seek help in the wider SQL community, rather than limiting yourself to the community for a given product (which can often be run by the company that makes the product, and may eventually have an interest in moderation that conflicts with your needs).
Comment: ***Heavy*** caveat on that MS recommendation: "_for new work_". I would take that to mean if you have an existing, legacy app, you'd need a pretty stark use case ("_These scientific tests fail when repeated b/c the date precision is too low!_") to swap, and I don't think that I'd mix the two -- casts galore for comparisons, I believe. Also, related/interesting: [`datetime` might wrap `datetime2` in SQL Server 2017+](https://blog.sqlauthority.com/2018/11/16/puzzle-datatime-to-datetime2-conversation-in-sql-server-2017/#comment-2036625).
Answer: DATETIME2 has a date range of "0001 / 01 / 01" through "9999 / 12 / 31" while the DATETIME type only supports year 1753-9999.
Also, if you need to, DATETIME2 can be more precise in terms of time; DATETIME is limited to 3 1/3 milliseconds, while DATETIME2 can be accurate down to 100ns.
Both types map to System.DateTime in .NET - no difference there.
If you have the choice, I would recommend using DATETIME2 whenever possible. I don't see any benefits using DATETIME (except for backward compatibility) - you'll have less trouble (with dates being out of range and hassle like that).
Plus: if you only need the date (without time part), use DATE - it's just as good as DATETIME2 and saves you space, too! :-) Same goes for time only - use TIME. That's what these types are there for!
Comment: Be careful when adding a .NET DateTime value as a parameter to an SqlCommand, because it likes to assume it's the old datetime type, and you'll get an error if you try to write a DateTime value that's outside that 1753-9999 year range unless you explicitly specify the type as System.Data.SqlDbType.DateTime2 for the SqlParameter.  Anyway, datetime2 is great, because it can store any value that can be stored in the .NET DateTime type.
Comment: Lol, I just tried to upvote my own comment (above), before I realized it was my own comment (made over a year ago).  I'm still dealing with the .NET framework's dumb design decision to TRUNCATE all DateTime values by default when passed as SqlParameters unless you explicitly set it to the more precise SqlDbType.DateTime2. So much for automatically inferring the correct type.  Really, they should have made the change transparent, replacing the less precise, less efficient, limited-range implementation, and kept the original "datetime" type name. See also http://stackoverflow.com/q/8421332/88409
Comment: @marc_s - Isn't that what null is for?
Comment: @JohnFX - a bit late here - but you wouldn't set a datetime to null. you would use Nullable or datetime? which handles null just fine - and in mapping to a proc would simply do param.value = someDateTime?? DBValue.Null  Its unfortunate we're stuck with a datatype with a number after it - just seems so 'generic' : )
Comment: @marc_s Isn't that what `Nullable` is for?
Comment: @Marc: There *is* a difference in the mapping to .Net types: DateTime2 is isomorphic with the .Net DateTime type, so no 'out of range' errors and probably some really tiny performance improvement as no conversion required.
Comment: @marc_s - Don't understand your point about preferring DATETIME2 when all else is equal. Is the flexibility to support year 1-1752 really a plus for most applications? I've never had an app that represented a year earlier than the late 1800's and it seems like it would encourage accidents like mis-coding 2011 as 11.
Comment: @JohnFx: I've had numerous occasions where apps would represent a "unknown" date as 01/01/0001 - which always causes trouble on SQL Server, unless you can use `DATETIME2`
Comment: I would agree with Marc.  Unless you need backwards compatibility for some reason, always go with DATETIME2.  Storage space is cheap and according to what I've seen in my own experience and read elsewhere, there is no difference in processing overhead between the two.
Comment: I don't find absolutely correct to say "Both types map to System.DateTime in .NET - no difference there".  At least nowadays EF Core recognizes  `System.DateTime` as  Sql datatype `Datetime2`
Comment: @Bazil: my response was from **2009** - yes, it probably has changed in the mean time ....
Answer: datetime2 wins in most aspects except (old apps Compatibility)

larger range of values
better Accuracy
smaller storage space  (if optional user-specified precision is specified)

please note the following points

Syntax

datetime2[(fractional seconds precision=> Look Below Storage Size)]

Precision, scale

0 to 7 digits, with an accuracy of 100ns.
The default precision is 7 digits.

Storage Size

6 bytes for precision less than 3;
7 bytes for precision 3 and 4.
All other precision require 8 bytes.

DateTime2(3) have the same number of digits as DateTime but uses 7 bytes of storage instead of 8 byte (SQLHINTS- DateTime Vs DateTime2)
Find more on datetime2(Transact-SQL MSDN article)

image source :
MCTS Self-Paced Training Kit (Exam 70-432): Microsoft® SQL Server® 2008 - Implementation and Maintenance
Chapter 3:Tables -> Lesson 1: Creating Tables -> page 66
Comment: Thanks for showing that statistics +1 for it, `datetime2` is awesome(Winner)
Comment: @Iman Abidi: According to Oskar Berggren's comment dated September 10, 2014 at 3:51 pm on the "SQLHINTS- DateTime Vs DateTime2" article you referenced: "datetime2(3) is NOT the same as datetime. They will have the same number of digits, but the precision of datetime is 3.33ms, while the precision of datetime2(3) is 1ms."
Comment: @PankajParkar: Woah, not so fast.  You might want to look at the Cons section of my Answer dated 7/10/17 below.
Comment: @Dai pretty sure the answer explains this. If you use `datetime2(3)` you save space for an analog for `datetime`. If you declare a higher precision (not an option in `datetime`), you don't save space, but you do gain precision, natch. **TL;DR** The space savings is for equal precision.
Comment: How does `datetime2` use less storage space than `datetime` and yet offer a larger range and higher precision?
Comment: One thing I ran into is that taking the MAX() of a DATETIME2(7) results in an INT. So if you compare the original value with the MAX of that column for a group of rows, you only get precision to the minute in the comparison and don't get the expected results when trying to find the latest entry in a group. That was...unexpected.
Answer: I concur with @marc_s and @Adam_Poward -- DateTime2 is the preferred method moving forward.  It has a wider range of dates, higher precision, and uses equal or less storage (depending on precision).
One thing the discussion missed, however...
@Marc_s states: Both types map to System.DateTime in .NET - no difference there.  This is correct, however, the inverse is not true...and it matters when doing date range searches (e.g. "find me all records modified on 5/5/2010").
.NET's version of  Datetime has similar range and precision to DateTime2.  When mapping a .net Datetime down to the old  SQL DateTime an implicit rounding occurs.   The old SQL DateTime is accurate to 3 milliseconds.  This means that 11:59:59.997 is as close as you can get to the end of the day. Anything higher is rounded up to the following day.
Try this :
declare @d1 datetime   = '5/5/2010 23:59:59.999'
declare @d2 datetime2  = '5/5/2010 23:59:59.999'
declare @d3 datetime   = '5/5/2010 23:59:59.997'
select @d1 as 'IAmMay6BecauseOfRounding', @d2 'May5', @d3 'StillMay5Because2msEarlier'

Avoiding this implicit rounding is a significant reason to move to DateTime2.  Implicit rounding of dates clearly causes confusion:

Strange datetime behavior in SQL Server
http://bytes.com/topic/sql-server/answers/578416-weird-millisecond-part-datetime-data-sql-server-2000-a
SQL Server 2008 and milliseconds
http://improve.dk/archive/2011/06/16/getting-bit-by-datetime-rounding-or-why-235959-999-ltgt.aspx
http://milesquaretech.com/Blog/post/2011/09/12/DateTime-vs-DateTime2-SQL-is-Rounding-My-999-Milliseconds!.aspx
Comment: You can also avoid this rounding by not trying to find the "end" of a day anyway. >= May 5 AND < May 6 is much safer and will work on any of the date/time types (except TIME of course). Also suggest avoiding regional, ambiguous formats like m/d/yyyy.
Comment: @AaronBertrand - totally agree, but looking at the number of questions we have the matter it seemed worth describing.
Comment: Why did you switch from `20100505` to `5/5/2010`? The former format will work with any region in SQL Server. The latter will break: `SET LANGUAGE French; SELECT Convert(datetime, '1/7/2015')` oops: `2015-07-01 00:00:00.000`
Comment: @EBarr: Re. "DateTime2 is the preferred method moving forward. It has a wider range of dates, higher precision, and uses equal or less storage (depending on precision": I strongly disagree.  See the Cons section of my Answer dated 7/10/17 below.  In short, those benefits are likely unneeded (outside engineering/scientific apps) and therefore not worth the loss of benefits MUCH more likely needed, the much easier (even considering workarounds) ability to implicitly / explicitly convert to a floating-point numeric (# of days incl. if appl., fractions since min date-time) value for +, - and avg.
Answer: Almost all the Answers and Comments have been heavy on the Pros and light on the Cons.  Here's a recap of all Pros and Cons so far plus some crucial Cons (in #2 below) I've only seen mentioned once or not at all.

PROS:

1.1.    More ISO compliant (ISO 8601) (although I don't know how this comes into play in practice).
1.2.    More range (1/1/0001 to 12/31/9999 vs. 1/1/1753-12/31/9999) (although the extra range, all prior to year 1753, will likely not be used except for ex., in historical, astronomical, geologic, etc. apps).
1.3.    Exactly matches the range of .NET's DateTime Type's range (although both convert back and forth with no special coding if values are within the target type's range and precision except for Con # 2.1 below else error / rounding will occur).
1.4.    More precision (100 nanosecond aka 0.000,000,1 sec. vs. 3.33 millisecond aka 0.003,33 sec.) (although the extra precision will likely not be used except for ex., in engineering / scientific apps).
1.5.    When configured for similar (as in 1 millisec not "same" (as in 3.33 millisec) as Iman Abidi has claimed) precision as DateTime, uses less space (7 vs. 8 bytes), but then of course, you'd be losing the precision benefit which is likely one of the two (the other being range) most touted albeit likely unneeded benefits).

CONS:

2.1.    When passing a Parameter to a .NET SqlCommand, you must specify System.Data.SqlDbType.DateTime2 if you may be passing a value outside the SQL Server DateTime's range and/or precision, because it defaults to System.Data.SqlDbType.DateTime.
2.2.    Cannot be implicitly / easily converted to a floating-point numeric (# of days since min date-time) value to do the following to / with it in SQL Server expressions using numeric values and operators:
2.2.1.  add or subtract # of days or partial days.  Note: Using DateAdd Function as a workaround is not trivial when you're needing to consider multiple if not all parts of the date-time.
2.2.2.  take the difference between two date-times for purposes of "age" calculation.  Note: You cannot simply use SQL Server's DateDiff Function instead, because it does not compute age as most people would expect in that if the two date-times happens to cross a calendar / clock date-time boundary of the units specified if even for a tiny fraction of that unit, it'll return the difference as 1 of that unit vs. 0.  For example, the DateDiff in Day's of two date-times only 1 millisecond apart will return 1 vs. 0 (days) if those date-times are on different calendar days (i.e. "1999-12-31 23:59:59.9999999" and "2000-01-01 00:00:00.0000000").  The same 1 millisecond difference date-times if moved so that they don't cross a calendar day, will return a "DateDiff" in Day's of 0 (days).
2.2.3.  take the Avg of date-times (in an Aggregate Query) by simply converting to "Float" first and then back again to DateTime.
NOTE: To convert DateTime2 to a numeric, you have to do something like the following formula which still assumes your values are not less than the year 1970 (which means you're losing all of the extra range plus another 217 years.  Note: You may not be able to simply adjust the formula to allow for extra range because you may run into numeric overflow issues.
25567 + (DATEDIFF(SECOND, {d '1970-01-01'}, @Time) + DATEPART(nanosecond, @Time) / 1.0E + 9) / 86400.0 – Source: " https://siderite.dev/blog/how-to-translate-t-sql-datetime2-to.html "
Of course, you could also Cast to DateTime first (and if necessary back again to DateTime2), but you'd lose the precision and range (all prior to year 1753) benefits of DateTime2 vs. DateTime which are prolly the 2 biggest and also at the same time prolly the 2 least likely needed which begs the question why use it when you lose the implicit / easy conversions to floating-point numeric (# of days) for addition / subtraction / "age" (vs. DateDiff) / Avg calcs benefit which is a big one in my experience.
Btw, the Avg of date-times is (or at least should be) an important use case. a) Besides use in getting average duration when date-times (since a common base date-time) are used to represent duration (a common practice), b) it's also useful to get a dashboard-type statistic on what the average date-time is in the date-time column of a range / group of Rows. c) A standard (or at least should be standard) ad-hoc Query to monitor / troubleshoot values in a Column that may not be valid ever / any longer and / or may need to be deprecated is to list for each value the occurrence count and (if available) the Min, Avg and Max date-time stamps associated with that value.
Comment: Like the contrarian view - it points out the c# side of the equation.  Combined with all the other "pros" it will allow people to make a good choice based on where they want to take their pain.
Comment: @EBarr: Only the Cons #1 part of my "'contrarian view'" "points out the c# side of the equation".  The rest (Cons #'s 2.2.1 - 2.2.3), which like I said are the far more likely needed benefits (of `DateTime`), are all related to effects on SQL Server Queries and statements.
Comment: Re 2.2.1 -- it is considered an unsafe practice to do arithmetic on dates, and the preferred way is always to use DateAdd and related functions. This is best practice. There are serious liabilities to doing date arithmetic, not the least of which is it doesn't work for most date types. A few articles:

https://www.sqlservercentral.com/blogs/manipulating-dates-and-times-in-t-sql
https://sqlblog.org/2011/09/20/bad-habits-to-kick-using-shorthand-with-date-time-operations
Comment: @RBerman:

Re. "unsafe": It's only unsafe with certain date types (like the `DateTime2` I already mentioned (due to high chance of overflow)).

Re. "desn't work for most date types": You only need it to work with one, and most dates in most apps will likely never need to be converted to another date type for their entire life times (except maybe, like I also mentioned, `DateTime2` to `DateTime` (e.g. to do "arithmetic on dates" ;P).  Given that, it's not worth all the extra coding in not only programmed but also ad-hoc research queries to use a non-arithmetic friendly date type.
Answer: Here is an example that will show you the differences in storage size (bytes) and precision between smalldatetime, datetime, datetime2(0), and datetime2(7):
DECLARE @temp TABLE (
    sdt smalldatetime,
    dt datetime,
    dt20 datetime2(0),
    dt27 datetime2(7)
)

INSERT @temp
SELECT getdate(),getdate(),getdate(),getdate()

SELECT sdt,DATALENGTH(sdt) as sdt_bytes,
    dt,DATALENGTH(dt) as dt_bytes,
    dt20,DATALENGTH(dt20) as dt20_bytes,
    dt27, DATALENGTH(dt27) as dt27_bytes FROM @temp

which returns
sdt                  sdt_bytes  dt                       dt_bytes  dt20                 dt20_bytes  dt27                         dt27_bytes
-------------------  ---------  -----------------------  --------  -------------------  ----------  ---------------------------  ----------
2015-09-11 11:26:00  4          2015-09-11 11:25:42.417  8         2015-09-11 11:25:42  6           2015-09-11 11:25:42.4170000  8

So if I want to store information down to the second - but not to the millisecond - I can save 2 bytes each if I use datetime2(0) instead of datetime or datetime2(7).
Answer: DateTime2 wreaks havoc if you are an Access developer trying to write Now() to the field in question. Just did an Access -> SQL 2008 R2 migration and it put all the datetime fields in as DateTime2. Appending a record with Now() as the value bombed out. It was okay on 1/1/2012 2:53:04 PM, but not on 1/10/2012 2:53:04 PM.
Once character made the difference. Hope it helps somebody.
Answer: Old Question... But I want to add something not already stated by anyone here... (Note: This is my own observation, so don't ask for any reference)
Datetime2 is faster when used in filter criteria.
TLDR:
In SQL 2016 I had a table with hundred thousand rows and a datetime column ENTRY_TIME because it was required to store the exact time up to seconds. While executing a complex query with many joins and a sub query, when I used where clause as:
WHERE ENTRY_TIME >= '2017-01-01 00:00:00' AND ENTRY_TIME < '2018-01-01 00:00:00'

The query was fine initially when there were hundreds of rows, but when number of rows increased, the query started to give this error:
Execution Timeout Expired. The timeout period elapsed prior
to completion of the operation or the server is not responding.

I removed the where clause, and unexpectedly, the query was run in 1 sec, although now ALL rows for all dates were fetched. I run the inner query with where clause, and it took 85 seconds, and without where clause it took 0.01 secs.
I came across many threads here for this issue as datetime filtering performance
I optimized query a bit. But the real speed I got was by changing the datetime column to datetime2.
Now the same query that timed out previously takes less than a second.
cheers
Answer: Interpretation of date strings into datetime and datetime2 can be different too, when using non-US DATEFORMAT settings. E.g.
set dateformat dmy
declare @d datetime, @d2 datetime2
select @d = '2013-06-05', @d2 = '2013-06-05'
select @d, @d2

This returns 2013-05-06 (i.e. May 6) for datetime, and 2013-06-05 (i.e. June 5) for datetime2.  However, with dateformat set to mdy, both @d and @d2 return 2013-06-05.
The datetime behavior seems at odds with the MSDN documentation of SET DATEFORMAT which states: Some character strings formats, for example ISO 8601, are interpreted independently of the DATEFORMAT setting.  Obviously not true!
Until I was bitten by this, I'd always thought that yyyy-mm-dd dates would just be handled right, regardless of the language / locale settings.
Comment: Nope. For ISO 8601 I think you meant YYYYMMDD (no dashes). `SET LANGUAGE FRENCH; DECLARE @d DATETIME = '20130605'; SELECT @d;` Try again with the dashes.
Comment: I know that but in SQL Server only the no-dash syntax is safe.
Comment: The standard allows for both YYYY-MM-DD and YYYYMMDD formats for calendar date representations. I think MSDN should be more specific about which subset of the ISO 8601 specification is interpreted independently!
Answer: while there is increased precision with datetime2, some clients doesn't support date, time, or datetime2 and force you to convert to a string literal.  Specifically Microsoft mentions "down level" ODBC, OLE DB, JDBC, and SqlClient issues with these data types and has a chart showing how each can map the type.
If value compatability over precision, use datetime
Answer: According to this article, if you would like to have the same precision of DateTime using DateTime2 you simply have to use DateTime2(3).  This should give you the same precision, take up one fewer bytes, and provide an expanded range.
Comment: To be clear, it's the same precision as SQL datetime, not a .NET DateTime.
Comment: That is correct, I assumed everyone would understand the context but its worth specifically stating.
Answer: I just stumbled across one more advantage for DATETIME2: it avoids a bug in the Python adodbapi module, which blows up if a standard library datetime value is passed which has non-zero microseconds for a DATETIME column but works fine if the column is defined as DATETIME2.
Answer: As the other answers show datetime2 is recommended due to smaller size and more precision, but here are some thoughts on why NOT to use datetime2 from Nikola Ilic:

lack of (simple) possibility to do basic math operations with dates, like GETDATE()+1
every time you are doing comparisons with DATEADD or DATEDIFF, you will finish with implicit data conversion to datetime
SQL Server can't use statistics properly for Datetime2 columns, due to a way data is stored that leads to non-optimal query plans, which decrease the performance
Comment: > "SQL Server can't use statistics properly for Datetime2 columns, due to a way data is stored that leads to non-optimal query plans, which decrease the performance"
Citation needed
Comment: @Milney it is quoted from the article mentioned (3rd paragraph from the end) - https://towardsdatascience.com/datetime2-why-you-should-not-use-it-70e50ae2bab9
Answer: I think DATETIME2 is the better way to store the date, because it has more efficiency than
the DATETIME. In SQL Server 2008 you can use DATETIME2, it stores a date and time, takes 6-8 bytes to store and has a precision of 100 nanoseconds. So anyone who needs greater time precision will want DATETIME2.
Answer: Accepted answer is great, just know that if you are sending a DateTime2 to the frontend - it gets rounded to the normal DateTime equivalent.
This caused a problem for me because in a solution of mine I had to compare what was sent with what was on the database when resubmitted, and my simple comparison '==' didn't allow for rounding. So it had to be added.
Answer: datetime2 is better

datetime range : 1753-01-01 through 9999-12-31 , datetime2 range : 0001-01-01 through 9999-12-31

datetime Accuracy : 0.00333 second , datetime2 Accuracy : 100 nanoseconds

datetime get 8 bytes , datetime2 get 6 to 8 bytes depends on precisions
(6 bytes for precision less than 3 , 7 bytes for precision 3 or 4 , All other precision require 8 bytes, Click and Look at the below picture)
Answer: Select ValidUntil + 1
from Documents

The above SQL won't work with a DateTime2 field.
It returns and error "Operand type clash: datetime2 is incompatible with int"
Adding 1 to get the next day is something developers have been doing with dates for years. Now Microsoft have a super new datetime2 field that cannot handle this simple functionality.
"Let's use this new type that is worse than the old one", I don't think so!
Comment: This is not clear. I have a SQLServer 2005 database with a datetime field in it.
Comment: Just so we're clear here the `datetime` and `datetime2` data types were both introduced in SQL Server 2008. You also get `Operand type clash: date is incompatible with int` from the `date` type which has been around since day dot. All three data types work just fine with `dateadd(dd, 1, ...)` though.
Comment: `datetime` was available in Microsoft SQL Server 4.0, when the codebase was still shared with sybase.  I'm not sure of the exact version it was added, but it's been there for a very long time.

DateTime2 vs DateTime in SQL Server


How to disable or limit compression of over-full pages in Lilypond?

Question: Sometimes lilypond tries to use less pages for more music, which is not always wanted. This can be easily fixed by manually adding \pageBreak , but sometimes an automatic solution is needed.
When vertical compression happens, lilypond log shows something like this:
warning: compressing over-full page by 36.9 staff-spaces
warning: page 4 has been compressed

In my particular situation lilypond script is generated by MusicXML analysis program and no manual tweaking of positions or pagebreaks is possible, because we do not know what music user can upload.
How can compression be totally disabled or limited, so that Lilypond would have to add page breaks? Automatic solution is required, which does not include manually tweaking positions of elements and pagebreaks.
Sorry for posting such a big example, but many elements are needed so that page is not enough any more. Here is an example of automatically generated score:
1. Automatic line breaking leads to vertically over-compressing first page (text lines are too close to each other, numbers inside score collide with text spanners):
https://github.com/rualark/MGen/blob/master/MGen/configs/ly2/debug/compressing/compressed2.ly
https://github.com/rualark/MGen/blob/master/MGen/configs/ly2/debug/compressing/compressed2.pdf
Mirror: http://lilybin.com/f7wjax/1
Mirror: https://www.hacklily.org/?edit=rualark/sheet-music/overcompressed.ly
2. Adding just one \pageBreak command fixes everything:
https://github.com/rualark/MGen/blob/master/MGen/configs/ly2/debug/compressing/uncompressed2.ly
https://github.com/rualark/MGen/blob/master/MGen/configs/ly2/debug/compressing/uncompressed2.pdf
Mirror: http://lilybin.com/7xlar8/1
Mirror: https://www.hacklily.org/?edit=rualark/sheet-music/uncompressed.ly
I already did a google search of known issues and visited lilypond documentation with no significant progress so far:
http://lilypond.org/doc/v2.18/Documentation/notation/vertical-spacing
http://lilypond.1069038.n5.nabble.com/warning-compressing-over-full-page-by-12-4-staff-spaces-td168716.html
Please help!
Comment: In your example, you often use `\once \override` with the same properties. Why don't you just use `\override` only once in the beginning? If you can navigate through your code, it's fine, but it can be simplified a lot! And this would help others to understand it. Now, to your question: did you look into vertical positioning in the doc: http://lilypond.org/doc/v2.18/Documentation/notation/explicit-staff-and-system-positioning.html
Comment: @JasperHabicht sorry that I did not state clearly enough, that automatic solution is needed in this particular case. The script is generated completely by a program and human cannot interfere to add manual positions or page breaks (I updated the post). As for '\once', I use it to prevent overriding properties back to previous color, which both makes lilypond script longer and makes analysis program more difficult. If you consider this an important issue, I will try to think of a better solution.
Answer: As far as I know, you can only tell Lilypond how to space lines within one markup, but not between markups (except perhaps with a padding). This is especially problematic if this markup is not embedded into a Staff context. Maybe I am wrong, though …
So, you should probably not use many single \markup macros, but instead make use of a \markuplist and \wordwrap-lines. This should prevent Lilypond from compressing the spacing between single markup commands. At least, it is worth a try.
You can use one markuplist per paragraph, for example. The spec says, markuplists can span over several pages, so maybe you can even just use one. I don't know how your script exactly works that generates this output, but maybe this is a feasible solution?
I added snippets from your code and in the following example but reduced it to the most important parts:
\version "2.18.2"
\language "english"
\paper {
  #(include-special-characters)
  bottom-margin = 0.27\in
}
% Your definitions here
\markup \wordwrap {
  \bold { "#"2 (from test-vocal-range) Key: G mixolydian }
  \tiny { "Lyrics:" "sp1." }
}
<<
% Your notes and formatting here
\new Staff = "staff1" {
  \set Staff.instrumentName = \markup { \teeny \override #'(baseline-skip . 2.0) \center-column{ "Part"  ""  "[Soprano]" } }
  \new Voice { \override NoteHead.color=#(rgb-color 1.000 0.000 0.000)
  d'1
  }
}
% etc.
>>
\markuplist {
  \wordwrap-lines { \tiny \bold "Part [bar 1, beat 1] note D" }
  \wordwrap-lines { \smaller \with-color #(rgb-color 1.000 0.000 0.000) "1 - Melody: Stagnation (5 notes <m3)" }
  \wordwrap-lines { \smaller \with-color #(rgb-color 1.000 0.000 0.000) "1 - Melody: Stagnation (5 notes <m3)" }
}
\markuplist {
  \wordwrap-lines { \tiny \bold "Part [bar 1, beat 1] note D" }
  \wordwrap-lines { \smaller \with-color #(rgb-color 1.000 0.000 0.000) "1 - Melody: Stagnation (5 notes <m3)" }
  \wordwrap-lines { \smaller \with-color #(rgb-color 1.000 0.000 0.000) "1 - Melody: Stagnation (5 notes <m3)" }
}
% ... and so on

Comment: Thanks for an idea! Yet, isn't it strange that we cannot prevent over-compressing blocks? For example, lilypond shows how many staff-spaces were compressed in the log above. Probably this value can be limited, but I cannot find how.
Comment: I tried this solution, but `\markuplist` `\workwrap-lines` entries have too far interval between them when uncompressed (see page 2). I tried to `\override #'(baseline-skip . 2)` with no success. The main problem with this approach is that markup inside score still collides with text spanners due to compression: https://github.com/rualark/MGen/blob/master/MGen/configs/ly2/debug/compressing/compressed3.ly https://github.com/rualark/MGen/blob/master/MGen/configs/ly2/debug/compressing/compressed3.pdf
Comment: You are right. I found another possible approach: You could add `#(define page-breaking ly:page-turn-breaking)` to the `\paper` macro. This allows Lilypond to switch to another page-breaking algorithm. Perhaps this helps in some cases. The compression problem is still not really solved. As for the distances: try to add `\override #'(baseline-skip . 2)` in front of every `\wordwrap-lines` command. And the distances inside the score can probably be adjusted using paddings?
Comment: I found that adding `#(define page-breaking ly:page-turn-breaking)` to `\paper` macro solves problem completely. I read about this option before, but did not even try that, because this was not straightforward. Obviously, there are bugs in `optimal-breaking` and `minimal-breaking` which both give bad results for this test score. Unfortunately, `page-turn-breaking` tends to generate more pages, because it leaves more blank space - and sometimes a lot of unneeded blank space like on page 1 in this example:
Comment: Example of too much blank space on page 1: https://github.com/rualark/MGen/blob/master/MGen/configs/ly2/debug/compressing/2019-02-08_23-48-55_Erreurs%20TP04-mod.ly https://github.com/rualark/MGen/blob/master/MGen/configs/ly2/debug/compressing/2019-02-08_23-48-55_Erreurs%20TP04-mod.pdf

Looks much better with `optimal-breaking`:
https://github.com/rualark/MGen/blob/master/MGen/configs/ly2/debug/compressing/2019-02-08_23-54-56_Erreurs%20TP04-mod.pdf

This is very unfortunate, because one method over-compresses and another is extremely sparse
Comment: And `minimal-breaking` tends to give most condensed results without compressing, until it fails with the same test example above - with the same over-full compression result. Here is example of best `minimal-breaking` results:
https://github.com/rualark/MGen/blob/master/MGen/configs/ly2/debug/compressing/2019-02-09_00-07-31_Erreurs%20TP04-mod.pdf


Density of $\mathscr{S}$ in $H^s(\mathbb{R}^n)$

Question: As usual, we define $H^s(\mathbb{R}^n)$ as the set of distributions $f\in\mathscr{S}'$ such that $\hat{f}\in L^2_{\text{loc}}$, and
$$ \|f\|_{H^s}:=\left(\int \left(1+\left|\xi\right|^2\right)^s\left|\hat{f}(\xi)\right|^2\mathop{dx}\right)^{1/2} <\infty$$
How can I prove that $\mathscr{S}$ is dense in $H^s$ for all $s\in \mathbb{R}$?
Comment: Wouldn't convergence in $L^2$ imply convergence in $H^s$ when $s<0$?
Comment: @MarkoKarbevski You're right! I edited this out.
Answer: Taking the Fourier transform it suffices to show that $\widehat{\mathscr{S}}=\mathscr{S}$ is dense in $L^2(\Bbb{R}, (1+|x|)^{2s}dx)$ which follows from that $(f1_{|f|<A})\ast ne^{-\pi n^2 x^2}$ is Schwartz, and $f1_{|f|<A}\xrightarrow{A\to\infty} f$, and $ne^{-\pi n^2 x^2}\xrightarrow{n\to\infty} \delta_0$.


Simplex Random Walk

Question: This link describes how to perform a random walk on the simplex using the Metropolis-Hastings algorithm:
http://en.wikipedia.org/wiki/User:Skinnerd/Simplex_Point_Picking
The description says:
"The stationary distribution of its samples is the unit-exponential distribution."
As well as
"This procedure effectively samples x_new from a gamma random variable with mean of x_old and standard deviation of h*x_old."
Finally the actual update step is:
"x_new <- x_old * exp( Random_Normal(0,h) )"
I'm trying to understand the algorithm, specifically how it calculates the hastings ratio given the general description of the algorithm here http://en.wikipedia.org/wiki/Metropolis%E2%80%93Hastings_algorithm.
My question is what is the proposal distribution g(x_old -> x_new)?
Is the proposal distribution actually g(x_old -> x_new) = x_old * exp( Random_Normal(0,h) ), which would make the hastings ratio g(x_new -> x_old) / g(x_old -> x_new) = x_new / x_old?
Thanks for any help.
Answer: The linked algorithm seems to actually be slightly erroneous (I explain the error in the end of the answer), however, the Hastings ratio you ask about is computed correctly
Goal of the algorithm
The algorithm described is a Metropolis-Hastings sampling on one-dimensional $x$ targeting the unit-exponential distribution. To use this to obtain the samples on the simplex, one needs to normalize a vector of samples from $n$ different unit-exponential $x$:s. The function next_point performs a single Metropolis-Hastings step in these one-dimensional distributions
Proposal distribution and Hastings ratio
The proposal is made in the following line:
x_new <- x_old * exp( Random_Normal(0,h) )

So,  $x_{new}$ is drawn by multiplying $x_{old}$ by a $e^Z$ where $Z\sim N(0,h)$. i.e.,
\begin{equation}
x_{new} = x_{old}e^Z
\end{equation}
Taking logarithms,
\begin{equation}
\log x_{new} = \log x_{old} + Z.
\end{equation}
So, actually the conditional distribution of $x_{new}$ is normal:
\begin{equation}
\log x_{new} \mid x_{old} \sim N(\log x_{old}, h).
\end{equation}
From the last expression we see that $q(x_{new}\mid x_{old})$ is a log-normal distribution with parameters $(\log x_{new},h)$. Then, to evaluate the Hastings ratio, we just plug in the log-normal densities:
\begin{equation}
\left. \frac{q(x_{old} \mid x_{new})}{q(x_{new} \mid x_{old})} = \frac{1}{x_{old}\sqrt{2\pi}h}e^{-\frac{-(\log x_{old} - \log x_{new})^2}{2h^2}} \middle/ \frac{1}{x_{new}\sqrt{2\pi}h}e^{-\frac{-(\log x_{new} - \log x_{old})^2}{2h^2}}\right. = \frac{x_{new}}{x_{old}}.
\end{equation}
This part corresponds to the code line:
hastings_ratio <- ( x_new / x_old )

Metropolis ratio (ratio of target densities)
Finally, we need to compute the ratio between the densities of the target distribution
\begin{equation}
\frac{p(x_{new})}{p(x_{old})} = \frac{e^{-x_{new}}}{e^{-x_{old}}}
\end{equation}
which corresponds to the code line:
metropolis_ratio <- exp(-x_new) / exp(-x_old)

The error in the algorithm
The acceptance ratio is calculated correctly. However, in Metropolis-Hastings, if a proposal is rejected, the current value should be repeated in the chain. The next_point function as written in the link will retry proposing new values until a proposal is accepted. Instead, it should simply return $x_{old}$ if the proposed value is rejected.
Comment: Thanks, your answer has completely cleared up my confusion. I have accepted it but cannot upvote because I have less than 15 reputation on this forum.

Simplex Random Walk


301 Redirection Issue

Question: I want to redirect /test/blog/old-acne-problems to samesite/test/blog/acne-being-taken-seriously
I did the following redirection
Redirect 301 /test/blog/old-acne-problems samesite/test/blog/acne-being-taken-seriously

but when I checked it the redirection comes out to be
samesite/test/blog/acne-being-taken-seriously?q=/test/blog/old-acne-problems

an extra query string is coming i.e. ?q
Please let me know the proper redirection. I don't want ?q=/test/blog/old-acne-problems this part.

Note: Redirection is on the same site itself.
Answer:
Option 1: You have forgotten the first slash !
Redirect 301 /test/blog/old-acne-problems /samesite/test/blog/acne-being-taken-seriously
Option 2: There are other rules which change your url. (Probably some rules from wordpress)

(give us all of your rules)

301 Redirection Issue


using multiple schemes in a clustered sql server 2008 Database

Question: I have a SQL server 2008 R2 database with 2 schemas, i need to enhance the performance of the server so we plan to cluster the DB, we will have 2 nodes . is it possible to separate each scheme so each node will have one schema
Answer: No. Simple like that. The unit of separation is a database, not a schema. And clusters are active/passive.
Answer: You can build an active/active cluster, which with SQL Server basically means you have two separate SQL instances with it's own name an virtual IP address. Each instance can hold one of your schemas.
Some caveats to keep in mind:

Note you need to fully license both cluster nodes in this scenario.<
You need to have enough shared storage for the two dedicated SQL instances as LUNs can't be active on more than one node.
You can only use half the memory on each node, in case of box failure you'd need to run both instances on one node.

There are good guides on the net how to configure this, it's a bit more complex than a normal active/passive cluster.


DeclarationError: Identifier not found or not unique. Not getting What declaration mistake I have made

Question: // SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract funcction{

    unit age = 18;

    function changeAge(unit _x) public view returns(unit){
        return _x+1;
    }

}

Answer: you misspelled uint
its uint not unit
fun fact!
uint defaults to uint256


how to change the background of hub title with random colors and change image pixel of hubtile?

Question: I have prepared a custom hubtile which has a image and textbloxk for displaying the image and text needed.I have hardcoded the background color of tiles as white,Now can anyone suggest how to change the background of tiles with multiple colors and also can any one suggest to change the color of image(i.e change pixel of image coming from server which is used as HubTile source). I have been using below code
xaml file code
<code><Style x:Key="HomePageTabStyle"
       TargetType="toolkit:HubTile">
    <Setter Property="Height"
            Value="173" />
    <Setter Property="Width"
            Value="173" />
   <Setter Property="Background"
            Value="White" />
    <!--<Setter Property="Background"
            Value="{StaticResource PhoneAccentBrush}" />-->
    <Setter Property="Foreground"
            Value="#FFFFFFFF" />
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="toolkit:HubTile">
                <Border x:Name="Container">
                    <Border.Resources>
                        <CubicEase x:Key="HubTileEaseOut"
                                   EasingMode="EaseOut" />
                    </Border.Resources>
                    <Border.Height>
                        <Binding Converter="{StaticResource HeightConverter}"
                                 Path="Size"
                                 RelativeSource="{RelativeSource TemplatedParent}" />
                    </Border.Height>
                    <VisualStateManager.VisualStateGroups>
                        <VisualStateGroup x:Name="ImageStates">
                            <VisualStateGroup.Transitions>
                                <VisualTransition x:Name="ExpandedToSemiexpanded"
                                                  From="Expanded"
                                                  GeneratedDuration="0:0:0.85"
                                                  To="Semiexpanded">
                                    <Storyboard>
                                        <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransform).(CompositeTransform.TranslateY)"
                                                                       Storyboard.TargetName="TitlePanel">
                                            <EasingDoubleKeyFrame EasingFunction="{StaticResource HubTileEaseOut}"
                                                                  KeyTime="0:0:0.0"
                                                                  Value="{Binding Size, ConverterParameter=-1, Converter={StaticResource HeightConverter}, RelativeSource={RelativeSource TemplatedParent}}" />
                                            <EasingDoubleKeyFrame EasingFunction="{StaticResource HubTileEaseOut}"
                                                                  KeyTime="0:0:0.85"
                                                                  Value="{Binding Size, ConverterParameter=-0.4566, Converter={StaticResource HeightConverter}, RelativeSource={RelativeSource TemplatedParent}}" />
                                        </DoubleAnimationUsingKeyFrames>
                                        <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="RotationX"
                                                                       Storyboard.TargetName="ViewportProjection">
                                            <EasingDoubleKeyFrame EasingFunction="{StaticResource HubTileEaseOut}"
                                                                  KeyTime="0:0:0.0"
                                                                  Value="0.0" />
                                        </DoubleAnimationUsingKeyFrames>
                                    </Storyboard>
                                </VisualTransition>
                                <VisualTransition x:Name="SemiexpandedToExpanded"
                                                  From="Semiexpanded"
                                                  GeneratedDuration="0:0:0.85"
                                                  To="Expanded">
                                    <Storyboard>
                                        <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransform).(CompositeTransform.TranslateY)"
                                                                       Storyboard.TargetName="TitlePanel">
                                            <EasingDoubleKeyFrame EasingFunction="{StaticResource HubTileEaseOut}"
                                                                  KeyTime="0:0:0.0"
                                                                  Value="{Binding Size, ConverterParameter=-0.4566, Converter={StaticResource HeightConverter}, RelativeSource={RelativeSource TemplatedParent}}" />
                                            <EasingDoubleKeyFrame EasingFunction="{StaticResource HubTileEaseOut}"
                                                                  KeyTime="0:0:0.85"
                                                                  Value="{Binding Size, ConverterParameter=-1, Converter={StaticResource HeightConverter}, RelativeSource={RelativeSource TemplatedParent}}" />
                                        </DoubleAnimationUsingKeyFrames>
                                    </Storyboard>
                                </VisualTransition>
                                <VisualTransition x:Name="SemiexpandedToCollapsed"
                                                  From="Semiexpanded"
                                                  GeneratedDuration="0:0:0.85"
                                                  To="Collapsed">
                                    <Storyboard>
                                        <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransform).(CompositeTransform.TranslateY)"
                                                                       Storyboard.TargetName="TitlePanel">
                                            <EasingDoubleKeyFrame EasingFunction="{StaticResource HubTileEaseOut}"
                                                                  KeyTime="0:0:0.0"
                                                                  Value="{Binding Size, ConverterParameter=-0.4566, Converter={StaticResource HeightConverter}, RelativeSource={RelativeSource TemplatedParent}}" />
                                            <EasingDoubleKeyFrame EasingFunction="{StaticResource HubTileEaseOut}"
                                                                  KeyTime="0:0:0.85"
                                                                  Value="0.0" />
                                        </DoubleAnimationUsingKeyFrames>
                                    </Storyboard>
                                </VisualTransition>
                                <VisualTransition x:Name="CollapsedToExpanded"
                                                  From="Collapsed"
                                                  GeneratedDuration="0:0:0.85"
                                                  To="Expanded">
                                    <Storyboard>
                                        <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransform).(CompositeTransform.TranslateY)"
                                                                       Storyboard.TargetName="TitlePanel">
                                            <EasingDoubleKeyFrame EasingFunction="{StaticResource HubTileEaseOut}"
                                                                  KeyTime="0:0:0.0"
                                                                  Value="0.0" />
                                            <EasingDoubleKeyFrame EasingFunction="{StaticResource HubTileEaseOut}"
                                                                  KeyTime="0:0:0.85"
                                                                  Value="{Binding Size, ConverterParameter=-1, Converter={StaticResource HeightConverter}, RelativeSource={RelativeSource TemplatedParent}}" />
                                        </DoubleAnimationUsingKeyFrames>
                                    </Storyboard>
                                </VisualTransition>
                                <VisualTransition x:Name="ExpandedToFlipped"
                                                  From="Expanded"
                                                  GeneratedDuration="0:0:0.85"
                                                  To="Flipped">
                                    <Storyboard>
                                        <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransform).(CompositeTransform.TranslateY)"
                                                                       Storyboard.TargetName="TitlePanel">
                                            <EasingDoubleKeyFrame EasingFunction="{StaticResource HubTileEaseOut}"
                                                                  KeyTime="0:0:0.0"
                                                                  Value="{Binding Size, ConverterParameter=-1, Converter={StaticResource HeightConverter}, RelativeSource={RelativeSource TemplatedParent}}" />
                                        </DoubleAnimationUsingKeyFrames>
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Visibility)"
                                                                       Storyboard.TargetName="Image">
                                            <DiscreteObjectKeyFrame KeyTime="0:0:0.185"
                                                                    Value="Collapsed" />
                                        </ObjectAnimationUsingKeyFrames>
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Visibility)"
                                                                       Storyboard.TargetName="BackPanel">
                                            <DiscreteObjectKeyFrame KeyTime="0:0:0.185"
                                                                    Value="Visible" />
                                        </ObjectAnimationUsingKeyFrames>
                                        <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="RotationX"
                                                                       Storyboard.TargetName="ViewportProjection">
                                            <EasingDoubleKeyFrame EasingFunction="{StaticResource HubTileEaseOut}"
                                                                  KeyTime="0:0:0.0"
                                                                  Value="0.0" />
                                            <EasingDoubleKeyFrame EasingFunction="{StaticResource HubTileEaseOut}"
                                                                  KeyTime="0:0:0.85"
                                                                  Value="180.0" />
                                        </DoubleAnimationUsingKeyFrames>
                                    </Storyboard>
                                </VisualTransition>
                                <VisualTransition x:Name="FlippedToExpanded"
                                                  From="Flipped"
                                                  GeneratedDuration="0:0:0.85"
                                                  To="Expanded">
                                    <Storyboard>
                                        <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransform).(CompositeTransform.TranslateY)"
                                                                       Storyboard.TargetName="TitlePanel">
                                            <EasingDoubleKeyFrame EasingFunction="{StaticResource HubTileEaseOut}"
                                                                  KeyTime="0:0:0.0"
                                                                  Value="{Binding Size, ConverterParameter=-1, Converter={StaticResource HeightConverter}, RelativeSource={RelativeSource TemplatedParent}}" />
                                        </DoubleAnimationUsingKeyFrames>
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Visibility)"
                                                                       Storyboard.TargetName="Image">
                                            <DiscreteObjectKeyFrame KeyTime="0:0:0.185"
                                                                    Value="Visible" />
                                        </ObjectAnimationUsingKeyFrames>
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Visibility)"
                                                                       Storyboard.TargetName="BackPanel">
                                            <DiscreteObjectKeyFrame KeyTime="0:0:0.185"
                                                                    Value="Collapsed" />
                                        </ObjectAnimationUsingKeyFrames>
                                        <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="RotationX"
                                                                       Storyboard.TargetName="ViewportProjection">
                                            <EasingDoubleKeyFrame EasingFunction="{StaticResource HubTileEaseOut}"
                                                                  KeyTime="0:0:0.0"
                                                                  Value="180.0" />
                                            <EasingDoubleKeyFrame EasingFunction="{StaticResource HubTileEaseOut}"
                                                                  KeyTime="0:0:0.85"
                                                                  Value="360.0" />
                                        </DoubleAnimationUsingKeyFrames>
                                    </Storyboard>
                                </VisualTransition>
                            </VisualStateGroup.Transitions>
                            <VisualState x:Name="Expanded">
                                <Storyboard>
                                    <DoubleAnimation Duration="0"
                                                     To="{Binding Size, ConverterParameter=-1, Converter={StaticResource HeightConverter}, RelativeSource={RelativeSource TemplatedParent}}"
                                                     Storyboard.TargetProperty="(UIElement.RenderTransform).(CompositeTransform.TranslateY)"
                                                     Storyboard.TargetName="TitlePanel" />
                                    <DoubleAnimation Duration="0"
                                                     To="0.0"
                                                     Storyboard.TargetProperty="RotationX"
                                                     Storyboard.TargetName="ViewportProjection" />
                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Visibility)"
                                                                   Storyboard.TargetName="Image">
                                        <DiscreteObjectKeyFrame KeyTime="0:0:0"
                                                                Value="Visible" />
                                    </ObjectAnimationUsingKeyFrames>
                                </Storyboard>
                            </VisualState>
                            <VisualState x:Name="Semiexpanded">
                                <Storyboard>
                                    <DoubleAnimation Duration="0"
                                                     To="{Binding Size, ConverterParameter=-0.4566, Converter={StaticResource HeightConverter}, RelativeSource={RelativeSource TemplatedParent}}"
                                                     Storyboard.TargetProperty="(UIElement.RenderTransform).(CompositeTransform.TranslateY)"
                                                     Storyboard.TargetName="TitlePanel" />
                                </Storyboard>
                            </VisualState>
                            <VisualState x:Name="Collapsed" />
                            <VisualState x:Name="Flipped">
                                <Storyboard>
                                    <DoubleAnimation Duration="0"
                                                     To="{Binding Size, ConverterParameter=-1, Converter={StaticResource HeightConverter}, RelativeSource={RelativeSource TemplatedParent}}"
                                                     Storyboard.TargetProperty="(UIElement.RenderTransform).(CompositeTransform.TranslateY)"
                                                     Storyboard.TargetName="TitlePanel" />
                                    <DoubleAnimation Duration="0"
                                                     To="180.0"
                                                     Storyboard.TargetProperty="RotationX"
                                                     Storyboard.TargetName="ViewportProjection" />
                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Visibility)"
                                                                   Storyboard.TargetName="Image">
                                        <DiscreteObjectKeyFrame KeyTime="0:0:0"
                                                                Value="Collapsed" />
                                    </ObjectAnimationUsingKeyFrames>
                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Visibility)"
                                                                   Storyboard.TargetName="BackPanel">
                                        <DiscreteObjectKeyFrame KeyTime="0:0:0"
                                                                Value="Visible" />
                                    </ObjectAnimationUsingKeyFrames>
                                </Storyboard>
                            </VisualState>
                        </VisualStateGroup>
                    </VisualStateManager.VisualStateGroups>
                    <Border.Width>
                        <Binding Converter="{StaticResource WidthConverter}"
                                 Path="Size"
                                 RelativeSource="{RelativeSource TemplatedParent}" />
                    </Border.Width>
                    <StackPanel x:Name="Viewport"
                                Height="{Binding Size, Converter={StaticResource HeightConverter}, RelativeSource={RelativeSource TemplatedParent}}"
                                Width="{Binding Size, Converter={StaticResource WidthConverter}, RelativeSource={RelativeSource TemplatedParent}}">
                        <StackPanel.Projection>
                            <PlaneProjection x:Name="ViewportProjection"
                                             CenterOfRotationY="0.25" />
                        </StackPanel.Projection>
                        <Grid x:Name="TitlePanel"
                              Height="{Binding Size, ConverterParameter=2, Converter={StaticResource HeightConverter}, RelativeSource={RelativeSource TemplatedParent}}"
                              RenderTransformOrigin="0.5,0.5"
                              Width="{Binding Size, Converter={StaticResource WidthConverter}, RelativeSource={RelativeSource TemplatedParent}}">
                            <Grid.RowDefinitions>
                                <RowDefinition />
                                <RowDefinition />
                            </Grid.RowDefinitions>
                            <Grid.RenderTransform>
                                <CompositeTransform />
                            </Grid.RenderTransform>
                            <Grid x:Name="BackPanel"
                                  Background="{TemplateBinding Background}"
                                  Height="{Binding Size, Converter={StaticResource HeightConverter}, RelativeSource={RelativeSource TemplatedParent}}"
                                  Grid.Row="1"
                                  Visibility="Collapsed"
                                  Width="{Binding Size, Converter={StaticResource WidthConverter}, RelativeSource={RelativeSource TemplatedParent}}">
                                <Grid.Projection>
                                    <PlaneProjection CenterOfRotationY="0.5"
                                                     RotationX="180" />
                                </Grid.Projection>
                                <Grid.RowDefinitions>
                                    <RowDefinition Height="Auto" />
                                    <RowDefinition Height="Auto" />
                                    <RowDefinition Height="Auto" />
                                </Grid.RowDefinitions>
                                <!--Foreground="{TemplateBinding Foreground}"-->
                                <!--<TextBlock x:Name="NotificationBlock"
                                           Foreground="Gray"
                                           FontSize="{StaticResource PhoneFontSizeMediumLarge}"
                                           FontFamily="{StaticResource PhoneFontFamilyNormal}"
                                           LineStackingStrategy="BlockLineHeight"
                                           LineHeight="32"
                                           Margin="8,8,0,6"
                                           Grid.Row="0"
                                           TextWrapping="Wrap"
                                           Text="{TemplateBinding Notification}" />-->
                                <!--Foreground="{TemplateBinding Foreground}"-->
                                <!--<TextBlock x:Name="MessageBlock"
                                           Foreground="{StaticResource AppFontColor}"
                                           FontSize="{StaticResource PhoneFontSizeMediumLarge}"
                                           FontFamily="{StaticResource PhoneFontFamilyNormal}"
                                           LineStackingStrategy="BlockLineHeight"
                                           LineHeight="23.333"
                                           Margin="10,10,10,6"
                                           Grid.Row="0"
                                           TextWrapping="Wrap"
                                           Text="{TemplateBinding Message}" />-->
                                <!--Foreground="{TemplateBinding Foreground}"-->
                                <!--<TextBlock x:Name="BackTitleBlock"
                                           Foreground="Gray"
                                           FontSize="{StaticResource PhoneFontSizeMediumLarge}"
                                           FontFamily="{StaticResource PhoneFontFamilySemiBold}"
                                           Margin="10,0,0,6"
                                           Grid.Row="1"
                                           TextWrapping="Wrap"
                                           VerticalAlignment="Bottom" />-->
                            </Grid>
                            <Border x:Name="Image"
                                    Background="{TemplateBinding Background}"
                                    Grid.Row="1">
                                <Image Height="80"
                                       Width="90"
                                       Margin="0,0,0,35"
                                       Source="{TemplateBinding Source}"
                                       Stretch="Uniform"/>
                                <!--<Image Height="{Binding Size, Converter={StaticResource HeightConverter}, RelativeSource={RelativeSource TemplatedParent}}"
                                       Source="{TemplateBinding Source}"
                                       Stretch="Uniform"
                                       Width="{Binding Size, Converter={StaticResource WidthConverter}, RelativeSource={RelativeSource TemplatedParent}}" />-->
                            </Border>
                            <!--Foreground="{TemplateBinding Foreground}"-->
                            <TextBlock Foreground="Black"
                                       Grid.Row="2"
                                       FontSize="{StaticResource PhoneFontSizeNormal}"
                                       FontFamily="{StaticResource PhoneFontFamilyNormal}"
                                       LineStackingStrategy="BlockLineHeight"
                                       LineHeight="27"
                                       MaxHeight="54"
                                       TextTrimming="WordEllipsis"
                                       Margin="10,0,0,6"
                                       TextWrapping="Wrap"
                                       Text="{TemplateBinding Title}"
                                       VerticalAlignment="Bottom" />
                        </Grid>
                    </StackPanel>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>
</code>
And C# file for it is
<code>tile = new HubTile()
                {
                    Name = currentTab.TAB_ID,
                    Title = currentTab.TAB_NAME,
                    Message = currentTab.TAB_NAME,
                    Notification = currentTab.DESCRIPTION,
                    Source = new BitmapImage(new Uri(currentTab.ICON_URL, UriKind.RelativeOrAbsolute)),
                    IsFrozen = true,
                    //Foreground = tabForegroundBrush,
                    //Background = tabBackgroungBrush,
                    DataContext = currentTab,
                    Margin = new Thickness(4),
                    Style = App.Current.Resources["HomePageTabStyle"] as Style,
                    Size = TileSize.Medium
                };
</code>
Here currentTab is object of class.
Please any one do suggest a working solution for it.
Thanks.
Answer: Using Array of Colors,I achieved point one.
<code>Color[] colors=new Color{Colors.Red,Colors.Blue,Colors.White}
</code>
and in hubtile code added below line
<code>Background=new SolidColorBrush(index % colors.Length),
</code>
Thanks.
Hope it helps someone.


How to synchronize timers of two programs

Question: I am making an application where I have a client and a server. The client will send some coordinates to the server which will use those to move a robot. What I want is to synchronize the timers, used for time stamping log data, so that I can compare the input vs output. The communication is done through TCP/IP, and the client is done in C++ while the Server is in RAPID (ABB robotic programming language). My problem is that the timers are not synched properly.
Right Now the timers start when the connection between the two is established:
Server side:
    ListenForConnection;
    startTimer;
Client side:
    connectToServer;
    startTimer;
This does not work. Is there a technique to ensure that the timers are synchronized?
NB: The server can only be connected through LAN.
Comment: Can you ensure that both share the same clock (e.g. NTP)? In that case, the Server can send the absolute end-time of its timer to the client. The client can then figure out how long to start its timer.
Comment: Unfortunately the server can not connect to anything other than the client. So it can't synchronize to an online clock. It only has its internal timer.
Comment: well, you don't need to synchronize to an external clock, only that one is master and the other synchronize to it.
Answer: You need a protocol between client and server to pass the timestamp.
Right now, presumably you have a protocol for sending coordinates.   You need to extend that somehow to allow one side to send timer information to the other side.
The easiest is if you have two way communication capability.   In that case, the client does

Connect to server
Keep asking until the server is there
Server says "yes I'm here, the time is 1:00"
The client starts sending coords

If the server has no way to send to the client, then the client needs to send a timestamp from time to time, which the server recognises as being a time, not a coordinate.   The two will not be synched until this happens the first time.
Comment: Thanks, its a two way communication so that is fine. I have the feeling that the server side might be drifting a bit. Would it be smart to have them synch with regular intervals?
Comment: I should say that this is not taking into account the network transmission delay, so you will find that your client is always off by some milliseconds.


Shouldn't we just merge the chat box of travel.se and expat.se?

Question: There is a poll going on for a name for the chatbox. Wouldn't merging both chatbox, make sense since both audience share relocating?
Comment: I would disagree.  While the contingent may be similar it is not necessarily the same.
Comment: Don't forget to merge with the workplace chatroom since many will be migrating for work. And the StackOverflow chatroom since many migrating for work will be software developers ...
Answer: These are two entirely separate communities. Entering a chat room shared between two sites would be a bit disconcerting and unexpected. Users would likely find a group of users discussing things that are entirely off topic and out of context from the site they just came from. We do not support this configuration in any case.
Comment: Well it wouldn't be the first time people in travel.se would discuss programming or football
Comment: @Andra Yes, but it's two different communities indulging a bit in relaxed banter. There's also nothing stopping folks from participating in both rooms, often simultaneously, and chat messages from one room magically 'one box' if quoted in another. It's _integrated_, but should be kept separate.
Comment: There's absolutely nothing stopping anyone from establishing a brand new room that has the declared purpose of hosting both travel and expats SE contributors and conversations.
Comment: That's simply inaccurate. For example, 6 of the top 10 expats users are also among the top users on travel. And avoiding off-topic discussion is not a serious argument: the travel chat is full of unrelated chitchat and far from overloaded, the expats chat is mostly dead and when a serious issue arises, it's often about what should go where and it's just as likely to be discussed on the travel chat. Maybe you *wish* them to be separate communities and that's good reason to keep the chat rooms separate but that's not the case at the moment, as a matter of fact.
Answer: Please no!  One of the main reasons Expat got a push was to separate the two distinct audiences.  We'll get overlap, for sure as many users who travel are expats too, but many of them are programmers too, and we're certainly not combining that with stackoverflow's chats.
Comment: +1 And for the overlap, there's nothing wrong with chatting in two rooms, I do it quite a lot.
Answer: Please visit the brand new chat room I just built:

Travelling, Expatriating, and Immigrating

Now we have a place to mingle.
And places to call home.


Calling Golang from HTML

Question: I'm helping with an open source project.  It's a small Go webserver running on a device containing a Raspberry Pi.  I want to be able to have a user click a button on an html screen, which calls a routine in Go, which returns 2 values, a boolean and a string.
What we are wanting to do is see which network interfaces are up on the raspberry pi e.g. is the lan connection up?
To do this I really need to ping a site from each interface.  This takes a few seconds for each of 3 interfaces: Lan, WiFi, and 3G.
I can do this when the page is requested and fill in an html template as the page loads, but it means waiting maybe 10 to 15 secs for the page to load, so it seems like something is broken.
So I want to be able to list each of the 3 interfaces on the page and have the user click 'test' which then calls a routine in the underlying Go webserver.
I then need to be able to display the results from the call in a couple of text areas for each interface.
What I have tried:
I have tried registering a Go function (in this case IsLANConnectionUp) using funcmap from the net/html package and calling it from the html template from a JavaScript function, like this:

  <button onclick = "getLANStatus()" class="btn btn-primary">Test</button>

But having the template code inside the javascript code doesn't seem to work.  Also, I'd like the text output from the ping command (which my Go function getLANStatus and I don't know how to extract that data from the function call.  The documentation says only one value can be returned.
Searching on StackOverflow I see this: calling Golang functions from within javascript code

$.ajax({
  url: "http://www.example.com/signup",
  data: {username: "whatever"} //If the request needs any data
}).done(function (data) {
  // Do whatever with returned data
});

But it says things like "// Do whatever with the returned data"  I'm new to web programming and so don't know how to use that code.  If this is the way to go, could someone please expand on this a little?
Any help would be much appreciated.
Comment: You're supposed to change the HTML on the page based on `data`. For instance like this: `if (data.lanup) document.getElementById("lanstate").style.color = "green";` The exact code depends on the format of the server's reply, and how you're displaying the state of each interface.
Comment: Hi, I understand about finding something in the DOM and changing it - once I can extract the data.  Not sure what form the data will come back to me in?  But firstly, how to make that call to ajax please?  Do I put that code in the javascript function called from the button's onclick event?
Comment: Yes, exactly. Ideally, the GO server sends back JSON. Something like `{ "lanup": true, "wifiup": true, "threegup": true }`. As for `$.ajax`, that's [jQuery](http://jquery.com/). It also has a simpler way: `$.getJSON`, but you can also use the native `fetch()`, that way you don't have to include jQuery in your project.
Comment: you can simply use Ajax to do the same with ease.
Comment: Why not run all tests at the same time, then you only wait 3 seconds, instead of 10-15.
Comment: @Flimzy, yes I had thought of this. But the project leader has asked for them to be able to be tested separately.
Comment: @ASHWINRAJEEV Yessssss, this is what I'm asking how to do!  Can you give me an answer showing how to do this?
Comment: @davo36: Of course, they should be testable separately. But you can still run them simultaneously. These are not the least bit mutually exclusive.
Comment: @Flimzy Yes, I see what you mean.
Answer: So couple different concepts here.
Render: On the initial request to your html that generates the Test button.  Your go server will render that html 1 time and return it to your browser.  It does not re-request dynamically unless you wire some stuff up to make the web page change.
Client: So when someone clicks your button, the function getLANStatus will be ran.  You will want that function to do a few things

Through ajax, communicate with your go server through an api that will return the status of your connections as a json object. Something like
{
  "3g": "up",
  "lan": "down",
  "wifi": "up"
}
Second, in the done part of your ajax, you will manipulate something in the DOM in order to convey that the status of the interfaces is what it is.  You could do that by finding the element, then changing the text to what is returned by the object.

As a simple first step, you can alert the payload in the function that would look like this
$.ajax({
  url: "http://YOUR_GO_SERVER_IP_OR_DNS:PORT/interfaces_status.json"
}).done(function (data) {
  alert(data);
  console.log(data);
  debugger;
});

Then if you request that with the console open in chrome, you will be able to directly play with the returned data so that you know what all it reponds to.
Comment: Hi, OK, can I ask why the url is a json file?  I'd need to have my Go function fill in that json file right? But how does that happen? I also don't really understand how to make that ajax call.  Is it in the javascript function called by the button's onclick event?
Comment: Actually I just re-read your answer, I understand a bit more.  With the lanStatus function, can I just pop that $.ajax bit into it somewhere?
Comment: You need to have your goserver serve an http api.  Javascript (ajax) is going to communicate with that http api.
Comment: https://www.reddit.com/r/golang/comments/2tmllh/sending_an_ajax_request_to_go_web_server/ good bones to get you started

Calling Golang from HTML


Strange cv2 behavior with imshow

Question: I'm using Python 3.8.2 on Kubuntu 20.04.
cv2 is the latest available version, as are NumPy and pip:
Requirement already up-to-date: pip in /usr/local/lib/python3.8/dist-packages (20.1.1)
Requirement already up-to-date: opencv-contrib-python in /usr/local/lib/python3.8/dist-packages (220.127.116.11)
Requirement already satisfied, skipping upgrade: numpy>=1.17.3 in /usr/local/lib/python3.8/dist-packages (from opencv-contrib-python) (1.19.1)
Requirement already up-to-date: numpy in /usr/local/lib/python3.8/dist-packages (1.19.1)

Here is my code:
import numpy as np
import cv2

black_image = np.zeros((480, 640, 3))
cv2.imshow("Test", black_image)
cv2.waitKey()

white_image = np.ones((480, 640, 3))
cv2.imshow("Test", white_image)
cv2.waitKey()

This simple test program, when run in IDLE, sometimes displays a small black image (95x25) instead of the 640x480 black image I passed to imshow. Other times, it will display the proper image. In either case, when this window is closed, OpenCV blocks forever instead of displaying the second image and I have to close the process via the IDLE shell window.
When run in the terminal, the results are the same: sometimes a weird small image of size 95x25, and OpenCV blocks before opening the second window resulting in me having to kill the process (Ctrl+C does nothing, and sending SIGTERM doesn't work either).
I have tried:
Passing 0 to cv2.imshow(). Same results.
Passing 1 to cv2.imshow(). This actually displays the white image as intended, but the black image (or its weird 95x25 substitute) is also displayed. As I understand it, cv2.imshow() is supposed to replace the contents of the already opened window if one exists with the same name.
I remember OpenCV working fine with Python 3.7 and below, although I can't test with that as those versions are no longer installable on my version of Ubuntu.
Both results are reproducible on my machine, but no code change is necessary to switch between them. What's going on here, and how do I fix it?
EDIT: Also tried closing windows (by name and through cv2.destroyAllWindows()) and waiting for specific key presses. The main problem persists: images are not being displayed consistently and OpenCV will sometimes hang forever. Normal programs and other code I've pasted do not work properly.
EDIT 2: Now attached are screenshots of my problem
The first weird window:

IDLE hanging with no OpenCV window open after closing the first one:

Konsole (my terminal emulator) also hanging after closing the first window:

Ctrl-C not working to end Python in the terminal:

I can also provide video proof if needed.
Comment: When working with cv2, don't forget to write at the end: cv2.destroyAllWindows().
Comment: Thanks for the tip, although it doesn't seem like I had to use that before Python 3.8.
Comment: When closing the window/imshow through a key (q or esc), you don't face the problem, right?
Comment: The program execution never gets there. cv2 blocks somewhere during waitKey.
Comment: What about the solution I provided in the answer?
Answer: I think you are facing two problems:

the code sometimes displays the black image in a wrong size.
When it does, the run stucks here.

The problem of 2 is that cv2.imshow accepts (by default) key events of closing the window (i.e. closing the window via x sign will lead to being stuck in the wait step forever).
As a solution for this, you can add an if statement to close the window if a key is pressed and to tell the program explicitly that if the x sign/button is pressed to close the window. Thus, you can write something like the following:
import numpy as np
import cv2

black_image = np.zeros((480, 640, 3))
white_image = np.ones((480, 640, 3))

images = [black_image, white_image]

for image in images:
    while True:
        cv2.imshow('Frame', image)
        if cv2.waitKey(1) & 0xFF == 27 or cv2.getWindowProperty("Frame", 0) == -1: # "0xFF == 27" for Esc-key in Windows
            break
cv2.destroyAllWindows()

Answer: After an updated version of Python (3.8.5 specifically) was released, I updated Python, pip, and PyOpenCV. Everything works as intended now, confirming my suspicions that this was an obscure bug not directly caused by my code.
Updated packages:
Requirement already satisfied: pip in ./.local/lib/python3.8/site-packages (20.3.3)
Requirement already satisfied: opencv-contrib-python in /usr/local/lib/python3.8/dist-packages (126.96.36.199)
Requirement already satisfied: numpy>=1.17.3 in /usr/local/lib/python3.8/dist-packages (from opencv-contrib-python) (1.19.1)

Maybe this can help someone with outdated packages experiencing the same issues in the future.
Answer: You can either use cv2.destroyWindow("Test") or cv2.destroyAllWindows() to properly close windows.
Comment: The window closing is not my problem, although I'll remember to do that next time I have it working. OpenCV is not behaving as it should according to the documentation. It blocks indefinitely without opening windows and displays the wrong image at times.

Strange cv2 behavior with imshow


Como faço para pegar a localização no google maps api de acordo com o clique do usuário?

Question: Eu entrei no site do google maps api e vi como colocar e utilizar a api no meu site, porém só consegui fazer com que cadastre um local de acordo com o que o usuário digita. Para uma melhor experiência, eu queria que quando o usuário clicasse em algum ponto do mapa, aquela latitude e longitude fossem salvas no banco de dados. Alguém tem ideia de como posso fazer isso?
Obs: Não é a localização que o usuário está, mas sim a que ele clicar.
Answer: <code><script>

    function initialize() {
       var latlng = new google.maps.LatLng(-19.949132746636568, -44.194307630538844);
        var map = new google.maps.Map(document.getElementById('map'), {
          center: latlng,
          zoom: 16,
          mapTypeId: google.maps.MapTypeId.ROADMAP
        });
        var marker = new google.maps.Marker({
          map: map,
          position: latlng,
          draggable: true,
          anchorPoint: new google.maps.Point(0, -29)
       });
        var input = document.getElementById('searchInput');
        map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
        var geocoder = new google.maps.Geocoder();
        var autocomplete = new google.maps.places.Autocomplete(input);
        autocomplete.bindTo('bounds', map);
        var infowindow = new google.maps.InfoWindow();
        autocomplete.addListener('place_changed', function() {
            infowindow.close();
            marker.setVisible(false);
            var place = autocomplete.getPlace();
            if (!place.geometry) {
                window.alert("O local retornado pelo preenchimento automático não contém geometria!");
                return;
            }

            if (place.geometry.viewport) {
                map.fitBounds(place.geometry.viewport);
            } else {
                map.setCenter(place.geometry.location);
                map.setZoom(17);
            }

            marker.setPosition(place.geometry.location);
            marker.setVisible(true);

            bindDataToForm(place.formatted_address,place.geometry.location.lat(),place.geometry.location.lng());
            infowindow.setContent(place.formatted_address);
            infowindow.open(map, marker);

        });
          google.maps.event.addListener(marker, 'dragend', function() {
            geocoder.geocode({'latLng': marker.getPosition()}, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
              if (results[0]) {
                  bindDataToForm(results[0].formatted_address,marker.getPosition().lat(),marker.getPosition().lng());
                  infowindow.setContent(results[0].formatted_address);
                  infowindow.open(map, marker);
              }
            }
            });
        });
    }
    function bindDataToForm(address,lat,lng){
       document.getElementById('location').value = address;
       document.getElementById('lat').value = lat;
       document.getElementById('lng').value = lng;
    }
    google.maps.event.addDomListener(window, 'load', initialize);
    </script>
</code>
Comment: Pode explicar o que está sendo feito no código, ou inserir comentários nas linhas mais relevantes?


$x \propto y^2$ Vs $x \propto y$

Question: $$x \propto y^2$$
How is it different from saying:
$$x \propto y$$
That is; when we say that Two variables are proportional then it means that two variables are related such that when one is zero other is too. And change in one variable is accompanied by change in other. This is a general definition for proportionality. Then if we write $x \propto y^2$, by definition, we implicitly mean that $x \propto y$. So, why write $x \propto y^2$ instead of a simple one $x \propto y$?
Is it due to the calculation of constant of variation? Viz., the constant of proportionality onliy lies between $x$ and $y^2$ relation and not between $x$ and $y$ relation? Is it for that purpose that we specify them?
Comment: But that's not what $\propto$ means; it's only part of it. We know $A=\pi r^2$. That is, $A$ is a constant multiple of $r^2$. That's what $A\propto r^2$ means. $A$ is not a constant multiple of $r$, so we can't say $A\propto r$.
Comment: $A\propto r^2$ means that, if $A$ doubles, then $r^2$ doubles. This is true. $A\propto r$ would mean that if $A$ doubles, $r$ doubles. This is not true.
Comment: Actually, the proportional symbol means more than if one grows, so does the other. It also says that the growth is linear, i.e. by a constant, which is stronger.
Comment: Proportionality means that when I double one side, the other side also doubles. So $x \propto y$ is not the same as $x\propto y^2$: if I double $y$, in the first $x$ doubles, while in the second it becomes $4$ times as large.
Comment: I am not asking that whether $x \propto y$ is same as $x \propto y^2$. I know that it is not and it is explicit. In a very general way, we say that if $x$ increases, $y$ increases too then it means $x \propto y$ mathematically. In $x \propto  y^2$ we mean same that is; as $x$ increases $y$ increase too. So Why to specify $x \propto y^2$ and $x \propto y$?
Comment: For example: If $A$ is the area of a circle and $r$ is the radius, then $A\propto r^2$ as the size of the circle varies. However, $A\not\propto r$. (That symbol means "is not proportional to")
Comment: @AkivaWeinberger can you please explain rigorously why is it wrong to say $A \propto r$? Area increases as radius. When radius vanishes, circle vanishes and so Area of the circle.
Answer: If $x$ is proportional to $y^2$, then when $y$ doubles, $x$ is four times as much.
If $x$ is just proportional to $y$, then $x$ doubles when $y$ doubles.
For example, the position of a ball falling towards the ground is proportional to $t^2$ ($t$ is time). So if the length of time doubles, the ball has fallen four times as far. This is very different from the ball's velocity, which is proportional to $t$. If the amount of time doubles, the final velocity of the ball also doubles.
EDIT: It may be tempting to think this way: $x\propto y$ means that there is some constant such that $x=cy$. But if $x=y^2$, then $x=y\cdot y$, so we could just write $x$ is proportional to $y$ since $x$ is something times $y$. This is not correct. We only call things proportional when one relates to the other via a constant.
Comment: $x\propto y$ if and only if $x=cy$ for some $c\neq0\in\Bbb{R}$
Comment: @SufyanNaeem yes, and $A\propto r^2\implies A=kr^2$
Comment: @Sir. How the definition of proportionality given at Wikipedia covers all the aspects, you are talking about? Definition says, "Two variables are proportional if a change in one is always accompanied by a change in the other, and if the changes are always related by use of a constant multiplier."
Comment: What is your question?
Comment: Suppose putting radius $x$, we get area of the circle $y$ then increasing radius 2 times viz, $2x$; must give us area of the circle 2 times as previous i.e $2y$. Isn't so?
Comment: No, every time the radius doubles, the area gets four times larger. Thus, $area\propto x^2$
Comment: To put matters straight. think of an arbitrary relation between two variables. Assume it is reported that by increasing one of them to $x$, other reaches $y$ then I have no need to resume and see the relation because I can imagine that if something is $y$ due to $x$ of other thing then must increasing $x$ of other thing 2 times increase something 2 times i.e. it must vary to $2y$.
Comment: This is not true. Consider $x$ is a side of a square with area $y$. If $x=1$, then increasing $x$ by $1$ increases $y$ by $3$. Increasing $x$ by $2$ increases $y$ by $8$. You can't think of "increasing by." You have to think of multiplying by.
Comment: Now, I can ask you that how the definition I stated above is covering all you arguments? Especially, this one just above.
Comment: That's what I'm trying to say: you do not have the correct definition of proportionality. "x is proportional to y" *means* that $x=cy$ for some non-zero constant $c$.
Comment: And, increasing two times and multiplying by 2 is same. You said, "you can't think of 'increasing by'. You have to think of 'multiplying by'." Explain this as well.
Comment: I'm not sure. I think we may be on the same page using different words.
Comment: As you said $x \propto y$ is only valid if $x=cy$. Then taking $A \propto r^2$ instead of $A \propto r$ must have just one and only one reason that  is: there must be no constant between $A$ and $r$ i.e. $\frac {A}{r} \neq k$. Isn't so? Now I think I am just one step away. If you just answer me to this question, I 'll be there.
Comment: OMG! The same thing I wrote in my original post earlier and you said "it may be tempting...". Well, Better late than Never. :)
Comment: You could have read the full paragraph and avoided this conversation :)
Answer: The proportionality symbol carries the implication that if
$x \propto y \implies x=ky$ for some nonzero real k.
That being said, it's clear that $ x \propto y \ne x \propto y^2 $ since $ ky \ne ky^2 $
Answer: While dealing with Functions we can do that.
For example. Whether $f(x)=x$, $f(x)=x^2$ or $f(x)=x^3$ we can say that $f(x)=y$ , in general.
While dealing with "$\propto$", don't forget the implication.
For example. $x \propto y \implies x=ky, k \neq 0$
I am pretty sure that you are thinking like we think while dealing with functions. $k$ is not a function there but a simple multiple. We can easily relate (with "equals to" sign) any two quantities in mathematics with prefixing just a $f$ (or any symbol denoting function). But we can not express two quantities in equation arbitrarily with placing a constant. So , we have to describe enough when we place a constant in contrast to the situation, when we place $f$ symbol. So, it is obligatory there to write $y^2$ in stead of $y$.

$x \propto y^2$ Vs $x \propto y$


Resultado de PHP dentro de um modal com CSS

Question: Olá, eu estou tentando colocar o resultado de um quiz feito apenas com PHP e um pouco de JS(usado somente para esconder a pergunta anterior e mostrar a proxima) dentro de um modal, feito apenas com HTML e CSS, pois estou construindo um site no qual tenho somente HTML, PHP e CSS disponiveis.
Aqui está o que tenho até o momento:

$totalcerto = 0;

if ($resposta1 == "B") { $totalcerto++; }
if ($resposta2 == "D") { $totalcerto++; }
if ($resposta3 == "A") { $totalcerto++; }
if ($resposta4 == "B") { $totalcerto++; }
if ($resposta5 == "A") { $totalcerto++; }

echo "$totalcerto / 5 respostas corretas";

?>
este é meu PHP, gostaria que essa variável $totalcerto aparecesse dentro de um modal, obrigado pela atenção.
Comment: Use o Bootstrap: http://getbootstrap.com/javascript/#modals
Comment: Você já conseguiu fazer o modal aparecer?
Answer: Primeiro crie seu modal com HTML e CSS, e deixe-o oculto, suponho que você já saiba fazer isso, caso não saiba é só perguntar que posto o código.
Depois de ter criado sua variável php $totalcerto como fez acima, coloque o seguinte JS:
document.getElementById('modal').innerHTML = "<?PHP echo $totalcerto; ?>";

Importante
Esse JS precisa estar no final do body ou no evento onload, caso contrário a div com a id modal ainda não existirá, portanto será retornado undefined. Aí é só criar uma função pra mostrar o modal quando o usuário terminar o quiz.
Answer: A pergunta é meio antiga, mas vamos lá.
Primeiro, aconselho o uso do bootstrap, o que já vai facilitar bastante seu trabalho. Após colocar os arquivos na pasta e criar as referências deles no seu arquivo crie um modal(pode ser no final da página) com a seguinte estrutura:

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Modal title

One fine body…

        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>

Na estrutura html acima, coloque seu contéudo php (no caso $totalcerto) dentro da tag div com class = 'modal-body', use o php do jeito normal, como você usaria numa página html qualquer.
Para chamar o modal, bastar criar dentro da tag  esse script:

Só uma observação, o seu código php parece não estar eficiente, porque
  se você tiver umas 10 perguntas, você teria que repetir esse código 10
  vezes para que sua variável $totalcerto pudesse somar a quantidade de
  acertos


Can I simulate a storage device in a VM to test OS image driver compatability?

Question: Greetings,
I'm trying to automate the testing of driver support in a library of OS images used for automated deployment in a data center environment.
In most cases, I see people standardize on a few OSs and a few server hardware models, which makes testing and validating that all the OS images contain drivers that are supported on all the hardware fairly manageable.
Unfortunately, I can't do that. I have several dozen OSs (Linux/Windows/Solaris, x86/x64/SPARC, versions going back 3 years) that really should be tested against representative server hardware from Dell, HP, IBM and Sun going back 3 years. That's a lot of work and a lot of physical systems.
What I'd rather do is pick up the PCI device info of the various storage controllers (and maybe NICs) and use something to simulate the devices in a VM. I could then apply/install the OS images to the VMs and see if the kernel code which matches up detected PCI devices with available drivers runs into a problem or not. There would have to be some simulation of actual device functions, since the OS would start trying to use the device after the driver loaded, but it seems like people doing driver or hardware development might have a similar need for such a tool.
Does anyone know if such a thing exists? Or is there a completely different workaround that would address my problem?
Thanks!
Answer: To simulate the various PCI devices you're talking about you'd have to have someone write virtual versions of those PCI devices.
Since there's no "standard" for writing a virtual hardware device (though, as I think about it, it would sure be cool if there was) that would work with different hypervisors I'm not sure how you'd go about that. (Heck, I'm not even sure if you can add virtual device modules to any of the major hypervisors.)
The effort to simulate a complex device, like a RAID controller, would be pretty major. It'd basically be a re-implementation of the hardware and software of the physical device in software. (It would be a neat thing, though, to have a clean-room implementation of a hardware device in software for validation testing of drivers in a virtual environment... Hmmm. Somebody has to have done this for some device in production at some point...)
It's a neat idea, but I don't think anything exists to do what you want, and if it did, it would be on a device-for-device basis.
Comment: Okay-- so does anybody here know: Is there any API for any of the mainstream hypervisors to create virtual hardware devices? I've done a little searching but I must not be using the right words. Even just exposing a range of PCI control registers or memory locations directly to the guest OS would be fairly cool.