Why is the available updates data always stale after upgrading to 14.04?

Question: I upgraded from 12.04 to 14.04 and ever since then, when I log in over SSH, the available updates is incorrect and out of date. This never happened with 12.04.
For example:

Log in and no updates are shown.
Exit and log in again. I now see:
25 packages can be updated.
15 updates are security updates.
I do the update and log out. Then log in and it still says:
25 packages can be updated.
15 updates are security updates.
Log out and log in and now see
System reboot required.

The output from today's 1st login was
0 packages can be updated.
0 updates are security updates.
So I exit and log in again and now see:
1 package can be updated.
1 update is a security update.
So I run it and the result is:
Get:1 http://security.ubuntu.com trusty-security InRelease [65.9 kB]
Get:2 http://security.ubuntu.com trusty-security/main Sources [117 kB]
Get:3 http://security.ubuntu.com trusty-security/restricted Sources [4,035 B]
Get:4 http://security.ubuntu.com trusty-security/universe Sources [37.3 kB]
Get:5 http://security.ubuntu.com trusty-security/multiverse Sources [2,760 B]
Get:6 http://security.ubuntu.com trusty-security/main amd64 Packages [485 kB]
Get:7 http://security.ubuntu.com trusty-security/restricted amd64 Packages [13.0 kB]
Get:8 http://security.ubuntu.com trusty-security/universe amd64 Packages [130 kB]
Get:9 http://security.ubuntu.com trusty-security/multiverse amd64 Packages [4,978 B]
Get:10 http://security.ubuntu.com trusty-security/main i386 Packages [458 kB]
Get:11 http://security.ubuntu.com trusty-security/restricted i386 Packages [12.7 kB]
Get:12 http://security.ubuntu.com trusty-security/universe i386 Packages [130 kB]
Get:13 http://security.ubuntu.com trusty-security/multiverse i386 Packages [5,168 B]
Hit http://security.ubuntu.com trusty-security/main Translation-en
Ign http://us.archive.ubuntu.com trusty InRelease
Hit http://security.ubuntu.com trusty-security/multiverse Translation-en
Hit http://security.ubuntu.com trusty-security/restricted Translation-en
Hit http://security.ubuntu.com trusty-security/universe Translation-en
Get:14 http://us.archive.ubuntu.com trusty-updates InRelease [65.9 kB]
Get:15 http://us.archive.ubuntu.com trusty-backports InRelease [65.9 kB]
Hit http://us.archive.ubuntu.com trusty Release.gpg
Get:16 http://us.archive.ubuntu.com trusty-updates/main Sources [277 kB]
Get:17 http://us.archive.ubuntu.com trusty-updates/restricted Sources [5,352 B]
Get:18 http://us.archive.ubuntu.com trusty-updates/universe Sources [156 kB]
Get:19 http://us.archive.ubuntu.com trusty-updates/multiverse Sources [5,939 B]
Get:20 http://us.archive.ubuntu.com trusty-updates/main amd64 Packages [773 kB]
Get:21 http://us.archive.ubuntu.com trusty-updates/restricted amd64 Packages [15.9 kB]
Get:22 http://us.archive.ubuntu.com trusty-updates/universe amd64 Packages [361 kB]
Get:23 http://us.archive.ubuntu.com trusty-updates/multiverse amd64 Packages [13.2 kB]
Get:24 http://us.archive.ubuntu.com trusty-updates/main i386 Packages [740 kB]
Get:25 http://us.archive.ubuntu.com trusty-updates/restricted i386 Packages [15.6 kB]
Get:26 http://us.archive.ubuntu.com trusty-updates/universe i386 Packages [363 kB]
Get:27 http://us.archive.ubuntu.com trusty-updates/multiverse i386 Packages [13.6 kB]
Hit http://us.archive.ubuntu.com trusty-updates/main Translation-en
Hit http://us.archive.ubuntu.com trusty-updates/multiverse Translation-en
Hit http://us.archive.ubuntu.com trusty-updates/restricted Translation-en
Hit http://us.archive.ubuntu.com trusty-updates/universe Translation-en
Get:28 http://us.archive.ubuntu.com trusty-backports/main Sources [9,551 B]
Get:29 http://us.archive.ubuntu.com trusty-backports/restricted Sources [28 B]
Get:30 http://us.archive.ubuntu.com trusty-backports/universe Sources [35.2 kB]
Get:31 http://us.archive.ubuntu.com trusty-backports/multiverse Sources [1,898 B]
Get:32 http://us.archive.ubuntu.com trusty-backports/main amd64 Packages [13.3 kB]
Get:33 http://us.archive.ubuntu.com trusty-backports/restricted amd64 Packages [28 B]
Get:34 http://us.archive.ubuntu.com trusty-backports/universe amd64 Packages [43.2 kB]
Get:35 http://us.archive.ubuntu.com trusty-backports/multiverse amd64 Packages [1,571 B]
Get:36 http://us.archive.ubuntu.com trusty-backports/main i386 Packages [13.3 kB]
Get:37 http://us.archive.ubuntu.com trusty-backports/restricted i386 Packages [28 B]
Get:38 http://us.archive.ubuntu.com trusty-backports/universe i386 Packages [43.2 kB]
Get:39 http://us.archive.ubuntu.com trusty-backports/multiverse i386 Packages [1,552 B]
Hit http://us.archive.ubuntu.com trusty-backports/main Translation-en
Hit http://us.archive.ubuntu.com trusty-backports/multiverse Translation-en
Hit http://us.archive.ubuntu.com trusty-backports/restricted Translation-en
Hit http://us.archive.ubuntu.com trusty-backports/universe Translation-en
Hit http://us.archive.ubuntu.com trusty Release
Hit http://us.archive.ubuntu.com trusty/main Sources
Hit http://us.archive.ubuntu.com trusty/restricted Sources
Hit http://us.archive.ubuntu.com trusty/universe Sources
Hit http://us.archive.ubuntu.com trusty/multiverse Sources
Hit http://us.archive.ubuntu.com trusty/main amd64 Packages
Hit http://us.archive.ubuntu.com trusty/restricted amd64 Packages
Hit http://us.archive.ubuntu.com trusty/universe amd64 Packages
Hit http://us.archive.ubuntu.com trusty/multiverse amd64 Packages
Hit http://us.archive.ubuntu.com trusty/main i386 Packages
Hit http://us.archive.ubuntu.com trusty/restricted i386 Packages
Hit http://us.archive.ubuntu.com trusty/universe i386 Packages
Hit http://us.archive.ubuntu.com trusty/multiverse i386 Packages
Hit http://us.archive.ubuntu.com trusty/main Translation-en
Hit http://us.archive.ubuntu.com trusty/multiverse Translation-en
Hit http://us.archive.ubuntu.com trusty/restricted Translation-en
Hit http://us.archive.ubuntu.com trusty/universe Translation-en
Ign http://us.archive.ubuntu.com trusty/main Translation-en_US
Ign http://us.archive.ubuntu.com trusty/multiverse Translation-en_US
Ign http://us.archive.ubuntu.com trusty/restricted Translation-en_US
Ign http://us.archive.ubuntu.com trusty/universe Translation-en_US
Fetched 4,499 kB in 5s (775 kB/s)
Reading package lists... Done
Reading package lists... Done
Building dependency tree
Reading state information... Done
Calculating upgrade... Done
The following packages will be upgraded:
  libxml2
1 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
Need to get 573 kB of archives.
After this operation, 0 B of additional disk space will be used.
Do you want to continue? [Y/n] y
Get:1 http://us.archive.ubuntu.com/ubuntu/ trusty-updates/main libxml2 amd64 2.9.1+dfsg1-3ubuntu4.8 [573 kB]
Fetched 573 kB in 0s (1,256 kB/s)
(Reading database ... 41499 files and directories currently installed.)
Preparing to unpack .../libxml2_2.9.1+dfsg1-3ubuntu4.8_amd64.deb ...
Unpacking libxml2:amd64 (2.9.1+dfsg1-3ubuntu4.8) over (2.9.1+dfsg1-3ubuntu4.7) ...
Setting up libxml2:amd64 (2.9.1+dfsg1-3ubuntu4.8) ...
Processing triggers for libc-bin (2.19-0ubuntu6.9) ...

and then I exit and log in again and it still says
1 package can be updated.
1 update is a security update.
and then I exit and log in again and now it is correctly not showing any updates available at all.
To reiterate - the problem is NOT with the updating, the problem is with the available updates ALWAYS being delayed by one log in/log out cycle. Makes absolutely no sense to me!
Comment: Have you rebooted yet?
Comment: Do you have any held packages? What's the output of `apt-get dist-upgrade --dry-run`?
Comment: Could this be the same bug as in this question? http://askubuntu.com/questions/36517/ubuntu-tells-me-i-have-packages-to-upgrade-when-i-dont
Comment: Yes I've rebooted many times. Output is `0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.` That bug was from 2011 and I don't have a motd file.
Comment: can you post the output of the update command so we can see how it went
Answer: You sometimes see old information because a cache is used.
We'd like the message to be up-to-date, but we also don't want to block on giving you a prompt while determining the update status. For example, you might be trying to log in to fix some unrelated fault causing excessive disk I/O; it would be frustrating if you couldn't do so quickly because logging in insisted on creating more disk I/O while update status is checked, when you don't even care about that to fix your disk I/O fault.
The point of the message is a reminder to install updates if you don't have automatic updates enabled and if you haven't logged in for a while. If you have just installed updates yourself, or want to query the exact up-to-the-minute information, you should use apt-get directly as you have done.
The message comes from the update-notifier-common package via /etc/update-motd/90-updates-available. To minimise login time, the script uses a cache. If the cache is considered stale, the information is updated. If the cache is not considered stale, for example if the information was recently updated, then the information is not updated.
In 16.04, we have adjusted the details again in favour of not slowing down login at all.
Answer: What are the contents of /usr/lib/update-notifier/update-motd-updates-available ?
https://bugs.launchpad.net/ubuntu/+source/update-motd/+bug/766827
Comments #14, #18, #22
(Sorry, I cannot make a comment yet)
Answer: Through this thread I found the solution was to disable the caching of update messages by editing these two files:
/etc/pam.d/sshd
/etc/pam.d/login
Delete "noupdate" from this line:
session    optional     pam_motd.so  motd=/run/motd.dynamic noupdate
I generally log in once a week and I now have available update messages that accurately show the current state rather than being stale by a week.
Comment: Spoke too soon. The problem is back. I guess I'm very much in the minority with only one login a week. So will just have to log in/log out/log in to get the correct data.


