Drupal and css related questions

Question: I have several CSS questions related to AT adaptive themes and how to improve this for a few sites. If I asked this question here I get feedback that they are not belonging here as it is not programming related. For me this reaction is very doubtfull and having a discussion about this does not solve the problem.
If I post these CSS questions in other forums (outside stockexchange) the first reaction I get back is: wauw whay a lot of css styles. Could you not simplify this? Or . you should post this question in drupal category. Answers Which are very logical if you don not understand the working of drupal architecture.
So how to deal with kinds of questions without getting voted down here.
- Is there are a anothere place where this should go?
- Should people voted the question up?
- Should I asked a moderater if the question is voted down?
Answer: Once the CSS has been prepared and sent to the client, there's nothing left for Drupal to get involved with, that's why such questions are off topic here.
CSS is a universal Language (sort of) and what applies to the markup produced by a Drupal site applies equally to the markup produced by any other method. There's nothing Drupal-specific about questions like these:

How do I make x look like y with CSS?
How do I find which CSS class or ID to target?

Those, and similar CSS-related questions, can be solved by learning the language and how to use browser dev tools to your advantage. Obviously those are not Drupal disciplines so covering them here would be going against the purpose of the site.
Stack Overflow is the right place to ask CSS questions, but you must remember that Stack Exchange sites are designed to be repositories of knowledge, not personal support forums. You mention that you've been asked Could you not simplify this?, and that's kind of the point....
An SE site is not somewhere you can post a link to your site, or an entire web page of styles let's say, and expect someone to dig through them all to find out what your issue is. It's too broad, there's too much room for ambiguity, and it simply doesn't make a good question for a Q+A site.
What you need to do is break the problem down into its smallest parts, and produce a small, self-contained example that demonstrates the issue. Don't get me wrong, this is a skill in and of itself, and one that takes a while to learn, but it's necessary to ask good programming questions (and those in closely related genres).
I'll try to address your individual questions as well:

So how to deal with kinds of questions without getting voted down here

Ask well researched, clear, on-topic questions in such a way that can be useful to future visitors of the site. This excludes questions about CSS/HTML syntax or general CSS/HTML development as already mentioned.

Is there are a anothere place where this should go?

As already mentioned the right place in the SE network is Stack Overflow. Beyond that I don't know where you'd ask about CSS, I tend not to stray too far from these walls for such help.

Should people voted the question up?

Not really possible to answer that, but if you want to look at it logically, then questions about CSS, which are off topic, should probably not be voted up, no.

Should I asked a moderator if the question is voted down?

Moderators have no say in how people use their votes so please don't raise flags for us to look into them, unless you suspect that one or more users are consistently targeting you with downvotes in a malicious manner.
Above all, read through the literature in the Help Center, that will give you a fuller idea of what this site is about, and the best way to use it. And, of course, raise individual concerns like this on the meta site, not on the main site itself.
Comment: That's right @Justme, when others ask you "could you not simplify this?" it means they're not prepared to spend the amount of time it would take to fully digest and understand all the code you're showing them. These people are volunteers, they don't have the time or motivation to learn every intricacy of your site to help identify one small CSS problem. The idea is that _you_ need to present your question is such a way that makes it easy for them to answer. For that you need a [SSCCE](http://sscce.org/)
Comment: One little thing to add: Of course upvoting offtopic questions makes no sense, but if, apart from being offtopic, they are not that bad, they shouldn't be downvoted either. On the other hand, dumping whole CSS files kinda *is* bad :(
Comment: Not on Stack Exchange I don't think, no. SO is about the closest to a CSS community you'd get because it's very nearly programming (and there are thousands of existing CSS questions there so we know they're acceptable).\
Comment: @Justme there are also [CSS questions on Webmasters](http://webmasters.stackexchange.com/questions/tagged/css), so at least some of them are acceptable there. As usual, read their help center firs.
Comment: Hi Molot, thxs for the answer. It is not me questioning "Could you not simplify this?" it is the answer of questions a post.
Comment: So in basic you say this is not the correct group as it is not drupal related and you say that stack overflow is the place for this. So in which community should it be posted then?
Comment: That's correct. If you feel that your question is of sufficient quality and detail for Stack Overflow, after reading their help center/about/etc to make sure, then that's the correct place to post it. It's not for me to tell you where you should post questions, I can just tell you what is and isn't on-topic on Drupal Answers, and point you in the direction of the literature of other sites to decide for yourself if your question would be suitable there.
Comment: Oke thanxs for your help. I understand this is not the place and where it is a good place on stack overflow is not know. There is no specifiek css comunnity for that.
Answer: As someone who downvoted and voted to close some of your questions I want to tell that Clive's answer nails it. We can't know all themes and their class / css structure. And after simplifying your problems, it's no longer Drupal in any way. It is, I'm afraid, a common misconception - not all things you see during Drupal development truly is Drupal related. As far as i remember there was similar issue with Programmers Stack Exchange - scope of this site changed over time, because less restrictive rules caused experts to go away. Hell, as far as I remember (sorry for lack of reference) someone even argued that making sandwiches is on-topic if they are meant to be eaten during coding. I know, I know, it is extreme case, but that's where "I see it with X so it is X question" can lead you. There is a long way from CSS to sandwiches, but I don't think we want to make even one step in that direction.
My votes to close were not meant as punishment. My downvotes kinda were - for apparent lack of own effort in making questions easier to answer, or lack of information about things already tried. But it was never personal. I don't say there was no effort on your part, only that particular question lacks that information.
Comment: Exactly: It's not that every problem I could find creating a Drupal site makes a question on Drupal Answers. I know that users could not know whenever a problem is caused by Drupal, but there is a topic for good reasons. Users should just not take a closure as something personal: Closing a question is not a punishment.
Comment: @kiamlaluno I have some closed questions, too. I don't mind. Especially duplicates - I really like how it can either show me already posted solution or explain by example where my question was unclear (if I believe it's not a dup but I failed to make differences clear to readers).

Drupal and css related questions


Steps for Using JavaBuilder with Java

Question: Can any one please tell me what are the steps for using JavaBuilder; to actually using Matlab Functions; with Java.
I've tried using JavaBuilder using its examples but I got the error as::
<code>Exception in thread "main" java.lang.UnsatisfiedLinkError: Failed to find the library mclmcrrt713.dll, required by MATLAB Builder JA, on java.library.path.
 This library is typically installed along with MATLAB or the MCR, its absence may indicate an issue with that installation or the current path configuration.
The MCR version that this component is trying to use is: 7.13.
</code>
What am I suppose to do to get rid of this error ?
Answer: The matlab support has a page about this, it might help you.
Why do I receive an error regarding missing mclmcrrt7x.dll when I run my stand-alone application compiled with MATLAB Compiler?
Comment: Did you check if you have the right version of the compiler installed?
Comment: Even after setting the path, I got the same error that Failed to find the library mclmcrrt713.dll.
Comment: I'm out of ideas then, sorry. It's difficult to solve problems like this without access to the computer in question.
Comment: actually settings were right. The problem was that I was suppose to restart the netbeans after setting the path variable..

Thanx for your help.. :)

Steps for Using JavaBuilder with Java


Homeowners Electric Permit - Mongomery County, Maryland, USA

