Oracle SQL - using SYSDATE to display

Question: Here is the table:
Col1    Col2    Col3
---------------------------------------
4567    102     5/5/2011 3:37:41 PM
9876    102     5/5/2011 3:37:43 PM
1234    104     5/5/2011 12:46:16 PM
9999    104     5/5/2011 12:47:09 PM
9999    104     5/5/2011 12:47:15 PM

How can I use the SYSDATE to fetch only one or more record(s) using rapid display on a report via seconds 'SS' and/or minutes 'MI'? I know about BETWEEN fxn, but dealing with seconds, it's kind of slippery slope to me. Any ideas?
Comment: what do you mean with "rapid display"
Comment: The format string `FF` means fractions of a second, but I am pretty sure that it is only valid with the `timestamp` datatype.
Comment: Nothing really, just fast to be displayed on the report, since seconds count.
Answer: Not quite sure what you mean, but if you want to restrict returned records to a few minutes or seconds old, and assuming COL3 is indexed, you can do something like this:
SELECT COL1, COL2, COL3
FROM MY_TABLE
WHERE COL3 > SYSDATE - INTERVAL '3' MINUTE
ORDER BY COL3 DESC;

INTERVAL can be in seconds if you prefer; or both, e.g. INTERVAL '01:30' MINUTE TO SECOND would go back 90 seconds, as would INTERVAL '90' SECOND. (Also not sure if this needs to be supplied by the user as a parameter).

Still unclear what you are trying to achieve and what criteria you want to use for restricting the returned rows. But if you do want the most recent record and any that fall within a specific period of it, you can do something like this:
SELECT COL1, COL2, COL3 FROM (
    SELECT COL1, COL2, COL3,
        NUMTODSINTERVAL(
            FIRST_VALUE(COL3) OVER (ORDER BY COL3 DESC) - COL3,'DAY') AS DIFF
    FROM MY_TABLE
)
WHERE DIFF < INTERVAL '01:30' MINUTE TO SECOND
ORDER BY COL3 DESC;

This would return the most recent record, plus any with COL3 within 90 seconds of it. So there will always be at least one record returned. But it isn't filtering COL3, it has to evaluate every row to work out the offset, so it'll probably do a full table or index scan. You may be able to filter the innner select anyway, if you only ever want records from today, for example. If not it might not meet your 'rapid' requirement.
A potentially faster, but perhaps uglier, solution might be:
SELECT COL1, COL2, COL3
FROM MY_TABLE
WHERE COL3 > (SELECT MAX(COL3) FROM MY_TABLE) - INTERVAL '01:30' MINUTE TO SECOND
ORDER BY COL3 DESC;

Really not sure this is what you want, or how SYSDATE fits in.
Comment: It looks OK. However, I need the first two rows displayed solely on col3, while the rest ones are not important. Those two rows have been populated roughly the same time '3:37:41 PM' and '3:37:43 PM'. So, is it possible to have those two records to appear on the report?
Comment: Sorry valmont74, I don't understand what you mean. How are you deciding that you want the first two rows? The number of rows; or the most recent row and any within a few minutes of that; or something else?
Comment: @valmont74: I've added a couple more options based on what I think you *might* mean, but I'm really not sure what you're trying to achieve, I'm afraid.
Comment: The first query provided is helpful in my situation.
Answer: You can calculate with SYSDATE. Minus 1 is yesterday. Minus 1/24 is one hour ago. Minus 1/(24*60) is one minute ago. And minus 1/(24*60*60) is one second ago.
This query should show you all records with a date in the last 10 seconds:
select *
from my_table
where col3 > sysdate - 10/(24*60*60);

Is that what you're after?
Comment: Interval is a far better method than this
Comment: Is that just for readability or are there other benefits to using INTERVAL?
Comment: PERFECT...You nail did. This is what I was looking for. In other words, once the report is run and the output is appeared ONCE (like 5-10 sec), the next time to run the report, will only show the output without the last records with a date in the last 5-10 seconds. And I hoped you understood my train of thought. Again, thanks a lot for your help.

Oracle SQL - using SYSDATE to display


How to test RJ45 ethernet cable failing to connect?

Question: My home network setup is that I have a simple network switch fed by a cable modem in my utility/data room and then 6 RJ45 cables going out of it to different rooms of the house. I like to have wired network connection in every room. 5 out of 6 cables are accounted for positively and correspond to the other remote ends but one does not connect, which means when I mount female jacks on both ends I don't get connection.
Since the ordinary connectivity using regular connectors is failing, I would like to test each of the 8 constituent wires for continuity. My fears are that, since the cable runs through the attic, a rodent ate it or that the guy who installed the AC duct work may have accidentally cut it.
These wires are super skinny, I believe gauge 28 or thinner. Can I run some current using a AAA battery on one end on each wire and test it with a multimeter on the other?
P.S.: I didn't test this immediately after running the cable, which is really my bad and could have prevented it.
Comment: `RJ45 ethernet cable` ... that's not really a thing ... RJ45 is a connector that is used on ethernet cables ... the cable is usually UTP (unshielded twisted pair) ... the cable is also referred to by `category`, such as CAT 5 cable
Comment: start by twisting the 8 conductors together at one end ... measure resistance between the 8 conductors at the other end ... that will detect any opens ... disconnect all conductors and measure again ... that will detect shorts
Answer: 10 MB or 100MB ethernet only require 4 conductors (wires).  Cat 5 & 6 have 8 conductors, 1GB ethernet does require all 8 conductors.
Next:  Although others have said differently, a cable tester is very handy and a huge time saver.  Since product recommendations are off topic I won't make a recommendation, but just let me say I have some and they've been invaluable in trouble shooting, esp. when I help friends.
The prices for them vary WIDELY...from $10 on Amazon for really simple ones to over $1,000 for very sophisticated ones.  I'd stay away from the $10 cheap ones, but you should be able to find one for about $40 or so that would more than meet your needs.   My recommendation is to get the kind that have 2 parts:  one that you plug into one end of the ethernet cable and another unit that actually does the testing that you plug into the other end of the cable. It'll tell you exactly what's wrong.
Trust me, they are worth it.
Answer: 28 Ga would be unusual. 24 is more typical...Unless you are inappropriately using patch cables as in-wall cables, rather than proper solid wire cable intended and marked for in-wall use.
Anyway, trivial to test - just connect a battery (I tend to use a 9V, but whatever you like) to two of the wires on one end (with the other end not connected to anything) and look for voltage on the other end between those two wires. No need to buy a network cable tester which someone will be along to suggest in a moment if you're just checking continuity and have a multimeter.
You can also short each pair at one end and check resistance from the other.
Likewise, you can make sure each pair is open (not shorted) and verify no continuity (infinite ohms) between all wires.
There are more subtle issues that a fancier network tester might be useful for, but worry about those after you do the basic tests, and really, running the cable anew will cost less than buying a fancy tester for "one cable in your house" (since the tester might well just show a problem that you'd still have to correct by running a new cable.) A cheap tester is no better than using a multimeter (other than speed) and can be worse (the indications of what's wrong can be unclear .vs. what you can see with an actual meter.)
Answer: I think testing individual conductors for continuity is not a good use of time.  If it doesn't work it doesn't work.  Maye it's the ends so cut both ends back an inch if you can and replace the connectors.  If it still doesn't work, abandon it. Run a new one.
Continuity doesn't mean it's good anyway.  With ethernet the shielding and connectors all have to be intact and to spec.  You can't test that with an ohmmeter.  There are tools to test it with but you already know it doesn't work so just run a new one.
Comment: @jay613 i am almost religiously devoted to having wired internet in every room
Comment: Drywall is hung, but is the existing cable stapled down?  Could you possibly use it to pull a new cable?
Comment: You most certainly can. Drywall repair may be required, of course. Or you get your network to that room some other way.
Comment: When we built our house, our contractor said not to bother with cat-5 or cat-6 cabling bc everything was going wireless.   I over-rode him on that and put POTS lines, Cable and Cat-5 to most rooms, really glad I did. It was a high quality WIFI router and not very far from the ROKO box.  Can't beat  hard wired both for performance and security.
Comment: I cannot run a new one because the drywall has been hung
Comment: Ok but if continuity is bad what are you going to do?   And if it's good what are you going to do?
Comment: not have a network connection in that room
Comment: Straying from the question, but you could question your need for wired ethernet everywhere.  You could extend to the room with a pair of mesh routers. You could extend to the room from the adjacent room with a switch there and a cable poked through the wall.
Comment: Biting the bait then :)  Install redundant cabling, patch bays, and pullways (assorted conduit and recessed raceways) at strategic locations throughout the house.  The cable gods demand it.
Comment: @amphibient You will have to admit to yourself that the cable to that room is broken. It cannot be repaired. If just one conductor is broken, the whole cable is broken. So, you have to work out how to get a new cable to the desired location - perhaps in tubular conduit so it is better protected, and also run two cables so that if one breaks or you need another one, it is there already.
Comment: @AndrewMorton -- I agree but i want to check every single wire
Comment: get yourself a tester, like I said in my answer, they are well worth it... cut your self  a break and buy one!  Since this is a comment, I'm going say a bad dad joke:   What is Ethernet really used for???   To catch the Ether Bunny.!   Sorry but had to pass this on!
Comment: Chiming on wired vs WIFI:   My wife wanted a ROKU streaming device and insisted on setting it herself.  Well, she went WIFI and the performance was awful, terrible, slow response times, pauses in the stream.  So after I let her struggle with it for a bit (does that make me an AH?)   I said:  " there's  a hard wired  cat-5 connection to the cable modem just behind the TV, why don't we try that?"  So I simply connected the ROKO box to the jack and it started working perfectly.  ...continued below....
Comment: I have a bunch of rokus all on wifi all work great all the time.


Covert Ruby hash to array of hash

Question: Convert Ruby Hash to following hash format which uses in parse.com:
[{
    "__type": "Pointer",
    "className": "Tag",
    "objectId": "DLAPiFlMYL"
}, {
    "__type": "Pointer",
    "className": "Tag",
    "objectId": "trIItAa4bJ"
}]

Input:
{: __type = > "Pointer",
    : className = > "Tag",
    : objectId = > "DLAPiFlMYL"
}

Output:
[{
    "__type": "Pointer",
    "className": "Tag",
    "objectId": "DLAPiFlMYL"
}]

Comment: Where is the code you wrote to try to solve this?
Comment: to_json gives "{\"__type\":\"Pointer\",\"className\":\"Tag\",\"objectId\":\"DLAPiFlMYL\"}" , But need [{"__type":"Pointer","className":"Tag","objectId":"DLAPiFlMYL"}]
Answer: Just use to_json method provided by rails
{:__type=>"Pointer",:className=>"Tag",:objectId=>"DLAPiFlMYL"}.to_json

Comment: it creates "{\"__type\":\"Pointer\",\"className\":\"Tag\",\"objectId\":\"DLAPiFlMYL\"}" But need [{"__type":"Pointer","className":"Tag","objectId":"DLAPiFlMYL"}]
Comment: You need a `JSON` response or a simple `Hash` in a array?
Answer: You can use HashWithIndifferentAccess.
require 'active_support/hash_with_indifferent_access'
my_hash = {:__type=>"Pointer",:className=>"Tag",:objectId=>"DLAPiFlMYL"}
my_hash = HashWithIndifferentAccess.new my_hash
=> {"__type"=>"Pointer", "className"=>"Tag", "objectId"=>"DLAPiFlMYL"}
> my_hash['className']
=> "Tag"
> my_hash[:className]
=> "Tag"

