How can prove that $T$ is a distribution?

Question: Let $f_t: \mathbb R^2 \to \mathbb R$ define by $f_t(x,y) = t \sin(t|x^2+y^2-1|)$.
For all $\phi\in D(\mathbb R^2-\{(0,0)\})$, we denote by $T$ the map given by
$$T(\phi)=\lim_{t\to +\infty}\int_{\mathbb R^2} f_t(x,y) \, \phi(x,y)\, \mathrm{d}x\, \mathrm{d}y$$
How can prove that $T$ is a distribution of order $0$ on $\mathbb R^2-\{(0,0)\}$?
Remark: I have prove that $T: D(\mathbb R^2-\{(0,0)\}) \to \mathbb R $  is a linear map. It remains to show $T$ is continuous. In fact, I started by using the polar coordinate system, then we get
$$T(\phi)=\lim_{t\to +\infty}\int_{0}^{2\pi} \int_{0}^{\infty}\,  t \sin(t|r^2-1|) \, \phi(r,\theta)\,r\, \mathrm{d}r\, \mathrm{d}\theta=... ??$$
Thank you in advance
Comment: Consider that for any test function $\phi$ with compact support in $\mathbb{R}^2\setminus \{(0, 0)\}$, we can write the support of $\phi$ as being contained in some annulus centered on the origin. Also, we can bound the integral of a continuous function over an annulus by its $C^0$ norm and the area of the annulus.
Answer:
Lemma. Let $\varphi \in C_c^1(\mathbb{R})$. Then
$$ \lim_{t\to\infty} \int_{\mathbb{R}} \frac{t \sin(t|u|)}{2} \varphi(u) \, du = \varphi(0). $$

