It is possible to wildcard for all distribution emails with GoDaddy?

Question: Title is the question. i.e. firstname.lastname@example.com, firstname.lastname@example.com, or any variation of distribution names to be sent to the a single forwarded email by using a wildcard, i.e. an asterisk *@example.com. It doesn't seem that it is possible, it seems they setup "catch all" for managing hosted exchange email lists.
Comment: Your question isn't clear.  Are you after how to set up a catch-all or are you just wanting to know how to forward the email addresses you create to a single address?
Comment: Correct.  However be warned...you WILL get spammed to death if you enable catch-all. And do not be tempted to start using random email addresses just because you can.  Because when you get spammed to death and decide to shut down the catch-all you are going to lose all those random addresses...trust one who fell for this many years ago and learned the hard way :P
Comment: I seemed to be overthinking this, the way their example in "catch all" is confusing based on my end goal, which is kind of the inverse of the example. "Catch all" does what i'm looking for, which is letting the domain have all of the distribution lists, i.e. email@example.com, firstname.lastname@example.com, etc, while not have to deal with setting them up individually.
Comment: I've not used their hosted exchange email, or exchange email at all, so I'm not 100% on this, but I believe that each distribution list you make automatically creates an alias (forwarder) with that name, and Exchange server will bounce or accept external email to that alias based on the selection you make in the setup. However, I'm pretty certain that you _don't_ want the catchall results to be forwarded to everyone an any distribution list. Spam is bad enough without passing it on to every person on the distribution list too.
Answer: What you are after here is what is known as catch-all (as has been mentioned in comments). When this is done you can specify the normal mailboxes you want (such as user mailboxes) and the catch-all will handle any emails not already handled by an established mailbox.
Catch all mailboxes are basically a worst case situation for email and should only be used where no other option exists to handle your needs in a more reliable manner. The issues here with catch all mailboxes include...

If someone tries to email a user and makes a typo they won't get an error back indicating that they should check the email, instead to the sender it will look like the email went through without an issue which can cause more workload on your end trying to forward an email with a spelling error to the correct mailbox.
You will open up your mail service to a significant amount of spam as anyone trying a dictionary attack or brute-force attack to send spam to your mail server will see every single email go through which will fill your server up (basically you will have an unlimited number of email addresses that can be spammed), which can cause issues even with spam filtering in place as a percentage of the spam emails can make it through, and when you are dealing with an infinite number of potential email addresses that can still mean a massive number of spam emails making it through.

Based on your question of forwarding distribution emails to a single email address you would basically take your catch all mailbox and forward all the emails from it to a given mailbox. Having said that unless you are coming up with 50 or more generic addresses then it will be just as easy, and more secure from span, to just create a number of auto forwarder addresses instead of a catch all mailbox. By doing that any emails to invalid addresses will still be bounced back as undeliverable to the original sender but emails to valid generic addresses will be forwarded as per your configuration.
Comment: Most SMTP servers allow aliases to be created. Instead of a catch all scenario, the OP can just create a user mailbox and assign as many aliases as they want. I have hundreds of aliases. It is no trouble to set up. As well, many of the email addresses the OP is suggesting, I would not set up. Why? Because these addys catch spam all day long.
Comment: @closetnoc Yes, the info@ and sales@, among others, tend to get a lot of span. That's because they are so often used. Many online businesses have decided that they _need_ such addys because it is what customers/clients _expect_, and keeping customers is more important than reducing the exposure to spam. Filters can help, some, and the sales/public relations team(s) have to deal with the rest. Over time a company can develop reasonably effective custom filters for those addys, since legitimate emails will fit into certain patterns based on the business of the company.
Comment: @GypsySpellweaver Yes. I do realize that. However, you will find that many companies avoid these addresses too. Assuming that the OP is not a company arises from the question. For most sites, it is inadvisable to use these addys unless required, for example, postmaster. Cheers!!
Comment: Oh, yea! postmaster/webmaster is just _asking_ for spam. Admin and owner aren't much better. For those, I like to set forwarders that return error at SMTP time, to make sure they _don't_ have a chance of getting through, even with a catchall enabled.
Comment: @closetnoc Actually, assuming the OP is not a company _does not_ arise from the question. GoDaddy hosted exchange email lists are designed for managing the distribution of emails within an organization: sales@.. distributes to all members of the sales team (as an example). Someone not an organization has very limited use for such distribution lists (all family members maybe, or all my online "friends" perhaps). Enabling the distribution list to _also_ receive email from the public is optional, not required. Sales@ and info@ are external candidates, managers@ is likely an internal only list.


Transit through the USA

Question: I am an Indian citizen who is a permanent resident Card holder in Canada. So, my nationality does not come under the US VWP. I wanted to transit through the USA for a trip to India next year. But I read that in order to transit through the USA (even if I do not plan to enter), I would still require a US visa. After some research I think that I need to apply for a ESTA visa. Is this information correct? Am I also correct in assuming that ESTA can be granted rather quickly and I also would not need to attend an interview.
Comment: This is a question for our sister site [travel.se] and it is [already answered there](https://travel.stackexchange.com/q/4859/3221).
Comment: It's worth noting that switching Canada and the US in the question would lead to a different outcome; Canada waives the visa requirement for US permanent residents and allows them to fly to Canada with eTA, but the US doesn't do the same for Canadian permanent residents.  @DipenShah I would also note that the transit visa is a C-1 visa, but for anyone who anticipates traveling to the US for another reason it's probably better to apply for a B visa because the cost is the same.
Comment: No you need a B1 or similar visa and you need to go for an interview. Done exactly the same in the past.
Comment: @MichaelHampton So what exactly is a question that is fit for expatriates? I am also a member on the Travel StackExchange. I always thought that visa questions go on Expatriates and Travel tips etc go on the Travel platform
Comment: Expatriates is about _long term_ travel, such as for work, study, or immigrating to a new country permanently.
Answer: ESTAs are not visas, and are only available to citizens of countries within the US visa waiver program. As an Indian, you are not eligible. There are no exceptions for Canadian residents. Since the concept of international transit doesn't really exist for US airports, you actually will need to "enter" the US. You must apply for a visa.
Comment: @TRiG Canada also doesn't consider its eTA to be a visa, so presumably they're happy to consider ESTA as something other than a visa.  The fact is that different countries mean different things by the word.  Some countries consider authorization documents issued by officers at the border to be a visa; others do not.  There's simply no uniform definition of the term in international law or as far as I can tell in any other international context.
Comment: Surely an ESTA is a visa by any definition except that used by the USA's own bureaucracy.
Comment: @TRiG So that means ETIAS will be a visa, too?!

Transit through the USA


Can't get Windows to boot from GRUB

Question: I recently installed Ubuntu 13.10 and am having some issues getting GRUB to work with me. Whenever I want to get to GRUB (to boot Ubuntu), I have to manually select it:
. Then I can select Ubuntu from there. However, I want to make GRUB the default bootloader for my machine so it doesn't autoboot into Windows if I forget to press esc on boot. My GRUB screen looks like this: . When I select Windows, I get this screen: . If someone could help me figure out how to make grub my default bootloader and how to boot into windows from GRUB, I would love it! Thanks :D
Answer: Your laptop is using UEFI, which is needed for Windows 8 to secure boot.
To fix this, leave the boot option to "OS boot Manager" and boot a live-cd/usb and select try Ubuntu. When at the desktop start Boot-Repair and click "Recommended repair". It will give a paste.ubuntu.com/XXXXXX/ url, note that down as we need it the repair doesn't work. Now reboot and you should see the GRUB menu.
Comment: Sounds good! I'll give this a go. But before I do, if something goes wrong, will anything happen to my HDD data or my ability to boot into Windows?
Comment: Also, by clicking on the link, I noticed it would be possible to do this without burning a live-cd/usb. Will this yield the same results or do I need a cd/usb? (I ask because I don't have a CD or USB available as of now).

Can't get Windows to boot from GRUB


Did Michael Jackson hate his black roots?

Question: Many people assume Michael Jackson used plastic surgery and skin lightening creams specifically towards the goal of  looking more like a white man.
Is this true, and if so, is the reason behind it his hatred for his black roots or is it something else?
Comment: Why the downvotes?
Comment: I was considering closing it, until I read Chris' answer. I think if you added some details and sources it would be better received. As it is, it comes across as supposition and rumor.
Comment: Hi. I didn't downvote and I think people shouldn't do that without explaining. My guess is your question looks opinion oriented and lacks of sources. When you say "I know that Jackson wanted to be white.", could you share your sources with us?
Answer: This isn't a question with an easy or unambiguous answer.  On the one hand, we have the following:
1) Jackson seemingly wasn't a fan of his own personal appearance.  Over the course of his adult life, his appearance steadily grew more Caucasian, presumably because of the deliberate use of plastic surgery and other techniques.
2) Jackson seemingly wasn't interested in continuing his own genetic legacy.  It's widely believed that he used donor sperm to conceive his children, who don't seem to have visible black physical features.
3) Jackson had many white friends and both of his marriages were to white women.
On the other hand:
1) Jackson frequently celebrated African and African-American culture in his music (with songs like "Liberian Girl," about a beautiful African woman) and typically featured black women in his videos.
2) Jackson had many black friends, and didn't distance himself from black culture, except visually.  He also disclaimed attempting to look more white, although most people didn't find his denials plausible.
It's worth noting that Jackson claimed to have vitiligo, a real skin disorder that causes skin to spontaneously lose pigmentation.  The disorder creates spots or patches of light skin --sufferers can choose either to darken the patches with makeup to match the natural color, or, if the pigment loss is extensive enough, to lighten the remaining skin with creams.
It's probably fair to say that Jackson had complex and ambiguous feelings about his racial heritage, and that his appearance changes were probably more personally motivated than a statement about race.  I've heard some armchair psychologists theorize he was actually motivated by destroying his resemblance to his hated and feared father, rather than obliterating his racial identity, but we'll almost certainly never know the answer for sure.
Comment: It's an interesting answer Chris. It would be nice to add some sources if you can. I always wondered if some of these statements aren't gossip rumours...


How to show multiple screens with right/left slide Gesture

