Prove that $({a\over a+b})^3+({b\over b+c})^3+ ({c\over c+a})^3\geq {3\over 8}$

Question:
Let $a,b,c$ be positive real numbers. Prove that $$\Big({a\over a+b}\Big)^3+\Big({b\over b+c}\Big)^3+ \Big({c\over c+a}\Big)^3\geq {3\over 8}$$

If we put $x=b/a$, $y= c/b$ and $z=a/c$ we get $xyz=1$ and
$$\Big({1\over 1+x}\Big)^3+\Big({1\over 1+y}\Big)^3+ \Big({1\over 1+z}\Big)^3\geq {3\over 8}$$
Since $f(x)=\Big({1\over 1+x}\Big)^3$ is convex we get, by Jensen,: $$\Big({1\over 1+x}\Big)^3+\Big({1\over 1+y}\Big)^3+ \Big({1\over 1+z}\Big)^3\geq 3f({x+y+z\over 3})$$
Unfortunately, since $f$ is decreasing we don't have $f({x+y+z\over 3}) \geq f(1) = {1\over 8}$.
Some idea how to solve this?
Comment: How is this question "seeking personal advice," whoever voted to close this thread?
Answer: This is more of a comment,  but I don't have the reputation.  Use Lagrange multipliers.  Solving, you find that the critical points occur when $xyz=1$ and $yz (1+x)^4 = xz (1+y)^4 = xy (1+z)^4$.  I think the only solution is $x=y=z=1$.  Clearly, it's a minimum and plugging in shows the bound.
Added:
We can rewrite the condition as $xyz=1$ and $\frac{(1+x)^4}{x} = \frac{(1+y)^4}{y} = \frac{(1+z)^4}{z}$
The function $g(x)=\frac{(1+x)^4}{x}$ is decreasing from $0$ to $1/3$ and increasing from $1/3$ to $\infty$.  This shows that 2 of $x,y,z$ must be equal (WLOG $x$ and $y$) and $z=1/x^2$.  It remains to solve $\frac{(1+x)^4}{x} = \frac{(1+1/x^2)^4}{1/x^2}$.  This time, it's not hard to check $x=1$ is the only solution and we are done.
Comment: It seems to me there's enough here to post as an answer, no need to apologize.
Answer: Let $g(t):=\left(\dfrac{1}{1+\exp(t)}\right)^3$ for $t\in\mathbb{R}$.  Then, $$g''(t)=\frac{3\,\exp(t)\,\big(3\,\exp(t)-1\big)}{\big(1+\exp(t)\big)^5}\text{ for each }t\in\mathbb{R}\,.$$
Thus, $g$ is convex on $\big[-\ln(3),\infty\big)$.
Let $x:=\dfrac{b}{a}$, $y:=\dfrac{c}{b}$, and $z:=\dfrac{a}{c}$ be as the OP defines.  Then, the required inequality is equivalent to
$$g\big(\ln(x)\big)+g\big(\ln(y)\big)+g\big(\ln(z)\big)\geq \dfrac{3}{8}\,.\tag{*}$$
If $x$, $y$, or $z$ is less than $\dfrac{1}{3}$, then clearly the left-hand side of (*) is greater than
$$\left(\dfrac{1}{1+\frac13}\right)^3=\frac{27}{64}>\frac38\,.$$
If all $x$, $y$, and $z$ are greater than or equal to $\dfrac13$, then $\ln(x),\ln(y),\ln(z)\geq -\ln(3)$, so that we can use convexity of $g$ on $\big[-\ln(3),\infty\big)$.  By Jensen's Inequality,
$$g\big(\ln(x)\big)+g\big(\ln(y)\big)+g\big(\ln(z)\big)\geq3\,g\left(\frac{\ln(x)+\ln(y)+\ln(z)}{3}\right)=3\,g(0)=\frac{3}{8}\,.$$
Hence, the equality holds if and only if $x=y=z=1$, making $a=b=c$.
Comment: I don't get it. What is the difference with my solution?
Comment: I'm not sure what to say to that, but my idea was to bypass the inequality $\frac{x+y+z}{3}\geq \sqrt[3]{xyz}$ that you would need to use in your attempt.
Answer: By Holder $$\left(\sum_{cyc}\frac{a^3}{(a+b)^3}\right)^2\sum_{cyc}1\geq\left(\sum_{cyc}\sqrt[3]{\left(\frac{a^3}{(a+b)^3}\right)^2\cdot1}\right)^3=\left(\sum_{cyc}\frac{a^2}{(a+b)^2}\right)^3.$$
Thus, it's enough to prove that
$$\frac{\left(\sum\limits_{cyc}\frac{a^2}{(a+b)^2}\right)^3}{3}\geq\frac{9}{64}$$ or
$$\sum\limits_{cyc}\frac{a^2}{(a+b)^2}\geq\frac{3}{4}.$$
Now, by C-S
$$\sum\limits_{cyc}\frac{a^2}{(a+b)^2}=\sum\limits_{cyc}\frac{a^2(a+c)^2}{(a+b)^2(a+c)^2}\geq\frac{\left(\sum\limits_{cyc}(a^2+ab)\right)^2}{\sum\limits_{cyc}(a+b)^2(a+c)^2}.$$
Thus, it's enough to prove that
$$4\left(\sum\limits_{cyc}(a^2+ab)\right)^2\geq3\sum\limits_{cyc}(a+b)^2(a+c)^2,$$
which is true even for all reals $a$, $b$ and $c$.
Indeed, the last inequality is symmetric inequality by degree four,
which says that by $uvw$ (https://math.stackexchange.com/tags/uvw/info )
it's enough to prove the last inequality for equality case of two variables and since
it's the homogeneous inequality by even degree, we can assume $b=c=1$, which gives
$$(a-1)^2(a+3)^2\geq0.$$
Done!


What's the back-story in Fez?

Question: I've been trying to piece together the backstory of FEZ - this is where I'm up to...
There are 4 races in FEZ:

Visitors - these appear as floating heads with 3 eyes and 3 tentacles.
Long-heads - these have long heads and one eye, they're only seen in pictures.
Big-heads - you can talk to these but they have a different language.
Gomez's species - only seen in the starting village.

Firstly, according to a blackboard in a classroom in Gomez's village:

It looks like the long-heads and big-heads are ancestors of Gomez's people.
I think that the long-heads were primitive ancestors that lived purely in 2D:

Their village is flat and the rooms there cannot be rotated.
They hunted animals (shown by one wall) and worshipped owls (shown by another), possible because the owls could see in 3D already.

The big-heads are harder to figure out, and I think visiting them might involve some time travel. There are two big-head villages:

Under construction village - this is populated and covered with scaffolding. It has the working stargate in it.
Ruined village - this is empty and overgrown, but almost identical.

I think that these are the same village before and after a catastrophe:

The populated village has a working stargate and a mural room that shows the visitors giving the stargate to the big-heads.

The classroom in that village shows a visitor holding the number 3, implying that visitors showed the big-heads about the third dimension too.
The ruined village has a mural that shows the stargate being built and then in its destroyed state.
The ruined village's stargate is destroyed by the space-holes, perhaps implying that's how they've come into the world?

I think the visitors and the owls are related somehow, but I'm not sure how?
Were the visitors destroyed by the same catastrophe?
If I'm right about the time travel then Gomez is going back in time to complete the game, and it's possible that in doing so he causes the disaster that destroys the big-head village.
If I'm wrong then what is going on?
Comment: This is a fascinating question, but almost certainly unanswerable. +1 anyway, though others might frown on it.
Answer: One of the coolest parts of playing Fez has been piecing together a story based purely on engravings and a smattering of owl and Dot sayings.
The only bit in the history you've outlined that I would take issue with is the bit where you say the big heads are ancestors to Gomez's people. And by big heads, I mean the ones running the successful stargate. I think the bigheads are the latest line in this string of creatures having heads large enough to contain information about the third dimension without shattering the hexahedron. They also all wear squares, or 2D cubes, on headbands almost as a religious or tribal identification.
I can't tell if the ruined city is in the past, or if it's more like ruins that the big heads discovered, or if it was a failed project that they relocated. There is some amount of time and space not acting as expected, beyond the established 3D gimmick, as when you enter the hut in the forest that exits in the mausoleum, or the underground place that is being rendered out of glitches.
Two tiny details that I thought were incredible: the tribal Gomezes live in 2 dimensional huts which they see with 1 dimensional eyes. They see in 2 dimensions because that's how many there are, while Gomez and the big heads have 2 eyes and can see in three dimensions, and the space squid have 3 eyes which presumably means they can see in four dimensions. This implies that the world was evolving as the creatures were.
Two final thoughts:

I think there might have been a second alien race or something. Throughout the game are skulls with three eyes, but laid out on a line, not in a triangular shape like the space squid have.
I'm not entirely sure why the one-eyes started worshipping owls, but in UFO lore, owls and aliens (in particular grays) are closely related. I have a friend who swears up and down he was visited by a talking owl as a kid, and the owl told him about the relationship between humans and aliens. It's as if, in the game, owls can straddle all the possible worlds because they can fly and see all the dimensions.
Comment: I think the big-heads and the long-heads (what you've called tribal Gomezes) both appear on the blackboard in Gomez's village's school hut on what looks like an evolutionary chart (see question). To me that suggests that both must precede Gomez's people, possibly as ancestors, but even if not they must have come before.
Comment: I guess you're right. I misread the picture as being Gomez's people. At the same time, don't human evolution charts terminate with regular humans on the farthest right? Where's Gomez's folk?
Comment: Not sure, maybe that would be too obvious? I think the big-heads are Gomez's predecessors, but they were wiped out in the calamity that destroyed their stargate. I think there was only one alien race, with three eyes and three tentacles - we only ever see stylised statues of them, so the eyes inline could just be part of that (like their tentacles only having 90 degree corners)
Answer: My two cents:
Owls: first of all, this is a clear reference to the Twin Peaks series,
the red drapes lodge around the graveyard levels is a place with which you travel
into that world. This is also true in TP, where the lodge is a place inhabited by spirits, who can travel between planes. Owls play a prominent role, as a spiritual embodiment of evil and darkness. The killer BOB is seen transforming into it several times. Also, it is implied that they are extraterrestrial.
As for the Big heads story, at the starting sequence, the megahedron thinks you are actually of the ???, I think he returns every once in a while, and performs some sort of checkup with the big heads. In the translated sequence ( see youtube ) he says "whats with your head?" meaning he has mistaken Gomez for a big head ancestor. He then shatters, maybe gomez was not supposed to perform the checkup?
Comment: I think you're right about the references to the Black Lodge and Twin Peaks, I'd forgotten owls featured in Twin Peaks. For an upvote include links to the videos and translations you're referring to.
Comment: I added some ??? marks where the sentence wasn't clear. (If my edit gets peer reviewed of course ;) ). With some work, and like @Keith said more links. This can be a good answer.
Answer: Totally in agreement; If you think about the "world tree" as a tesseract, then Gomez is really moving around in time as well as space, and you can piece together a rough history. After the fall of the classical, stargate-using age, it seems like they had to migrate to other 'worlds' and reinvent things (mechanical age, broken rainy world, death world?) and somehow Gomez' village is the end, a sort of sheltered pocket universe where the remainder of the population live (and evolved into their current form), but it's been so long, they forgot they lived in three dimensions. Maybe the big head = slightly larger brain, and by Gomez' time their brains have shrunk... :)
I have a related theory (spoiler)

 that the time travel setup is also linked to the "tree rings" you can see on the ground in a New Game+; blocky pyramids appear in a few places. These possibly indicate there's a pyramid in time, as well. The center square is the same place in space, but you're in a different time level in each location.
Answer: I think the backstory of Fez goes like this:
The tall, 2-dimensional seeing men hunted and lived in caves (shown as big carved stones with windows). They knew how to draw, and they worshipped the owls. As time passed, they evolved into the big heads, who have their own alphabet and numeral system. The visitors came, and the first Fez greeted them. The visitors gave them the technology to make stargates and warp gates.
Because of this, the Fez became ruler of the big heads. However, when they tried to use their newly made stargate, something went wrong and it broke. Here, there are no more etchings, and it jumps to the modern city. I think that some of the big heads rebelled and went to a small island, and some went to another island. The original civilization went to the waterfall hub they made and went to the last door of the hub. They entered it and begun to rebuild their civilization, and now their hypercube symbol just became part of their "fashion sense." They discovered an artifact that sensed movement.
A stray big head became lost between worlds. He made Hypercube pillars in some places, and made a stone etching for people to see and rescue him. The big heads on the small island renounced their religion, alphabet and numeral system, and slowly became Gomez's ancestors. The other island's Long heads were mostly engineers of the king. Their knowledge on technology made them an advanced civilization, but a black hole engulfed them. Then Gomez was born, Gezzer got his Fez, and here they are now.
Comment: Can you please edit your post so that it's less 'wall-of-text-in-your-face'? Punctuations are all over the place in this one as well.
Answer: Here's what I personally think about the backstory of Fez:
The first people to exist were the long-headed people, who didn't know the third dimension existed. Then, owls showed them the third dimension, possibly in the form of handing out Fezzes. The long-headed people, with access to the third dimension, built a lot of Fez's landscape and evolved into the square-headed people, as well as Gomez's species. However, at some point, some tentacle alien things (what you called the Visitors) came and attempted to steal the third dimension, but there was still 1 Fez left. This Fez was passed down through the generations, until eventually going to Gomez. Then, all of Fez happened.

What's the back-story in Fez?


regex match as long as it comes before an optional character

Question: I currently have the regex /\B(?=(\d{3})+(?!\d))/g but I only want it to match as long as it comes before . iff . exists.
In other words 12345 can match. But 12345.6789 can't have matches after .
An easy workaround would be to make if else blocks breaking up the cases but I'd like it to it in a single regex

More detail
I'm working in javascript and making a regex to help me format numbers. Specifically, this regex will insert commas into numbers.
Currently this code works like this:
function formatter(myNum) {
   return myNum.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}

Input 1: 12345.6789
Output 1: 12,345.6,789
Desired Output 1: 12,345.6789
Input 2: 12345
Desired Output 2: 12,345.6789
Hopefully that clears up any confusion.

I want it to match when there is no .
If it does have a . it should be able to match before
I can make a simple work-around but it seems like regex should handle this easily?
Comment: It's not clear exactly what you want. Please clarify by showing a few more input examples to illustrate what matches and what doesn't. And make it clear if you want the entire input to match or only part of it.
Comment: To successfully skip decimals like this `123.456789` the regex engine type must be known.
Comment: @sln it's the one that came with js for me. How can I get you this info?
Comment: More complicated really. Only way I know is with PCRE `(?:(?:(?<!\d)\d{1,3}(?:\.\d*)*(?![.\d])|(?:\.\d*)+)(*SKIP)(*FAIL))|(?<=\d)(?=(\d{3})+(?!\d))` https://regex101.com/r/ZLdqtY/1
Comment: @sln the accepted answer does it.
Comment: Yeah, variable look behind will work if supported. There are other ways just using look ahead,  but its more involved. An important fact here is that `\B` is not appropriate. Need `(?<=\d)` as in `(?<=\d)(?=(\d{3})+(?!\d))`
Comment: So for example using `\B` matches between a5 as seen here https://regex101.com/r/ZYd7ji/1 . For reference, using `(?<=\d)` makes it work as it should like here https://regex101.com/r/9KgIIy/1
Answer: If you can use negative lookbehind with quantifiers (modern JS engines):

function formatter(myNum) {
   return myNum.replace(/(?<!\.\d+)\B(?=(\d{3})+(?!\d))/g, ',');
}

console.log(formatter('1234512345'));
console.log(formatter('1234512345.1234512345'));

See compatibility:

https://caniuse.com/?search=lookbehind
https://node.green/#ES2018-features--RegExp-Lookbehind-Assertions


Why is every second breaker out in my panel?

Question: I have notice that every other circuit breaker in the panel is not working.I also notice after pulling the breakers that they all tested good using a continuity tester!! however inspecting the red wire the bus behind looks burned.The 220 on that line that feeds the washer only has partial power what can be done to fix the problem???
Comment: Possible duplicate of [Half of my lights and oulets are not working after heavy winds?](https://diy.stackexchange.com/questions/62368/half-of-my-lights-and-oulets-are-not-working-after-heavy-winds) ( There are several duplicates to choose from, this is the one I found first).
Comment: In a typical breaker panel, "every other breaker" is fed by one of the legs coming into the box from the meter.  Check the voltage between each leg and neutral to see if you have a power outage.  Turn off the main breaker before checking the voltage, and if there is a problem, the electric utility will most likely have to fix the issue "on their side".
Comment: Does the pattern of out breakers look anything like [this?](https://diy.stackexchange.com/questions/110151/what-is-a-tandem-breaker-aka-duplex-cheater-twin-double-stuff-etc)
Comment: I have seen service calls where half the panel was dead. One of the service entrance wires running between the street pole and the house was touching a branch. Lights sometimes flickered, but only when the wind was blowing and the tree branch was scraping the wire.
Answer: Multiple possibilities.
If you have aluminum feeder wire, check the clamp to that wire AND that anti-oxidation compound was used.  As the load varies, the joint heats up and cools down.  Aluminum expands and contracts more than the other metals, so the wire will squish down and work its way loose!  This happened at our old place.  The panel got hot and I saw arcing at the clamp.  Remember that the wire is electrically hot!
If you have a loose connection to a breaker, that could heat up the bus.
Copper or aluminum bus bars in the panel?  Aluminum oxide is non-conductive, a high-resistance connection can develop.
Feeder wires can be damaged in the ground, including long after the insulation is nicked.


Internet Randomly Stops Working, But Starts Working Again Upon Reboot

Question: I am new to Ubuntu 14.04 LTS and I just installed it today on my Lenovo G50-70 laptop. Before marking this as duplicate, please hear me out. I have read countless posts on this issue, but none have been able to help me. I am having an issue with the WiFi that I didn't have with Windows 10, my previous OS. This issue started since installing Ubuntu when I was trying to install updates. The Internet on my laptop goes out randomly, but all other computers are fine so it can't be my router. Sometimes it stops working after a minute after reboot and sometimes an hour. It's random as to when it will stop working and once it's gone, it doesn't come back unless I reboot. I have 2 Windows 10 machines and another Ubuntu 14.04 machine that my brother runs that is fine. The Internet issue I am facing resolves upon reboot, but it occurs again randomly when I'm browsing and is not fixed by enabling/disabling WiFi or disconnecting/reconnecting. I have to restart the computer to fix the wifi. I ran the command dmesg before the Internet could go out again and got the result. I am unable to post it on here since there's a character limit, but I have the result in a text file. I have also tried to change my ipv6 settings to Link-Local Only, but that didn't resolve the issue. Also, the WiFi icon says that my Internet is fine, but it isn't. Pinging in the terminal also does not work when the Internet is gone, even though the WiFi icon is still active.
After the Internet went out, I ran the command lcpci -v and got:
00:00.0 Host bridge: Intel Corporation Haswell-ULT DRAM Controller (rev 0b)
    Subsystem: Lenovo Device 3978
    Flags: bus master, fast devsel, latency 0
    Capabilities: <access denied>

00:02.0 VGA compatible controller: Intel Corporation Haswell-ULT Integrated Graphics Controller (rev 0b) (prog-if 00 [VGA controller])
    Subsystem: Lenovo Device 380c
    Flags: bus master, fast devsel, latency 0, IRQ 47
    Memory at c0000000 (64-bit, non-prefetchable) [size=4M]
    Memory at b0000000 (64-bit, prefetchable) [size=256M]
    I/O ports at 5000 [size=64]
    Expansion ROM at <unassigned> [disabled]
    Capabilities: <access denied>
    Kernel driver in use: i915

00:03.0 Audio device: Intel Corporation Haswell-ULT HD Audio Controller (rev 0b)
    Subsystem: Lenovo Device 3978
    Flags: bus master, fast devsel, latency 0, IRQ 48
    Memory at c0610000 (64-bit, non-prefetchable) [size=16K]
    Capabilities: <access denied>
    Kernel driver in use: snd_hda_intel

00:14.0 USB controller: Intel Corporation Lynx Point-LP USB xHCI HC (rev 04) (prog-if 30 [XHCI])
    Subsystem: Lenovo Device 3978
    Flags: bus master, medium devsel, latency 0, IRQ 42
    Memory at c0600000 (64-bit, non-prefetchable) [size=64K]
    Capabilities: <access denied>
    Kernel driver in use: xhci_hcd

00:16.0 Communication controller: Intel Corporation Lynx Point-LP HECI #0 (rev 04)
    Subsystem: Lenovo Device 3978
    Flags: bus master, fast devsel, latency 0, IRQ 45
    Memory at c0618000 (64-bit, non-prefetchable) [size=32]
    Capabilities: <access denied>
    Kernel driver in use: mei_me

00:1b.0 Audio device: Intel Corporation Lynx Point-LP HD Audio Controller (rev 04)
    Subsystem: Lenovo Device 3978
    Flags: bus master, fast devsel, latency 0, IRQ 46
    Memory at c0614000 (64-bit, non-prefetchable) [size=16K]
    Capabilities: <access denied>
    Kernel driver in use: snd_hda_intel

00:1c.0 PCI bridge: Intel Corporation Lynx Point-LP PCI Express Root Port 3 (rev e4) (prog-if 00 [Normal decode])
    Flags: bus master, fast devsel, latency 0
    Bus: primary=00, secondary=01, subordinate=01, sec-latency=0
    I/O behind bridge: 00004000-00004fff
    Memory behind bridge: c0500000-c05fffff
    Capabilities: <access denied>
    Kernel driver in use: pcieport

00:1c.3 PCI bridge: Intel Corporation Lynx Point-LP PCI Express Root Port 4 (rev e4) (prog-if 00 [Normal decode])
    Flags: bus master, fast devsel, latency 0
    Bus: primary=00, secondary=02, subordinate=02, sec-latency=0
    I/O behind bridge: 00003000-00003fff
    Memory behind bridge: c0400000-c04fffff
    Capabilities: <access denied>
    Kernel driver in use: pcieport

00:1d.0 USB controller: Intel Corporation Lynx Point-LP USB EHCI #1 (rev 04) (prog-if 20 [EHCI])
    Subsystem: Lenovo Device 3978
    Flags: bus master, medium devsel, latency 0, IRQ 23
    Memory at c061c000 (32-bit, non-prefetchable) [size=1K]
    Capabilities: <access denied>
    Kernel driver in use: ehci-pci

00:1f.0 ISA bridge: Intel Corporation Lynx Point-LP LPC Controller (rev 04)
    Subsystem: Lenovo Device 3978
    Flags: bus master, medium devsel, latency 0
    Capabilities: <access denied>
    Kernel driver in use: lpc_ich

00:1f.2 SATA controller: Intel Corporation Lynx Point-LP SATA Controller 1 [AHCI mode] (rev 04) (prog-if 01 [AHCI 1.0])
    Subsystem: Lenovo Device 3978
    Flags: bus master, 66MHz, medium devsel, latency 0, IRQ 43
    I/O ports at 5088 [size=8]
    I/O ports at 5094 [size=4]
    I/O ports at 5080 [size=8]
    I/O ports at 5090 [size=4]
    I/O ports at 5060 [size=32]
    Memory at c061b000 (32-bit, non-prefetchable) [size=2K]
    Capabilities: <access denied>
    Kernel driver in use: ahci

00:1f.3 SMBus: Intel Corporation Lynx Point-LP SMBus Controller (rev 04)
    Subsystem: Lenovo Device 3978
    Flags: medium devsel
    Memory at c0619000 (64-bit, non-prefetchable) [size=256]
    I/O ports at 5040 [size=32]

01:00.0 Ethernet controller: Realtek Semiconductor Co., Ltd. RTL8111/8168/8411 PCI Express Gigabit Ethernet Controller (rev 10)
    Subsystem: Lenovo Device 380a
    Flags: bus master, fast devsel, latency 0, IRQ 44
    I/O ports at 4000 [size=256]
    Memory at c0504000 (64-bit, non-prefetchable) [size=4K]
    Memory at c0500000 (64-bit, non-prefetchable) [size=16K]
    Capabilities: <access denied>
    Kernel driver in use: r8169

02:00.0 Network controller: Realtek Semiconductor Co., Ltd. RTL8723BE PCIe Wireless Network Adapter
    Subsystem: Lenovo Device b736
    Flags: bus master, fast devsel, latency 0, IRQ 19
    I/O ports at 3000 [size=256]
    Memory at c0400000 (64-bit, non-prefetchable) [size=16K]
    Capabilities: <access denied>
    Kernel driver in use: rtl8723be

I then ran ifconfig and got:
eth0      Link encap:Ethernet  HWaddr 68:f7:28:18:33:e0
          UP BROADCAST MULTICAST  MTU:1500  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:0 (0.0 B)  TX bytes:0 (0.0 B)

lo        Link encap:Local Loopback
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:65536  Metric:1
          RX packets:1392 errors:0 dropped:0 overruns:0 frame:0
          TX packets:1392 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:125457 (125.4 KB)  TX bytes:125457 (125.4 KB)

wlan0     Link encap:Ethernet  HWaddr c0:38:96:12:bd:c7
          inet addr:192.168.1.129  Bcast:192.168.1.255 Mask:255.255.255.0
          inet6 addr: fe80::c238:96ff:fe12:bdc7/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:4186 errors:0 dropped:0 overruns:0 frame:0
          TX packets:4472 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:4124758 (4.1 MB)  TX bytes:810905 (810.9 KB)

I would greatly appreciate if someone could help me on this issue. If you need the results for dmesg, please let me know so that I can post it. Thank you for your time.
Comment: Just a workaround, but upgrading to 15.04 _might_ fix it. If not, it's probably a hardware issue.
Comment: Well that definitely points to it being a driver bug with Ubuntu, though it could still have something to do with your specific hardware. Sorry if I suggest something you've already disproved or tried. I'm just a little busy for the time being.
Comment: Is it just me or is this a more comprehensive duplicate of the question below? http://askubuntu.com/questions/667513/wireless-turns-off-a-few-minutes-after-computer-start
Comment: @Zacharee1 I was not aware of that post as it never showed up in any searches that I conducted. Nonetheless, neither post has an answer.
Comment: That wasn't a duplicate report. I just thought it interesting that two people had the exact problem at the same time. Have you tried reinstalling the network drivers or running `sudo apt-get update` and `sudo apt-get upgrade`?
Comment: @Zacharee1 I already did all those things the moment I installed Ubuntu. The WiFi issues persisted before and after running those commands.
Comment: @Zacharee1 I doubt it's a hardware issue. Like I said, it ran perfectly on WIndows 10 and I did a fresh install of Windows 8.1 30 minutes ago over 14.04 and everything is running perfectly. I then fresh installed 14.04 and the same issue is arising. This looks to be a software-related issue on Ubuntu's part. I'll try your suggestion on 15.04
Comment: possible duplicate of [lenovo e540 RTL8723be wifi not working](http://askubuntu.com/questions/517772/lenovo-e540-rtl8723be-wifi-not-working) To moderators: The answer below should be merged with the duplicate.
Comment: @user68186 Thanks for your comment, however, I have seen that post already and its solutions did not help me, but they helped the OP (thus why a best answer was selected). Therefore, merging my solution to this post with the other post makes no sense.
Comment: I will remove the duplicate recommendation.
Comment: @Zacharee1 This does looks like the same exact problem [I'm having](http://askubuntu.com/questions/667513/wireless-turns-off-a-few-minutes-after-computer-start).
Answer: I found a solution, but it is not THE solution. According to my searches on this issue, for some odd reason, majority of the machines having this problem are by Lenovo. I'm not sure if this issue is a result of hardware conflicts or what, but I "fixed" the issue by installing a fresh copy of 15.04 and it is working perfectly.
The machine started off at Windows 8 and was perfect for 8.1 and 10. When I installed a fresh copy of 14.04, I experienced the issue I detailed above. I experienced the same issue at 14.10. When I reinstalled a fresh copy of Windows 8.1, the laptop functioned perfectly. When I tried 14.04 again, same issue. This leads me to believe that there is some sort of problem with what's being supported in 14.04. When I fresh installed 15.04, everything ran perfectly.
So if you're having this issue and you absolutely cannot figure out how to fix this problem, I recommend trying out 15.04. Yes, it's not a solution to the problem since I, myself, wanted 14.04 LTS, but at least with this method, your laptop isn't useless.
For now, I will mark this as the best answer.
Comment: This bug is probably already reported. See search results at  https://bugs.launchpad.net/ubuntu?field.searchtext=rtl8723be&search=Search&field.status%3Alist=NEW&field.status%3Alist=INCOMPLETE_WITH_RESPONSE&field.status%3Alist=INCOMPLETE_WITHOUT_RESPONSE&field.status%3Alist=CONFIRMED&field.status%3Alist=TRIAGED&field.status%3Alist=INPROGRESS&field.status%3Alist=FIXCOMMITTED&field.assignee=&field.bug_reporter=&field.omit_dupes=on&field.has_patch=&field.has_no_package= and find the most appropriate one for you. Then add yourself as affected by the bug. thus the bug gets more attention.
Comment: Interesting, upgrading to 15.04 didn't work for me.
Comment: @TheNumberOne Did you rule out hardware malfunction? Was it a fresh install?
Comment: @JoffreyBaratheon I did rule out hardware malfunction. However, I did use apt to upgrade my system instead of doing a fresh install. I found that switching to WEP encryption fixes the problem.


Search marked word with single keystroke?

Question: Is there a way in Visual Studio Code (current, v1.81.1) to mark a word, then search for this, with a single keystroke?
In one of my earlier editors, I used to mark something, then hit F3, which would jump to the next occurrence immediately. One keystroke. Very convenient.
Currently, in Visual Studio Code, I find myself hitting Cmd-F, then Enter, to achieve the same. Two keystrokes.
Answer: Press F1 -> open keyboard shortcuts
And then search for "find". I think the behavior you described is "Find next Selection" (for me Ctrl+F3):
Comment: Oh my, so easy? On my Mac it's Cmd-F3 and working out of the box. Thx.


Vim spell highlighting

Question: I want to change vim cyan highlighting, like on Autocompletion word:

Please note, only change, do not remove.
I've already changed red highlighting for SpellBad to underline with the next settings:
<code>hi clear SpellBad
hi SpellBad cterm=underline
</code>
But the same strategy for SpellRare doesn't work for me.
Comment: I think you should get your question migrated to [Vi and Vim](https://vi.stackexchange.com/)
Comment: @VladHatko There are other highlight groups containing the keyword `spell` in their name. To list them, you can type `:hi *spell*`, then hit `C-d` (`control`+`d`; not `Enter`). On my machine, it lists `SpellBad`, `SpellCap`, `SpellLocal`, `SpellRare`. Maybe you need to change one of them. If for some reason, your changes are not taken into account, they may be overwritten by a plugin. To see where a highlight group was last defined, you can use the `:verbose` modifier. For example: `:verb hi spellrare`
Comment: Are you using `gvim` or command line `vim`?
Comment: dlmeetei, command line vim
Answer: With the help from user852573 I finally get it to work. My mistake was setting SpellRare, instead of SpellLocal.
Currently my .vimrc looks like this:
<code> hi clear SpellBad
 hi SpellBad cterm=underline
 hi clear SpellRare
 hi SpellRare cterm=underline
 hi clear SpellCap
 hi SpellCap cterm=underline
 hi clear SpellLocal
 hi SpellLocal cterm=underline
</code>
And an entire editor free from this highlighting.

Vim spell highlighting


Bad encoding using smart card decryption

Question: I'm using the RSACryptoServiceProvider to encrypt and decrypt simple strings and while it works with normal certificates, it's giving me some grief when it comes to smart cards.
Here is the code I'm using:
private X509Certificate2 _cert // this certificate is set early on in the program

private string Encrypt(string Data)
{
    if (string.IsNullOrEmpty(Data)) return default(string);

    RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)_cert.PublicKey.Key;
    return Convert.ToBase64String(((rsa.Encrypt(Encoding.Unicode.GetBytes(Data), true))));
}

private string Decrypt(string CipherText)
{
    if (string.IsNullOrEmpty(CipherText)) return default(string);

    RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)_cert.PrivateKey;
    return Encoding.Unicode.GetString(((rsa.Decrypt(Convert.FromBase64String(CipherText), true))));
}

It does decrypt successfully (no errors) but the encoding isn't correct. It's giving me results like

\u08d8黔㡉Ẑ༴쨳층器\u0888諬翉烽偪䚘螷퓰薑낯ꄯ鯪ꘇ台ᾨ鳞텟칆蘟マ⺁ൿ䤳譻宐Ṹ鉱㒎艴偃堎え뢈癘蚰૩�⸮賆슉ଞ맿댿䀵㓹摵�뼚⡨ቾ᳓낣쏀ꖌ엷ὦ楐豎⸌ꅑ뙳餱Ч鎋筧粅嚄罜칮嬒쐞ڮ묭泊䘐쫦⊗邀☇仇挃箍絁绺罽华⏓፦귪ﻳ咷믭鹺簽艉闼敹Ԓ嵯젨泪ꔤ狫ꆙ\uab41軧\n"

What's also interesting is no matter what I encrypt, the decrypted byte[] length is always 256.
I know smart card private key operations always take place on the card itself so I'm sure that has something to do with it but I was hoping some of you have experience with this and can save me the mounds of trial-and-error.
Thanks!
Comment: What about RSA message length limitations? If you try to encrypt/decrypt long messages, you can face some troubles: http://stackoverflow.com/a/8418238/3899583
Comment: Length was one of the things I checked. My key size is 2048 and my plain text is simply the word "test" (no quotes).
Answer: It seems your Smart Card performs so called raw or textbook RSA. In other words, it only performs modular exponentiation, leaving the PKCS#1 v1.5 (EME-PKCS1-v1_5) or - in your case - OAEP (EME-OAEP decoding) decoding up to you. This padding has the same size as the key size / modulus size. In your case that would be 256 bytes or 2048 bits.
So something is very wrong with the Smart Card that's used. Unpadding should be an integral part of the functionality provided by it; it makes little sense to do that on the PC.
The padding largely consists of random (looking) data so it's little wonder that it looks like random text, especially now UTF-16 LE is being used (incorrectly called Unicode by .NET).
Comment: I agree that something is going on inside the Smart Card and your post makes sense to the constant length I'm getting. I use this same code on an HSM protected certificate and it works perfectly. The cards I'm using are Gemalto ID Prime (.NET). I'm dumping CAPI and working with CNG and as soon as I get to the Smart Card KSP I'm going to swing back around on try to get this working.


Installing Python modules on Ubuntu

Question: I have been using Python on Windows for a while, so I'm into a lot of modules, including Pygame and LiveWires, but how do I install them into Ubuntu?
I have the py file for LiveWires, which has been specially edited (from a book I'm reading). I want to install it, but I'm not sure how to. I also want to install Pygame, but I can't.
Answer: In Ubuntu, you can list the packages available with the command
apt-cache pkgnames

but its output is huge, so pipe it to grep and search for what you want, (and then pipe to sort doesn't hurt either).
apt-cache pkgnames | grep py | sort

From this, looks like you want the python-pygame package, so install it with:
sudo apt-get install python-pygame

Answer: Before doing anything I recommend you install virtualenv and virtualenvwrapper. These make it easy to create isolated Python environments for any project you start. This comes in really handy if ever you break anything because it's isolated to one project.
Install Python modules inside a virtualenv is as easy as running:
pip install Pygame

from a terminal. pip will also keep track of what packages are in each of your environments, making it easy to upgrade or uninstall them when needed. Although I don't work on Windows so can't confirm, I believe this solution is also cross-platform.
Comment: Sorry I was unclear. There's no risk from using an IDE. The problem virtualenv solves is making sure you don't load lots of unrelated modules for different projects into the system-wide Python interpreter. Using project-specific Python interpreters means each one only ever has what it needs so you reduce the risk of a conflict.
Comment: I'm studying Python and Linux for the LPI cert right now.  How could you break something so bad that it affects the rest of the system, if you're just working on one python project in set directory?  When I'm on the desktop, would I be at this risk if I'm using an IDE like say, Ninja IDE?
Comment: That's very informative, thank you!  Since you mention that, I will continue to just use my IDE then, since it's more stable than gedit.  Then I don't have to worry about the modules glitch.
Answer: Do this:
$ sudo apt-get install python-pygame

In general, if you want some  on Linux, you search a corresponding package by
$ apt-cache search <python-module>

and install an appropriate package by apt-get install like above.

Installing Python modules on Ubuntu


How to update android app without uninstalled from device

Question: when i try to update version in my android app to own site. The problem will be occured during the installation. that's

App not installed
An Existing package by the same name with a conflicting is already
  installed.

Can any one help how to download updated app without uninstall.
Thanks in advance.
Comment: have you sign apk with same keystore?
Comment: You cannot to that, if you have signed with different `key`
Comment: yes i have tried sign apk with same and different keystore also but not worked
Comment: @VenomVendor i tried different key but not working
Comment: @Android : Is the version on your device a debug version and the update a release version (or the other way around)? You can't update debug -> release or release -> debug.
Comment: @Squonk how to do that can u explain clearly?
Comment: @Android : You haven't answered my question. If you have a debug version on your device and want to install a release version you *MUST* uninstall the debug version first. The same applies if the version on the device is a release version and you want to install a debug version. There is no way around this - debug and release apps are signed with different keys.
Answer: you have to change both
<code>android:versionCode="4"
android:versionName="1.0.4"

android:versionCode is a integer, eveny update increment by 1
android:versionName can any string
</code>
and you use same Keystore
Comment: yes i increament the version code also but not working
Comment: then the problem cloud be with Keystore.
check this link http://stackoverflow.com/questions/19959890/android-app-not-install-an-existing-package-by-the-same-name-with-a-conflicting
Answer: If your installing from your own site, don't increment the version code and name of new apk your uploading, use the same code and name of already existing apk, it will replace the existing one so no need to uninstall the app.
Try by enabling the "install app from unknown source" in device settings
Best way to do Even if your using the app for internal purpose you can sign the app using live keystore(not debug keystore) and upload it in your own site.
Another way to avoid getting your scenario:
If you want only some particular users to download the app that is the reason if you have hosted your app in your own site means, google provides an option to do this for testers where you can add their email in alpha testing or beta testing so that whenever you upload an apk to playstore those users who you have added will be notified and can update the app without uninstalling the existing(this wont be visible to all users who you have not added).


Resource-efficient way to obtain list of all Wikidata items with labels, altLabels and Description?

Question: I want to check if string s is contained in any wikidata item's label, altLabel or description and if so, return all of them. The sheer number of Wikidata items prohibits the use of SPARQL, because it will reach a timeout, so I need to do it locally. I did the same for properties before by performing this query and parsing the result locally:
SELECT ?property ?propertyLabel ?propertyDescription (GROUP_CONCAT(DISTINCT(?altLabel); separator = ", ") AS ?altLabel_list) WHERE {
    ?property a wikibase:Property .
    OPTIONAL { ?property skos:altLabel ?altLabel . FILTER (lang(?altLabel) = "en") }
    SERVICE wikibase:label { bd:serviceParam wikibase:language "en" .}
 }
GROUP BY ?property ?propertyLabel ?propertyDescription

It produces a table that looks similar to this "official" one on wikidata.
What is a space- (and ideally time-)efficient way of obtaining a list/table of all wikidata items with labels, descriptions and altLabels just like the one above? Namely, can I somehow avoid downloading the whole Wikidata dump, parsing it and building the list myself with standard hardware?
I found this tool, but am not sure if is capable of doing what I need. I do not want to waste community resources either.
Answer: The wdumps tool works and would seem to be the closest to what you're asking for, i. e. a complete list. If you look at the list of recent runs of the tool, you may find what you need anyway, because it's a common ask.
Aside from working with the whole list locally, the documentation recommends the SPARQL interface to wikipedia's "regular" search engine, like this:
SELECT ?item ?label
WHERE
{
  SERVICE wikibase:mwapi
  {
    bd:serviceParam wikibase:endpoint "www.wikidata.org";
                    wikibase:api "Generator";
                    mwapi:generator "search";
                    mwapi:gsrsearch "inlabel:Frankfurt";
                    mwapi:gsrlimit "max".
    ?item wikibase:apiOutputItem mwapi:title.
  }
  ?item rdfs:label ?label.
  FILTER CONTAINS(?label, "Frankfurt")
}

And,  as a third possibility, I want to mention the interface at https://query.wikidata.org/bigdata/ldf. This is a little-known API for the data. Judging by its speed and from its documentation, it is very efficient. But, as the linked example query shows, there are half a billion labels, so even a fast method of access such as this will be a challenge.


Is there a positive-semidefinite convolution kernel, that is continuous at $0$ but discontinuous elsewhere?

Question: A positive-semidefinite, symmetric convolution kernel on the circle $\mathbb{T}^1$ is a function $k:\mathbb{T}^1\to\mathbb{R}$ such that $k(x)=k(-x)$, and $\sum_{i=1}^n\sum_{j=1}^n k(x_i-x_j)c_i c_j\geq 0$ for all sequences $x_1 \ldots x_n \in \mathbb{T}^1$ and $c_1 \ldots c_n\in\mathbb{R}$.
Question: does there exist a positive-semidefinite convolution kernel, that is continuous at $0$ but discontinuous somewhere else?
Motivation: Mercer's theorem tells us that a symmetric continuous positive-semidefinite kernel has a basis of eigenfunctions, whose eigenvalues have finite sum. I am looking for examples of discontinuous functions to show how these predictions fail. Convolution kernels on the circle are simple place to look, as their spectrum can be computed by Fourier analysis.
Thus the problem is equivalent to asking if there is a cosine series with non-negative terms that is continuous at 0 but not somewhere else.
Attempts so far:
A first thought would be a step function: $k(x) = I(|x|<\Theta)$. But this is not positive semidefinite.
A second try goes in reverse: take $k(x) = \sum_{n=1}^{\infty} {\cos(nx) \over n}$. The eigenvalues are 1/n, so the conclusions of Mercer's theorem cannot hold. But also see that $k(0) = \infty$. This kernel is discontinuous in a very specific way: it's value tends to infinity at $x=0$.
A third try would be $k(x) = \sum_{n=1}^{\infty} {\cos(n^2x) \over n^2}$. This converges absolutely for all $x$. But it turns out to be "Riemann's example" - a classic pathological function that is continuous everywhere but differentiable almost nowhere.
Are all discontinuous positive-semidefinite convolution kernels discontinuous at $x=0$? Or are there some which are well behaved at $0$ with other types of discontinuity, such as a jump at a point $x\neq0$?
Comment: If there are counterexamples, the theorem is not valid. Please specify the additional conditions that are crucial for the theorem.
Comment: Thanks - the title wasn't phrased right. The theorem is certainly valid, I'm looking for examples that don't fulfill the conditions of the theorem. Title changed accordingly.
Answer: The answer is no: if the kernel is discontinuous, it cannot be finite at $x=0$. The trick came from a related question. (At least for kernels definable by Fourier series, and any others will be pretty pathological.)
If the kernel function can be expressed as a Fourier series, this series will have only cosines, and they will have only non-negative coefficients. If such a Fourier series converges at 0, the coefficients must be in $l^1$, which means the kernel function is continuous everywhere.


fancybox thumbnail helper not working because of dir="rtl"

Question: I am testing fancybox thumbnail helper on my site.
However I just found that because of the line -

setting the site to be a right to left text website the thumbnails are moved off screen and only if there are enough of them (over 5) they start popping out from the right side of the screen.
I now put the page online so you can have a look-
The sheep page
Click on the pictures of the sheep to get the fancybox. some don't have enough images in their library to get the thumbnails showing and some have enough.
Is there anything I can do to make fancybox work with a rtl website?
Thank you!
Yael :)
Comment: Ok, I found a work around. :)
For only that specific page, I changed the dir="rtl" tag to be local rather than global.
So it no longer sits in the  tag but inside the bigger  tag which houses all the page's content.

And the  which houses the pictures who call the fancybox, has it's dir="ltr" set inside the table tag to flip the direction for only that specific table.

It works  :)
Comment: So what you're saying is if you remove the `dir=""` entirely, fancybox starts working again? You're 100% sure that's the cause of your fancybox not working?
Comment: Yep! thats exactly what I am saying :)
When I removed it, it worked.
Comment: Also, I found out now, that it is not that the thumbnails are not working- they are simply 'off screen'.

When there are enough of them they get pushed into view, but obviously are not synced with the image and get pushed off screen again once you click them all
Comment: Thanks for looking @Howdy_McGee !
ok, i uploaded the page so you can have a proper look :) -
[link](http://www.gaderkivsa.co.il/sheep.html)
If you click the first sheep images from the left the thumnails are off the screen (as there are only 3) but if you click the next two, there are enough thumnails that they get pushed into view
Comment: It seems to be working fine for me, if I click the sheep thumbnails in the content i opens up in the fancybox as expected. I even checked, the htl has rtl direction.
Comment: @Howdy_McGee really?! did the thumbnails open up under the image for you as well? even when you clicked the first sheep on the left (the red one with the yellow clouds)? which browser did you use?
Comment: @Howdy_McGee : thumbnails helper is the core of the question and they don't work properly (Firefox, Chrome, Opera, Safari and IE ) when setting `dir="rtl"`. very good question BTW
Comment: Thank you @JFK :) any idea for the solution? :)
Comment: @Yaeluk : you should post your workaround as an answer and accept it (it's encouraged to answer your own questions) so it will help others with the same issue.
Comment: @JFK thanks! I will do it right away :) (I am new to this so thanks for the tips!)
Answer: Ok, I found a work around. :)
For only that specific page, I changed the placement of the dir="rtl" attribute to be local rather than global. So it no longer sits in the  tag but instead it now sits inside the biggest
 tag in the body of the page, the one which houses all the page's content. And the
 which houses the pictures who call the fancybox, has it's dir="ltr" set inside the table tag to flip the direction for only that specific table.