Proof of Lemma. We have
\begin{align*}
\int_{\mathbb{R}} \frac{t \sin(t|u|)}{2} \varphi(u) \, du
&= \int_{0}^{\infty} t \sin(tu) \cdot \frac{\varphi(u) + \varphi(-u)}{2} \, du \\
&= \varphi(0) + \int_{0}^{\infty} \cos(tu) \left( \frac{\varphi'(u) - \varphi'(-u)}{2} \right) \, du \\
&\xrightarrow[t\to\infty]{} \varphi(0)
\end{align*}
by the Riemann-Lebesgue lemma. ////
Now we return to the original problem. Let $\phi \in \mathcal{D}(\mathbb{R}^2\setminus\{0\})$ and write
$$ \varphi(r) = \int_{\partial B_1(0)} \phi(r\omega) \, \sigma(\mathrm{d}\omega), $$
where $\sigma$ is the surface measure on $\partial B_1(0)$. Then applying polar coordinates,
\begin{align*}
\int_{\mathbb{R}^2} f_t(x, y) \phi(x, y) \, \mathrm{d}x\mathrm{d}y
&= \int_{0}^{\infty} rt \sin(t|r^2-1|)\varphi(r) \, \mathrm{d}r \\
&= \int_{-1}^{\infty} \frac{t\sin(t|u|)}{2} \varphi\left(\sqrt{u+1}\right)
\end{align*}
where $u = r^2 - 1$. Now taking $t\to\infty$ and applying the lemma together with the observation $\varphi \in C_c^{1}((-1,\infty))$, we have
$$ T\phi = \varphi(1) = \int_{\partial B_1(0)} \phi(\omega) \, \sigma(\mathrm{d}\omega). $$
That is, $T\phi$ is the $2\pi$ times the average value of $\phi$ on the unit circle. This gives
$$|T\phi| \leq 2\pi \|\varphi\|_{\sup}$$
and hence $T$ is a distribution of order $0$.
Comment: and without the absolute value : $t \sin(t (x^2+y^2-1))$ converges to the $0$ distribution on $\mathbb{R}^2 \setminus (0,0)$
Comment: Very nice lemma!
Answer: First, we note that for $\mathrm{supp}(\phi)\subset \Omega = B_{r_2}(0)\setminus B_{r_1}(0)$ for some $0 < r_1 < r_2$, \begin{align*} I_t(\phi) &:= \int_0^{2\pi}\int_{r_1}^{r_2} t\sin(t\lvert r^2-1\rvert)\phi(r, \theta)\,r\,\mathrm{d}r\,\mathrm{d}\theta \\ &= \int_{r_1}^{r_2} t\sin(t\lvert r^2-1\rvert)\left[\int_0^{2\pi} \phi(r, \theta)\,\mathrm{d}\theta\right]r\,\mathrm{d}r \\ &= \Im\left[\int_{r_1}^{r_2} te^{it\lvert r^2-1\rvert}\left[\int_0^{2\pi} \phi(r, \theta)\,\mathrm{d}\theta\right]r\,\mathrm{d}r\right] \end{align*} We let $\Phi(r) := \int_0^{2\pi} \phi(r, \theta)\,\mathrm{d}\theta$. First, we note that for $r_i > 1$, $$\int_1^{r_i} te^{it\lvert r^2-1\rvert}\Phi(r)\,r\,\mathrm{d}r = \int_1^{r_i} te^{it(r^2-1)}\Phi(r)\,r\,\mathrm{d}r = \frac{t}{2}\int_0^{\sqrt{1+r_i}} e^{itu}\Phi\left(\sqrt{1+u}\right)\,\mathrm{d}u$$ for $u = r^2-1$. Recall from the proof of the Riemann-Lebesgue lemma that $$\left\lvert\int_0^{\sqrt{1+r_i}} e^{itu}\Phi\left(\sqrt{1+u}\right)\,\mathrm{d}u\right\rvert\leq \frac{1}{t}\int_0^{\sqrt{1+r_i}} \left\lvert\frac{\Phi'(\sqrt{1+u})}{2\sqrt{1+u}}\right\rvert\,\mathrm{d}u$$ and $\Phi'(r) = \int_0^{2\pi} \partial_r\phi(r, \theta)\,\mathrm{d}\theta$, so \begin{align*} \left\lvert\int_1^{r_i} te^{it\lvert r^2-1\rvert}\Phi(r)\,r\,\mathrm{d}r\right\rvert &\leq \frac{1}{2}\int_0^{\sqrt{1+r_i}} \frac{1}{2\sqrt{1+u}}\left\lvert\int_0^{2\pi} \partial_r\phi(\sqrt{1+u}, \theta)\,\mathrm{d}\theta\right\rvert\,\mathrm{d}u \\ &= \frac{1}{2}\int_1^{r_i} \left\lvert\int_0^{2\pi} \partial_r\phi(r, \theta)\,\mathrm{d}\theta\right\rvert\,\mathrm{d}r \end{align*} We can show a similar bound for the case $r_i\leq 1$, which allows us to write \begin{align*} \lvert I_t(\phi)\rvert &\leq \frac{1}{2}\int_{r_1}^{r_2} \left\lvert\int_0^{2\pi} \partial_r\phi(r, \theta)\,\mathrm{d}\theta\right\rvert\,\mathrm{d}r \\ &\leq \frac{1}{2}\int_{r_1}^{r_2}\int_0^{2\pi} \lvert \partial_r\phi(r, \theta)\rvert\,\mathrm{d}r\,\mathrm{d}\theta \\ &\leq \pi(r_2-r_1)\|\phi\|_{C^1} \end{align*} for all $t$, which implies $\lvert T(\phi)\rvert\leq \pi(r_2-r_1)\|\phi\|_{C^1}$. Therefore, $T$ is a distribution and has order at most 1. I'm not sure how to improve this to order 0.
Comment: Where did you show $\lim_{t \to \infty} I_t(\phi)$ converges ?
Comment: The asker said that they already proved that $T : D(\mathbb{R}^2\setminus \{0, 0\})\to \mathbb{R}$ is a linear map, so I took it as an assumption that the sequence converges. Do you think I should add a proof of convergence?
Comment: When showing $T_l$ converges it is obvious $T$ is a distribution of order at most $2$, so I'm sure the OP didn't show it.


How to iterate over a range of numbers in golang template?

Question: I'd like to do something like this:
  {{range $y := .minYear    .maxYear}}
      <option value="y"> {{$y}}</option>
  {{end}}

But the template is not rendered as expected. How can I fix this?
Comment: Related / possible duplicate: [Golang code to repeat an html code n times](https://stackoverflow.com/questions/46112679/golang-code-to-repeat-an-html-code-n-times/46112802#46112802)
Answer: The template package does not support this directly.  Create a template function that returns a slice of the integer values:
var funcs = template.FuncMap{
    "intRange": func(start, end int) []int {
        n := end - start + 1
        result := make([]int, n)
        for i := 0; i < n; i++ {
            result[i] = start + i
        }
        return result
    },
}

Use it like this:
t := template.Must(template.New("").Funcs(funcs).Parse(`{{range $y := intRange .minYear .maxYear}}
   <option value="y"> {{$y}}</option>{{end}}`))

err := t.Execute(os.Stdout, map[string]int{"minYear": 1961, "maxYear": 1981})
if err != nil {
    // handle error
}

Run it on the Go playground.
Answer: You can use the sprig library in your templates:
https://github.com/Masterminds/sprig


Brightness control not working (lenovo + intel tiger lake + ubuntu 20.04)

Question: I just got a new Lenovo with an Intel Core i3-1115G5 with integrated graphics. After a fresh install of Ubuntu 20.04 the Fn keys that are supposed to control the brightness do not work. The brightness slider in the system menu as well as the one in Settings->Power are missing. I tried installing xbacklight, but the command xbacklight -get doesn't yield any output and the -set [number] option does not produce any change in brightness.
Here's the output of lspci:
$ lspci | grep VGA
00:02.0 VGA compatible controller: Intel Corporation Device 9a78 (rev 01)

I tried modifying the /etc/default/grub file so that
GRB_CMDLINE_LINUX_DEFAULT="quiet splash acpi_osi=Linux acpi_backlight=vendor"

updated the grub and restarted but it didn't have any effect.
I also tried this solution but it didn't work. The command ls /sys/class/backlight/ gives no output. I also tried the find command as in the accepted answer here but it didn't yield anything related to intel:
$sudo find /sys/ -type f -iname '*brightness*'
/sys/devices/platform/i8042/serio0/input/input2/input2::numlock/brightness
/sys/devices/platform/i8042/serio0/input/input2/input2::numlock/max_brightness
/sys/devices/platform/i8042/serio0/input/input2/input2::capslock/brightness
/sys/devices/platform/i8042/serio0/input/input2/input2::capslock/max_brightness
/sys/devices/platform/i8042/serio0/input/input2/input2::scrolllock/brightness
/sys/devices/platform/i8042/serio0/input/input2/input2::scrolllock/max_brightness
/sys/devices/pci0000:00/0000:00:14.3/leds/phy0-led/brightness
/sys/devices/pci0000:00/0000:00:14.3/leds/phy0-led/max_brightness
/sys/module/video/parameters/hw_changes_brightness
/sys/module/video/parameters/brightness_switch_enabled
/sys/module/i915/parameters/invert_brightness

I nevertheless tried creating a file /usr/share/X11/xorg.conf.d/20-intel.conf with contents:
Section "Device"
        Identifier  "card0"
        Driver      "intel"
        Option      "Backlight"  "intel_backlight"
        BusID       "PCI:0:2:0"
EndSection

but it just produced a black screen after logging out. I got the log-in screen again after pressing the power button. After logging in the problem was not resolved.
I don't know what else to try... Any help is highly appreciated!
Answer: I did a fresh install of Ubuntu 20.10 and this solved the problem


Lost game & don't know what I used when I signed up

Question: My kid deleted the game & I can't remember if I used a google account or trainer club to log in.  I've tried both but still can't get the game with progress back.  Is there any way to tell which one was used?
Answer: The only way to tell is to log in with every account you know you could have used. With GMail you could use the google website to check which apps you allowed to access your info. If Pokémon Go is in there you most likely have an account there. (If not you should check it anyway. It's just quicker, if you find a google account with Go having access.)
Comment: It did earlier. I deleted mine, too, and it works fine. The rest of the answer still stands, though.
Comment: I don't think that Go uses Google Play Games (if you're on Android).

My game is working fine, I log in with my main Gmail account but in this list in your link, the game doesn't appear.


PS3 backup with another HDD

Question: My PS3 died with YLOD couple of weeks ago and I got my new PS3 with 160GB hdd today. I also have my old hdd with 500GB including all my game saves. Can I somehow restore my game saves to the new hdd with the older one?
If I use SATA to USB -cable to connect my old hdd to PS3, can I restore my old gamedata that way (in the same way as regular USB-stick)?
Thank you!
Answer:
My PS3 died with YLOD couple of weeks ago and I got my new PS3 with 160GB hdd today. I also have my old hdd with 500GB including all my game saves. Can I somehow restore my game saves to the new hdd with the older one?

Only if you saved them to the cloud. ie. if you have PS+ membership and have been backing up your saves.
Some saved games can be copied to a USB drive (but not all), but it doesn't sound like you've been doing this.

If I use SATA to USB -cable to connect my old hdd to PS3, can I restore my old gamedata that way (in the same way as regular USB-stick)?

No.
The hard disk in the PS3 is encrypted and can only be read in the PS3 that created the data in the first place. Since that PS3 is not working, there is no way to read the data from that hard disk.
Well, there is one way. Get your old PS3 repaired, either by the 'reflowing' or 'reballing' technique. (Don't send it to Sony though - last I checked their policy was to format all HDDs in PS3s received for repair. Find a 3rd party that will do it.) After this your old PS3 will work again, but don't treat this as a long-term fix - it can be expected to last maybe 3 months. Instead use this opportunity to sign up to PS+ and copy all of your saves to the cloud. Then restore your saves to your new PS3 (you might have to wait 24 hours before you can do this step).
The PS+ part is necessary because a number of saved games are copy protected, and the only way they can be transferred between systems is via the PS+ cloud. Even the backup utility feature won't transfer these files.
Answer: If you are lucky you can just attach the SATA to USB cable and it'll show your old PS3 drive as a USB storage device.
Then simply choose what to copy from the old drive, onto the console with the 160Gb.
You may be able to just put the 500Gb drive into the PS3, however I'm unsure if this requires formatting it, so I'd recommend doing the above instead.
Comment: I first tried to put the 500Gb drive into the PS3. But it just said that I have to update the hdd to 4.75 (newest ps3 version) and its content will be cleared.So, I'll try to connect old hdd with SATA to USB cable. (Going to buy that cable tomorrow)
Comment: I was told that it's not possible to just attach hdd with SATA to USB cable and use it like USB storage device.
Comment: According to who?

"I plugged an external HDD/USB flash drive into my PS3, and it isn't detected.

If you want to hook up any kind of external HDD or flash drive via USB to your PS3, it needs to be formatted in FAT32. Most external HDDs that claim support with Mac/OSX will be pre-formatted in FAT32, so you won't need to worry about it."

as per https://whirlpool.net.au/wiki/ps3_hdd
Comment: PlayStation support told that I have to format my hdd to FAT32 (and formatting will erase all the memory, won't it?) and a seller at technology store told me that what I wrote in previous comment (can't use hdd as USB storage without formatting). EDIT: Sorry, I wrote previous comment in hurry and that is why I forgot to add these information)
Answer: This might NOT work,but have you thought of just swapping the HDs? pop open that little door on the bottom of the unit with your thumb nail,Then,unscrew the little screw and while its still upside down, slid the little door to the left. Then,lift up the little hard-wire handle and pull. HD removal complete. NEXT,just replace the new one with the old one,put it back togather, and when you fire it up, save all your game saves to the cloud. I hope this helps you,
Skintech
Comment: You can't swap old hdd (which you have been used in another PS3) to new PS3 without formatting it (and thus clearing all the data).  This is made for preventing piracy..

PS3 backup with another HDD


How to complete the P.T. Demo on PS4?

Question: I have played the P.T. (Playable Teaser AKA Silent Hill) Demo a few times but always get stuck at the very end and seem to be in a constant loop.
I know there is some sort of sequence that needs to be performed to be able to stop the looping corridors and to reveal the end video but no matter how many different sequences I try it never seems to work.
I've tried many of the walkthroughs online but none seem to do the trick.
Has anyone actually completed it? and what sequence did you use?
Comment: @Caleb I'd prefer not to watch anything with Pewdiepie in it.
Comment: Pewdiepie did a video on this a day or two ago.  I would watch the  video to see if it helps.
Answer: Obviously this is later down the road than you may have wanted.  I am sure there are more detailed walkthroughs out there today AND I certainly hope you haven't uninstalled the game.  BUT... There are many ways to complete the game, but most ways are not entirely completing it.  I followed the FAQ below and got every detail of the game and finished with correct ending / teaser.  There are MANY ways to complete this demo  This is by far the most terrifying game I have ever played, and its so beautiful.  I hope this works for you!
[And yes, the game was technically cancelled... sad...]
IGN P.T. Walkthrough
As a backup in case the link stops working in the near future, here are the proper steps (Summed Up) to complete P.T.:
Leave the starting area and make your FIRST pass through the hallway and down the staircase.
Head to the stairway door to see it is closed. Turn around and head back towards the door you came through.  The door on your left will begin to shake (This is the bathroom door). Once at the starting place, turn around and head back to the stairway to find it open.  Head down the stairs to complete your SECOND pass.
Head for the stairway again.  Before you reach the open doorway the door will slam shut. Approach and essentially hit the door until your controller shakes.  You will head a door creak behind you. Approach the bathroom door to see bugs escaping. You will hear a Baby crying in the bathroom. Go to the crack of the bathroom door and peer in using (R3). A "woman-like" creature will show up and slam the door shut.  Head to the stairway to finish the THIRD pass.
Head for the stairway. Once you see the hulking ghoul around the corner continue to approach him until the light flickers, and turns off.  Head to the stairway to finish the FOURTH pass.
Head for the stairway.  This time the bathroom door will be entirely open.  Head inside to find a flashlight on the floor.  Zoom in (R3) to pick it up.  The door will slam shut.  Head to the sink and view "it".  Look above the sink (at the reflection of yourself) to hear the door creak open.  Head into the hallway and proceed to the stairway to end loop FIVE.
Head for the stairway and proceed down the stairwell to complete loop SIX.
Head for the stairway and listen for the radio (you may need to wait a moment to hear the specific dialogue) to say "Look Behind You".  Do it.  BOO!  Loop SEVEN complete.
Note: Before you begin this loop, look around the room you wake up in.  Use your flashlight to find the talking box (at least that's what I believe it is).  This is also a good loop to find picture fragments on. Location Below.
Head for the stairway.  You will see a photo next to the radio in the hallway with a message "Gouge it out!" on it. Zoom (R3) in on the Blue X and hit the (X) button.  This will burn out one eye and the door will open.  Head down the stairs, reading "I can hear them calling to me from" on the way, to complete Loop EIGHT.
Head for the stairway noticing everything is red now.  Step under the bloody fridge and head down the stairway to complete the NINTH Loop.
Head for the Phone in this pass to see the word "HELLO" written on the wall. Head to the foyer where you see "calling to me from" again. The letter "L" should appear. Make three more trips from "HELLO" to the foyer where "L" had appeared to spell out "HELL".  Head down the stairs to complete Loop TEN.
Enter the hallway yet again where the fridge has been replaced with a single swinging red light.  Enter the red hallways and find a picture frame that had fallen off the wall with a hole behind it.  Use Zoom (R3) to peer through the hole.  Hold (R3) while listening to the audio.  Once you are forced out of the peer hole, continue down the hallway and down the stairs to complete Loop ELEVEN.
The rest of the demo is straight forward.  It will take control of your screen, play some subliminal messages and then cut out to the "Silent Hills" teaser.  This may be a bit choppy, I will edit it to clean it up tomorrow.  I really hope this helps someone out because this game is worth every sketchy second of playing.  Again, its a real shame that it was cancelled.
Picture Fragment Locations:

On the floor beneath the clock, among the discarded cans and bottles.
On the vase which hold the potted plant, to the right of the clock.
Beneath the window near the phone, near the teddy bear on the floor.
Lodged in the ceiling beam between the foyer and the bathroom
On the stairway leading down to the Loop door.
In the [adjust brightness] Options menu (press R3 while in the menu to collect this piece)

Final Puzzle Notes [can be completed on the last Loop] (via IGN):

Everything must be attempted after the clock strikes midnight.
Players should have a microphone or headset plugged into their Dualshock 4 controller.
In order for the phone to ring, you must hear a baby laugh 3 times.
Walking exactly ten paces in any direction will trigger a laugh.
After the second laugh, FREEZE. Do not move, do not adjust the camera - after a few seconds your controller will begin to vibrate. Remain motionless until the vibrations cease entirely, and the third laugh will trigger.
The phone will begin to ring after all three laughs.
Comment: @Mumford451 Could you edit your question to include one or more possible methods of completion? AS frank said said this is helpful if the link goes away, but it also makes the information a lot easier to find if it's just in your answer rather than on another page (where the user will need to search through the page for it themselves).
Comment: @Wipqozn - Absolutely!  Sorry, still a bit new to SE.  I will edit it right away, thanks for the heads up :)
Comment: Wow, great improvement! Thanks for adding all this information to your  answer!
Comment: Absolutely @Wipqozn thanks for giving me the heads up about the link :)
Answer: Saying his name works ALWAYS for me, tried 3 times already. First do the 10 steps, the baby will laugh. Then when she starts crying/breathing wait until she shuts up and while the radio static is still playing say in your ps4 mic Jerath. Always works. Then just wait until the controller starts vibrating and dont move, not even a bit for the thirth laugh. The phone will ring and thats it.

How to complete the P.T. Demo on PS4?


check the compatibility of an XML document against a DTD using JDOM?

Question: I am working with Java and I want to check if an XML file is valid against a DTD.
Assuming that we do have a DTD file, I want to check if certain XML file is valid against the same definitions proposed in the DTD file.
Is there any way to do it using JDOM?
Answer: Yes, you can, in JDOM. It's easiest in JDOM 2.x (as opposed to 1.x).
See the SAXBuilder constructor that takes an XMLReaderJDOMFactory. An example usage is:
<code>    SAXBuilder sb = new SAXBuilder(XMLReaders.DTDVALIDATING);
    Document doc = sb.build("http://www.w3schools.com/dtd/note_ex_dtd.xml");
    XMLOutputter xout = new XMLOutputter(Format.getPrettyFormat());
    xout.output(doc, System.out);
</code>
Note that the above code validated the XML against the DTD specified in the DocType Declaration ("note.dtd") which is at a location relative to the note-ex_dtd.xml document.
Comment: can you give me a more clear code, staring with creating a DTD file, then the XMLfile, and finally check if the XML file is valide according to the DTD declared
Comment: @steevn - ypu can run that code. the xml and dtd files exist at the url used in the example I show. See http://www.w3schools.com/dtd/default.asp


What kind of connection is used to attach the legs to this table?

Question: I (a beginner) would like to build a table of this form.

Does anyone know what kind of corners are used to connect the legs, or any other construction tips.
Comment: Visit Ikea to discover a wide variety of similar type "joinery".
Answer: It could possibly be done using Mortise and Tenon joints, however, it looks like this table simply uses  Hanger Bolts.

If you look at a picture from the bottom of the table,

you'll notice there are holes bored in the underside of the table top.  This is likely where the nut would be attached to the bolt, which is in turn screwed into the leg.
Comment: And I wouldn't put too much faith in a table built using this technique, personally.  The entire load of the table is relying on the shear strength of four little bolts...
Comment: Getting a hanger bolt design like that to work properly is NOT a good task for a first timer. Those angled holes in the tabletop are going to be a major pain to do right the first time, four times in a row. Once those are in correctly, the legs are not going to just automatically line up for tightening at exactly the right height and angle.  Whoever built the example table likely had a fancy jig and drill set made expressly for the purpose.
Comment: Look at the pictures closely - the table top is notched with a 1/4 round cutout to fit the legs, and the legs are topped level with the top of the table.  It's *possible* that there is a mortice joint hidden inside that cutout that's simply secured by the hangar bolt but I wouldn't bet on it without actual disassembly of the table.
Comment: @TheEvilGreebo: Presumably the table top is resting on top of all four legs.
Comment: Actually, in the image shown, the table top is simply bolted to the side of the table leg. While it's possible to design a table with bolt-on legs where the legs themselves actually pick up the weight (my kitchen table has legs that use hangar bolts to attach to a frame under the tabletop), it's not mandatory and I've seen many a coffee table with exposed leg tops.
Comment: @TheEvilGreebo: A proper bolted joint never relies on the shear strength of the bolt. Instead, the bolt is only in tension and it is the friction between the clamped surfaces that prevents the movement of the joint. In an improper bolted joint, you might rely on the shear strength of a 1/4" fastener, which still exceeds 300 pounds.
Comment: I agree completely.  That should give you an indication of what I think about that particular join. ;)


