Handling missing references

Question: I'm getting the error Can't use an undefined value as an ARRAY reference in a Perl script. Below is a highly simplified version.
Basically I have setup a hash of arrays where some of them might be empty (B in this case). It works just fine if I DON'T sort the data array. I've tried adding a conditional to test if that particular array exists, but it doesn't like that in this setup. It would not be easy to sort the array as it's populated (unlike in this example).
use strict;
use warnings;

my @list = ('A', 'B', 'C');
my %data_for;
$data_for{'A'} = ['apple', 'astronaut', 'acorn'];
$data_for{'C'} = ['car', 'cook', 'candy'];

# Creates error
foreach my $letter (@list) {
    print "$letter: ";
    foreach my $item ( sort @{$data_for{$letter}}) {
        print "$item, ";
    }
    print "\n";
}

This is the output I want (seems obvious, but eh):
A: acorn, apple, astronaut,
B:
C: candy, car, cook,

As a strange aside, if I print the working version (without the sort) first, the second version with the sort works without an error. I do not understand this, but I may be able to use that as a work around.
Comment: plus one for coming up with a simpler example that demonstrates your issue
Comment: Reopened, but there was nothing useful in the question of which this one was flagged as a duplicate. [This one](https://stackoverflow.com/questions/7818243/how-should-i-handle-undefined-references-with-xmlsimple) is an actual duplicate, but I'd rather close the old one in preference to this clearer new one. I have done so.
Comment: @mob - I would say that I didn't have a choice given how complex hash-of-arrays can be, but I know how bad some can be. Technically this question is a repeat, but I simply couldn't follow the earlier ones who had incoherent code, which lead to incomplete answers.
Comment: I am surprised that it hasn't made it into even *Merriam-Webster*, but ***setup*** isn't an English verb anywhere. There seems to be a fashion for removing spaces from phrases that is making American English more and more like German. I don't like it. I am sorry that this is so off-topic.
Comment: @Borodin - it may be a duplicate question title, but that code didn't clearly show where the problem was and the accepted answer was "use diagnostics. There is another question about this same error code, but the code was so confusing that they couldn't figure out what it was written in (perl, python, php??) - and the final answer was "use diagnostics". My question got an actual answer that explains what was wrong.
Comment: @ikegami - thanks for the fix for that. It bothered my OCD, but didn't really matter so I was forcing myself to ignore it :-)
Answer: $data_for{B} is not defined, so the attempt to dereference it as an array (in the sort @{$data_for{$letter}} expression) is an error.
One workaround is to assign a (empty) value for $data_for{B}:
$data_for{'A'} = ['apple', 'astronaut', 'acorn'];
$data_for{'B'} = [];
$data_for{'C'} = ['car', 'cook', 'candy'];

but a more general workaround is to use the '||' operator (or '//' operator for Perl >=v5.10) to specify a default value when a hash value is not defined
foreach my $item ( sort @{$data_for{$letter} || []}) { ... }

When $data_for{$letter} is undefined (and therefore evaluates to false), the expression $data_for{$letter} || [] evaluates to a reference to an empty array, and the array dereference operation will succeed.
Answer: So you need to check if $data_for{$letter} is a reference or not. Possible checks:

exists($data_for{$letter}).
defined($data_for{$letter}) because a non-existent hash element is undefined.
$data_for{$letter} because references are always true.

We can use the check to provide us something to dereference:
sort @{ $data_for{$letter} // [] }

We can use the check to avoid dereferencing at all.
sort $data_for{$letter} ? @{ $data_for{$letter} } : ()

This gives us the following:
print "$letter: ";
for my $item ( sort $data_for{$letter} ? @{ $data_for{$letter} } : () ) {
    print "$item, ";
}
print "\n";

Or better yet, we can avoid the trailing , with the following:
use feature qw( say );

say "$letter: ", join ", ", sort $data_for{$letter} ? @{ $data_for{$letter} } : ();

It works just fine if I DON'T sort the data array.

When you dereference an undefined variable that's used as a modifiable value (lvalue), Perl will automatically create a variable of the appropriate type, and it will place a reference to the newly created variable in the undefined variable. This is called "autovivification".
Since autovivifying only happens in lvalue context, derefencing an undefined value elsewhere leads to the an error.
 my ($a,$b);  # Both are undefined.
 @$a = @b;    # OK. Equivalent to @{ $a //= [] } = @b.
 @a = @$b;    # XXX. "Can't use an undefined value as an ARRAY reference."

sort doesn't modify its operands, so it doesn't evaluate them in lvalue context.
A foreach loop evaluates its operands in lvalue context to allow for for (@$a) { $_ = uc($_); }. That means that
for (@{ $data_for{$letter} }) { ... }

implicitly modifies $data_for{$letter} as follows:
for (@{ $data_for{$letter} //= [] }) { ... }

Handling missing references


Limit memory usage NXT client

Question: I noticed that the RuneScape NXT client uses about 1.6 GB of memory when I am in the Living Rock Caverns on the LRC world, even when I have all graphics options turned down. While I have 4 GB memory on this system, this much memory for that application makes my system unstable. The old java client didn't seem to have this problem.
Is there a settings file that allows me to limit the amount of memory, or an other way that allows me to hint the application to only use about 1GB?
Answer: You can't decrease the memory usage via a configuration setting. Unlike the old Java client, which could only use memory up to a limit that could be set through JVM startup options, the C++-based NXT client can use as much memory as it needs, up to the total available system memory.
This is a good thing. Unused memory is wasted memory. If you're having issues due to your computer running out of memory, try closing other memory-intensive programs (Chrome is a common culprit), or upgrading your RAM (4 GB is a bit on the low side nowadays).
Comment: @Sumurai8 I did answer the question - you can't decrease the memory usage via a configuration setting. If your computer is freezing up, it's more likely that something else is going on that's causing it.
Comment: It's... interesting to read that an application using so much memory that it literally freezes the system, sometimes requiring a power cycle to get out of it, is "a good thing". Nevertheless, it does not seem to answer the question I had...

Limit memory usage NXT client


Drawing text centered within a rectangle

Question: I have code, similar to the following:
string myText = "This is a test";
Font myFont = new Font("Arial", 10);
Rectangle rect = new Rectangle(10,10,100,100);
Graphics g = e.Graphics;
g.DrawString(myText, myFont, rect.X, rect.Y);

Although this works, what I would like to do is have the text vertically and horizontally centered within the dimensions of the rectangle. In addition, if its possible, I'd like to wrap the text if its too big to fit on one line. How do I do this in C#/GDI+?
Answer: I would use one of the DrawString Overloads that takes a StringFormat You would have to check the Length of your Text using MeasureString  to make sure it would fit and wrap it yourself. In looking further at the StringFormatFlags it has a NoWrap Flag implying that the default is to wrap:
from last link:

Text wrapping between lines when formatting within a rectangle is disabled. This flag is implied when a point is passed instead of a rectangle, or when the specified rectangle has a zero line length.
Comment: Thank you! Yes, I just found out, wrapping will automatically occur, so this solution solves both my problems!
Comment: I tried all possible StringFormatFlags but could not find any that centers the text vertically in the rectangle as requested by the OP. Maybe an example of the code needed for this could be shared here ?
Answer: the simple, un-researched way to do it:
to word-wrap break your strings up into smaller sub-strings.  I.e.
"this is"
"a test"

you can use the String.Split() method to split your strings up into words, and then append the words together until your string has reached a certain threshold.  and then make a new string.
As for centering, you can pad your individual strings with spaces.  for vertical centering, you can add some newlines to the beginning of your strings.
I'll leave the arithmetic involved to you.  it shouldn't be that hard.


apache2 web server index.html problems

Question: I am having a problem with document root. The onlt way I can get to my index.html is by specifying
http://mysite.com/index.html , is there a way to have it automatically redirected to index.html with http://mysite.com ?

        ServerAdmin email@example.com
<code>    DocumentRoot /var/www/mysite.com
    <Directory />
            Options FollowSymLinks
            AllowOverride None
    </Directory>
    <Directory /var/www/mysite.com>
            Options Indexes FollowSymLinks MultiViews
            AllowOverride None
            Order allow,deny
            allow from all
    </Directory>

    ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
    <Directory "/usr/lib/cgi-bin">
            AllowOverride None
            Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
            Order allow,deny
            Allow from all
    </Directory>

    ErrorLog /var/log/apache2/error.log

    # Possible values include: debug, info, notice, warn, error, crit,
</code>
Answer: You need to add DirectoryIndex to your host configuration. This basically tell the server what files to look for if no file is specifed in the request.
In your case this could work:
<code><Directory /var/www/mysite.com>
        DirectoryIndex index.html
        Options Indexes FollowSymLinks MultiViews
        AllowOverride None
        Order allow,deny
        allow from all
</Directory>
</code>

apache2 web server index.html problems


Avoiding stack overflow with functional programming

Question: I am trying to solve "the grid search" problem on hacker rank using functional programming. Please view the problem description on hackerrank.
https://www.hackerrank.com/challenges/the-grid-search/problem
I want to use only recursion and functional programming primitives such as map, filter, etc. My current solution checks to see if it can find the pattern at the start of the array, if it can't, then I call recursively on  the tail of the array. I came up with the following:
def checkLine(str1, str2):
    return str1 in str2

def checkGroup(group1, group2):
    return False not in list(map(lambda x: checkLine(x[0], x[1]), zip(group1, group2)))

def gridSearch(G, P):
    # Write your code here
    if len(G) < len(P):
        return "NO"
    if checkGroup(P, G):
        return "YES"
    else:
        return gridSearch(G[1:], P)

The issue is that I am running into stack overflow when both the array is very large. I know you can avoid stack overflow by using tail recursion but I'm not quite sure how to accomplish that here. Can anyone give an example of how solve this problem functionally but also avoid stack overflow?
Comment: " I know you can avoid stack overflow by using tail recursion " You cannot. CPython does not do tail-call optimization. Indeed, your grid-search function is already tail recursive. Fundamentally, you should just use iteration in Python when you want to use deep recursion. Python is not a functional programming langauge (although, it borrows from the paradigm, e.g. list comprehensions).
Comment: You can increase the recursion limit, but doing so causes HackerRank to return a wrong answer. Are you sure your code is correct?
Comment: See [Does Python optimize tail recursion?](https://stackoverflow.com/q/13591970/5987).
Comment: @BrokenBenchmark It passed about 10 of the test cases but failed for the others that had very large input. Thanks for the replies. I see now that function I wrote is already tail recursive.
Answer: I'm not really a Python programmer, so there might be more idiomatic ways of doing this, but in JavaScript I would use a technique known as trampolining:
def trampoline(original_function):
    def wrapped_function(*args):
        # Call the original function
        result = original_function(*args)
        # If a function is returned, call the function until
        # a non-function is returned, which is the final result
        while callable(result):
            result = result()
        return result
    return wrapped_function

# Factorial function example
def _fact(n, acc=1):
    if n == 0: return acc
    return lambda: _fact(n - 1, n * acc)
fact = trampoline(_fact)

def _gridSearch(G, P):
    # Write your code here
    if len(G) < len(P):
        return "NO"
    if checkGroup(P, G):
        return "YES"
    else:
        # note the lambda: here
        return lambda: _gridSearch(G[1:], P)
gridSearch = trampoline(_gridSearch)

I personally don't like doing if callable(result) to check if the recursive function has outputted the final value, so another method could be to do something like this:
from dataclasses import dataclass

@dataclass
class Recurse:
    value: ...

@dataclass
class Return:
    value: ...

def trampoline(fn):
    def f(*args):
        x = fn(*args)
        while isinstance(x, Recurse):
            x = fn(*x.value)
        return x.value
    return f

# Factorial function example
def _fact(n, acc=1):
    if n == 0: return Return(acc)
    return Recurse((n - 1, n * acc))
fact = trampoline(_fact)

def _gridSearch(G, P):
    # Write your code here
    if len(G) < len(P):
        return Return("NO")
    if checkGroup(P, G):
        return Return("YES")
    else:
        return Recurse((G[1:], P))
gridSearch = trampoline(_gridSearch)

This way is more general than the other one as it works for recursive functions that return another function (but I can't think of why you would need to do this).


error while loading shared libraries: libqt-mt.so.3:

Question: I'm trying to run an Qtstalker installed on schroot. Steps described here: How do I install Qtstalker on Ubuntu 17.10?
When I come to the last step schroot -c precise env DISPLAY=:0.0 qtstalker I get the error:

qtstalker: error while loading shared libraries: libqt-mt.so.3: cannot open shared object file: No such file or directory

I tried going to root schroot -c precise -u root, then tried sudo apt-get install qt3 as well as sudo apt-get install libqt-mt
Gettin the error

Unable to locate package libqt-mt

I had already added lists to sources.list in chroot as outlined in that solution.
deb http://archive.ubuntu.com/ubuntu precise main universe multiverse
deb http://security.ubuntu.com/ubuntu precise-security main restricted universe multiverse

@N0rbert
UPDATE. Downloaded https://launchpad.net/ubuntu/precise/amd64/libqt3-mt/3:3.3.8-b-8ubuntu3 and started installing on schroot with dependency and as well as debconf errors.. It even tries to remove libqt3-mt (see Bold markups please)
Any thoughts? Thanks very much again.
dpkg -i --force-all libqt3*.deb

dpkg: libqt3-mt: dependency problems, but configuring anyway as you requested:
   libqt3-mt depends on libaudio2; however:
    Package libaudio2 is not installed.
   libqt3-mt depends on libfontconfig1 (>= 2.8.0); however:
    Package libfontconfig1 is not installed.
   libqt3-mt depends on libfreetype6 (>= 2.2.1); however:
    Package libfreetype6 is not installed.
   libqt3-mt depends on libice6 (>= 1:1.0.0); however:
    Package libice6 is not installed.
   libqt3-mt depends on libjpeg8 (>= 8c); however:
    Package libjpeg8 is not installed.
   libqt3-mt depends on libmng1 (>= 1.0.10); however:
    Package libmng1 is not installed.
   libqt3-mt depends on libpng12-0 (>= 1.2.13-4); however:
    Package libpng12-0 is not installed.
   libqt3-mt depends on libsm6; however:
    Package libsm6 is not installed.
   libqt3-mt depends on libstdc++6 (>= 4.1.1); however:
    Package libstdc++6 is not installed.
   libqt3-mt depends on libx11-6; however:
    Package libx11-6 is not installed.
   libqt3-mt depends on libxcursor1 (>> 1.1.2); however:
    Package libxcursor1 is not installed.
   libqt3-mt depends on libxext6; however:
    Package libxext6 is not installed.
   libqt3-mt depends on libxft2 (>> 2.1.1); however:
    Package libxft2 is not installed.
   libqt3-mt depends on libxi6; however:
    Package libxi6 is not installed.
   libqt3-mt depends on libxinerama1; however:
    Package libxinerama1 is not installed.
   libqt3-mt depends on libxrandr2; however:
    Package libxrandr2 is not installed.
   libqt3-mt depends on libxrender1; however:
    Package libxrender1 is not installed.
   libqt3-mt depends on fontconfig; however:
    Package fontconfig is not installed.
  Setting up libqt3-mt (3:3.3.8-b-8ubuntu3) ...
  Processing triggers for libc-bin ...
  ldconfig deferred processing now taking place

apt-get install -f

Reading package lists... Done
  Building dependency tree
  Reading state information... Done
  Correcting dependencies... Done
  The following extra packages will be installed:
    apt-utils binutils:i386 cpp:i386 cpp-4.6:i386 debconf debconf-i18n debianutils dpkg
    fontconfig fontconfig-config gcc:i386 gcc-4.6:i386 libapt-inst1.4 libapt-pkg4.12
    libaudio2:i386 libc-dev-bin libc6-dev:i386 libdb5.1 libdrm-intel1:i386
    libdrm-nouveau1a:i386 libdrm-radeon1:i386 libdrm2:i386 libexpat1 libexpat1:i386
    libffi6:i386 libfontconfig1 libfontconfig1:i386 libfreetype6 libfreetype6:i386 libgcc1
    libgcc1:i386 libgl1-mesa-dri:i386 libgl1-mesa-glx:i386 libglapi-mesa:i386 libglu1-mesa:i386
    libgmp10:i386 libgomp1:i386 libice6:i386 libjpeg-turbo8:i386 libjpeg8:i386 liblcms1:i386
    libllvm3.0:i386 liblocale-gettext-perl libmng1:i386 libmpc2:i386 libmpfr4:i386
    libpam-modules libpam-modules-bin libpam0g libpciaccess0:i386 libpng12-0:i386
    libqt3-mt:i386 libquadmath0:i386 libsm6:i386 libstdc++6 libstdc++6:i386
    libtext-charwidth-perl libtext-iconv-perl libtext-wrapi18n-perl libtinfo5 libuuid1
    libuuid1:i386 libx11-6:i386 libx11-data libx11-xcb1:i386 libxau6:i386 libxcb-glx0:i386
    libxcb1:i386 libxcursor1:i386 libxdamage1:i386 libxdmcp6:i386 libxext6:i386 libxfixes3:i386
    libxft2:i386 libxi6:i386 libxinerama1:i386 libxmu6:i386 libxrandr2:i386 libxrender1:i386
    libxt6:i386 libxxf86vm1:i386 linux-libc-dev:i386 lsb-base manpages manpages-dev ncurses-bin
    passwd perl-base sed sensible-utils ttf-dejavu-core tzdata ucf uuid-runtime x11-common
  Suggested packages:
    binutils-doc:i386 cpp-doc:i386 gcc-4.6-locales:i386 debconf-doc debconf-utils whiptail
    dialog gnome-utils libterm-readline-gnu-perl libgtk2-perl libnet-ldap-perl libqtgui4-perl
    libqtcore4-perl apt gcc-multilib:i386 make:i386 manpages-dev:i386 autoconf:i386
    automake1.9:i386 libtool:i386 flex:i386 bison:i386 gdb:i386 gcc-doc:i386
    gcc-4.6-multilib:i386 libmudflap0-4.6-dev:i386 gcc-4.6-doc:i386 libgcc1-dbg:i386
    libgomp1-dbg:i386 libquadmath0-dbg:i386 libmudflap0-dbg:i386 binutils-gold:i386 nas:i386
    glibc-doc:i386 libglide3:i386 liblcms-utils:i386 libpam-doc pciutils:i386
    libqt3-mt-psql:i386 libqt3-mt-mysql:i386 libqt3-mt-odbc:i386 man-browser
  Recommended packages:
    uuid-runtime:i386
  The following packages will be REMOVED:
libqt3-mt
The following NEW packages will be installed:
    apt-utils binutils:i386 cpp:i386 cpp-4.6:i386 debconf debconf-i18n debianutils dpkg
    fontconfig fontconfig-config gcc:i386 gcc-4.6:i386 libapt-inst1.4 libapt-pkg4.12
    libaudio2:i386 libc-dev-bin libc6-dev:i386 libdb5.1 libdrm-intel1:i386
    libdrm-nouveau1a:i386 libdrm-radeon1:i386 libdrm2:i386 libexpat1 libexpat1:i386
    libffi6:i386 libfontconfig1 libfontconfig1:i386 libfreetype6 libfreetype6:i386 libgcc1
    libgcc1:i386 libgl1-mesa-dri:i386 libgl1-mesa-glx:i386 libglapi-mesa:i386 libglu1-mesa:i386
    libgmp10:i386 libgomp1:i386 libice6:i386 libjpeg-turbo8:i386 libjpeg8:i386 liblcms1:i386
    libllvm3.0:i386 liblocale-gettext-perl libmng1:i386 libmpc2:i386 libmpfr4:i386
    libpam-modules libpam-modules-bin libpam0g libpciaccess0:i386 libpng12-0:i386
    libqt3-mt:i386 libquadmath0:i386 libsm6:i386 libstdc++6 libstdc++6:i386
    libtext-charwidth-perl libtext-iconv-perl libtext-wrapi18n-perl libtinfo5 libuuid1
    libuuid1:i386 libx11-6:i386 libx11-data libx11-xcb1:i386 libxau6:i386 libxcb-glx0:i386
    libxcb1:i386 libxcursor1:i386 libxdamage1:i386 libxdmcp6:i386 libxext6:i386 libxfixes3:i386
    libxft2:i386 libxi6:i386 libxinerama1:i386 libxmu6:i386 libxrandr2:i386 libxrender1:i386
    libxt6:i386 libxxf86vm1:i386 linux-libc-dev:i386 lsb-base manpages manpages-dev ncurses-bin
    passwd perl-base sed sensible-utils ttf-dejavu-core tzdata ucf uuid-runtime x11-common
  0 upgraded, 95 newly installed, 1 to remove and 0 not upgraded.
  1 not fully installed or removed.
  Need to get 0 B/52.0 MB of archives.
  After this operation, 144 MB of additional disk space will be used.
  Do you want to continue [Y/n]? y
  E: Cannot get debconf version. Is debconf installed?
  debconf: apt-extracttemplates failed: No such file or directory
  Extracting templates from packages: 31%E: Cannot get debconf version. Is debconf installed?
  debconf: apt-extracttemplates failed: No such file or directory
  Extracting templates from packages: 63%E: Cannot get debconf version. Is debconf installed?
  debconf: apt-extracttemplates failed: No such file or directory
  Extracting templates from packages: 94%E: Cannot get debconf version. Is debconf installed?
  debconf: apt-extracttemplates failed: No such file or directory
  Extracting templates from packages: 100%
  dpkg: regarding .../dpkg_18.104.22.168ubuntu7.7_amd64.deb containing dpkg, pre-dependency problem:
   dpkg pre-depends on coreutils (>= 5.93-1)
    coreutils is unpacked, but has never been configured.
  dpkg: error processing /var/cache/apt/archives/dpkg_220.127.116.11ubuntu7.7_amd64.deb (--unpack):
   pre-dependency problem - not installing dpkg
  Errors were encountered while processing:
   /var/cache/apt/archives/dpkg_188.8.131.52ubuntu7.7_amd64.deb
  E: Sub-process /usr/bin/dpkg returned an error code (1)

Tried the next in schroot:apt-get install libqt3-mt and got the below error again with dependencies.. Ubuntu suggested apt-get -f install did that and re-tried to install libqt3-mt; again the same error.

Reading package lists... Done
  Building dependency tree
  Reading state information... Done
  libqt3-mt is already the newest version.
  You might want to run 'apt-get -f install' to correct these:
  The following packages have unmet dependencies:
   coreutils : Depends: dpkg (>= 1.15.4) or
                        install-info
   libc6 : Depends: libgcc1 but it is not going to be installed
           Depends: tzdata but it is not going to be installed
   libc6:i386 : Depends: libgcc1:i386 but it is not going to be installed
                Depends: tzdata:i386
   libqt3-mt : Depends: libaudio2 but it is not going to be installed
               Depends: libfontconfig1 (>= 2.8.0) but it is not going to be installed
               Depends: libfreetype6 (>= 2.2.1) but it is not going to be installed
               Depends: libice6 (>= 1:1.0.0) but it is not going to be installed
               Depends: libjpeg8 (>= 8c) but it is not going to be installed
               Depends: libmng1 (>= 1.0.10) but it is not going to be installed
               Depends: libpng12-0 (>= 1.2.13-4) but it is not going to be installed
               Depends: libsm6 but it is not going to be installed
               Depends: libstdc++6 (>= 4.1.1) but it is not going to be installed
               Depends: libx11-6 but it is not going to be installed
               Depends: libxcursor1 (> 1.1.2) but it is not going to be installed
               Depends: libxext6 but it is not going to be installed
               Depends: libxft2 (> 2.1.1) but it is not going to be installed
               Depends: libxi6 but it is not going to be installed
               Depends: libxinerama1 but it is not going to be installed
               Depends: libxrandr2 but it is not going to be installed
               Depends: libxrender1 but it is not going to be installed
               Depends: fontconfig
               Recommends: libgl1-mesa-glx or
                           libgl1
               Recommends: libglu1-mesa but it is not going to be installed or
                           libglu1
               Recommends: libxmu6 (>= 4.3.0.dfsg.1-4) but it is not going to be installed
   libqtstalker0:i386 : Depends: libgcc1:i386 (>= 1:4.1.1) but it is not going to be installed
                        Depends: libqt3-mt:i386 (>= 3:3.3.8b) but it is not going to be installed
                        Depends: libstdc++6:i386 (>= 4.1.1) but it is not going to be installed
   qtstalker:i386 : Depends: libgcc1:i386 (>= 1:4.1.1) but it is not going to be installed
                    Depends: libqt3-mt:i386 (>= 3:3.3.8b) but it is not going to be installed
                    Depends: libstdc++6:i386 (>= 4.1.1) but it is not going to be installed
                    Depends: libx11-6:i386 but it is not going to be installed
                    Depends: libxext6:i386 but it is not going to be installed
                    Recommends: qtstalker-doc:i386 (= 0.36-2) but it is not installable
   qtstalker-plugin-mysql:i386 : Depends: libgcc1:i386 (>= 1:4.1.1) but it is not going to be installed
                                 Depends: libqt3-mt:i386 (>= 3:3.3.8b) but it is not going to be installed
                                 Depends: libstdc++6:i386 (>= 4.1.1) but it is not going to be installed
   qtstalker-quote-plugins:i386 : Depends: libgcc1:i386 (>= 1:4.1.1) but it is not going to be installed
                                  Depends: libqt3-mt:i386 (>= 3:3.3.8b) but it is not going to be installed
                                  Depends: libstdc++6:i386 (>= 4.1.1) but it is not going to be installed
   ta-lib0-dev:i386 : Depends: libc6-dev:i386 but it is not going to be installed or
                               libc-dev:i386
  E: Unmet dependencies. Try 'apt-get -f install' with no packages (or specify a solution).

Thanks again.
****Per @N0rbert's advice I reinstalled. Qtstalker launced, but crashed **** with an error in the comments at first try of data retrieval.
During the re-installation, at the last command dpkg -i --force-all *.deb to install packages. I get the following errors. Not sure what's going on, it encountered errors libqt3-mt Perhaps that's the reason...

Preparing to replace libdb4.6:i386 4.6.21-16 (using
  libdb4.6_4.6.21-16_i386.deb) ... Unpacking replacement libdb4.6:i386
  ... Preparing to replace libmysqlclient15off:i386 5.0.92-b23.87.lenny
  (using libmysqlclient15off_5.0.92-b23.87.lenny_i386.deb) ... Unpacking
  replacement libmysqlclient15off:i386 ... Selecting previously
  unselected package libqt3-mt. dpkg: error processing
  libqt3-mt_3.3.8-b-8ubuntu3_amd64.deb (--install):  libqt3-mt:
  3:3.3.8-b-8ubuntu3 (Multi-Arch: no) is not co-installable with
  libqt3-mt:i386 3:3.3.8-b-8ubuntu3 (Multi-Arch: no) which is currently
  installed Preparing to replace libqtstalker0-dev:i386 0.36-2 (using
  libqtstalker0-dev_0.36-2_i386.deb) ... Unpacking replacement
  libqtstalker0-dev:i386 ... Preparing to replace libqtstalker0:i386
  0.36-2 (using libqtstalker0_0.36-2_i386.deb) ... Unpacking replacement libqtstalker0:i386 ... Preparing to replace libta-lib0:i386 0.4.0-2
  (using libta-lib0_0.4.0-2_i386.deb) ... Unpacking replacement
  libta-lib0:i386 ... Preparing to replace qtstalker-doc 0.36-2 (using
  qtstalker-doc_0.36-2_all.deb) ... Unpacking replacement qtstalker-doc
  ... Preparing to replace qtstalker-plugin-mysql:i386 0.36.0-1 (using
  qtstalker-plugin-mysql_0.36.0-1_i386.deb) ... Unpacking replacement
  qtstalker-plugin-mysql:i386 ... Preparing to replace
  qtstalker-quote-plugins:i386 0.36-2 (using
  qtstalker-quote-plugins_0.36-2_i386.deb) ... Unpacking replacement
  qtstalker-quote-plugins:i386 ... Preparing to replace qtstalker:i386
  0.36-2 (using qtstalker_0.36-2_i386.deb) ... Unpacking replacement qtstalker:i386 ... Preparing to replace ta-lib0-dev:i386 0.4.0-2
  (using ta-lib0-dev_0.4.0-2_i386.deb) ... Unpacking replacement
  ta-lib0-dev:i386 ... Setting up libdb4.6:i386 (4.6.21-16) ... Setting
  up libmysqlclient15off:i386 (5.0.92-b23.87.lenny) ... dpkg: also
  configuring libqt3-mt:i386' (required bylibqtstalker0:i386')
  Setting up libta-lib0:i386 (0.4.0-2) ... Setting up qtstalker-doc
  (0.36-2) ... dpkg: also configuring libqt3-mt:i386' (required by
  qtstalker-plugin-mysql:i386') dpkg: also configuring libqt3-mt:i386'
  (required byqtstalker-quote-plugins:i386') dpkg: also configuring
  libqt3-mt:i386' (required byqtstalker:i386') Setting up
  ta-lib0-dev:i386 (0.4.0-2) ... Setting up libqt3-mt:i386
  (3:3.3.8-b-8ubuntu3) ... Setting up libqtstalker0:i386 (0.36-2) ...
  dpkg: error processing libqt3-mt:i386 (--install):  package
  libqt3-mt:i386 is already installed and configured Setting up
  qtstalker-plugin-mysql:i386 (0.36.0-1) ... dpkg: error processing
  libqt3-mt:i386 (--install):  package libqt3-mt:i386 is already
  installed and configured Setting up qtstalker-quote-plugins:i386
  (0.36-2) ... dpkg: error processing libqt3-mt:i386 (--install):
  package libqt3-mt:i386 is already installed and configured Setting up
  qtstalker:i386 (0.36-2) ... Setting up libqtstalker0-dev:i386 (0.36-2)
  ... Processing triggers for libc-bin ... ldconfig deferred processing
  now taking place
  Errors were encountered while processing:  libqt3-mt_3.3.8-b-8ubuntu3_amd64.deb  libqt3-mt:i386  libqt3-mt:i386
  libqt3-mt:i386
Answer: As far I can see:

$ apt-cache policy libqt3-mt
libqt3-mt:
  Installed: (none)
  Candidate: 3:3.3.8-b-8ubuntu3
  Version table:
     3:3.3.8-b-8ubuntu3 0
        990 http://archive.ubuntu.com/ubuntu/ precise/main amd64 Packages
     3:3.3.8-b-6ubuntu2 0
        500 http://old-releases.ubuntu.com/ubuntu/ lucid/main amd64 Packages
     3:3.3.8-b-0ubuntu3 0
        500 http://old-releases.ubuntu.com/ubuntu/ hardy/main amd64 Packages
     3:3.3.6-1ubuntu3 0
        500 http://old-releases.ubuntu.com/ubuntu/ dapper/main amd64 Packages >```

you need to install libqt3-mt package into the schroot and then proceed.
Comment: Thanks @N0rbert. I think I'm facing dependency issues. It seems like its trying to remove the libqt3-mt, and install bunch of others. I came thus far -appended to question.
Comment: It seems that you use wrong method of package installation. You just need simple `apt-get` inside schroot - `schroot -c precise -u root apt-get install libqt3-mt`. Your method added the problems...
Comment: thanks. Tried this as soon as I can; got the appended response. Still giving dependency error. Should I start from scratch, what do you think?
Comment: I think you should start from scratch. I have tested [my instruction](https://askubuntu.com/a/1002350/66509) before publishing it, so please follow it precisely. Last time I have checked it in 18.04 LTS.
Comment: Thank you very much sir, you are a gentlemen. I got the qtstalker launch, but it crashed with Child terminated by signal 'Segmentation fault' message...During the reinstallation, I got error at the final dpkg. Appended the screen message with errors. Thanks again, hopefully this software pays dividend for all your efforts :)
Comment: I'm sorry, but I can't reproduce the problem.


Concatenate a string within a text cell with other string at (the same place - delimiter) in other cells

Question: First of all, just to be clear, I am using Excel 2013 so I won't be able to access the new fancy stuff on Excel 2016.
Second of all, I need help as I haven't been able to work out a solution or at least a method to my problem below.
I will try my best with the formatting. Perhaps a screenshot is better

So for this question, I have 3 columns and lots of rows.
The delimiter in each cell is ; . There will be the same number of this delimiter in each cell on the same row.
But each row will have different numbers of delimiter.
There is an assumed value before the first, after the last and in between the delimiters.
I've been looking for a way to concatenate or join these value that in at the same place within these delimiters together into the same text but I couldn't think of anything.
So for example:
<code>          Column 1 - Column 2 - Column 3
   Row 1   a;b;c      1;2;3      q;w;e
   Row 2
   Row 3
</code>
So I would for column 4 to contain the result of concatenating which is "a1q", column5 "b2w" and column 6 "c3e"
Or it could just be all in column 4 with a delimiter which is something like "a1q;b2w;c3e"
Same thing with row 2 and 3 but they may have more or fewer values. This is why I need something scale-able.
I don't think it is possible with normal Excel unless VBA is involved. I hope I made the question clear and thank you in advance for any help.
Comment: Can you please [edit your question](https://stackoverflow.com/posts/53417802/edit) to give us a clear example of initial data and expected result? Also, what have you tried so far and how is it failing to achieve your expected output?
Answer: This one should put everything in Column 4 or "D".
<code>Sub splitter()
    Dim SubBNameSplit() As String, BuildNameSplit() As String, NumberSplit() As String, result As String
    Dim lrow As Long
    Dim x As Range
    Dim i As Long

    With Worksheets("Sheet1")
        lrow = .Cells(Rows.Count, 1).End(xlUp).Row
            For Each x In .Range("A2:A" & lrow)
                SubBNameSplit() = Split(.Range("A" & x.Row), ";")
                BuildNameSplit() = Split(.Range("B" & x.Row), ";")
                NumberSplit() = Split(.Range("C" & x.Row), ";")
                result = ""

                For i = LBound(SubBNameSplit) To UBound(SubBNameSplit)
                    result = result & SubBNameSplit(i) & BuildNameSplit(i) & NumberSplit(i) & ";"
                Next i

                .Range("D" & x.Row).Value = result
            Next x
    End With
End Sub
</code>
Comment: Thank you so much. This was what I had in mind, but I didn't know about the Split function or the LBound. (I am not that familiar with working with arrays).

I managed to edit the smaller loop i to format the concatenation to how I want.


How to create a batch file to backup Mysql database?

Question: I have been trying to create a batch file to backup MySQL database. All worked fine but the backup is just empty. I don't know where have gone wrong. Here is my code
set year=%DATE:~10,4%
set day=%DATE:~7,2%
set mnt=%DATE:~4,2%
set hr=%TIME:~0,2%
set min=%TIME:~3,2%

IF %day% LSS 10 SET day=0%day:~1,1%
IF %mnt% LSS 10 SET mnt=0%mnt:~1,1%
IF %hr% LSS 10 SET hr=0%hr:~1,1%
IF %min% LSS 10 SET min=0%min:~1,1%

set backuptime=%year%-%day%-%mnt%-%hr%-%min%
echo %backuptime%
set dbuser=root
set dbpass=vsplabs
set mysqldumpexe="C:\Program Files\MySQL\MySQL Server 5.6\bin\mysqldump.exe"
set backupfldr="C:\Users\sowmya\Desktop\Mysqlbackups"
set datafldr="C:\ProgramData\MySQL\MySQL Server 5.6\data"
set zipper="c:\MySQLBackups\zip\7za.exe"
pushd %datafldr%
echo "Pass each name to mysqldump.exe and output an individual .sql file for each"
@echo off
FOR /D %%F IN (*) DO (
IF NOT [%%F]==[performance_schema] (
SET %%F=!%%F:@002d=-!
%mysqldumpexe% --user=%dbuser% --password=%dbpass% --databases --routines --log-error=%errorLogPath% %%F > "%backupfldr%%%F.%backuptime%.sql"
) ELSE (
echo Skipping DB backup for performance_schema
)
)
 echo "Zipping all files ending in .sql in the folder"
 %zipper% a -tzip "%backupfldr%FullBackup.%backuptime%.zip" "%backupfldr%*.sql
 echo "done"
 popd

And another issue I just wanted only one database its being retrieving all the databases from database..How to modify that and And i have been getting an extra database named as "mysql"
Comment: The mysql db is a standard db which stores previliges and so on.
Answer: This can be run directly in cmd (I wrapped the line but it should not be wrapped):
You should give the root access.
mysql.exe -uroot -p1234 -s -N -e "SHOW DATABASES" |
for /F "usebackq" %D in (`findstr /V "information_schema performance_schema"`)
do mysqldump %D -uroot -p1234 > S:\Backup\MySQL\%D.sql

In a batch file you will need to escape % with an additional %, that is use %%D.
Comment: The application user cant do all this so I have been creating batch file so that he can simply run that and the database will be stored in a specific folder
Comment: You can definitely add my piece of code to a batch with escapes.
Comment: Then how about the path and db name along with date


JavaFX ScrollPane vs. TabView filling space

Question: I've placed some content inside a TabPane's tab, but the TabPane's width seems to me being equal to the longest element inside the tab (the longest element is not visible on the picture).
The TabPane is loaded to a ScrollPane via FXMLLoader.load(), that's why I would expect it to fill the whole space, not just the size of the longest element inside..

How could I make the TabPane fill all available space?
Loader:
        FXMLLoader loader = new FXMLLoader();
        loader.setLocation(Main.class.getResource("View.fxml"));
        Node tp = loader.load();
        ScrollPane sp = new ScrollPane();
        sp.setContent(tp);
        primaryStage.setScene(new Scene(sp, 300, 200));
        primaryStage.show();

View.fxml:
<TabPane tabClosingPolicy="UNAVAILABLE" xmlns="http://javafx.com/javafx/8.0.65" xmlns:fx="http://javafx.com/fxml/1">
  <tabs>
    <Tab text="Untitled Tab 1">
      <content>
        <AnchorPane />
      </content>
    </Tab>
    <Tab text="Untitled Tab 2">
      <content>
        <AnchorPane />
      </content>
    </Tab>
  </tabs>
</TabPane>

Answer: ScrollPane sp = new ScrollPane();
sp.setContent(tp);
sp.setFitWidth(true);

Comment: Thank you! The correct method name is sp.setFitToWidth(true); if anyone else is looking for the solution...


Sumifs Dynamic Range

Question: Iam using sumifs formula. My sumrange is dynamic and is based on the cell value. I have been able to get the column name by using the formula.
Now iam getting stuck when i try to reference the cell value(which has column name "g") to the range in sumifs, for example
=SUMIFS(LinkedIn!H:H,LinkedIn!A:A,Worksheet!B28). i want to change the range (H:H) with the column name which i have in the cell. i tried doing this "=SUMIFS(LinkedIn!D14:D14,LinkedIn!A:A,Worksheet!B28)" but its giving error.
please advise.
regards,
srijith
Comment: Can I assume "g" is in cell D14? and that if D14 is "g", you want your sumrange to be column G?
Answer: This should work:-
<code>=SUMIFS(INDIRECT("LinkedIn!" & D14),LinkedIn!A:A,Worksheet!B28)</code>
D14 should hold "H:H" or its equivalent.
Comment: You got me out of big trouble man!! It was like a dead end to me..exausted with searching google. You made my day Thank you!!! :)
Comment: It was a pleasure helping out.

Sumifs Dynamic Range


ASP.NET MVC date format

Question: I have the following code: <%= Html.Encode(String.Format("{0:g}", item.startDate)) %>
It outputs something like 01/01/2011 00:00 but I would to ONLY show the date and not the time! How can I do this? Thanks
Answer: Try
<%= Html.Encode(String.Format("{0:d}", item.startDate)) %>

Answer: <%= item.startDate.ToShortDate() %>

The above will take into account the current Locale and format it as the locale dictates.  There is also no point in using Html.Encode() since it's impossible for the output of the date function to contain anything dangerous that needs encoding.
Answer: <%= Html.Encode(item.StartDate.ToString("dd/MM/yyy")) %>

ASP.NET MVC date format


Why I'm participating here a lot less often

Question: Q like this get a lot of upvotes for some reason Long term effect of masturbation on Estrogen receptors
Spoiler: the paper doesn't mention masturbation in its abstract:

Males of many species present a long-term inhibition of sexual behavior after several ejaculations, known as sexual satiety. It has been shown that androgen receptor density is reduced 24 h after a single ejaculation or mating to satiety, in the medial preoptic area, nucleus accumbens and ventromedial hypothalamus. The aim of this study was to analyze if the density of ERα [Estrogen receptor alpha] was also modified 24 h after a single ejaculation or mating to satiety.

I haven't actually read all of it, but the q doesn't justify why it's asking just about masturbation (with any quote from the paper.) Still it got 7 up-votes and 0 down-votes (before mine), as if it were a well-researched q.
And yeah, I've even read the methods section of the paper now:

All observations were made
  under dim red light, 2 h after the onset of darkness. Each male was placed alone
  in a test arena and 5 min later an intact receptive female was introduced, except
  for controls.

Those rats got some real action, not masturbation.
I have the feeling this site has tipped to the point of too many participants like that (i.e. trolls and their perhaps-not-so-cognizant cheerleaders), from a quick inspection on the main page. (See also my previous rant: Upvoting under-researched questions )
Answer: I wanted to answer another question with this problem first before answering here.
I whole-heartedly agree with @StevenJeuris, and also lament any negative impact that highly-voted questions may have on participation of valued contributors such as @Fizz.
I did upvote the question at hand, and do not intend to change that.  As I mentioned previously, I upvote questions with references, and do not upvote those without.  I do not discriminate reference quality, which I realize means that it's easy to game my vote, but as I said, I only get 1 vote.
Like the question at hand, the question I just answered includes a reference that fails to support assertions made by the poster.  I argue that (1) this is better than not providing a reference (hence the upvote), and (2) that even a bad reference is better than none because it provides context with which to compose a useful answer.  My answer to the other question followed @StevenJeuris's 4th option: Address the error in the answer.
Again, my reasoning comes from my pre-existing bias that answer quality is far more important than question quality.  Someone asking a question is expected to not know stuff - eg, how to interpret a research paper to validate assumptions.  This is part of why this forum exists.
Whatever my personal reasoning for upvoting, this is a community forum, and highly upvoted questions are obviously of interest to the community.  I don't know why that should upset anyone - I am personally only upset by highly upvoted answers that are incorrect, as good answer quality is the ultimate goal of the StackExchange.
Answer: Well-caught! Citations are not always indicative of a well-researched question. That happens, even in peer-reviewed scientific work.
That is why we need curators like you to stick around to down vote, comment on, and even close vote problematic questions like this. But of course, this is a huge time investment, time not all of us have, which is why the problem with this question likely went unnoticed for so long in the first place.
You have a couple of options here:

Choose to participate less since this is not the type of curation you want to invest time in. Totally your right!
Simply down vote, maybe leave a comment, and move on (which you did, thank you!)
Edit the question to correct the misrepresentation of the cited paper. That would be a suitable option in this case, since the question has not attracted answers yet.
Answer the question, as part of which you highlight the erroneous assumptions that lie in the original question and emphasize the specific context your answer applies to which is not indicative of the original intended question.


Can `#ifdef` be used inside a macro?

Question: I only found this related question, which isn't quite what I am looking for.
I used to have macros defined inside an #ifdef statement:
#ifdef DEBUG
#   define PRINT_IF_DEBUGGING(format) printf(format);
#   define PRINTF_IF_DEBUGGING(format, ...) printf(format, __VA_ARGS__);
#else
#   define PRINT_IF_DEBUGGING(...)
#   define PRINTF_IF_DEBUGGING(...)
#endif

Now, I want to do the inverse, to have the #ifdef statements inside the macros. Something like this:
#define PRINT_IF_DEBUGGING(format, ...) \
#if defined(DEBUG) print(format); #endif
#define PRINTF_IF_DEBUGGING(format, ...) \
#if defined(DEBUG) printf(format, __VA_ARGS__); #endif

However, I am having an issue using __VA_ARGS__ inside the #ifdef defined.
error: '#' is not followed by a macro parameter
 #define PRINT_IF_DEBUGGING(format, ...)
error: '#' is not followed by a macro parameter
 #define PRINTF_IF_DEBUGGING(format, ...)
warning: __VA_ARGS__ can only appear in the expansion of a C++11 variadic macro
 #if defined(DEBUG) printf(format, __VA_ARGS__); #endif

Is this possible?
Comment: The more I look at it the more I wonder _why_ you'd want to abandon something that is readable and works.
Comment: Let's say I was exploring new ways for using Macros. If my intent was possible, I would be able to use `#define DEBUG` to enable the `printf` for a segment of code instead of the entire program code.
Comment: In other words, I would like to the compiler to define the code not when parsing the definition of the macro `PRINTF_IF_DEBUGGING`, but when parsing the use of it.
Answer: This should really be a comment, but I can't format that in a way that will allow me to say what I want to say, so I'm answering instead.
Anyway, just change this:
#if defined(DEBUG) print(format); #endif

to this:
#if defined(DEBUG)
    print(format);
#endif

and so on, and that should fix it.
Comment: Fwiw, I think this _should_ be an answer :-)
Comment: @TedLyngmo To quote [Kenneth Wolstenhome](https://en.wikipedia.org/wiki/Kenneth_Wolstenholme) RIP, "it is now" :)  Hmmm, I see Wikipedia have fluffed the quote.  Oh well.
Comment: @EduardoReis Your updated code shows that you still try to put multiple preprocessor directives on the same line. That's not what Paul suggested at all.
Comment: It did not solve the issue. Notice that the issue is on the second macro, the one that can evaluate to `printf(format, __VA_ARGS__)`
Comment: Oh right, you have two separate issues.  I missed that, sorry.  I recommend you ask a new question, incorporating the fix described in my answer, so that readers can focus on your problem using `__VA_ARGS__` .  When you do that, please focus on just that issue and show both your macro and how you are invoking it, see [mre].
Comment: PS: I rolled back your edit.  Editing questions that have been answered in a way that renders the answer invalid is a no-no.  And if you take note of and act on what @ted told you, your second problem might go away in any case.
Answer: You can't use #ifdef inside of #define , so no, this is not possible.  The first code you showed is the correct solution.
Answer: Using #ifdef inside of #define is not possible. But there are still ways you can detect wether or not a macro has been defined within a macro definition.
1. Solution
godbolt
#define CAT(a, b) CAT_IMPL(a, b)
#define CAT_IMPL(a, b) a ## b

#define IS_DEBUG_DEFINED() CHECK((CAT(CHECK_,DEBUG), 0, 1))
#define CHECK_DEBUG ~,~
#define CHECK(tup) CHECK_IMPL tup
#define CHECK_IMPL(a, b, c, ...) c

#define IIF(condition, true_value, false_value) CAT(IIF_,condition)(true_value, false_value)
#define IIF_0(true_value, false_value) false_value
#define IIF_1(true_value, false_value) true_value

#define PRINT_IF_DEBUGGING(format) IIF(IS_DEBUG_DEFINED(), PRINT_DEBUGGING, PRINT_NOT_DEBUGGING)(format)
// this will be used if DEBUG is defined:
#define PRINT_DEBUGGING(format) debugPrint(format)
// this will be used if DEBUG is NOT defined:
#define PRINT_NOT_DEBUGGING(format) print(format)

PRINT_IF_DEBUGGING(foo) will expand to:

if DEBUG is defined: debugPrint(foo)
if DEBUG is not defined: print(foo)

Example:
PRINT_IF_DEBUGGING("test1");

#define DEBUG
PRINT_IF_DEBUGGING("test2");
#undef DEBUG

PRINT_IF_DEBUGGING("test3");

would result in:
print("test1");

debugPrint("test2");

print("test3");

2. How IS_DEBUG_DEFINED() works
The fundamental trick behind this is to use concatenation - if the macro was defined it will be expanded, otherwise the token will be left unmodified by the preprocessor:
godbolt
#define CAT(a, b) CAT_IMPL(a, b)
#define CAT_IMPL(a, b) a ## b

// DEBUG NOT DEFINED:
CAT(CHECK_,DEBUG) // will expand to CHECK_DEBUG

// DEBUG DEFINED:
#define DEBUG 1234
CAT(CHECK_,DEBUG) // will expand to CHECK_1234

The first CAT will expand to CHECK_DEBUG, because DEBUG was not defined.
The second CAT however will expand to CHECK_1234, because DEBUG was defined and expanded to 1234 before the concatenation with CHECK_.

By defining a macro named CHECK_DEBUG we can change the result if the macro was not defined, e.g.:
godbolt
#define TEST CAT(CHECK_,DEBUG), 0, 1
#define CHECK_DEBUG ~,~

If DEBUG is not defined the result will be ~, ~, 0, 1 (4 comma-separated tokens)
If DEBUG is defined the result will be CHECK_, 0, 1 (3 comma-separated tokens)

Notice how we got 4 tokens in the first case, but only 3 tokens in the second.
Now all we need to do is take the 3rd token from that sequence (which will be 0 if DEBUG is not defined and 1 otherwise), for example with a simple macro that always returns the 3rd argument:
#define CHECK(a, b, c, ...) c

Putting it all together, this is what a full IS_DEBUG_DEFINED() could look like:
godbolt
#define CAT(a, b) CAT_IMPL(a, b)
#define CAT_IMPL(a, b) a ## b

#define IS_DEBUG_DEFINED() CHECK((CAT(CHECK_,DEBUG), 0, 1))
#define CHECK_DEBUG ~,~
#define CHECK(tup) CHECK_IMPL tup
#define CHECK_IMPL(a, b, c, ...) c

IS_DEBUG_DEFINED() will expand to 0 if DEBUG is not defined, and 1 if it is, e.g.:
IS_DEBUG_DEFINED() // -> 0

#define DEBUG
IS_DEBUG_DEFINED() // -> 1
#undef DEBUG

IS_DEBUG_DEFINED() // -> 0

With IS_DEBUG_DEFINED() you can then use a standard preprocessor IIF to change the behaviour of your macro depending on wether DEBUG is defined or not.
Example: godbolt
#define IIF(condition, true_value, false_value) CAT(IIF_,condition)(true_value, false_value)
#define IIF_0(true_value, false_value) false_value
#define IIF_1(true_value, false_value) true_value

#define PRINT_IF_DEBUGGING(format) IIF(IS_DEBUG_DEFINED(), PRINT_DEBUGGING, PRINT_NOT_DEBUGGING)(format)
// this will be used if DEBUG is defined:
#define PRINT_DEBUGGING(format) debugPrint(format)
// this will be used if DEBUG is NOT defined:
#define PRINT_NOT_DEBUGGING(format) print(format)

PRINT_IF_DEBUGGING("test"); // -> print("test");

#define DEBUG
PRINT_IF_DEBUGGING("test"); // -> debugPrint("test");
#undef DEBUG

PRINT_IF_DEBUGGING("test"); // -> print("test");

3. Caveats
One small caveat with this is that if DEBUG is defined it must expand to a valid preprocessing token (so it must only contain letters, digits and underscores) - otherwise the concatenation will result in an error.
So this would not work:
#define DEBUG ()
#define DEBUG +

Can `#ifdef` be used inside a macro?


Forcing HTTP Response to return Status 200 in Rails

Question: How do you force your requests to return status 200 except for serious cases where I return 500? Currently, I am running into the issue where my client keeps getting a status code of 411 (length not specified) and this is causing issues with my test framework.
Is there a way to manually specify your return status in maybe a Rails controller?
EDIT: More specifically I know that you can use

:status

but where do I place that when using

format.json { render :json=>final_obj}

to return a HTTP response after a POST?
Answer: render status: 200, json: @controller.to_json

Comment: I think using :ok instead of the literal 200 is better. In case http changes and it becomes something else :)
Comment: @Purrell using variables instead of magic numbers is just good practice.
Answer: I suppose this should answer your question, if I understood your question correctly.
Ruby 1.9.3
format.json { render json: final_obj, status: :ok }

Ruby 1.8.7
format.json { render :json => final_obj, :status => :ok }


C++ member function pointer compile error

Question: This is similar to Member function pointer cast, from Derived to Base class But not EXACTLY the same.  Plus, I posted an answer here, despite the multiple posts on the similar question which said it's "not possible".
I have a class constructor which takes a pointer an object and to a member function of that object's class.  It will call back into that object.
typedef QByteArray(QObject::*PollerClientFetchFunc)(void);

class FunctionPoller
{
public:
    FunctionPoller( QObject *client,
                    PollerClientFetchFunc clientFunc ){}
};

I have another class where the functional code will be defined:
class SomeClass : public QObject
{
    Q_OBJECT
public:
    SomeClass(){}

    QByteArray poll();
};

And I have a derived class from the one doing the call back:
class MyPoller : public FunctionPoller
{
public:
    MyPoller( SomeClass *someClass );
    ~MyPoller();

    SomeClass *someClass_;
};

MyPoller::MyPoller( SomeClass *someClass )
    : FunctionPoller( someClass, &SomeClass::poll )
    , someClass_( someClass )
{}

This code fails in the MyPoller constructor. The arguments passed to the super class are not kosher. That is the line : FunctionPoller( someClass, &SomeClass::poll ) Here's the error:

no known conversion for argument 2 from 'QByteArray (SomeClass::)()'
  to 'PollerClientFetchFunc {aka QByteArray (QObject::)()}'

In a nutshell, it seems like it can't convert SomeClass to QObject in this context even though it's a decedent of it.   What's wrong here?
Comment: "In a nutshell, it seems like it can't convert SomeClass to QObject.." No, the first argument is okay, the error is for the second one.
Comment: Wait, what? If that's the case this is going over my head somehow.  What's the second argument then?
Comment: It's the function pointer that's the problem and converting the owner class of that, no? That's what I was trying to say.  The pointer to the object is fine.
Comment: Yep. The owner class must be the base class, as you specified.
Comment: Possible duplicate of [Cannot cast "member pointer to derived class" to "member pointer to base class"](https://stackoverflow.com/questions/28156381/cannot-cast-member-pointer-to-derived-class-to-member-pointer-to-base-class)
Comment: poll() is not a member of QObject.  I also tried changing the code so  the parent and child did share such a function name, but that gave me the same error. Plus, it really flies in the face of what I'm actually trying to do.  I want to have a call back into a function of an any object derived from QObject (new functions tacked on on the fly).
Comment: I figured it out.  Answer posted.
Answer: I got it.  Sometimes one just needs to post a question to finally arrive at the answer!  The solution is to just explicitly cast the function pointer.
 : FunctionPoller( someClass, (PollerClientFetchFunc) &SomeClass::poll )


How to create and implement a pixel tracking code

Question: OK, here's a goal I've been looking for a while.
As it's known, most advertising and analytics companies use a so called "pixel" code in order to track websites views, transactions, conversion etc.
I do have a general idea on how it works, the problem is how to implement it. The tracking codes consist from few parts.

The tracking code itself.
This is the code that the users inserts on his webpage in the  section. The main goal of this code is to set some customer specific variables and to call the *.js file.
*.js file.
This file holds all the magic of CRUD (create/read/update/delete) cookies, track user's events and interaction with the webpage.
The pixel code.
This is an  tag with the src atribute pointing to an image *.gif (for example) file that takes all the parameters collected on the page, and stores them in the database.

Example:
WordPress pixel code:
Google Analitycs:
http://www.google-analytics.com/__utm.gif?utmwv=4&utmn=769876874&etc
Now, it's obvious that the *.gif request has to reach a server side scripting language in order to read the parameters data and store them in a db.
Does anyone have an idea how to implement this in Zend?
UPDATE
Another thing I'm interested in is: How to avoid the user's browser to load the cached *.gif ? Will a random parameter value do the trick? Example: src="pixel.gif?nocache=random_number" where the nocache parameter value will be different on every request.
Comment: One quick trick for the cache problem is to ask the browser not to cache the image.`header("Cache-Control: no-cache, must-revalidate");`  `header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");`
Comment: Hi, check this out on the chache problem. http://stackoverflow.com/a/18852257/318489
Answer: As Zend is built using PHP, it might be worth reading the following question and answer: Developing a tracking pixel.
In addition to this answer and as you're looking for a way of avoiding caching the tracking image, the easiest way of doing this is to append a unique/random string to it, which is generated at runtime.
For example, server-side and with the creation of each image, you might add a random URL id:
<?php

  // Generate random id of min/max length
  $rand_id = rand(8, 8);

  // Echo the image and append a random string
  echo "";

?>

Answer: Just adding my 2 cents to this thread because I think an important, and frequently used, option is missing: you don't necessarily need a scripting language to capture the request. A more efficient approach is to use the web server access log (like apache access log for instance) to log the request and then handle that log with whatever tools you see fit, like ELK stack for instance.
This makes serving the requests much lighter because no scripting language is loaded to prepare the response, just native apache response, which is typically much more efficient.
Answer: First of all, the *.gif doesn't need to be that file type, the only thing that is of interest is the Content-Type http header. Set that to image/gif (or any other, appropiate type) in the beginning, execute your code and render some sort of image to the response body.
Comment: Thank you, yes, I did create the proper headers and actually generating the `pixel.gif` file with `PHP` `imagecreatefromgif()` which actually has the `php` extension. The only thing is that, when `www.customerpage.com` loads `` ZF throws an error, that controller `pixel.gif` doesn't exist.
Comment: Have you added a route for it?  And see also the answer on http://stackoverflow.com/questions/3203354/php-script-to-render-a-single-transparent-pixel-png-or-gif - this will be much faster than using imagecreatefromgif
Comment: about the route, not yet, I'm wondering if there's a way to do it without routing. And thank you for the link for the transparent pixel, it;s really useful.
Answer: Well, all of the above codes are correct and is good but to be certain, the guy above mention "g.gif"
You can just add a simple php code to write to an sql or fwrite("file.txt",$opened)
where var $opened serves as the counter++ if someone opened your mail... then save it as "g.gif"
TO DO all of this just add these:
<Files "/thisdirectory">
 AddType application/x-httpd-php .gif
</Files>

to your ".htaccess" file but be sure to make a new directory for that g.gif or whatever.gif where the directory only contains g.gif and .htaccess


My power strip has (what appears to be) a burn mark. What do I do?

Question: I got an power strip from IKEA around 12 months back.  I used it for at my desk with the laptop, pc, printer and light plugged in simultaneously. Now I discovered when I was moving that there's a burn mark midway covering around a sixth of the circumference and around 0.5 cm long. There's clearly heating since it's deformed/bent but it's hard to judge the extent of the damage.

Since it's only a year old, is it reasonable to go back to IKEA and ask for a replacement?
Could the fact that I used the extension cord on a non-earthed wall socket have contributed to the problem (old dutch houses just don't come with them...) and if so, I am liable to see this problem again?
Is it safe to continue using this one?

pic http://www.ikea.com/nl/nl/images/products/koppla-contactdoos-schakelaar--contact__0293166_PE425719_S4.JPG
Comment: I've had something like this happen with a mouse USB cord due to external heating (it was a portion that was near the vent output of the PC) - Was it an actual burn mark (with scorching/melting), or was the insulation just discolored and brittle?
Comment: I had 3 larger size power strips from Ikea, none of them had a burn mark, but every now and them, when plugging something it, there'd be a hiss or pop ... I was lazy and never tossed them - even though I completely agree with @diceless comment below. Luckily in the 10 years this was occurring nothing happened. Upon a recent move, I tossed them and am super thankful that I finally got those pieces of crap out of my life. Not sure I really trust such items to an Ikea branding product.
Answer: Don't risk your life over a power strip.  Throw it away and get a new one.
You can try taking it back and Ikea is pretty good with customer service.  But I personally wouldn't be trusting an Ikea power strip with my computer equipment.  I would get something a little more heavy duty and has surge protection.
Also is your printer laser or ink jet?  If laser you should be treating that device as a small appliance.  IE, no power strip/extension cords as they tend to draw high current during the printing processes.


Dealing with big O

Question: Is this true or false?
$(n(n+1)(n+2))/6$ is $O(n^3)$  (big O)
I have broken it down to this
$(n^3 + 3n^2 + 2n) / 6$
but am unsure what to do next to prove/disprove this statement.
Comment: What does $f(n)=O(n^3)$ mean, according to the definition of $O$?
Answer: Hint
Do you think that $$n\longmapsto \frac{\frac{n^3+3n^2+2n}{6}}{n^3}$$
is bounded when $n\geq 1$ ?
Comment: By definition, $$f(n)=O(g(n))$$ if $\left|\frac{f(n)}{g(n)}\right|$ is bounded when $n\to \infty $. My be you should reconsider your answer ;-)
Comment: I would say no? I am mostly confused as to what it means by "is O(n^3)". I am in a class where the professor doesnt show up, so a few of us are trying to teach ourselves with practice problems from the book.
Answer: Working off of Surb's answer, take
$$\lim_{n \to \infty}  \frac{\frac{n^3+3n^2+2n}{6}}{n^3}$$
$$\lim_{n \to \infty} \dfrac{n^3+3n^2+2n}{6n^3}$$
$$\lim_{n \to \infty} \dfrac{n^3}{6n^3} + \dfrac{3n^2}{6n^3} +  \dfrac{2n}{6n^3} $$
$$\lim_{n \to \infty} \dfrac{1}{6} + \dfrac{1}{2n} +  \dfrac{1}{3n^2} $$
As $n$ approaches $\infty$, $\dfrac {1}{2n}$ and $\dfrac {1}{3n^2}$ both go to zero, so the result is $\dfrac 16$.

Dealing with big O


Help with hauppauge wintv-hvr-2250 on ubuntu 13.04

Question: I've been following the instructions on this website: http://www.linuxtv.org/wiki/index.php/Hauppauge_WinTV-HVR-2200
I'm by no means an expert and I'm stuck on the section titled "Making It Work". where it says:
To get the card working you'll have to
apply the this patch
download v4l-saa7164-1.0.2-3.fw and copy it to /lib/modules

I have no clue how to apply the patch and I'm looking for some help. Thank you.
Comment: Ubuntu may recognize your card. Have you tried using it on VLC. It can open TV tuner cards.
Comment: ubuntu recognizes the card but vlc does not open it.
Answer: I recently purchased the same card knowing nothing about tv-tuner cards and linux.
I had a rough time setting it up and at one point I almost returned the card thinking it was a bad buy.
I'm glad I didn't because the card works nicely with my setup.
Here's what I did
I copied these files
NXP7164-2010-03-10.1.fw
v4l-saa7164-1.0.2-3.fw
v4l-saa7164-1.0.3-3.fw

to /lib/firmware
you can get them from here  http://www.steventoth.net/linux/hvr22xx/firmwares/
just look through the folders and you'll find them.
reboot and they should load.
you can check with dmesg | grep saa7164
this is my output

[   23.126026] saa7164 driver loaded
[   23.126116] saa7164 0000:05:00.0: PCI INT A -> GSI 16 (level, low) -> IRQ 16
[   23.128214] CORE saa7164[0]: subsystem: 0070:8851, board: Hauppauge WinTV-HVR2250 [card=7,autodetected]
[   23.128224] saa7164[0]/0: found at 0000:05:00.0, rev: 129, irq: 16, latency: 0, mmio: 0xfd800000
[   23.128234] saa7164 0000:05:00.0: setting latency timer to 64
[   23.305001] saa7164_downloadfirmware() no first image
[   23.305024] saa7164_downloadfirmware() Waiting for firmware upload (NXP7164-2010-03-10.1.fw)
[   24.346108] saa7164_downloadfirmware() firmware read 4019072 bytes.
[   24.346113] saa7164_downloadfirmware() firmware loaded.
[   24.346129] saa7164_downloadfirmware() SecBootLoader.FileSize = 4019072
[   24.346136] saa7164_downloadfirmware() FirmwareSize = 0x1fd6
[   24.346139] saa7164_downloadfirmware() BSLSize = 0x0
[   24.346142] saa7164_downloadfirmware() Reserved = 0x0
[   24.346145] saa7164_downloadfirmware() Version = 0x1661c00
[   31.208034] saa7164_downloadimage() Image downloaded, booting...
[   31.312020] saa7164_downloadimage() Image booted successfully.
[   33.436032] saa7164_downloadimage() Image downloaded, booting...
[   35.308041] saa7164_downloadimage() Image booted successfully.
[   35.352417] saa7164[0]: Hauppauge eeprom: model=88061
[   35.961461] DVB: registering new adapter (saa7164)
[   38.890487] DVB: registering new adapter (saa7164)
[   38.891328] saa7164[0]: registered device video0 [mpeg]
[   39.122255] saa7164[0]: registered device video1 [mpeg]
[   39.332681] saa7164[0]: registered device vbi0 [vbi]
[   39.332747] saa7164[0]: registered device vbi1 [vbi]

I've used both the analog and digital parts of the card but at the moment I'm only using the analog side because my cable provider only gives me what I'm currently paying for via analog.
I'm sure you already know this but
ivtv-utils and vlc are great tools for testing and debugging
Comment: This worked great for me. Simply `cd /lib/firmware` and `sudo wget ` the files!
Answer: Short answer: you don't need the patch.
The Hauppauge_WinTV-HVR-2500 needs several files in order to be detected.  These are the files contained in my /lib/firmware/3.8.0-27-generic directory: dvb-fe-tda10048-1.0.fw, NXP7164-2010-03-10.1.fw, v4l-saa7164-1.0.2.fw, v4l-saa7164-1.0.3.fw, v4l-saa7164-1.0.3-3.fw.  If you obtained the files from http://onwww.steventoth.net, as instructed on the web page at http://www.linuxtv.org/wiki/index.php/Hauppauge_WinTV-HVR-2200, and ran the script:
sh extract.sh

the necessary files should be located in your home directory. All you need to do is copy them by navigating to your home directory in a terminal and using the cp command:
sudo cp *fw /lib/firmware/3.8.0-27-generic  [enter your password when prompted].

This will copy all files with the .fw suffix to the firmware sub-directory.  Then reboot.
To see that that your card is recognized, open a terminal and enter:
dmesg | grep 7164

You should see something like:
[    0.253798] pci 0000:02:00.0: [1131:7164] type 00 class 0x048000
[   15.412176] saa7164 driver loaded
[   15.412653] CORE saa7164[0]: subsystem: 0070:8851, board: Hauppauge WinTV-HVR2250 [card=7,autodetected]
[   15.412658] saa7164[0]/0: found at 0000:02:00.0, rev: 129, irq: 16, latency:
0, mmio: 0xfe400000
[   15.648146] saa7164_downloadfirmware() no first image
[   15.648213] saa7164_downloadfirmware() Waiting for firmware upload
(NXP7164-2010-03-10.1.fw)
[   17.518041] saa7164_downloadfirmware() firmware read 4019072 bytes.
[   17.518044] saa7164_downloadfirmware() firmware loaded.
[   17.518077] saa7164_downloadfirmware() SecBootLoader.FileSize = 4019072
[   17.518082] saa7164_downloadfirmware() FirmwareSize = 0x1fd6
[   17.518083] saa7164_downloadfirmware() BSLSize = 0x0
[   17.518084] saa7164_downloadfirmware() Reserved = 0x0
[   17.518085] saa7164_downloadfirmware() Version = 0x1661c00
[   24.396922] saa7164_downloadimage() Image downloaded, booting...
[   24.501486] saa7164_downloadimage() Image booted successfully.
[   27.220221] saa7164_downloadimage() Image downloaded, booting...
[   29.086382] saa7164_downloadimage() Image booted successfully.
[   29.136008] tveeprom 6-0000: audio processor is SAA7164 (idx 43)
[   29.136009] tveeprom 6-0000: decoder processor is SAA7164 (idx 40)
[   29.136011] saa7164[0]: Hauppauge eeprom: model=88061
[   29.887825] DVB: registering new adapter (saa7164)
[   29.887831] saa7164 0000:02:00.0: DVB: registering adapter 0 frontend 0 (Samsung S5H1411 QAM/8VSB Frontend)...
[   32.832640] DVB: registering new adapter (saa7164)
[   32.832646] saa7164 0000:02:00.0: DVB: registering adapter 1 frontend 0 (Samsung S5H1411 QAM/8VSB Frontend)...
[   32.832982] saa7164[0]: registered device video0 [mpeg]
[   33.063193] saa7164[0]: registered device video1 [mpeg]
[   33.274041] saa7164[0]: registered device vbi0 [vbi]
[   33.274065] saa7164[0]: registered device vbi1 [vbi]

Hope this helps.
Comment: Excuse me, steventoth site appears to be down. Any chance you could host those files somewhere else? Thanks!
Answer: Great answers, I was also having issues with the card working after suspend.  I found if I remove the device prior to suspending and restore after suspend, all is good.  This can be done as follows:
Add file in /etc/pm/sleep.d/06_saa7164  ( make executable )
##!/bin/sh
## Fix some issues with mythtv

if [ "$1" = "suspend" ]
then
    stop mythtv-backend
    sleep 2
    modprobe -r saa7164
fi
if [ "$1" = "resume" ]
then
        modprobe saa7164
        sleep 2
        start mythtv-backend
fi

I struggled with this for quite a while,  hope it help.


For what values do these parametric equations draw a circle in the clockwise direction?

Question: So I've got this set of parametric equation on the x-y plane
$x=cos(ln(5t))$
$y=sin(ln(5t))$
for $t>0$. I need to find the range of values for which the circle is drawn in the clockwise direction. Initially I tried for values where $t>0.2$ and $0>t>0.2$, but neither of these worked. I also tried for t values within $\displaystyle\frac{1}{5}e^\frac{\pi}{2}$ and $\displaystyle\frac{1}{5}e^\frac{3\pi}{2}$, but these didn't work either.
Answer: Sine and cosine trace out the unit circle when the parameter varies from $0$ to $2\pi$. What values of $t$ make $\ln(5t)$ equal $0$ and $2\pi$?
Comment: neither  for $t<0.2$, $t>0.2$, nor $t<\frac{1}{5}e^({2\pi})$, $t>\frac{1}{5}e^(2\pi)$ works.


Prove $R$ is not homeomorphic to $R^n$ with usual topology by using clopen set.

Question: Attempt:
Subspace of $R$ by removing a point has nontrivial clopen set, but Subspace of $R^n$ by removing a point has no clopen set. Since has clopen set is a topological invariant, the two subspace is not homeomorphism. So the original spaces are not homeomorphic.
But I cannot figure out why subspace of $R^n$ by removing a point has no nontrivial clopen set. Any help? Thanks.
The question not allows to specially use the definition of connected. Or it only allows to use that having no nontrivial clopen set is topological invariant. (Although having no nontrivial clopen set implies connected...)
Comment: You certainly mean "not homeomorphic" and $n > 1$.
Comment: Thanks, should be not.
Comment: I'm confused. In the body of your question you ask for help in showing that $\mathbb R^n$ minus a point is connected, but the title asks us not to use connected. How do you expect us  to prove that something is connected without using the concept of connectedness? Or did you mean something else by "without using connected"?
Comment: I mean do not specially use connected, since I think there are other way to show a certain space is connected without using clopen set. In this question it requires only to use clopen set. Or I should say only use clopen set to prove connected.
Comment: This is a very confusing question.
Comment: Inasmuch as "has no nontrivial clopen set" is the definition of what it means for a space to be connected, I can't imagine what it would mean to prove that something has no nontrivial clopen set without proving that it's connected.
Comment: @bof I think that the question is asking to avoid the use of (path connected $\Rightarrow$ connected).
Answer: First, your question is somewhat misleading:
The condition that you're asking for is equivalent to connectedness.  In particular, a space $X$ is disconnected if there exist nonempty open sets $U$ and $V$ so that $X=U\cup V$ and $U\cap V=\emptyset$.  Moreover, if $W$ is a nontrivial clopen set, then $W$ and $W^c$ are both open, $X=W\cup W^c$, and $W\cap W^c=\emptyset$.  Therefore, they form a separation of $X$.  Hence, by asking for a nontrivial clopen set, you are asking for a separation and using the definition of disconnected.
What I think that you are asking is to avoid the implication path connected implies connected.  So, to prove that $\mathbb{R}^n$ is connected without going through path connected.
Suppose that $\mathbb{R}^n\setminus\{0\}$ has a nontrivial clopen set $X$.  Then, since $\mathbb{R}^n\setminus\{0\}$ has the induced topology, there is an open set $U$ in $\mathbb{R}^n$ and a closed set $D$ in $\mathbb{R}^n$ so that $U\cap \mathbb{R}^n\setminus\{0\}=X$ and $D\cap\mathbb{R}^n\setminus\{0\}=X$.  We note that $U$ and $D$ only differ by a single point $\{0\}$ since their intersection with $\mathbb{R}^n\setminus\{0\}$ is the same.  Moreover, the two sets must differ because $\mathbb{R}^n$ is connected and has non nontrivial clopen sets.
Let $x\in X$ and let $y\not\in X$.  By perturbing $x$ and $y$ slightly, we may assume that the line $\ell$ though $x$ and $y$ does not include $0$ (since $X$ is clopen, there are small neighborhoods around $x$ in $X$ and around $y$ in in $X^c$).  Then the induced topology from $\mathbb{R}^n$ to $\ell$ produces the standard topology on $\ell\simeq\mathbb{R}$.  We observe that $U\cap \ell=D\cap \ell$, since their only difference is at $0$.  Since $x\in U\cap\ell$ and $y\not\in U\cap \ell$, this defines a nontrivial clopen set in $\mathbb{R}$, which contradicts the fact that $\mathbb{R}$ is connected.
Comment: You can simplify your proof. The sets $U$ and $D$ are not needed. Take your line $\ell$ which avoids $0$. Then $\ell$ is homeomorphic to $\mathbb{R}$ and $\ell \cap X$ is a nontrivial clopen subset of $\ell$ which is impossible. However, it seems to me that the argument is just a hidden version of "path-connected" implies "connected" (the connectedness of real intervals is the essence of that implication).
Comment: @PaulFrost I agree with both of your comments.  If I suppress the sets $U$ and $D$, they are still there behind the scenes since all the topologies are induced.  From the OP's question, I thought that a little bit more detail would be helpful for instructive purposes.


How complicated is the theory of $\mathbb Q_p$?

Question: Let $p=7$, say.  How complex is the theory of the field $(\mathbb Q_p,0,1,+,\cdot)$ ?  One extreme would be that the theory is like $\mathbb R$: decidable

... admits quantifier elimination, is o-minimal.  Do I need to include $\;<\;$ for $\mathbb R$ for these?  Or is it enough that $<$ is definable in $(\mathbb R, 0,1,+,\cdot)$ ?

The other extreme would be that $\mathbb Z$ is definable in $\mathbb Q_p$, so the theory is as complex as the theory of $\mathbb Z$.

I thought of this when reading a recent question, asking whether $\mathbb C$ and $\mathbb C_p$ admit a Borel-measurable isomorphism.
Comment: this theory is in fact [NIP](https://en.wikipedia.org/wiki/NIP_(model_theory)), and hence cannot interpret the theory of the ring $\mathbb{Z}$. for some discussion, see Appendix A.2 of Pierre Simon's [book](http://www.normalesup.org/~simon/NIP_guide.pdf) on NIP theories
Answer: There is a strong analogy between the model theory of $\mathbb{R}$ and the model theory of $\mathbb{Q}_p$. Here's a brief history of some of the main results (I've necessarily left a lot out, so I encourage others to edit and add to the list):

In the '60s, the theory of $\mathbb{Q}_p$ was shown to be decidable, independently by Ershov (On the elementary theory of maximal normed fields, 1965) and Ax and Kochen (Diophantine problems over local fields. III. Decidable fields, 1966).
In the '70s, Macintyre proved that the structure $(\mathbb{Q}_p;0,1,+,-,\times,^{-1},V,(P_n)_{n\in \mathbb{N}})$ has quantifier elimination, where $V$ is a unary predicate naming the valuation ring, and each $P_n$ is a unary predicate naming the set of $n^{\text{th}}$ powers. Like $\mathbb{R}$ (and like every non-algebraically-closed field, by another result of Macintyre's - see below for more on this), $\mathbb{Q}_p$ does not have quantifier elimination in the language of rings. (On definable sets of $p$-adic fields, 1976).
In the '80s, Denef proved a cell decomposition theorem for $\mathbb{Q}_p$, analogous to Tarski's cell decomposition for real closed fields. (See The rationality  of the Poincaré  series associated  to  the  p-adic  points  on  a  variety, 1984, and p-adic semi-algebraic sets and cell decomposition, 1986).
In the '90s, Haskell and Macpherson defined a $p$-adic analogue of o-minimality, called "P-minimality" (A version of o-minimality for the p-adics, 1997). They did not obtain a cell decomposition theorem for general P-minimal structures, and since then there have been a number of papers about cell decomposition in the P-minimal setting, usually under additional hypothesis, such as definable Skolem functions.
It follows easily from cell decomposition that the theory of $\mathbb{Q}_p$ is NIP, and this was probably folklore for some time. The dp-rank is a measure of complexity for NIP theories. In the 21st century, Dolich, Goodrick, and Lippel showed that the theory of $\mathbb{Q}_p$ is dp-minimal, meaning that it has dp-rank 1 (dp-minimality: basic facts and examples, 2011). The theory of real closed fields is also dp-minimal, as is any o-minimal theory.

Regarding your side question: most model-theoretic notions are impervious to the exact choice of language, as long as the languages considered are interdefinable. This includes notions like decidability, dp-minimality, and NIP. Characterizations of definable sets, like o-minimality, are mostly language-independent, except that e.g. the definition of o-minimality requires the symbol $<$ to be in the language. On the other hand, quantifier elimination is highly sensitive to the choice of language.
So for $\mathbb{R}$, decidability (and dp-minimality, and NIP) holds in the  language of rings, quantifier elimination does not hold in the language of rings, and it doesn't even make sense to ask about o-minimality in the language of rings.

P.S. Above I alluded to a theorem of Macintyre on fields admitting quantifier elimination. The original reference is On $\omega_1$-categorical theories of fields, 1971, where Macintyre proves that the following are equivalent for infinite fields (in the language of rings):

$K$ is algebraically closed
$\text{Th}(K)$ is $\aleph_1$-categorical
$K$ is totally transcendental ($\omega$-stable)
$\text{Th}(K)$ has quantifier elimination

A simpler argument for the equivalence of (1) and (4) was given by Macintyre, McKenna, and van den Dries in Elimination of quantifiers in algebraic structures, 1983. The main results are the following:

If a field admits quantifier elimination in the language of rings, it is algebraically closed.
If an ordered field admits quantifier elimination in the language of ordered rings, it is real closed.
If a non-trivially valued field admits quantifier elimination in the language of of rings together with a binary relation symbol for $v(x)\leq v(y)$,  it is an algebraically closed valued field.
If a $p$-field (see the paper for the definition) admits quantifier elimination in the Macintyre language described above (with $V$ and $(P_n)_{n\in \mathbb{N}}$), it is $p$-adically closed (elementarily equivalent to $\mathbb{Q}_p$).
Answer: This is not by any means a complete answer, but I'd like to record a few facts that hopefully address at least some of your questions. Fix a prime $p$ and let $T$ denote the complete theory of $\mathbb{Q}_p$ in the language of rings; for convenience, I'll assume that $p$ is odd. (The case when $p=2$ is similar, but some details are a bit different.) Define a formula $\varphi(v)\equiv\exists w[w^2=pv^2+1]$. Rather remarkably, this gives a definition of $\mathbb{Z}_p$ in $\mathbb{Q}_p$; this is a good exercise using Hensel's lemma. So this is immediately enough to tell us that $T$ does not have elimination of quantifiers; indeed, the quantifier-free formulas in $T$ are just Boolean combinations of polynomial equations, so every quantifier-free definable subset of $\mathbb{Q}_p$ is either finite or cofinite. Since $\mathbb{Z}_p$ is neither, we cannot have QE in the pure language of rings.
There are however several natural ways of enriching the language to obtain QE. For example, the following is due to Angus Macintyre. Let $L_{\text{mac}}$ be the union of the language of rings with a predicate symbol $\mid$ and predicate symbols $P_n$ for each $n\in\omega$. Let $v$ be the valuation on $\mathbb{Q}_p$, and realize $\mid$ in $\mathbb{Q}_p$ by taking $a\mid b$ to hold if and only if $v(a)\leqslant v(b)$; further realize each $P_n$ in $\mathbb{Q}_p$ by taking $P_n(a)$ to hold if and only if $a$ is an $n$-th power. Then, by a theorem of Macintyre's, $\mathbb{Q}_p$ admits elimination of quantifiers in the language $L_{\text{mac}}$. With some work, one can use this QE result to show that $T$ has something called the "no independence property", aka NIP. If you are unfamiliar with this notion, it is basically a kind of "tameness" condition, prohibiting the existence of certain "bad" combinatorial configurations within models of $T$. In particular, no NIP theory can interpret an IP theory. The theory of the ring $\mathbb{Z}$ has IP, so this fact is enough to show that $\mathbb{Z}$ is not only not definable in $\mathbb{Q}_p$, but also not even interpretable in $\mathbb{Q}_p$.
Okay, if I'm not misunderstanding, you then ask whether $\mathbb{Q}_p$ might be o-minimal. This is a bit of a "type error", as o-minimality is something that applies to totally ordered structures. I don't know of any "natural" total ordering on $\mathbb{Q}_p$, and, in contrast with $\mathbb{R}$, there certainly does not exist an ordering on $\mathbb{Q}_p$ compatible with the field structure; for example, $1-p$ admits a square root in $\mathbb{Q}_p$. There is however a generalization of o-minimality called dp-minimality, and it apparently is the case that $T$ is dp-minimal; I am not familiar with dp-minimality, so perhaps someone on the site who has more experience with that notion could provide further insight.
Finally, let me just give a few references for further reading. Disclaimer: the model theory of valued fields is a very deep field, and I only know a small amount of it. Here and here are some notes of David Marker and Zoe Chatzidakis, and Alex Kruckman's undergraduate thesis gives a very nice exposition of the Ax-Kochen theorem. Finally, if you are interested in learning about things like NIP theories in the context of valued fields, you may want to check out Appendix A.2 of Pierre Simon's book on NIP theories, which gives an overview of many of the things I discuss above. Enjoy!
Comment: I think our answers complement each other well! Just an additional comment on the question of whether the $p$-adics could be o-minimal under some ordering: a strong negative answer is given by a theorem of Pillay (https://doi.org/10.1016/0022-4049(88)90125-9) that every field definable in an o-minimal structure is real closed or algebraically closed.
Comment: Every *infinite* field, that is!
Comment: @AlexKruckman oh fantastic, that's a very nice theorem!! I was also going to ask about the theorem of Macintyre's that you mention in your answer – that an infinite field has QE if and only if it is algebraically closed. what's the original reference for that? it's a wonderful result!
Comment: I've edited my answer to include some more details about Macintyre's theorem.


React native, Image not showing

Question: so I'm very new to react native and I'm trying to create a FlashList. Seems to work fine with most elements but my images aren't really playing along.
Seems like the FlashList is importing the image styling since it's creating space for the height and width I've declared but no Image is showing, it's simply blank.
Appreciate some help!
Expo App (How it looks)
My Code:
import React from "react";
import { Text, StyleSheet, Image, View } from "react-native";
import { FlashList } from "@shopify/flash-list";

const ListScreen = () => {
  const Trips = [
    {
      id: 1,
      Place: "Tuscany",
      TripLength: "4 days",
      description: "A trip to a WineCountry",
      image: require("../../assets/Tuscany.jpg"),
    },
    {
      id: 2,
      Place: "Venice",
      TripLength: "7 days",
      description: "A trip to a floating city",
      image: require("../../assets/Venice.jpg"),
    },
    {
      id: 3,
      Place: "Rome",
      TripLength: "3 days",
      description: "A trip back in time",
      image: require("../../assets/Rome.jpg"),
    },
    {
      id: 4,
      Place: "Paris",
      TripLength: "8 days",
      description: "Drink wine under the Eiffel Tower",
      image: require("../../assets/Paris.jpg"),
    },
    {
      id: 5,
      Place: "Aix-enProvence",
      TripLength: "14 days",
      description: "A city of thousand fountains and lavender gardens",
      image: require("../../assets/Aix-en-Provence.jpg"),
    },
  ];

  return (
    <FlashList
      data={Trips}
      renderItem={({ item }) => (
        <View>
          <Text>{item.Place}</Text>
          <Text>{item.TripLength}</Text>
          <Text>{item.description}</Text>
          <Image style={styles.image} Source={item.image} />
        </View>
      )}
    />
  );
};

const styles = StyleSheet.create({
  text: {
    fontSize: 20,
    marginTop: 10,
  },
  place: {
    fontSize: 18,
  },
  TripLength: {
    fontSize: 12,
  },
  description: {},
  image: {
    height: 500,
    width: "100%",
  },
});

export default ListScreen;

You can see in the code what I tried and I expected the image to show. But I can't figure out what's missing.
Answer: You made a very minor mistake. Source should be source. I also added a resizeMode="contain" to stop the image from exceeding its container's width/height link:
 return (
    <FlashList
      data={Trips}
      renderItem={({ item }) => (
        <View>
          <Text>{item.Place}</Text>
          <Text>{item.TripLength}</Text>
          <Text>{item.description}</Text>
          <Image style={styles.image} source={item.image} resizeMode="contain"/>
        </View>
      )}
    />
  );
};

React native, Image not showing


Is F1-F12 the same for every keyboard/language

Question: I have little tooltip graphics, each with a picture of a keyboard shortcut. Sometimes, the picture is a F5, a F10, etc.
I was wondering (for accessibility reasons) if everyone has a keyboard with "F" shortcuts. Maybe in some other language it's C1, C2, ..., C12.
What about Ctrl, Cmd, Esc, etc. ?
Comment: I disagree: This is a UX issue. The question is basically: "Does displaying a specific piece of terminology negatively impact the usability of the site?" which is a valid question.
Comment: I suggest you read about the difference between key-codes and char-codes. Not really a UX issue, btw.
Comment: While I was studying abroad in Japan, I noticed that the `F1-12` keys were labeled as such. From some brief image searching on google, it seems that any keyboard that contains the function keys has them labeled as `f1-12`.
Comment: I read that you tag it as accessibility issue so I would ask to you a simple thing off-topic:
These images have the method Title in its  tag?
If not this is an issue for blind persons!
Answer: It's not really depending on the language layout, but more to the computer system you are using. Here's a list of computer systems and their relation to function keys:
http://en.wikipedia.org/wiki/Function_key
I think that on a regular Windows PC you can safely assume that the function keys are there.
Answer: Function is such a common "international" word, that it's always begins with F, even in such a strange language, like Hungarian: it's funkció, where the accented o is a long o (ooh). Alt is the same story. Ctrl is also common, in Hungarian keyboard, it's Ctrl too, but Germans use Strg for Ctrl.


Is there an alternative to the for loop when looping through DOM elements

Question: I recently read that many developers have stopped using the for loop, it seems that I'm wrong in using it all the time.
I did a bit of research and it seems that methods like map are quicker to write. Whilst I need to work through all the available array methods, a method to do the following I can't find.
Say we have a bunch of quotes and we want to create something with them
var quotes = document.getElementsByTagName('blockquote');

for(var i = 0; i < quote.length; i++){
  console.log(quotes[i])
}

Is there a way to do this without the for loop
Comment: Using for loop is not an evil thing.
Comment: @RajaprabhuAravindasamy the `.querySelector()` function returns a NodeList, and that's not a native JavaScript iterable type. You could do that if you used `Array.from()` to build a JavaScript array from the NodeList.
Comment: @RajaprabhuAravindasamy: [nodelists are not yet iterable](http://stackoverflow.com/q/30836289/1048572)
Comment: @RajaprabhuAravindasamy [MDN has a list](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#Builtin_iterables). Anybody can define an iterable type however.
Comment: what are you planning to do?
Comment: `for (var quote of document.getElementsByTagName('blockquote')) console.log(quote)` or `[].forEach.call(document.getElementsByTagName('blockquote'), console.log, console)` would be alternatives for what you are doing here.
Comment: @Bergi I was about to suggest spread operator to OP. But while checking(`[...document.querySelector(".something")]`) it with nodeList, it is throwing an error. Can't we use spread operator at this context?
Comment: @DanielA.White nothing, I just read a comment that said most developers no longer use the `for` loop, so I wanted to know if there is an alternative for this use case.
Comment: See also [Alternative for `[].forEach.call(…)` in ECMAScript6](http://stackoverflow.com/q/30342742/1048572)
Comment: @Pointy Where can i find the list of javascript iterable typed objects? It would be useful for me when using spread operator.
Comment: @relidon everything has a place including the for loop
Comment: @DanielA.White My problem was, when I read that the commenter rarely used the `for` loop. I thought "what? But I always use it!" then I searched and found a bunch of methods that do what the `for` loop does but with less code. Then I asked this question because I thought just as I didn't know about `map`, `filter` and a bunch  of other methods, there might be one for this specific problem.
ps - thanks to all for the clarifications
Answer: You could use Array.from() with array.prototype.forEach():
Array.from( document.querySelectorAll('blockquote') ).forEach(function(quote) {
    console.log( quote );
});

But this is, effectively, a personal choice and entirely a matter of preference.


Mysql stopped suddenly and cannot be restarted

Question: Here is what /var/log/mysql/error.log says
[ERROR] /usr/sbin/mysqld: unknown option '--mysql/'
Full log: http://pastebin.com/hhUY2LXi
Mysql config: http://pastebin.com/cNMux19T
Command to start mysql: sudo service mysql start
Any ideas or debugging steps will realy help
Comment: How are you starting the MySQL daemon?
Comment: `sudo reboot` will solve your problem
Comment: sudo service mysql start
Comment: You can't just solve every problem by rebooting it.
Comment: Tried rebooting. Didn't work. Any other ideas?
Answer: So it turns out that there was an long running process which filled up ram cache.
I ran sudo sysctl -w vm.drop_caches=3 and i was able to restart mysql


Replacing a double wall switch and I am confused by the wiring

Question: I am replacing a double set of single pole wall switches. One switch controls a ceiling fan and another controls the fan lighting.
There are 4 runs of romex terminating in the box, 1 from the fan/light and the other three from other parts of the circuit.
The fan switch has the black wire from the fan stabbed at the top of the switch and at the bottom there are two black wires, one is stabbed in and the other is stripped in the middle, wrapped around the terminal screw and then run to the other switch.
The light switch has the red wire from the fan's light fixture stabbed at the top and at the bottom the black wire from the other switch is stabbed in and the third black wire is hooked to the screw.
Does this make sense? Why would the electrician have run the black to one switch and then the other?
I cannot use the backstabs in the replacement switches as they don't accept 12 gauge wire. I had a couple of ideas on how to rewire these:

Use an Ideal In-Sure 5 port connector and run two pigtails one to each switch terminal. These don't seem to be sold at home stores and they are quite pricey.
Using an Ideal In-Sure 4 port connector connect the 3 hot wires and a single pigtail which would run to an Ideal In-Sure 3 port connector where two pigtails would then run one to each switch terminal.

Neither of these options seem like great ideas, can anyone provide some advice?
Answer: Whoever wired this was trying to cheap out on wire nuts and pigtails in a sloppy/cheap way instead of doing a proper pigtailing job -- "through wiring" a terminal screw like that is not considered proper workmanship and also violates the device's listing.
What I would do is use a 6-port push-in type connector (Ideal In-Sure, Wago connector, or equivalent device) as the unused port is finger safe, and then pigtail to each switch terminal.  (The 6-port type seems to be much more commonly stocked than the 5-port is.)


Can I cancel a queued batch?

Question: I queued up a batch, but after finishing the pervious one, one of my employees levelled up. I chose to improve her craft stat, and I don't want it to go to waste.
Can I cancel that batch and make a new one?
Answer: You can't just cancel a queued batch. You can, however, do one of the following:

Any time before the batch begins to brew, you can queue up a different batch and replace the originally queued batch.
When you have nothing brewing but something is queued (such as when your holding area is full), you can fire an employee to cancel the batch.

With either workaround, any ingredients purchased but unused will remain in your inventory.

Can I cancel a queued batch?


Insert and update doesn't change database (sdf)

Question: I have a problem with saving data to database named Settings.sdf. I have few files:
- Settings.sdf
- SettingsDataSet.xsd
 - SettingsDataSet.Designer.cs
 - SettingsDataSet.xsc
 - SettingsDataSet.xss

If I tried use UPDATE or INSERT INTO queries I would not update my database (Settings.sdf), only change data in cache file (whatever and wherever it is). I'm using correctly all SqlCeCommands. For example:
string conString = "Data Source=Settings.sdf";
con = new SqlCeConnection(conString);
con.Open();
...
using (SqlCeCommand com = new SqlCeCommand("UPDATE Settings SET [Value] = (@loc) WHERE [Key] = 'Location'", con))
{
    com.Parameters.AddWithValue("@loc", device.Location);
    com.ExecuteNonQuery();
}
...
con.Close();

How manage this problem? Why this command doesn't update directly my database?
Answer: You can adjust your database path, you must set full path:

Adjust with:
string conString = "Data Source=" + Path.Combine(Your full path,"Settings.sdf");`

Add ; at the end of your query

using (SqlCeCommand com = new SqlCeCommand("UPDATE Settings SET [Value] = (@loc) WHERE [Key] = 'Location';", con))
{
...
}

Comment: add ; in the end of your query
Comment: I'm using WPF so it's bad to add Windows.Forms references. I can't use Application.StartupPath. The ';' at the end of the query is not necessery, but I've tried to use it and still nothing.
Comment: I have the same problem, but I added `;` and `using (SqlCeCommand com = new SqlCeCommand("UPDATE Settings SET [Value] = (@loc) WHERE [Key] = 'Location';", con))
{
...
}` but It doesn't work... Another idea?
Answer: the changed maded in the sdf file in debug directory but when you run again the sdf will be created again, remove the create always and test again