It works :)
Answer: You could add direction: ltr to any element you want to reset the direction on:
.fancybox-wrap, .fancybox-thumbs {
   direction: ltr;
}

Answer: in file name jquery.fancybox-thumbs.js
replace every left to right in all file
:D


Dagger 2 Modules and generic parameters in Kotlin

Question: The question is if Dager 2 supports proper Generic parameters. I have the following test class:
@Module
class Test {

    @Provides
    fun t(
        l: List<String>,
        l1: List<Number> /* Error points to this dependency */
    ): String {

        return "String" + l + l1
    }

    @Provides
    fun list1(): List<Number>{
        throw Error()
    }

    @Provides
    fun list() : List<String> {
        throw Error()
    }
}

in the AppComponent I have usage
@Component(modules = [Test::class])
interface AppComponent {

    fun str(): String
}

When I try to compile I got the following error:

/AppComponent.java:8: error: [Dagger/MissingBinding] java.util.List<? extends java.lang.Number> cannot be provided without an @Provides-annotated method.
public abstract interface AppComponent {
^
java.util.List<? extends java.lang.Number> is injected at
com.example.android.dagger.di.Test.t(…, l1)
java.lang.String is requested at
com.example.android.dagger.di.AppComponent.str()

The question is if Dagger support usage of generic parametered types in modules
UPDATE
As per @Jeff_Bowman answer, the convenient way of removing wildcards would be with usage on Kotlin typealias, like this:
typealias NumericList = List<@JvmSupressWildcards Number>

@Module
class Test {