Question: I am having an application in which i have a ListView .List is populated from an array list .
On selection of each item it show the detail description for that item in a seperate screen populated data from another array list .
A single screen is used to display details of all the items.it loads data from  dynamically.
Can anyone please tell me how can i display all details on same screen using right/left slide gesture.
Screen with ListView -itemList
Screen to display detail -detail listView
 on next and previous gesture it should dynamic data on screen 2detail list view from arraylist
Answer: You can use Gallery View or horizon


Finding optimal parameters for an unknown function - (learning with an unknown loss function)

Question: I am working on a project where my objective is to find a set of parameters for a synthesizer which makes the synthesizer replicate an input sound. I do not know exactly what goes on inside of the synthesizer.
More formally, the objective is to given an input x, find the set of parameters p which minimize the distance between g(p) and x.
Problem
Since I do not know g(p), I can not differentiate it hence I can not compute the gradient of the loss function. So although I can measure the distance between between g(p) and x, I do not know in which direction to update my model to produce a better p.
Naive approach
The naive approach would be to generate a bunch of data with known p, and learn the mapping x --> p that way. However, g(p)is high dimensional and non-linear. It can not be assumed that two set of parameters p1 and p2 which are similar will make g(p) yield similar outputs.
Another approach would be to use some Evolutionary Algorithm to brute force a set of presets. This has been tested and works pretty well, but at the price of very computationally expensive predictions.
Suggestions?
I suspect the problem of finding optimal parameters for a more or less unknown system without the possibility to use brute force. Other real world problems I can think of would be finding parameters for some cloud infrastructure or smart temperature system to optimize for energy consumption.
Any suggestions? Any ideas as well as resources on related problems are welcome!
Answer: To anyone seeing this, after further investigation I have found that some type of Neuroevolution could be the answer.
Cool sources:
https://eng.uber.com/deep-neuroevolution/
https://arxiv.org/abs/1712.06567
NEAT by Stanley et al.


Where is this possibly WWI Eastern European military uniform from?

Question: This family members picture is a mystery. I would like to be able to know what country and military unit this uniform is from. I think is is eastern Europe around World war 1 era.
Comment: Hello & thanks for the question! Is there any writing of any kind on the photo?
Comment: Additionally: Would it be possible to take the picture out of the frame and onto a scanner, to give as high(er) resolution image? Of special interest are the areas: hat, belt, collar, cuffs, button-line, shoulders, perhaps even shoes and sidearm.
Comment: Provide a full visual description for the blind and search engines.
Comment: Austro-Hungarian definitely, but since they had many "separate" armies it is hard to tell which part https://en.wikipedia.org/wiki/Austro-Hungarian_Armed_Forces
Answer: Based on a these links: 1,2, an 3 your relative is wearing an Austro-Hungarian uniform, probably Austrian (according to this video). More detail on the photo would possibly allow for a better ID.
Comment: Thank you so very much for the insight. This makes sense to me. Gary


Windows Server debugging: view User Mode Stack in WDM Kernel Mode Driver Breakpoint

Question: I'm debugging a WDM Kernel driver IOCTL using Visual Studio Kernel Mode Debugger via pipe Serial connection to a Hyper-V VM running Windows Server 2012 R2.
Once I hit a breakpoint inside the Driver IOControl is it possible to view the user mode call stack?
At the moment I can only see the kernel stack, eg:
    SIoctl!SioctlDeviceControl+0x14b [d:\workspace\ioctl\c++\sys\sioctl.c @ 320]    C/C++/ASM
    nt!IovCallDriver+0x3cd  C/C++/ASM
    nt!IopXxxControlFile+0x8d2  C/C++/ASM
    nt!NtDeviceIoControlFile+0x56   C/C++/ASM
    nt!KiSystemServiceCopyEnd+0x13  C/C++/ASM
    ntdll!NtDeviceIoControlFile+0xa C/C++/ASM
    KERNELBASE!DeviceIoControl+0x73 C/C++/ASM
    KERNEL32!DeviceIoControl+0x80   C/C++/ASM
    0x9c402408  C/C++/ASM