Covert Ruby hash to array of hash


Access a C++ struct in C#

Question: I am having a VC++ stucture like
struct VideoInputV20 {
   int m_nBrightness;
   int m_nSharpness;
   int m_nSaturation;
   int m_nContrast;
   int m_nInputState;
   CString m_sObjref;
};

Here in C# I'll receive this stucture in byte[]. Here I need to convert byte[] to stuct.
How can I achive this? Please provide sample code, if possible.
Comment: I have no idea what you are asking... can you rephrase this?
Answer: Declare your struct in C#:
[StructLayout(LayoutKind.Sequential, Pack = 2, CharSet = CharSet.Ansi)]
struct VideoInputV20
{
    int m_nBrightness;
    int m_nSharpness;
    int m_nSaturation;
    int m_nContrast;
    int m_nInputState;
    [MarshalAs(UnmanagedType.LPWStr)]
    string m_sObjref;
}

Then the code to get it out of a byte[]
GCHandle handle = new GCHandle();
try
{
    // Pin the byte[]
    handle = GCHandle.Alloc(yourByteArray, GCHandleType.Pinned);
    IntPtr ptr = handle.AddrOfPinnedObject();

    // Marshal byte[] into struct instance
    VideoInputV20 myVideoInputV20 = (VideoInputV20 )Marshal.PtrToStructure(ptr, typeof(VideoInputV20 ));
}
// Clean up memory
finally
{
    if (handle.IsAllocated) handle.Free();
}

Comment: what is GCHandle how i declare in .net2003
Comment: You need to add the System.Runtime.InteropServices namespace, it should then be available. It is part of the .NET framework 1.1
Answer: Badly. Ints are relatively easy to recover, but that CString's object serialization is platform and compiler dependent. Try converting this in C++ to some other representation.
Answer:
byte[] data = GetData();
int structSize = Marshal.SizeOf(VideoInputV20);

if(structSize <= data.Length)
{
   IntPtr buffer = Marshal.AllocHGlobal(structSize);
   Marshal.Copy(data, 0, buffer, structSize);
   VideoInputV20 vi = (VideoInputV20)Marshal.PtrToStructure(buffer, VideoInputV20);
   Marshal.FreeHGlobal( buffer );
}

Access a C++ struct in C#


How to fix 'Cannot read property 'document' of null' when trying to access window.opener.document

Question: I'm trying to access elements in the window that opened the popup however, as the title says, I'm getting 'Cannot read property 'document' of null' when trying to access them.
I've seen a few other posts on this subject however unfortunately none of them helped in this case.
I've tried
    openerWindow = window.opener.document;
       selectedTableRow = openerWindow.querySelectorAll(".highlighted-rows");
As well as
    selectedTableRow = window.parent.document.querySelectorAll(".highlighted-rows");
The above does run, however it brings back an empty array, even though I know that there are table rows with the class .highlighted-rows
And
    selectedTableRow = window.opener.document.querySelectorAll(".highlighted-rows");
The interesting thing is, when I try running selectedTableRow = window.opener.document.querySelectorAll(".highlighted-rows"); through the Chrome console, it actually works and returns the row I was expecting, it's just running it through the code that fails.
Comment: The error means that `window.opener` is `null`.
Comment: One does not have access cross-window like that. You'll need to use the cross-window messaging API to assist you.
Comment: @Pointy Thanks for the quick reply. I'm aware that's what the error means, sorry I should have made this more clear.
I'm wondering why I'm able to run ```window.opener.document.querySelectorAll(".highlighted-rows");``` through the Chrome console and it works though. The same line of code gives me the error if I run it through the javascript file
Comment: @RandyCasburn Isn't that only when you don't meet the same origin policy? I don't see why I wouldn't be in-line with this policy.
Answer: You will only have an opener if it was set.  See docs for more details, but the important bit:

When a window is opened from another window (using Window.open or a link with its target attribute set), it maintains a reference to that first window as window.opener. If the current window has no opener, this method returns null.

If you're sure the window you're trying to access should have an opener, can you post the code that spawned it?


Static resources (images) Tomcat or Nginx server

Question: Give me the right way. I have nginx server (list 80port) which proxy to tomcat server (for ex 8080port). I need to get static images in my spring app. I got something like this:
1) map images on tomcat server (aliease) or Context docBase
2) map static on nginx server
3) create another sub domain for ex images.mysite.com and work with him.
And also what will be better?
Comment: As with any performance question, you have to measure to pick the best solution. So either you do what is easiest, or you spend a week measuring which is fastest. I can't count the number of times I have been wrong in my assumptions about which is fastest. I remember having 100 static html pages, and I was sure Apache www would be faster than Tomcat, but with the default settings Tomcat beat Apache with a factor of 10.
Comment: choose most easy way to get started, and choose later if it is necessary
Comment: I think about this, but i would to get right way initially
Answer: There is no universal right way.
If you have a low traffic site: Use what you can set up quickest. Don't worry, if you are running into performance problems, they won't be due to this decision but due to other aspects of your solution.
If you have a high traffic site: Start with the easiest setup (same as before). Then measure where your performance problems are. Again, most likely they won't be due to the delivery of static content, but whatever your biggest performance problem is: Fix it, rinse, repeat. If static content delivery makes up for an improvement of 0.5% of performance, while another factor makes up 20%, guess where you should invest your time (hint: it's not static content delivery)
In this regards I'm totally with Klaus Groenbaek's comment: Building a complex system that's harder to maintain without having some justification (measurements) showing the advantage of the complexity is preposterous.
Unless you identify an actual performance bottleneck in your own system, optimize for maintainability, build the simplest possible system.
Answer: Performance:
Nginx is a great webserver and at the moment is the best when talking about serving static content. You can referr to benchmarks available online, or benchmark it yourself.
Subdomain/Separate domain for  static content:
By using sub/separation for static content, you will eliminate cookies on static content, reduce http request/response size and will have better performance.
You will also increase the number of parallel downloads that the browser can perform. This will reduce your page load time.
This will increase your costs if you have ssl enabled, you need a certificate for your sub/separate domain too.


What is a better way to state this?

Question: Let $T : V → W$ be a linear map of finite dimensional vector spaces. Prove that $T$ is surjective (respectively, injective) if and only if $T^*$ is injective (respectively, surjective).
What is a better way to state this?
Comment: A statement of the form "if X (resp. X'), then Y (resp. Y')" should be read as two implications: (1) X implies Y and (2) X' implies Y'.
Comment: Um, the statement looks fine, are you wondering how to prove it? I don't really understand your issue with this.
Comment: That's what I mean. Thank you.
Comment: (respectively, injective) just means show both sur. and inj.?
Answer: The statement seems fine as it is. However, if you do not know about the convention used, I will describe how it is read. There are really two statements contained in the expression "$T$ is surjective (respectively, injective) if and only if $T^{\ast}$ is injective (respectively, surjective)."
The first statement ignores the parentheses: "$T$ is surjective if and only if $T^{\ast}$ is injective." The second statement replaces what comes before the parentheses with what is in the parentheses: "$T$ is injective if and only if $T^{\ast}$ is surjective."
In general, when ever you see a statement of the form "if $X$ (respectively, $X'$), then $Y$ (respectively, $Y'$)" then you read it as the statements "if $X$ then $Y$" and "if $X'$ then $Y'$".

What is a better way to state this?


Flash the local drives, scan and retrieve deleted files with vsc++

Question: Does anyone know how to be able to list down all the working local drives ( like drive C, D, removable disks and so on..) through combo box? And with that, I could be able to scan that specific drive and retrieve all the deleted files in it. I mean, to recover those files that have been deleted through formatting or by pressing shift+delete.
Just the functions that would be needed to do all of these stuffs would be enough though. By the way,
I know it would be hard if I would be using high-level language like Java and C# to do that, so visual c++ is the one I've been working on.
That's it! I hope to get positive response from you guys. Any suggestions would be highly appreciated. Thank you!
Comment: You want us to write the code for a file recovery utility for you? I don't think that's going to happen, no matter how nicely you ask. This is a lot more complicated and difficult than you seem to understand, considering your question ends with "That's it!" There are entire companies with products like this as their flagship applications. If it were completely trivial, these companies wouldn't exist. A search will reveal plenty of questions covering similar topics that will help get you started.
Comment: possible duplicate of [Recovering deleted file on windows](http://stackoverflow.com/questions/2837307/recovering-deleted-file-on-windows), [C# classes to undelete files?](http://stackoverflow.com/questions/8819188/c-sharp-classes-to-undelete-files) (yes, it says C#, but the code is all P/Invoked, so it's trivial to translate to C++)
Comment: I suggest you learn the internals and implementation details of NTFS. It's not a simple task and has every chance of compleely screwing up a drive.
Answer: Use TestDrive
http://www.cgsecurity.org/wiki/TestDisk_Download
Its open source and works great
Answer: pull the drive out of the unit, if it's NTFS, go get getdataback for NTFS.
Install it on a windows computer, slave this drive to the system and scan it for deleted files.
It will show all the ntfs structures, even deleted or destroyed ones.
It's not free but will be the best $100 you ever spent if it saves your files.


How many controllers does OS X support?

Question: Dear fellow Steam on OS X players,
I wonder how many controllers can be connected either per USB or paired via Bluetooth to OS X? I have just one PS4 dualshock which works perfectly with my Macbook Pro, but I want to know if it supports another one, and if possible, up to four controllers?
Comment: did you succeed ? i'm trying to figure out why it doesn't work properly on my osx...
Answer: Yes it is possible to connect up to four controllers having a maximum of 7 connections through USB and unlimited number of connections through pairing, as long as your game supports multiplayer. You should check this out.
Comment: ahh superusers. of course :)
Answer: Answering for the USB side of things.
OS X itself should be able to detect up to 127 total USB connected devices through a single port.
I highly recommend reading this: https://superuser.com/a/330570/259665
I would also recommend getting a 4-port, powered USB hub to make sure that USB lag is not a factor when 4 people are actively using a controller.

If you actually want to connect 127 devices then it would require very careful planning to make sure that all of the USB hubs are powered properly.
Furthermore, if you actually connect 127 devices through one USB port then expect some very extreme lag when using your controller.

How many controllers does OS X support?


DoCmd.RunSQL Use Transaction equivalent in adodb.command

Question: In my MS ACCESS application i execute SQL code in 2 different ways.
First - DoCmd.RunSql
Second -  Adodb.Command + executing it after.
In first method i can set Use Transaction parameter to false. Is there any way to set Adodb.Command executing SQL code not to use tranactions? As i can do with DoCmd.RunSQL, by setting that parameter?
Answer: ADODB.Command doesn't use a transaction unless you explicitly start one in your code with yourConnection.BeginTrans. See http://msdn.microsoft.com/en-us/library/windows/desktop/ms680895%28v=vs.85%29.aspx
In short, the connection object controls the transactions, not the commmand object.


why sfunction in onReset was called 2 times in GWTP?

Question: i want my web app to show a dialog box after the web app got started. I used:
protected void onBind(){
   super.onBind();
   DialogBox dg=new DialogBox();
   dg.show();
}