    @Provides
    fun t(
        l: List<String>,
        l1: NumericList
    ): String {

        return "String" + l + l1
    }

    @Provides
    fun list1(): NumericList{
        throw Error()
    }

    ........

}

Answer:
java.util.List<? extends java.lang.Number> cannot be provided without an @Provides-annotated method

Note the wildcard: Kotlin defaults to using wildcards in a way that Java does not. You can adjust those types using the @JvmWildcard and @JvmSuppressWildcards to ensure Dagger sees matching declarations.
You have your choice of whether the parameter has wildcards suppressed or whether your @Provides return value has wildcards added. The answer may depend on whether you expect most of your call sites to be Java versus Kotlin.
@Provides
fun t(
    l: List<String>,
    l1: List<@JvmSuppressWildcards Number>  // Note wildcard suppression
): String {
    return "String" + l + l1
}

See also:

Dagger in Kotlin: gotchas and Optimizations (Manuel Vivo, July 2019)
google/dagger#900: Kotlin+Dagger best practices/documentation/pain points (comment by tasomaniac, October 2017)
Dagger 2 with Kotlin, returning type with generic in ApplicationComponent (SO user Bisca, March 2017)


Angularjs: Can I have my directive run after controller API callback

Question: first time asker. Apologies if my jargon isn't quite right I'm new to angularjs
I have a controller which gets a list of products with a HTTP call
contractManagementControllers.controller('PriceBandsCtrl', ['$scope', '$routeParams',     '$http', '$location',
    function ($scope, $routeParams, $http, $location)
    {
        $http.get('products').success(function (products)
        {
            $scope.productList = products
        })
    }

And a directive which I would like to have access to that product list.
contractManagementControllers.directive("priceBands",function($http)
{
    return {
        scope: true,
        restrict: 'AE',
        replace: 'true',
        templateUrl: 'Partials/PriceBand.html',
        link: function ($scope, ele, attrs, c)
        {
            // use $scope.productList
        }
});

My issue is with the order in which things happen.  The controller function runs first, followed by the directive link function, followed by the callback which sets the product list.  As such $scope.productList is undefined in the directive link function and gives an error
Is there a way to force the link function to wait until the callback has completed?
Answer: Set default value to productList in order not get error about undefined variable
contractManagementControllers.controller('PriceBandsCtrl', ['$scope', '$routeParams',     '$http', '$location',
    function ($scope, $routeParams, $http, $location)
    {
        $scope.productList = [];
        $http.get('products').success(function (products)
        {
            $scope.productList = products
        })
    }

and then watch for changes of the productList in directive:
contractManagementControllers.directive("priceBands",function($http)
{
    return {
        scope: true,
        restrict: 'AE',
        replace: 'true',
        templateUrl: 'Partials/PriceBand.html',
        link: function ($scope, ele, attrs, c)
        {
            $scope.watch('productList', function(newValue, oldValue) {
                //Perform here if you need
            });
        }
});

Comment: That's great thanks, although turns out the watch needs a dollar sign
$scope.$watch
Answer: no need of waiting for callback in angularjs. just put the $scope.productList=[]; in your controller as first line. it will not give undefined to directive.
In your directive link function just write the $watch function to watch changes in element.


Does the following set spans the real vector space $\mathbb{C} $

Question: Does the set $\beta = \{2i-1,2i+3,4 \} $ spans the real vector space $\mathbb{C} $ ?
What I have done:
$span(2i-1,2i+3,4) = \mathbb{C} $
Let $a,b,c,d,e \in \mathbb{R}$ then
$a(2i-1)+b(2i+3)+4c = d+ie$
$-a+3b+ 4c + (2a+2b)i = d+ie $
$\implies$ $-a+3b+ 4c =d $ and  $2a+2b = e $
Which gives
$b = \dfrac{e}{2} - a$ and  $c = \dfrac{d}{4} + a - \dfrac{(3 e)}{8}$
As $b,c$ are dependent on $a$ as well. So, $span(2i-1,2i+3,4) \neq \mathbb{C} $
Is this solution correct ?
Comment: @MorganRodgers Doesnt this gives us same system of linear equations as I wrote above?
Comment: @JalilAhmad Presumably it is so you can turn it into a matrix system, and apply the usual Gaussian elimination procedures. However, I think not doing this is better, not because it's simpler, but because in my experience, students who turn everything into matrices automatically tend to miss the finer points of linear algebra (like someone who reaches for a calculator to do every piece of arithmetic).
Comment: By the way, what are $x$ and $y$? You have $a, b, c, d, e$, but nothing about $x$ and $y$.
Comment: @TheoBendit That was a mistake. I have edited the question.
Comment: @MorganRodgers Thank you for your time.
Answer: Your working is good, up until the final line, where you draw a false conclusion. Dependence on $a$ signifies that the solution is not unique, not that there are no solutions. It just means that $a$ can be chosen arbitrarily, while $b$ and $c$ depend on the choice of $a$.
For example, we could make the executive decision that $a = 0$. From this arbitrary choice, we conclude that
\begin{align*}
b &= \frac{e}{2} \\
c &= \frac{d}{4} - \frac{3e}{8}.
\end{align*}
This gives us a linear combination of the three vectors to produce our arbitrary vector $d + ei$. Thus, every $d + ei$ lies in the span of our three vectors.
What the infinitely many choices implies is that the set of vectors is not linearly independent. This is to be expected: we have a two-dimensional space, so any three vector set must be linearly dependent.
Comment: @Hanno Indeed it is.
Comment: Thank you sir...
Comment: @JalilAhmad
This is a good answer, so I voted it up. What about you?


RAID array doesn't reassemble after reboot

Question: RAID array doesn't assemble after reboot.
I have one SSD from which the system is booted, and three HDD that are part of the array. The system is Ubuntu 16.04.
The steps that I've followed are based mostly on this guide:
https://www.digitalocean.com/community/tutorials/how-to-create-raid-arrays-with-mdadm-on-ubuntu-16-04#creating-a-raid-5-array

Verifying if I'm good to go.
lsblk -o NAME,SIZE,FSTYPE,TYPE,MOUNTPOINT

The output shows sda, sdb, and sdc devices besides the SSD partitions. I've verified if these in fact represent HDDs by looking at output of this:
hwinfo --disk

Everything matches.

Assembling the array.
sudo mdadm --create --verbose /dev/md0 --level=5 --raid-devices=3 /dev/sda /dev/sdb /dev/sdc

I verify if it looks OK by entering: cat /proc/mdstat
The output looks something like this:
Personalities : [linear] [multipath] [raid0] [raid1] [raid6] [raid5] [raid4] [raid10]
md0 : active raid5 sdc[3] sdb[1] sda[0]
      7813774336 blocks super 1.2 level 5, 512k chunk, algorithm 2 [3/2] [UU_]
      [=======>.............]  recovery = 37.1% (1449842680/3906887168) finish=273.8min speed=149549K/sec
      bitmap: 0/30 pages [0KB], 65536KB chunk

unused devices: <none>

I wait till the process ends.
Personalities : [raid1] [linear] [multipath] [raid0] [raid6] [raid5] [raid4] [raid10]
md0 : active raid5 sdc[3] sdb[1] sda[0]
      209584128 blocks super 1.2 level 5, 512k chunk, algorithm 2 [3/3] [UUU]

unused devices: <none>

Creating and mounting the filesystem.
sudo mkfs.ext4 -F /dev/md0

sudo mkdir -p /mnt/md0

sudo mount /dev/md0 /mnt/md0

df -h -x devtmpfs -x tmpfs

I put some data in, and the output looks like this:
Filesystem      Size  Used Avail Use% Mounted on
/dev/nvme0n1p2  406G  191G  196G  50% /
/dev/nvme0n1p1  511M  3.6M  508M   1% /boot/efi
/dev/md0        7.3T  904G  6.0T  13% /mnt/md0

Saving the array layout.
sudo mdadm --detail --scan | sudo tee -a /etc/mdadm/mdadm.conf

sudo update-initramfs -u

echo '/dev/md0 /mnt/md0 ext4 defaults,nofail,discard 0 0' | sudo tee -a /etc/fstab

Rebooting and verifying if everything works correctly.

After reboot I try:
    cat /proc/mdstat
It isn't showing any active raid devices.
ls /mnt/md0

is empty.
The following command isn't printing anything and doesn't work either:
mdadm --assemble --scan -v

Only the following restores the array with data on it:
sudo mdadm --create --verbose /dev/md0 --level=5 --raid-devices=3 /dev/sda /dev/sdb /dev/sdc

What should be done differently?
Additional, probably useful info:
sudo dpkg-reconfigure mdadm

The output shows:
update-initramfs: deferring update (trigger activated)
Generating grub configuration file ...
Warning: Setting GRUB_TIMEOUT to a non-zero value when GRUB_HIDDEN_TIMEOUT is set is no longer supported.
Found linux image: /boot/vmlinuz-4.4.0-51-generic
Found initrd image: /boot/initrd.img-4.4.0-51-generic
Found linux image: /boot/vmlinuz-4.4.0-31-generic
Found initrd image: /boot/initrd.img-4.4.0-31-generic
Adding boot menu entry for EFI firmware configuration
done
update-rc.d: warning: start and stop actions are no longer supported; falling back to defaults
Processing triggers for initramfs-tools (0.122ubuntu8.5) ...
update-initramfs: Generating /boot/initrd.img-4.4.0-51-generic

The intriguing part for me is "start and stop actions are no longer supported; falling back to defaults"
Also the output of /usr/share/mdadm/mkconf doesn't print any arrays at the end.
# mdadm.conf
#
# Please refer to mdadm.conf(5) for information about this file.
#

# by default (built-in), scan all partitions (/proc/partitions) and all
# containers for MD superblocks. alternatively, specify devices to scan, using
# wildcards if desired.
#DEVICE partitions containers

# auto-create devices with Debian standard permissions
CREATE owner=root group=disk mode=0660 auto=yes

# automatically tag new arrays as belonging to the local system
HOMEHOST <system>

# instruct the monitoring daemon where to send mail alerts
MAILADDR firstname.lastname@example.com

# definitions of existing MD arrays

whereas the output of cat /etc/mdadm/mdadm.conf does.
# mdadm.conf
#
# Please refer to mdadm.conf(5) for information about this file.
#

# by default (built-in), scan all partitions (/proc/partitions) and all
# containers for MD superblocks. alternatively, specify devices to scan, using
# wildcards if desired.
#DEVICE partitions containers

# DEVICE /dev/sda /dev/sdb /dev/sdc

# auto-create devices with Debian standard permissions
CREATE owner=root group=disk mode=0660 auto=yes

# automatically tag new arrays as belonging to the local system
HOMEHOST <system>

# instruct the monitoring daemon where to send mail alerts
MAILADDR email@example.com

# definitions of existing MD arrays

# This file was auto-generated on Sun, 04 Dec 2016 18:56:42 +0100
# by mkconf $Id$

ARRAY /dev/md0 metadata=1.2 spares=1 name=hinton:0 UUID=616991f1:dc03795b:8d09b1d4:8393060a

What's the solution? I've browsed through half the internet and no one seems to have the same problem.
I've also added the exact same question on serverfault a couple of days ago (no answer). I apologize if I violated stack exchange's community rules by doing that.
Comment: Did you manage to solve this problem? I am in a very similar situation and i can't find an answer anywhere
Comment: The solution below (user @Avi) worked for me.
Answer: I had the same problem, I am not sure but the work around I have found was to create new partitions on the raid members of type LINUX Raid and then when creating the array I used the partition rather than using the device.
Comment: Thank you! I was facing the same problem and this is a solution for me: creating the raid on the partitions, not the whole disk: `mdadm --create  /dev/md0 --level=5 --raid-devices=3 /dev/sdb1 /dev/sdc1 /dev/sdd1`
Answer: It seems, this is quite a common problem when using whole disks in an array.
This post gives the latest summary of the problem and how I solved it: mdadm RAID underlaying an LVM gone after reboot
This post helped me to understand and solve my problem: What's the difference between creating mdadm array using partitions or the whole disks directly
Answer: I was unable to reproduce your exact problem, but I think I found a possible reason for the behavior of your system:
When you create the 3 disk RAID5 array with the command:
sudo mdadm --create --verbose /dev/md0 --level=5 --raid-devices=3 /dev/sda /dev/sdb /dev/sdc

While the RAID device is in recovery, the mdadm scan command shows:
sudo mdadm --detail --scan
ARRAY /dev/md0 metadata=1.2 spares=1 name=desktop:0 UUID=da60c69a:1cbe4f2e:e83d0971:0520ac89

After the recovery process is completed, the spares=1 parameter is gone:
sudo mdadm --detail --scan
ARRAY /dev/md0 metadata=1.2 name=desktop:0 UUID=da60c69a:1cbe4f2e:e83d0971:0520ac89

I assume, that reassembling the 3 disk read with the spares=1 parameter will fail on a fully recovered software RAID5, since you don't have any more spared disks. If you try to assemble a RAID with the following command, it will fail:
sudo mdadm --create --verbose /dev/md0 --level=5 --raid-devices=3 --spare-devices=1 /dev/sda /dev/sdb /dev/sdc

and the next command will create a different RAID layout:
sudo mdadm --create --verbose /dev/md0 --level=5 --raid-devices=2 --spare-devices=1 /dev/sda /dev/sdb /dev/sdc

On a different note: If you don't need to boot from the RAID5, there is no need to add the configuration to the /etc/mdadm/mdadm.conf file. Ubuntu will automatically start the RAID, since the configuration is available in the RAID superblock.
Answer: I had the exact same problem.  Solved by:
$ sudo update-initramfs -u

followed by a reboot
Answer: The solution is the following: You scan all drives that do not carry your OS. Then you choose from those what drives you want to select. Before creating any RAID you need to format the drives to a compatible format like ext4. See my example bash code to select all drives from a rented computer except the OS drive and build a RAID0 for maximum speed to later form a fast database node.
{
  #database here
  cd "/home/$1/UltiHash/"
  cwd=$(pwd)
  sudo systemctl start postgresql.service
  sudo service postgresql restart
  if ! [[ $(sudo -u postgres psql --command='SHOW data_directory') == *"/mnt/md0/postgresql/13/main"* ]]; then
    sudo chown -R ${mainuser} /home/${mainuser}/
    echo "${passwd}\n${passwd}\n" | sudo passwd postgres
    echo "postgres password set!"
    sudo usermod -aG sudo postgres
    echo "Configured postgres as a root user"
    sudo postgres -D /usr/local/pgsql/data > logfile 2>&1 &
    version=$(psql --version)
    cutter="$(cut -d ' ' -f 3- <<< "$version" )" && tmpcut="${cutter%% *}"
    folver="${tmpcut%%.*}"
    cd /etc/postgresql/${folver}/main
    sudo -u postgres psql --command="ALTER USER postgres WITH PASSWORD '${passwd}';"
    sudo -u postgres psql --command="CREATE USER admin WITH PASSWORD '${passwd}';"
    sudo -u postgres psql --command="ALTER USER admin WITH SUPERUSER;"
    sudo -u postgres psql --command="ALTER USER admin CREATEDB;"
    sudo service postgresql restart
    sudo systemctl stop postgresql
    cd ~/

    #unmask cinnamon
    if [[ $(file /lib/systemd/system/x11-common.service) == "/lib/systemd/system/x11-common.service: symbolic link to /dev/null" ]]; then
      sudo rm /lib/systemd/system/x11-common.service
      sudo apt-get install --reinstall x11-common
      sudo systemctl daemon-reload
      #systemctl status x11-common
    fi

    #scan drives except OS drive
    drivelist=""
    count=0
    os_drive_path="$(df -hT | grep /$ | awk -F " " '{print $1}')"
    os_drive=${os_drive_path%p*}
    no_dev=${os_drive#*/dev/}
    NL=$'\n'
    while read line; do
      if [[ ($line == *nvme* || $line == sd*) && ! ( $line == *"${no_dev}"* ) ]]; then
        drivelist="${drivelist}/dev/${line}${NL}"
        count=$((count+1))
      fi
    done <<< "$(lsblk -f)"

    #create partitions on the free drives directly in ext4 format
    drivelist_overrideable=""
    while read line; do
      drivename=$(echo "$line" | awk -F " " '{print $1}')
      drivelist_overrideable="${drivelist_overrideable}${drivename}${NL}"
      if [[ $drivename == *nvme* ]]; then
        sudo mkfs.ext4 -b 1024 -m 0 -F "$drivename"
      else
        sudo mkfs.ext4 -m 0 -F "$drivename"
      fi
    done <<< "${drivelist}"

    #now we know what has been formatted, so we know the hardware name, now we must scan again and mount the partition to the files created
    #create RAID0
    printf "Y\n" | sudo mdadm --create --verbose /dev/md0 --level=0 --raid-devices="${count}" ${drivelist_overrideable}
    cat /proc/mdstat
    sudo mkfs.ext4 -b 1024 -m 0 -F /dev/md0
    sudo mkdir -p /mnt/md0
    sudo chown -R benjamin-elias /mnt/md0
    sudo chmod -R 777 /mnt/md0
    sudo mount /dev/md0 /mnt/md0
    df -h -x devtmpfs -x tmpfs
    hardware_uid_string=$(sudo mdadm --detail --scan | sudo tee -a /etc/mdadm/mdadm.conf)
    sudo update-initramfs -u
    echo "$(echo "${hardware_uid_string}" | awk -F " " '{print $5}') /mnt/md0 ext4 defaults,nofail,discard 0 0" | sudo tee -a /etc/fstab
    sudo update-initramfs -u

    #safely move database
    sudo rsync -av /var/lib/postgresql /mnt/md0
    sudo mv /var/lib/postgresql/${folver}/main /var/lib/postgresql/${folver}/main.bak
    sudo chown -R postgres /mnt/md0/

    postgresconf="/etc/postgresql/${folver}/main/postgresql.conf"
    sudo cp -f ${postgresconf} ${postgresconf}.bak

    while read line; do
        if [[ $line == data_directory* ]]; then
          echo "data_directory = '/mnt/md0/postgresql/${folver}/main'" | sudo tee -a "${postgresconf}"
        else
          echo "${line}" | sudo tee -a "${postgresconf}"
        fi
    done <<< $(cat ${postgresconf}.bak)

    #setup ports
    sudo sed -i "s/#listen_addresses = 'localhost'/listen_addresses = '*'/" ${postgresconf}

    postgresconf="/etc/postgresql/${folver}/main/pg_hba.conf"

    while read line; do
      echo "${line}" | sudo tee -a "${postgresconf}"
      ipadress=$(echo "${line}" | awk -F " " '{print $4}')
      echo $ipadress
      ipfilter=${ipadress%%/*}
      echo $ipfilter
      sudo iptables -A INPUT -p tcp -s 0/0 --sport 1024:65535 -d ${ipfilter} --dport 5432 -m state --state NEW,ESTABLISHED -j ACCEPT
      sudo iptables -A OUTPUT -p tcp -s ${ipfilter} --sport 5432 -d 0/0 --dport 1024:65535 -m state --state ESTABLISHED -j ACCEPT
    done <<< $(cat /home/${mainuser}/UltiHash/trust_host.txt)
    #restart to load changes
    sudo systemctl start postgresql
    sudo systemctl status postgresql
    #setup firewall
    echo "$(sudo -u postgres psql --command="SHOW data_directory;")"
    sudo rm -Rf /var/lib/postgresql/${folver}/main.bak
    sudo ufw allow 5432/tcp
    sudo systemctl restart postgresql
    sudo systemctl status postgresql
  fi
}||{
  echo "Could not configure database!"
}


Why does Ruby "include?" behave differently when nested within an if/end conditional?

Question: To my mind the following three examples are logically equivalent and ought to generate identical results.
print "Enter your string: "
my_string = gets.chomp

#Example 1
my_string.include? ("j" or "J")
puts "1. Your string includes a j or J."

#Example 2
if
  my_string.include? ("j" or "J")
  puts "2. Your string includes a j or J."
end

#Example 3
if
  my_string.include? ("j") or my_string.include? ("J")
  puts "3. Your string includes a j or J."
end

Here are the results with a capital J.
Enter your string: Jack
1. Your string includes a j or J.
3. Your string includes a j or J.

Here are the results with a lower case j.
Enter your string: jack
1. Your string includes a j or J.
2. Your string includes a j or J.
3. Your string includes a j or J.

For reasons I don't understand, only examples 1 and 3 generate identical results.  In example 2, by contrast, only the first item in the brackets (the lower case j) is evaluated.
But why?  If example 1 works perfectly, why does example 2 fail simply because the "include?" method is nested within an "if/end"?
And if we need to wrap the code in an "if/elsif/end" conditional, is there a way in which to list multiple values to be assessed in an "include?" method without needing to write them out individually as in example 3?  This would be tedious - almost "anti-Ruby" - if there were many values to be evaluated!
In other words, is there a means of making example 2 work correctly?
Comment: The simplest way to get example 2 working may be `my_string.downcase.include?('j')`
Comment: The condition really should be on the same line as the `if`. It's also probably time for you to dabble with regular expressions: `my_string.match(/[j]/i)` would be what you want here, where in that you can add other letters as required.
Comment: Thanks @Tadman, That's a clear example.  It's become obvious that the include? method is far too limiting (e.g. useful only where there is a single value to be checked).  I expanded upon your suggestion as follows (as Example 2b), and it gave me exactly what I was looking for:     `if (my_string.chars & %w[ j J x y z]).any?
  puts "2b. Your string includes a j or J or x or y or z."
end`
Comment: Glad that helped! That translates to: `my_string.match(/[jJyz]/)` if you want to match against arbitrary characters. That's probably a lot more efficient, although regular expressions can be hard to read if you're not familiar with them.
Answer: Here's what's happening in each of these examples:
First Example
This example outputs 1. Your string includes a j or J. regardless of the previous line. The my_string.include? check is being ignored as it's not used in a comparison anywhere, so the second line is just a regular puts.
Second Example
The second example is a little more interesting. ("j" or "J") is syntax in Ruby which will output the first of the provided arguments which evaluates to true. "j" evaluates to true because it's not nil or false, so it becomes the argument of the second include? method. include? is case-sensitive, so it will return false – the string Jack does not include a lowercase j.
You can try this out by running irb and entering something like 1 or 2 or false and 1; you'll see pretty quickly that the first true argument is returned (or false if no arguments are true).
There's no good way to make this work as-is, other than updating the include? check to use something like set intersections. An easier solution may be to downcase the input before checking characters.
Avdi Grimm posted a good video on using and and or in Ruby.
Third Example
The third example is calling include? twice on the string, and returning true when it hits the second call, hence the if statement being evaluated.
Update
papirtiger's answer got me thinking, so I did a bit of digging with Ripper using the following script:
require 'ripper'
require 'pp'

expression = <<-FOO
if true
  puts 'Hello'
end
FOO

pp Ripper.sexp(expression)

Here's the result:
[:program,
 [[:if,
   [:var_ref, [:@kw, "true", [1, 3]]],
   [[:command,
     [:@ident, "puts", [2, 2]],
     [:args_add_block,
      [[:string_literal,
        [:string_content, [:@tstring_content, "Hello", [2, 8]]]]],
      false]]],
   nil]]]

After updating the expression to the following:
expression = <<-FOO
if
  true
  puts 'Hello'
end
FOO

This was the new output:
[:program,
 [[:if,
   [:var_ref, [:@kw, "true", [2, 2]]],
   [[:command,
     [:@ident, "puts", [3, 2]],
     [:args_add_block,
      [[:string_literal,
        [:string_content, [:@tstring_content, "Hello", [3, 8]]]]],
      false]]],
   nil]]]

It looks as though Ruby does indeed ignore any whitespace and evaluate the next expression. I don't have enough expertise to dig much deeper, but after trying a few more examples (such as throwing a dozen newlines in after an if statement), I'm convinced.
Comment: Many thanks samsymons, The reference to the Avdi Grimm video is extremely useful.  I'll also further explore your set intersections example.  I'd been hoping for an easy answer to my question, expecting that there would be a simple way to poke a set of values into the include? method - e.g. include?(a, b, c, .... - but it seems to be a limitation of the include? method that it takes only a single value inside the brackets, so an alternative approach is obviously required for cases which involve the need to test for many possible matches.
Comment: @GingerCat if you want to check string against multiple values, you can use regex and then use `if my_string[/J|j/]`. if you want more sophisticated checks you can use everything regex has to offer.
Comment: Nope - the conditionals in 2 & 3 will never evaluate due to the linebreak after ´if´
Comment: Interesting – if you enter `jack` as input, the second conditional passes. If you enter `Jack` with a capital `J`, it fails.
Comment: papertiger, I removed the white spaces and it did not change the result.  In other words, with or without space, if I wanted the code to work then I had to use the long form, fully-written out version as per Example 3, instead of being able to use the succinct version I tried to use in Example 2.
Comment: The most Ruby-like adaptation of #2 is: `(my_string.chars & %w[ j J ]).any?`
Answer: Ruby interpreter evaluates everything line by line and arguments are evaluated first before calling the method. so for example if you have a code that reads foo(bar('test')), then interpreter will evaluate 'test' first that will return string test, then it will pass that as argument to bar and whatever bar returns will be passed to foo.
Lets apply same analysis to each example.
# Example 1
my_string.include? ("j" or "J")
puts "1. Your string includes a j or J."

interpreter will evaluate "j" or "J" on line my_string.include? ("j" or "J"). If you type in irb "j" or "J", you will see the output is "j". So that line becomes my_string.include?("j"). my_string evaluates to "Jack" so whole expression becomes "Jack".include?("j") which returns false and we dont do anything with that information, we just move to next line and print a statement to screen puts "1. Your string includes a j or J.". So no matter what you enter for string, you will always get same answer from Example 1.
Lets go to example 2. If you remove unnecessary new line after if, you can rewrite it in more understandable way:
#Example 2
if my_string.include?("j" or "J")
  puts "2. Your string includes a j or J."
end

No we already analyzed my_string.include?("j" or "J") and we know it will be same as "Jack".include?("j") which will return false. so we get if false ..., therefore puts statement in if statement will not be executed and nothing is printed to screen.
Last example can be written in clearer way by removing extra new line after if
if my_string.include? ("j") or my_string.include? ("J")
  puts "3. Your string includes a j or J."
end

It will evaluate to if false or true.. which will be if true so it will print the statement.
Comment: I'm glad you groked it @GingerCat
Answer: #Example 2
if
  my_string.include? ("j" or "J")
  puts "2. Your string includes a j or J."
end

In this case "j" or "J" is an expression which evaluates to "j". You can run this in irb to test for yourself. Expressions are always evaluated using a right-left style walk (see http://www.cs.uml.edu/~canning/101/RLWM.pdf). Ruby is a little fuzzy on this as the last method doesn't need parentheses, so you have to just imagine them being there
Thus, an input of "Jack" doesn't cause this to pass because it doesn't include "j"
It's also worth noting that the or operator is not the same as the ||, and it will likely bite you if you don't use it correctly.
It is really more of a Perl-ism for control flow. See Avdi's screencast on it here: http://devblog.avdi.org/2014/08/26/how-to-use-rubys-english-andor-operators-without-going-nuts/
Answer: You may solve this by using the || operator, instead of or - they are not interchangeable. For example 2, try my_string.include?('j') || my_string.include?("J") or even better, my_string.downcase.include?('j')
Comment: Thanks mdkirbym, I agree that either of these solutions would work.  However, I was looking for a really succinct way of writing an expression to check if certain values were included in a string, especially if I had many values to check.  (The J and j examples were just a simplification.) The excellent answers above from several people demonstrate that the include? method is limited to a single value to check - include?(x) - and will never allow include?(x, y, z).  This suggests that a regex solution (as per the luri G comments above) is a better way to go than the include? method.
Comment: Indeed, I focused too much on the last sentence in the question, and didn't pay attention to the other parts. The two major things are 1. Use ```or``` for control flow, use ```||``` for boolean checks. 2. Use regex checks for strings/substrings, use ```include?``` for objects in an array (or keys in a Hash, or Objects in an Enumberable, etc.)


MySQL: Finding duplicates across multiple fields

Question: Background: my employer has a database powered by a really old version of MySQL (3.23). I have been asked to find duplicate serial numbers and MAC addresses in the database.
I was able to find the duplicate serial numbers, but since this version of MySQL doesn't support subqueries, I had to resort to using a temporary table. These are the two SQL statements I ended up using:
CREATE TEMPORARY TABLE IF NOT EXISTS Inventory_Duplicate_Serials
SELECT Serial
FROM Inventory
WHERE Serial IS NOT NULL
GROUP BY Serial
HAVING COUNT(Serial) > 1

SELECT DeviceName, Model, Inventory.Serial
FROM Inventory
INNER JOIN Inventory_Duplicate_Serials
ON Inventory.Serial = Inventory_Duplicate_Serials.Serial
ORDER BY Serial

Now I need to find the duplicate MAC addresses. The problem is the "Inventory" table has three MAC address fields (MAC, MAC2, and MAC3). So, for example, if the value of an item's "MAC" field is the same as the value of another item's "MAC2" field, I need to know about it. How do I go about doing this? Thank you for your time.

UPDATE: Solved. I ended up creating two temporary tables (Inventory_All_MACs and Inventory_Duplicate_MACs). These are the five queries:
CREATE TEMPORARY TABLE IF NOT EXISTS Inventory_All_MACs
SELECT MAC
FROM Inventory
WHERE MAC != ''

CREATE TEMPORARY TABLE IF NOT EXISTS Inventory_All_MACs
SELECT MAC2 AS MAC
FROM Inventory
WHERE MAC2 != ''

CREATE TEMPORARY TABLE IF NOT EXISTS Inventory_All_MACs
SELECT MAC3 AS MAC
FROM Inventory
WHERE MAC3 != ''

CREATE TEMPORARY TABLE IF NOT EXISTS Inventory_Duplicate_MACs
SELECT MAC
FROM Inventory_All_MACs
GROUP BY MAC
HAVING COUNT(MAC) > 1

SELECT DeviceName, Model, Inventory_Duplicate_MACs.MAC AS DuplicateMAC, Inventory.MAC, MAC2, MAC3
FROM Inventory_Duplicate_MACs
INNER JOIN Inventory
ON Inventory.MAC  = Inventory_Duplicate_MACs.MAC
OR Inventory.MAC2 = Inventory_Duplicate_MACs.MAC
OR Inventory.MAC3 = Inventory_Duplicate_MACs.MAC
ORDER BY Inventory_Duplicate_MACs.MAC, DeviceName, Model

Thanks everybody!
Answer: A 'simple' solution that comes to mind is to create a second temporary table that lists all MAC addresses in one column, so you would need to create three entries for one entry from the first temporary table.
Answer: Not 100% sure on this answer but it could be worth a try using LEFT JOINS e.g:
SELECT address1
FROM addresses
LEFT JOIN Inventory_Duplicate_Addresses ad1
ON Addresses.MAC = ad1.mac
LEFT JOIN Inventory_Duplicate_Addresses ad2
ON Addresses.MAC = ad2.mac2
LEFT JOIN Inventory_Duplicate_Addresses ad3
ON Addresses.MAC = ad3.mac3

Answer: CREATE TEMPORARY TABLE IF NOT EXISTS Inventory_Mac
  SELECT Mac
  FROM Inventory

INSERT INTO Inventory_Mac
  SELECT Mac2
  FROM Inventory

INSERT INTO Inventory_Mac
  SELECT Mac3
  FROM Inventory

CREATE TEMPORARY TABLE IF NOT EXISTS Inventory_Duplicate_Mac
  SELECT Mac, COUNT(*) AS cnt
  FROM Inventory_Mac
  GROUP BY Mac
  HAVING COUNT(*) > 1

SELECT DeviceName, Model, im.Mac, i.Mac, i.Mac2, i.Mac3
FROM Inventory_Duplicate_Mac AS im
  JOIN Inventory AS i
    ON    i.Mac  = im.Mac
       OR i.Mac2 = im.Mac
       OR i.Mac3 = im.Mac
ORDER BY im.Mac

Comment: MySQL 3.23 doesn't support unions :( But thank you very much for your time!
Comment: @Roger: Some checks `WHERE Mac IS NOT NULL` can be added to the first 3 queries to lower the number of rows in the temp table (but I think this will not affect the result).
Comment: Thanks for the edit. What you did is essentially what I did (see my edited question). Your answer is what got me started, though, so you're the winner :)


Parametric equation for intersection of curve

Question: Here's the three part question:
A) Find parametric equations for curve which is the intersection of the cylinder $x^2 + z^2 = 1$ and the plane y = -x.
B) Show that the curve lies on the surface $x^2 + y^2 + 2z^2 = 2$.
C) What is the shape of the curve?
What have I done so far?
For (A), should I set the two equations equal to find the curve's equation?
For (B), I believe once I have the curve equation, I can enter the value of x, y, and z into the given equation in (B) to see if it's equal to 2. If it is, it lies on the surface.
For (C), I assume graphing the curve equation would give me the general shape...
Answer: A) The relation $x^2+z^2=1$ calls for the substitution $x=\cos t, z=\sin t$. Then $y=-x$ turns to $y=-\cos t$.
B) Indeed, $\cos^2t+(-\cos t)^2+2\sin^2t=2$. But you can establish this independently: $x^2+y^2+2z^2=x^2+(-x)^2+2z^2=2(x^2+z^2)=2$. The surface in question is an ellipsoid of revolution.
C) When projected onto $xz$, the curve is the unit circle. When projected onto $yz$, the curve is the unit circle. And when projected onto $xy$, the curve is a line segment with direction $-45°$. As is well known, the intersection of a cylinder and a plane is an ellipse (axes $1$ and $\sqrt2$).
You can check all of this by rotating space around the axis $z$ by $45°$, with the transform
$x=\frac1{\sqrt2}(u+v), y=\frac1{\sqrt2}(u-v), w=z$.
The cylinder and the plane become $\frac{(u+v)^2}2+w^2=1$ and $u=0$, so that $\frac{v^2}2+w^2=1$. This is the implicit equation of an ellipse centered at the origin, with axis $\sqrt2$ and $1$.
Also, $u=\frac{x+y}{\sqrt2}=0, v=\frac{x-y}{\sqrt2}=\sqrt2\cos t, w=\sin t$, which is the parametric equation of an ellipse.
Comment: This makes sense, thanks for the quick answer. I'll go back over my notes and rework it.
Answer: Hint for A) Suppose you only had the equation between $x$ and $z$. How would you parameterize this? What would this imply for $y$?
Hint for B) Given that the points of the solution satisfies $y=-x$, what does this tell you about the the sum $x^2+y^2+2z^2$?
Hint for C) Draw the cylinder and draw the plane. It may be more easier to plot with the $y$-coordinate as vertical rather than $z$.


HTML PHP redirect submit form to same page with error message

Question: I am creating a submit contact form. However when the submit button is pressed with incorrect informations, i want it to go back to my contact.php page with an additional error message at the top of the body page such as. "We are very sorry, there were errors found with the form you submitted, these errors appear below:
Incorrect Email
Incomplete Last name" etc
i have two files, contact.php for form and send_form_email.php for email process
in my contact file, i have below code;
$inc = $_GET['inc'];
if($inc ==1) {
            echo "We are very sorry, but there were error(s) found with the form you submitted. ";
            echo "These errors appear below.

";
            echo $error."

";
            echo "Please go back and fix these errors.

";}
    ?>

And in my send_form_email.php, i have following code
function died($error) {
    header("location: contact.php?inc=1");
    die();
}

if(!isset($_POST['first_name']) ||
    !isset($_POST['last_name']) ||
    !isset($_POST['email']) ||
    !isset($_POST['telephone']) ||
    !isset($_POST['comments'])) {
    died('We are sorry, but there appears to be a problem with the form you submitted.');
}

$first_name = $_POST['first_name']; // required
$last_name = $_POST['last_name']; // required
$email_from = $_POST['email']; // required
$telephone = $_POST['telephone']; // not required
$comments = $_POST['comments']; // required

$error_message = "";
$email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
if(!preg_match($email_exp,$email_from)) {
$error_message .= 'The Email Address you entered does not appear to be valid.
';}
$string_exp = "/^[A-Za-z .'-]+$/";
if(!preg_match($string_exp,$first_name)) {
$error_message .= 'The First Name you entered does not appear to be valid.
';}
if(!preg_match($string_exp,$last_name)) {
$error_message .= 'The Last Name you entered does not appear to be valid.
';}
if(strlen($comments) < 2) {
$error_message .= 'The Comments you entered do not appear to be valid.
';}
if(strlen($error_message) > 0) {
died($error_message);}

however, when i entered incorrect name, the error message would not appear.
Can you please kindly help me ?
Regards, Lex
Comment: What is `died`?  Could be what's going wrong.  See example code here:  http://ideone.com/CZp0pz
Comment: echo $error.""; >> this code is not working in contact.php.the rest are working.
Comment: What name are you testing?
Answer: I think you're trying to use $_GET. If so, you can do something like:
if($_GET['inc'] ==1)

Comment: Hi, apology, i have added the code mention above, however $error still not working.


Semidirect products of groups (and its relation to the coproduct)

Question: Suppose I have two groups $G,H$ and a homomorphism $H\rightarrow\text{Aut}(N)$. Suppose further that I have another group $T$ and two maps: $f_G : G\rightarrow\text{Aut}(T)$ and $f_H : H\rightarrow\text{Aut}(T)$.
Does this induce a map $f : G\rtimes H\rightarrow\text{Aut}(T)$ that restricts to $f_G,f_H$ on $G$ and $H$?
The context for this question is as follows. Let $N$ be an ideal of $\mathbb{Z}[\zeta_d]$. Then the multiplicative group $(\mathbb{Z}[\zeta_d]/N)^*$ acts on its additive group $\mathbb{Z}[\zeta_d]/N$ by multiplication. Thus, we may form the semidirect product $\mathbb{Z}[\zeta_d]/N\rtimes (\mathbb{Z}[\zeta_d]/N)^*$. Clearly the first factor acts on $\mathbb{Z}[\zeta_d]/N$ by translation, and the second factor acts on $\mathbb{Z}[\zeta_d]/N$ as mentioned before by multiplication, thus yielding maps
$$\mathbb{Z}[\zeta_d]/N\rightarrow\text{Aut}(\mathbb{Z}[\zeta_d]/N),\qquad\text{and}\qquad (\mathbb{Z}[\zeta_d]/N)^*\rightarrow\text{Aut}(\mathbb{Z}[\zeta_d]/N).$$
(here by Aut I mean automorphism groups of the set)
Gabriel Berger in section 2.3 of his paper "Fake Congruence Modular Curves and Subgroups of the Modular Group" says that this induces an action of $\mathbb{Z}[\zeta_d]/N\rtimes (\mathbb{Z}[\zeta_d]/N)^*$ on $\mathbb{Z}[\zeta_d]/N$ (as a set). However, I don't see how this action can work (his description of the action doesn't seem to be a legit action).
In other words, our $G$ is the additive group of $\mathbb{Z}[\zeta_d]/N$, and $H$ is the multiplicative group of that ring. Then multiplication in the semidirect product is done as follows: $(g_1,h_1)(g_2,h_2) = (g_1 + h_1g_2, h_1h_2)$ (actually his multiplication I think is the opposite of this, but neither multiplication works to make the action that he describes a legit group action).
Now take $t\in\mathbb{Z}[\zeta_d]/N$, and consider the action that he describes (taken as a right-action): $t.(g,h) = (t+g)h$.
Now consider: $t.(g_1,h_1)(g_2,h_2)$.
First, $t.((g_1,h_1)(g_2,h_2)) = t.(g_1+h_1g_2, h_1h_2) = (t+g_1+h_1g_2)h_1h_2 = th_1h_2 + g_1h_1h_2 + h_1^2h_2g_2$
On the other hand, $(t.(g_1,h_1))(g_2,h_2) = ((t+g_1)h_1 + g_2)h_2 = th_1h_2 + g_1h_1h_2 + g_2h_2$
Which are clearly not the same. Pretending that the action is a left-action still doesn't fix things.
Comment: I'm actually more interested in the special case which I wrote above as the "context" for the first question.
Answer: I think all Berger claims is that the semidirect product $\mathbf{Z}[\zeta_{d}] \rtimes \mathbf{Z}[\zeta_{d}]^{*}$ acts on the set $\mathbf{Z}[\zeta_{d}]$. The element $(a,b) \in \mathbf{Z}[\zeta_{d}] \rtimes \mathbf{Z}[\zeta_{d}]^{*}$ acts on $x \in \mathbf{Z}[\zeta_{d}]$ by $x \mapsto b x + a$. It seems to me that this is quite clearly spelled out by Berger, which works in a slightly more general setting.
Comment: Ahhhh, see what he wrote was that $t(x[\gamma]) = (t+x)[\gamma]$ (ie, first add, then multiply), whereas the action you gave was $t(x[\gamma]) = (t\gamma + x)$ (first multiply, then add).
Comment: thanks!

I can't believe I didn't think to check that. My intuition for semidirect products is terrible.
Comment: @oxeimon you're welcome!


Why do manufacturers of most small/medium refrigerators default the door to swing counter-clockwise?

Question: Most people are right-handed, right hand is handy.
However, most small/medium refrigerator doors swing counter-clockwise (top view) by default.  This forces you to move/arrange heavy things with your left hand.
Given that the majority of the population is right-handed, this makes things so inconvenient.
Even if you can change the rotation of the door on some large & expensive refrigerators, their factory setting are still default to counter-clockwise.
So why do refrigerator manufacturers prefer doors that swing counter-clockwise by default?
Comment: Is the fridge in this picture of a right- or left-handed design? Personally I would open this door with my right handed so I'm not sure the picture goes with the question or if I open doors in an unconventional way.
Comment: So I have a question - do manufacturers in say, Israel or other Hebrew speaking countries tend to fit them the other way round? No - really. I have a serious theory about this - honestly!
Comment: I want to thank you who make this question clear and moved it to this proper website.
Comment: Every fridge, freezer or combined fridgefreezer I have ever owned had reversible doors. On occasion I have reversed them if they were situated where the open door caused an issue. I have never reversed them because I prefer to use my left or right hand, as from a usability perspective it is unimportant - anything you do with a fridge will be easy enough with one hand (either) or require two hands. My current fridge freezer opens with the hinge on the right. I am right handed. This is fine - I use my right hand to open the door, then my left to put things in (both when they're very big)
Comment: @Vitaly: There are other countries where they speak RTL-languages such as Arabic. And indeed, I've never seen a "lefty" fridge, though I had a reversible one, and reversed it to fit my kitchen better.
Comment: It is not clear what you mean by "door swinging (counter-)clockwise" unless you have a hidden biased assumption on which angle you are looking at the door from.
Comment: @RogerAttrill There are no other Hebrew speaking countries :). No, Israeli manufacturers also make them either the same way as in the picture, or reversible, or with double doors.
Comment: @Jonathan I was replying to Roger's "or other Hebrew speaking countries".
Comment: the door of the fridge is probably more heavy than anything your going to put in it, especially if it's bearings are stiff or it's full of bottles
Comment: @ColinSharpe, usually this doesn't bother me, I don't store many bottles on the door side, just some eggs and pills are put on the door side.
Comment: @LiuYan, maybe for you this is fine, but is your case common?
Comment: @sawa, good point, it's from the top view. question edited.
Comment: I'm not sure this is a valid question. What data is there that shows the majority of doors default to only open in one direction? At least in the US, most all appliances come with doors that open in either direction. It doesn't have anything to do with being right or left handed but where the appliance is situated.
Answer: The answer is in your question: "Most people are right-handed, right hand is handy". A right-hander would reach for the door with their right hand, and if you don't want the door to open in your face or have to cross your arms while opening, you'd want the door to swing anti-clockwise.
Grabbing a small item with your left hand wouldn't be all that hard. However, I highly doubt that anyone tries to move/lift a heavy item with one hand. In that case, irrespective of which direction the door swings open, you'd open it and then use both hands to lift the item.
Comment: Ha! You've never seen me moving a 16 quart stockpot into the fridge. I don't... *plan ahead*...
Comment: My habit is like this: unhandy hand do easy job, handy hand do hard/heavy job. Open refrigerator door (and keep the door opening because the door will close automatically) is easy job, move/arrange things (such as move half of a big watermelon, or arrange things if there's no enough space, or arrange a dozen of eggs carefully) into refrigerator is hard/heavy/complex job for me. So, as a right-handed person, I prefer **use left hand to open door (easy job)**, **use right hand to move/arrange things (complex job)**.
Comment: I'd support the use of the right hand to open argument.  You can get more pull if you pull straight back with your right hand.
Comment: @LiuYan刘研 It's easy to do with the unhandy hand when you're _conscious_ of it. But, 99% of the time you won't be moving stuff that requires superhuman strength, and you'll _subconsciously_ reach for the handle with your dominant hand. I hope you realize that it would piss a lot of people off, especially those that don't do complex jobs with their refrigerator most of the the time.
Answer: You'll have to poll some major manufacturers of refrigerators.
I would guess at this point in in time (today's world) it has to do with what people are buying/demanding. Families, Apartment managers, companies, and anyone else with the need for a fridge.
I will also assume that you buy a refrigerator based on the configuration of where you will install it. Some spots require a refrigerator to open from the left-side, other the right, and still other it doesn't matter as there is enough space between it and other counters/appliances. Industrial freezers are the same way, and lets not forget fridges that open from the middle.
For example, I've rented apartments where the door opened with the right-hand and it blocked or hit something. My immediate thought was, why didn't they install a fridge that opened from the other side. I call them up and they say we can replace it, or we don't have any that open from the other side.
Comment: Every fridge I've seen (at least larger than one intended only for chilling your drink cans) can have the door easily moved to the other side. So, really, if it opens on the wrong side, the installer was lazy (or, I suppose, for non-professional installation, unaware of this).
Comment: Yes, most fridges are reversible nowadays. Not so 20 years ago...
Answer: As the above has mentioned, I would have also assumed it's based on where you install it. Also, say if you're kitchen is to the right of your fridge, you'd want the fridge to open clock-wise for quicker access?
Answer: Contrary to some of the claims above, NOT ALL modern fridges have reversible doors and those that do often have very poorly executed designs. Here in the UK I have just bought a Hotpoint Fridge Freezer and with my kitchen layout it needed the doors to open the opposite way. I am a keen DIY'er (i've built my own house), but for a novice this would have been a big or at least an awkward job. Firstly they used Star screw bits (TORX)... but didn't include a free screwdriver (cheapskates). They marked but did not pre-drill the hinge mounts so a 3mm drill bit was required. then there was a requirement to fit spacers once the centre hinge was inverted, and then, both the top and bottom fascia plates had to be modified and a panel in the door swapped round as well as moving the door handles over. the only reference to swapping the door over was an exploded diagram (ikea style) on a loose A4 sheet. no manual, instructions or tool requirements so if you needed to get it up and running on the day it arrived then you better hope the shops are still open if you haven't got the tools !!  Moral of the story GET THE DETAILS AT THE STORE- ASK THEM TO SHOW YOU WHATS INVOLVED. A decent independent dealer will do it for you unless its being drop shipped from a distributor of course.   I understand that manufacturers cannot have both opening options as stock items but good design seems to be lacking even on an expensive model. mine cost £450GBP  ($600 approx) so i'm not talking about a baseline budget model
Comment: Hello and welcome to ux! Please not that stackexchange wants answers to be complete and standalone. Auxillary replies like yours would better fit a comment.