JFrame printing very weirdly?

Question: I'm trying to make a java RAT but atm I only have screen displaying. When I run it it displays the screen on the JFrame fine, but it keeps dragging the same image a little lower with each draw like this:

Client:
import java.awt.AWTException;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.io.IOException;
import java.net.Socket;
import java.util.zip.GZIPOutputStream;
import javax.imageio.ImageIO;

public class Client {

    public static void main(String[] args) {
        try {
            Robot robot = new Robot();
            Toolkit toolkit = Toolkit.getDefaultToolkit();
            Rectangle screen = new Rectangle((int) toolkit.getScreenSize().getWidth(), (int) toolkit.getScreenSize().getHeight());
            Socket socket = new Socket("127.0.0.1", 25565);
            GZIPOutputStream out = new GZIPOutputStream(socket.getOutputStream());

            while(socket.isConnected()) {
                ImageIO.write(robot.createScreenCapture(screen), "png", out);
            }
            out.close();
        } catch (AWTException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Server:
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.zip.GZIPInputStream;

import javax.imageio.ImageIO;

public class Server {

    public static void main(String[] args) {
        try {
            ServerFrame frame = new ServerFrame();
            ServerSocket serverSocket = new ServerSocket(25565);
            Socket socket = serverSocket.accept();
            GZIPInputStream in = new GZIPInputStream(socket.getInputStream());
            BufferedImage image = null;
            while(socket.isConnected()) {
                image = ImageIO.read(in);
                if(image != null) {
                    frame.setBufferedImage(image);
                }
            }
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

ServerFrame:
import java.awt.Graphics;
import java.awt.image.BufferedImage;

import javax.swing.JFrame;

public class ServerFrame extends JFrame {

    private BufferedImage image;

    public ServerFrame() {
        setTitle("RAT");
        setSize(1920, 1080);
        setVisible(true);
        image = null;
    }

    public void setBufferedImage(BufferedImage image) {
        this.image = image;
        this.repaint();
    }

    public void paint(Graphics g) {
        if(image != null) {
            g.drawImage(image, 0, 0, this);
        }
    }
}

Answer: For some reason the drawing of the screen capture in the g.drawImage(image, 0, 0, this);  line, when drawing in the JFrame, begins to slide up and left when you view the frame maximized.
Try extending ServerFrame from JPanel and adding it to a JFrame, that way you get an anchor in the top-left corner. You can add a JScrollPane in there too, so that you can navigate the whole panel with the screen capture.
Here's the code I used to replicate your situation, it captures the screen whenever a key is pressed. I renamed the ServerFrame class to ScreenCapture.
Hope it helps.
import java.awt.AWTException;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferedImage;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class ScreenCapture extends JPanel implements KeyListener {

    private BufferedImage image;

    public ScreenCapture() {
        setSize(1920, 1080);
        setVisible(true);
        image = null;
    }

    public void setBufferedImage() throws AWTException {
        Robot robot = new Robot();
        Toolkit toolkit = Toolkit.getDefaultToolkit();
        Rectangle screen = new Rectangle((int) toolkit.getScreenSize().getWidth(), (int) toolkit.getScreenSize().getHeight());
        this.image = robot.createScreenCapture(screen);
        this.repaint();
    }

    public void paint(Graphics g) {
        if (image != null) {
            g.drawImage(image, 0, 0, this);
        }
    }

    @Override
    public void keyTyped(KeyEvent e) {}

    @Override
    public void keyPressed(KeyEvent e) {
        try {
            setBufferedImage();
        } catch (AWTException e1) {
            e1.printStackTrace();
        }
    }

    @Override
    public void keyReleased(KeyEvent e) {}

    public static void main(String [] args) {
        ScreenCapture capture = new ScreenCapture();

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.addKeyListener(capture);
        frame.add(capture);
        frame.setSize(500, 500);
        frame.setVisible(true);
    }
}

EDIT
Here's a piece of code to wrap the image in a JScollPane.
import java.awt.AWTException;
import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferedImage;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;

public class ScreenCapture extends JLabel implements KeyListener {

    private BufferedImage image;

    public ScreenCapture() {
        setSize(1920, 1080);
        setVisible(true);
        image = null;
    }

    public void setBufferedImage() throws AWTException {
        Robot robot = new Robot();
        Toolkit toolkit = Toolkit.getDefaultToolkit();
        Rectangle screen = new Rectangle((int) toolkit.getScreenSize()
                .getWidth(), (int) toolkit.getScreenSize().getHeight());
        this.image = robot.createScreenCapture(screen);
        this.setIcon(new ImageIcon(this.image));
        this.repaint();
    }

    @Override
    public void keyTyped(KeyEvent e) {
    }

    @Override
    public void keyPressed(KeyEvent e) {
        try {
            setBufferedImage();
        } catch (AWTException e1) {
            e1.printStackTrace();
        }
    }

    @Override
    public void keyReleased(KeyEvent e) {
    }

    public static void main(String[] args) {
        JPanel panel = new JPanel();
        panel.setLayout(new BorderLayout());

        ScreenCapture capture = new ScreenCapture();
        JScrollPane scroll = new JScrollPane();
        scroll.getViewport().add(capture);
        panel.add(scroll, BorderLayout.CENTER);

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(panel);
        frame.addKeyListener(capture);
        frame.setSize(500, 500);
        frame.setVisible(true);
    }
}

Comment: Thanks a lot, I can't rep but if I could I definitely  would :D
Comment: No problem :). You can mark the answer as correct if it answered your question. Glad I could help.

JFrame printing very weirdly?


Swift UIButton Image color

Question: I want put the image on button, so I
var cancelImage =
    UIImage(named: "close.png")?.withRenderingMode(.alwaysTemplate)

self.viewCancel.setImage(cancelImage, for: .normal)

close.png color is skyblue but build the project, it seems like UIButton default color(I can't explain that but I guess, it maybe .systemBlue)
I want show the image's color.
How I can show it?
Answer:
I want show the image's color

Then why did you say withRenderingMode(.alwaysTemplate)? You are slapping yourself in the face and then complaining that your face is being slapped.
Instead, say withRenderingMode(.alwaysOriginal).
Answer: When you use
withRenderingMode(.alwaysTemplate)

you're telling the system you want to use the image as a template. This allows it to use the UIButton's tintColor property to tint the image. If you want to use the image's normal colors, you should remove the
.withRenderingMode(.alwaysTemplate)

and just use
UIImage(named: "close.png")

Here's the doc for alwaysTemplate
Comment: sure, should remove 'withRenderingMode(.alwaysTemplate)' as a normal state
Comment: @Chris Hansen So I remove the .alwaysTemplate, but it's color like blue, but set .alwaysOriginal, it is what i want. Thank you for your answer

Swift UIButton Image color


How can I heat up my apartment more efficiently?

Question: I live in a studio apartment that I rent from my parents, in France. Each winter, it gets very cold. The region is very sunny, but the specific area around my building is significantly colder (due to being in a small valley, a water stream nearby, tall trees, etc). The building is very old (1800s) and made out of stone. My studio has two floors: the second floor (main area) and a bedroom upstairs, under the roof.
I did not heat my apartment from spring to November, but this past few days, it has been very cold and I need to act. The temperature in the studio dropped from 20ish degrees celsius to 11.5 in a matter of days. The problem is that I track my power consumption using an app provided by the electricity company, and as soon as I turned on the heaters, my daily cost went from 1.90€ to 7.50€. I unfortunately cannot afford to pay this daily for the whole winter.
Here is how the apartment is heated.
Second floor (main floor, kitchen, office, bathroom):

There is a new generation "ceramic inertia heater" underneath the kitchen window (facing south).
There are two old school electric radiators under the windows facing North
There is a heating towel rack in the bathroom, that I never really use
The kitchen window is well located but really tall trees prevent a lot of sunlight from entering the room. Each day, I have to turn on the lights, except between 11 AM to 2 PM approximately.

Third floor (bedroom, under the roof)

There is a ceiling window (Velux) on the roof, facing South

There is an old oil radiator that I can move around and that I sometimes turn on at night.

Additional details:
Last week, I did not heat my apartment and it went down to 11.5 degrees Celsius when I came back from work at 6 PM.
The apartment below mine is not inhabitated, neither is the one across the hall from my entrance door.
I cannot install a wood furnace, a petrol heater or the like. All windows, Velux included, are double-paned glass.
My current heating strategy:
This is what I am currently doing. I turn on the kitchen window radiator to 13.5 degrees. I put the ones on the two other windows oon anti-freeze mode with the dial on 2 or 3. I do not use the bathroom's radiator because the heat from my shower is enough for comfort. At night, I sometimes turn on the oil heater in my bedroom, to the minimum setting. I wear a sweater, slippers, and put a drape over myself when I sit at the computer for a long time.
I'm being as frugal as I can be, but I am very cold and expected to pay 200+ euros at the end of the month for electricity only. I am willing to keep living like this, but if you have any advice or solution, it is more than welcome.
Here is a plan of my apartment (proportions are wrong):
Comment: Mini split  heat pumps are about the best bang for money when running.  Much better than the electric heaters you have now.
Comment: All your heat sources (new or old) are "toaster" heat. That is electric resistance. 100% efficient, but only 100% efficient, where heat pumps can be 300-500% efficient (more typically 300) on the same fuel. Heat pumps do have a high inital cost, but the much lower running cost soon pays off. Of course, insulation pays off even faster, if you have uninsulated stone walls...
Comment: I'd investigate if there's a way in the historic rules to add something outside but some meters away from the historic building, which would thus not alter the building exterior. Otherwise, get historic and start covering the walls inside with heavy tapestries for the winter.
Comment: Sitting on an XPS or EPS insulating foam panel, your body's heat feels amazingly warm. Sitting on such a chunk of insulating foam might make you considerably more comfortable at your computer. Even double pane windows are pretty useless for keeping heat inside, so you could use that same insulation material over windows at least 50% of the time.
Comment: @ChrisH, the trees outsides are massive sycamore trees. Deciduous, but they have very thick branches and they still cast a lot of shadow without leaves.
Comment: @crip659 Thanks for the quick answer. I forgot to add, unfortunately the building is classified as a historic building and I am not allowed to add anything outside :(
Comment: About the only other advice is to increase insulation and to seal all drafts around windows/doors to help keep the heat in.  Adding insulation the walls is a big job usually if the walls are already finish.
Comment: Dang, I was hoping there would be another way! There's actually a project to renovate the roof, and unfortunately it might mean that my ceiling window has to go (again, because classified building).
Comment: You say nothing about insulation or the construction of the roof.  Those are crucial details; insulating the roof is likely to be the most cost-effective way to improve things.
Comment: You could use electric resistance heated garments like electric socks or electric heating pad for the feet or an electric blanket. Some of these would be corded but others could be battery powered, e.g., an electric vest. If the floor is cold, then an insulating rug or pad under your feet while sitting will improve comfort. Wear gloves with open finger tips.
Comment: Aren't the stairwells labelled wrong in the diagram?
Comment: What is on the "first" floor? A separate apartment? A garage? Do you wear an insulating cap on your head in rooms at 13.5 C? Is 11.5 C just the temp when you arrive home and you raise the air temp of the space to 13.5 C (56 F) when you are home?
Comment: Would it be allowed to cut down one or a few trees to allow direct sunlight on the structure? I love trees and have always lived in excessively hot and sunny locales where the shade from trees was desirable, but your situation is the opposite.
Comment: How much do you pay per kWh? If your unit rates are similar to mine, you're using a similar amount of heat as I do for quite a big (but well insulated) house, suggesting your insulation is really in need of improvement. I don't keep mine very warm, but a significant few degrees warmer than yours
Comment: If the trees are deciduous, they'll soon be shading the building much less
Comment: Thank you all for the comments and apologies for the late replies. @ChrisH, I paid 41€ in October for 182 kWh, so that would be 0.225€/kWh (+16€ subscription cost).
Comment: @JimStewart, the first floor is an apartment that the landlord decided not to rent out. So it's basically an empty apartment, unheated. 11.5°C was the temperature of my apartment unheated (basically outside temp, now it has dropped). I used to let the heater set to 13.5°C, whether I'm home or not. Now I set it higher, to 15ish degrees.
Comment: OK, so you used about 6kWh each day.  Not all of this will have gone on heating, but most will Electricity used by the PC, lights etc. will end up as heat, so it's only really if you heat water electrically then it goes down the drain taking heat with it.  Most of my heating is gas, but my gas and electricity combined comes to about 8.5kWh/day for a big house at 16°C when I'm there alone, to 18°C when my daughter is there.  You're losing a lot of heat.
Comment: Even wrapped up warm, indoor temperatures consistently that low are cold enough to have health effects.  You need to find where insulation will be most useful.  What's the inside of the roof/lost ceiling like (pictures)?
Comment: If this is a young person who is dressed for warmth, I would think that 15 C would be OK.
Comment: How is the water heated? Is there hot water at the kitchen sink or just in the shower? Is the cooking stove gas or electric? Do you do much cooking?
Comment: Does this apartment have its own water heater or is there a common water heater for several units? Is the water heater a storage tank or is it a tankless? Gas fired or electric?
Comment: Is there a cooktop and separate oven or a stove with all in one unit? If the surface burners are electric, are they resistance or induction? Do you ever turn on the oven or the surface burners for extra space heating?
Comment: @JimStewart Just a gas cooktop and an eleectric oven. I bareley turn on the oven except for when I have people over.
Comment: To address other comments, I now set the heaters to around 14.5 degrees. It's not that cold when you move around. The water heater is electric and a bit too big for a single person (300L I think). There's hot water in the sink, the washing machine, the dishwasher, etc. I usually cook once a day but these past few weeks I've been out a lot.
Comment: What gas is used by the cooktop? Do you have piped in gas or do you use gas from a tank or bottle? Wow a 300 L (80 galUS) hot water tank!? In the US this would serve a large family! This is probably an electric resistance water heater so this would be a significant electric power load. To save on electricity you may have the temperture set point on this tank relatively low, possibly far lower than international guideline of 60 C (140 F). The purpose of keeping the water in a tank at 60 C is to prevent growth of certain harmful bacteria, specifically Legionella. Where is the tank located?
Comment: A 1-bedroom apartment should not need more than a 150 L hot water tank. In this day and age the hot water tank should be an electric heat pump type which uses about 1/3 of the electric energy of an electric resistance heater. However, heat pump WHs cost more, require more service, make some noise in operation, AND cool their surroundings! Where is this tank located? What temp do you have it set to? Is the hot water scalding? Moderately hot? Lukewarm? For showering how much cold water do you have to meter in?
Comment: @JimStewart Yeah, I gotta look into changing it. The thing is, when I'm not renting the studio, my parents rent it out to tourists and they may need a lot of hot water. It's a 2-bedroom apartment actually, and with 1 double bed, 2 simple beds and the convertible couch, you can fit 6 people easily. The tank is in the bathroom (cylinder on my plot). The water is quite hot, but not incredibly so. I'll try to tune it down a little bit.
Comment: I did not advise you to turn the set temp down on the WH. If you turn it down too low, you could allow Legionella bactera to grow in the storage tank and infect yourself or the renters. Don't change anything without checking with the owner of the apartment.
Comment: Better still don't take it upon yourself to change the setpoint of the water heater. You will be responsible if this goes wrong.
Comment: Okay, indeed good advice. I checked yesterday annd I think I can't even change the water heater without the appropriate tools to turn the dial.
Answer: Add insulation:
start adding heavy curtains to the windows on the north side of the building,
then insulate the ceiling of the top floor (under the roof), if you have enough height, consider a suspended ceiling otherweise just add insulation panels under the shingles from outside.
Consider double-glazing, at least the windows facing north.
Use heat-pump to heat instead of resistive heaters, it's 3 five more efficient than electric (your 8€/day will go to around 3€/day just for that). A 3-split system may be enough (also if you already have the AC, check if it can also do heat, as said is much more efficient than resistive).
Consider moving the PC in the bedroom, so you'll avoid to heat a room with no much use (or, better, move the bed at the second floor so you avoid heating the loft that is much more wasteful having 5 sides exposed instead of 4)
Comment: If you abandon the loft for the winter, you'll need to close it off somehow as warm air will convect up there. There may already be a door of course.  I stayed for a few days somewhere like that (usually only rented out in summer but it was winter), and we had to get creative with clips and weights to cover the top of the stairwell with a blanket.  That made a huge difference to keeping the lower floor warm
Comment: Hi, good ideas, thank you. All my windows are already double-glazed and I cannot install a heat pump (building limitations), but I did add heaevy curtains to close off the north-facing part of the house. I tried moving my desk upstairs, and closing off the lower bedroom. My plan is for th Velux to heat up the house during the day, and close it with a thick built-in curtain at night.


Unable to understand how list is built

Question: Can someone explain me why the code line below :
Returns <- eapply(Data,function(s) ROC(Ad(s), type="discrete"))

does return :

I guess that it's classed by value but quite not sure
Since Data is built as below :

Why isn't my list structured as excepted :
Returns :
  -> ACA.PA
  -> BNP.PA
  -> UG.PA

How would I Fix this in order to keep the same structure ?
Reproducible Example
stock_list <- c("ACA.PA","BNP.PA","UG.PA")
Data <- new.env(hash = FALSE)
getSymbols(stock_list,
           from = start_date,
           to = end_date,
           src = "yahoo",
           periodicity = "monthly",
           env=Data)
Returns <- lapply(Data,function(s) ROC(Ad(s), type="discrete"))

Comment: Can you try on `lapply`  According to `?eapply` `The user can request that all named objects are used (normally names that begin with a dot are not). The output is not sorted and no enclosing environments are searched.`
Comment: Also, `A named (unless USE.NAMES = FALSE) list. Note that the order of the components is arbitrary for hashed environments.`
Comment: @akrun `lapply` return the same thing, how would I sort it or keep my environment structure (`Data`) ?
Comment: I assume `Data` is a `list` and not an `env`?
Comment: @akrun `Data <- new.env()` its an env
Comment: Can you try `Data <- new.env(hash = FALSE)`
Comment: It is not hash sorted.  Can you show a small reproducible example for testing.
Comment: Suppose, you have the original objects in a string, you can use `mget(yourobjs, envir = Data)`
Answer: if we need the output in the same order, we can use mget with envir specified as 'Data'
Returns <- lapply(mget(stock_list, envir = Data),
        function(s) ROC(Ad(s), type="discrete"))

names(Returns)
#[1] "ACA.PA" "BNP.PA" "UG.PA"

According to ?eapply

order of the components is arbitrary for hashed environments.

and in ?new.env

env.profile returns a list with the following components: size the number of chains that can be stored in the hash table, nchains the number of non-empty chains in the table (as reported by HASHPRI), and counts an integer vector giving the length of each chain (zero for empty chains). This function is intended to assess the performance of hashed environments. When env is a non-hashed environment, NULL is returned.

Unable to understand how list is built


Launching multiple custom urls in the main thread

Question: I have 2 applications application1 & application2 with registered custom urls.I am unable launch the 2 applications sequentially as follows
<code>[[UIApplication sharedApplication]openURL:[NSURL URLWithString:@"abc://"]];
//where abc:// is the custom url of application1

[[UIApplication sharedApplication]openURL:[NSURL URLWithString:@"xyz://"]];
////where xyz:// is the custom url of application2
</code>
here the first application(ie custom url abc://) is successfully launched while the second application(ie the custom url xyz://) fails to launch even though the code runs through it in the debugger.
Any inputs/help is deeply appreciated....
Answer: It seems sort of logical that you cannot launch two apps at once (only one can be actively seen anyway), but I can see why this could be useful.
My suggestion for a workaround would be that if you have control over application1 you could have application1 launch application2 if needed. Or pass control back to your original application and have it launch application2 then.
Also, you should definitely test this on an actual device. The simulator does not fully implement the launch url scheme.
Comment: i knew about the workaround u suggested, but the problem is that i am not allowed to make the custom url call from the application1 that is called from the original application.


How to freeze the table headers without any plugins and show when scrolled vertically?

Question: I have used many plugins like freezeHeaders, stickytableHeaders, floatThead , nothing helped me.
In my project the header and footer are constant .It comes dynamic.Its a huge project. In my current jsp , i'll show the title and table which contains headers and dynamic data.
I need to have a freeze headers between the header and footer.
Can anyone give an exact idea to solve this problem.
Please.
Comment: Have fix height for tbody with overflow auto.
Comment: Possible duplicate of [Freezing/Fixing the Top Header Row of a table](http://stackoverflow.com/questions/15307135/freezing-fixing-the-top-header-row-of-a-table)
Answer: Please see the example below:

.fixed_headers {
  width: 750px;
  table-layout: fixed;
  border-collapse: collapse;
}
.fixed_headers th {
  text-decoration: underline;
}
.fixed_headers th,
.fixed_headers td {
  padding: 5px;
  text-align: left;
}
.fixed_headers td:nth-child(1),
.fixed_headers th:nth-child(1) {
  min-width: 200px;
}
.fixed_headers td:nth-child(2),
.fixed_headers th:nth-child(2) {
  min-width: 200px;
}
.fixed_headers td:nth-child(3),
.fixed_headers th:nth-child(3) {
  width: 350px;
}
.fixed_headers thead {
  background-color: #333;
  color: #FDFDFD;
}
.fixed_headers thead tr {
  display: block;
  position: relative;
}
.fixed_headers tbody {
  display: block;
  overflow: auto;
  width: 100%;
  height: 300px;
}
.fixed_headers tbody tr:nth-child(even) {
  background-color: #DDD;
}
.old_ie_wrapper {
  height: 300px;
  width: 750px;
  overflow-x: hidden;
  overflow-y: auto;
}
.old_ie_wrapper tbody {
  height: auto;
}

      Name
      Color
      Description

      Apple
      Red
      These are red.

      Pear
      Green
      These are green.

      Grape
      Purple / Green
      These are purple and green.

      Orange
      Orange
      These are orange.

      Banana
      Yellow
      These are yellow.

      Kiwi
      Green
      These are green.

      Plum
      Purple
      These are Purple

      Watermelon
      Red
      These are red.

      Tomato
      Red
      These are red.

      Cherry
      Red
      These are red.

      Cantelope
      Orange
      These are orange inside.

      Honeydew
      Green
      These are green inside.

      Papaya
      Green
      These are green.

      Raspberry
      Red
      These are red.

      Blueberry
      Blue
      These are blue.

      Mango
      Orange
      These are orange.

      Passion Fruit
      Green
      These are green.


Equality in matrix norm equation.

Question: I have proved that for a matrix $A \in M_{m \times n}$
$$\frac{1}{\sqrt n} \|A\|_{\infty} \leq \|A\|_2 \leq \sqrt m  \|A\|_{\infty}$$
But wanting to know example of nonzero matrix $A$ where equality occurs.
Will Identity matrix work as an example?
Comment: @LordSharktheUnknown can you give me an example in rectangular case
Comment: The zero matrix?
Comment: @Holo of course I want a nonzero example
Comment: what if you set $m=n=1$?  Then what can you conclude?
Answer: Suppose you want
$$\frac1{\sqrt{n}}\|A\|_\infty = \|A\|_2 = \sqrt{m}\|A\|_\infty$$
Then we have $$\|A\|_\infty=\sqrt{mn}\|A\|_\infty$$
 and since $\|A\|_\infty >0$ if $A \neq 0$, we have $\sqrt{mn}=1$, that is $m=n=1$.
When $m=n=1$, the equality holds.
Also, when $m \neq n$, then the equality doesn't hold if $A \ne 0$.

Equality in matrix norm equation.


How many Nexus Mods can Skyrim run before breaking?

Question: I wanted to know how many Nexus Mods I can install and run on Skyrim before the game can't handle anymore. I'm looking to install a lot of mods that fix bugs, graphics, NPCs and other general fixes for the game that make the game a much better experience.
At the moment I have around 30 mods installed and the game is running fine, but I don't know how far I can go with the number of mods until I break something.
Comment: Yes, but that asks about Steam Workshop mods. I don't want to sound stupid but I thought that the Steam Workshop mods might have a cap on how many you can download or what you can download, as I don't use Steam Workshop for modding any of my games, so I'm not sure if it would differ in comparison to Nexus Mods or not.
Comment: Other than having the Steam tag, which Skyrim on the PC is always on anyway, that question doesn't have anything about the Workshop to it at all.
Comment: @HazedCube except for the way the mods are added to the game, there's no difference between where you get them.
Answer: The absolute upper-limit is 253 total mods. This only counts certain types of mods, though; specifically, ones that add a .esm or .esp file so they can change actual data in-game (i.e. not mods that simply change models or textures). This also does include the expansions, and any such mods downloaded through Steamworks rather than Nexus.
The reason for the limit is that Skyrim (and other Bethsoft games) uses an internal code (the Form IDs) for everything added by a mod. The first two hex digits indicate where this thing came from, with 00 being the base game, 01 being official patches to the base game, and FF being reserved for items created by player interaction (custom potions, items dropped in-world, summoned NPC refIDs, etc). This leaves only 253 prefixes for other mods, before the game simply cannot load up items from the mod.
Note, of course, that any given collection of 253 mods is likely to be impossible to run together anyway for reasons of mod conflicts or of your computer simply being unable to handle them all. 253 is just the absolute theoretical upper limit.
Comment: If one were to have more mods than that, would it only load items from the first 253 in the load order or the last 253?  Or would it simply exit on startup?
Answer: Well, it depends on your PC specs and the mods you're installing, some break because of conflict, some break because your PC simply can't handle it anymore. You'll be fine as long as the mods are not conflicting.


Simple modal div in jQuery?

Question: I have tried almost all of the jQuery Modal plugins I can find on the net but they are all much to bulky for what I need.  I don't need all the fancy features, I want to be able to open a div and have the background of the page go transparent grey like the photo below and have my div be on top of it, that is all I need to do so I would like to write some jQuery to do this instead of using a bulky plugin.  Does anyone have any small code that can do this task?  Is the transparent background an image or just CSS?
Answer: This is what I use myself; it looks nice, the code is simple and easy to understand, and uses minimal CSS and jQuery.
Here is the code (And a fiddle to see it in action: http://jsfiddle.net/cadkJ/125/):
HTML

Bacon ipsum dolor sit amet

Magna adipisicing eu, pig ex pariatur non biltong nisi consequat do exercitation. Biltong exercitation consequat aute. Excepteur velit ribeye, et salami pariatur sed consequat enim ham. Tenderloin consequat et, in pastrami aute meatloaf beef spare ribs tri-tip beef ribs sed ut jerky strip steak. Fugiat turkey shank frankfurter pork loin pastrami.

<button id="modal-launcher">Launch Modal Window</button>

    <button id="modal-close">Close Modal Window</button>

CSS
#modal-background {
    display: none;
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: white;
    opacity: .50;
    -webkit-opacity: .5;
    -moz-opacity: .5;
    filter: alpha(opacity=50);
    z-index: 1000;
}

#modal-content {
    background-color: white;
    border-radius: 10px;
    -webkit-border-radius: 10px;
    -moz-border-radius: 10px;
    box-shadow: 0 0 20px 0 #222;
    -webkit-box-shadow: 0 0 20px 0 #222;
    -moz-box-shadow: 0 0 20px 0 #222;
    display: none;
    height: 240px;
    left: 50%;
    margin: -120px 0 0 -160px;
    padding: 10px;
    position: fixed;
    top: 50%;
    width: 320px;
    z-index: 1000;
}

#modal-background.active, #modal-content.active {
    display: block;
}

jQuery
$(function(){
    $("#modal-launcher, #modal-background, #modal-close").click(function() {
        $("#modal-content, #modal-background").toggleClass("active");
    });
});

Do you want to lock scrolling?
Add the following CSS rule:
body.active { position: fixed; overflow: hidden; }

Replace the jQuery function with: (body added to line 3)
$(function(){
    $("#modal-launcher, #modal-background, #modal-close").click(function() {
        $("body, #modal-content, #modal-background").toggleClass("active");
    });
});

Do you want to prevent click events on the background from closing the modal?
Replace the jQuery function with: (#modal-background removed from line 2)
$(function(){
    $("#modal-launcher, #modal-close").click(function() {
        $("#modal-content, #modal-background").toggleClass("active");
    });
});

Comment: Yeah, that's a good point @PeterNosko; to remove the background click behaviour, just change the second line of jQuery to `$("#modal-launcher, #modal-close").click(function() {`
Comment: And just a heads up if you want to lock scrolling on the body (not part of the questions but perhaps helpful): Add the following CSS rule `body.active { position: fixed; overflow: hidden; }`, and change line 3 of the jQuery to `$("body, #modal-content, #modal-background").toggleClass("active");`
Comment: The look is nice and simple. But I question it being modal since clicking in the background closes it. Modal to me means only the close button should close it.
Answer: EDIT: This is obviously outdated. So please refer to Andrew Odri post below.
I don't know how good you are in CSS and JavaScript, but your request shouldn't be that hard to do yourself.
body, html { margin:0; padding:0; }
#modalTabelGray
{
    position:absolute;
    width:100%;
    height:100%;
    background-color:#000000;
    filter:alpha(opacity=60);
    opacity:0.6;
    -moz-opacity:0.6;
    z-index:100;

    text-align:center;
    vertical-align:middle;
}

#modalDiv
{
    position:absolute;
    z-index:101;
}

I haven't tested the code, might not work, but you'll get the idea.
Comment: Actually I have only good experience with creating my own, they become just as lightweight as I want them, and I'm sure they don't conflict with other libraries I might use. But I do still agree with you, there are a lot of good plugins out on the internet, and things can get ugly when you create them yourself.
Comment: if this works, this is basicly what I needed help with is the css part
Comment: I haven't testet it, but as said, it shouldn't be that hard to make. The most important part, is that you don't nest the div in the div with opacity, because then the content will also become transparent. You can use a transparent PNG, instead if you like.
Comment: I think creating your own version could be a good idea. I will work for the first 2-3 tasks you want completed. But later on, you need it to be more complex. My experience tells me, that it will end up being more messy and end up being larger, than some of the other plugins out there. There are tons of them :-)
Comment: just add `top: 0px; left: 0px;` on the css and it should display as an overlay.
tested on IE 10.
Answer: I would NOT recommend jQuery UI - it's huge and overcomplex for that simple task. Here are some other plugins:

ThickBox
BlockUI
jqModal
Facebox
Comment: Yeah I will not use jqueryUI but I also want to stay away from other main ones liek you listed, they are "light weight" but not light weight enough for my needs
Comment: I will say the http://malsup.com/jquery/block/ I have not seen before and it is pretty nice!
Comment: I listed just some of the plugins that exists. Just google "jquery modal" and you will find lots of them. Some more complex than other :-)
Answer: SimpleModal does precisely what you want to do.
Answer: You can create a simple modal using pure HTML and css,no need of javascript and   jquery,which will indirectly reduce time and work.
html-->
    Open Modal

    X

Modal Box

This is a sample modal box that can be created using the powers of CSS3.

You could do a lot of things here like have a pop-up ad that shows when your    website loads, or create a login/register form for users.

      css-->

   .modalDialog {
position: fixed;
font-family: Arial, Helvetica, sans-serif;
top: 0;
right: 0;
bottom: 0;
left: 0;
background: rgba(0, 0, 0, 0.8);
z-index: 99999;
opacity:0;
-webkit-transition: opacity 400ms ease-in;
-moz-transition: opacity 400ms ease-in;
transition: opacity 400ms ease-in;
pointer-events: none;
 }
 .modalDialog:target {
 opacity:1;
pointer-events: auto;
}
.modalDialog > div {
width: 400px;
position: relative;
margin: 10% auto;
padding: 5px 20px 13px 20px;
border-radius: 10px;
background: #fff;
background: -moz-linear-gradient(#fff, #999);
background: -webkit-linear-gradient(#fff, #999);
background: -o-linear-gradient(#fff, #999);
}
.close {
background: #606061;
color: #FFFFFF;
line-height: 25px;
position: absolute;
right: -12px;
text-align: center;
top: -10px;
width: 24px;
text-decoration: none;
font-weight: bold;
-webkit-border-radius: 12px;
-moz-border-radius: 12px;
border-radius: 12px;
-moz-box-shadow: 1px 1px 3px #000;
-webkit-box-shadow: 1px 1px 3px #000;
box-shadow: 1px 1px 3px #000;
}
.close:hover {
background: #00d9ff;
}

visit this.
Answer: You can use jQuery UI which has a dialog plugin that supports modal .. http://jqueryui.com/demos/dialog/#modal
Alternatively you would create a div that spans the whole viewport in size, set its opacity to 50% (0.5) and also catch and stop all events to make it modal. Then display your div on top of it ..
Answer: I've been using the jQuery UI Dialog for this.
http://jqueryui.com/
Answer: To name another plugin for this task is nyromodal which I find easy to use but still offers a lot of setting options if you should find yourself in the need for that (later)

Simple modal div in jQuery?


Am I creating my raygeneration shader correctly

Question: Hi I want to create a ray generation shader which traces rays inside a box frustum given by an Orthographic projection matrix(XMMatrixOrthographicLH) I use the following ray generation shader code:
<code>struct RTConstants
{

    matrix invproj;
};

struct Simpleraypayload
{
    float3 outcol;
};
RWTexture2D<float4> outtex: register(u0);
RaytracingAccelerationStructure basicas:register(t0);
ConstantBuffer<RTConstants> rtconsts:register(b0);
[shader("raygeneration")]
void rgsmain()
{
Simpleraypayload payload;
payload.outcol=float3(0.0f,0.0f,0.0f);
RayDesc ray;

ray.TMin=0.001f;
ray.TMax=10.0f;
ray.Direction=float3(0.0f,0.0f,-1.0f);
    uint3 rayidx=DispatchRaysIndex();
    uint3 raydims=DispatchRaysDimensions();
    float2 clippointxy=rayidx.xy/float2(raydims.xy);
    clippointxy=(clippointxy*2.0f)-float2(1.0f,1.0f);
    float4 clippointnear=float4(clippointxy,0.0f,1.0f);
    clippointnear=mul(rtconsts.invproj,clippointnear);clippointnear=clippointnear/clippointnear.w;
    float4 clippointfar=float4(clippointxy,1.0f,1.0f);
    clippointfar=mul(rtconsts.invproj,clippointfar);clippointfar=clippointfar/clippointfar.w;
    ray.Origin=clippointnear.xyz;
    ray.Direction=normalize(clippointfar.xyz-clippointnear.xyz);
    TraceRay(basicas,RAY_FLAG_NONE,0xFF,0,0,0,ray,payload);
    //flipping the output.
    uint2 outindex=uint2(rayidx.x,raydims.y-rayidx.y);

    outtex[outindex]=float4(payload.outcol,1.0f);
}
</code>
here "invproj" is the inverse of the ortho projection matrix for which we are trying to shootrays for.Am I right in using this rgs shader code for tracing all possible rays inside the frustum represented by the ortho matrix whose inverse I am using here?I have tested it for ortho projection only though.
Answer: Yes the raygen shader used here is correct for shooting rays inside the frustum given by the projection matrix(whose inverse is used here).


How to extend SignalProducerType of ReactiveCocoa4

Question: I try extending SignalProducerType with SequenceType value. But I can't do. 'Type of expression is ambiguous without more context' error occurs in compiling.
protocol TranslatorType {
    typealias Source
    typealias Destination
    func translate(source: Source) -> Destination
}

extension SignalProducerType where Value: SequenceType {
    func translate<T: TranslatorType, U: SequenceType where T.Source == Value.Generator.Element, T.Destination == U.Generator.Element>(translator: T) -> ReactiveCocoa.SignalProducer {
        return lift { $0.map { seq in seq.map(translator.translate) } } # Type of expression is ambiguous without more context error
    }
}

How can I do that?
Answer: The map function of SequenceType returns an array, you can't map to a generic SequenceType. Change type U to an array, it can compile:
extension SignalProducerType where Value: SequenceType {
    func translate<T: TranslatorType, V where T.Source == Value.Generator.Element, T.Destination == V>(translator: T) -> ReactiveCocoa.SignalProducer<[V], Error> {
        return lift {  $0.map { seq in seq.map(translator.translate) } }
    }
}


Why is this Moebius equivalence true?

Question: I would like to know why the following is true:
$$\tau(n^2) = \sum_{d | n} \mu(n/d)(\tau(d))^2$$
I cannot derive it. It is on OEIS but I'd like to know how this was found.
$\tau(n)$ is the count of divisors function and $\mu(n)$ is the Moebius function.
Answer: Outline: Both sides are multiplicative. So it is enough to check whether the result is correct  for $n$ of the shape $p^m$, where $p$ is prime. That is a straightforward computation. Note that $\tau(p^t)=t+1$.
Added: Let $n=p^m$. Then $\tau(n)=2m+1$.
Now we look at the right-hand side. The only $d$ for which $\mu(n/d)\ne 0$ are $d=p^m$ and $d=p^{m-1}$.
For $d=p^m$, we have $\mu(n/d)=\mu(1)=1$ and $\tau(d)=m+1$. So $\mu(n/d)(\tau(d))^2=(m+1)^2$.
For $d=p^{m-1}$, we have $\mu(n/d)=-1$ and $\tau(d)=m$. So $\mu(n/d)(\tau(d))^2=-m^2$.
Finally, $(m+1)^2-m^2=2m+1$.

Why is this Moebius equivalence true?


Enabling a submit button after submitting

Question: I am opening up a new page when the user clicks submit.  It would be a common occurrence for the user to come back to the original page to select something else from the drop down and need to "submit" again.  Now the problem is that my js function disables the submit button, and the user would have to reload the page.  The js is a standard thing, so unfortunately, I cant change that, but I was wondering if there was a way to reenable it in HTML or in a separate script, here is my relevant code:
<form name="verification_form" action="CreateVerification"   target="_blank" onSubmit="return submitForm(this, 0, this.length-2, SUBMIT)" method="post">

        Stuff<input type="HIDDEN">

                <select name="stuff" id="stuff" class="R">
                    <option value=" ">   </option>
                    <option value="<% =stuff %>"> <% =stuff %>  </option>
                </select>

            <input type="submit" name="SUBMIT" value="SUBMIT">

Any help would be appreciated, and let me know if there are any questions.
Comment: Can you change the onSubmit handler? If so, you could 1) have an ajax call do the actual form submission, 2) re-enable the submit button in the ajax call's complete handler and 3) return false from the replacement onSubmit handler so the default submit behavior did not send the form a second time.
Answer: You can remove the disabled option using jquery like this:
$("input[type=submit]").removeAttr("disabled");

The issue would be when exactly in your code do you want to enable the submit button. You will probably want to wire it to the onchange event on your dropdown list.
$('#dropdownlist').change(function(){
        //Validate your form here maybe:

        if(validated) $("input[type=submit]").removeAttr("disabled");
  });

Comment: If you always want it to be enabled after the page loads (which may not make sense depending on your implementation) you can put it in the document.ready funtion: `$(document).ready(function(){ $("input[type=submit]").removeAttr("disabled");});`
Comment: Might do this if I cant find a way to do it without the user changing the drop down, thanks.
Answer: You could put a button somewhere (in the original page or in the popup) that says "select another item" and runs some javascript to re-enable the button with :
var submitButton = ... (find the submit button)
submitButton.enabled=true

Comment: Thanks for the help, but I wanted to try and avoid putting anything else on the page.
Comment: You can add this script in the popup, then. Use the "opener" variable as a root : opener.getElementById(...) then re-enable it.
Answer: Check if your submit button is disabled. Enable it in that case.
With jQuery this will be the approach:
if($("#submit-button").is(":disabled")) {
    $("#submit-button").removeAttr("disabled");
}

Hope it helped
Comment: Not sure what this is doing, I ran it.....and no changes.  I was experimenting with this jquery script, but I cant get it to work either:   *   $('#submit-button').click(function(){
    $('#submit-button').attr('enabled','true');
  });*
Comment: Oh god, I was thinking that you deleted the button... javascript code changes. Forget last answer, I'm updating it!!


How to unlist glm summaries into date frames

Question: Let's consider list of summaries:
set.seed(42)
bin_var <- sample(0:1, 125, T)
indep_1 <- rnorm(125)
indep_2 <- rexp(125)
indep_3 <- runif(125)

summary_list <- list(summary(glm(bin_var~indep_1)),
                     summary(glm(bin_var~indep_2)),
                     summary(glm(bin_var~indep_3)))

What I want to end up with is identical list containing those summaries but each in data frame format.
To convert summary.glm into data frame we just need to use:
summary_list[[1]]$coefficients

So my idea was to use:
lapply(summary_list,"$", "coefficients")

But it gives only NULLs. Do you know how it can be done ?
Answer: Another way would be the following:
do.call('rbind',
        lapply(seq_len(length(summary_list)),
               function(i) coefficients(summary_list[[i]])))

which yields:
# Estimate Std. Error    t value     Pr(>|t|)
# (Intercept)  0.56664011 0.04473468 12.6666853 4.779611e-24
# indep_1     -0.01879638 0.04246236 -0.4426597 6.587894e-01
# (Intercept)  0.58719761 0.06862352  8.5567986 3.891567e-14
# indep_2     -0.01719474 0.04668204 -0.3683373 7.132549e-01
# (Intercept)  0.39294331 0.09647586  4.0729705 8.253436e-05
# indep_3      0.34647724 0.17000447  2.0380478 4.368955e-02

Answer: You can use an anonymous function :
result <- lapply(summary_list,function(x) x$coefficients)

Or using [[ is similar to $.
result <- lapply(summary_list, `[[`, 'coefficients')

If you want everything on one dataframe use do.call(rbind, result).


Can't save textarea to file using php?

Question: I have issue saving textarea to file. I used POST method to send the form to the other page then, in the next page I can't include the textarea content with the file Im not sure what is the problem.
Is there any idea about what is the problem?
Here are the two pages:
page1:
<!DOCTYPE HTML>

    <title>Save</title>

    <form action="page2.php" method="post">
    name:
    <input type="text" name="name">

    file extension:
    <select name="ext" id="ext">
        <option value=".txt">.txt</option>
        <option value=".doc">.doc</option>
    </select>
    <textarea name="txt1" id="txt1" cols="15" rows="10"></textarea>

          <input type="submit" name="submit"  id="submit" value="Save">
          </form>

-page2.php
$txt1 = $_POST['txt1']; //textarea
$name = $_POST['name'];
$ext = $_POST['ext'];  //choose from multiple extensions
if ($ext == '.txt')    // In case if I want to add more than extension.
{
    $file = "'. $name$ext.'" ;
    $output = "$txt1";
    file_put_contents($file, $output);
    $text = file_get_contents($file);

    header("Content-Description: File Transfer");
    header("Content-Type: application/text/plain");
    header("Content-Disposition: attachment; filename=".basename($file));
    ob_clean();
    flush();
    readfile($file);
    exit;
}

Comment: Please provide your html part ()
Comment: `print_r($_POST)` looks correctly to you?
Comment: Not that it actually matters for the logic, but you are reading the file twice, once with `file_get_contents()` and once with `readfile()`.
Comment: I added the html form I hope it is clear now.
Answer: $file = "'. $name$ext.'";
should be:
$file = $name.$ext;
At least that's what I had to change to get it to work on my server.
Comment: Thanks.. I can download the file, but It shows no content inside.
Comment: any suggestion, how can I get the content of the textarea to be inside the file?
Answer: Without seeing your html I can't be sure of what the problem is.  But its been my experience that when your having trouble accessing POST vars on the server side that it's probably a simple spelling error.  Make sure the name attributes in your form line up with your POST vars.  Just my two cents.
Answer: I have no idea what did you mean with your code, so, I'd just rewrite it
To save a file on the server you need these 2 lines
$name = basename($_POST['name']).'.txt';
file_put_contents($name, $_POST['txt1']);

Answer: You need to add an id to the form, then add the form Id to the textarea element. For example:
<form action="page2.php" method="post" id="myform">
    <textarea name="txt1" id="txt1" cols="15" rows="10" form="myform"></textarea>

Answer: Try using the wrap element in your textarea
<textarea name="txt1" id="txt1" cols="15" rows="10"></textarea>

add wrap
<textarea name="txt1" id="txt1" cols="15" rows="10" wrap="virtual"></textarea>

you can also use wrap: off, hard, soft and physical
In your database make sure the field txt1 is defined properly (i.e type text).

Can't save textarea to file using php?


Use variable as data in apexcharts

Question: I'm trying to display a chart in apexcharts, and use a variable as the data. When I do this, nothing is displayed. See the following:
var message = '[1,4]'
var options = {
  chart: {
    type: 'line',
    sparkline: {
      enabled: true,
    }
  },
  series: [{
    data: message,
  }],
}

var chart = new ApexCharts(document.querySelector("#chart"), options);
chart.render();

Using the variable message as data doesn't work. When I switch the line:
data: message,

to
data: [1,4]

it displays correctly. However, I must use a variable. How do I do this?
Answer: You declared message variable as STRING, It is expecting an ARRAY
Please change
var message = '[1,4]'

to
var message = [1,4];

Comment: Or `JSON.parse` the string

Use variable as data in apexcharts


Getting a bitmap from gallery using Delphi via JNI, fails with Delphi XE7, works with Delphi XE6

Question: I'm getting a bitmap using Delphi XE7 from android gallery using jni. Same code, worked using Delphi XE6:
<code>unit home;

interface

uses
  FMX.Platform.Android, Androidapi.Helpers, Androidapi.JNI.App, Androidapi.JNI.GraphicsContentViewText, Androidapi.JNIBridge,
  FMX.Helpers.Android, Androidapi.JNI.Net, Androidapi.JNI.Provider, Androidapi.JNI.Media, Androidapi.JNI.JavaTypes,
  System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, System.Messaging,
  FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls,
  FMX.Objects, FMX.Surfaces, Data.DB, MemDS, DBAccess, MyAccess, Strutils,
  FMX.Layouts, FMX.Memo;

type
  TForm1 = class(TForm)
    ToolBar1: TToolBar;
    SpeedButton1: TSpeedButton;
    Label1: TLabel;
    Image1: TImage;
    procedure SpeedButton1Click(Sender: TObject);
  private
    { Private declarations }
    const ScanRequestCode = 0;
    var FMessageSubscriptionID: Integer;
    procedure HandleActivityMessage(const Sender: TObject; const M: TMessage);
    function OnActivityResult(RequestCode, ResultCode: Integer; Data: JIntent): Boolean;
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.fmx}
{$R *.NmXhdpiPh.fmx ANDROID}

procedure TForm1.SpeedButton1Click(Sender: TObject);
var
  Intent: JIntent;
begin
  FMessageSubscriptionID := TMessageManager.DefaultManager.SubscribeToMessage(TMessageResultNotification,
    HandleActivityMessage);
  Intent := TJIntent.Create;
  Intent.setAction(TJIntent.JavaClass.ACTION_GET_CONTENT);
  Intent.setType(StringToJSTring('image/*'));
  SharedActivity.startActivityForResult(Intent,0);
end;

procedure TForm1.HandleActivityMessage(const Sender: TObject; const M: TMessage);
begin
  if M is TMessageResultNotification then
    OnActivityResult(TMessageResultNotification(M).RequestCode, TMessageResultNotification(M).ResultCode,
      TMessageResultNotification(M).Value);
end;

function TForm1.OnActivityResult(RequestCode, ResultCode: Integer; Data: JIntent): Boolean;
var
  uri: Jnet_Uri;
  bitmap: JBitmap;
  surface: TBitmapSurface;
begin

  TMessageManager.DefaultManager.Unsubscribe(TMessageResultNotification, FMessageSubscriptionID);
  FMessageSubscriptionID := 0;

  if Assigned(Data) then
    begin
    try
      uri:=Data.getData;
      bitmap := TJImages_Media.JavaClass.getBitmap(SharedActivity.getContentResolver, uri);
      surface := TBitmapsurface.Create;
      JBitMapToSurface(bitmap,surface);
      // Fails here in Delphi XE7
      //Image1.Bitmap.Assign(surface);
    finally
        surface.Free;
        Result := true;
    end;

    end
    else Result := false;

end;

end.
</code>
Code fails in Image1.Bitmap.Assign(surface), I get a Fragmentation class error.
What's changed in Delphi XE7 to cause this error?
Comment: What is the exact error message text?
Comment: TBitmapsurface should be created before the try .. finally block
Comment: Finally and Free call not needed with ARC
Comment: I get a black screen, even in debug mode. One time, raised: "Project ....apk raised exception class segment fault (11)". With Delphi XE6, never fails.
Answer: Try:
TThread.Syncronize( nil,
  procedure
  begin
    Image1.Bitmap.Assign( surface );
  end
);
Comment: It works on tablets, like samsung galaxy tab S, and fails on phones, like Samsung S4. But if the application is compiled with Delphi XE6, works on all devices. Compiled with XE7 or XE8, fails.


C# dotnetcore Regex Hangs When Given Long, Unbroken String

Question: I have a regex that is hanging when it tries to match against a long, unbroken string. Here is a sample console app:
using System;
using System.Diagnostics;
using System.Text.RegularExpressions;

public class Example
{
    public static void Main()
    {
        Stopwatch sw;
        string pattern = @"(?:(?:https?|ftps?):\/\/)?(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]+-?)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]+-?)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?";
        string input = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";

        Console.WriteLine("Press any key to match regex.");
        Console.ReadKey();
        Console.WriteLine("Starting regex...");

        sw = Stopwatch.StartNew();
        Match m = Regex.Match(input, pattern, RegexOptions.IgnoreCase | RegexOptions.Multiline);
        sw.Stop();

        Console.WriteLine($"Regex completed in {sw.Elapsed}. Press any key to exit.");
        Console.ReadKey();
    }
}

The Regex is meant to find URLs in user-generated comments. When a normal comment is provided, it processes in no time at all. A 100-word lorem ipsum it processes in about 36ms. As soon as a long, unbroken string is introduced, the regex hangs and, as far as I can tell, never finishes processing. The string does not need to have the same characters repeated.
Any help or insight would be appreciated.
Comment: That sounds very much like your regex pattern is suffering from catastrophic backtracking. Also, your regex pattern is so long, complicated and essentially unreadable, i hope no one else will have to maintain it later ;-)
Comment: I feel with you. I refuse to pick that regex apart, i am not enough of a masochist to do that voluntarily. :-(  I would suggest instead of using such a complex regex, try to develop several different regex patterns that each match only a certain kind/style of URL. If you got those regex(es) working, you might think of combining them into one regex, using an alternation. But personally, i would prefer to keep regex simple, readable, maintainable, even if it would mean that i would have to deal with more than just a single regex...
Comment: Things like `(?:[a-z\u00a1-\uffff0-9]+-?)*` kill the performance. Search for quantified groups with one obligatory and other optional patterns inside. Replace so that each subsequent pattern could not match the same char/type of chars.
Comment: Besides long regex the `RegexOptions.IgnoreCase` is also causing the problem. Without ignore case flag it will proceed normally.
Comment: @MikeKaskun, yeah, alright. Now, replace the given input sample string with `"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"`. What now?
Comment: Yea, the guy needs to fix his regex :D
Comment: @elgonzo Yes, I didn't get to choose the Regex. If I can't figure out how to get it to work, I may have evidence to use a simpler one.
Comment: So probably too many optional clauses, that's the working theory. I'll try tweaking it.
Answer: The main problem with your regex is that there are optional patterns alongside obligatory one pattern inside a * / + quantified group, see (?:[a-z\u00a1-\uffff0-9]+-?)*. This may lead (with long non-matching strings) to the the behavior when the regex engine starts trying all possible routes to match a string, and there may appear too many of them, so many that the system appears to freeze: a catastrophic backtracking.
Thus, if you plan to use your simplified solution you should avoid the similar patterns, use
(?:(?:https?|ftp)://)(?:-\.)?[^\s/?.#-]+(?:\.[^\s/?.#-]+)*(?:/\S*)?

where (?:[^\s/?\.#-]+\.?)+ is unrolled as [^\s/?.#-]+(?:\.[^\s/?.#-]+)*. While it is longer, the engine fails much quicker than when the optional pattern is inside the quantified group.
If you want to fix the original pattern, use
string pattern = @"(?:(?:http|ftp)s?://)?(?:\S+(?::\S*)?@)?(?:(?!1(?:0|27)(?:\.\d{1,3}){3})(?!1(?:69\.254|92\.168|72\.(?:1[6-9]|2\d|3[0-1]))(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:[a-z\u00a1-\uffff0-9]+(?:-[a-z\u00a1-\uffff0-9]+)*)(?:\.[a-z\u00a1-\uffff0-9]+(?:-[a-z\u00a1-\uffff0-9]+)*)*(?:\.[a-z\u00a1-\uffff]{2,}))(?::\d{2,5})?(?:/\S*)?";

Check how this regex matches and how (?:[a-z\u00a1-\uffff0-9]+-?)* is unrolled as [a-z\u00a1-\uffff0-9]+(?:-[a-z\u00a1-\uffff0-9]+)* to match patterns so that each subsequent pattern could not match the same chars. I also merged some negative lookaheads with common "suffixes". Note that (?:\S+(?::\S*)?@)? is left untouched as it may need to match any :s up to the last : before the rest of matching patterns.
Comment: Thank you for the additional information. I ran your regex's in my sample program and they worked beautifully. While the answer I posted works as well, yours are much more performant and allows me to use the better matching regex.


MySQL selecting specific entries from joined table

Question: I have a table with users' subscriptions to a specific service, billed monthly.
There is also a table of 'suspensions' - with 'from' and 'to' dates to store information about user's temporary suspension of his subscription.
There are three possible cases:

both 'from' and 'to' dates are in the past - the user had its subscription suspended for a period in the past, but now the subscription is active again
'from' is in the past, but 'to' is in the future or is NULL - the service is suspended at the moment (until 'to' date or undefinitely)
'from' and 'to' are in the future (or 'from' is in the future and 'to' is NULL) - the user requested a future subscription suspension/cancellation, but at the moment the service is still active

There may be multiple entries in 'suspensions' for a given subscription, some may be already done (in the past), some 'in progress'.
Now I need to select active subscriptions.
I tried to do someting like:
SELECT * FROM service
LEFT JOIN suspensions ON service.id = suspensions.service_id
WHERE
  suspensions.id IS NULL
OR
  ( suspension_from < CURDATE() AND suspension_to < CURDATE() )
OR ( suspenstion_from > CURDATE() AND ( suspension_to > CURDATE() OR suspension_to IS NULL)) )
GROUP BY
   service.customer_id

and that works if there's only one entry in 'suspensions' table for a given service.
But if a customer has multiple suspension entries with different outcomes as to present moment, for example from 01-01-2021 to 31-12-2021 and 01-09-2023 to 31-08-2024 then the WHERE clause treats the first one as "active service" (suspension in the past), the second one as "inactive at the moment" (and omits that one as expected) and in the result I have that service as active (because of the first entry), while in fact it is inactive.
How to do this? Somehow count (or concat) "active" results and "inactive" results, group by customer_id and afterwards filter only those, which have 0 inactive results?
Comment: I would flip the logic around and filter suspensions to list inactive subscriptions only and then use the anti-join (... left join ... where ... is null) to get the ones that are active. Determining the inactive subscription is easier as if you find any rows in the suspensions table that make  a subscription inactive now, then it cannot be in the active list.
Comment: How about the case where there is no entry in the table suspensions for a certain service_id? Is that possible?  (I already see the where suspension_id is null part....). So yes
Comment: If there's no entry in suspensions, then the service is active (was never suspended)
Comment: Yeah, writng a question on a forum somehow relaxes my brain and I find the answer :) I added to the select: SUM(IF ( suspension_from < CURDATE() AND suspension_to < CURDATE(),1,0)) AS past, SUM(IF (suspension_from < CURDATE() AND (suspension_to > CURDATE() OR suspension_to IS NULL),1,0)) AS present, SUM(IF ( suspension_from > CURDATE(),1,0)) AS future.
And now I can make an outer SELECT filtering entries with 'present > 0'
Comment: Your `GROUP BY service.customer_id` makes no sense and produces logically incorrect query (and output). It results in only one random non-suspended service returned for each separate customer - or produces an error if ONLY_FULL_GROUP_BY mode is set.
Answer: SELECT *
FROM service
LEFT JOIN suspensions ON service.id = suspensions.service_id
WHERE suspensions.service_id IS NULL
   OR CURRENT_DATE NOT BETWEEN suspension_from AND COALESCE(suspension_to, CURRENT_DATE)
-- GROUP BY service.customer_id
-- maybe, ORDER BY service.customer_id ?


What can I do to help orienting myself in Minecraft Alpha?

Question: The current cave I'm working on is becoming unwieldy and disorienting. It's becoming harder and harder for me to keep bearings of where I am and what is the fastest way to my shelter. I'm looking for a cost effective way to fix this.
This is mainly due to my policy of digging through all earth and gravel in mines. It may be an excellent way to find coal and iron veins (not to forget openings to further areas) at zero cost, but it makes areas hard to navigate fast.
So far the only idea I have is to get going with signs:
<code>┌───────────────┐ ┌───────────────┐ ┌───────────────┐
│     CAVE 1    │ │   SHELTER 1   │ │ SAFETY  FIRST │
│    DEPTH 15   │ │               │ │  Be advised:  │
│ <== Shelter 1 │ │  Cave 1 down  │ │ Sea above the │
│  Workshop ==> │ │ mind the lava │ │     cave      │
└───────────────┘ └───────────────┘ └───────────────┘
</code>
I love this idea - which is why signs are quite costly to make (~1½ log each):
I could use a compass, but that's not very good when you are in a hurry. Besides, the cave extends below the spawn point. Also, I still have no Redstone to work with.
I could also make additional ways up, but this costs even more between torches and doors (to keep the ground level mob outside) and opens flooding risks (see sign 3).
What is, then, a good, cost effective way to help orientation in Minecraft caves?

Here's, to give you an idea of my progress, my full inventory as of a few game days ago:

In the background, Shelter 1. :)
Comment: @fredley I like clearing out all gravel and dirt, as it tends to unearth ores cheaply.
Comment: Nice Signs! You can get 8 signs from 13 logs, making each sign worth 1.625 logs.
Comment: Hence why I wrote ~1½, @alex :)
Comment: Why all the gravel?!
Comment: Fair enough. I usually mine out dirt but unless I can get underneath it I don't bother with gravel, I just find it really annoying to mine...
Comment: @fredley Just torch-mine it.
Comment: @fail Yeh, I do if I can, but my mining technique is to go straight down to bedrock and strip mine from there, so removing gravel is not so simple (and unnecessary in strip mining).
Comment: @fredley uh... bedrock? Gravel bubbles are rarely larger than 6 in height.
Comment: @fail The floor of my mine is on the highest level that bedrock can appear, so digging underneath gravel to lay torches is more difficult.
Answer: Place redstone torches on north walls. Redstone is quite easy to find deep underground and not required for much else.
Punch the ground directly beneath you. The break pattern is always the same relative to north.
Cheaper than torches, inlay the right-hand side of the floor with a dirt block every three squares. Build wide main corridors which you can follow back when you find one.
Grow a tree farm. Use the wood to make plenty of signs.
Design each area with its own character, so you can recognise them. Identical corridors are a good way to get lost. Place occasional markers, such as sand or wood.
Dig arrows into the wall pointing toward the nearest familiar spot. You can fill the arrow with dirt for extra visibility.
Create staircases upward occasionally. At the top, use excess stone to build a hut with a door and an observation tower. Use this to travel back to your shelter by aboveground when completely lost. Style your observation towers differently to use them as landmarks and build cobblestone roads between them.
Comment: To find North, look for the L on Cobblestone, furnace tops or Mossy Cobblestone textures. This only works with the default graphics pack or ones that specifically retain these features.
Comment: That redstone idea novel, but more expensive than say putting 2 regular torches side by side on North walls.
Answer: One thing I do is only put torches on the right hand side when exploring.  Then to find my way back I keep the torches on my left.  If a cave is big enough to need more than one torch I put the extra ones on the floor.
I also occasionally replace stone with cobblestones if I'm at a place where the correct way back is difficult to spot.
Comment: I do this too, although I use the cobble stone to tell me that the cave leads to a dead end.
Answer: I find that most cave offshoots have very little use after a single visit so I tend to wall them off with cobblestones after I explore an offshoot to it's maximum potential. This way I can easily tell where I've been and it makes going up and down from my base to my current dig site in the caves much less of a hassle.
I used to clear caves of torches before I walled them off, but then I realized that it's easier to tell if I've already been in a cave if I accidentally dig into it from another direction if I leave the torches.
Comment: Oh that is perfect! No more running around in underground circles for me.
Answer: A cheaper way than the signs is to make paintings, these are 9sticks(0.5625 wood) and 1 wool. Put then up on the way you should take to get back. Use signs or torches if you need directions when you're not on the 'main path'.
Answer: What I'd suggest is to head over to minecraft WIKI and get yourself a mapper (makes a map of the world in JPG or PNG i.e.). Use it to keep track of where you might be. This is best for close-to-surface and linear digging.
I tend to have one entrance, and then mine in a linear way, spiraling down. This is awesome, since you can't get lost. Minecart rails with a powered cart to transport rock/stone/minerals up when my inventory is full. (System found here

).
If you go up-down from ground level, build a 3-8block high tower and place some torches. A mapper will make it easy to find.
So basicly, my way is to have one above-ground entrance and use a compass or mapper to find my way between.
Comment: The mapper is kinda akin to cheating :/
Comment: Humans don't make maps when they explore caves in the real world? ;-) (hint - they do!)
Comment: I found that to be cheating too. so i started hand drawing maps with symbols akin to how middle earth is draw in the lord of the rings maps.  I was thinking about using http://autorealm.sourceforge.net/show.php but it was overkill.
Answer: Great ideas here, I thought I'd add a couple of my own.

Color coded routes: after finding a monster spawner, I mined all the mossy stone and dropped one at each intersection on my way back to the main mine shaft. That's the Green Tunnel, and I know it leads to the monster spawner (& likely a chest full of less valuable stone that I might still want someday).
A torch on top of a cobblestone/sand/dirt block (provided you don't use that in non-marker situations) is also distinctive.
2 torches to either side of a tunnel entrance
plant a cactus/sugar cane (they grow just dandy underground)

The idea is just that you can see whatever the marker is from the previous marker, if it's a confusing cavern.
Answer: Once I have found something, like a monster spawner, I write down the co-ordinates then go back to my base. From there, I dig a tunnel directly to the place I want to be.
Comment: This wouldn't work due to it being Minecraft Alpha.


Cluttered map on ME 2

Question: My current Mass Effect Galaxy looks like the following:

The maps in ME1 and 3 were beter IMO
Is there a way to remove all the labels and clutter either in-game or through an INI file or some third party tool?
Answer: The easiest way to clean up your galaxy map in Mass Effect 2 with all of the downloadable content installed (as you clearly have above) would be to quickly go and scan all of the planets marked with minerals on them - these are adding up the bulk of the excess on your screenshot and won't take any time at all to clear (just planet scanning).
In the screenshot above, these are marked as the following;

Eezo Rich Planet
Iridium Rich Planet
Palladium Rich Planet
Platinum Rich Planet

I do not believe there is any other method of 'cleaning up' the galaxy map other than actually completing each thing listed on the map.
Comment: I'm not sure, I always scan them to 'depleted' - shouldn't take too long to reach that state anyway

Cluttered map on ME 2


What is the significance of the blinking white health bars?

Question: When I attack an enemy, their health bar has a blinking white portion when I aim at them.

At first I thought this indicated the possible damage from an attack, but as you can see from this screenshot, a 3-4 dmg grenade is highlighting slightly over 6 bars of the enemy's health, and I can attest that it only did 3 damage to the enemy in question.
What do these blinking white health bars mean?
Answer: This is the maximum damage of the attack, minus the armour of the enemy. I am pretty sure no other damage sources are taken into consideration (e.g. a tank that is guaranteed to explode).
This mechanic is somewhat bugged. You will notice that in certain scenarios the blinking does not stop, even if an other target is chosen, or if an other attack is done first. What you are seeing is likely the potential damage for a different attack.


I'm confused by a simple regex: I need to match something like [Test] but not Test

Question: How would I go about writing a regex to match the first example, but not the second?
Thank you --
Comment: `\[Test\]` should do it...?
Comment: basic knowledge about regular expressions
Answer: Try
\[Test\]

You need to escape the [ and ] as they indicate range start/end.
Comment: It's fun, racing for the points :-)
Answer: [] are special characters for a regex, used for defining a character class, therefore escape them with backslashes.
\[Test\]

If you use [Test], it will match a single character which is either T, e, s or t.


Accidentally Touching One Lead Of A Multimeter While Other Is In Electrical Outlet

Question: If I have a multimeter, and I put one lead in the hot slot of an electrical outlet, will accidentally touching the other lead complete a circuit and electrocute me?
Likewise, if instead I put one lead in the neutral slot of an electrical outlet, will accidentally touching the other lead complete a circuit and electrocute me?
Answer: If the multimeter is set to read voltage, it will have a very high-resistance, so if everything is working correctly touching the other lead will not shock you.
If it's set to read current, it will have almost 0-resistance, so touching the other lead would be equivalent to touching the bare wire.  Thus, having the multimeter plugged into the hot-slot and touching the other lead will shock you (but, having it plugged into the neutral won't)
Comment: Only if the outlet is actually wired correctly. The **much** safer approach is to use the leads as designed and not touch the metal on either one; and don't leave one plugged into something when you are not actually testing it.
Comment: Then it sounds like putting the first lead into neutral is slightly safer.
Answer: If you have one lead in hot, yes, touching the other lead would complete the circuit and shock you.
If everything is wired correctly, you would not be shocked in the neutral scenario, however swapping hot/neutral is a pretty common error, so it is not a given that you would want to assume is correct.
Comment: How much of a shock would depend on what mode the meter is in. If it has a high current ammeter mode, it's going to to hurt... or worse. In AC voltage mode I believe the internal resistance is quite high and there may not be much of a shock. I'm pleased to say I never tested this theory, neither should anyone else unless they really know what they are doing. Just sayin' for the sake of discussion.
Answer: No. It wouldn't electrocute you unless you were touching ground. I found this out when I was stationed in Taiwan years ago and some locals installed ceiling fans for us. I kept waiting for them to tell me when to turn off the breaker, but they never did. When they came down out of the attic I asked them how they didn't get electrocuted touching hot wires. They told me that they didn't because they were not in contact with ground. But I've never tested this myself: still don't trust touching a hot wire. Better safe than sorry.


How to check the status of a storyboard?

Question: How would I check the status of a storyboard?
Example:
if (storyboard.Completed += true) // ???
{
}

(This code does not work, for obvious reasons.)
Comment: Back-ticks for inline code; New paragraph and 4-space indent for code blocks (select code block and press the "{}" button in the editor). Happy SO'ing.
Comment: Thanks! I always wondered why the code editor hated me...
Comment: just wanted to check in to see if the below answers your question.
Answer: Just hook the Completed event and when your code runs in there, the storyboard will have been completed. See: http://msdn.microsoft.com/en-us/library/system.windows.media.animation.timeline.completed(VS.95).aspx#Y565
Comment: How would I use this? (for instance,                 storyboard.Completed += Completed;)
Comment: That's right. Check out the sample on http://samples.msdn.microsoft.com/Silverlight/SampleBrowser/index.htm#/?sref=change_targetname_2 (click the "View Sample Source Code" button and then the C# button that comes up on that page at the top).
Answer: how about creating a boolean variable (e.g. IsCompleted) and set it to true in the Completed callback?
Answer: if(storyboard.GetCurrentState() == ClockState.Active)
{
    // do something
}

Comment: Code-only answers are generally frowned upon on this site. Could you please edit your answer to include some comments or explanation of your code? Explanations should answer questions like: What does it do? How does it do it? Where does it go? How does it solve OP's problem? See: [How to anwser](https://stackoverflow.com/help/how-to-answer). Thanks!
Answer: This doesn't work.

            Storyboard storyBoardPulse = this.FindResource("StoryboardMainIconPulse") as Storyboard;
            Storyboard.SetTarget(storyBoardPulse, this.imageIcon);

            if (storyBoardPulse.GetCurrentState() != ClockState.Active)
            {
                storyBoardPulse.Begin();
            }

gets back this error:

System.InvalidOperationException was unhandled by user code
HResult=-2146233079
Message=Impossible to execute the action. the Storyboard specify not
  applied to this object for interactive control.

Ao I make a very bloody workaround:

private Boolean pulseOn;

private void operationsOfMaintenance_OperationExpired(Boolean state)
        {
            Storyboard storyBoardPulse = this.FindResource("StoryboardMainIconPulse") as Storyboard;
            Storyboard.SetTarget(storyBoardPulse, this.imageIcon);

            if (!state)
            {
                storyBoardPulse.Stop();
                storyBoardPulse.Remove();
                pulseOn = false;
            }
            else
            {
                if(!pulseOn)storyBoardPulse.Begin();
                pulseOn = true;
            }
        }

There's anyboody know why the first example gets an error!
thanks