but it didn't work.
So i put the cose into onReset
protected void onReset() {
    super.onReset();
    DialogBox dg=new DialogBox();
    dg.show();
}

this time it showed ok, but it showed 2 dialogboxes instead of 1?
How to fix this problem in GWTP?
Answer: i think some certain function called my presenter that i didn't know so the onReset was called 2 times.
I fixed, i put into onReveal, & it's ok


Rails dosen't log database queries

Question: I set in development.rb the following line:
config.log_level = :debug

The server starts normally, but it still doesn't log teh query, I expect to see the SELECT CREATE etc in the log, but nothing appears. I installed exceptional some time ago, it is possible that it bothers the regular log ? If yes, how to solve the problem ?
EDIT 1 for the requirement of the answer:
ls -la log/ :

totale 26416
drwx------  2 marco marco     4096 18 giu 13.14 .
drwx------ 15 marco marco     4096  5 lug 10.48 ..
-rw-r--r--  1 marco marco 27027849 18 lug 12.07 development.log
-rw-r--r--  1 marco marco     1578 18 giu 13.14 exceptional.log
-rw-r--r--  1 marco marco     2676 18 giu 13.14 production.log
-rw-r--r--  1 marco marco        0 18 giu 13.14 test.log

cat ./Gemfile :

source 'http://rubygems.org'

gem 'rails', '3.0.3'
gem 'exceptional' #Logging system in production

group :development, :test do
  gem 'railroady'
end
# Bundle edge Rails instead:
# gem 'rails', :git => 'git://github.com/rails/rails.git'

gem 'sqlite3-ruby', :require => 'sqlite3'
gem 'paperclip', '~> 2.3'
gem 'aws-s3'
gem 'rails3-jquery-autocomplete'
# Use unicorn as the web server
# gem 'unicorn'

# Deploy with Capistrano
# gem 'capistrano'

# To use debugger (ruby-debug for Ruby 1.8.7+, ruby-debug19 for Ruby 1.9.2+)
# gem 'ruby-debug'
# gem 'ruby-debug19'

# Bundle the extra gems:
# gem 'bj'
# gem 'nokogiri'
# gem 'sqlite3-ruby', :require => 'sqlite3'
# gem 'aws-s3', :require => 'aws/s3'

# Bundle gems for the local environment. Make sure to
# put test-only gems in this group so their generators
# and rake tasks are available in development mode:
# group :development, :test do
#   gem 'webrat'
# end

Answer: Ciao Giuseppe,
perhaps you are using a web server that does not log this kind of stuff, just
tail -f log/development.log

in a separate console.
Comment: Tnx, but unfortunately the development.log doesn't logs the queries too
Answer: try to set specific RAILS_ENV as following:

RAILS_ENV=development rails server
Comment: Done I set it in environment.rb nothing is changed :(
Comment: how do you run the rails application in development mode? can you do some things: 1. ls -la log/ 2. cat ./Gemfile
Comment: everything is correct, **development.log** is on place and it's 27Mb. seems the **exceptional** gem catch the SQL queries from the log. try to move gem 'exceptional' to "production" group

Rails dosen't log database queries


Linear forms of $L^1$

Question: I am an engineering student who has unwittingly taken a module in functional anylysis which, unfortunately, is ever so slightly over my head.  I would greatly appreciate if you could either point me in the right direction for the questions below, or at least tell me where I might find some materials which would enlighten me in this area.
So,
$$
\varphi(f)=\int u\times f
$$$$
u\in L^\infty,    f\in L^1
$$
Show that $\varphi(f)$ is a continuous linear form on $L^1$.
Now, if
$$
A=\text{sup}{ \{ |\varphi(f)| \text{ for } f\in L^1 \text{ and } ||f||_1 \leq1 \}}
$$
can $A=\infty$?
Many thanks.
Comment: There are some details missing for this problem, such as what space these functions $f$ and $u$ are $L^1$ and $L^{\infty}$ on exactly, and what the space of the codomains of these functions are. But I think this can get you started: A linear operator is bounded if and only if it is continuous. Thus, just show that $\varphi$ is a linear operator, and $ \| \varphi (f) \|_1 \leq M \| f \|_1$ for some $M >0.$
Comment: Holder inequality (I imagine you could do it more directly using the above comment)
Answer: To show that $\varphi$ is continuous, you have to show that $A$ is finite. Let $M=||u||_\infty$.
Then for $||f||_1\le 1$:
$$|\varphi(f)|=\biggl|\int uf\,\biggr|\le\int|uf|\le \int  M|f|=M\int |f|=M||f||_1\le M.$$
That $\varphi$ is linear follows from the linearity of integration.
Comment: Thank you David and Ragib, that was very useful.  I should of course have mentioned that the space is $\mathbb{R}$. A later question is similar but for $L^2$: $\psi (f) = \varphi (w \times f), w,f \in L^2 (\mathbb{R})$.  I assume I have to do the same process but for $L^2$ i.e show that $||\psi(f)||_2 \leq M||f||_2$?  Thanks once again.
Comment: @NIM: The estimate is a bit less trivial, but works the same way: use [Hölder's inequality](http://en.wikipedia.org/wiki/Holder's_inequality).

Linear forms of $L^1$


How to send unsigned characters over TCP in this communication protocol format in Python?

Question: So, I'm working on a project with a proprietary communication protocol. I need to send data in given format and Up, Down, Left & Right co-ordinates to particular IP address. Communication happens over TCP and I need to program TCP client in python to send data in following format:
IP address/Handshake address: 126.96.36.199
This is the Data format.
Data type is unsigned char 0-255 (8-bit binary) and data length is 6-64 bit.
Data length of each frame is 10-64 bit.
So, If I want to move object at 126.96.36.199 to (23, 45, 67, 89), this is the given instruction:
Send 255 255 10 3 1 0 0 1 23 45 67 89 to specified IP address. I imagine specified IP address is 18.104.22.168. You can refer to data format to understand this data that I'm supposed to send. It's quite simple.
The question is, how am I supposed to send this series of unsigned chars over TCP in python?
I've tried following:
import socket
host = '220.127.116.11'
port = 80                   # 80 Because TCP

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))

data = '255 255 10 3 1 0 0 1 23 45 67 89'
s.sendall(data)
result = s.recv(1024)
s.close()
print('Received', repr(result))

Obviously this is not working. I've not specified unsigned char and I'm just sending raw data and spaces.
This is what I get in return from server:
('Received', '\'HTTP/1.0 400 Bad Request\\r\\nServer: Mini-IoT-314\\r\\nDate: , 31  1969 23:59:59 GMT\\r\\nPragma: no-
cache\\r\\nCache-Control: no-cache\\r\\nContent-Type:
text/html\\r\\nConnection: close\\r\\n\\r\\n<TITLE>400 Bad
Request</TITLE>\\n
400 Bad
Request
\\nCan\\\'t parse request.\\n\\n\'')

Now, I'm not sure what to do and how to send this data so server can process this data appropriately. I would really appreciate a help here.
Answer: Not really my area of expertise, just an idea:
You might need to send the data as a Structure.
Have a look at python's ctypes: https://docs.python.org/3/library/ctypes.html#structured-data-types
from ctypes import *

class payload(Structure):
    _fields_ = [("data_sign1", c_ubyte),
                  ...]

Comment: Thanks for the answer. I tried this. But It's not working. Server is not able to parse the request.
Answer: 1) I tested your code in python 3.5 with slight modifications rather than sending string,i sent bytes by converting string into bytes
bytes(data,'utf-8')

2) Do not use Port 80,might be your http server is running on that port,
 Try to use some other port. it will work
Comment: Thanks for the answer. I tried this but It's not working. Got the same error message.

I scanned with arp and nmap. And only one host is active which is 184.108.40.206 and only two ports are open, 80 & 50000. And IBM DB2 is hosted on 50000.


Compute MLE and MSE

Question: $X_1,\ldots , X_n$ i.i.d. and $f_{\theta}(x)=\frac{1}{\theta}x^{\frac{1}{\theta}-1}\hbox{I}_{(0,\infty)}(x)$
Compute $MLE\theta$ and $MSE(\hat \theta)$
I had no problem with computing $MLE\theta$ which is $\hat\theta=-\ln((x_1\cdot\ldots\cdot x_n)^{\frac{1}{n}}) $, but i have a problem now with computing $MSE(\hat\theta)$.
I started with:
$MSE(\hat\theta)=Var(\hat\theta)+(b(\hat\theta))^2$ where $b$ is bias.
But I have a problem even computing a bias.
To be exact, my biggest problem is to compute $\mathbb{E}[\hat\theta]$. I competly don't know what to do, since there is a logarithm in there. Any hints would be appreciated.
Comment: In order to provide a bit of assistance, remember that $E[\hat{\theta}]=\int^\infty_{-\infty}\hat{\theta}f(x)dx$. (Replace the integral with a summation in the discrete case.)
Answer: I'm suspecting that you made some mistakes.
1) Probably the support of the original r.v is $[0,1]$ and not $(0,\infty)$, otherwise it is not a valid density function.
2) You should check your calculations, the MLE should be $$
\hat{\theta}_n = -\frac{\sum_{i=1}^n \ln(x_i)}{n}.$$
3) Lets start with the expected value,
$$
\mathbb{E}\theta_n = \frac{1}{n}\sum\mathbb{E}(-\ln X_i)
$$
so, denote $Y=-\ln X$, hence
$$
F_Y(y) = P(-\ln X \le Y) = 1-F_X(e^{-y}),
$$
thus,
$$
f_Y(y) = \frac{1}{\theta}e^{-y/\theta}, \quad y \ge 0.
$$
That is an exponential r.v, therefore, $\mathbb{E}\theta_n = \theta$. Can you proceed to the MSE?

Compute MLE and MSE


How is the level of a Greater Rift Keystone decided?

Question: I would like to know 2 things :

What determines the level of a Greater Rift Keystone level during the first trial ?
What determines how many levels Urushi gives to the next Greater Rift Keystone at the end of a Greater Rift ?

Thanks
Answer: The level of the Greater Rift Keystone obtained by completing the Realm of Trials is determined by the wave you killed last. The wave level is determined by how fast you killed the previous wave (note the timer on each wave). It always starts at 1.
This metric has been slightly described in more detail for multiplayer groups. A group of 2 receives a key equal to the level complete minus 4, group of 3 gets a key equal to minus 5, and a group of 4 gets -6.
What determines how many levels Urushi gives to the next Greater Rift Keystone at the end of a Greater Rift ?
Of 15 minutes,
0-3 minutes taken: level + 9
3-4 : +8
4-5 : +7
5-6 : +6
6-7 : +5
7-8 : +4
8-9 : +3
9-10 : +2
10:30+ : +1
Comment: I think you can update your answer : http://us.battle.net/d3/en/forum/topic/14579008081
Comment: And what is the relation between the # of the wave during the trial and the number of the key. For example at wave level 46 I recieve a key level 40, wave 41 is a key level 35 : how does that work ?
Comment: @WizLiz - The keystone trial has been since slightly tweaked I believe, although I could not find any posts actually saying anything about it. From observation, it seems to be that you get the key level of the last wave you defeated without the timer going below 30%.
Comment: @WizLiz - I included the group modification numbers to the Greater Rift Keystone.
Comment: I finished a rift in 7:05 and got +4.  I dont know how exactly your list categorizes that.   does "4: +8" mean < 4 minutes?  If so, then there is no time for 10-11 minutes remaining.
Comment: From my own testing, anything over 10:30 is +1.  10:26 is +2
Comment: This answer is out of date. It's 10:30 for +1