Question: Our county allows homeowners to test to acquire permits for "rough wiring" and "heavy-ups" (https://www.montgomerycountymd.gov/DPS/Process/combuild/homeowner-electrical.html).
I did electronics/electrics in school, so believe I have the basis for knowledge that would be required to take this test, and they provide the National Electrical code for reference during testing.
However was wondering if anyone else had undertaken this test, or similar in their area, and could advise some resources for passing this exam?
Comment: To those who voted to close, I am not sure how asking about a resource for learning about a subject (books in the library was provided as such to date, which will be in circulation for years, if not centuries) fits with something that would become obsolete quickly.
Comment: I'm in the same county and I've read about that but not taken the test.
Answer: Sorry, you don't.  I also started in electronics... Very little of my experience was applicable to NEC code electrical.
Knowing how electrons are supposed to behave gives you a small edge.  But you must throw out all your existing knowledge about "how to do things" and allow yourself to grasp a different paradigm and ultimately the reasons why. Code does nothing without a reason.
You will find the codebook to be useless.  It's a book of law and is very poorly formatted to be a reference guide or learner.  It says so, flat-out, in Article 100.
So, are you ready to answer questions like this:
You are wiring a receptacle circuit in 12 AWG wire.  The circuit breaker and receptacles are rated for 75 degrees C.  The cable is UF, which is rated for 90 degrees C. Do you use a breaker size of

15 amps
20 amps
25 amps
30 amps

 20A.  The stuff about degrees C was a red herring, to make you turn to table 310.15b16, which is what you'd do when under the gun and flipping through NEC at the exam.

You are running six circuits in 12AWG UF (90 degree C) cable which all pass through a conduit 22" long.   What is the largest breaker you can use in these circuits?

15A
20A
25A
30A

 20A.   This situation comes perilously close to the 310.15b2a rule requiring a "50% derate off the wire's highest temperature column in 310.15b16, which is 30A at 90C" ... but the conduit is less than 24" so you dodge the rule.

You are wiring a new multi-wire branch circuit, featuring two hots and a shared neutral.   You only have one space remaining in the panel.  Which type of breaker is appropriate?

a duplex breaker
a quadplex breaker
a 2-pole breaker

 A quadplex.  A duplex is not appropriate for MWBC, and a 2-pole won't fit!

Select the minimum requirements for a Grounding Electrode System using ground rods:

one ground rod
two ground rods, or one if it passes the  test in NEC 250.24.
two ground rods
one ground rod, encased in concrete

 The last, 1 in concrete.  I played a trick on you, this answer is affected by a local amendment!

The point
None of these things have anything to do with electronic design. Life is different on the other side of the wall-wart!
The solution
I say with sincerity, electronics guy to electronics guy, to hit the library and thumb through some books on residential electrical.  Find one that speaks your language and devour it.  You will find many things that seem unimportant, like the above.   Then, browse a couple more and see what their takes are.
Then, spend a lot of time surfing this site, as it can backfill, expose you to common situatuons and give code refs, which books do not.  Mostly read existing questions (we're not big fans of hypotheticals unless it's a really good question).
Hopefully the test won't ask questions inapplicable to residences, which is what most of NEC is.
Some actually involving design
In 120V/240V split phase, a multi-wire (shared neutral) branch circuit has both its hot wires breakered 20A, but no breaker on the neutral.  Which condition causes the maximum (worst case)  current that could possibly flow on the neutral?

20A on both hots
20A on one hot, 10A on the other
20A on one hot, zero on the other

All the wires are in the same cable.  Among the above choices, which one results in the least total wire heating in the cable?
Sadly, even these basic thinkers won't be on the exam.
Comment: My comment is referring to the Montgomery County amendments pdf that Harper linked. It is scanned so searching doesn't work well. But scroll down until you find the part about grounding and you'll see it.
Comment: Fascinating. Though I think they should have used **principal** instead of **principle** in the section requiring the concrete encased electrode.
Comment: Can't find any word starting with the letters prin, per what I assume [manassehkatz](https://diy.stackexchange.com/users/69578) is [eluding to](https://diy.stackexchange.com/questions/156982/homeowners-electric-permit-mongomery-county-maryland-usa#comment262785_157018), but thanks Harper for such a detailed answer. If you're curious, I got 2 of the 4 questions you posed correct, and probably understated my understanding of electrics (I took those electronics courses in another country, so not sure what one knows/assumes US schools teach should apply to me). As I don't like wasting money...
Comment: ... I will take your advise and read up on electrician posts/find some books on the subject, instead of taking the test just yet. I would be interested if you could provide an answer, in your post above, to the question about maximum possible currently flowing along the neutral, and the least total wire heating, if you would please, so I can see if I am right also (might be helpful to others too).


How can I Fix a broken plastic screw hole

Question: One side of a plastic screw hole completely broke so the screw cannot screw on, is a way I can repair it?
I cannot add another hole because it's on a electronic keyboard
Comment: I'm voting to close this question as off-topic because it has nothing to do with home improvement.
Comment: A slightly larger screw will often do the trick.
Answer: If you can get to the screw hole, mix some quick setting epoxy and form it into a side. You'll have to keep forming it until it hardens. Maybe wrap some tape around the side that's not broken and make a "form" to put the epoxy in. Once it's cured, drill a hole for the screw
Comment: I would drill *and tap* the hole.  Epoxy can be tough and brittle.
Comment: @Harper-ReinstateMonica  Good point. Even the self threading screws for plastic would probably crack the epoxy.


How do you defeat the bounty hunter in full of stars?

Question: In the ios game Full of Stars, after you reach the slave destination, you get pursued by a bounty hunter who wants the slaves you're carrying (if you disagreed to give them up). Is there any faster way or technique to defeat this guy? Thanks
Answer: My strategy is stocking up iridium. What I do is make sure I have like 5000 iridium stored. I always either repair my shield to 20 or 50% because they can only bring down your shield to zero percent, then they have to attack again to kill your crew. Here's a list:

Stock up iridium(as much as you can! This can be done easier by getting it in Riftinity!)
Don't fill your shield all the way
Always use main cannon as soon as it's ready. In bad situations use iridium to make it fire right away. But remember it takes 4 turns to recharge. Main cannon does upwards to 40% damage.
Rapid gun fire is priority. This is why you need iridium. They do up to 20% damage.
If all else fails, repair your shield to 20%, and flee in the normal way.
If all else fails but you have resources to spare, use 10 iridium crystals to launch torpedos. Only in emergencies! I don't know how much damage it does, but emergency only!!


Connecting two pieces of metal curtain rod

Question: I have a curtain rod that has become disconnected in the middle. I am trying to figure out what kind of connector is used to join the two pieces of the curtain rod. There appears to be some kind of insert within each rod with threads.
Here is a photo of the curtain rod:

And here is the other side of the curtain rod.
Comment: what is your question?
Comment: How about a picture of the other piece of rod.
Comment: I added a picture of the other piece of the rod.  My question is what kind of connector can I use to reattach the rods to each other?
Comment: I should also add that the two sides of the rod are the same size.  There does not appear to be a way to insert one side of the rod into the other, which is why I assume there must been some kind of connector.
Answer: NEW info considering to your images...
** Your type of closet rod **
Your bar is horizontally held in place by a set screw which is located on the underside of the holder.
If the bar cannot reach two holders or walls to hold each end, then the rod cannot be held into position.
** A different type of closet rod **
Yes, there is a threaded insert. The insert of lobed.

Insert the smaller rod (with the insert) into the bigger rod.
Turn the small rod clockwise to tighten so that the small rod will not longer side in or out of the bigger rod.
Turn the small rod counter-clockwise to loosen.
After you understand, insert the rod into the closet, expand to desired length, and tighten.

Note: Do not over tighten or it will be very difficult to loosen and/or you may break/reshape the insert or the larger pipe. This is not a connection which slowly tightens. You will discover that the tight/loose difference is only about 1/4 turn.
Comment: Yes, I saw the threads too. You shall remove the rod on the first photo to expose the male part.


Display instruction as tooltip or popover

Question: I need help with some code.
I am building a web app to work on a tablet. Part of the app asks a number of questions, and also provides 3 answers, A,B, or C. Each answer has a brief instruction which I need to display as tooltip, or popover. However when I test tooltip on my ipad it requires two clicks to select the answer, one for the tooltip and for for the answer.
If there any type of tool that can do this in one, display instruction and answer question by selecting A, B or C?

       Is there an indication for the drug?

<input type="radio" name="indication" id="a1" value="0" <?php echo $a1; ?> required>A</input>

<input type="radio" name="indication" id="a2" value="0" <?php echo $a2; ?> required>B</input>

<input type="radio" name="indication" id="a3" value="5" <?php echo $a3; ?> required>C</input>

Comment: How do you feel about Jquery UI? Use the Popups that can be triggered when hovering or on a click.
Comment: could you give an example, I am not familiar with them
Comment: Working on it. Can you supply a bit more of an example of what data would be in the tip?
Comment: at the moment there are some text files, but the questions are a scoring system, each answer has a score attached to it. So if in question one 'C' is selected a score of 3 is passed to the table. Hope that helps
Answer: You can do this with JQuery Mobile. Working Example: http://jsfiddle.net/Twisty/1hd0phbL/
Your HTML:

        Is there an indication for the drug?

            <fieldset data-role="controlgroup" data-type="horizontal">
                <input type="radio" name="indication" id="a1" value="0" />
                A

Instructions for A.

                <input type="radio" name="indication" id="a2" value="0" />
                B

Instructions for B.

                <input type="radio" name="indication" id="a3" value="5" />
                C

Instructions for C.

            </fieldset>

Your JQuery Mobile:
$(function () {
    $("#Indication label").click(function () {
        //Get the ID that this label is for
        var ida = $(this).attr("for");
        // Get the Position for later
        var pos = $(this).offset();
        var ox = pos.left;
        var oy = pos.top;
        // Popup the correct tip
        $("#" + ida + "-popup").popup(
            "open",
            { x: ox+140, y: oy+50 }
        );
    });
});

Since Tablets can't mimic hovering very well, this combines the action of selecting the answer and bringing up the instructions in one click action.
Comment: thanks very much for the effort! greatly appreciated!
Comment: would there be any way of keeping A B and C on the same line?
Comment: Yes. Wrap them in `DIV` and use CSS to align.
Comment: Updated my working example. Wrap with `fieldcontainer` https://demos.jquerymobile.com/1.4.5/forms-field-contain/


Windows 10 will not boot after I deleted partitions

Question: I had win 10 installed on my SSD 240 Samsung hard drive and thought I was installing Ubuntu to my new M.2 hard drive that I just fitted to my Intel NUC to run along side each other.
At one point I was able to load both win 10 and Ubuntu from the Ubuntu boot menu. Then I got a bit carried away and decided to delete the partitions on my SSD Windows 10 hard drive. Since I have done that I cannot boot Windows 10 anymore. Ubuntu says that I only have Ubuntu installed on my computer.
I can see my files on the SSD through Ubuntu but it will not boot or give an option to boot? Can someone help please?
Comment: Possible duplicate of [How to recover a deleted NTFS partition with data](http://askubuntu.com/questions/171163/how-to-recover-a-deleted-ntfs-partition-with-data)
Comment: UEFI or BIOS. Best to see what is missing: Post the link to the Create BootInfo summary report. Is part of Boot-Repair:
https://help.ubuntu.com/community/Boot-Info But if you deleted Windows Boot partition, then link above to using testdisk should work.
Comment: i ran testdisk last night and it could not find the partitions on the drive. i really don't know what i have done. i can access the hard drive and see all he windows components on it etc. I ensured it was mounted and have backed up the data on an external hard drive. Would it be best to just format it and re-do?. Oh i did get an error on testdisc where it said "warning bad sectors" or something like that. i will run again and post , thanx
Comment: http://paste.ubuntu.com/14403576/                        here is the pastebin, can some one advise why i cant get this to fix?. i have tried installing a new windows via usb but get errors on every copy i try to boot.  by seond hard drive is saying "warning bad sectors when i try and boot into it. I can se al the files via ubuntu file view but i cannot get a windows to work. i dont mind wiping the drive and loading a new version of windows onto it, if only i knew how?.
Answer: Try this: https://help.ubuntu.com/community/Boot-Repair
Just burn Boot-Repair into a USB stick and then launch from USB
Comment: i tried that but doesnt work, paste bin above shows details


Pointers how it works when copied to another pointer

Question: Hey everyone.
#include <bits/stdc++.h>
    using namespace std;

    int main()
    {

        int* ptr1 = new int;

        int* ptr2 = ptr1;

        delete ptr2; // Detroying ptr2

        return 0;
    }

In the above case will the memory used by ptr1 will be freed or just the ptr2 will be destroyed.
I have one more doubt. I have a tree kind of structure in which the node is pointing to two children (These children have leaf nodes, Consider its a big tree). If I have to delete one child of the root node, Do I need to delete each pointer object of the grand children, grand grand children and so on?
Thanks in advance?
Answer: The int pointed to by both ptr2 and ptr1 will be freed.  The delete operator frees the object the pointer points to, not the pointer itself.  (The pointers remain after the delete but they are now "dangling pointers", pointing to memory that is no longer yours to use)
As for deleting a tree structure, yes, you will need to delete recursively, down to the leaves.  Typically this is done inside the destructor-method of your node-class and is quite easy (just call delete on each of your direct child nodes, which will cause their destructor-methods to execute and delete each of their children, and so on)
Answer: This part:
new int;

Is allocating memory for an int which is what will later be deleted. The location of that memory is the value of the pointer. You can have any number of pointers point to that memory, all of the pointers will have the same value. When that memory is deleted the value of the pointers is still the same, you just shouldn't dereference the pointers because they now point to deleted memory
#include <iostream>

int main() {
    int* ptr1 = new int;
    int* ptr2 = ptr1;

    // When I ran this the output was: 0x7fe835402a40 0x7fe835402a40
    std::cout << ptr1 << ' ' << ptr2 << std::endl;

    delete ptr1;

    // Output is still: 0x7fe835402a40 0x7fe835402a40
    std::cout << ptr1 << ' ' << ptr2 << std::endl;

    return 0;
}

As for your second question you do not delete pointers, you delete the memory they point to. If the later nodes have memory you want to free then yes, you will have to delete those recursively


Cover & sound-suppression for doorbell transformer in utility closet

Question: This transformer is installed in the utility closet of a 1970's condo.

Notice the wad of cut paper sheets pinched between transformer and the wall plate. This is an attempt at halting a low-tone humming caused by the transformer. Is there a better way to avoid this annoying hum?
And should a transformer be exposed in the open like this? If this is proper, are there covers available to hide the ugly and protect the wires?
Comment: *It is literally the job of a utility closet to contain 'ugly' utilities*. While I'm all for a neat panel, utility space is supposed to look industrial.
Comment: Asking more than one question in one post is frowned upon. That said, to answer the secondary question that shouldn't have been included: it's very common to see a doorbell transformer mounted like that. The transformer probably has a threaded conduit stub with a nut that holds it to the metal plate, with the line voltage wires hidden behind that plate. This isolates line voltage from low voltage (a code requirement). The low voltage is permitted to be exposed since it's basically harmless. If you cover it, make sure the cover has venting to let the heat out.
Answer: The best way to eliminate transformer noise is to purchase a quality transformer.
The noise is because the laminated core is heavily loaded or overloaded and the plates are actually vibrating because of eddy currents. I can't quite make out the size, but it looks like 24V, 20VA. I would bump it up to a 24V, 40VA unit that would be compatible with video doorbells and probably a lot quieter. Usually, hard mounting is fine unless the core is coming apart or overloaded so going to a new larger one fixes both problems.
Answer: First, even though the exposed wires are low-voltage, likely 16 VAC, they should be covered for esthetics (if the transformer were accessible to children, not inside a closet, it is likely required). That said, the buzzing noise is likely being transmitted to the metal plate and wall, which make it much louder. A few things to reduce the buzz:

Remove the transformer from the metal plate and reinstall it using rubber grommets in the mounting holes of the transformer and of the cover plate, but run a ground wire from the box to a mounting lug of the transformer. This would also reduce vibration of the plate cause by the transformers magnetic field, effectively making the plate act as a loudspeaker.
Put sound-deadening tape inside the metal box cover. Perhaps a local garage has a small left=over piece? Golf-club weighting tape might also work.
Install a replacement of the correct voltage and current or VA rating, in the hope it would be quieter. A similar transformer might be ~US$10.


Breaker box below electric meter

Question: I have an interesting question for anyone willing to answer. Below my electric meter outside there is a breaker box housing the 200 amp main shut off breaker as well as two 20A outside appliance breakers.
There are 3 2AWG aluminum wires leading to a barn about a hundred feet from house through 1.25" underground conduit. These three aluminum wires were not previously hooked up to any breaker on either end of run, but terminate in both breaker boxes. I have since installed two 60A breakers in both breaker boxes, one in the panel below the meter as well as one in the new breaker box in the barn as a main shut off.
The problem is that only one of the two hot wires in barn has power, leaving only one side of breaker box having power, leaving me with only 30A and 110V service at the barn. Are breaker boxes below meters typically only 110V? Any ideas of what could be the problem?
Comment: Obvious question, perhaps, but are all of the Al wires actually connected to the buses in the breaker box beneath the meter?
Comment: Is the 60-A breaker in the meter panel a 2-pole breaker? I have seen this type of electric panel before and in that case *all* of the breakers in the outside panel were 2-pole 240 v breakers for a/c, electric dryer, and electric kitchen range. All the breakers in the *inside* panel were 120 V. If you know how to do it safely, remove the dead front of the outside panel and check the voltage across the two poles of the 60-A breaker that feeds the barn.
Comment: I did not get to take off the dead front on the panel I described above to see how the two bus bars are arrannged. In my 45-year-old GE panel one has to note that 2-pole breakers won't work electrically and won't fit in *every* pair of adjacent slots. I have two columns of 8 one-half inch slots for branch circuits. The panel will not accept 2-pole breakers  in positions 1 & 2, but will in 2 & 3, not in 3 & 4, but will in 4 & 5 . . . The reason is that 1 & 2 are on the same leg, 3 & 4 are both on the other leg, etc. If you have to put in a new 2-pole breaker, note that the two poles must be opp
Comment: You say only one of the wires in the barn is powered leaving you with only 30 A and 120 V. The voltage between the powered hot and the neutral will be 120 V, but if you have a double pole 60-A breaker in the main panel, you will be able to draw 60 A. If both of the hots are powered and on different legs, you will be able to draw 60 A at 240 V. The barn connection is a sub panel and you do not need a second 60-A double pole breaker there, but only a means of disconnection (which the 60-A breaker will serve), but normally you'd have some smaller breakers in the barn (light, 120 V receptacles)
Answer: Sometimes panel manufacturers will have a null breaker slot on top, bottom, and/or both. Even though a double breaker seemingly fits right in like it's supposed to, only one phase will be hot.
A visual inspection of the busbar is one way to tell, or if you have the busbar layout diagram it will show too.
In case this is the problem, simply move the double pole breaker into the proper slot, then put a blank slot filler to cover the exposed parts.  If you don't have a blank handy a breaker with nothing on it is fine too.
Answer: I recently saw an example of the type of electric panel in which there are breakers in the panel outside below the meter, and there are breakers in the panel on the other side of the wall inside. In this instance, all of the breakers in the outside panel were double-pole 240 v breakers for a/c, electric dryer, electric kitchen range, and main breaker. All the breakers in the inside panel were single-pole 120 V.
The house where this panel was installed was a quality house and so I assume this must be an accepted type, but it strikes me as odd that one would have to go outside (maybe in rain or wind storm) to switch off the breaker to these appliances or to shut off the main breaker.
If you know how to do it safely, remove the dead front of the outside panel and check the voltage across the two poles of the 60-A breaker that feeds the barn.
Comment: Not only inconvenient for the owner, but seems like a lot of extra work for nothing for the electrician.  Really makes you go hmmmmmm

Breaker box below electric meter


Safety of Python 'eval' For List Deserialization

Question: Are there any security exploits that could occur in this scenario:
eval(repr(unsanitized_user_input), {"__builtins__": None}, {"True":True, "False":False})

where unsanitized_user_input is a str object. The string is user-generated and could be nasty. Assuming our web framework hasn't failed us, it's a real honest-to-god str instance from the Python builtins.
If this is dangerous, can we do anything to the input to make it safe?
We definitely don't want to execute anything contained in the string.
See also:

Funny blog post about eval safety
Previous Question
Blog: Fast deserialization in Python

The larger context which is (I believe) not essential to the question is that we have thousands of these:
repr([unsanitized_user_input_1,
      unsanitized_user_input_2,
      unsanitized_user_input_3,
      unsanitized_user_input_4,
      ...])

in some cases nested:
repr([[unsanitized_user_input_1,
       unsanitized_user_input_2],
      [unsanitized_user_input_3,
       unsanitized_user_input_4],
       ...])

which are themselves converted to strings with repr(), put in persistent storage, and eventually read back into memory with eval.
Eval deserialized the strings from persistent storage much faster than pickle and simplejson. The interpreter is Python 2.5 so json and ast aren't available. No C modules are allowed and cPickle is not allowed.
Comment: "The reason for doing this would make much more sense if I presented the larger context" Could you please elaborate on the problem? Currently the command seems utterly pointless - the same as doing nothing with `unsanitized_user_input`..
Comment: "we have thousands of these" That makes no sense.  Why would you store input that way?  There's no point in repr()ing a string for storage purposes.
Comment: Why aren't you using pickle or something simpler?
Comment: pickle is more than an order of magnitude slower and not necessarily more secure, if the docs are to be believed
Comment: I too am curious why the data is being repr-ed in the first place.
Comment: the data is repr'd to change the nested list structure into a string so it can be compressed and stored in a blob property
Comment: To ask the obvious question, is serialization/de-serialization time really a bottleneck, or are you engaging in premature optimization?
Comment: Good observation Nick, it is _not_ a bottleneck with the current number of users of the app and in fact the current actual cpu usage is very low, however after some load problems with my previous app I have tested with 1000 users and unfortunately the serialization does become quite the bottleneck at that point. However there may never be that many real users, it is always a guessing game
Answer: It is indeed dangerous and the safest alternative is ast.literal_eval (see the ast module in the standard library). You can of course build and alter an ast to provide e.g. evaluation of variables and the like before you eval the resulting AST (when it's down to literals).
The possible exploit of eval starts with any object it can get its hands on (say True here) and going via .__class_ to its type object, etc. up to object, then gets its subclasses... basically it can get to ANY object type and wreck havoc. I can be more specific but I'd rather not do it in a public forum (the exploit is well known, but considering how many people still ignore it, revealing it to wannabe script kiddies could make things worse... just avoid eval on unsanitized user input and live happily ever after!-).
Answer: If you can prove beyond doubt that unsanitized_user_input is a str instance from the Python built-ins with nothing tampered, then this is always safe. In fact, it'll be safe even without all those extra arguments since eval(repr(astr)) = astr for all such string objects. You put in a string, you get back out a string. All you did was escape and unescape it.
This all leads me to think that eval(repr(x)) isn't what you want--no code will ever be executed unless someone gives you an unsanitized_user_input object that looks like a string but isn't, but that's a different question--unless you're trying to copy a string instance in the slowest way possible :D.
Comment: That's exactly right; I definitely don't want anything in the string to be executed. The reason for doing this would make much more sense if I presented the larger context but I tried to simplify the scenario for the question.
Answer: With everything as you describe, it is technically safe to eval repred strings, however, I'd avoid doing it anyway as it's asking for trouble:

There could be some weird corner-case where your assumption that only repred strings are stored (eg. a bug / different pathway into the storage that doesn't repr instantly becmes a code injection exploit where it might otherwise be unexploitable)
Even if everything is OK now, assumptions might change at some point, and unsanitised data may get stored in that field by someone unaware of the eval code.
Your code may get reused (or worse, copy+pasted) into a situation you didn't consider.

As Alex Martelli pointed out, in python2.6 and higher, there is ast.literal_eval which will safely handle both strings and other simple datatypes like tuples.  This is probably the safest and most complete solution.
Another possibility however is to use the string-escape codec.  This is much faster than eval (about 10 times according to timeit), available in earlier versions than literal_eval, and should do what you want:
>>> s = 'he\nllo\' wo"rld\0\x03\r\n\tabc'
>>> repr(s)[1:-1].decode('string-escape') == s
True

(The [1:-1] is to strip the outer quotes repr adds.)
Answer: Generally, you should never allow anyone to post code.
So called "paid professional programmers" have a hard-enough time writing code that actually works.
Accepting code from the anonymous public -- without benefit of formal QA -- is the worst of all possible scenarios.
Professional programmers -- without good, solid formal QA -- will make a hash of almost any web site.  Indeed, I'm reverse engineering some unbelievably bad code from paid professionals.
The idea of allowing a non-professional -- unencumbered by QA -- to post code is truly terrifying.
Answer:
repr([unsanitized_user_input_1,
      unsanitized_user_input_2,
      ...

... unsanitized_user_input is a str object

You shouldn't have to serialise strings to store them in a database..
If these are all strings, as you mentioned - why can't you just store the strings in a db.StringListProperty?
The nested entries might be a bit more complicated, but why is this the case? When you have to resort to eval to get data from the database, you're probably doing something wrong..
Couldn't you store each unsanitized_user_input_x as it's own db.StringProperty row, and have group them by an reference field?
Either of those may not be applicable, since I've no idea what you're trying to achieve, but my point is - can you not structure the data in a way you where don't have to rely on eval (and also rely on it not being a security issue)?
Comment: One reason is that the strings need to be compressed to fit in App Engine's 1MB entity limit, and I thought the overhead of compressing 1000s of strings individually would probably be much higher than serializing them, compressing them all together, and putting them into a blob. The space savings would probably be less too.

But it's a good point... I'm definitely looking for ways to avoid eval without increasing running cost too much.


Complex projective manifolds and holomorphic mappings

Question:
Let $X\subset\mathbb{P}^2$ be a complex manifold defined by a homogeneous polynomial of degree $d>3$. Let $$\phi:\mathbb{P}^1\rightarrow X$$ be a holomorphic map. Show that $\phi$ is constant.

Let $\mathcal{O}_{\mathbb{P}^n}(-1)$ be the Tautological line bundle on $\mathbb{P}^n$. We know the following facts:

The Canonical line bundle of X is the restriction of $\mathcal{O}_{\mathbb{P}^2}(d-2-1)=\mathcal{O}_{\mathbb{P}^2}(d-3)$ to $X$.
The Canonical line bundle of $\mathbb{P}^1$ is $\mathcal{O}_{\mathbb{P}^1}(-2)$.

From this we can conclude that $X$ and $\mathbb{P}^1$ are certainly not isomorphic.
Now the problem is solved straightforwardly by means of the Riemann-Hurwitz formula:
if $\phi$ is non constant then the genus of $X$ is less or equal the genus of $\mathbb{P}^1$, which is zero.
Thus $g_X=0$, and we know this implies $X$ to be isomorphic to $\mathbb{P}^1$. This is a contradiction.
My goal is instead to solve the problem without using the theory of Riemann Surfaces but by means of other methods, e.g. the properties of holomorphic mappings.
Answer: Claim: If a non-constant holomorphic map $$\phi:\mathbb{P}^1\rightarrow X$$ exists with $X$ a hypersurface in $\mathbb{P}^2$ of degree $d$, then $d \le 2$ and $\phi$ is biholomorphic.
First, I prove that the existence of $\phi$ implies that $X$ is biholomorphic to $\mathbb{P}^1$: The holomorphic map $$\phi:\mathbb{P}^1\rightarrow X$$ is surjective: The image is compact, hence closed. In addition, the image of a non-constant holomorphic map of one variable is open.
Being surjective, $\phi$ induces an inclusion
$$\phi^*: \mathscr{M}(X) \longrightarrow \mathscr{M}(\mathbb{P}^1) $$
of the corresponding function fields. The field extension $\mathscr{M}(\mathbb{P}^1)$ of $\mathbb{C}$ is pure transcendental with transcendence degree $1$. By Lueroth's theorem every subfield, which properly contains $\mathbb{C}$, is pure trancendental, too. Hence
$$\mathscr M (\mathbb{P}^1) \cong \mathscr{M}(X) $$
from an abstract point of view. As a consequence, a bimeromorphic map
$$X \longrightarrow \mathbb{P}^1$$
exists. In general, a meromorphic map is defined outside an analytic subset, which has codimension at least 2. Hence the bimeromorphic map is already biholomorphic.
Secondly, I prove that a hypersurface in $\mathbb{P}^2$ of degree $d > 2$ is not biholomorphic to $\mathbb{P}^1$: The hypersurface $X$ is the zero-variety of a section $s \in H^0(\mathbb {P}^2, \mathscr{O}_{\mathbb {P}^2}(d))$ according to the following exact sequence of sheaves
$$ 0 \longrightarrow \mathscr O_{\mathbb{P}^2}(-d) \mathop{\longrightarrow} \limits^{s} \mathscr O_{\mathbb{P}^2} \longrightarrow \mathscr O_X \longrightarrow 0$$
The long exact cohomology sequence contains the following segment
$$ H^1(\mathbb {P}^2, \mathscr{O}_{\mathbb {P}^2}) \longrightarrow H^1(X, \mathscr{O}_X) \longrightarrow H^2(\mathbb {P}^2, \mathscr{O}_{\mathbb {P}^2}(-d)) \longrightarrow H^2(\mathbb {P}^2, \mathscr{O}_{\mathbb {P}^2})$$
The cohomology of projective spaces is well-known. Hence
$$H^1(X, \mathscr{O}_X) \cong H^2(\mathbb {P}^2, \mathscr{O}_{\mathbb {P}^2}(-d))$$
and $H^1(X, \mathscr{O}_X) \neq 0$ for $d > 2$, but $H^1(\mathbb {P}^1, \mathscr{O}_{\mathbb {P}^1}) = 0$, q.e.d.
One question: In my opinion the proof using Riemann-Hurwitz formula is fine. Why do you want to avoid it?


Using Google docs API for OCR in android

Question: I am trying to develop an android app which uses OCR. The app should be able to scan business cards and other documents to pull the content.
Is it possible to implement this using Google Docs Api?
How do I do it?
Answer: The Google Documents List API allows to upload PDFs or images and automatically perform OCR to extract their text.
Comment: example ? needed  ?
Answer: You may use Tesseract. It's powerful library and it has java wrapper Tess4jtoo.
Answer: you can use Google Cloud Vision API. its free for 1-1000 units/month. you can check pricing here
Answer: maybe you will find OpenCV useful. It's a powerful native library with an Android wrapper.


celery workers unable to connect to dockerized redis instance using Django

Question: Currently have a dockerized django application and intended on using Celery to handle a long-running task.
BUT Docker-compose up fails with following error:
[2018-12-17 17:25:59,710: ERROR/MainProcess] consumer: Cannot
connect to redis://redis:6379//: Error -2 connecting to redis:6379.
Name or service not known..

There are some similar questions concerning this on SOF but they all seem to focus on CELERY_BROKER_URL in settings.py, which I believe I have set correctly as follows
CELERY_BROKER_URL = 'redis://redis:6379'
CELERY_RESULT_BACKEND = 'redis://redis:6379'

My docker-compose.yml :
db:
  image: postgres:10.1-alpine
  restart: unless-stopped
  volumes:
    - postgres_data:/var/lib/postgresql/data/
  networks:
    - dsne-django-nginx
django: &python
  restart: unless-stopped
  build:
  context: .
  networks:
    - dsne-django-nginx
  volumes:
    - dsne-django-static:/usr/src/app/static
    - dsne-django-media:/usr/src/app/media
  ports:
    - 8000:8000
  depends_on:
    - db
    - redis
    - celery_worker
nginx:
  container_name: dsne-nginx
  restart: unless-stopped
  build:
  context: ./nginx
  dockerfile: nginx.dockerfile
  networks:
    - dsne-django-nginx
  volumes:
    - dsne-django-static:/usr/src/app/static
    - dsne-django-media:/usr/src/app/media
    - dsne-nginx-cert:/etc/ssl/certs:ro
    - /etc/ssl/:/etc/ssl/
    - /usr/share/ca-certificates/:/usr/share/ca-certificates/
  ports:
    - 80:80
    - 443:443
  depends_on:
    - django
redis:
  image: redis:alpine
celery_worker:
  <<: *python
  command: celery -A fv1 worker --loglevel=info
  ports: []
  depends_on:
    - redis
    - db
volumes:
  postgres_data:
  dsne-django-static:
    driver: local
  dsne-django-media:
    driver: local
  dsne-nginx-cert:
networks:
  dsne-django-nginx:
    driver: bridge

init.py :
from .celery import fv1 as celery_app

__all__ = ('celery_app',)

celery.py :
    from __future__ import absolute_import, unicode_literals
    import os
    from celery import Celery
    import fv1
    # set the default Django settings module for the 'celery' program.
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'fv1.settings')

    app = Celery('fv1')

    # Using a string here means the worker doesn't have to serialize
    # the configuration object to child processes.
    # - namespace='CELERY' means all celery-related configuration keys
    #   should have a `CELERY_` prefix.
    app.config_from_object('django.conf:settings', namespace='CELERY')

    # Load task modules from all registered Django app configs.
    app.autodiscover_tasks()

    @app.task(bind=True)
    def debug_task(self):
        print('Request: {0!r}'.format(self.request))

Where am I going wrong and why can't my celery workers connect to Redis?
Answer: your redis container does not list port 6379
Comment: adding the port in docker-compose fixed the issue, thank you


Bundling not working in MVC5 when I turn on release mode

Question: I have the following bundle configured in BundleConfig.cs:
bundles.Add(new StyleBundle("~/bundles/css").Include(
                      "~/assets/bootstrap/css/bootstrap.css",
                      "~/assets/css/global/all.css"));

and I reference it using the following:
@Styles.Render("~/bundles/css")

When I'm in debug mode (web.config compilation debug="true") it works as expected in that it renders both css files as normal ie:
<link href="/assets/bootstrap/css/bootstrap.css" rel="stylesheet"/>
<link href="/assets/css/global/all.css" rel="stylesheet"/>

However when I set debug="false" the above behaviour still occurs in that it does recognise the files, however it's just rendering them as normal.
To confirm bundling can definitely work I've enabled optimizations in BundleConfig ie BundleTable.EnableOptimizations = true;
Whenever I do the above, it bundles the css and appears as expected ie:
<link href="/bundles/css?v=WBKHkZAJly7jUzHrVDT8SwfaQE-CA9dbOUQUlLKadNE1" rel="stylesheet"/>

EDIT:
A few people have mentioned that adding the following code to my BundleConfig.cs file will achieve what I am after:
#if DEBUG
            BundleTable.EnableOptimizations = false;
#else
            BundleTable.EnableOptimizations = true;
#endif

I understand and appreciate this response, however according to the documentation, the default behaviour of MVC bundling is to bundle in release mode but not in debug mode. I don't see why I should need to add extra code to make it do this when it should be doing it already.
EDIT 2
I've a confession to make.  It turns out I had the web.config from the Views folder opened and not the main web.config.  I changed the setting in the main web.config and this works just fine for me. I blame ReSharper
Comment: Are you compiling with `RELEASE` or `DEBUG`?
Comment: I've tried with both, I've also deleted all of the debug binaries and pointed a live endpoint at my project using my hosts file
Comment: is this not a duplicate of this question http://stackoverflow.com/questions/15155344 ?
Comment: possible duplicate of [Running an ASP.NET MVC 4 app in release mode does not bundle and minifiy the js files](http://stackoverflow.com/questions/15155344/running-an-asp-net-mvc-4-app-in-release-mode-does-not-bundle-and-minifiy-the-js)
Comment: no, that's not the case, I'm not using transforms via web.release.config or web.cdebug.config
Comment: Manually setting the `` to ``. Maybe this can be a workaround.
Comment: thanks, see my latest edit
Answer: This is the default behavior.

Bundling and minification is enabled or disabled by setting the value of the debug attribute in the compilation Element  in the Web.config file.

<system.web>
    <compilation debug="true" />

</system.web>

To enable bundling and minification, set the debug value to "false". You can override the Web.config setting with the EnableOptimizations property on the BundleTable class. The following code enables bundling and minification and overrides any setting in the Web.config file.

public static void RegisterBundles(BundleCollection bundles)
{
    bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                 "~/Scripts/jquery-{version}.js"));

    // Code removed for clarity.
    BundleTable.EnableOptimizations = true;
}

http://www.asp.net/mvc/overview/performance/bundling-and-minification
Comment: yeh this is my problem, the EnableOptimizations overrides the web.config but I don't want to have to override the web.config and use the default behaviour, which doesnt seem to work
Comment: When you set your compilation to "release", does your JavaScript get minified or not?
Comment: I get exactly the same behaviour as the style bundles
Comment: Does the style bundles get minified in release mode? or not?
Comment: this **answer works** as mentioned [here](http://stackoverflow.com/a/22515066/2218697) , i have changed the `web.config` to ``  and in `BundleConfig.cs` added `BundleTable.EnableOptimizations = true;`
Answer: The way that I get around this is to force it in the BundleConfig to do exactly what I want it to do. I don't think MVC4 had the same options with the config file (or I just never got them to work).
So this is what I have at the end of my RegisterBundles method:
#if DEBUG
BundleTable.EnableOptimizations = false;
#else
BundleTable.EnableOptimizations = true;
#endif

This way it's always there, plain to see. However, you do have to remember to put that in there when you're starting up the project, but that's not a huge deal.
If you're not familiar with these, the #if DEBUG is a preprocessor directives that tells the CLR to do what is in that block when the DEBUG build parameter is present (should only be present in DEBUG mode, though that can be changed from the Project Properties). If that variable is not present (Release mode, or any other mode), then it will do the other block.
Comment: "It is meant to do this as the default". If it's not doing that by default, then make it. If the steps in Tjaart's answer aren't helping you (setting it up to do that by default), then override the default.
Comment: I know, I understand that. I've never seen it work the way it's "supposed" to, though I haven't worked with MVC5 too much. There has to be some setting that is incorrect, and you haven't included all of that in your question. Unfortunately, that would also bloat your question far too much, and reduce readability. If you're able to spend the time to figure out what setting is wrong, then awesome! I just personally get it to work, especially when it's such a minor fix.
Comment: I like this approach because it is clear and easy to understand by the next developer coming along to take over the code.  Thanks for posting!
Comment: I understand this will work, however in the documentation it is meant to do this as default
Comment: What I'm saying is, according to the documentation, the default behaviour of MVC bundling is to bundle in release mode but not in debug mode.  I don't see why I should need to add extra code to make it do this when it should already.
Answer: The default Release Web.config transform removes the debug attribute like so:
<compilation xdt:Transform="RemoveAttributes(debug)" />

However, this will not cause the expected bundling behavior to occur. Instead, you must create a transform that literally sets the debug attribute to "false", like so:
<compilation debug="false" xdt:Transform="SetAttributes" />

Answer: Another possible issue is that inside of your Global.asax.cs file in the Application_Start() method, you're missing the call to your BundleConfig.
For example, assuming your method is using the default name RegisterBundles(BundleCollection bundles) then inside of your Global.asax.cs file, you'll want to add BundleConfig.RegisterBundles(BundleTable.Bundles); in the Application_Start() method.
So your Global.asax.cs file might look something like this:
using System;
using System.Collection.Generic;
using System.Linq;
using System.Web;
using System.Http;
using System.Mvc;
using System.Routing;
using System.Optimization;

namespace MyProject
{
    public class MvcApplication : System.Web.HttpApplication
    {
        AreaRegistration.RegisterAllAreas();

        WebApiConfig.Register(GlobalConfiguration.Configuration);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);

        // ** This line right below might be what you are missing **
        BundleConfig.RegisterBundles(BundleTable.Bundles);

    }
}

Answer: I had this problem when I changed the css folder. My problem was that I changed the BundleConfig file for css files:
BundleConfig.cs:
bundles.Add(new StyleBundle("~/Content/css").Include(
                      "~/Content/css/bootstrap.css",
   ....

Views included:
@Styles.Render("~/Content/css")

For some reason, this didn't worked. 'bundles' seems to be a keyword or something (not sure). You must left it this way:
bundles.Add(new StyleBundle("~/bundles/css").Include(
                      "~/Content/css/bootstrap.css", ...

Views:
...
@Styles.Render("~/bundles/css")
...

I have no need to modify 'BundleTable.EnableOptimizations' nor web.config nor anything else.
Hope this helps someone.
Comment: The name you give the bundle needs to be something that doesn't match an actual directory that exists.  If a directory exists, then IIS is going to apply security checks before allowing access and often will return a forbidden 403 error.  'bundles' isn't a keyword, it is just easier to recognize what this is when referencing it because I never use a 'bundles' folder in my solution.
Comment: Good point. I have run into this problem many times and I had no idea why I didn't worked. You helped me a lot! Thanks!
Answer: After fighting against this issue for several hours, I recommend that you try this as well:

Add this at the very beginning of the view you are using your bundle:
@{
    BundleTable.EnableOptimizations = true;
}
Reset IIS
Reload your page and check if minify works

In my case somewhere in my solution was changing "BundleTable.EnableOptimizations" from true to false. When I force that to TRUE right before the bundle is used, I got this working.
After I noticed it works, I moved that into a static method at my BundleConfig class:
public static void EnableOptimizations()
{
    #if DEBUG
        BundleTable.EnableOptimizations = false;
    #else
        BundleTable.EnableOptimizations = true;
    #endif
}

So I can call it from the view and have it minify disabled for developers
@{
    BundleConfig.EnableOptimizations();
}

Answer: Make sure that you do not have any minified file in you BundleConfig class,
e.g   bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include("~/Scripts/js/popper.min.js"));
Instead use   bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include("~/Scripts/js/popper.js"));
Answer: In addition to all other replies, if you still cannot bundle your CSS and JS files, be sure that you are addressing the correct paths and/or folder/file names.
In my case, some of the files I'm addressing are actually missing, and some has typo while addressing. After you correct these kind of things bundle should work properly.
Lastly, if you have references via relative paths on your CSS or JS files (e.g. url(../../css/img/loading.gif)), you might want to turn them into absolute paths (e.g. url(/Content/css/img/loading.gif)) otherwise they won't be worked or rendered eventhough files are successfully bundled. Relative paths in bundle show differences from browsers' point of view.
Answer: <compilation debug="true" targetFramework="4.5.2" />

solve my problem.
debug=true was missing in my web config while publishing.
Comment: if you set debug=true then bundling will not apply.


Filereader.Onload fired too early

Question: I try to read files uploaded by a input type file (multiple). The code is the following:
$(document).ready(function() {
  $('#convert').on('click', function() {
     var files=$('#files')[0].files;
     if (!files) return;
     for (var i=0; i<files.length; i++) {
       var file=files[i];
       fr = new FileReader();
       fr.onload = (function(received) {
         var note=$(fr.result);
       });
       fr.readAsText(file);
     }
  });
});

Now my problem is:
The "onload" - function is called even before the file is loaded. note never has any content. But when I put a breakpoint just before the note - line and wait a while, note gets the content.
So it seems, the onload()-event is called too early. What can I do about that?
(Browser is Chrome)
Answer: I replaced fr.result by this.result:
fr.onload = (function() {
  var note=$(this.result);
});

That did the trick
Answer: You are making fr a global variable and at the time the onload fires it will be a different object than you expect due to the loop
Try wrapping it in an IIFE to create a closure and making fr a local variable
for (var i = 0; i < files.length; i++) {
  (function(file) {
    var fr = new FileReader();
    fr.onload = function(received) {
      var note = $(fr.result);// not sure what intent is here
    };
    fr.readAsText(file);
  })(files[i])
}

Filereader.Onload fired too early


Heronian triangles

Question: How to prove that all Heronian triangles can be found using formulas described here?
I understand that the described substitution will give Heronian triangle, but how to prove that using the described substitution will give all Heronian triangles (with scaling solutions, for example $(12,10,10)$ is obtained when multiplying $(6,5,5)$ by $2$)?
Comment: [This](http://www.gutenberg.org/files/20073/20073-pdf.pdf) appears to be the Carmichael publication referred to in the Wikipedia article.
Comment: Perhaps related: http://math.stackexchange.com/questions/114112/heronian-triangle-generator
Answer: Well, understanding that Heronian triangles are cyclic is a start. So the scaled up($\times n$, say) version of a Heronian would fit precisely into a circle of twice the diameter.
Comment: What do you mean, "Heronian triangles are cyclic"? Every triangle, Heronian or not, can be inscribed in a circle.

Heronian triangles


How to cut a straight line for conduit between floors

Question: I am going to run conduits for Ethernet from the walls of my 1-story house to the basement below. How do I measure and cut in a straight line such that the hole I open in the wall lines up with the hole I open up in the floor below?
Comment: FYI for potential answers: I'm doing my best to break down my [closed question](https://diy.stackexchange.com/questions/282644/best-practices-for-running-data-conduits-through-basement) into more specific bites, but my lack of experience might lead me to create an XY problem.
Answer: Usual practice is to find the studs, cut a hole the size of your box or low voltage ring, have a look through the hole with a light and a mirror (or a cell phone camera and flash, or  borescope camera - looking for things to avoid when drilling) and drill down into the basement from there.
If trying to work from both ends, you need to measure with care from landmarks you can positively locate on both sides of the floor. Which is easier said than done, unless there's something already passing through the bottom plate of the stud bay you are in.
Answer: You use a flex auger bit, available in various lengths up to about 6'.  Cut a hole in the wall where your LV box will be and drill down through the bottom plate (and maybe top plate of the floor below if there is one).
Answer: You use a long, thin (say 1/8 or 1/16) drill bit. Then once you are sure both ends are where you want them, you use the small holes as the center of your new larger holes.
Answer: You don't (just) measure or cut both holes at once, you listen for someone rapping on the end of the 4' long drill bit on the 1st fl, that the business end is now somewhere behind the basement wall. Which means you need another guy.
Comment: Going up is no fun, but that's only necessary if the location in the basement is more important than the 1st fl, which would be unusual.


Am I able to install the codelite plugins package without uninstalling codelite?

Question: I have the most recent stable version installed (version 3.5.5375) but every time I try to apt-get install the codlite plugins it advises it will remove the codelite install.
Comment: How did you install codelite?. It looks like there is a missmatch between your codelite version and the plugins version. Maybe one is from the repositories and the other not?
Comment: Yeah there is. Is that an issue?
Answer: The codelite-plugins available in the Ubuntu repositories is older than the codelite version that you downloaded from their page. So you can't have both installed at the same time using the package manager.
The good news is that (in a superficial check) all the plugins available in the Ubuntu codelite-plugins deb, seems to be included in the codelite deb available from the official codelite page.
Note that using the version from the repos has some advantages, like automated updates.
The short answer: No, you can't mix the Ubuntu codelite packages with the official packages.


How to stop all idle EC2 instances using AWS Lambda

Question: I have been trying to detect and shutdown AWS EC2 instances that are idle (<10% CPU).
Lambda code (set with IAM role AmazonEC2FullAccess):
import boto3
def put_cpu_alarm(instance_id):
    cloudWatch   = boto3.client('cloudwatch')
    cloudWatch.put_metric_alarm(
        AlarmName          = f'CPU_ALARM_{instance_id}',
        AlarmDescription   = 'Alarm when server CPU does not exceed 10%',
        AlarmActions       = ['arn:aws:automate:us-east-1:ec2:stop'],
        MetricName         = 'CPUUtilization',
        Namespace          = 'AWS/EC2' ,
        Statistic          = 'Average',
        Dimensions         = [{'Name': 'InstanceId', 'Value': instance_id}],
        Period             = 300,
        EvaluationPeriods  = 3,
        Threshold          = 10,
        ComparisonOperator = 'LessThanOrEqualToThreshold',
        TreatMissingData   = 'notBreaching'
    )
def lambda_handler(event, context):
    instance_id = event['detail']['instance-id']
    ec2 = boto3.resource('ec2')
    instance = ec2.Instance(instance_id)
    put_cpu_alarm(instance_id)

Event pattern in Cloudwatch Rule
{
  "source": [
    "aws.ec2"
  ],
  "detail-type": [
    "EC2 Instance State-change Notification"
  ],
  "detail": {
    "state": [
      "running"
    ]
  }
}

Error I am getting,
[ERROR] KeyError: 'detail'
Traceback (most recent call last):
  File "/var/task/lambda_function.py", line 19, in lambda_handler
    instance_id = event['detail']['instance-id']

Expecting result:
Detect and stop EC2 idle running instances.
Comment: Any time you get an error like this print out what you're getting in the `event` - it's obviously not what you're expecting.
Comment: Why an autoscaling groups is not sufficient and you are building a custom solution?
Comment: What's the point of the lambda function exactly? To create a new alarm every time a new EC2 instance is created?
Comment: All this doesn't make any sense! You can create a cloudwatch alarm for the EC2 instance and when it's less than 10% for $time, stop the instance(select from EC2 actions in cloudwatch). Why do you need a lambda??
Answer: The event parameter passed to an AWS Lambda function contains multiple Records. You can see this by debugging the function with print(event).
Therefore, your code should loop through each Record:
def lambda_handler(event, context):
  for record in event['Records']:
    instance_id = record['detail']['instance-id']
    ...

Comment: Thanks for your reply. How are you able to debug the function inside the lamda console? I'm still getting a key error for 'Records'.
Comment: It appears the problem was that I needed permission with CloudWatch logs. I solved the problem by giving admin access to the lamda function. I'm going to scale back by removing admin and finding the right permission set needed.
Comment: Every AWS Lambda function should be assigned the `AWSLambdaBasicExecutionRole` policy. See: [AWS Lambda execution role - AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/lambda-intro-execution-role.html)


Hail hit my roof. Do I need to replace it?

Question: We had a hail storm last night. Some of the pebbles were about an inch in diameter, although most were smaller. I went up and took some pictures of part of the roof. Most of the shingles look ok, but some appear to be missing granules and some also have small pieces of the shingle missing.

There's more photos here: https://photos.app.goo.gl/WRFFCTTuBfHoRo2GA.
Do I need a new roof?
Answer: Yes
The granules (they're typically ceramic) act as UV protection and fire retardant. It's normal to lose these over time, but the shingle in your bottom picture looks to be missing as much as half its granules. Additionally, the larger the hail stone, the more likely it damaged the shingles themselves (1" hail stones are serious).
Most homeowners insurance will cover this type of damage, meaning you pay the deductible and get a new roof. The key here is I would not wait long to at least explore a claim on this, lest you be unable to prove it was hail that did the deed. This is one of those lesser known (and hard to notice) ways your roof can be seriously damaged. I would get at least two roofing companies out to examine it and verify the damage.
Comment: To be fair, it clearly doesn't look like a *new* roof, but at the same time it doesn't look so bad as to necessarily require *immediate* replacement.  If I were OP I'd carefully consider how old the shingles are, when they would have been planned for replacement, what insurance premium hit a claim would make, and would probably have it inspected by a good roofer before committing to any course of action.
Comment: @J... True, but the other thing to consider is that a claim now for insurance coverage to pay for a new roof, mitigation, or a proportional payment for the damage would likely be upheld, assuming the OP's coverage applies. If the OP does nothing at this time, it's unlikely that a claim filed when the roof actually starts leaking, assuming that's quite some time from now, is significantly less likely to be paid. I agree that the OP should look at the full economics of the situation and decide what is best for them.
Comment: The shingles will degrade much more rapidly due to direct exposure to UV.  I wouldn't spend more than a year or two actively investigating.  It isn't as bad as an immediate leak, but this damage is for your **entire roof**.  You're going to be leaking everywhere when it starts, and I can imagine it cascading really, really quickly (first leak will cause even more leaks as the material crumble and wash away from the flowing water).
Comment: Agreed, although the roofing has surely been compromised, the roof will not leak..., yet. It may take years, it may take less, but it will happen much sooner since the protective surface has been damaged
Comment: Definitely contact your insurance company to see how long after an event (ie Hail) occurs that you can still file a claim. It wasn't that long of a time period that I had a basement flood that I had to file a claim lest I'd be on my own for damages. YMMV.
Answer: My shingles have been replaced twice because of hail at ages of about 12 and 5 years. They didn't look very bad to me but the insurance inspector agreed and it was covered 100% both times. I am not a professional but I have put on two roofs. So, as has been said, you need a qualified inspector . After the hail storms we had many contractors come to the neighborhood to give free inspections . We got an inspector  recommendation from our insurance agent.
Comment: @user1177071 You let your insurance deal with that.  That's what they're for.
Comment: Be wary of the companies that chase storms. They're often the shoddiest to be found, and they'll disappear as soon as they reappear, so don't expect followup calls to go well.
Comment: Thanks for the reply. The roof was last replaced in 2004. So, it's about 15 years old. On the receipt, it says the shingles have a 30-year warranty. So, maybe the cost of materials will be covered.
Answer: Your roof has apparently taken damage, as you have documented.
Should you choose to not proceed with an insurance claim with this particular incident, and you have indeed taken damage, keep in mind that the next incident that damages your roof might cause issues with a future claim, should it necessitate an immediate repair.
What I mean is that if the damage from a future incident is in itself minor, but enough to tip it over the edge to require you to replace it, the insurance company might claim that since the damage caused in the last incident was only minor the roof shouldn't be covered by them - that the fault was a previous issue or a pre-existing fault.
I don't know if I'm explaining it well. What I'm trying to say is that not checking with a roofing professional and the insurance company to gauge whether it needs repairs now, might give the insurance agency a loophole to not process a future unrelated claim.
Comment: Contrapoint though, if you *don't* check you can claim ignorance of any issues if you need to make a claim in the future. I think you're more likely to be covered by insurance if you didn't know something was a problem than if you knew it was a problem and ignored it. For example, if you have a leak in your bathroom that you know about and ignore, when it finally causes massive structural damage, the insurer will blame you for not taking care of it. But if you didn't know there was a leak, then it is not your fault and they will cover it.
Comment: In my extensive experience with homeowner claims to insurance companies, they couldn't care less about your ignorance. Whether or not you know what you're entitled to has nothing to do with their decisions. In fact, they are likely banking on the fact that you don't know what you can claim. Never forget insurance companies are in it for the profit. (And I work for one, although not in the insurance part of the company.)
Comment: Thanks. I filed a claim today for it. They said a bunch of other households in my area also called about hail damage from the storm.


Can I legally add an outlet with 2 screws when the previous outlet was passthough with 4 screws?

Question: My existing wiring has 2 black and 2 white and a ground. One pair is obviously source. The 2nd pair passes to the next outlet.
The current outlet has 4 screws: black on one side and white on the other.
Now I need an outlet with USB ports, so I selected the Leviton t5633-w because of its high USB amperage.
It only has 1 set of screws.
Can I add a short piece say 4-6 inches to the black and the white so I can connect it to the single set of screws?
Therefore there would be 3 black wires wire nutted together, and 3 white.
Physically, it's clear I can do this. However, what does the US National Electrical Code say?
Comment: I hate in-wall USB power.  No matter how high you go in amperage and capabilities, the next phone you buy will need even more.  QC, QC2, QC3, PD.   That Leviton you chose will not charge ANY of my devices as fast as they are capable of being charged with the right charger.    It's actually not a very good USB charger at all.  15W per outlet max.  A 15W PD outlet is a joke.  Do yourself a favor, put in a regular AC outlet and buy good chargers.
Comment: The one to look out for is (usually) white one side, black and red the other - a sign of an MWBC, where both hots cannot connect to a single screw as there's 240V between them. Or else a half-switched outlet. Or just pay attention to if the hot side tab between screws is intact, or broken off (intentionally.) If the tab is there, nutting them with a pigtail won't cause problems.
Comment: @jay613 Well I know that these outlets ONLY provide 5v and not the other voltages expected by the PD,QC, or etc.  However, I just have a 5v 1000ma device so rather than using an outlet strip for 1 more device I am doing this.  Also the other outlets are not close enough.  Only someone who doesn't know any better would expect to quick charge their phone or tablet this way.  Sadly this is a lot of people.
Comment: @jay613 you wait, future houses will have 00 gauge wiring at 20v from a central PSU to USB outlets in every room :-)

No electrician required, unless they change the wiring code after shorts burn down houses.
Comment: @Rich That doesn't make electricians enough labor money, you will need a whole separate circuit breaker box for 20v with dual wiring all over your house.  Each outlet will have 2 set of wires one for 20v and one for 120/240 or etc.
Answer: Adding the short wire is called pigtails and it is code compliant so yes you can do this.
Pigtails are a superior way of making connections in my opinion. The pigtails do not add to the wire volume in the box.
Comment: Or rather, they don't add to the **calculated** wire volume in the box.
Comment: @Nelson A properly made pigtail will not come apart even if you pull on the wires.  In fact, you **should** be giving the wires a good pull-test *to make sure the pigtail is solid and won't come apart like this*.  Screws will also not come loose over time unless they weren't properly torqued to begin with.  Making electrical connections is not foolproof - it has to be done correctly.  If it's done poorly, it can fall apart.  If it's done well, it won't.
Comment: Gotta agree with Ed, once again.  In fact pigtailing is the best practice for all outlets.  At least the one you removed was using the screws and not the backstab connections. +
Comment: Pigtails don't come undone by itself unless something massively stupid was done, like you yanking on the wires. Screws can actually come loose over time, but it is still much better than backstabs, which are guaranteed to come loose.
Answer: The most important rule in NEC is 110.3(B), which requires you to follow labeling and instructions... which means read them.
In this case, that only makes things better, particularly the boldface in 4a and 4b.  These explain how to use Leviton's "back-wire" feature, which allows placing 2 wires under each screw.
Pay heed to the word "FIRMLY".  You really need to torque it like you mean it. You can tell if it's not tight enough, the wires won't pass a "pull test".
However, Code only requires you read and follow those instructions, it doesn't require you to use that splice technique.  If you want to use a pigtail and can correctly execute it, that is fine.
Remember to give a very firm "pull test" on the wire nut splices (hold the nut and pull each wire in turn, hard - if it pulls out that's a technique problem: refine).  And never, ever use tape on wire nuts to keep wires from falling out - that sets the stage for an arc fault creating a house fire.
Comment: I think this should be the accepted answer. Fewer points of failure means that the homeowner doesn't try to contrive a pigtail which relies on the holding power of electrical tape.
Comment: @cybernard Zeus is suggesting that pigtails can be more likely to fail simply because the homeowner who tasks themselves with constructing one may not be aware of the correct way to do it and may therefore concoct some sort of DIY pigtail splice made with tape or some such - had they not tried to swim out of their depth, in this case, and just used the backwire clamps instead we therefore avoid the situation of an untrained person potentially producing a substandard splice.
Comment: @cybernard Glad to hear you don't rely on electrical tape for pigtails! This page will be visited by thousands of people long after you've gotten use from this community.
Comment: +1 I really wish manufacturers would start making people use 110.14(D).  I mean, they even put a torque spec (14-18 in-lbs) for the side-wire configuration.  The least they could do is give a torque spec for the backwire method as well.  *"Torque it like you mean it"* always makes me cringe.  For some people it's still not going to be enough.  For the rest, it means stretched bolts and stripped lugs.  I'd go with the side-wire guidance and aim for the high side of 14-18 in-lbs in, personally.  A torque wrench is never a bad idea.
Comment: @MonkeyZeus How do pigtails require electrical tape?  I certainly didn't use any.  I am depending on the holding power of wire nuts.  In a sealed environment, that a person opens maybe once every 5 years maybe.
Comment: @Cybernard you are correct, that's just a boilerplate "PSA" statement anytime I talk about wire nuts.  It's not a reflection on you, it's precisely because these Q&A are found by many, many passive viewers.  You know to do it, but it would not even occur to many people to attempt a "pull test"; tapers feel lucky when it holds together at all lol.
Comment: @Harper-ReinstateMonica I saw a study, don't recall where now, but they found that most electricians got the torque wrong by hand - either too much or too little. In any case, this is about DIY, and I think especially for homeowners who aren't that practised at such things, a torque screwdriver is a really smart thing to use for a job like this.  It never hurts to do it right.
Comment: Could you please define "hard"?  I once stripped threads in a K-member after being told to pull the ratchet "as hard as I could".  Is "hard" 1, 5, 10, 20, 50 pounds force?
Comment: @Technophile that is too subjective to define.  Really if you are reading instructions, it should call out a torque. 14-18 inch pounds is apparently stated.  Now you just need to find one of the five electricians in the US who has actually taken their torque screwdriver out of the blister pack lol.
Comment: @Harper-ReinstateMonica  I was asking about the pull test, which (from its name) I would expect to involve a pull rather than a twist.
Comment: @Technophile my rule of thumb is "hold the sides of the nut without special tools or tricks, while pulling each wire in turn. Your ability to grasp the nut is limited, and that's the test limit.


ImageSharp get dominant color from a stream

Question: I'm trying to find an alternative to System.Drawing and ColorThief to be used in a docker container with Linux (because the prior mentioned have some issues).
So far I found this gist
But it seems to be on an older version since OctreeQuantizer had now a different constructor.
I've tried different approaches but most of the times I either always get FFFFFF or a null reference exception.
I get the NRE when I try new OctreeQuantizer(new QuantizerOptions { Dither = null, MaxColors = 1 }) which I thought might be the same as in the gist. I get always white when I play around with the QuantizerOptions.
I have little to no experience in image processing and ImageSharp, feels like I'm missing something.
tl;dr: trying to find the dominant color from a stream using ImageSharp.
Answer: I had the same issue. Solved using the code below. It is a bit hacky but works well for me.
using var image = Image.Load<Rgba32>(imageBytes);

image.Mutate(x => x
    .Resize(new ResizeOptions {Sampler = KnownResamplers.NearestNeighbor, Size = new Size(100, 0)}));

int r = 0;
int g = 0;
int b = 0;
int totalPixels = 0;

for (int x = 0; x < image.Width; x++)
{
    for (int y = 0; y < image.Height; y++)
    {
        var pixel = image[x, y];

        r += Convert.ToInt32(pixel.R);
        g += Convert.ToInt32(pixel.G);
        b += Convert.ToInt32(pixel.B);

        totalPixels++;
    }
}

r /= totalPixels;
g /= totalPixels;
b /= totalPixels;

Rgba32 dominantColor = new Rgba32((byte) r, (byte) g, (byte) b, 255);

// This will give you a dominant color in HEX format i.e #5E35B1FF
string hexColor = dominant.ToHex();


Why no 4x options for headers in CRC 2019?

Question: The California Residential Code (CRC) 2019 has a table of header sizes for various spans / building widths / roof loads: https://up.codes/viewer/california/irc-2018/chapter/6/wall-construction#R602.7
The size column list various combinations of double, triple and quadruple 2x materials (e.g. 2x8, 2x10, 2x12).
Why are there no 4x options (e.g. 4x8, 4x10, 4x12)? Does a different section of code cover that, and do they have different allowable spans?
Context: my local building department suggested I revise my plans from 'double 2x12' to 'single 4x12', and said "like the CRC requires". I'd like to comply with their wishes, but I'd like to fully understand them by reading them in the code. I'd prefer to use double 2x, as it's easier to get in place.
Comment: Just wondering if local building department has a stake in local lumber yard.  Can read this question/answers for some info about 4x to double 2x.  https://diy.stackexchange.com/questions/89117/why-mate-two-boards-instead-of-using-one-thicker-board
Comment: Suggest to your local building department that you'll be happy to comply when they show you exactly where in the CRC the table is located.
Answer: I can't speak to the CRC, so I'll respond more generally.
Four-by lumber is typically far more expensive than combinations of smaller lumber due to much lower sales volume, so LVL and other more stable and precise options become favorable.
Large timbers typically aren't milled to a precise size like standard lumber, nor will they usually be planed for safer handling.
Large timbers are much less stable than beams built from multiple components, so warping and checking are more likely.
Single-member beams aren't rated for as much load. By using multiple components the risk of weakness caused by a knots or other flaws is lessened.
Four-by timbers would need to be lifted into place as a unit, requiring more people or equipment. Beams constructed from several smaller members are more manageable.
For these reasons four-by timbers have become passé as beam options. It could be that they're simply not included because they're rarely considered appropriate.
Comment: Thanks. I agree with all the reasons to prefer 2x, but I'm not sure about "It could be that they're simply not included because they're rarely considered appropriate." There are so many other entries in that table - they had room a for a few more! Also, I see other references online about 4x being typical in CA.
Comment: @tom you do know the proper way to say "thanks" is to click the up-vote arrow, right?
Comment: @freeman. I chose not to upvote your answer as I don't think it actually answers the question, sorry. Your answer lists many valid cons for 4x material, however 4x headers seemingly are common in CA, so all those cons must be overridden by something. Hence the cons don't seem to be a good explanation for why 4x material is not listed in the code. Thank you for taking time to write an answer, it contains many true and useful statements, it just doenst answer the question.
Comment: Not my answer, @tom, but fair enough.
Comment: I'd like to hear more about "seemingly common". Have you seen them implemented in recent construction? Are they readily available in lumber yards and home improvement stores? I'm not sure why that would be the case there and not here in Minnesota. I'm closer to Canada than you are. :D


How to extract the values for a list of given tags in the xml value using re library?

Question: I'm trying to extract the values for a list of data types like string,int,char in a xml file. Apart from these data type tags there are other tags also.
For example there are 2 tags like the below
<string> GenIdeal </string>
 <int>88</int>

I've written the below code
re.findall(r"<string>(.*?)</string>", elem)

and its fetching only string values when tried with
re.findall(r"<int|string>(.*?)</int|string>", elem)

getting empty values.
Comment: Does this answer your question? [Regex select all text between tags](https://stackoverflow.com/questions/7167279/regex-select-all-text-between-tags)
Comment: Maybe you want both of values between  tag and  tag? If so, re.findall(r"(.*?) (\d+)", elem) will return both.
Comment: thanks for your response but either one data type will be there at one point of time and i need to store the value in a variable.
Comment: Use a proper xml parser it will make life much easier and makes extedning your code simpler in the future
Answer: To make your regex work just add regular parentheses around the logical alternative, so it will indicate literal:
import re

x="""<string> GenIdeal </string>
 <int>88</int> """

y=list(re.findall(r"<(int|string)>(.*?)</(int|string)>", x))

print(y)

Returns:
[('string', ' GenIdeal ', 'string'), ('int', '88', 'int')]

On the side note - if there's more complexity to your use case- consider using XML parser instead e.g.
https://www.geeksforgeeks.org/xml-parsing-python/
Or
https://docs.python-guide.org/scenarios/xml/


ASP.net MVC 4 Error when trying to delete a record

Question: I'm trying to delete a client record. The client contains an address and I guess I'm having issues with the order of deletion when it comes to their relationship.  Basically I want to delete a client and if they have an address, to delete that along with it.
This is the complete exception error message I get:

DbUpdateException was unhandled by user code
An error occurred while saving entities that do not expose foreign key
  properties for their relationships. The EntityEntries property will
  return null because a single entity cannot be identified as the source
  of the exception. Handling of exceptions while saving can be made
  easier by exposing foreign key properties in your entity types. See
  the InnerException for details.

Models
public class Address
{
    [Required]
    public int Id { get; set; }

    [DataType(DataType.Text)]
    [Display(Name = "Street Address")]
    public string StreetAddress { get; set; }

    [DataType(DataType.Text)]
    [Display(Name = "Postal Code")]
    public string PostalCode { get; set; }

    [DataType(DataType.Text)]
    public string City {get; set; }

    [DataType(DataType.Text)]
    public string Province {get; set;}

    public virtual Clients client { get; set; }

}
public class Clients
{
    [Required]
    public long Id { get; set; }

    [Required]
    [DataType(DataType.Text)]
    [Display(Name = "First Name")]
    public string FirstName { get; set; }

    [Required]
    [DataType(DataType.Text)]
    [Display(Name = "Last Name")]
    public string LastName { get; set; }

    [Required]
    [DataType(DataType.PhoneNumber)]
    [Display(Name = "Phone ")]
    public string PhoneNumber { get; set; }

    public virtual Address Address {get; set;}

    [Display(Name = "Email List")]
    public Boolean EmailList { get; set; }

    [DataType(DataType.EmailAddress)]
    [Display(Name = "E-mail")]
    public string Email { get; set; }

    [DataType(DataType.Text)]
    [Display(Name = "Hair Type")]
    public string HairType { get; set; }

   [DataType(DataType.MultilineText)]
    public string Description { get; set; }
}

Context Class
public class VolumeV2Context : DbContext
{
    public DbSet<GiftCard> GiftCards { get; set; }
    public DbSet<Clients> Clients { get; set; }
    public DbSet<Address> Address { get; set; }
    public DbSet<Inventory> Inventories { get; set; }

    protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Clients>()
            .HasOptional(j => j.Address)
            .WithOptionalDependent()
            .WillCascadeOnDelete(true);

       /* modelBuilder.Entity<Address>()
            .HasRequired(j => j.client)
            .WithRequiredDependent()
            .WillCascadeOnDelete(true) ;
        */

        base.OnModelCreating(modelBuilder);
    }
}

Client Controller Delete Method
[HttpPost, ActionName("Delete")]
    public ActionResult DeleteConfirmed(long id)
    {
        //find the client
        Clients clients = db.Clients.Find(id);

        //find the address
        Address address = db.Address.Find(clients.Address.Id);

        //  set the reference to null?
        address.client = null;

        //remove the address foreign key?
         clients.Address = null;

        //Apply to db?
         db.Entry(address).CurrentValues.SetValues(address);
         db.Entry(clients).CurrentValues.SetValues(clients);

        db.Address.Remove(address);

        //remove the client
        db.Clients.Remove(clients);
        //exception error happens here
        db.SaveChanges();
        return RedirectToAction("Index");
    }

Is there something wrong with my order or deletion ? or am I just not doing something right? I just want to have the ability to remove clients with or without an address.
Comment: plz post the inner exception you are getting on delete operation
Comment: sorry. I posted it now
Comment: when you get the exception copy the inner exception message and post it here
Answer: Remove the reference from an address to a client. Just keep your reference from a client to an address, that will do.


Liouville Theorem or Maximum Modulus Principle

Question: $f$ and $g$ are two analytic functions on set $\Bbb C$ of all complex numbers such that
$$f\left(\frac{1}{n}\right)=g\left(\frac{1}{n}\right)$$  for $n=1,2,3...$, then show that $f(z)=g(z)$ for each $z$ in $\Bbb C$.
Answer: Hint: The set of zeros of the analytic function $f - g$ has an accumulation point at $0$.
Comment: Is it possible to use Liouville's theorem or Maximum modulus principle in this problem?
Comment: I doubt that Liouville is at all applicable, since it's really a statement that has to do with the behavior at large $|z|$. And maximum modulus is usually easiest to use with boundary values. Why do you ask?
Comment: ok. Then please elaborate on your hint. I can't get past the hint
Comment: @prat If the set of zeros of an analytic function has an accumulation point, then the analytic function is in fact identically zero.


How casual friendly is The Secret World?

Question: I'm considering The Secret World as a new game to play, as the setting fascinates me. However, I'm hesitant to pick up a MMO, because the time I can invest in it is limited.
Can I enjoy all of the content in a reasonable amount of time, if I'm only able to spend ~10 Hours per week on the game?
Comment: Welp, if I committed that much time to a single game, I wouldn't call myself a casual at it.
Answer: The main story line assuming that you complete the main story quests and enough side quests to be sufficiently levelled to complete the main story quests will take about 40 hours of continual play approximately. Every quest in the main story line can be completed solo, although like all MMORPGs there is a benefit to playing in a party.
PvP is very much influenced by character progression, as having greater progression in the game will result in having more abilities available, thus doing more damage or healing. PvP is possible at low levels but having more ability points and better gear will yield better results in the battlegrounds.
There are "dungeons"/instances in game throughout the story which require group play and there is a random dungeon finder available in game to find groups:

Again, these instances are not required for the main story, although they are all tied into the main story.
In contrast, there are also instances in the game throughout the story which are enforced single player as well, in which you enter alone to complete a task. Again these instances are not required for the main story.
There is not much of a requirement to ever join a guild, with the content currently available in game. Obviously being an MMORPG the game is improved by playing with friends but even for the solo play the quest progression and story line are definitely a lot of fun.
Comment: Some of the main story quests are solo dungeons, even if you're in a party. The other members of your party will be given their own instance and you *can't* complete it together.
Comment: As of issue #2, there is now a LFG tool built into the game.
Comment: There is now a "Dungeon Finder" in the form of a third party addon called "Field Agent Locator", which is widely used by players. It can be found on Curse: http://www.curse.com/tsw-mods/tsw/field-agent-locator
Comment: Shift + C for the Group Finder tool


Where is the mistake in my attempts : $\cos(\arctan(-2)) ?$

Question: I want to calculate this simple problem

$$\cos(\arctan(-2))$$

My attempts,
$$\sin^2x+\cos^2x=1$$
$$\tan^2x+1=\frac1{\cos^2x}$$
$$\cos x= ±\sqrt{\frac1{\tan^2x+1}}$$
Then, I wrote $\tan x=-2$ where $x=\arctan(-2)$ then, I must find $\cos x=?$
I find $$\cos x=±\frac1{\sqrt5}$$ or $$\cos(\arctan(-2))=±\frac1{\sqrt5}$$
Where is the mistake in my attempts? Because the answer is $$\cos(\arctan(-2))=\frac1{\sqrt5}$$
Comment: You found the answer to the related question: if $\tan x = -2$, then what is $\cos x$?  If the tangent function were injective, this would be the same question; but tangent is not injective, so $\arctan z$ is selected in a specific way from among all solutions to $\tan x = z$.
Answer: You should take only the positive square root, because $\arctan(-2)\in\left(-\frac\pi2,\frac\pi2\right)$ and therefore $\cos\bigl(\arctan(-2)\bigr)>0$.
Comment: By definition, $\arctan$ is the inverse of the restriction of the tangent function to $\left(-\frac\pi2,\frac\pi2\right)$. Therefore,$$(\forall x\in\mathbb R):\arctan(x)\in\left(-\frac\pi2,\frac\pi2\right).$$
Comment: Yes. Besides what I wrote, what you did is just fine.
Comment: How can I prove  $\arctan(-2)\in\left(-\frac\pi2,\frac\pi2\right)$ ?
Comment: Thank you for explaining.
Comment: And is the method I am using correct?


Indeterminate form uniform convergence limit

Question: I have $$u_n(x) = \sqrt{\bigg(\frac{2}{3}x + \frac{1}{\sqrt[3]{n^2}}\bigg)^3} - \frac{1}{n}$$
$$u(x) = \sqrt{\bigg(\frac{2}{3}x\bigg)^3}$$
and $u_n(x) \rightarrow u(x)$.
I have to check uniform convergence in $[0, +\infty)$:
$$\sup_{x \in [0, +\infty)}|u_n(x) - u(x)| \rightarrow  ?$$
$u_n(x)$ and $u(x)$ have positive derivatives in $[0, +\infty)$, so their sup is $+\infty$, and I have an indetermined form $+\infty -\infty$ in the limit above.
I thought that I could consider $ \forall b > 0$: $$\sup_{x \in [0, b]}|u_n(x) - u(x)| = |u_n(b) - u(b)| \rightarrow 0$$
and then state that we have the same result in $[0, +\infty)$. Is it correct?
Any help would be very appreciated, thanks!
Answer: Hint. By Taylor expansion, for $n\geq 1$ and for $t>0$,
$$\bigg(t + \frac{1}{n^{2/3}}\bigg)^{3/2}=t^{3/2}\bigg(1 + \frac{1}{tn^{2/3}}\bigg)^{3/2}=t^{3/2}\bigg(1 + \frac{3}{2tn^{2/3}}+\frac{3}{8t^2n^{4/3}}+o(1/t^2)\bigg).$$
So, given $n\geq 1$, what is the limit (note that $t=\frac{2x}{3}$)
$$\lim_{x\to +\infty}|u_n(x) - u(x)|=\lim_{t\to +\infty}\left|
\bigg(t + \frac{1}{n^{2/3}}\bigg)^{3/2}-\frac{1}{n}-t^{3/2}\right|?$$
What is $\sup_{x \in [0, +\infty)}|u_n(x) - u(x)|$?
Comment: Not very confident using Taylor expansion (not an engineer here), but I have to admit it's always the fastest way. I got sup is $+\infty$, now I'll try to find another method.
Comment: @insane.user17 Yes, the $\sup$ is $+\infty$ and therefore the convergence is not uniform in $[0,+\infty)$.
Answer: The difference of two increasing functions is not increasing in general. In your case it is since the derivative of the difference.
$$(u_n-u)'(x)=\left(\frac23x+\frac1{n^{3/2}}\right)^{1/2}-\left(\frac23x\right)^{1/2}>0.$$
Since $u_n-u>0$ you get
\begin{align}\sup_{x\in[0,\infty)}|u_n(x)-u(x)|=\lim_{x\to\infty}(u_n(x)-u(x))=\lim_{x\to\infty}\frac32 \sqrt{\left(\frac23x+\frac1{n^{3/2}}\right)^{3}}-\frac32 \sqrt{\left(\frac23x\right)^{3}}-\frac1n
\\=\lim_{x\to\infty}\frac32\frac{\left(\frac23x+\frac1{n^{3/2}}\right)^{3}-\left(\frac23x\right)^{3}}{ \sqrt{\left(\frac23x+\frac1{n^{3/2}}\right)^{3}}+ \sqrt{\left(\frac23x\right)^{3}}}-\frac1n\end{align}
where we used $a^2-b^2=(a-b)(a+b)$. Now develop the cube and do some manipulations. After cancellations the numerator goes like $x^2$ and the denominator like $x^{3/2}$ so the limit should be...
Comment: the limit as $x\to \infty$ is $\infty$ so there is no need to send $n\to\infty$. You cannot have uniform convergence since $\sup|u_n-u|=\infty$.
Comment: since the function $u_n-u$ is positive and increasing, its supremum is exactly $\lim_{x\to\infty}(u_n-u)$. It's a theorem about increasing functions.
Comment: I'm not sure about the first equality, I think the sup is $\ge$ than the limit as $x \rightarrow +\infty$. And then I get the same result. Yes, I got the n-thing, thanks!