>   0x0000005e`2f5af9c8 C/C++/ASM

Answer: Yes, you need to switch to the desired process first and then you have access to it's stack(s).  See .process:

The .process command instructs the kernel debugger to use a specific user-mode process as the process context. This usage has several effects, but the most important is that the debugger has access to the virtual address space of this process. The debugger uses the page tables for this process to interpret all user-mode memory addresses, so you can read and write to this memory.
Note   If you are performing live debugging, you should use the /i or the /p parameter. Without one of these parameters, you cannot correctly display user-mode or session memory.
  The /i parameter activates the target process. When you use this option, you must execute the target once for this command to take effect. If you execute again, the process context is lost.
  The /p parameter enables the forcedecodeuser setting. (You do not have to use /p if the forcedecodeuser option is already active.) The process context and the forcedecodeuser state remain only until the target executes again.

I am aware you asked about Visual Studio and I answered about WinDbg. I think you should use a tool appropriate for the job. WinDbg is infinitely more flexible and more powerful when it comes to debugging. I think in VS you would use the Process context, but I would recommend, again, use WinDbg.
Answer: I have tried that by using !process 0 0 app.exe and then doing .process /i pid or .process /P id as well, both fail to display the user stack.
I think it's because I'm already in that process, even thought it is inside the kernel driver, the running process is the application.exe. So when I either look in the call stack window or type in k I only see the kernel stack.
The "Visual studio way" of "switching" to different processes does not seem to work, the only thing I can do is walk around the different stack frames (within only the kernel stack - same as shown in the call stack window).
I'll try doing it in WinDbg see if it's any different.
EDIT:
I did something different now, after switching the context I did !threads and then .thread to the one thread that showed up and it is now working within a sleep call. Somehow in my IOCTL it does not work. But I tried it now using WinDbg and it works wonderfully!
Many Thanks!


What does undergraduate tuition fund, and how does this differ between public universities and private universities in the U.S.?

Question: Does undergraduate tuition help fund professor salaries? Does it help fund graduate student salaries, especially if the grad students are TAs? What about lab facilities?
Comment: Even within the US, this varies significantly between public and private universities.
Comment: Undergraduate tuition? What's that? Universities are free (in some locations).
Answer: (This is very much a US centric answer; other countries structure their university systems differently.)
This is a difficult question to answer because money is fungible, so in some sense it doesn't matter what the nominal answer is---if the money isn't going to fund those things, it's filling in other expenses so that other sources of revenue pay for those things.  But in practice, most universities put undergraduate tuition directly in their "General Fund"---a big pot of money, which is then divvied up to support the general operation of the university, which includes all the things you mention.  (Note that many sources of funding for the university are dedicated for particular things, and don't go into the General Fund, but undergraduate tuition usually isn't one of them.)
The University of Michigan has a nice online presentation about this, and as far as I know, that's typical: undergraduate tuition pays into the general fund, which pays for most of the university's core activities.


dimmers - is the problem solved with pure sine wave

Question: I've been interested in dimmer technologies these days, and spent some time in reading about this topic on the web.
According to what I understand, the problem with usual dimmers is that with inductive or capacitive loads, the current is not in phase with the voltage, which prevents the dimmer from working. So, they invented various technologies like phase adaptive dimmers, or pulse width modulation etc.
I just want to understand: if a dimmer were able to deliver a pure sine voltage of settable amplitude (and of the same frequency as the main), without regard to the current flowing through the device, would the problem be solved ? would led lamps, transformers etc. work well under this "dimming", or is there something else?
Answer: Incandescent filament lamps would dim well on the waveform you propose, but then they work well with conventional TRIAC phase shift dimmers.
As flourescent lights need a minimum voltage, and both compact flourescents and LEDs use electronics which rectifies the peak voltage provided, a variable amplitude sine wave would fail to dim all of these types, but in a slightly different way that the phase shift dimmer fails to dim them.
Ballast flourescent lights would dim as the voltage reduced a little, then probably flicker and fail to light at all as the tube temperature dropped at further reduced voltage. For high frequency flourescent, CCFL and LED, it all depends on how the control circuitry has been designed. 'Passive' LED with the cheap'n'cheerful capacitive input would dim quite a long way, as the current dropped with voltage. LEDs with a constant current source would keep going at constant brightness, drawing more current from the supply as the voltage dropped, until they went out at a low enough voltage.
Note that dimmable LEDs are available. They rectify the peak voltage, take their control input as the width of the pulse from the TRIAC dimmer, and program their current output accordingly. Some clever types even change their colour temperature according to the dimmer setting, hard white when full on, and warm white when dimmed.
Dimmers. The problem is solved when the type of dimmer and the type of lamp are matched.
Comment: Thank you again for having updated your answer. Just to let me know, are constant current source LED dimmable in some way (that is, without modifying the inner control circuitry to make them dimmable) ?
Comment: No, the current, and therefore the light output, is constant, until it eventually fails. How it fails is down to its detailed design, it may go off, it may flash


What is the measurement in inches of a XL frame?

Question: What is the conversion of a (XL) frame to it's measurement in inches?
Comment: Whatever they want it to be.  Bike sizes are not particularly well standardized.
Answer: It depends on the particular frame - XL doesn't mean a specific size. Also, even for frames labeled as the same size number (say 23" or something), thats only one measurement to summarize the size of the bike - there are many more which can make a bike fit or not - top tube length, stand over height, etc.

(Look at all of the quantities labeled on the figure, courtesy of Trek).
The two most important though are top tube length (E) and standover height (B?).
Comment: I think L is standover height in that diagram.
Comment: I hope standover height is actually B, it's hard to be sure.
Comment: Yeah, B is "frame size", more or less.  From the top of the seat tube to the centerline of the BB is one way to measure it, though others measure from the top tube junction to the bottom of the BB, along the seat tube.
Comment: (It should be noted that the conventional "frame size" measure has become a poor one as slanted top tubes have become more common.)
Comment: Looks like A is BB to top of seat clamp and B is BB to top tube, but that's not a great diagram.
Comment: L is the standover, but the diagram is just there to illustrate that theres a bunch of measurements - its hard to summarize in one number. But the most important numbers are L and E.
Answer: It depends on the manufacturer so you'll need to check the frame geometry specs. Even frames sized in inches or centimeters are not all the same, since different manufacturers measure between different points to describe frame size. There's usually a diagram on the frame spec page defining the different measurements.


What's wrong with USB sticks that you need 3 tries to plug them in correctly?

Question: You've all probably experienced this at least once: trying multiple times to plug in a USB stick correctly, because somehow it isn't intuitive what side goes up. This is especially the case when the USB stick in question hasn't been yet used by the user. But it can also happen with sticks that the user is already familiar with, as confirmed by the experience of the writer of this post.
Here are some pictures that illustrate this common experience.

So what's wrong with the design of a USB stick that makes it not intuitive enough to plug it in correctly the first time?
Comment: My theory is that you don't force it enough in the first try, because you are unsure if that is the right side. So in the second try you force a little more until you realize it was right in the first try. It happens to me all the time.
Comment: Hilarious! These cartoons illustrate *precisely* what I experience virtually every time I try to connect a USB plug, not only storage devices, but also cables and the like.
Comment: I don't know; I never seem to have this problem - all I do is look at the port, look at the device to be plugged in, and hold the latter so that it goes into the former correctly first time.
Comment: What's wrong with Intel's explanation.  USB plug superpositioning fits the available evidence and conforms to a relevant, well established scientific model of the world.  We continue to find more practical applications of quantum mechanics in unexpected places.
Comment: Personally, my biggest issue with plugging in USB cables into the back of my PC is when it goes in just right, with the correct amount of resistance, yet the device doesn't work.  You then look and find that the plug _exactly_ matches the width of the Ethernet port you have just "plugged" it into...
Comment: Thankfully, we now have USB C which can go in either way!
Comment: @Daniel, yes! USB-C only requires two attempts.
Comment: It's operator error: look first, orient key, insert.
Comment: Related: https://lifehacks.stackexchange.com/questions/1627/how-can-i-make-sure-i-get-the-usb-plug-in-the-right-way-up
Comment: This doesn't mean that it's in a superposition, it means that USB sticks have non-integer spin.
Comment: Reminds me of the story told to me about the funeral of the designer of the USB socket, whose coffin was lowered solemnly into the grave as family and friends wept, was then gently raised again, rotated, and then lowered back in.
Comment: It takes me 4 attempts. 1: try the HDMI socket. 2: try the HDMI socket the other way around. 3: try the USB socket the wrong way around 4: try the USB socket the right way around. After step 3, I will generally put my specs on.
Comment: @Aline Never use the force USB 2 twice method! I once broke an USB port on a laptop doing it because I am so confident that is the right side, and it was my friend's laptop too......
Comment: It's because they live in the 4th dimension, and the only way to get to the correct side is to turn them 3 times. Source: Four Dimensional Maths: Things to See and Hear in the Fourth Dimension - with Matt Parker https://www.youtube.com/watch?v=1wAaI_6b9JE
Comment: What Jeff Zeitlin says is overkill. Ports in devices are oriented the same way, and if they aren't, you notice the first time after buying a new computer and then remember that yours are upside down. Then the plug: that almost always carries a tactile and visual marker that is the top side. In the rare case it doesn't, you can still see at a glance whether there is plastic directly behind the the holes (normal USB-A: up has no plastic) or tell by the shape (USB-B, mini-USB, or micro-USB). It's the same with HDMI, RJ45 (ethernet), etc. Somehow, I do this automatically and never had this issue.
Comment: @Baldrickk This is why I have a short USB 3.0 extension from the back of my case over the top. Now I only have the problem originally posed by the OP :)
Comment: @Aline Do you work for NASA? You should.
Comment: @mcalex maybe. Although if you know that it can go in either way, presumably you wouldn't try flipping it over when it doesn't seem to fit at first.
Comment: I always had this problem, but I discovered the design logic and now only need to look at usb to plug it in first try 97% of the time (as apposed to usb + port). USB logo in image should point away from motherboard (plastic inside should face motherboard).
Comment: "What's wrong" is of course obviously "Physical symmetry without symmetry of use", as the best answer below mentions.
Comment: [Relevant SMBC](http://www.smbc-comics.com/comic/2011-10-04): Cables exist in four-dimensional space.
Answer: In my experience a USB plug needs a bit of pressure to go in the port. It's enough pressure to make me wary that I might break it if I'm putting it in the wrong way.
After reversing the plug, it becomes obvious that it does not fit at all. This observation allows me to flip it again and now apply more pressure with confidence.
Comment: The usb ports on my desktop will allow you to push them in the wrong way which makes me very careful about putting them in.
Comment: Or you can jam them into the HDMI port and... well, really screw things up at that point...
Comment: So, to the question of what's wrong with a USB stick to cause this action, you're saying it's because of the required pressure?
Comment: @wondering actually most usb plugs have the usb logo on one side, and that is usually the one that needs to be up when inserting horizontally
Comment: Exactly my point, this came immediately to my mind, after seeing the picture (though before I did not realize). But the next obvious question should be - WHY THE HELL THERE IS NO COLOR CODE which would distinguish the two sides??
Comment: @beppe9000 "most" and "usually" do not really help, as proves this question. Moreover, my experience is different (and definitely so with usb cables).  Also, not always one inserts a usb sticks horizontally. And even if there was a logo on one side, why should one interpret it intuitively as "plug in with this side on the top"? Why not to make it more obvious, such as using a color code? Why would people have this problem if the logo should be a solution?  So I would strongly disagree if you want to suggest that the occasional logo on the sticks is of any real help.
Comment: @Nelson ethernet too
Comment: @wondering The USB plug has 4 holes: 2 at the "wrong" ("bottom") side and 2 on the "right" ("up") side. these holes let you see which side has the plastic "tab" or not. The USB ports also have 4 tiny metal "lips" that help to keep the USB device in place. When an USB port is loose, it seems to be due to these. In almost all cases, on laptops, the plastic "tab" is on the top. So, rotate the USB plug so that the "empty" holes are facing up. Should help you.
Comment: @IsmaelMiguel I am not looking for a non-obvious solution which would enable me to plug the USB on first try (one has to remember some things to be able to do that). My point is that not making the process obvious (e.g. using color code on both the plug and the device) is strange, it's like making doors where you can't really recognize without an analysis which way they open, if you have to push or pull. As you know, this really happens.
Comment: @wondering If the holes have "color" (aka: plastic on the inside), flip around. Works most of the time. How is this different than color-coding?
Comment: It is different because there is no indication on the device itself (color coding would mean that there is the same color on the one side both on the USB and the plug). Again, I understand that there are ways to increase the chances that you get it right. I am just stating that there might be a much more better and obvious way to do it.
Answer: Short answer: Design commonly causes misalignment
Most plugs or ports have a flared edge, beveled plug or some other design that allows for the orientation of the plug to be slightly off and still match.  USB doesn't.
Oftentimes, the first attempt will cause your plug to be aligned too high, slightly twisted, or some other orientation that doesn't allow it to go into the jack.  Most USB ports are surrounded by plastic, where you might have the plug touching the edge of the plastic at some corner, and you assume you had it upside down.  When you flip it, the fiberglass circuit board edge inside the plug hits the fiberglass circuit board in the jack.  This causes the plug to shift to an angle up or down, and you are certain it is upside down.  Now when you flip it again, you are more certain that you have it the right way and you shift it around within the plastic hole in the case until it plugs in.
Comment: @allo I've got 5 USB sticks here, 3 are identical at both sides, 2 have printing on one side, but one has the print on the "up" side and the other on the "down" side.
Comment: Almost every usb Plug has a USB Logo on top, often you can feel it with your fingers. Next challenge: Vertical sockets. How do you need to rotate the plug, when you know its upside?
Comment: @Darkwing Did you know, that there is a norm, what side of a micro usb connector should be "up"? I think it was the flat one. But even two different Google devices did it in different ways (iirc the Nexus 7 did it wrong). The manufacturers just do not care.
Comment: An asymmetrical plug design may not help as much as you seem to think: For example, the micro and mini USB connectors are asymmetrical but it is still often not obvious which way they go; if the socket is badly accessible it can be hard even with the bigger and more obviously asymmetrical HDMI or SCART plugs.
Comment: @allo I can imagine that in a crammed device like a smartphone the "wrong" orientation made the connector or attached circuitry fit better. From my experience with car infotainment head units carelessness is unlikely; many people on many levels inpect and test design and prototypes of a device which is crucial for the company's success from all angles.
Comment: @PeterA.Schneider I've struggled occasionally with a SCART or VGA plug when it was out of sight behind a TV, but never when it was right in front of me. The same cannot be said about USB plugs. So while asymmetric design alone does not automatically solve all problems, it's typically solving quite a share of the problems (and in particular avoids the typical USB problem). But yes, there is also a wide range of how well an asymmetric design can help, the more you can not just see but also feel it, the better such visibility problems are solved, for instance.
Answer: Physical symmetry without symmetry of use
I'm surprised that so many of these answers are addressing the consequences of poor design without discussing what made it a poor design in the first place. The issue at hand here is that the USB devices have a correct orientation and that correct orientation is indistinguishable from the incorrect orientation.
In his book The Design of Everyday Things, Don Norman lists the following as the 7 fundamental principles of design:

1. Discoverability. It is possible to determine what actions are possible and the current state of the device.
2. Feedback. There is full and continuous information about the results of actions and the current state of the product or service.
  After an action has been executed, it is easy to determine the new
  state.
3. Conceptual model. The design projects all the information needed to create a good conceptual model of the system, leading to
  understanding and a feeling of control. The conceptual model enhances
  both discoverability and evaluation of results.
4. Affordances. The proper affordances exist to make the desired actions possible.
5. Signifiers. Effective use of signifiers ensures discoverability and that the feedback is well communicated and intelligible.

Mappings. The relationship between controls and their actions follows the principles of good mapping, enhanced as much as possible
  through spatial layout and temporal contiguity.

7. Constraints. Providing physical, logical, semantic, and cultural constraints guides actions and eases interpretation.

The non-reversible USB devices lack a good signifier for correct orientation. As Toby Speight mentions in his answer, the USB specification did include the requirement for such a signifier:

6.5.1 USB Icon Location
The USB Icon is embossed, in a recessed area, on the topside of the USB plug. This provides easy user recognition
  and facilitates alignment during the mating process.

..but I'd argue that that's not enough for two reasons. First, that specification is easily ignored by USB manufacturers. Second, even with an embossed icon, you haven't communicated to the user what the correct orientation is unless they already know that the icon signifies orientation. A USB icon just looks appropriate on a USB device and isn't going to be noticed by a normal user as an intended signal of information. Bedrooms often have an outlet which is controlled by a light switch in the room. To signify that that outlet is the one controlled by the light switch, it's often installed upside down. To someone who's aware of this relationship, this is helpful, but to someone who isn't in the know, it's up to chance that they discover it themselves or are informed of it. Same with the USB icon. It shouldn't have been expected that people would know what it meant.

A similar issue is seen with the design of some doors. Here are a few pictures of doors from The Design Of Everyday Things again:

In the first image, the left door must be pulled but the right door pushed even though they have the same handle. In the next two images, it's not clear where on the door you should press (left or right) to open it. Don Norman has this to say about the doors:

When external signifiers—signs— have to be added to something as simple as a door, it indicates bad design.

If something as simple as a cable needed an icon to indicate which orientation was correct, it was already poorly designed.
The solution? Either make a cable that's reversible or remove the misleading symmetry.
Comment: There's an interesting circular logic with the spec: if the plug doesn't have the embossed USB logo, then it doesn't conform, and so isn't entitled to have a USB logo...
Comment: Icons are also not as useful in poor lighting conditions or when you're reaching around to the back of a computer. Also, some USB cables omit the icon in exchange for a logo, etc.
Comment: Knowing the top side of the plug is very useful in cases where you have horizontal USB ports that weren't installed upside down.  It's less useful for the vertically oriented ones.
Comment: This is one of the best answers I've ever read.
Comment: @MrLister: But the commonly used USB micro-A plugs aren't symmetric. The top is flat and has narrower, rounded edges, the bottom is wider and has latching pins. The socket is almost always shaped to match, as far as I've seen.
Comment: They did remove the misleading symmetry with USB Mini. But apparently that was too easy, because then they dropped that for USB Micro.
Comment: The bedroom example doesn't work for me - European sockets are the "USB-C" of power sockets ..
Comment: Good answer. However I don't think HDMI is such a good example. It's hardly better than USB, especially where USB devices are plugged in and out of the front of a PC a lot of the time, whereas HDMI is (mostly?) at the back, so the correct orientation is much harder to find.
Comment: I agree with everything you've written here, and Norman's book is one of my favorites. I didn't interpret the question as being focused on what was wrong with the design in the first place, but rather what specifically causes the operator behavior of trying it one way, flipping it over, and then flipping it back.
Comment: When people ask more than one question I tend to prioritize the one in the title, YMMV.
Comment: @HagenvonEitzen - weeeel. I guess [somewhat european](https://de.wikipedia.org/wiki/L%C3%A4nder%C3%BCbersicht_Steckertypen,_Netzspannungen_und_-frequenzen) Too many different ones still, imho :-)
Comment: Great answer. I originally thought your outlet picture was going to illustrate how lack of symmetry makes it easy to tell which way to plug something in, even if the receiver end is in a different orientation than expected (which is a problem even for folks who know what the USB icon means), but now I've learned what an upside down outlet is likely to mean! (Also, I think your last two pictures are in the wrong order.)
Comment: USB-C is awesome.
Comment: @Toby, I wouldn't call that circular logic though. You say "entitled to have a USB logo", but the logo is part of the design itself, not a certification of the correctness of an implementation
Comment: @gatkin, the bottom of the question has: "So what's wrong with the design of an USB stick that makes it not intuitive enough to plug it in correctly the first time?". My interpretation is that OP is asking what was wrong with the design that a user is unable to just plug it in correctly with one try.
Answer: The underlying problem, as I think we all know, is that the tactile feedback you get with an incorrectly oriented plug is hard to distinguish from the tactile feedback with a slightly misaligned plug. Given that, your question can be reformulated as: why do many (most?) people mistakenly assume the orientation is wrong when they actually just need to keep trying to get the alignment right?
Best guess: deciding which way round to hold the plug (and attempt to insert it) was a conscious decision; and since it's hard to predict which way round will work it was also a provisional decision. We have doubt that it was correct, so we're predisposed to try it the other way. Of course we're consciously aware of our failing attempt to insert the plug, and we're trying to get the alignment right, but the ambiguous tactile feedback isn't giving us reason to reject the preconceived notion that the orientation might be wrong. So we give up sooner than we should and flip the plug over.
Another part of your question asks why the USB designers didn't anticipate this problem. I would observe that the ports USB was intended to replace either had a clearly visible "up" (the D shaped parallel, serial, and game ports) or good tactile feedback for "up" (the round keyboard and mouse ports) or both. The USB designers may have simply underestimated the potential for a problem those ports didn't suffer from.
After all, it's not like they didn't think about tactile feedback. When you finally slide the plug in it bottoms out and the latching mechanism clicks in, giving very good tactile feedback that you've got it right. A plugged-in USB cable feels solidly connected, and that's the result of deliberate design effort. (Which also fixed a problem the older ports did have: the round ones felt tight when they were loose, and the D connectors felt loose when they were fine (which is why everyone over-tightened the stupid thumbscrews.))
Comment: Even with the D connectors and round mouse connectors you had to get back there with a light to see which way to plug them in. Don't get me started with the stupid thumbscrews.
Comment: @RedSonja: With the round mouse connectors, I always looked first because I was afraid I'd bend the pins on the connector again. The orientation dent isn't very good at preventing that.
Comment: Actually, the designers of USB *did* think of this issue, and that's exactly why USB connectors must have an embossed (tactile) USB logo on them.  Unfortunately, there are far too many USB-like connectors missing this crucial feature, as I complain about in [my answer](/a/123589/94571).
Comment: Very nice analysis, although I will admit to constantly having this problem back in the days of round mouse/keyboard connectors, too.
Comment: @DarrenRinger Lots of fun wasn't it? Worse is when you have to reach behind it but that goes for all kinds of connectors I would think. Or as RedSonja says those thumbscrews ... I hate those too.
Comment: @TobySpeight A logo for this purpose is already a failure in design (or shows low priority for this goal), you can hardly feel it and crucially, it is easy to build connectors that do not have it as they will still work. If you want to make sure everyone includes your orientation indicator, the plug has to not work if it's missing, the easiest for something like that is to include it in the form. Another drawback is of course, that users have to know the meaning of the sign, which again is not intuitive at all, while asymmetric form is.
Answer: Failure to follow the USB specification
I've had trouble with USB devices that completely fail to provide the tactile indicator that the USB specification mandates:

6.5.1   USB Icon Location
The USB Icon is embossed, in a recessed area, on the topside of the USB plug.  This provides easy user recognition and facilitates alignment during the mating process.

That's taken from the USB 2.0 specification, but similar wording has been present since the earliest USB versions.
The same section also specifies which way up the sockets should be:

Receptacles should be oriented to allow the Icon on the plug to be visible during the mating process.
Comment: What if the USB socket is aligned vertically? Should the icon be on the left or the right?
Comment: Requires you to be able to see the thing while you're plugging it in. Reaching behind a tower this isn't always so. Not your fault, but it means the standard isn't entirely without fault here either.
Comment: The icon is supposed to be embossed 0.6 mm high, so that it's tactile.  It would help if there was a corresponding tactile locator on the socket, too - is that what you're saying?
Comment: @SimonG: "*Receptacles should be oriented to allow the Icon on the plug to be visible during the
mating process.*" (from the same USB 2.0 spec), so no direction is specified when the socket is aligned vertically and there are no other constraints.
Comment: Ah, if the embossing is sufficient to be tactile, I guess that solves that. (The socket is its own issue, of course!)
Comment: @Our_Benefactors Was just thinking it's not always that simple if you're fumbling around behind a tower and, fine, you've looked at it a minute ago when it first went in your hand, but it can be easy to forget what its orientation is when it's a little thing that you're reaching around a corner (and possibly turning sideways) to plug in in the dark with your arms outstretched and you're on your back with your knees creaking. But perhaps that's just me....
Comment: The USB-IF controls the USB trademarks and logo. If they wanted to put some teeth behind the provision you're quoting, they could do so. They've chosen not to.  If you want to give the USB folks credit for solving the "which way is up" problem, as you do in your comment on my answer, you also have to blame them for not enforcing it.
Comment: Surprised I had to scroll this far to find the real answer. @LightnessRacesinOrbit , presumably you can look at the device before you plug it in, and once it's plugged in it doesn't matter if you know which way it's oriented, just yank the thing out. Of course, in addition to manufacturers putting the wrong thing on the USB male (looking at you, coolermaster), it's also possible for the USB female to be upside down, as I've seen before on some very budget laptops.
Comment: @SimonG. The Dell Optiplex minitowers we have (in the design vertical orientation) have front USB ports vertical and insert with the logo facing left. Looking around the office, it seems people tend to put the computer to the right of the user; this enables the top of USB sticks to be visible to their user.
Comment: @SimonG for nearly all towers, when facing the front of the tower, the "upwards" position will be on your lefthand side, as that position matches how the motherboard was originally installed.
Comment: My desktop tower violates this guideline and it bothered me so much I went in and tried to flip the board the ports were on up side down. But no, the manufacturer had made things in such a way that that was not possible. Infuriates me to no end.
Comment: Yes @gatkin - I agree with all of that.  It's a shame that the enforcement is lacking.
Comment: The USB ports I tend to have the most trouble with are the ones under my monitor. They point downwards, so there's no "up" side. Unless, of course, I turn my screen 90 degrees to put it in portrait orientation -- which I can do in either direction, so the ports are going to be upside-down in at least one of them. And the "visible during mating" rule doesn't really help either, since neither the ports nor the plugs in them are visible from the front side of the screen anyway.
Comment: Add to it that a computer can have several usb ports which are oriented differently. For example in my old tower, I had front usb 2.0 ports that are oriented one way, and a usb 3 port that is part of an internal card reader, which is oriented the other way... Couldn't really understand how to plug stuck in without having a look at the ports first.
Comment: The specs do not say that there can't be anything else embossed on the plug, right? I have here a USB cable from a well-known company (which I'd better leave unnamed /s), and this cable has the letters "SONY" embossed on the other side of the plug, opposite the USB logo. That doesn't break the specs, does it?
Comment: @FedericoPoloni, if you read Section 6.5.1, you'll see that that's provided for (figure 6-6).  Your implication is right, though - there's nothing to say that the manufacturer embossing has to be sufficiently distinct from the USB logo (in practice, I've never had a problem with that).
Comment: It continues to upset me that this isn't the accepted answer, when it is the most factually relevant one.
Answer: It's not an issue of poor design on the male USB - it's that there's no fixed orientation for the port.  When I plug my mouse into my laptop, I get it right every time.  But when I plug it into a desktop, there are (in general) three possible orientations for the port: left, right, up.
Because of this, it doesn't feel like I can ever get it right all the time.  If I haven't spent time examining lots of computers, there's no reason why I might think that the 'down' orientation is impossible, and so I have to examine both the computer's port and the USB to get it right the first time.  Because of this, it's less effort overall to just attempt whichever orientation I happen to be holding it in.  That's where we get to what others described.
Comment: @pipe I'm speaking from the position of a user; a priori, I have no reason to know that.
Comment: The down orientation is definitely _possible_ but you're not allowed to use the USB logo because it's not a valid position. (IIRC from reading the standards)
Comment: @pipe but not all kit has a clearly defined up and down anyway. It's less common for things with USB-A sockets but not completely unknown (e.g. Raspberry Pis in some cases
Comment: @pipe, and manufacturers would never dream of ignoring a specification's fine print :)
Comment: No, proper design helps you align to the port's orientation, just like any other plug.
Comment: I have upside down USB ports on my desktop.
Comment: @immibis The orientation reminds me of SATA ports upside down - and stacked on top of each other! That's just insane but it's done. ASUS does it for example. It's a terrible design but I love their boards so I just deal with it (though I've not upgraded my systems in years now).
Answer: Problem #1: On USB type A, there is a wrong way.  This is alone is a design problem. Headphone jacks, most car keys, non-polarized 120v power plugs, and the newer USB type C connectors don't have this problem.
Problem #2: USB type A lacks clear and standardized visual indication as to which way is the 'right way'. Most residential keys, grounded 120v power plugs, old 3.5" floppy disks, RJ-45 connectors, and most CD/DVD's make it very clear at a glance which way is the 'right way'. In the case of USB type A, both the plug and the jack lack visual indication without very close inspection
Problem #3: The USB type-A jack and plug support a very limited range of self-alignment combined with poor tactile feedback for any condition other than correct insertion. This results in users thinking they had an incorrectly oriented plug, when in fact the orientation was correct. As a counter example look at the typical door lock, and notice the indentation in the center of the keyway designed to catch the tip of an incorrectly aligned key. This aids the user in wiggling the key into the correct orientation.
Answer: There's a lack of a cue from the external casing:  in the old days when macs used connectors with lots of pins there was a flat in one place on the circular plug which matched up with a flat on the connector the plug plugged into:
If you matched the two flats together then the plug and its plug socket were correctly orientated.
(And the two flat surfaces had icons stamped on them to match up)
https://collections.museumvictoria.com.au/items/1267769
Comment: Wait, a pile of LocalTalk cables from the 90s is a museum piece now? I suddenly feel very old.
Comment: @ZachLipton I still have a pre-GB HDD and one that's ~2.5GB. I like telling a friend who was born in the 90s that I have dust collecting on hard drives that are all older than he is! He gets a laugh out of that piss take and it's very easy to turn around.
Comment: @ZachLipton, I've got a bigger collection than that in my attic, including some PhoneNet connectors still in original packaging.
Answer: The way I see it, it's a bit like docking to the Space station. There is one way to do it right.
It seems easy, but a slight misalignment requires you to try again.

I believe this is because , on the third try, you've become frustrated and are  now paying close attention to what you are doing. That, then, makes the alignment (and orientation) correct with the right amount of pressure.

Annoying, yes. Frustrating, usually. The alternative? I've never had a problem with inserting a floppy disk incorrectly. :D
Comment: I'd like to point out that inserting and removing a floppy disk is immensely more satisfying than trying to insert a USB device.
Comment: I assume you know this, but for the benefit of any readers who don't: the 3½ floppy casing and door latch was carefully designed so that of the eight ways you could try to insert it, only one would physically work.
Comment: @Joshua, some older 5¼ floppies/drives were actually single-sided, and you could flip them to read the other side, like tapes. And like cassettes, they had write protection notches on both edges. The point is, they were intentionally designed that way. (I remember even _cutting_ the index holes in order to make a single-side floppy double side :)
Comment: @gatkin: Ah yes. The 5¼ weren't. I recall some rumor about using this trick to hide data only readable by putting it in upside down.
Comment: You could also physically write protect floppies, so you couldn't accidentally wipe all your data.
Comment: Apart from the obvious design aspects, I completely agree with this answer and was wondering if anyone would raise this. Going in with **confidence** is key. When you know there is another possible answer in the set you lack confidence of your first try. Human psychology plays a big role to exaggerate this issue IMO
Comment: @Zeus  I remember buying single-sided 5.1/4" discs and, like you, cutting another write-permit notch into the sleeve, so that I could use both sides, even though I was only able to afford the single-sided discs.
Answer: Just selection bias at work here.  You don't notice when it works correctly first time, or when you just have to flip it once.  Instead you notice when due to a slight misalignment you end up having to flip it over twice.
Answer: I can't really speak for others but in my case the problem usually, at least partially, comes down to the dark colors used in USB ports. In some ports the plastic part inside the socket (where the contacts are) is white and then it's quite easy to see which side of the port it's on and orientate the device/cable appropriately, but often it's black or dark gray and then in the darker lighting closer to the floor where most computer towers/cases are it's difficult to see which side it's on without bending down to look at it more closely. In the case of an eye-level port that I can see easily I don't usually have any difficulty getting the orientation correct first time.
Combine this with the tactile feedback, as others have mentioned, and the fact that the plastic part of the socket is weak and prone to breaking (at least I imagine it that way), and I am usually hesitant to push it too hard even if I think that the orientation is correct (knowing that, if the orientation is incorrect, I may well damage the port). So it's difficult to feel if the orientation is correct in cases where it's hard to see. And in some cases shoving the connector up against the metal "rim" around the port provides a similar feeling, if the device/cable is misaligned.
Also worth noting that this has never been an issue (for me) with horizontally-orientated USB ports. "Upside-down" ports may well exist, but for all the horizontally-orientated ports that I've seen the device/cable connects "right-way up" (i.e. with the label/markings/etc. on top - similarly I have not yet come across a device where the markings are "underneath" in relation to the USB connector). Vertically-orientated USB ports are a problem because there doesn't seem to be any consistency as to whether they are orientated "left" or "right".
Answer: There's no gate('funnel') in the port to ensure that it would slide in smoothly. Therefore, on the first try it is quite easy to hit the sides of the metal surrounding the bracket making you turn it around and try again(this time the wrong side). It doesn't help that the bracket itself quite often sits 1-2mm inside of the device. The spec and reality of how it is used doesn't really leave space for such a gate to exist as well.
Part of it is just that it was good enough when introduced, it's a lot easier to get in without fiddling than a db9, db25, pc joystick connector or even the ps/2 connector.
Answer: I've found checking for the stripe indicating the join in the plug's casing to be a good indicator of insertion orientation (try saying that five times fast).
More generally the plug requires orientation, but doesn't provide much in the way of an indicator at insertion time in the plane of view. Many other plugs do, but they tend to be more elaborate, such as with HDMI and DisplayPort.
Answer: On USB 1.x and 2.0 ports/plugs the internal plastic carrier for the contacts is typically made of black plastic, and thus quite hard to see inside an unlit cavity.
USB 3.0 chose to make the plastic blue to help indicate that the port is capable of higher performance, and inadvertently made inserting devices easier by making it easier to see which way the port and plug are oriented.


Univariate anomaly / outlier detection

Question: I'm facing a problem that seems 'easy,' but I've been struggling with it for a while now in the field of anomaly/outlier detection.
I have a dataset of around 60K data points. Each data point is part of a group (~1500 groups; min group size is 15) and has a length parameter.
The task is to perform anomaly detection within the groups, i.e., if a data point has an irregular length compared to the other data points in the group, mark it as an anomaly.
I'm using a log2 transformation on the data, and after the transformation, the majority of groups (75%) are normally distributed based on Shapiro-Wilks test.
As a first solution, I tried the classical distance in std from the mean, where if the length is bigger than mean+3*std, then this is an anomaly.
I had 2 problems with this solution:
In groups with a high number of data points, where the vast majority of data points had the same or very similar length, the std was very small, thus making the threshold very small, and it resulted in alerting on data points, which I do not consider as anomalies.
This method resulted in a relatively high detection (~250 anomalies), and I aim to alert only a small number of the most extreme anomalies in my data across all the groups.
When I tried to increase the threshold, e.g., to 4std, I faced another problem, where I missed anomalies in groups where one data point had a very large length compared to the others, which resulted with a high std, and thus making the extreme data point to have a 'low' std from the mean distance.
I'd appreciate any help or thoughts on the subject. Thanks!
Answer: Consider swapping the Z-score for Median Absolute Deviation, it might improve robustness.
Furthermore, it is critical to choose a threshold wisely. At minimum, plot the anomaly scores using a histogram, and see if you can select an appropriate point.
It might also be that you need different strategies for the different subgroups.

Univariate anomaly / outlier detection


How to update one table based on another table's values on the fly?

Question: I have a table in the name of ips as below:
CREATE TABLE `ips` (
 `id` int(10) unsigned NOT NULL DEFAULT '0',
 `begin_ip_num` int(11) unsigned DEFAULT NULL,
 `end_ip_num` int(11) unsigned DEFAULT NULL,
 `iso` varchar(3) DEFAULT NULL,
 `country` varchar(150) DEFAULT NULL
) ENGINE=InnoDB

Lets assume I have a countryid field on this table from country table which is as below:
CREATE TABLE `country` (
 `countryid` tinyint(3) unsigned NOT NULL AUTO_INCREMENT,
 `name` varchar(50) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
 `ordering` smallint(5) unsigned NOT NULL DEFAULT '0',
 `iso` char(2) NOT NULL,
 PRIMARY KEY (`countryid`)
) ENGINE=InnoDB

There is about 100,000 records in ips table. Is there any query for the following scenario:
Check if ips.iso is equal to country.iso, if it's equal then add country.coutryid to that record. I couldn't think of any way to do it. Do you have any idea how to do that?
Answer: UPDATE ips INNER JOIN country
    ON ips.iso = country.iso
SET ips.countryid = country.countryid

Using MySQL update multiple table syntax:
14.2.11 UPDATE Syntax
Note that you have two different lengths and data types on your iso columns.  There are, in fact, two separate sets of ISO codes, 2-letter and 3-letter, so you may not in reality be able to join these columns:
ISO 3166-1
The join condition USING (iso) instead of ON ips.iso = country.iso works too.
Comment: You are a Genius you answer saved my time
Comment: It amazes me how little code is necessary to perform this action!
Comment: you saved my time. this is worked as well
Answer: @Cade Roux's solution gives me a syntax error, the correct one for mysql 5.5.29 is:
UPDATE ips
INNER JOIN country
    ON ips.iso = country.iso
SET ips.countryid = country.countryid

without the "FROM" keyword.
Comment: It has since been fixed, seems...
Answer: This syntax might be better readable
UPDATE country p, ips pp
SET pp.countryid = p.countryid
WHERE pp.iso = p.iso

Answer: thanks @Cade, but I found a simple solution for it:
update ips set countryid=(select countryid from country where ips.iso=country.iso )

Comment: There is a difference in behavior to my version - your version will set it to NULL if it's not found, mine will not alter an existing value if it's not matched.  This may or may not be desirable.  Also the execution plan may differ depending upon the optimizer.
Comment: @john.locke It's probably not a problem - when you add the new column, I'm assuming it will be NULL and also a foreign key, so invalid entries wouldn't be allowed anyway.  But it's hard to tell from what has been explicitly given in your question.
Comment: @CadeRoux I didn't think about NULL part, thanks.


Handling ajax response on page load

Question: In JS file, we're collecting some data on home page and sending to JS function called sendPageData() as an input parameter. In this sendPageData() function, we're calling $.ajax call and merging this ajax call response with input parameter. This activity is being done on page load. Finally we're merging input parameter array and ajax response array but ajax call response is missing in final array response because $.ajax call take sometime to respond since it's back-end call. One option is to create one controller rendering component, call  REST API call to fetch data and keep the response object in script tag. This way when JS function is called after page load, this object can be used. Is there any better way to capture REST API response on page load?
Answer: One of the options would be if you create a new function and call it after

success() it will make sure Ajax call response is available basically make a chain of function calls, also you can use local/session storage to store response if it's same in every response.
Note: make async:true so that it will not hold back other requests

$.ajax({
        url: '/api/sitecore/GlobalHeader/GetGlobalHeaderBanner',
        async: true,
        success: function (bannerHtml) {
            UpdateGlobalHeaderBannerSessionObject(bannerHtml);
        },
        error: function (error) {
            console.log(error);
        }
    });

Answer: Instead of merging the AJAX response with the input parameter immediately, you can modify your code to handle the AJAX response asynchronously. This means that you would move the code that merges the response with the input parameter inside the AJAX success callback function. This way, the merging will only occur once the AJAX call has completed and the response is available.
function sendPageData(inputParameter) {
  $.ajax({
    url: 'your-api-url',
    success: function(response) {
      // Merge the response with the input parameter here
      var mergedData = mergeData(inputParameter, response);

      // Use the merged data
      // ...
    }
  });
}

function mergeData(inputParameter, response) {
  // Merge the input parameter array and the response array here
  // ...

  return mergedArray;
}

// Call the sendPageData function on page load
$(document).ready(function() {
  var inputParameter = // Collect data from the home page
  sendPageData(inputParameter);
});

Comment: Yeah this works. I think main point is to implement logic inside AJAX success function which is right place because that's where we're getting response back
Answer: You can also think of updating your logic to pass your input parameter into the AJAX call. To do this you can create a model like below.
public class DataViewModel
{
    public string Property1 { get; set; }
}

And call your AJAX request to post this data to your controller.
$.ajax({
    url: '/api/sitecore/{controller}/{action}',
    data: { Property1: '<your-data>' },
    type: 'post',
    success: function () {

    },
    error: function () {

    }
});

Then perform the logic on the backend and finally merge both responses to create a final response JSON object. And this way it will not miss the response and you will get the desired result.
Hope this works for you.

Handling ajax response on page load


Symbolize the selected feature

Question: I am working on a plugin on QGis, i want to know if it possible to change the color of the border of the selected polygone, to appare differently from other polygones when i print the layout.
Cordialy
Answer: There's a function called is_selected() : so you're able to use it to create a rule-based symbology to highlight the selected features in the layout (or do you mean you want to achieve that programmatically ?)
Comment: well you'are still able to programmaticaly create the rule-based symbology (some answers on gis.stack.exchange) and use the `is_selected` filtering condition ...
Comment: Thanks for your answer,  yeah exactly, i want that the current selection (polygone) appear differently than others when i am generating the layout.
Comment: but ... do u want to do it using **python** or is my answer fitting your needs ?
Comment: Yes i am using pyqgis to code a plugin on QGIS, so i am looking for if there is a possible to do it using Python Code
Comment: I found some answer but for pyqt 2, i am using pyqt 3, if you have any reference, i will be thankful if you share it

Symbolize the selected feature


Subdivided mesh cube with texture

Question: How can I create a subdivided cube with the texture shown on the example:
Comment: Do you have access to an _Image texture_ to wrap around a cube? Hand painting it could take a long time.
Comment: My texture is created with cycles render , is not image texture
Answer: An option to achieve this look would be to use a musgrave texture as the factor of two diffuse shaders. For this example, a quick search for 'grid image' gave me an image to use for slight displacement, and to keep things simple as the wireframe node will give triangles, and freestyle didn't look too good either.
This is the image used for the grid:

The node setup is as follows, note that the musgrave is connected to the object output of the texture coordinate node, and the mapping node to the UV output as the cube is uv unwrapped.

Play with the scale on the musgrave texture to get a look that you like, likewise with your grid texture in the mapping node.
This should give you a starting point, hope it helps. Finished result:
Comment: You're welcome, glad to help @saded.
Comment: Thank's, for the image grid, are you send me?

Subdivided mesh cube with texture


He is not, like his father, optimistic about future

Question: The sentence goes,
"He is not, like his father, optimistic about future."
It means he is not optimistic but his father is.
But I dont' understand the logic of negation here because it says'like his father'.
Please explain.
Answer: "He is not, like his father, optimistic about future" states that the father in question is also not optimistic about the future.
Like his father is a non-essential appositive clause (which is why it is set off by commas) and thus can be moved around in the sentence. So, we can rewrite the sentence like this - Like his father, he is not optimistic about future.
If we needed to state that the father in question was optimistic about the future we would say, Unlike his father, he is not optimistic about future or He is not, unlike his father, optimistic about future.
Comment: You could use _as his father is_ instead of _like his father_.


How GAE datastore key is generated?

Question: Is it random value? Or, can user extract some data from this value?
Comment: 2 reasons why I wouldn't ask or wouldn't answer the question: unwise for app design, unwise for GAE security.
Comment: @topchef, I could agree with second part, but wouldn't agree with first ;) - I should understand if I can use this as part of url - whether user can extract something more from this or not.
Comment: @LA - then we talk about just 2d part all together. Accidentally, I just had conversation with one the clients of the software I maintain the other day, who asked why we don't expose internal keys in our UI model (in MVC) while we heavily use it in URLs. I couldn't think of any valid reason except why we don't: they have no meaning for the customer and we offer unique ids that carry business semantic as well as identity. And since I am in no position to give hackers any extra chances I resist to expose those keys just because I can.
Answer: a datastore key consists of a kind, a string name or integer id, and an optional parent entity path (docs). all of those are user-specified except the id, so i assume that's what you're asking about.
ids are allocated based on simple integer counters that start at 0. currently, in a given app, all root entities share a single counter, and non-root entities share a counter within their entity group. over the long term, ids from a given counter will increase, but datastore servers reserve ids in batches, so you'll often see ids increase and decrease over the short term.
more details: http://groups.google.com/group/google-appengine/browse_thread/thread/dec83c2dbd9542e4#f495648c988d758c
(as to the security question, none of app engine's security depends on keeping this id allocation mechanism secret. you might want to read up on why security through obscurity is generally considered a Bad Thing. :P)

How GAE datastore key is generated?


How do I see what symlinks exist for a given directory?

Question: I want to do some housekeeping in a directory, and I want to see if a given directory has any symlinks pointing to it. I can easily enough see what directory a symlink points to, but now I want to see the relationship in reverse.
Comment: have a look at this question: http://stackoverflow.com/questions/100170
Answer: Symbolic links are not tracked, so you'll have to perform an exhaustive search. Furthermore, symbolic links are textual, so they keep "existing" even if the filesystem they reside on is unmounted (and they may have a different target if mounted in a different place or if you rename directories). So the most you can do is find the symbolic links pointing to a particular file (or directory), say /target, in a particular directory hierarchy, say /haystack.
(Note that I assume you are really looking for symbolic links to a particular directory. Finding symbolic links pointing into a directory (i.e. to a file or subdirectory of that directory) or accross a directory (i.e. that may become dangling if you remove the directory) are much harder problems.)
With some versions of find (e.g. on (recent enough) Linux, FreeBSD or Mac OS X), you can easily look for symbolic links whose target is /target:
find -L /haystack -xtype l -samefile /target

On systems whose find command doesn't have the -samefile primary, you can use ksh or bash instead, if available. Remove -xtype if it's also not supported; then the command will also list the target itself (or any hard link to it).
find -L /haystack -xtype l -exec ksh -c '
    for x; do [[ $0 -ef $x ]] && printf "%s\n" "$x"; done
' /target {} +

Doing this with only POSIX tools is a lot harder, due to the lack of POSIX ways to test same-file-ness or obtain information about symbolic links. Here's a solution for directories; it assumes there are no newlines in any filename.
find /haystack -type l -exec sh -c 'cd -P -- "$0" && pwd' {} \; |
  grep -Fx "$(cd -P /target && pwd)"

And here's my obligatory zsh solution.
echo /haystack/**/*(@e\''[[ $REPLY -ef /target ]]'\')

Comment: Okay, this is actually what I need in my case. In a single directory with no recursion, I want to see if any symlinks to it also reside in that directory, so I know whether deleting it will cause any breakage. Will `find -L ./ -xtype l -samefile /target` do the trick? If I wrapped it in a foreach() covering each file, I could search all the files for symlinks to them, right?
Comment: @user394: I don't understand the requirement in your comment, there are several ambiguous "it"s and "the"s. Could you reformulate it more clearly, perhaps with examples?
Comment: For `find -L /haystack -xtype l -exec ksh...`, ITYM `find /haystack -type l -exec ksh...` unless you do intend to descend into symlinks to directories (in which case you'd have used `***` in `zsh`).
Comment: Note that `-ef` has been [requested be added to POSIX](http://austingroupbugs.net/view.php?id=375) as it's widely supported.
Answer: You'll need to search from / using find(1) and the -type l option to identify all links, followed by a grep(1) to isolate the links of interest.
Comment: `grep` alone might be not enough, if relative links are involved like `../other`.  You might need to expand detected links and compare with the full path to your dir of interest for a match.


How to go about combining dropdowns / filter queries?

Question: I'm coming up short with my googling here. (As 'filter' in wordpress always turns up more content related info).
Anyway, my situation is this: I have Categories, Tags, Authors and Archive dropdowns on my blog page (using the built in wordpress dropdown functionality (http://codex.wordpress.org/Function_Reference/wp_dropdown_categories, for example).
I want to be able to combine these filters; such that if you choose a category Hats, and then when you have your list of results if you choose Blue from the dropdown you would get anything that matched both Blue and Hats. (Or if you choose a month, you'd get the posts that matched Blue and Hat from your chosen month.)
I know there has to be a way to do this. But I'm coming up short even figuring out where to start. (I'm certain there was a plugin that did this that I wanted to look at, but I can't even find that.)
So... If anyone has any ideas about how to start this that would be amazing. Or even just an example plugin I can look at to glean some info (I really want to code this myself so I understand what is going on).
Comment: The keyword you are looking for is "faceted search", it's popular feature to be required, should be plenty info on it around.
Answer: To get you started: you can make a custom form (I never worked with wp_dropdown_categories). When the form is submitted, it gets the input variables and uses them in the query.
The form could be something like:
<form action="http://example.com/resultspage" method="post">
<select name="categories">
   <option value="categoryname1"></option>
   <option value="categoryname2"></option>
   <option value="categoryname3"></option>
</select>
<select name="tags">
   <option value="tagname1"></option>
   <option value="tagname2"></option>
   <option value="tagname3"></option>
</select>
<select name="authors">
   <option value="authorname1"></option>
   <option value="authorname2"></option>
   <option value="authorname3"></option>
</select>
<select name="archives">
   <option value="archivesname1"></option>
   <option value="archivesname2"></option>
   <option value="archivesname3"></option>
</select>
</form>

And then on the resultspage
$category = $_POST['categories'];
$tag = $_POST['tags'];
$author = $_POST['authors'];
$archive = $_POST['archives'];

$args = array(
    'category' => $category,
    'tag' => $tag,
    'author' => $author,
    'posts_per_page' => -1 // Number of posts per page, -1 is show all
);

$query = new WP_Query($args);

A few notes. First, this is not tested. Second, check the codex on WP_Query how to use these (and other) arguments and what kind of input they need. For instance, you can use 'tag' and input the tag slug, but you can also use 'tag_id' and use the tag ID as input. Then you would change the option value of the tags select field. Third: I don't know what you would like to do with the archives. Would you like to display posts from a certain month? This can be achieved with a meta_query (you can find documentation in the WP codex).
Is this a good start? Let me know if it worked out.


An equation for Killing vector fields

Question: Let $(M,g)$ be Riemannian manifold with Levi-Civita Connection $\nabla$. We know that a vector field $X$ is a Killing vector field if and only if it satisfies the Killing equation (written in abstract index notation)
\begin{equation}
    \nabla_{\mu}X_{\nu} + \nabla_{\nu}X_{\mu} = 0
\end{equation}
Now I'd like to show that $X$ also satisfies the equation
\begin{equation*}
\Delta_{g}X^{\mu} + {R^{\mu}}_{\nu}X^{\nu} = 0 \tag{$\heartsuit$}
\end{equation*}
where $\Delta_{g} = \nabla^{\mu}\nabla_{\mu}$ is the Laplace-Beltrami operator and $R_{\mu \nu}$ is the Ricci tensor. The derivation should be straightforward. Indeed, if we apply $g^{\lambda \nu} \nabla^{\mu}$ to both sides of the Killing equation, we can commute the order of covariant differentiation and get
\begin{align*}
g^{\lambda \nu}\nabla^{\mu}\nabla_{\mu}X_{\nu} + g^{\lambda \nu}\nabla^{\mu}\nabla_{\nu}X_{\mu} &= \Delta_{g}X^{\lambda} + \nabla^{\mu}\nabla^{\lambda}X_{\mu}\\
& = \Delta_{g}X^{\lambda} + \nabla^{\lambda}\nabla^{\mu}X_{\mu} + {R^{\mu \lambda}}_{\mu \nu}X^{\nu}\\
& = \Delta_{g}X^{\lambda}+ \nabla^{\lambda}\text{div}X + {R^{\lambda}}_{\nu}X^{\nu}\\
& = \Delta_{g}X^{\lambda}+ {R^{\lambda}}_{\nu}X^{\nu}\\
& = 0
\end{align*}
where the second to last equality follows from the fact that a Killing vector field is divergence free. However, I'm not sure about the third equality, that
\begin{equation}
 \nabla^{\lambda}\nabla^{\mu}X_{\mu} =  \nabla^{\lambda}(\nabla^{\mu}X_{\mu}) = \nabla^{\lambda}\text{div}X
\end{equation}
The main confusion comes from whether we can evaluate the term $\nabla^{\mu}X_{\mu}$ first, and then apply  the outer convariant differentiation. On the other hand, I'm pretty sure  $(\heartsuit)$ holds, since it will serve as a key step to prove the fact that $\Delta_{g}$ commutes with Killing vector fields on Riemannian manifolds.
Answer: Yes, $\nabla^{\lambda}\nabla^{\mu}X_{\mu}$ means  $\nabla^{\lambda}(\nabla^{\mu}X_{\mu})$. It equals $0$ since $\nabla^{\mu}X_{\mu} = 0$.
(I think that is your only question? Everything in your derivation looks correct.)
Comment: Yes, this is my only question. Thank you! When doing this type of computation, I'm under the expression that all covariant derivatives are taken before indices are applied. So I'm a bit unsure why in this case we can first evaluate $\nabla^{\mu}X_{\mu}$ and then take the outer covariant derivative.
Comment: @ShaoyangZhou Ok I think I see the confusion. Let's take an example like $\nabla_\mu \nabla_\nu X^\rho$. It means $\nabla_\mu (\nabla_\nu X^\rho)$: first evaluate $\nabla_\nu X^\rho$. And I means the whole tensor, not just one component. Think of the [indices as abstract](https://en.wikipedia.org/wiki/Abstract_index_notation). If you want a concrete component w.r.t. some coordinates, that's done at the end. For example, to compute the "$\mu=1, \nu=2, \rho=3$" component of $\nabla_\mu \nabla_\nu X^\rho$, you need to compute all $n^2$ components of $\nabla_\nu X^\rho$, not just "$\nabla_2 X^3$".

An equation for Killing vector fields


Crystal Disk Info: "Total Host Writes" shows two distinct values

Question: Crystal Disk Info shows two distinct values for Total Host Writes on my SSD when hovering over it, one of which is less than the other; which number of writes is correct?
Comment: Well 1472 divided by 1024 does equal to 1.438 :)
Comment: Beware that some versions of CrystalDiskInfo include malware/adware OpenCandy.
Answer: It is the same number. If you look carefully the result is 1472 GB and in the pop-up is 1.438 TB, where according to the binary convention 1024 gigabytes equals 1 terabyte.
Formula:
1472 / 1024 = 1.4375 TB

You can find a more detailed post about the metrics here .
Answer: Edit: It's not drive capacity but total bytes written.
It show the capacity of your drive in different binary format (in this case 1472 GiB 'GibiByte' and 1.438 TiB 'TebiByte').
For anyone looking to quickly convert between different format, just google
[NumberToConvert] [format in binary] to [format to convert to in binary]

ex: 1472 GiB to TiB => 1.4375 TiB
Make sure the dropdowns below the number are in the correct format too (Gibibyte and Tebibyte respectively. See screenshot below).
***I think Windows always display drive capacity in binary format while most drive manufacturers use decimal format in their ads. To convert from binary to decimal and viceversa, google as 1472 GiB to GB (GB stands for 'GigaByte')
Google image to convert binary format
Comment: That's not capacity, it's total bytes written.  Since a byte can be overwritten many times, it can be bigger than the drive size.  (In this case 512.1 GB).  But yes, it's using binary for those write-endurance numbers.
Comment: Sorry, must have misread it at first sight.


Does Allah dislike war?

Question: I've tried to google and can't find the answers in Qu'ran and Hadith. Here's my question, does Allah dislike war? For example, war world II, etc.
Comment: Allah dislikes injustice, but war can be good or bad depending on the war
Answer: First and firemost, we need to understand the cause and purpose of war..if it's against injustice and saving victim then its applicable. Quran says
"Permission to fight is given to those against whom war is made, because they have been wronged — and Allah indeed has power to help them" (Quran 22 :40)
And once peace prevail then war should be stopped immediately. If we study the islamic history then we will realise all the war took place in self defence. But if the intention is to harm people or humanity by war then its prohibited and would be considered as great Sin."The Holy Quran clearly says that " If you have killed even a single person, you have killed the whole humanity". (Quran Surah maida)
By the above verse The Quran is actually promoting humanity and showing how important a human life is. It's greater than Worship to save human life. There are rules of war set by Prophet Muhammad as follows:
Islamic Rules of War Given by Prophet Muhammad (PBUH)
Here is a glimpse of some of the Islamic rules of war based on the Hadith of Prophet Muhammad (PBUH):

No killing of children and women
No killing of elderly and sick persons
Exercising patience even during war
Not to head into war "hoping" for a conflict
Leaving the monks and those in places of worship alone
No destruction of property, cultivated lands and crops, etc.
No uprooting or burning of green and fruit-bearing trees
No slaughtering of animals for reasons other than food
No hurting or burning beesNo theft or robbery in the guise of war
Avoiding destruction to an inhabited place!

Hope it helps you.

Does Allah dislike war?


Analysing log and square-root transformed variables

Question: I'm just wondering if it's possible to analyse and interpret variables that have been transformed using different transformations (eg log and square-root) or if all variables in the analysis have to have been transformed with the same method in order to interpret the results.
Thanks,
Suzie
Comment: Yes to the first, No to the second. A number of threads on this site with the 'data-transformation' tag should be helpful, e.g., http://stats.stackexchange.com/questions/18480/interpretation-of-log-transformed-predictor (see Charlie and jthetzel's answers).
Answer: Just a simple example to see why data can be transformed in any suitable way for the analysis:
Imagine we want to find out the dependency between the size of a car and its price. For some reason you measure the area (or volume), whereas the effect perhaps can be explained better when looking at the length. Let's assume also that the marginal utility of additional income decreases, hence we would expect a dependency between $\log(income)$ and the length. The only way to capture this correctly is to apply different transformations to the variables.


Idiom for someone who got a tiny fraction of power and abuses it?

Question: Is there any idiom for a person who somehow obtained a (usually small) power to control people and is using it in every possible way to make problems for people around him?
Answer: I don't know how current or widespread this is but one term is 'a little Hitler'. Google ngram: a little Hitler

As the produce of an evident inability to make moral distinctions,
  Chorover' s verdict shares with such seemingly innocuous and self-
  deprecatory confessions as "there is a little Hitler in each of us,"
Race and Other Misadventures: Essays in Honor of Ashley Montagu By
  Larry T. Reynolds, Leonard Lieberman
Comment: Yeah, "little Hitler" is the first term that came to mind.  (And I haven't heard
"too big for his britches" (or more idiomatic, "gettin' kinda big for his britches") in decades, but it's an excellent put-down for this scenario.)
Comment: In German we wouldn't use this image but instead draw from the same source and call the person a 'Blockwart'. They were given the task to observe and keep at bay the people living in one block of houses.
Answer: A term that is probably restricted to Britain but very widely used here is 'a jobsworth'

A jobsworth is a person who uses their job description in a
deliberately uncooperative way, or who seemingly delights in acting in
an obstructive or unhelpful manner.
From Wikipedia, the free encyclopedia

The word comes from a common expression used by such people, e.g.
"Could I park here just for a few minutes? I need to collect an urgent prescription of heart medicine for my mother?"
"No, sorry, it's more than my job's worth to let you do that."
In other words the jobsworth is using the excuse that they will get sacked from their job if they bend the rules even slightly.
Comment: I always think of a jobsworth as someone who has a little bit of power (e.g. the power to enforce parking regulations), but not enough power to occasionally over-ride those same regulations. e.g. they cannot permit you to park for 5 minutes in an emergency.
Answer: A low-status employee inclined to abuse power within the public domain is sometimes referred to as a petty bureaucrat.

"However, since these petty bureaucrats' power is almost absolute, they
  also control the channels for addressing grievances."
"Any system of universal ID, once established, is the slippery slope,
  it is a short step to then requiring people to have and carry ID cards
  which petty bureaucrats and police can demand at will."
Examples from Globse.

 Abuse from a petty bureaucrat may express itself as simple disregard or lack of consideration, passive aggression, the imposition of unreasonable obstacles, or outright demeaning behaviour towards a client or customer.

Patrick M (see comments below) suggests petty tyrant as another common idiom for a person who abuses his or her power.  This American Life devotes a 45 minute broadcast to the story of a particular petty tyrant, a janitor who rose through the ranks to become head of maintenance,

"when he starts messing with his employees. Teasing them at meetings. Punishing them with crummy work assignments. Or worse things like slashing their tires in the middle of night."  Patrick M notes that, although the janitor may have started out as a petty tyrant, he turned into a full-blown psychopath.

The petty bureaucrat and the petty tyrant are but two roles taken by people in positions of relative power without status. Abuse of power by people in low status roles may take on grotesque forms such as the demeaning behaviour of soldiers in the Abu Ghraib prison in Iraq.  See  The destructive nature of power without status. Journal of Experimental Social Psychology (2011) by Nathanael J. Fast, Nir Halevy and Adam D. Galinsky.
The study On the Ethics of Intervention in Human Psychological Research:
With Special Reference to the Stanford  Prison Experiment (P.D.F.), undertaken by Phillip G. Zimbardo suggests that ordinary people placed in low status, high power positions--temporary prison guards--will carry out abusive behaviour towards innocent peers.
The abuse of power was even more powerfully demonstrated in the classic obedience studies carried out by Stanley Milgram. (Milgram, Stanley. "Behavioral study of obedience". The Journal of Abnormal and Social Psychology 67.4 (1963): 371). But who is the greater abuser of power? The experimenter who demands that electric shocks be applied to a victim, or the experimental subject who is placed in the role of a "teacher" who must punish the "student" each time the student makes a mistake on a trivial word-pair memorisation task?
Comment: @Tonepoet, thanks for formatting the links correctly. I now see how it is done.
Comment: Petty tyrant sticks in my mind as a common phrase for this type of person. +1 to you.
Comment: Patrick M, yes, excellent point. I hope you don't mind that I mentioned your suggestion in my response. If you want to submit a response of your own, I will gladly remove my reference to petty tyrants.
Comment: I don't mind at all! I don't think it's worth a separate answer, as it's really similar to your main answer, and we don't have a good reference for modern slang & snowclone etymology to draw real usage comparison from. And holy cow, I heard part of that story about the Janitor: he may have started out petty, but ended at terrorist level machinations. A typical petty bureaucrat is less interested or successful in acquiring so much more power. That janitor was a full-blown psychopath in the clinical sense (IMHO, anyways, I am not a psychologist).
Comment: You are right about the janitor eventually becoming a psychopath. I'm not sure about full-blown. There is still a long distance between a person who slits tires and one who calmly slits the throats of others.
Answer: Drunk with power. It's pretty self explanatory and applies universally to the obnoxious and abusive wielding of power, no matter how big or small.
In a work environment context, slave driver is appropriate because it's describing one with authority over another in reference to all the scummy negatives that come along with the implication of being involved in the slave trade.
In a general context, "surprised he/she can get their head through the door" may also be appropriate, referring to the inflated ego that these types get when anything complimentary lands in their lap. However, this isn't specific to obtaining power or authority, but it can still apply nicely.
"You see the way Jim has acted since his promotion? I'm surprised he can get his head through the door."
Comment: Downvote explanations would be great. Hard to learn without them.
Answer: Tin-pot Napoleon is also used.
Earliest date I'm finding is a book title from 1932: Amazon:

The Career of a Tinpot Napoleon: A Political Biography of Huey P. Long
  --- by John Kingston Fineran

(Huey Pierce Long, Jr., Governor and Senator from Louisiana)
The phrase may go back further, but Google ngram is not being helpful this morning, and tin-pot vs tinpot obfuscates matters.
Answer: There is an idiom Give somebody an inch and they'll take a mile (See theFreeDictionary) and it does get used to refer someone who has been given a little of something and they make the worst/best/most of it.
Comment: This doesn't sound right; I understand the idiom to describe people who continue to take *more*, rather than exploit what little they're given.
Answer: Toxic leader:

A toxic leader is a person who has responsibility over a group of people or an organization, and who abuses the leader–follower relationship by leaving the group or organization in a worse-off condition than when s/he first found them. The phrase was coined by Marcia Whicker in 1996 and is linked with a number of dysfunctional leadership styles.

Other names include the little Hitler, manager from hell, The Toxic Boss and boss from hell.  Their leadership style is both self-destructive and ultimately corporately harmful as they subvert and destroy organisational structures.

(Wikipedia)
Answer: I think this expression comes close,  bossy boots. The term  can be applied to someone who thinks they can order people about because they have a modicum of responsibility. Very often used with young women who are used to having things their own way, or with small girls who boss their siblings.
Macmillan Dictionary tells us

bossy boots
  someone who is always telling other people what to do, in a way that annoys them
Answer: A nice adjective for this is power happy.  Example:

Cons [of working in particular company]: District Manager is power happy. No matter how much your store prepares nothing will ever be right for him. Stores call each other to warn that he's headed to their store for what's called a "Store Walk". etc.
http://www.glassdoor.com/Reviews/Employee-Review-Harris-Teeter-RVW6385278.htm
Comment: Is the downvote due to my offering an adjective, or something else?
Answer: I might call such a person a martinet.
Comment: Rare enough to include a definition.
Answer: a would-be dictator or tyrant.

would be - wanting or trying to be  (Cambridge Online)

"a would-be actress who dresses up as Marilyn Monroe"
"He's a would-be politian. Just pay attention to how he talks"
"Opera singers and would-bes should practice at least four hours a day."
Comment: -1, would-be does not imply misuse of power, just being deluded.
Comment: @QuoraFeans  When would you use the phrase "a would-be dictator"?  When a person tells you he would love to be a dictator?  Or when one displays enjoyment in acting like one?  A would-be polititian starts off talking like a demagogue, and not telling people he would like to become one. Reconsider.
Comment: Tyrant is a great answer!