How can i do select multiple rows ( allowMultipleSelection="true" ) in datagrid using flex?

Question: I have id(array) used in my application . i want to select number of rows mathching given array but if i used gatagrid selected Index then it will be selected only one row only . i set data grid allowMultipleSelection="true" also .. . how can be select mutipule rows in datagrid ? please refer me
for(var i:int=0;i<id.length;i++)
        {

            datagrid.selectedIndex=id[i];
        }

Answer: If id is an array of integers, you should be able to do this:
datagrid.selectedIndices = id;

Answer: try setting them through selectedItems instead that allows you to set multiples.


sorting Vertices ClockWise

Question: I am using This Algorithm To sort a list of Point ClockWise:
<code>private List<Point2D> SortClockWise(List<Point2D> Points) {
    // First Calculate Center of Points
    double CenterX = 0;
    double CenterY = 0;
    for (int i = 0; i < Points.size(); i++) {
        CenterX += Points.get(i).getX();
        CenterY += Points.get(i).getY();
    }
    Point2D Center = new Point2D(CenterX / Points.size(), CenterY
            / Points.size());
    int n = Points.size();
    int k;
    for (int m = n; m >= 0; m--) {
        for (int i = 0; i < n - 1; i++) {
            k = i + 1;
            if (!less(Points.get(i), Points.get(k), Center)) {
                Point2D tmp = new Point2D();
                tmp = Points.get(i);
                Points.set(i, Points.get(k));
                Points.set(k, tmp);
            }
        }
    }
    for (int i = 0; i < Points.size(); i++) {
        mTempShape.add(Points.get(i));
    }
    return mTempShape;
}

private Boolean less(Point2D a, Point2D b, Point2D center) {
    if (a.getX() - center.getX() >= 0 && b.getX() - center.getX() < 0)
        return true;
    if (a.getX() - center.getX() < 0 && b.getX() - center.getX() >= 0)
        return false;
    if (a.getX() - center.getX() == 0 && b.getX() - center.getX() == 0) {
        if (a.getY() - center.getY() >= 0 || b.getY() - center.getY() >= 0)
            return (a.getY() > b.getY());
        return b.getY() > a.getY();
    }

    // compute the cross product of vectors (center -> a) x (center -> b)
    double det = (a.getX() - center.getX()) * (b.getY() - center.getY())
            - (b.getX() - center.getX()) * (a.getY() - center.getY());
    if (det < 0)
        return true;
    if (det > 0)
        return false;

    // points a and b are on the same line from the center
    // check which point is closer to the center
    double d1 = (a.getX() - center.getX()) * (a.getX() - center.getX())
            + (a.getY() - center.getY()) * (a.getY() - center.getY());
    double d2 = (b.getX() - center.getX()) * (b.getX() - center.getX())
            + (b.getY() - center.getY()) * (b.getY() - center.getY());
    return d1 > d2;
}
</code>
the problem is in some Cases Like this:

the algorithm gives me the BlackLine Drawn in the picture, But What i want to get is the Numbered Vertices In picture.
Comment: The black line looks like the correct expected behaviour to me. The points have been arranged clockwise in a circle (or at least as close to that as possible). The only way I see it being able to get what you want is if `Center` was a point somewhere in the middle of the 7-3-6 triangle. But that's only in this case - I think that for some other shapes no `Center` would work. So you probably want a completely different, more advanced algorithm that is aware of the role of the points as vertices of a shape, not just as locations. How is the shape currently represented?
Comment: Your center is located somewhere above point 3 (same x coordinate). This makes the sorting correct for that center.
Comment: yes the sorting is correct for this algorithm, But i want to Know How i can get the result that i want
Answer: I would try an approach with splitting all into polygon first. Start with point 1, then you go though your vertex in your polygons until you reach a vertex that is shared. Then you have to change the polygon.
After all, if you only have points, without defining edges (implicit or explicit) you can only have a convex shape.

sorting Vertices ClockWise


Blackmagic intensity pro is a virus. It crash motherboard + PCI + USB devices

Question: Blackmagic intensity pro is a virus. Do not buy this card anymore?
I bought a card and it crashed my whole system. I cant see network anymore getting up.
I tested this with: Ubuntu 10.04, 11.04, Fedora, CentOS, ArchLinux all the time it crashed my system.

I cant boot to my own BIOS
System do not show network or it does not get auto DHCP or no network interface
CPU/RAM do not function properly

Has anyone same problem?
Comment: This is more of a discussion and experience sharing than an answerable question, so it is more suitable for a forum than this site. Please take it to ubuntuforums.org
Answer: A piece of hardware, by definition, is not a virus. It can however, be incompatible with your current hardware, OS or other software. I would suggest you return this product, and purchase a comparable device that is compatible. (I'll post a link to the Ubuntu/Linux HAL here shortly.)
 You might also contact their company. I suggest you find their website for contact information. In your correspondence, you should include that you are a Linux user who would like to use their product, but you've had to return it due to the fact that they do not properly support a viable, and widely used Operating System. Also, that you will not purchase any further products until such matters are resolved.
Aside from that, @Javier Rivera make an excellent suggestion to visit http://ubuntuforums.org.
I've been a member there for some time and I'm sure there is someone there that would be glad to continue a discussion on this topic.


Hibernate attempted to assign id from null one-to-one property

Question: I have two entities:
@Entity
@Table
public class User {

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

    @OneToOne(cascade = CascadeType.ALL, orphanRemoval = true, mappedBy = "user")
    private UserDetails userDetails;

}

@Entity
@Table(name="user_details")
public class UserDetails {

    @GenericGenerator(name = "generator", strategy = "foreign",
        parameters = @Parameter(name = "property", value = "user"))
    @Id
    @GeneratedValue(generator = "generator")
    @Column(unique = true, nullable = false)
    private Integer id;

    @OneToOne
    @PrimaryKeyJoinColumn
    private User user;

    public UserDetails(User user) {
        this.user = user;
        user.setUserDetails(this);
    }

}

It works if I create a user with a userDetails. But then it creates a UserDetails row and I don't want it. I have to fetch a User from database and add a UserDetails later:
userRepository.findOneById(id).map(user -> {
    UserDetails userDetails = user.getUserDetails();
    if (userDetails == null)
        userDetails = new UserDetails(user);
     userDetails.setEmail(email);
     userRepository.save(user); //error here
});

Error

org.springframework.orm.jpa.JpaSystemException: attempted to assign id from null one-to-one property [com.app.domain.UserDetails.user]; nested exception is org.hibernate.id.IdentifierGenerationException: attempted to assign id from null one-to-one property [com.app.domain.UserDetails.user]
Answer: The UserDetails object in this case is the owning side of the relationship between a User and the UserDetails
Bidirectional relationships between managed entities will be persisted based on references held by the owning side of the relationship.
Therefore, when you say userRepository.save(user), you're actually trying to save from the child side of the relationship.
You need to create a UserDetailsRepository and invoke the save from that new object.
i.e. here's what the code should look like:
userRepository.findOneById(id).map(user -> {
    UserDetails userDetails = user.getUserDetails();
    if (userDetails == null)
        userDetails = new UserDetails(user);
     userDetails.setEmail(email);
     userDetailsRepository.save(userDetails);
});

Comment: I wonder, why UserDetails is in this case the owning side? Usually it tends to be User (in this example), as specified by "mappedBy".
Comment: How do I make User side as owning ?
Answer: the answer of was very helpful to me, is tricky to understand how hibernate works... at least for me (nooby :D)
Comment: You use the comment function to  comment the helpful answer (or simply upvote)


asset() function in twig gives an NotFoundHttpException "No route found for "GET /favicon.ico"

Question: I have just installed a new Symfony project (I use xampp). When I started the application the favicon on the url tab wasn't showing, i opened the source code and opend the icon from there, but I got the error message I writed in the title.
In the code the link is presented as:
<link rel="icon" type="image/x-icon" href="{{ asset('favicon.ico') }}" />

and in the source code it was like
 <link rel="icon" type="image/x-icon" href="/favicon.ico" />

What is the problem, am I missing something ?
Thanks
Comment: Which Symfony version are you using? It can't be both 1 and 2.
Comment: Symfony 3.3, i just selected that so i can get the answer faster, i tought it is the same thing when it comes to this problem. Sry
Comment: did you find the solution to this?
Answer: you should put the file in the web folder
the asset function target a folder web by default.
http://symfony.com/doc/current/best_practices/web-assets.html
Comment: Care to expand?
Comment: It is in the web folder "web -> favicon.ico" ... I just installed the project, I didn't touch anything. The .ico file is by default in the web folder


I screwed up a dual boot (Windows 7 + Ubuntu 14.04.1) so bad that no OS will load and I had to buy Windows again

Question: So heres what happened: I had Windows 7, partitioned so that 64GB of unallocated space would be used to install Ubuntu side by side Windows 7. My live CD booted up and gave me the error message: Could not open "\EFI\BOOT\fallback.efi": 14
However, it still loaded and gave me a few options.
->Try Ubuntu without installing.
->Install Ubuntu
->Install OEM (for Manufacturers)
->Check disk for defects
I should note here before I get further in, that it said it detected no operating systems on my PC and I had to use the "something else" option from the installer.
I then ran into another problem. My hard drive was partitioned multiple times, (The main, local C:\ drive, "HP TOOLS" and "RECOVERY" and the System Reserved partition. I also had some weird listing that said it was only a megabyte. I deleted it. HP had set these partitions up. (This is a laptop, not a custom made PC.) I realized since the limit for partitions is 4, I was getting the "unusable" error because I couldn't have more than four partitions. I wanted to have one for "/home", one for "/", and one for "swap" or "swap area". I transferred over the HP TOOLS files to the main C:\ drive. I stupidly did not copy the recovery over, I just deleted it. So then I deleted the partitions made by HP, and put the partitions back into the main drive, as to be able to create more for Ubuntu. So FINALLY, after hours of work, (and no backups, because I'm an idiot,) I was able to create partitions for "/" and "swap" But not a separate partition for "/home" because the system reserved partition and main C:\ took up two out of four partitions already. But at least I had two for "swap" and "/" So I install Ubuntu. Everything is going great! The install finished and I was told that it needed to restart. Heres where everything messed up. I reboot and am greeted with this long error message:
"
Gave up waiting for root device. Common problems:
 - Boot args (cat /proc/cmdline)
   - Check rootdelay= (did the system wait long enough?)
   -Check root= (did the system wait for the right device?)
 -Missing modules (cat /proc/modules; 1s /dev)
ALERT! /dev/disk/by-uuid/89313593-abaf-4f90-add3-496f84d6b339 does not exist
Dropping to a shell!
BusyBox v1.21.1 (Ubuntu 1:1.21.0-1ubuntu1) built-in shell (ash)
Enter 'help' for a list of built-in commands.
(initramfs) -
"
If I press enter it just shows "(initramfs) - " over and over. I tried changing boot devices and only "EFI file" and Disk drive are listed. I tried to restore my PC in every way I was given but couldnt. Tried with a Win 8.1 install disk and it loaded but I didn't have a serial key so it wouldn't work. Tried to restore but I had deleted HP's restore. Tried to Reset the computer completely from the Win8.1 disk but it said "Unable to reset your PC. A required drive partition is missing." If I click "Refresh your PC" it says the drive where Windows is installed is locked. Unlock the drive and try again."
This might be because I'm trying to repair a Windows 7 PC with a Windows 8.1 disc. But who knows...?
Every time I start up the PC it just lists these options:
->Ubuntu
->Advanced options for Ubuntu
->System Settings
When I hit "Ubuntu" it shows a blinking underscore which eventually turns into the "Gave up waiting for root device" error message above.
When I hit "Advanced options for Ubuntu" it lists:
->"Ubuntu, with Linux 3.13.0-44-generic"
->"Ubuntu, with Linux 3.13.0-44-generic (recovery mode)"
->"Ubuntu, with Linux 184.108.40.206-generic"
->"Ubuntu, with Linux 22.214.171.124-generic (recovery mode)"
I've only tried the first two from the advanced options list and they both result with the "Gave up waiting for root device" error message.
When I hit "System Setup" it says:
"error: can't find command 'fwsetup'.
Press any key to continue."
Please help! What did I do wrong? I'm screwed. I lost all my files from the past 3 years... :(
Also, I need to know if the same serial key that will come with my new copy of Windows 8.1 will be able to install the OS more than once, in case I keep trying to dual boot and it keeps screwing up like this, and I need to keep installing it.
Comment: You were wrong when you assumed that it is only possible to have four partitions. It is true, but only for primary partitions. Instead of the fourth primary partition, you can create an extended partition which is nothing more than a container for as much logical partitions as you want.
Answer: Please order a Restore DVD from your manufacturer (HP) and the Windows product key will still be valid! (Last time I did this, I only paid shipping and handling)
Then read this Q&A: What's a good back-up strategy for 1 desktop PC? (You're definitely User type 4!)
Then follow the article here: Installing Ubuntu Alongside a Pre-Installed Windows with UEFI
Even though it's a Q&A about Windows 8, it applies to Windows 7 UEFI systems!
Comment: Fabby, thanks for the reply. So you're saying even though I'm gonna put Windows 8.1 on my Windows 7 laptop, it'll still be a Windows 7 UEFI? Also, thanks for the links, but I don't think I'm gonna order a restore dvd, unless that would get all my files back? Would it?
Comment: You can install Windows 7 on UEFI??
Comment: Where are you going to buy Windows 8.1? From HP?  Because if you've destroyed your *UEFI* partition, you need to restore that too!
Comment: How would I restore that?
Comment: Well, a **Restore DVD from HP** as per the answer, would be the easiest (and cheapest) way of restoring the entire PC.
Comment: Couldn't I just re install Windows? Would a restore dvd from HP get my files back? Sorry about all the questions, you're being very helpful.
Comment: As you're a reputation 1 user: If this all works, don't forget to click the grey check-mark under the "0" at the left of this text, which means "yes, this answer is valid"!  ;-)
Comment: Unfortunately, AskUbuntu is not a forum, and the maximum number of comments has been reached. If you want additional information: http://askubuntu.com/questions/ask
Comment: Wait will the restore DVD from HP get my files back or not?