FM Actuary question, comparing interest rate and Discount rate

Question: On January 1, 2011, Tina invested P into a fund which accumulates at an interest rate of 3% compounded every 2 months. On January 1, 2012, Sam invested 50 in a fund with a discount rate of 6% compounded semiannually. On January 1,2011, the sum of the present value of the two funds is 100. Calculate the total combined amount that will be in the two funds on January 1, 2014.
A)106
B)108
C)110
D)112
E)114
So besides the actual arithmetic, the format of this question itself is not very straight forward for me. I'm not understanding how Sam can have money in his account in 2011 at all if he didn't deposit anything until 2012. Any ideas?
Comment: After researching "Discount Rate", I'm pretty sure what they mean by present value in 2011 is the amount of money that Sam would have had to invested in Jan 2011 to have the value in Jan 2012 be the 50 he actually did invest then. So pretend Sam invested $Q$ on Jan 2011 at 6% compounded twice a year. Figure out how much he would have in Jan 2012, set that equal to 50, and solve for Q. You also know that Q+P =100, so you can find P. Finally figure out what both accounts are worth in Jan 2014.
Answer: As noted in the comment, when computing the present value of a cash flow, you are not computing an actual balance in the sense of a realized amount of money.  Instead, you are computing the equivalent time value of money at a specified point in time.
To this end, we note that if $P$ is the present value of Tina's fund on 01 Jan 2011, and $Q$ is the present value of Sam's fund on that same date, then $P+Q = 100$.  Since the value of Sam's fund is $50$ on 01 Jan 2012, where the nominal semiannual discount rate is $d^{(2)} = 0.06$, then the effective annual rate of discount is $$d = 1- (1 - d^{(2)}/2)^2 = 0.0591.$$  This means that $$50(1-d) = Q,$$ or $Q = 47.045$.  Equivalently, we can observe that the effective annual interest rate is $$i = \frac{d}{1-d} = 0.0628122,$$ thus $Q(1+i) = 50$ and the answer is the same.  Consequently, $P = 100-Q = 52.955$, and the accumulated value on 01 Jan 2014 of both funds is $$P\left(1 + \tfrac{i^{(6)}}{6}\right)^{18} + Q(1+i)^3 = (52.955)(1.005)^{18} + (47.045)(1.0628122)^3 \\= 57.929 + 56.4785 = 114.4.$$  Note we could have obtained the accumulated value of Sam's fund by taking the value at initial deposit on 01 Jan 2012 and discounting it by two years; i.e., its accumulated value is also $50/(1-d)^2 = 50/(1-0.0591)^2 = 56.4785$.
Comment: Ok, I gave an upvote, but how do you know that you need to find the value of Sam's fund before 2012, as it states that he starts investing starting on January 1, 2012.


Unable to register the DLL/OCX: RegSvr32 failed with exit code 0xC0000005 with Inno Setup 5.2.3

Question: I am trying to register a COM DLL using Inno Setup in a setup package I created.  During test installations on Vista, I get this error:

Unable to register the DLL/OCX: RegSvr32 failed with exit code 0xC0000005

I click "Ignore" and my application appears to install, but I have to then open a command prompt (as an administrator) and then regsvr32 to install the COM DLL.  Is there any way to do this automatically in Inno Setup?
Answer: Don't use self-registration (i.e. regsvr32), Microsoft provides more information on the reasons why in the Windows Installer documentation.
Most commonly, certain dependencies that your application is looking for are not yet present (i.e. Microsoft DLLs deployed with your app) when the self-registration process happens.
Can InnoSetup write registry entries? That's all that regsvr32 is accomplishing... you can use the WiX tool heat to extract the relevant registry information that regsvr32 would put in place and then hand-port that back to InnoSetup code.
Comment: Can't InnoSetup write registry entries? That's all that `regsvr32` is accomplishing... you can use the WiX tool `heat` to extract the relevant registry information that `regsvr32` would put in place and then hand-port that back to InnoSetup code.
Comment: Are you sure about this? Inno Setup can't really use anything but `regsvr32` to install a DLL or OCX, any Windows Installer features don't really help here IMO.
Comment: That's interesting information; put that into your answer and I'll vote it up. Inno Setup surely can write to the registry. But I don't think that it will affect the problem the OP has, which looks more like a permission issue, in which case writing to the registry would probably fail as well.
Answer: 0xC0000005 = EXCEPTION_ACCESS_VIOLATION
The DLL is doing something that is causing regsvr32 to crash.


How/where to preload has_many relationship data in Phoenix 1.3

Question: I'm learning Elixir/Phoenix on a sample project and started with Phoenix 1.2.
Now I recreated the project with Phoenix 1.3 to see/learn differences and adapt my old code.
In there I have a has_many relationship between a model Position and Skill. Whereas in the 1.2 code in position_controller.ex I used
case Repo.insert(changeset) do
  {:ok, position} ->
    position = position |> Repo.preload(:skills)
    ...