Electrical Sub panel unequal legs

Question: ElectricalSub panel unequal legs. With all of the sub panel power is equal on both legs right at 1:20 apply power light switch in a small circuit the lights are down voltage one leg drops to 107 second leg goes up to 133
Comment: Is this only happening at the subpanel, or at the main panel end of the feeder as well? Is this feeder within the same structure, underground, or overhead?
Comment: Possible duplicate of [240 volt house wiring, 130 volts on one leg and 112 volts on the other?](https://diy.stackexchange.com/questions/88599/240-volt-house-wiring-130-volts-on-one-leg-and-112-volts-on-the-other)
Answer: You have a lost neutral. Serious business! Fix immediately!
I don't know whether you've lost a neutral in a multi-wire branch circuit, at the subpanel, at the main panel, or at the pole.  The most common one is "at the pole", which is good news because that's the power company's problem and they'll fix it fast for free. Just report a power outage, which is what it is.
Once I had this happen on a 30A feeder which supplies our cottage.  Checked the other house circuit, nope, it's low too. Then I discovered we were only 1/2 of a 30A MWBC with the next cottage over, who was getting ~150V and was frying appliances.  Suddenly her complaints of frying appliances made sense.  So it's the creaky MWBC to the cottages - nope, it's the ancient FPE master panel.  Nope, it's the meter.  Nope, it's the pole - our entire complex was affected and the neighbor too.  Moral of the story: cast a wide net when searching for this thing. We should have started at the master panel.
What's really happening
Look at my diagrams here that describe how split-phase works.  What  you have going on is this:

Notice how the 240V loads don't care, but the 120V loads are now out of balance.  That's what is happening, and it's changing as loads are turned on and off.  The two 120V legs will add up to 240V, but  they won't be 120V.
Answer: Sounds like you have a bad connection at your neutral. With no load the voltage measures correctly, check the connections at both the main panel and the sub.

Electrical Sub panel unequal legs


How to secure an outdoor 1" PVC 3ft long watering riser pipe?

Question: How can I secure a ~3ft 1" white PVC pipe riser from getting snapped off?
Riser presently is 6ft up and capped.
I plan to add right angle elbow, valve, and spout (standard lawn house threaded).
Gory Details...
18" below ground riser connects 90 degree elbow that runs 1" white PVC pipe through 18" deep buried trench 75ft to pressurized (60psi) well water supply.
I've thought of a couple of rebar stakes on either side of riser, but directly below riser, 18" down, a gray 3/4" electrical 110vac conduit also runs along same trench, parallel with and touching the 1" water PVC.
Gray elec conduit runs a few feet past water riser and elbows upward to an outlet box, also for my wife's beloved chickens.
I installed trench with 1" white PVC pipe for bringing pressurized well water near to chicken coop.
I've thought of a wooden stake about a foot on either side of water riser.  But chickens will jump on them and crap.
Answer: 4x4 treated wood (or concrete for the ultimate) post, 24" (or more) deep beside the pipe (thus beside, not through, the conduit as well) Pipe fastened to post and painted to prevent sun damage. If the present pipe has been left unpainted in the sun for any significant time, it may already be damaged and need to be replaced. Metal T-post for the low-end post option, I guess, but you need to dig at least to the conduit before driving the post.
Alternatively, and pretty much required if you live where it freezes, transition to metal pipe below ground with a galvanized (or stainless for the ultimate) pipe riser and a frost-proof hydrant (drains below ground when shut off. Valve and bleed to drain the riser when shut off are below frost line. Valve handle is up top.)
Comment: Encasing the pressurized pipe in a larger diameter PVC or similar pipe provides protection against elements and trauma.   When protecting in-service pipes, I will sometimes run a slit along the length of the larger pipe so the pipe is not taken out of service: this is unnecessary in the OP's case as the end has not been outfitted with a fixture.  I also like Ecnerwal's idea of pinning the pipe to a wooden post
Answer: Cut the pipe a little shorter, say 2 feet instead of 3.   Pile rocks or concrete blocks around it.  8 inch concrete blocks stacked 2-high leaving 8 inches of pipe exposed should protect it from most snappy offy events.  An artistic pyramid of rocks might do even better.   Anything rock-like will scare away careless drivers of mowers, tractors etc.  And anything that leaves no more than 12 inches exposed should protect it from rough handling when attaching hoses.  What else are you worried about?
Comment: +1 for "snappy offy" events. ;)


How can I export an iPad app's data to a computer?

Question: I have a simple survey iPad app. The data is saved in a TSV (tab separated file). I'm looking for an easy way to export this TSV file to a computer (without emailing it, if possible, and without doing it through iTunes).
Comment: Just email it if it's absolutely neccisary
Answer: Have a look at IExplorer. It's a great little program / app that let's you access your iPad's file system from your computer. You can just drag and drop any file from your iPad to your computer.
Answer: App data on iOS is not directly accessible from a connected computer. It's not like you can mount the iPad's flash drive directly on a computer, navigate to the app's data directory, and copy the file to the computer. You have to have something with rights to access the data.
Some options are:

email or otherwise 'share' the data from within the iPad app.
Make the app's data accessible via iTunes
Turn the app into an FTP client or server
Dropbox integration (There was some problem where Apple was rejecting apps that did this, but i don't know the current state)


Group by hour - specifying the minute to start at

Question: I've got a query that gets data for a specific day and groups it by hour:
SELECT id, timetag
FROM table
-- rest of long query
-- rest of long query
GROUP BY  DATEPART(YEAR, timetag), DATEPART(MONTH, timetag), DATEPART(DAY, timetag), DATEPART(HOUR, timetag)

and that works fine.
But is it possible to specify the time the hour starts? The data being retrieved is in 15 minute increments, i.e. there is data for 12:00, 12:15, 12:30, 12:45, 13:00, 13:15 and so on. So when it is grouping by hour it is grouping the data for 12:00, 12:15, 12:30 and 12:45, then for 13:00, 13:15, 13:30 and 13:45 and so on. I would like to group the data by hour but start at 15 minutes past the hour, so the grouping would be for 12:15, 12:30, 12:45 and 13:00, then next grouping would start at 13:15 and so on.
Is there a way to do this?
Using SQL Server 2008.
Comment: Your query as posted should give an error like `Column 'id' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.`
Comment: True, I wasn't paying attention to the SELECT, just typed it in quickly as it was the GROUP BY part of the query I was focusing on.
Answer: You can do this by subtracting 15 minutes and using that for the grouping:
SELECT DATEPART(YEAR, new_timetag),
       DATEPART(MONTH, new_timetag),
       DATEPART(DAY, new_timetag),
       DATEPART(HOUR, new_timetag),
       COUNT(*)
FROM (SELECT t.*, dateadd(minute, -15, timetag) as new_timetag
      FROM table t
     ) t
-- rest of long query
-- rest of long query
GROUP BY  DATEPART(YEAR, new_timetag),
          DATEPART(MONTH, new_timetag),
          DATEPART(DAY, new_timetag),
          DATEPART(HOUR, new_timetag);

Because subtracting 15 minutes can affect all the date/time parts, I moved it to a subquery so the code only has it once.
Comment: You can't select `id` or `timetag` without grouping on them


How should've I written: How does the prefix 'in-' in 'intonation' relate to the difference between 'tone' and 'intonation'?

Question: What exactly should I've written to communicate my question in How does the prefix 'in-' in 'intonation' relate to the difference between 'tone' and 'intonation'?? My writing probably wasn't punctilious or pinpoint enough to communicate what I was trying to ask:
Because the nouns 'tone' and 'intone' differ only by the prefix 'in-', 'in-' (and not some other prefix) must have been chosen because it somehow communicates the difference(s) between  ⟨tone⟩ and  ⟨intone⟩. So what does 'in-' (in 'intone') communicate in ⟨intone⟩ that 'in-' can't in ⟨tone⟩?
I.e.: why was 'tone', and not 'intone', chosen to mean ⟨tone⟩? Conversely, why wasn't 'intone' chosen to mean ⟨tone⟩?
Answer: This is the only thing I can think of:

What is the difference between "tone" and "intonation"?

I can't think of a sensible question about the Latin etymology of the two words, though possibly you're curious about the Latin prefix in-, and whether it had a compositional semantic function (then I'd suggest drawing in a few more examples, e.g. flame / inflame; prison / imprison). But this could run afoul of the language-specific anti-desideratum.


Sum values in multidimensional array (selecting multiple columns with multiple rows)

Question: Let's say I have 5 different columns, a, b, c, d, e, and I'm selecting multiple rows:
$result = mysqli_query($conn,"SELECT a,b,c,d,e FROM posts WHERE submitter='$user'");

while ($row = mysqli_fetch_assoc($result)){
  $ratings[] = $row;
}

Example:
The user has 3 posts, so it'll select 3 rows in the query.
I want to sum all of the rows' values for a (and the rest of course).
e.g.
row 1 a value = 4
row 2 a value = 10
row 3 a value = 1
So I need to sum all of those to get 15.

I know to use array_sum($ratings) to find the sum of the array but only if you select one column (a) which can have multiple rows, but this is multi-dimensional right due to multiple column values being selected?
Comment: possible duplicate of [MySQL Sum() multiple columns](http://stackoverflow.com/questions/22369336/mysql-sum-multiple-columns)
Answer: You can just use sum in your query:
select sum(a)
     , sum(b)
     , sum(c)
     , sum(d)
     , sum(e)
from posts
where submitter = '$user'

Comment: Yes, just saw your edit. Was trying $row[0] and $row['a'] but wasn't working, $row['sum(a)'] works though
Comment: What will be stored in the `$ratings` array?
Comment: I think you read that wrong.. -What- will be stored in there I mean?
Comment: @frosty: sorry, there will be an array of sums for each column, you can `var_dump` result to see it yourself.
Comment: Thanks, I think it's still producing a multi-dimensional array tho. `array(1) { [0]=> array(5) { ["sum(a)"]=> string(2) "22"` --- how do I retrieve the "22"?
Comment: @frosty: well, just use `$ratings = mysqli_fetch_assoc($result)` instead of the whole `while` loop. Then you can get `22` with `$ratings["sum(a)"]`.
Comment: Ahh, so it sums all the rows into "one" row kinda?
Comment: @frosty: yes, it is the main idea here.
Answer: You can use count aggregate function and group by in MySQL.
SELECT
  submitter,
  count(a) as rating
FROM posts
WHERE submitter='$user'
GROUP BY submitter

A a result you will get something like that:
some submitter, 3
another submitter, 10
one more submitter, 1

Is this helpful?
Comment: ty for the answer, I was able to get it working with the other answer tho


GameCenter - handling incoming calls etc

Question: What would you do in the following scenario:

When implementing a multiplayer game, you use GKMatchmaker to find players.
When the required number of players has connected, you start the match.
Now one of the players receives an incoming call.

What now? If the user takes the call, the application will move to the background, the connection to GameCenter will be lost, right?
What to do with the player and what to do with the match?
I guess you would have to rate that game as lost for the player who has disconnected, and try to go on with the match with the remaining players.
Has anyone come up with a better way of handling this?
Answer: The connection to Game Center is not "lost" immediately, i am unsure of the actual timeout period, and would not count on it being any particular period if it is not specified in the docs somewhere. You can always test it for a particular release/version using two connected players.
In our game Tic Tac Toe Twist, when a player disconnects due to timeout or other networking problem, we let the players know who disconnected with a message on screen for five seconds, leave the match we are in, reset the game state and then drop them back to the start game screen.
You could also remove them from your game and recover, if your particular game worked well that way.
Be sure to check out the WWDC 2011 information for updates as to how Game Center will handle this in the future, just in case Apple decides to change things...


Problems with Sass when using angular-fullstack generator

Question: I have set up a webapp using Sass with Yeoman's angular fullstack generator. It seemed to be running fine, until I realised errors that were being output every time grunt tries to run a task. Here's the output:
/Users/rorysmith/.rvm/rubies/ruby-2.2.1/bin/scss --no-cache --update app.scss:app.css
error app.scss (Line 4: File to import not found or unreadable: ../bower_components/bootstrap-sass-official/vendor/assets/fonts/bootstrap.)

Process finished with exit code 1

It's referring to a line in the app.scss file:
@import '../bower_components/bootstrap-sass-official/vendor/assets/fonts/bootstrap'
I changed the directory to include ../ at the start, as this is where my bower_components live:

When commented out, it has an issue with a different line of the same file:
@import 'modal/modal.scss';
Here's the app.scss file in its entirety, it's just the stock one created by the generator:
$icon-font-path: "../bower_components/bootstrap-sass-official/vendor/assets/fonts/bootstrap";
$fa-font-path: "../bower_components/font-awesome/fonts";

@import '../bower_components/bootstrap-sass-official/vendor/assets/fonts/bootstrap';
@import '../bower_components/font-awesome/fonts';

/**
 * App-wide Styles
 */

.browsehappy {
    margin: 0.2em 0;
    background: #ccc;
    color: #000;
    padding: 0.2em 0;
}

// Component styles are injected through grunt
// injector
@import 'account/login/login.scss';
@import 'admin/admin.scss';
@import 'create/create.scss';
@import 'main/main.scss';
@import 'modal/modal.scss';
// endinjector

Any idea what on earth is going on?
Answer: I was encountering the same problem, here's what "fixed" it for me...
In the Gruntfile, find the following:
  // Inject component scss into app.scss
  sass: {
    options: {
      transform: function(filePath) {
        filePath = filePath.replace('/client/app/', '');
        filePath = filePath.replace('/client/components/', '');
        return '@import \'' + filePath + '\';';
      },
      starttag: '// injector',
      endtag: '// endinjector'
    },
    files: {
      '<%= yeoman.client %>/app/app.scss': [
        '<%= yeoman.client %>/{app,components}/**/*.{scss,sass}',
        '!<%= yeoman.client %>/app/app.{scss,sass}'
      ]
    }
  },

Modify the following line to read:
filePath = filePath.replace('/client/components/', '../components/');

Now it should inject with the correct paths.
Caveat: I don't really know what I'm doing.


How to encrypt existing HOME folder on Kubuntu 20.04

Question: I am using Kubuntu 20.04 and would like to encrypt the home folder to protect my data if the hard disk / laptop is stolen. Can anybody help me how to do it? Which tool is recommended for it?
Comment: No, it is a default installation. So It is on the same partition as other data. When I create a separate partition for /home how to encrypt it then?
Comment: When I choose a separate partition for home during installation: is there an option to ecrypt only this particular partition? I installed "diska" but the encryption option is greyed out on all partitions.
Comment: But of course I do not like to enter additional passwort for hard disk encryption. I hope it can be encrypter with my Kubuntu user name.
Answer:
There is not a guided installation option that will encrypt only your /home folder:
This is likely due to the false sense of security it offers, since your unencrypted OS and swap can expose data kept this way.
Trying to install Kubuntu 20.04 using "Manual" partitioning to encrypt only /home isn't an option either:
Setting up partitions manually results in a broken installation.  Processes need to access files stored in ~/ immediately after authentication, but it's locked.

There exists a utility to relocate your /home: ecryptfs-utils:
It will attempt to migrate your current /home to an encrypted location.
Check out hhlp's answer on Encrypt home drive after installation for more info on using ecryptfs-utils.
I have concerns using this method because these kinds of relocations can sometimes be messy, since it's hard to account for all variables.  Also, This utility doesn't seem to address the part of your disk where your /home is currently located.  Without securely erasing this data, it could still be recovered without a password.

My suggestion is that you use the guided installation to encrypt Ubuntu entirely.  This is the only way to ensure that if someone gains physical access to your PC, they won't be able to access data without your decryption key.
Comment: You can check the option to log into your user automatically, and then you only need to enter the decryption key at boot.
Comment: OK, it sounds reasonable. But I would not liuke to enter 2 passwords: one for the HD encryption and one for Kubuntu. Would it be the case then?
Comment: good idea. thx!
Comment: One problem with that is that disk cloning will be slow - determined by the disk/partition size, not by the actually used space.


Getting javahg 0.6-SNAPSHOT from Maven

Question: I'm trying to get JavaHG 0.6 snapshot using the following Maven pom:
<dependencies>
  <dependency>
    <groupId>com.aragost.javahg</groupId>
    <artifactId>javahg</artifactId>
    <version>0.6-SNAPSHOT</version>
  </dependency>
</dependencies>
<repositories>
  <repository>
    <id>sonatype-ossrh</id>
    <name>Sonatype Open Source Software Repository Hosting</name>
    <url>https://oss.sonatype.org/content/repositories/snapshots/</url>
  </repository>
</repositories>

This makes the build fail with the following error:
Could not find artifact com.aragost.javahg:javahg-parent:pom:0.6-SNAPSHOT in sonatype-ossrh (https://oss.sonatype.org/content/repositories/snapshots/) -> [Help 1]

I think this is because 0.6-SNAPSHOT is not found in
https://oss.sonatype.org/content/repositories/snapshots/com/aragost/javahg/javahg-parent/
Does anyone know how to make it work?
Answer: Unfortunately recent builds aren't in maven currently. It is possible to build locally.
This thread has some details: https://bitbucket.org/mercurialeclipse/main/issue/424/plugin-readmemd-information-out-of-date

Clone the JavaHg repositories, including javahg-parent
Update to the 0.6 tag for each
Invoke mvn install for javahg-parent, and then again for the other repositories

Getting javahg 0.6-SNAPSHOT from Maven


pgtype.Numeric to float conversion

Question: I have an app that uses interfaces to get a variable number of columns from a postgresql database. It uses a dynamic struct of type map[string]interface{} for the data type for the query to scan into and it is all working to the point where the data is coming back fine, I can decode the column names into keys on the map and the data is able to be converted to either time.Time (for the time stamps) or pgtype.Numeric for the other fields.
This is great... BUT. I have been totally unable to get the pgtype.Numeric results to convert to float32 or Int results.
I can pull apart the pgtype.Numeric returns and print them out (for example)
Turbine, Timestamp, WindSpeed, WindDir, Power
   t017,2024-02-15 18:20:00 +1100 AEDT,{892 -2 2 false none},{7200 -2 2 false none},{226391 -2 2 false none}

But, try as I might I am totally unable to go from pgtype.Numeric to a base type.
There are directions for using set to make the pgtype.Numeric, but I've tried .Scan, and .Get and straight up casts and have not had any joy at all at getting the number back.
This MUST be easy... but I cannot work it out.
var floatval float32
err := pgNumeric.Scan(&floatval) just returns 0 every time.

What have I missed?
Comment: Just wondering: how did you convert the `time.Time` or other fields?
Answer: It seems there is an AssignTo method on the pgtype.Numeric:
var f float64
err := pgNumeric.AssignTo(&f)

It checks the given input type and fills the variable with it's internal value. Here is a link to the implementation.
Scan does the parsing of the DB value into the Numeric variable.

pgtype.Numeric to float conversion


Error building Angular Application

Question: While building this application I have kept running into this error "[ts] ',' expected". If I added the comma, saved and tried again the application would run. Now if I stop the local server and try to run it again I have to remove the comma to get the app to run. I would like to know what is going on and what I am doing incorrectly as I have only just started learning how to use Angular.
Error Message
ERROR in src/app/breeds/breeds.component.ts(35,5): error TS1005: ','
   expected.
   src/app/newbreed/newbreed.component.ts(41,10): error TS1128: Declaration
   or statement expected.
   src/app/newbreed/newbreed.component.ts(45,1): error TS1128: Declaration
   or statement expected.

Code
import { Component, OnInit } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { map } from 'rxjs/operators';
import { element } from 'protractor';
import {RequestOptions, Request, RequestMethod} from '@angular/http';

@Component({
  selector: 'app-breeds',
  templateUrl: './breeds.component.html',
  styleUrls: ['./breeds.component.css']
})
export class BreedsComponent implements OnInit {
  restItems: any;
  restItemsUrl = 'https://breeds-a648.restdb.io/rest/dogs';

  constructor(private http: HttpClient) {};

  ngOnInit() {
    this.getRestItems();
  }

  // Read all REST Items
  getRestItems(){
    this.restItemsServiceGetRestItems()
      .subscribe(
        restItems => {
          this.restItems = restItems;
      },
       (err) => console.log(err), () => {
         setTimeout(() => {
           this.getImages();
           this.deleteBreed();
        },0)
      }
    } <<<<<<< This is where it expects ","

  getImages() {
    let breedName = document.querySelectorAll('#breedName');
    breedName.forEach( (el) => {
      let image = document.createElement('IMG');
      this.http.get(`https://pixabay.com/api/?key=&q=${el.innerHTML}&image_type=photo`).subscribe(
        res => {
          image.src = res.hits[0].largeImageURL;
          image.width = '100';
          image.height = '100';
          el.appendChild(document.createElement('br'));
          el.appendChild(image);
        },
        err => {
          alert("Error occured");
        }
      );
    })
  }

  deleteBreed() {
    let deleteLinks = document.querySelectorAll('.del');
    deleteLinks.forEach( (e) => {
      e.addEventListener('click', (element) => {
        this.http.delete('https://breeds-a648.restdb.io/rest/dogs' + '/' + element.target.id, { headers: new HttpHeaders()
        .set("x-apikey", "")
        .set("Content-Type", "application/json")
        .set('cache-control', 'no-cache') })
        .subscribe(
          res => {
            window.location.href = '/index';
          },
          err => {
            alert("Error occured");
          }
        );
      })
    })
  }

  // Rest Items Service: Read all REST Items
  restItemsServiceGetRestItems() {
    const headers = new HttpHeaders()
    .set("x-apikey", "")
    .set("Content-Type", "application/json")
    .set('cache-control', 'no-cache');

    return this.http
      .get<any[]>(this.restItemsUrl,{headers})
      .pipe(map(data => data));
  }

}

Answer: You are missing a closing ) in your method:
getRestItems(){
    this.restItemsServiceGetRestItems()
      .subscribe(
        restItems => {
          this.restItems = restItems;
      },
       (err) => console.log(err), () => {
         setTimeout(() => {
           this.getImages();
           this.deleteBreed();
        },0)
      }) <-- added closing )
    }

Comment: That seemed to work for that section but now I'm getting another error (41,10): error TS1128: Declaration or statement expected.
src/app/newbreed/newbreed.component.ts(45,1): error TS1128: Declaration or statement expected.
Comment: Paste your whole file as one piece of code in your questioin and maybe I can help you..... most IDEs should point out where the error is
Comment: So sorry, rookie move. The error is pointing towards a different file. Time to take a break lol. I will mark this correct because it did fix the error in this file.
Comment: Awesome! Thanks.

Error building Angular Application


How to show $\|I -AX_0\|<1$, $(I -AX_0)^k\rightarrow0$ as $t \rightarrow \infty$?

Question: Let $A$ be an invertible matrix such that $\|I -AX_0\|<1$, how can we show $(I -AX_0)^k\rightarrow0$?
Is there any other way other than spectral decomposition theorem to show it? I do not want to use that.
Comment: There's nothing special about matrices here.  If $t$ is any number with $0 \le t < 1$, what can you say about $t^k$ as $k \to \infty$?
Comment: @Robert Israel: You are right, via that I was looking for proving the convergence to zero matrix. I revised the question.
Comment: $\|A\| =0 \iff A = 0$, and moreover you can show that norm convergence to $0$ means you have the limit (which is an operator) going to identically $0$.
Answer: Hint: since matrix norm is sub-multiplicative,
$\|(I - A X_0)^k\| \le \|I - A X_0\|^k$.


decltype(auto) works with SFINAE in some cases?

Question: I was under the assumption that decltype(auto) is an incompatible construct when used to try and SFINAE off the return type.  So, when you would have otherwise gotten a substitution error you get a hard error
But why does the following program work? https://wandbox.org/permlink/xyvxYsakTD1tM3yl
#include <iostream>
#include <type_traits>

using std::cout;
using std::endl;

template <typename T>
class Identity {
public:
  using type = T;
};

template <typename T>
decltype(auto) construct(T&&) {
  return T{};
}

template <typename T, typename = std::void_t<>>
class Foo {
public:
  static void foo() {
    cout << "Nonspecialized foo called" << endl;
  }
};
template <typename T>
class Foo<T,
          std::void_t<typename decltype(construct(T{}))::type>> {
public:
  static void foo() {
    cout << "Specialized foo called" << endl;
  }
};

int main() {
  Foo<Identity<int>>::foo();
  Foo<int>::foo();
}

Shouldn't we get a hard error when Foo is instantiated with int?  Given that int has no member alias named type?
Answer:
I was under the assumption that decltype(auto) is an incompatible construct when used to try and SFINAE off the return type.

It is generally incompatible because it forces instantiation of the body of the function. If a substitution failure occurs in the body, then that's going to be a hard compile error - SFINAE doesn't apply here.
However, in this example, the only way that you would get a substitution failure in the body is if T weren't default constructible. But you call construct(T{}), which already requires T to be default constructible - so the failure would happen first or never.
Instead, the substitution failure that happens is in the immediate context of substituting into typename decltype(construct(T{}))::type. Trying to get ::type off of an int happens while we're in the immediate context of instantiating the template arguments to Foo, so SFINAE still applies.
An example demonstrating where decltype(auto) breaks SFINAE is if we had instead implemented this as:
template <typename T>
decltype(auto) construct() {
  return T{};
}

template <typename T, typename = std::void_t<>>
class Foo {
public:
  static void foo() {
    cout << "Nonspecialized foo called" << endl;
  }
};
template <typename T>
class Foo<T,
          std::void_t<typename decltype(construct<T>())::type>> {
public:
  static void foo() {
    cout << "Specialized foo called" << endl;
  }
};

And then tried to instantiate:
struct X {
    X(int);
};

Foo<X>::foo(); // hard error, failure is in the body of construct()

Comment: @Curious Because now the `T{}` is in the immediate context first.
Comment: Ah, that makes a lot of sense!  My understanding was incomplete apparently.  Thanks!  Just for completeness, could you point to the relevant part in the standard?
Comment: Somehow I still don't get an error here - https://wandbox.org/permlink/PsV9Z7mlCS8uzppg?


How to prove $Tr(A)$ is sum of Eigen values of $A$

Question: If a matrix $A$ is Diagonalizable, then $\exists$ a Non singular matrix $P$ such that
$$D=P^{-1}AP$$  Now taking Trace on both sides
$$Tr(D)=Tr(P^{-1}AP)=Tr(APP^{-1})=Tr(A)$$
Now since $D$ is Diagonal matrix with diagonal elements as eigen values we have
$Tr(A)$ as Sum of eigen values of $A$.
But how to prove this if $A$ is not diagonalizable?
Comment: By extending the underlying field if necessary, we may replace the diagonal matrix $D$ with a matrix in normal Jordan form. Such a matrix is upper triangular, so again its diagonal entries are its eigenvalues.
Answer: What you can do is realize that the sum of eigen values is -(the sum of coefficients of $x^{n-1}$) in the characterestic polynomial. Now just see what the coeeficient of $x^{n-1}$ is while expanding the determinant of $xI-A$.( I assume A is a $n\times n$ matrix)


Triple boot, customize grub (Windows 8.1, Ubuntu, Zorin)

Question: I have a Win8.1 laptop. I installed Ubuntu, and had the installer put it on it's own 50MB partition. I installed Zorin and did the same.
I installed Grub Customizer on Zorin, and changed the list order.
When I rebooted, The order wasn't what I set it to.
So, I installed Grub Customizer on Ubuntu and did the same thing.
The header says "GNU Grub Version 2.02~beta2-9ubuntu1.7"
The list items are in this order:

Windows Boot Manager (on /dev/sda2)
Advanced Options for Zorin
Advanced Options for Ubuntu 14.04.3 LTS (14.04) (on /dev/sda6)
System Settings
Zorin
Ubuntu 14.04.3 LTS (14.04) (on /dev/sda6)

When I go back into Zorin and launch Grub Customizer, it agrees with this order. If I edit the order, save and re-boot, the order reverts to this.
I set my preferred order in Ubuntu and it seems to save, and it worked before I installed Zorin. But, the actual boot menu does not reflect the changes. If you follow my shorthand, I want the boot order to be W,Z,U,AOZ,AOU,SYSTEM. I also set a background image for GRUB in both customizers and neither one made the image display.
How can I verify which distro is actually in control of grub? How can I customize the boot order and appearance?
side note: All 3 OSs load correctly when selected.
Comment: Post the link to the Create BootInfo summary report. Is part of Boot-Repair:
https://help.ubuntu.com/community/Boot-Info And Summary report will not show the grub.cfg in /EFI/ubuntu, post that also, its UUID should be the UUID of your Ubuntu install.
Answer: I don't know if it is THE solution, or even the right solution, but my solution to the settings not being saved was to use "File->Install to MBR..."
My solution to the background image was to replace it with a PNG.
I did this in Zorin, not Ubuntu. My GUESS is that the latest installed OS has the preference, and writing to the MBR removes any doubt or ambiguity.


How to make fluid web site consistent

Question: I am redesigning my fixed-width web site to be (more) responsive and ran into some problems:
For one, I really like using a fluid width layout since a lot of visitors are using my web site in (much) bigger browsers than 1024px in width (currently minimum supported browser width). It just works well for the dashboard and statistics and tables with a lot of content - so I'm very happy with this part.
On the other side though I run into problems with sub-pages that contain less or condensed information. For example, input forms don't make any sense stretched all the way from left to right. Either the text input gets to wide or the input label moves too far away.
So I could just leave those pages as they are with a 960px width which doesn't look bad on its own but kind of breaks the user experience with other pages. Especially on one sub-pages with multiple tabs it just looks weird that the content width jumps from one tab to the next.
So here are my questions:
Is there a good way to get forms into a fluid layout?
Should I just mix fluid and fixed layout?
Is there a better solution?
Comment: Take a look at fluid grid systems in popular frameworks such as Bootstrap or Zurb; there are ways to make fluid form layouts behave properly.
Comment: How wide *is* your content?  You imply that the viewport you're accounting for is 1024px, but is your content taking up the entire horizontal space (minus a bit of margins)?
Comment: @cimmanon Well that's exactly the problem. Some pages really profit from a bigger viewport while others really don't need it since the content just isn't that wide
Comment: Do you have any concrete examples?  Outside of an oversized spreadsheet, I have a hard time imagining content that benefits from being 1024px wide (or more).
Comment: @cimmanon Graphs look nicer on a wide screen as well as my dashboard with 3 columns. And I have some tables with a lot of content (columns) as well that work better on a big screen.
Comment: Again, you're not very specific here.  What kind of graph?  A bar graph is just as effective when displayed horizontally as it is when it is vertical (have you looked at SVGs instead of images?).  Are you sure that you need *all* of those columns for your table visible at all times or is condensed version of the table with a link to more data an option?
Comment: @cimmanon Well I'm using different graph layouts that are based on SVG (highcharts.js). In the end I just want to take advantage of the space available. And sometimes that works well and sometimes there's not enough content to stretch it all the way so it actually doesn't make that much sense. So the question remains: How should I design those pages that don't *need* fluid layout while keeping the entire page consistent?
Answer: In the wake of mobile devices and wider support for media queries, liquid (or fluid) designs have largely become a thing of the past in favor of responsive design (refactoring your layout to fit a multitude of viewport sizes).
Why Responsive?
One of the major negative points against liquid designs in terms of user experience is that the content ends up being too wide to be read comfortably.  There have been many studies regarding line length, and the long lines of typical liquid designs on a very wide viewport cause eye fatigue.  Using media queries reduces this problem, as now you're free to say viewports X wide are 1-colum, viewports Y wide are 2-column, etc. to prevent your content from sprawling all over the place.
Note, however, that writing media queries based around "standard devices" is like painting yourself into a corner.  Plan for any sized device, you never know what is coming out next month or next year.

http://blog.cloudfour.com/the-ems-have-it-proportional-media-queries-ftw/
http://designshack.net/articles/css/responsive-design-why-youre-doing-it-wrong/
http://coding.smashingmagazine.com/2012/03/22/device-agnostic-approach-to-responsive-web-design/
http://alistapart.com/article/vexing-viewports

Alternatives
Media queries are excellent for making rules about how your layout should adapt to the size of the viewport, but they're weak when it comes to adjusting content layout relative to the size of its parent.  There are 2 very useful CSS modules on the horizon (they've been around for a while in most browsers, but IE doesn't support either until v10) that let you be responsive without media queries:

Flexbox (see also: What you need to know about the different Flexbox implementations)
Multi-column (newspaper/magazine style columns)

I have a collection of demos of them in action (many are solutions for SO questions): CodePen Naturally Responsive Collection
Forms that Fit
Forms are inherently responsive, as all form controls are inline.  The only way to make them non-responsive would be to mark them up (eg. via tables)/style them that way.
One thing to be very aware of is how forms behave on many handheld devices (eg. phones).  When focus is brought to an input or textarea element, the device zooms in to fit around that element (and if the device has a touch keyboard, the keyboard will take up the bottom half of the screen).  If your labels are to the left, they might not be visible to the user while they're trying to fill out the form.
Answer: You can use media queries in CSS to set the min and max width.
This could then allow you to produce a reusable grid for smaller elements and still have them behave responsively.
http://css-tricks.com/snippets/css/media-queries-for-standard-devices/

How to make fluid web site consistent


Lucian and Nami duolane

Question: I'm playing Nami support and i found the botlane Nami/Lucian very strong, but i'm wondering something.
If Lucian does the combo AA + Dash + reset AA + double AA, does he use all stacks of Tidecaller's blessing?
If the combo works, it is preferable to maximaze Ebb and Flow or Tidecaller's blessing?
He'll slows the enemies ADC or the support and you can Aqua Prison one of them.
If you don't know the name of Nami's skill, i give you a like to the wiki here.
Comment: yes all stacks used, max tidecallers
Comment: Thx for your answer ! I made a mistake i uped the other spell. It's very powerfull burst !
Comment: yea but blessing gives alot to lucian. need to practice timing it right though
Comment: @Brian Why not post that as an answer? :D
Comment: @cloudymusic i don't feel like keeping it updated/relevant across patches, feel free to use it and do it yourself though. Also this is my opinion others may benefit more from maxing ebb and flow
Comment: Posting an answer doesn't obligate you to be in charge of keeping it up to date, but up to you, I suppose.
Answer:
If Lucian does the combo AA + Dash + reset AA + double AA, does he use
  all stacks of Tidecaller's blessing?

Yes.

If the combo works, is it preferable to maximize Ebb and Flow or
  Tidecaller's blessing?

The problem with Lucian especially in the recent patches is his low range. He is constantly in danger's way and therefore, very susceptible to poke bot lanes (e.g. Caitlyn Lulu).
The burst potential for Tidecaller's blessing + Lucian's Kit is immense, but you have to consider :

Can Lucian pull it off? You're putting all the damage and work for the ADC, that 1 CC would break off all your damage. (Lulu's W, Annie's stun, etc.)
Are you at a position to be aggressive? Are you generally at an advantage?
Is the enemy bot lane a sustain comp? (Soraka's heal can nullify your whole combo)

There are some cases when you'd still want Nami to take Ebb and Flow for its powerful sustain.
TL;DR,
Tidecaller's is a pretty good skill to max if you're going to be aggressive (kill lane). Ebb and Flow is more for sustain lanes.

Lucian and Nami duolane


Rebase current branch to a previous commit version in GIT

Question: I am in my current branch say "feature/Sprint2"
With the following commits:

c1004
c1003
c1002
c1001
c1000

Now i want to update my current branch to c1002 and update the current branch..after which the commits will look like:

c1002
c1001
c1000

Whats the commands ?
Comment: You seem to want to *drop* the two most recent commits, which I wouldn't describe as an "update" or "rebase" but which can be done with `git reset HEAD~2 --hard`.
Comment: He didn't specify whether or not he wants to keep the code so telling him to do a hard reset may not get him to his desired goal in this situation. You also didn't tell him what that argument does which may have unintended effects.
Comment: I want to discard all commits prior to c1002
Answer: Since you didn't tell me your situation I will consider a couple cases and give you advice on what to do in those cases.
Case 1: You want to keep the code but drop the commits
git rebase -i <c1001 commit hash>
<change the pick to fixup for c1003 and c1004>
<save your text editor>
git push -f origin feature/Sprint2

Case 2: You don't want to keep the commits or the code
git reset --hard <c1002 commit hash>
git push -f origin feature/Sprint2

Comment: I want to discard all commits prior to c1002
Comment: In your post you said you wanted to discard all commits *after* c1002. Which one is it?
Comment: want to discard c1004, c1003
Comment: Then the second set of commands I gave you will achieve this.


Android: If/Else statement makes app crash

Question: I'm trying to tell if an android int is null by using If/Else
public void onClick(View v) {

            EditText min = (EditText) findViewById(R.id.EditText01);
            EditText max = (EditText) findViewById(R.id.maxnum);
            EditText res = (EditText) findViewById(R.id.res);

            int myMin = Integer.parseInt(min.getText().toString());
            int myMax = Integer.parseInt(max.getText().toString());

            String minString = String.valueOf(myMin);
            String maxString = String.valueOf(myMax);

            int f = (int) ((Math.random()*(myMax-myMin+1))+myMin);

            if (minString.equals(""))
            {
                // Do Nothing
            }

            if (maxString.equals(""))
            {
                // Do Nothing
            }

                res.setText(String.valueOf(f));

There are no any errors, but when I'm running the app its crashing when im pressing the button.
I'm also trying to use null instead of "":
if (minString.equals(null))
{
    // Do Nothing
}

if (maxString.equals(null))
{
    // Do Nothing
}

And i have a crash.
Please help me!!!
Comment: "android int is null". int can not be null
Comment: What does the logcat say?
Comment: Please post your LogCat output.
Comment: probably Integer.parseInt() that crashes if you try to parse a non number.
Comment: How to post a logcat output?
Comment: use logcat, e.g in terminal or through eclipse/android studio and edit your question. do you have the correct names on your EditTexts? Set the correct xml?
Answer:        do if (maxString == null )
    {
        // do something
      }

Comment: Then check your integer values and/or editText views. Are you using the correct editTexts ??
Comment: Also, you are writing the code in onClick() method. So usually we compare : if(v== btn1){ // my code here } Give me the error log.
Comment: I'm using  android:inputType="number"
Comment: Anything you write in EditText will give you string. The 'number' property is for keyboard type. copy paste your error Log please.
Comment: just press control,select the line and copy the error log and paste it here.
Answer: public boolean equals (Object object)

Compares the specified object to this string and returns true if they are equal. The object must be an instance of string with the same characters in the same order.
So its returning error so if you want to check if its null then use  == operator on the object.
if (maxString == null )

Use
        int myMin = 0;
        int myMax = 0;
        if(min.getText().toString()!="")
        myMin = Integer.parseInt(min.getText().toString());
        if(max.getText().toString()!="")
        myMax = Integer.parseInt(max.getText().toString());

        String minString = String.valueOf(myMin);
        String maxString = String.valueOf(myMax);

        int f = (int) ((Math.random()*(myMax-myMin+1))+myMin);

        if (minString.equals(""))
        {
            // Do Nothing
        }

        if (maxString.equals(""))
        {
            // Do Nothing
        }

Comment: I get the error around

myMin = Integer.parseInt(min.getText().toString());
Answer: int variables can't be null
If a null is to be converted to int, then it is the converter which decides whether to set 0, throw exception, or set another value (like Integer.MIN_VALUE)
So if you convert int to string again you cannot get null value.
Answer:   check = input.getText().toString();
 try {
    if (!check.equals("null")) {
        int max = Integer.parseInt(input.getText().toString());
        int constant1 = 1;
        int constant2 = 1;
        int nextNumber = 0;
        int count = 0;
        String fibResult = "";
        for (int i = 0; i <= max; i++) {
            fibResult += "F" + count + "=" + nextNumber + "\n";
            constant1 = constant2;
            constant2 = nextNumber;
            nextNumber = constant1 + constant2;
            count++;
        }
        dspResults.setText("\n" + fibResult);
    } else {
        dspResults.setVisibility(View.VISIBLE);
        dspResults.setText("Invalid");
        dspResults.setText(Gravity.CENTER);
        dspResults.setTextColor(Color.DKGRAY);
    }
} catch (IllegalArgumentException e) {
    e.printStackTrace();
}

Comment: here check is a string , and its been used as to check for the null value ,
pls help me to give a code which work for Null !
Comment: I am trying to do a simple Fibonacci code with switch statement,
i want to check the given edittext input string value is null or not ,
if not null then if statement code should execute otherwise else statements ,
The if statement code works fine , But if edittext given is empty or null  or "" then it does not executes the else statement ,
And it crash ,if not put in try block.
How can i make it work ?
Answer: public void onClick(View v) {

            EditText min = (EditText) findViewById(R.id.EditText01);
            EditText max = (EditText) findViewById(R.id.maxnum);
            EditText res = (EditText) findViewById(R.id.res);

            int myMin = Integer.parseInt(min.getText().toString());
            int myMax = Integer.parseInt(max.getText().toString());

            String minString = String.valueOf(myMin);
            String maxString = String.valueOf(myMax);

            int f = (int) ((Math.random()*(myMax-myMin+1))+myMin);
           {

            if (minString.equals(""))
            {
                // Do Nothing
                 res.setText(String.valueOf(f));
                  return false;

            }

            else if (maxString.equals(""))
            {
                // Do Nothing
                res.setText(String.valueOf(f));
                return false;

            }

             else
             res.setText(String.valueOf(f));

           return true ;
       }