to have skills preloaded for rendering I'm unsure where to put this in my 1.3 code.
Controller seems to be the wrong place now (Repo isn't even known) so I placed it into my context file inside create_position like this:
def create_position(attrs \\ %{}) do
  with {:ok, %Position{} = position} <-
    %Position{}
    |> Position.changeset(attrs)
    |> Repo.insert() do

    position = Repo.preload(position, :skills)
    {:ok, position}
  end
end

Which feels strange since it now does more than just inserting.
So what is the correct and best way to perform this task?
Answer: You will want to separate things out depending on what your contexts / application looks like.
def insert_position(attrs) do
  attrs
  |> changeset()
  |> MyApp.Repo.insert()
end

If skills and positions are in the same context, you can do something along the lines of
def load_skills(position) do
  MyApp.Repo.preload(position, :skills)
end

If it is in a separate context, you can do the following
def get_skills_for_position(position) do
  # I'm not sure which way you have the relationship
  MyApp.Repo.all(from skill in MyApp.Skill,
    join: position in MyApp.Position,
    on: skill.id == position.skill_id)
end

Then, in your controller, it is up to you to put these things together.
def create(conn, %{"position" => position_attrs}) do
  case create_position(position_attrs) do
    {:ok, position} ->
      # or load_skills_for_position, depending if they are in the same contexts.
      position = load_skills(position)
      ...
    {:error, changeset} ->
      ...
  end
end


No sound after installing "gnome-media"

Question: How do I revert whatever gnome media has done? I ran sudo apt-get purge gnome-media to uninstall the package but it doesn't seem to work. ...seems like it tampered with the defaults or something. Any help appreciated. I'm using an LXDE in 14.04
Answer: Okay that worked. Reinstalling Pulseaudio (which resets things to defaults).
To cut to the chase just type in these commands in a terminal in order.
sudo apt-get remove --purge alsa-base pulseaudio indicator-sound
sudo apt-get install alsa-base pulseaudio indicator-sound
sudo alsa force-reload
rm -rf ~/.config/pulse
sudo reboot

(restarts computer)
sudo apt-get install pavucontrol
pavucontrol

No sound after installing "gnome-media"


Backbone change model of View

Question: I am fairly new to Backbone and have the following question:
I have a collection of models.
I have a collection view displaying tabs (with a view for each model in the collection).
I have a view for a model (for the content).
I have a router with routes.
What I am trying to achieve is a functionality like http://jqueryui.com/demos/tabs/
I click on a tab (model of collection) and then want to pass the model to the content view maybe change it and reflect the changes in the collection.
I came up with four solutions:
In the router:
'switchCommunity': function(id) {
        // (a) set new model attributes
        this.view.community.model.set(communities.get(id));

        // (b) replace model
        this.view.community.model = communities.get(id);

        // (c) a custom function of the view changes its model
        this.view.community.changeModel(communities.get(id));

        // (d) a new view
        this.view.community = new View({
            model: communities.get(id)
        })
}

The problem here is

(a) does not reflect changes to the model in the
collection
(b) does not trigger (change) events, because the bind in the
initialize function of the view never triggers, because it is
a completly new model
(c) seems like a hack to me
(d) everytime i click on a tab a new view is created (is this a
performance issue?)

What is the best pratice here?
Comment: I would try (d) - this doesn't become a performance issue if you remove the old view first.
Comment: This should be sufficient, as long as the old dom elements aren't hanging around and have event listeners bound to them, they should be garbage collected. I'd verify with firebug, but I think that's correct.
Comment: in (d) I overwrite my this.view.community is this sufficient or do I have to remove it manually?
Comment: I always add a close method to my views which removes it from the dom after unbinding all bacbone and dom events.
Comment: Thank you for this very useful question! Option (d) is also not a good option because if you have event listeners on your (sub)view, they will pile up when new (sub)views are created
Answer: One of your solution is close to be okay :D
Here is what you want:
this.view.community.model.set(communities.get(id).toJSON());

And this will trigger model.on("change") as well.
Comment: `communities.get(id).attributes` also works and looks cleaner to me.
Answer: Why do you think (c) is a hack? It seems like a good place to encapsulate the unbinding of the old model, and connecting up the new one.
Answer: The Backbone.Marionette plugin provides a streamlined solution for your problem.
It provides functionality for Application Initialization, View Management, and Event Aggregation.
In essence, it takes the pain out of hiding and showing multiple views.
You can read this blog post to learn more about it.
Comment: Absolutely, but keep in mind the plugin is fairly new and might change a few times in the not so distant future
Answer: The short answer is you should use d. Yes is isn't performant but unless you notice slowdown in the user interface you shouldn't worry too much. You should code something that 1. always works 2. doesn't take long to code so you can move on to coding other more important features.
If/when you need more performance then you can take the extra time to do c. To be the most performant you shouldn't destroy and re-render templates. You should use jquery to manually find the elements on the DOM and replace them with the new model. When you call:
view.$el = _.template(string, model);

It's very little code but lots of work for the browser. Replacing the DOM with a new model is much more performant.
If you need to be more performant you can use object pooling. I've been working on a PerfView for backbone that implements a lot of optimizations. https://github.com/puppybits/BackboneJS-PerfView There's comments in the code with a lot of best practices to maintain the best browser performance.

Backbone change model of View


action does not call reducer

Question: I am using react-redux, the problem is that one of my actions does not dispatch to reducer
here is my code:
Actions.js:
export const getRooms = () => {
  console.log('reach action')
  const config = {
    headers: {
      Authorization: localStorage.getItem('lets_chat_token')
    }
  }
  return dispatch => {
    console.log('in dispatch')
    return axios
      .get(`/api/rooms`, config)
      .then(data =>
        dispatch({
          type: 'GET_ROOMS',
          payload: data.data.data
        })
      )
      .catch(err =>
        dispatch({
          type: 'ERROR',
          payload: err
        })
      )
  }
}

I am calling this action in a react component:
import React, { Component } from 'react'
import { connect } from 'react-redux'
import { getRooms } from '../../Redux/Actions'

import './Connections-list.css'

class ConnectionsList extends Component {
  handleRooms = () => {
    getRooms()
  }

  render() {
    return (

aasa

    )
  }
}

export default connect(
  null,
  { getRooms }
)(ConnectionsList)

The problem is that the first log appears in the getRooms() function:
console.log('reach action')

But nothing happens after that.
Note: I am using redux-thunk. And I have other actions that works perfectly.
Comment: You need to call binded version of `getRooms` you get from the props `this.props.getRooms()`
Comment: Can you see the HTTP request being made in the console?
Comment: have you tried [bindActionCreators](https://redux.js.org/api/bindactioncreators) ?
Comment: @Squiggs. the http request does not reach the server. it does not been made
Answer: You need to bind you're redux action and then get it in props. Below is modified code.
import React, { Component } from 'react'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux' // bind redux action with dispatch
import { getRooms } from '../../Redux/Actions'

import './Connections-list.css'

class ConnectionsList extends Component {
  handleRooms = () => {
    const { getRooms } = this.props //get the redux action from props
    getRooms()
  }

  render() {
    return (

aasa

    )
  }
}

const mapDispatchToProps = dispatch => {
  return bindActionCreators({getRooms}, dispatch)
}

export default connect(
  null,
  mapDispatchToProps
)(ConnectionsList)

Comment: this works too. but way I should use bindActionCreators here. I mean what is the cases that I should use it
Comment: @M.Amer you rarely need to call `bindActionCreators` manually. `connect` does it for you if you say pass an object as the second argument. Just get the function you call from the component props.
Comment: The only use case for bindActionCreators is when you want to pass some action creators down to a component that isn't aware of Redux, and you don't want to pass dispatch or the Redux store to it.` and for further [reference](https://redux.js.org/api/bindactioncreators)

action does not call reducer


Thunderbird does not wrap text in 14.04

Question: In 14.04, I notice that while composing Thunderbird has stopped wrapping text, and it is annoying to have to use to 'enter' to see the whole mail on screen without having to scroll horizontally!!
I don't know where to set wrap text after xx (72??) characters in Thunderbird
Answer: There is a place it can be set although I don't know why it would have been changed on you.
From the Thunderbird Menu, choose Edit->Preferences->Advanced->General->Config Editor
In the Config Editor, enter 'wrap' as a search term
I've enclosed a screenshot of my settings for this, which work and have not been changed that I know of.
Comment: Mine shows 72 here as well. I now discover that the first line of the mail being composed wraps after 72 ch. The second line onwards goes on and on...I have not counted to how many characters...
Comment: After experimenting with the ADDON suggested above by @Tim, the firstline wrap has gone as well!
Comment: I edited this to 78 just to see if it works. No!
Comment: From editing Firefox before, if the settings in thunderbird are not default they should be bold - could you scan through the config to see if there is something changed from default?
Comment: @ Charles Green when I changed it to 78, it was bold. Said User Set or something. Since it not solve the problem, I changed it back to 72. Now it is 'default' 'integer' and no longer bold.
Answer: I don't think toggle wrap is an option in Thunderbird. Thee is however an extension, called Toggle Word Wrap:

Checking "Enable Word Wrap" will enable word wrapping again and set it to the standard width (which is modifiable through the "mailnews.wraplength" preference in the Config Editor, the default is 72 characters).

You can also disable it whenever you want, however I believe that is only temporary.
You can get it from the Addons site.
Comment: @ Tim...I installed this Addon, and it shows greyed under 'options' so, I am unable to set it. See my comment below the other answer, now even the first line fails to wrap :-(.
Comment: I have now removed the extension.. now the first line wrapping that worked before is gone for good. Now auto text wrapping is not possible.
Comment: Don't know, sorry it messed it up...
Answer: 1) Go to your Thunderbird profile folder
2) Make a directory named chrome
3) Inside the chrome folder make a file named userContent.css as a plain text file (be sure to show file extensions otherwise you may end up with a userContent.css.txt)
4) Edit the file with any text editor and put the following line in it:
* { word-wrap: break-word; }

5) Restart Thunderbird
Comment: FYI - Unlike Windows, Ubuntu (and all other *nix based OS's) don't use file extensions automatically and don't have an option to show or hide them. Correct me if I'm wrong.
Comment: Your wrong on the hiding part.  I have Ubuntu 16.10 and on it and previous versions, Ctrl-H turns hiding on/off on Nautilus.
Comment: This answer has been copied from here: https://superuser.com/a/709723/598527
Answer: As Charles Green suggests, go to Edit->Preferences->Advanced->General->Config Editor and enter 'wrap' as a search term. There change plain_text.wrap_long_lines to true. This worked for me.

Thunderbird does not wrap text in 14.04


How can I get my coordinates in Minecraft pocket edition?

Question: I want to use the /fill command, but I need my coordinates in order to use it. How can I get my coordinates in Minecraft Pocket Edition?
Comment: I think this is a dupe, but I can't find the original
Comment: @Ben [You're talking about this answer](https://gaming.stackexchange.com/a/289472/75275). The only problem is that the question _isn't_ a duplicate. The question was asking for [tag:minecraft], not [tag:minecraft-pocket-edition].
Answer: Without any behaviour packs:
As of 0.16.0, you can find your coordinates by enabling cheats and teleporting yourself nowhere.
/tp @p ~ ~ ~

In the console, it will display something like:
aytimothy teleported from 0, 0, 0 to 0, 0, 0

To sum it up, it'll display both your destination and your original co-ordinates. Since you're going nowhere, those two should be the same.
With behaviour packs:
This should do the trick.
You can do this by creating a player_position_text display in an .mcmod that changes the UI.


Data validation with multiple parameters

Question: I want to make sure the user doesn't input anything except a positive integer. Minus numbers and letters are not allowed. I'm having trouble with setting those two parameters for my data validation. Code is below:
product = 0

while product < 100:
    number = input("Enter a positive integer: ")
    try:[
        number = int(number),
        number = number.isnumeric
        ]

    except ValueError:
        print("Invalid input. Please enter a positive integer.")
        continue

    product = number * 10
    print("The number entered is", number, " and the product is", product)

Answer: Here, the below program should work:
product = 0

while product < 100:
    number = input("Enter a positive integer: ")
    try:
        number = int(number)
        if number <= 0:
            print("Invalid input. Please enter a positive integer.")
            continue
    except ValueError:
        print("Invalid input. Please enter a positive integer.")
        continue

    product = number * 10
    print("The number entered is", number, "and the product is", product)

Answer: You can use the isdigit function:

Return True if the string is a digit string, False otherwise.
A string is a digit string if all characters in the string are digits and there is at least one character in the string.

For example:
>>> "-1".isdigit()
False
>>> "1.1".isdigit()
False
>>> "123".isdigit()
True
>>> "abc".isdigit()
False

In your case, you can do the following:
product = 0

while product < 100:
    num_in = input("Enter a positive integer: ")
    if num_in.isdigit():
        number = int(number)
    else:
        print("Invalid input. Please enter a positive integer.")
        continue

    product = number * 10
    print("The number entered is", number, " and the product is", product)

Note: You can also use try-except but it will take more conditions as int can also be a negative number.


Only run a highlighting rule as a nextgroup in syntax file?

Question: I have these rules in a custom syntax file.
syn match id '\w\+'
syn keyword _type void int bool string list nextgroup=id

I only want id to be matched after a _type.
Comment: Can you give examples of what should be highlighted and would shouldn't be?
Answer: You're already close.

To avoid that the id group matches anywhere else, just add contained.
For nextgroup=..., the match must begin exactly after the end of the current group. Therefore, you need to include the leading whitespace in the id group match: \s\+, or add skipwhite.
The naming convention for syntax groups is to prepend them with your syntax name; I've used my... here.

:syn match myId '\w\+' contained
:syn keyword myType void int bool string list nextgroup=myId skipwhite

Comment: Adding `skipwhite` after `nextgroup=myId` is probably better. Thanks!
Comment: @KennethCheng Great idea! I've incorporated that in my answer.
Comment: This is not working if you have a rule that contains ALL (like parenthesis matching). `contained` causes the match to only trigger when contained inside SOMETHING - still not ONLY when following `myType`


Making a wrapper div's width relative to the contents

Question: I need your help.
How can the "wrap"'s div width be re-sized such that its width is relative to the other contents that are in it. Right now it appears to be automatically 100%?
Here's a pic of the problem:

<!DOCTYPE html>

<input id="txt1" type="text"/>

Comment: Have you tried #wrap{display:inline;}?
Comment: Firstly; make a JSFiddle, it makes it much easier for folks to help you. Secondly; that's what `` elements *do*, they're block level. Consider using a `` instead.
Comment: If I use a , its still the same result.
Answer: I would use display: inline-block;.
#wrap {
    display: inline-block;
}

Answer: It should go like this i guess:

Answer: By default, elements with display: block will occupy the entire width available. Try using this:
display: inline-block;

However, this will cause that your div will no longer cause a line break, so you may have to insert a
 element
Answer: A
 element is by default block level and will use 100% of the available width unless you style it not to. You'll have to set its display CSS property to inline-block in order for it to expand according to the elements inside it.


error code for travelling salesperson i.e finding cycle with minimum cost of a graph

Question:     #include <stdio.h>
    int a[10][10],visited[10],n,cost=0;
    void mincost(int city)
    {
        int i,ncity;   //ncity==nearest city
        visited[city]=1;
        printf("%d->",city+1);
        ncity=least(city);
        if(ncity==999)  //no nearest city,hence back to 1
        {
            ncity=0;
            printf("%d",ncity+1);
            cost+=a[city][ncity];
            return;
        }
        mincost(ncity);   //recursive
    }
    int least(int c)
    {
        int i,nc=999;
        int min=999,kmin;
        for(i=0;i<n;i++)
        {
            if((a[c][i]!=0) && visited[i]==0)
            {
                if(a[c][i]<min)
                {
                    min=a[i][0]+a[c][i];
                    kmin=a[c][i];
                    nc=i;
                }
            }
        }
        if(min!=999)
            cost+=kmin;
        return nc;
    }
    int main()
    {
        int n,i,j;
        printf("Enter the number of cities:");
        scanf("%d",&n);
        printf("\nEnter the cost matrix:");
        for(i=0;i<n;i++)
        {
            for(j=0;j<n;j++)
            {
                scanf("%d",&a[i][j]);
            }
        }
        for(i=0;i<n;i++)
            visited[i]=0;
        printf("\nThe minimum path is:\n");
        mincost(0);
        printf("\nMinimum cost:%d",cost);
        getch();
        return 0;
    }

The program finds the cycle with least cost for a given graph.
The function least finds the next nearest city denoted by nc & each city is considered one by one by recursively calling mincost function.
The output is always the the first city & it's cost,that's it.
Please help!
Comment: For some input what is the expected and actual output? Have you tried debugging it? Do anything change if you declare a prototype of the `least` function before you use it?
Comment: As a side note: the program does not always find the cycle with the _least_ cost. It is a greedy heuristic that may work well in some cases but fails utterly in others (it also depends on the starting point of the search).
Answer: You have a global variable n which gets initialized to zero by the compiler. Then in the main function you have a local variable n that shadows the global variable, so when you read input from the user and initialize n to that, it's only the local variable which is initialized ad not the global which will still be zero.
General tip: Avoid global variables. If you need other functions to know about a value or variable, then pass it as an argument.


Labels in Java for exception handling

Question: I'm doing the Java Associate level certification and while we are expressly told we won't be tested on labels, we have been shown them. Looking on here though the advice seems to be never use labels?
I'd like to use them in a catch block/user input console as a means of validating input.
do {//Keep calculator going as long as user wants
            numInputCheck:
            do {
                try {//Force user to input a whole number
                    System.out.print("\nPlease enter the Mark you want to Calculate\n(Enter marks between " + GradeCalculator.getMIN_MARK() + " and " + GradeCalculator.getMAX_MARK() + " only): ");
                    mark = Integer.parseInt(scn.nextLine());
                }catch(NumberFormatException nfe) {
                    System.out.println("\nInvalid entry - Please ensure entry is a number only.");
                    continue numInputCheck;
                }
                gradeCalc.isValidMark(mark);//Ensure input is within valid range
            }while(!gradeCalc.getIsValidMark());
            *etc*......

Is this bad coding?
EDIT: The code above wasn't doing what I thought it was/wanted it to do - it wasn't actually jumping back to the label at all.
I ended up changing the code to
do {//Keep calculator going as long as user wants
            do {//Force user to enter number within valid range
                do {//Force user to enter a whole number
                    try {
                        System.out.print("\nPlease enter the Mark you want to Calculate\n(Enter marks between " + GradeCalculator.getMIN_MARK() + " and " + GradeCalculator.getMAX_MARK() + " only): ");
                        mark = Integer.parseInt(scn.nextLine());
                        isValidInput = true;
                    }catch(NumberFormatException nfe) {
                        System.out.println("\nInvalid entry - Please ensure entry is a number only.");
                        isValidInput = false;
                    }
                }while(!isValidInput);
            }while(!gradeCalc.isValidMark(mark));

which I'm fairly sure is working correctly.
Anyway, I think I answered my own question - labels are discouraged because people like me try to use them.
Comment: I don't think the label serves much purpose in this exact example, because `continue` should apply to the inner `do` loop by default.  I might not go so far as to say this is _bad_ coding, but I think most Java gurus would say labels should not be used unless they are needed.
Comment: @TimBiegeleisen This comment is a pretty good answer :-)
Comment: @TimBiegeleisen thanks. I didn't think of that.
Comment: @tim no, continue will jump to the `while` evaluation (possibly causing an NPE)
Comment: @Strelok So are you saying that `continue` would behave differently from `continue numInputCheck` ?  I was only commenting on the use of labels, not the rest of the code.
Comment: @TimBiegeleisen Thanks Tim and others. Stupid question so, time to read the chapter on nesting loops...
Comment: The point by @Strelok seems valid.  You might want to make sure that the loop evaluation doesn't go NPE on you.
Answer: No this is not actual example because continue can do all the job by itself without the help of the label .
 A good example is when you have 2 nested loops and you want to break the outer loop from a condition in the inner loop
    outerloop:while(condition1) {

                 while(condition2) {
                       if(condition3)
                           break outerloop;
                 }
          {

Answer: Continue statement skips all sentences above, you have to use break sentence for stopping the loop. Labels are useful for more than one loop, for example:
label1:
for (int i = 0 ; i<10; i++){
    for (int j = 0 ; j<10; j++){
        if (i+j = 3)
            break label1;
    }
}

Labels in Java for exception handling


Can't select Jquery elements after reloading a div with AJAX

Question: I have a message inbox which I refresh with AJAX after removing a message, resulting in a new message inbox without the message.

My HTML code looks like that, when the document is ready, I call a show/hide message function:
        $(document).ready(function()
        {
            message_show();
        });

        function message_show()
        {
            $("div.message").hide();
            $(document).on("click", "div.title", function()
            {
                $("#" + this.id + ".message").fadeToggle("fast");
                $("#fold" + this.id).fadeToggle("fast");
            });
        }

This works fine, when the page loads, the messages are hidden, and the moment you click on a title the messages show up, and the fold icon changes.
However, the moment I refresh the content with AJAX by using a .get() to remove the message:
function delete_message(message_id)
{
    $.get("message_inbox.php",{delete_id:message_id}, function(data)
    {
        $("div#messages_inbox").load("message_inbox.php div#messages_inbox > *");
        // $("div.message").hide();
        message_show();
    });
}

After using the .load the message divs aren't hidden anymore.
I managed to select the div.title by using the $(document).on to toggle them, which works, but hiding the messages, when the content has been loaded doesn't seem to work.
Neither was I able to hide the div inside the $.get (the part I left commented)
Comment: Please look into re binding events following an ajax call. What is happening is every time you use AJAX on DOM elements the events are wiped out.
Answer: $("div#messages_inbox").load(...) - You're overwriting everything that is inside of #messages_inbox when .load completes.
If what is inside of div#messages_inbox > * in the returned content from message_inbox.php does not contain div.message or div.title, it will look like message_show() does nothing.
See documentation for .load
You'll also want to make your call to message_show() as .load's callback function to ensure the content has been loaded prior to using it:
function delete_message(message_id)
{
    $.get("message_inbox.php",{delete_id:message_id}, function(data)
    {
        $("div#messages_inbox").load("message_inbox.php div#messages_inbox > *", message_show);
    });
}


ViewPager unable to swipe after changing visibility

Question: I have an Activity which has a ViewPager. In this ViewPager are 4 Fragments. One of these Fragments (let's call it MyListFragment) has a layout file with a ListView and a MapView (Google maps V2), in a RelativeLayout. Only one of these 2 Views is visible at a time. Initially, the ListView is visible and the MapView is gone. I have a Button, and when I click it, I switch the visibilities: ListView to gone and MapView to visible. When I click it again, MapView is set to gone and ListView to visible. You get the picture.
Now the problem is the following: after setting the MapView to gone and the ListView back to visible, the ViewPager won't swipe anymore. Instead, all touch events go to the ListView (which is a normal vertical ListView). I broke this up in a few steps, and checked when I could or could not swipe the ViewPager.

ListView is visible, MapView is gone: everything behaves normally.
Setting ListView to gone: everything behaves normally.
Setting ListView back to visible: everything behaves normally.
Setting ListView to gone, MapView to visible, MapView back to gone: everything behaves normally.
Setting ListView to visible: !!! the ViewPager won't swipe anymore on this Fragment !!!
Setting the ListView to gone: everything behaves normally.

It's weird because step 5 seems to be the same state as step 1. Here is my layout file:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<ListView
    android:id="@+id/listView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/fragment_padding"
    android:paddingRight="@dimen/fragment_padding"
    android:paddingBottom="@dimen/list_padding_bottom"
    android:clipToPadding="false"
    android:scrollbarStyle="outsideOverlay"/>

<com.google.android.gms.maps.MapView
    android:id="@+id/mapView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:visibility="gone"/>

<Button
    android:id="@+id/button_switch"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:layout_marginBottom="@dimen/fragment_padding"
    android:layout_marginLeft="@dimen/fragment_padding"
    android:layout_marginRight="@dimen/fragment_padding"
    android:text="Show on map"/>

Here is some of the onCreateView code:
this.listView = (ListView) view.findViewById(R.id.listView);
this.mapView = (MapView) view.findViewById(R.id.mapView);
this.mapView.onCreate(savedInstanceState);
this.mapView.getMapAsync(this);

Here is what happens in the onClick for the button:
            if(this.listView.getVisibility() == View.VISIBLE)
            {
                this.listView.setVisibility(View.GONE);
                this.mapView.setVisibility(View.VISIBLE);
                this.buttonSwitch.setText("Show in list");
            }
            else
            {
                this.listView.setVisibility(View.VISIBLE);
                this.mapView.setVisibility(View.GONE);
                this.buttonSwitch.setText("Show on map");
            }

If I need to provide another piece of the code, let me know. Any help would be appreciated because I can't seem to find the cause for this bug.
Comment: Same problem here! Did you got any solution/workaround?
Comment: @MuhammadBabar I found a workaround, it's not ideal though. When switching from the map to the list I disable all gestures on the map. When I switch back, I enable them again.
Comment: Thanks mate while i also managed to workaround the issue but your's seems like an easy one!
Comment: Thanks, Its worked for me also.
Answer: just enable and disable like:-
java:-
 googleMap.getUiSettings().setAllGesturesEnabled(false); // true / false with Visible / Gone

Kotlin:-
 googleMap?.uiSettings?.setAllGesturesEnabled(false)


what kind of electrical boxes and fashioning methods are best for metal framing?

Question: What kind of electrical boxes and fastening methods are best for metal studs?  Are there special boxes that are best to use?
Answer: As far as I recall, the main differences are using appropriate metal screws to attach (standard) boxes, and using bushings (should be either provided with framing or easily available from the framing supplier or an electrical supplier) to protect wires passing through the framing.
This guide from "steelframing.org" might be a helpful read.


Is it acceptable to splice a circuit in two opposite directions for outdoor recepts/lighting?

Question: Per the 2011 NEC, is it acceptable to...

Splice a circuit (using a junction box indoors) as long as I leave it exposed, use the correct wire connectors, and have it covered?
Use this run one side of the spliced wire to a pair of GFCI outlets at the base of my house(outside), and the other to a switch (inside) and then to a flood light (outside)?

So can I splice and can I have outdoor receptacles on same circuit as outdoor light?
Also, If anyone knows what section either of these are covered in the 2011 NEC and could tell me that would be great too!
Comment: There is no problem with what you want to do. Though if I posted all the relevant code sections, I don't think it would be considered "fair use" anymore. See NEC chapters 1-4.
Comment: What wouldn't be considered "fair use" anymore? Thanks for your help!
Comment: If I posted the entirety of chapters 1-4 of NEC, I don't think that would fall under [fair use](http://en.wikipedia.org/wiki/Fair_use).
Comment: Ah I see. Ok, well thanks again for all of your help!
Answer: We can't post what is not there. There is nothing prohibiting this and as Tester states, quite a bit of chapters 1 thru 3 apply in general, with spots in 4.
The NEC is NOT written in a way that you can simply look up a specific job you are doing. It can be very general and very broad, yet also specific on certain things.
I realize this question is 3 months old and the project likely done by now, but what is being proposed in the original post is fine.
Comment: Yes this OK and there is nothing in the code that will say that in one spot.  It's not only OK but very common.
Answer: The wiring code may also be locally governed.  However, I have lived in houses that have outside outlets on the same circuit with inside lights and outlets. This has always made me mildly uncomfortable, because of lightning strike issues, so I have modified that sort of wiring where I can do it without major rewiring; especially when expensive electronics are involved.
Comment: The fact that a circuit is shared between outdoor and indoor outlets is fine. Lightning will have no different effect on either.


Regex matching className in jsx

Question: I have the following text file, from which I want to extract className attribute.

 toggleAccordion(ev.target)}>
   {content ? (

   {content}

Objectives:

match className="no-margin text-medium main-heading text-heading" - (Passed)
match className={classes} - (Failed)

Regex and results which I have tried:

className\s*=\s*["\{] matches both className=" or className={
className\s*=\s*["\{].+ matches both className={classes} {...attributes} onClick={ev => toggleAccordion(ev.target)}> and className="no-margin text-medium main-heading text-heading" style={{pointerEvents: 'none'}}>
className\s*=\s*["\{].+" matches className="no-margin text-medium main-heading text-heading" (one of the objective)
className\s*=\s*["\{].+\} matches className={classes} {...attributes} onClick={ev => toggleAccordion(ev.target)} and className="no-margin text-medium main-heading text-heading" style={{pointerEvents: 'none'}}

All are using the global /g flag.
Comment: /className="([\s\w-]+)"/
Comment: It has the same result. Only objective 1 is passed.
Answer: Try with this :  className\s*=\s*[\"{]([^\"}]*)?[\"}]
Demo here

Regex matching className in jsx


Instagram: Checking profile names if they are in my own follower list

Question: My idea is to build a form which checks if the typed profile name is or is not in the follower list of my instagram page. Just a simple form, something like:
<code><form action="something.php" method="post">
   <input type="text" name="profile_name"/>
   <input type="submit" value="Check">
</form>
</code>
Since the Instagram API is almost deprecated I was wondering if there is a way to get a follower list...or other ways to get a "true" or "false" in the end.
Comment: You can write a parser...
Answer: You can use this "Instagram's private API"
There is a function to get followers (line 360)
Comment: I will try it out and see what I will achieve! Thanks alot!


C - Same number of number of comparisons for bubble sort and insertion sort

Question: Recently I am doing a school task that ask us to write a program to count the number of comparisons for bubble sort and insertion sort.
However, when I execute the program, it returns 2 same value for bubble sort and insertion sort.
Example:
Sorted!
Number of comparison for bubble sort:    559150
Number of comparison for insertion sort: 559150

Here is my program:
#include<stdio.h>
#include<time.h>
#define SIZE 1500

void swap(int *a,int *b)                 //swap function
{
    int temp;
    temp = *a;
    *a = *b;
    *b = temp;
}

int bubblesort(int x[])                  //Bubble sort
{
    int i,j;
    int count = 0;
    for(i=0;i<SIZE-1;i++)
    {
        for(j=0;j<SIZE-i-1;j++)
        {
            if(x[j]>x[j+1])
            {
                swap(&x[j],&x[j+1]);
                count = count + 1;      //count comparison
            }
        }
    }
    return count;
}

int insertionsort(int x[])             //Insertion sort
{
    int i,j,temp;
    int count = 0;
    for(i=1;i<SIZE;i++)
    {
        temp = x[i];
        j = i-1;
        while((j>=0)&&(x[j]>temp))
        {
            count = count + 1;          //count comparison
            x[j+1] = x[j];
            j--;
        }
        x[j+1] = temp;
    }
    return count;
}

int main()
{
    int i;
    int b_array[SIZE];
    int i_array[SIZE];
    int b_count = 0;
    int i_count = 0;

    srand(time(NULL));

    for(i=0;i<SIZE;i++)             //Generate random number and assign it the the array
    {
        b_array[i] = rand()%SIZE;
        i_array[i] = b_array[i];
    }

    b_count = bubblesort(b_array);
    i_count = insertionsort(i_array);

    printf("Sorted!\n");
    printf("Number of comparison for bubble sort:    %d\n",b_count);
    printf("Number of comparison for insertion sort: %d",i_count);

    return 0;
}

I want to know where the problem is? and how can I solve it?
Thanks a lot.
Comment: Why is it a problem?
Answer: Number of comparisons - how many times program reach if statement.
In case of bubble sort - if(x[j]>x[j+1]).
In case of insertion sort - (x[j]>temp) in while loop. So you are counting number of swaps not comparisons.
int bubblesort(int x[])
{
    int i,j;
    int count = 0;
    for(i=0;i<SIZE-1;i++)
    {
        for(j=0;j<SIZE-i-1;j++)
        {
            count++;      //comparison. Increment "count" each time program reach "if"
            if(x[j]>x[j+1])
            {
                swap(&x[j],&x[j+1]);
            }
        }
    }
    return count;
}

Answer: I don't see anything strange with this at all. They both have the same time complexity, which is O(n²). They also have O(n²) comparisons. Besides. If you analyze bubble sort and insertion sort (the variant without binary search, which is the one you're using) you'll find that they are VERY similar.
But when I look in your code, you do not count comparisons. You count swaps.
    for(j=0;j<SIZE-i-1;j++) {
        // Move it outside the comparison
        count = count + 1;      //count comparison
        if(x[j]>x[j+1]) {
            swap(&x[j],&x[j+1]);
        }
    }

Comment: Actually having same time complexity in asymptotic case isn't really related to having same number of comparisons with some specific input.
Comment: I understand that the time complexity for both sorting is the same. But I find it strange to have the exactly same number of comparisons every time I run the program


How to plot a graph using my C program

Question: My problem is that I can't plot a graph from my c program.
When I searched StackOverflow and google, I got this statement:
system("gnuplot -p -e \"plot 'C:/Users/Ashfaaq Muhammad Dam/Desktop/New folder (3)/myfile.txt'\"");
But the problem is that the terminal says Gnuplot is not recognised as internal or external command.
//start of the program
 #include <stdio.h>
 #include <conio.h>\
 #include <stdlib.h>

int main()
{
        int j;
        int i;

printf("Enter how many coordinates you want to input:\n");
scanf("%d", &j);

int x[j];
int y[j];

 for(i=0; i<j; i++)
   {
       printf("Enter your x and y coordinate:\n");
       scanf("%d %d", &x[i], &y[i]);

   }

   freopen("myfile.txt", "w", stdout);

   for(i=0; i<j; i++)
   {
       printf("\n%d %d\n", x[i], y[i]);

   }
system("gnuplot -p -e \"plot 'C:/Users/Ashfaaq Muhammad Dam/Desktop/New folder (3)/myfile.txt'\"");

system("pause");

return 0;
}

// Ending it.
Comment: You need to install gnuplot
Comment: did you install `gnuplot`?
Comment: After I run my c program, a txt file is saved.
if I use Gnuplot to plot the coordinate in the txt file, the points are plotted. But I want my program to plot it directly after the user inserted the coordinates
Answer: is gnuplot found when you run it directly from the terminal prompt?
Either gnuplot is not installed or it is not in your PATH.
A simple solution is to find its location with which gnuplot or find / -name gnuplot -type f and use the absolute path in the system string argument.
Comment: Thanks a lot.
Actually I haven't inserted it in my PATH.
Answer: I think you need to install gnuplot in your system. Try
sudo apt-get install gnuplot-nox

Or
sudo apt-get install gnuplot-qt

Or
sudo apt-get install gnuplot-x11

How to plot a graph using my C program


Fn keys can't adjust brightness MATE desktop

Question: I just installed Ubuntu 14.04 and removed Unity and installed MATE. Now, the Fn keys on my keyboard can't adjust brightness. Here's the thing that makes it extra extr confusing: my brightness worked under Unity. Even more confusing, there is a bug in MATE that makes a small white square appear. I don't see it. It's like when I press my brightness keys, nothing happens like I'm not even pressing them. This worked under Unity.
Comment: Also, I'm not using a version of Ubuntu MATE or anything, I installed the packages myself from official PPAs and the Ubuntu repos.
Comment: Is there a package that is responsible for the brightness? maybe I need to install it.
Comment: Okay. If no one wants to give me an answer, at least tell me of a program I can use to adjust my brightness. A command would do nicely.
Answer: The problem is MATE does not come with a program to manage brightness. In a terminal, type sudo apt-get install mate-power-manager and let it install. Restart, and brightness should now work because there is a program to handle brightness key presses.


Best design pattern for a conditional booking system

Question: I'm building a flight booking system from a specification for my OOP class in college. The system has to be written in C#. I'm wondering what the best way to tackle the following problem would be

The company currently operates a discount scheme. Western Isles residents get a 10% discount.
  Scotia also records the island of residence of these passengers for marketing purposes. Business
  travellers get a 25% discount and must supply their company name. Ordinary passengers do not
  normally receive a discount unless it is part of a current promotion, in which case they receive a
  5% discount.

Should I have a passenger class, from which each separate type of customer inherits from? Any help on this would be appreciated
Comment: @DarrenFindlay If this is for college, I'm sure your professor wants you to use the strategy pattern. It is one of the typical examples I saw in college too.
Comment: I'd probably also use a decorator if passengers can receive multiple discounts, is that the case?
Comment: Hi Benjamin. Each customer can only receive one of the available discounts. Thanks.
Comment: Does your description mean that a passenger can get multiple discounts? Like 10% because of residence *and* 25% for business? If so, I guess one derived class per discount would not work. In a real world scenario, I would consider some simple if-statements because introducing a full fledged pattern seems way overengineered. However, if it's homework and you want to show off, maybe you can find one that better fits the "many discounts" requirement.
Comment: Youve stated passengers only get one discount? Are you *sure* thats in the spec?
Comment: Hi Jamie, yeah its not actually in the spec but I have confirmed this with my lecturer. Thanks.
Comment: @DarrenFindlay Did you tried something or thought something?
Answer: In my opinion you do not want to inherit from Passenger. Inheritance implies that the object changes in some way, but a passenger is a passenger no matter what discount he obtains. Put another way, his functionality does not change just because he gets a bigger discount.
This example you are using is very close to the examples usually given for the Decorator pattern, although that is usually because it demonstrates that multiple discounts can be applied to the object being decorated (Passenger in your case). Take a look at the Coffee example on wiki here
Another possibility is Strategy pattern, this gives you a clean interface for creating a Ticket for a passenger, while internally it switches the DiscountStrategy depending upon what type of passenger is requesting a ticket.
Comment: +1 Concerns of passenger class are orthogonal to discount logic
Comment: Thanks Jamie, great answer. I think I'm going to go with the strategy pattern as it seems most fitting. What about the face that Business customers need their business name recorded? And western Isles customer need their Island of residence recorded? This is were i get confused. Thanks again.
Comment: @DarrenFindlay - Aha, now *that* might give you a case for inheritance. The Passenger clearly has additional functionality (in this case, new fields for the extra info). As a side effect of that, you can use the type of passenger to determine the right discount strategy to use.
Comment: Excellant, thanks Jamie. Should passenger creational logic then be encapsulated? For example a passenger factory? Or factory method?
Answer: You want to make discount policy flexible, the passengers are not really that different.
You could have a Customer base class from which Passenger and Company derive, but that doesn't really affect how you apply the discount logic.
Inheritance implies different behavior, but behavior of passengers doesn't change, only the applied discounts, and discount should not be a part of passenger state so it doesn't fit into that class. Additionally, many discounts are active only for some timespan, and it doesn't make sense to encode that into Customer class, you should be able to add and remove them dynamically.
As discount logic is actually a business rule which is applied at customer, it should be encapsulated into a separate set of classes. Common pattern used to implement this is strategy. Depending on your design, as you want to apply different policies to different type of users, you might find visitor pattern useful or not.
Answer: I would use a Strategy pattern as described in previous posts"Another possibility is Strategy pattern, this gives you a clean interface for creating a Ticket for a passenger, while internally it switches the DiscountStrategy depending upon what type of passenger is requesting a ticket."
Answer: if it is all about discount shemes, it may be sufficient to just use the decorator pattern as described by others.
Then you would check the type of the interface and not of the passenger, if you want to e.g. list the number of business travellers, or residence for marketing purposes etc.


Based on user id, determine if a user is an app user for your app (php, not fbml!)

Question: I know of the FBML tag to see if "is app user" for an id, but how can I determine that within PHP itself?
Comment: There is no way using the FB's API to know if a user installed/authorized your app. It's up to you to store that information when user authorizes it for the first time. By the way, Facebook doesn't send you a valid user session with an user id if the user did not authorized first.
Comment: They also don't seem to include many examples for PHP...I had to spend an hour of googling simply figuring out how to get that friend list in the first place.
Answer: It seems that i have misread the question. if you want to know if your user is an app user  or not you cannot use the graph api.
When a user comes to your application for the first time facebook sends you some data regarding that user. At that time you can decide what to do with that information. An easy way would be to use a database and store the id of that user so you can later use it when you want to check if other users have used your app or not.


Selenium RC - Unable to click on a link using XPATH / CSS path / //a[contains(text(),'abc')]

Question: Selenium IDE is able to recognise the ID, Xpath, CSSPath for a link. But, Selenium RC is unable to click on the link using XPath or CSSPath or ID. I have also used "Contains Text()", but of no use. Please find below code that i am currently executing in Eclipse IDE.
selenium.open("https://abc.com");
selenium.type("UserName", "123456");
selenium.click("xpath=//form[@id='loginForm']/table/tbody/tr[7]/td/input");
selenium.click("xpath=//a[@id='_ebg9dd']");
// selenium.click("xpath=//a[contains(text(), 'Request Form')]");

Can someone please suggest any other alternative or correct the code if there is any discrepancy ?
Answer: Are you converting it using the IDE? For example, this is an Xpath selector for Java Junit 4 RC:
Seems unusual to have an id on your a-tag but if you wanted to try using 'contains' this is an example of one that works for me when I just tried it..
selenium.click("//div[@class='span5 footer-links']/ul/li/a[contains(text(), 'Submit your page')]");

I also wonder about the fact that you look to be inputting text into a 'username' field and then followed with two 'clicks'. Do you not need to either input something into another field or wait for something after the first click? Just seems like an odd series of events (may not be though, I obviously don't know the specifics of what it is you're doing.
Comment: Hi Goose, In our application, we do not need to enter any password after Entering user name. So, I am clicking on the login button. After entering the User HomePage, i am clicking on the other link whose xpath is "//a[@id='_ebg9dd']". But i am unable to click the element. i have used "isElementPresent" command in Selenium RC. This command is returning True, which means the element is found. but when i use the command selenium.click("xpath=//a[@id='_ebg9dd']");                          the link is not being clicked. The result in Eclipse Console is displayed is "OK"
Answer: Try this :
selenium.click("link=name_of_link_present_on_page");


Best method for saving data - preferences, sqlite, serializable or other?

Question: I've been investigating alternative methods for saving my game's data between turns, and wonder if anyone can point me in the right direction.
I have approximately 32k of data which must be saved during onPause.  I ruled out preferences due to the sheer quantity of data.  I spent a few days playing around with SQLite but couldn't get the data to save in less than two seconds (although the time certainly hasn't been wasted).
I've decided that I'll use the database for loading constant data at the beginning of the game.  This will certainly make it easier to tweak various parameters and default values in the game.  But this still leaves me looking for the ideal method for writing data.
The data that needs to be saved is basically nine occurrences of class A and nine occurrences of class B.  I'm an intensive month into the learning curve of Android (and the nuances of Java, coming from a C++ background) and have been googling like crazy.  This brought two possibilities to mind -
1) Serialization (ObjectOutputStream)
I thought this would be the perfect solution but, having read several other posts regarding the subject, gather that it isn't highly recommended on the Android platform due to speed and memory allocations provoking the garbage collector into a potential rage.
2) DataOutputStream class
My current thought is to add Load and Save functions to both classes and to use DataOutputStream and DataInputStream calls in them to write and read the data respectively.
The data in the classes are primitives (strings and ints mostly) and arrays of primitives, so there's nothing too complicated in there to break down.  Would this second solution seem a good, viable one?  Or are there other solutions that I am unaware of as yet?
Comment: Thanks for the advice.  I've gone with the DataOutputStream method and the time taken to write the data is now negligible (approx 0.1 seconds).  I'm glad I got sidetracked with SQLite databases though, as they're sure to come in very useful, too :)
Comment: The main consideration to take into account is that writing to flash can be a long operation, irrespective of the size of the data. Even writing 1 byte can take a noticeable amount of time. So make sure your solution buffers up all the data and writes it in as few operations as possible.
Answer: Why do you have a 2 second limit on your database write?  If it is purely for the sake of UI responsiveness, then there is another approach you can take.
You don't actually have to perform the save within your onPause method itself, you could just kick off a new Thread that actually does the save for you.
private void backgroundSave(){
    Thread backgroundThread = new Thread() {
        @Override
        public void run() {
            //do save here
        }
    };
    backgroundThread.start();
}

@Override
protected void onPause() {
    super.onPause();
    backgroundSave();
}

You could alternatively use an AsyncTask for this.
You might have to consider the case when a user attempts to restart your app before the save is complete, but that shouldn't be too hard to take into account.
Comment: The data being saved is in constant use throughout all activities.  The idea of assigning the save to a background thread sounds a good one, but I haven't had time yet to familiarise myself with solving synchronization issues.  It's something I will definitely look into as soon as I get the chance.  For now, I've found that I can write the data in a binary file in around 0.1 seconds.  I do appreciate the advice though.  So much to learn, so little time... :)
Answer: You should use an Async task to save the data, I used this method to fetch highscores at the start a game:
new HighscoreTask().execute(this);

the Async task looks like this:
public class HighscoreTask extends AsyncTask<MainView, Void, Void> {

    protected void onPreExecute() {
    }

    protected void onPostExecute(final Void unused) {
    }
    @Override
    protected Void doInBackground(MainView... params) {
        HighScoreFactory.syncScores();
        return null;
    }
}

All the database interaction happens in HighScoreFactory.syncScores() this can take as long as it needs because it happens in the background. In my case it sends an HTTP request to an external server and loads these into a database. It's never caused any problems and works seamlessly.
Comment: Thanks - I'll certainly keep that in mind.  I'm saving the game data as raw binary files now which is working a *lot* faster.  But will definitely investigate Async as a few people have suggested it now.
Answer: Have you tried insert data to the database in transaction?
try{
 db.beginTransaction();

 //here insert data to database

 db.setTransactionSuccessful();
} finally {
 db.endTranscation();
}

That can speed up operation.
Comment: I experimented with using transactions to the point where all my writes were done in a single transaction - this brought the time down from 8 seconds to 2 seconds.  I seemed to hit a brick wall at that point and, give or take a tenth of a second, couldn't get any lower.  This is the first SQLite coding I've done, but my feeling was that I couldn't get it any quicker (though I'd be happy to be told otherwise)
Answer: Create a new Thread that does the data writing using Context.openFileOutput(String name, int mode) with this as the context. You can then write it in the background with the new thread and retrieve it with: Context.openFileInput(String name) again with this as the context. Hopefully this helps.


Find an equivalence relation on $\mathbb{N}$ with exactly 3 classes and such that one class hase size 30, another 50.

Question: My answer is: Let $X=${$1,2,3,4,5,...,147$} and let for all $x,y\in\mathbb{N}$, $x=y\Leftrightarrow x-y\in 3X$. There are threee classes and such that one class hase size 30, onether 50.
Can you check my answer?
Comment: that relation isn't an equivalence relation
Comment: Equivalence relations can be defined by arithmetical formulae and you can try to see what the equivalence classes become... Or you can go the other way and define whatever equivalence classes you want and make an equivalence relation from there.
Comment: Hint: You don't need any arithmetic at all. Just make the two classes you need and ...
Comment: Longer hint. Let the first set be $\{1,2, ..., 30\}$. Then let the second set be $\{100, 101, ... , ?\}$.
Comment: Your relation isn't transitive. $1$ is related to $400$ and $400$ to $799$, but $1$ isn't related to $799$.
Comment: Yes. You are right. So, what should be answer?
Comment: @EthanBolker Can you give more clear hint?
Comment: @DavidP Is it eq. relation ?
Answer: Let $X_1=\{1,2,\cdots,50\},X_2=\{51,52,\cdots,80\}$ and $X_3=\{81,82,\ldots\}$. If we can make an equivalence relation with these three sets as the equivalence classes, then we're done. And we can: let the relation $\sim$ be defined by $x\sim y$ iff $x$ and $y$ belong to the same $X_i$.


Is the weather report ever incorrect?

Question: I checked the TV on my last day of Spring - Year 1 and it said that it would rain tomorrow. SCORE! I can prep fields to start planting right away tomorrow (well, after the seed shop opens). After spending the time tilling the soil and fertilizing, I go to sleep, excited to jump into Summer without having to water day 1.
Overnight there was an event that shook things up.

 From what I can find online (Spoilers Guide) the earthquake always happens end of Spring - Year 1.

Not only that, it wasn't raining the next day!
Now I'm beginning to doubt if I checked the weather correctly.
Is the weather report ever incorrect?
Was this because of the other event that happened overnight or that the season changed?
What other events might cause the weather to be different than what the TV says? Did I just fail to remember what the friendly weather person told me?
Comment: The only time I've *noticed* it being "wrong" was when I checked it after midnight and it gave me the *next* next day's weather, so it was actually right. … Though come to think, that may count as a bug worth reporting, since you can get two days' weather that way.
Comment: On my very first day (day 1), the TV told me it'd rain the next day, but it actually rained on day 3 instead of day 2. I'm not quite sure if I just misinterpreted the forecast, though.
Comment: Same thing happened to me, except it was windy weather instead of rain. I think its only wrong in corner cases like this. When the seasons change there's a new set of possible weather conditions.
Comment: (…and of course, I haven't been able to reproduce it since writing that comment.)
Answer: From personal experience I can confirm that on multiple occasions weather report was wrong about today's weather.
Both with wrongly forecasting rain (when a sunny day actually happened) and with failing to forecast it (sunny forecast with an actual rain).
Answer: Sometimes the weather report says it's going to be sunny, but the next day it's raining.

Is the weather report ever incorrect?


Don't show hours in 1 month zoom Highstock

Question: I need to hide the hours when zoomed to 1 month.
I have a demo here: http://dev.feldsam.cz/unipetrol-stock/
I tried to use tickPositioner:
tickPositioner: function(min, max) {
    var diff = max - min;

    // month
    if(diff <= 31 * 24 * 3600 * 1000 && diff > 24 * 3600 * 1000) {
        var date = new Date(max);
        var minus = date.getHours() * 3600 * 1000;
        max = max - minus;

        var pos,
        tickPositions = [],
        tickStart = new Date(date.getFullYear(), date.getMonth(), 1).getTime();

        for (pos = tickStart; pos <= max; pos += (5 * 24 * 3600 * 1000)) {
            tickPositions.push(pos);
        }

        tickPositions.info = {
            unitName: "day",
            higherRanks: {}
        };

        this.options.ordinal = false;

        return tickPositions;
    } else {
        this.options.ordinal = true;
    }
}

But the hours are still showing. Also, when I click from one month to another, ordinal is still false.
Answer: You can define it in dateTimeLabelFormat http://api.highcharts.com/highstock#xAxis.dateTimeLabelFormats


Implementing a "soft delete" system using sqlalchemy

Question: We are creating a service for an app using tornado and sqlalchemy. The application is written in django and uses a "soft delete mechanism". What that means is that there was no deletion in the underlying mysql tables. To mark a row as deleted we simply set the attributed "delete" as True. However, in the service we are using sqlalchemy. Initially, we started to add check for delete in the queries made through sqlalchemy itself like:
customers = db.query(Customer).filter(not_(Customer.deleted)).all()

However this leads to a lot of potential bugs because developers tend to miss the check for deleted in there queries. Hence we decided to override the default querying with our query class that does a "pre-filter":
class SafeDeleteMixin(Query):
    def __iter__(self):
        return Query.__iter__(self.deleted_filter())
    def from_self(self, *ent):
        # override from_self() to automatically apply
        # the criterion too.   this works with count() and
        # others.
        return Query.from_self(self.deleted_filter(), *ent)
    def deleted_filter(self):
        mzero = self._mapper_zero()
        if mzero is not None:
            crit = mzero.class_.deleted == False
            return self.enable_assertions(False).filter(crit)
        else:
            return self

This inspired from a solution on sqlalchemy docs here:
https://bitbucket.org/zzzeek/sqlalchemy/wiki/UsageRecipes/PreFilteredQuery

However, we are still facing issues, like in cases where we are doing filter and update together and using this query class as defined above the update does not respect the criterion of delete=False when applying the filter for update.
db = CustomSession(with_deleted=False)()
result = db.query(Customer).filter(Customer.id == customer_id).update({Customer.last_active_time: last_active_time })

How can I implement the "soft-delete" feature in sqlalchemy
Answer: I've done something similar here. We did it a bit differently, we made a service layer that all database access goes through, kind of like a controller, but only for db access, we called it a ResourceManager, and it's heavily inspired by "Domain Driven Design" (great book, invaluable for using SQLAlchemy well).  A derived ResourceManager exists for each aggregate root, ie. each resource class you want to get at things through.  (Though sometimes for really simple ResourceManagers, the derived manager class itself is generated dynamically) It has a method that gives out your base query, and that base query gets filtered for your soft delete before it's handed out. From then on, you can add to that query generatively for filtering, and finally call it with query.one() or first() or all() or count(). Note, there is one gotcha I encountered for this kind of generative query handling, you can hang yourself if you join a table too many times. In some cases for filtering we had to keep track of which tables had already been joined. If your delete filter is off the primary table, just filter that first, and you can join willy nilly after that.
so something like this:
class ResourceManager(object):
     # these will get filled in by the derived class
     # you could use ABC tools if you want, we don't bother
     model_class = None
     serializer_class = None

     # the resource manager gets instantiated once per request
     # and passed the current requests SQAlchemy session
     def __init__(self, dbsession):
         self.dbs = dbsession

     # hand out base query, assumes we have a boolean 'deleted' column
     @property
     def query(self):
         return self.dbs(self.model_class).filter(
            getattr(self.model_class, 'deleted')==False)

 class UserManager(ResourceManager):
     model_class = User

 # some client code might look this
 dbs = SomeSessionFactoryIHave()
 user_manager = UserManager(dbs)
 users = user_manager.query.filter_by(name_last="Duncan").first()

Now as long as I always start off by going through a ResourceManager, which has other benefits too (see aforementioned book), I know my query is pre-filtered. This has worked very well for us on a current project that has soft-delete and quite an extensive and thorny db schema.
hth!
Answer: I would create a function
def customer_query():
    return db.session.query(Customer).filter(Customer.deleted == False)

I used query functions to not forget default flags, to set flags based on user permission, filter using joins etc, so that these things wont be copy-pasted and forgotten at various places.
Comment: `customer_query().filter(something).update(something2)` should apply the delete filter along with the `something` filter.
Comment: That does not stop the querying without the deleted, This is critical. Because the whole point is avoiding mistakes.


What exactly goes wrong with this definition of a limit

Question: What goes wrong when I define $\displaystyle{\lim_{x \to c} f(x) = L}$ as $$ \forall \epsilon > 0, \forall \delta > 0; 0 < |x-c|<\delta \implies |f(x)-L|<\epsilon$$
Comment: That's only true when $f$ is constant, and that constant is $L$.
Comment: It can't be true for *ALL* $\delta$ because if you make $\delta$ honkin' huge and $f$ isn't constant everywhere but at $x=c$ this can always be falsee.  Let $f(x_0)\ne L$.  Let $\delta > |x_0-c|$ and let $\epsilon < |f(x_0) - L|$.  This *cant* be true.
Comment: In words, you don't want $f(x)$ to be close to $L$ for points that are any distance from $c$, you just want them to be close to $L$ for points that are **sufficiently** close to $c$. So all that matters is that you can find **some** $\delta>0$.
Comment: @LordSharktheUnknown quibble:  $f(x) = L$ if $x \ne c$ and $f(c) = M$.  Then $\lim_{x\to c} f(x) = L$ by this definition as well.
Comment: I adding that $c$ must be an accumulation point.
Answer: What goes wrong?  Everything.
Let $f(x) = x^2$ and let $c = 2$
Claim $\lim_{x\to 2} x^2 \ne 4$.
Pf:  Let $\epsilon = 0.1$.  Let $\delta = 7$.
So if $x=6$ then $0 < |x-2| = |6-2| = 4 < \delta$.  But $|f(x) -4|=|36-4|=32 \not < 0.1 = \epsilon$.
So $\lim_{x\to 2}x^2 \ne 4$.
Very few functions and points will have limits.  I think only constant functions will.  Or functions that are constant everywhere but the value we are taking the limit toward.
====
You can't do it for ALL $\delta$.
If $x_0 \ne c$ and  $f(x_0) \ne L$ then we can take $\delta >|x-x_0|$ and $\epsilon < |f(x_0) -L|$. And then  you have .....
$|x-x_0| < \delta$ and $|f(x) - L| > \epsilon$.
So $\lim_{x\to c} f(x) \ne L$. Ever.  (Assuming $f$ has at least one point other that $c$ where $f(x) \ne L$.)
Comment: +1. For the OP: rephrasing a bit, fleablood pointed out that we can "get rid of $\delta$" so that your definition is equivalent to $$\forall \epsilon>0,\forall x\not=c(\vert f(x)-L\vert<\epsilon).$$ And that is clearly equivalent in turn to $$\forall x\not=c, f(x)=L.$$
Comment: True.  Although I imagine for one inexperienced enough to make $\forall \delta > 0$ error in the definition, s/he may be equally inexperienced enough to not immediately get that $\forall \delta >0$ is the same as "getting rid of it" (we can make it so large as to have $|x-c|<\delta$ have no significance) and to not notice that $|f(x)-L|<\epsilon$ for all $\epsilon \iff f(x) = L$ (if $|f(x)-L| 0$ then if $|f(x)-L|\ne 0$ then $|f(x)-L| > 0$ and so $|f(x)-L|$ would be less than ... itself).
Answer: You should have for every epsilon, there exist a delta such as...
Else it will not work. We need to pick one delta, and show that every epsilon > 0 is less than f(x0) - L, thus their distance goes to 0, and hence f(x) -> L for sufficiently small epsilon. Letting this be true for all deltas would result in that every two point in the domain will make the limit go to L, so it would make the function a constant.