How do you UDP multicast in Python?

Question: How do you send and receive UDP multicast in Python? Is there a standard library to do so?
Answer: This works for me:
Receive
import socket
import struct

MCAST_GRP = '188.8.131.52'
MCAST_PORT = 5007
IS_ALL_GROUPS = True

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
if IS_ALL_GROUPS:
    # on this port, receives ALL multicast groups
    sock.bind(('', MCAST_PORT))
else:
    # on this port, listen ONLY to MCAST_GRP
    sock.bind((MCAST_GRP, MCAST_PORT))
mreq = struct.pack("4sl", socket.inet_aton(MCAST_GRP), socket.INADDR_ANY)

sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)

while True:
  # For Python 3, change next line to "print(sock.recv(10240))"
  print sock.recv(10240)

Send
import socket

MCAST_GRP = '22.214.171.124'
MCAST_PORT = 5007
# regarding socket.IP_MULTICAST_TTL
# ---------------------------------
# for all packets sent, after two hops on the network the packet will not
# be re-sent/broadcast (see https://www.tldp.org/HOWTO/Multicast-HOWTO-6.html)
MULTICAST_TTL = 2

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, MULTICAST_TTL)

# For Python 3, change next line to 'sock.sendto(b"robot", ...' to avoid the
# "bytes-like object is required" msg (https://stackoverflow.com/a/42612820)
sock.sendto("robot", (MCAST_GRP, MCAST_PORT))

It is based off the examples from http://wiki.python.org/moin/UdpCommunication which didn't work.
My system is...
Linux 2.6.31-15-generic #50-Ubuntu SMP Tue Nov 10 14:54:29 UTC 2009 i686 GNU/Linux
Python 2.6.4
Comment: For mac os x you need to use the socket.SO_REUSEPORT option as an alternative to socket.SO_REUSEADDR in the above example, to permit multiple listeners on the same multicast port address combination.
Comment: @RandallCook: When I replace '' by MCAST_GRP I get
socket.error: [Errno 10049] The requested address is not valid in its context
Comment: for udp multicast you need to bind to multicast group/port not the local group port, `sock.bind((MCAST_GRP, MCAST_PORT))`, your code might and might not work, it may not work when you have multiple nics
Comment: For sending, i also needed "sock.bind((, 0))" because my multicast listener was bound to a specific adapter.
Comment: @atikat : Thanks!! Although why do we need this on the MAC but not on Ubuntu ?
Comment: @stefanB makes a great point. As it stands, the code `sock.bind(('', MCAST_PORT))` will receive messages on *ALL* groups on that port, not just the group being joined. Replace `''` with `MCAST_GRP` to receive only from that group. I'll add a comment to the code to make this more prominent.
Comment: Do you maybe know an answer to the question over [here](https://stackoverflow.com/questions/35876323/netlink-multicast-in-kernels-above-4)?
Comment: If you want to use a specific address for the mreq interface instead of `socket.INADDR_ANY`, the format string for `struct.pack` is `4s4s`.
Comment: python 3 needs `struct.pack("4sl", socket.inet_aton(MCAST_GRP), socket.INADDR_ANY)` (struct.pack has evolved and is less permissive)
Comment: Not works when from two pcs within a same local area network. Not yet figure out why.
Comment: I have created a gist and added two command-line arguments: https://gist.github.com/knotman90/3a970484b97bb6e42ad7db606b881178
Answer: Multicast sender that broadcasts to a multicast group:
#!/usr/bin/env python

import socket
import struct

def main():
  MCAST_GRP = '188.8.131.52'
  MCAST_PORT = 5007
  sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
  sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 32)
  sock.sendto('Hello World!', (MCAST_GRP, MCAST_PORT))

if __name__ == '__main__':
  main()

Multicast receiver that reads from a multicast group and prints hex data to the console:
#!/usr/bin/env python

import socket
import binascii

def main():
  MCAST_GRP = '184.108.40.206'
  MCAST_PORT = 5007
  sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
  try:
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  except AttributeError:
    pass
  sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 32)
  sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_LOOP, 1)

  sock.bind((MCAST_GRP, MCAST_PORT))
  host = socket.gethostbyname(socket.gethostname())
  sock.setsockopt(socket.SOL_IP, socket.IP_MULTICAST_IF, socket.inet_aton(host))
  sock.setsockopt(socket.SOL_IP, socket.IP_ADD_MEMBERSHIP,
                   socket.inet_aton(MCAST_GRP) + socket.inet_aton(host))

  while 1:
    try:
      data, addr = sock.recvfrom(1024)
    except socket.error, e:
      print 'Exception'
    else:
      hexdata = binascii.hexlify(data)
      print 'Data = %s' % hexdata

if __name__ == '__main__':
  main()

Comment: you need to bind to multicast group/port not local port on multicast address, `sock.bind((MCAST_GRP, MCAST_PORT))`
Comment: I tried this, it did not work. In Wireshark I can see the transmit, but I don't see any IGMP join stuff and I don't receive anything.
Comment: This example doesn't work for me, for an obscure reason. Using socket.gethostbyname(socket.gethostname()) to select the interface doesn't always elect the external interface - in fact, on debian systems, it tends to select the loopback address. Debian adds an entry of 127.0.1.1 in the host table for the hostname.

Instead, it is more effective to use socket.INADDR_ANY , which the higher ranking answer uses through the 'pack' statement ( which is more correct than the '+' ). Also, the use of IP_MULTICAST_IF is not required, as the higher ranking answer correctly states.
Comment: @BrianBulkowski there are many programmers who use socket.INADDR_ANY, to the great woe and consternation of those of us with multiple interfaces, that need the multicast data to come on a particular interface. The solution is not socket.INADDR_ANY. It is to select the proper interface by IP address, however you think is best (a config file, asking the end user, however you choose for your application's needs). socket.INADDR_ANY will get you the multicast data, true, and is easiest if you a assume a single-homed host, but I think it's less correct.
Comment: @MikeS while I agree with you in some principle, the idea of using IP addresses to select interfaces is terribly, terribly fraught. I know the problem well, but in a dynamic world, and IP address isn't the answer. So you need to write code that iterates everything and chooses by interface name, looks at the interface name, picks out the current IP address, and uses that. Hopefully, the IP address hasn't changed in the meantime. I wish that Linux/Unix had standardized on using interface names everywhere, and the programming languages had, that would make a config file more sensible.
Comment: @BrianBulkowski if the IP address has changed in the meantime you are probably not in a corporate environment with static IPs on multiple interfaces and hundreds of servers. Maybe you're on a laptop with a wireless and LAN interface, I don't know. But the fact is, INADDR_ANY can be a big problem, and we have to fix software that specifies it because you really don't want your multicast data to come in on a 1Gig interface if you need it on a 10Gig interface. Programmers who paint with a wide brush, assuming that the system is unknowable or uncontrolled, are the bane of my existence.
Comment: ...anyway, future generations who study this problem should understand all facets of the situation, which ultimately is my point. INADDR_ANY *may* get you what you want. Then again, it may not. Know your systems and your use case, and please be kind to your systems administrator who may spend a number of long and painful hours debugging these situations.
Comment: Do we need to edit the receiver so that the last two lines of the 'except' block are moved to the 'try' block? Seems like as-is the receiver has no output at all.
Answer: Better use:
sock.bind((MCAST_GRP, MCAST_PORT))

instead of:
sock.bind(('', MCAST_PORT))

because, if you want to listen to multiple multicast groups on the same port, you'll get all messages on all listeners.
Answer: In order to Join multicast group Python uses native OS socket interface. Due to portability and stability of Python environment many of socket options are directly forwarded to native socket setsockopt call. Multicast mode of operation such as joining and dropping group membership can be accomplished by setsockopt only.
Basic program for receiving multicast IP packet can look like:
from socket import *

multicast_port  = 55555
multicast_group = "126.96.36.199"
interface_ip    = "10.11.1.43"

s = socket(AF_INET, SOCK_DGRAM )
s.bind(("", multicast_port ))
mreq = inet_aton(multicast_group) + inet_aton(interface_ip)
s.setsockopt(IPPROTO_IP, IP_ADD_MEMBERSHIP, str(mreq))

while 1:
    print s.recv(1500)

Firstly it creates socket, binds it and triggers triggers multicast group joining by issuing setsockopt. At very end it receives packets forever.
Sending multicast IP frames is straight forward. If you have single NIC in your system sending such packets does not differ from usual UDP frames sending. All you need to take care of is just set correct destination IP address in sendto() method.
I noticed that lot of examples around Internet works by accident in fact. Even on official python documentation. Issue for all of them are using struct.pack incorrectly. Please be advised that typical example uses 4sl as format and it is not aligned with actual OS socket interface structure.
I will try to describe what happens underneath the hood when exercising setsockopt call for python socket object.
Python forwards setsockopt method call to native C socket interface. Linux socket documentation (see man 7 ip) introduces two forms of ip_mreqn structure for IP_ADD_MEMBERSHIP option. Shortest is form is 8 bytes long and longer is 12 bytes long. Above example generates 8 byte setsockopt call where first four bytes define multicast_group and second four bytes define interface_ip.
Answer: Have a look at py-multicast. Network module can check if an interface supports multicast (on Linux at least).
import multicast
from multicast import network

receiver = multicast.MulticastUDPReceiver ("eth0", "184.108.40.206", 1234 )
data = receiver.read()
receiver.close()

config = network.ifconfig()
print config['eth0'].addresses
# ['10.0.0.1']
print config['eth0'].multicast
#True - eth0 supports multicast
print config['eth0'].up
#True - eth0 is up

Perhaps problems with not seeing IGMP, were caused by an interface not supporting multicast?
Answer: Just another answer to explain some subtle points in the code of the other answers:

socket.INADDR_ANY - (Edited) In the context of IP_ADD_MEMBERSHIP, this doesn't really bind the socket to all interfaces but just choose the default interface where multicast is up (according to routing table)
Joining a multicast group isn't the same as binding a socket to a local interface address

see What does it mean to bind a multicast (UDP) socket? for more on how multicast works
Multicast receiver:
import socket
import struct
import argparse

def run(groups, port, iface=None, bind_group=None):
    # generally speaking you want to bind to one of the groups you joined in
    # this script,
    # but it is also possible to bind to group which is added by some other
    # programs (like another python program instance of this)

    # assert bind_group in groups + [None], \
    #     'bind group not in groups to join'
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)

    # allow reuse of socket (to allow another instance of python running this
    # script binding to the same ip/port)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

    sock.bind(('' if bind_group is None else bind_group, port))
    for group in groups:
        mreq = struct.pack(
            '4sl' if iface is None else '4s4s',
            socket.inet_aton(group),
            socket.INADDR_ANY if iface is None else socket.inet_aton(iface))

        sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)

    while True:
        print(sock.recv(10240))

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--port', type=int, default=19900)
    parser.add_argument('--join-mcast-groups', default=[], nargs='*',
                        help='multicast groups (ip addrs) to listen to join')
    parser.add_argument(
        '--iface', default=None,
        help='local interface to use for listening to multicast data; '
        'if unspecified, any interface would be chosen')
    parser.add_argument(
        '--bind-group', default=None,
        help='multicast groups (ip addrs) to bind to for the udp socket; '
        'should be one of the multicast groups joined globally '
        '(not necessarily joined in this python program) '
        'in the interface specified by --iface. '
        'If unspecified, bind to 0.0.0.0 '
        '(all addresses (all multicast addresses) of that interface)')
    args = parser.parse_args()
    run(args.join_mcast_groups, args.port, args.iface, args.bind_group)

sample usage: (run the below in two consoles and choose your own --iface (must be same as the interface that receives the multicast data))
python3 multicast_recv.py --iface='192.168.56.102' --join-mcast-groups '18.104.22.168' '126.96.36.199' '22.214.171.124' --bind-group '220.127.116.11'
python3 multicast_recv.py --iface='192.168.56.102' --join-mcast-groups '18.104.22.168'
Multicast sender:
import socket
import argparse

def run(group, port):
    MULTICAST_TTL = 20
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
    sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, MULTICAST_TTL)
    sock.sendto(b'from multicast_send.py: ' +
                f'group: {group}, port: {port}'.encode(), (group, port))

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--mcast-group', default='220.127.116.11')
    parser.add_argument('--port', default=19900)
    args = parser.parse_args()
    run(args.mcast_group, args.port)

sample usage:  # assume the receiver binds to the below multicast group address and that some program requests to join that group. And to simplify the case, assume the receiver and the sender are under the same subnet
python3 multicast_send.py --mcast-group '188.8.131.52'
python3 multicast_send.py --mcast-group '220.127.116.11'
Comment: INADDR_ANY does *not* 'choose one of the local interfaces]'.
Answer: To make the client code (from tolomea) work on Solaris you need to pass the ttl value for the IP_MULTICAST_TTL socket option as an unsigned char. Otherwise you will get an error.
This worked for me on Solaris 10 and 11:
import socket
import struct

MCAST_GRP = '126.96.36.199'
MCAST_PORT = 5007
ttl = struct.pack('B', 2)

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, ttl)
sock.sendto("robot", (MCAST_GRP, MCAST_PORT))

Answer: For the Windows programmers out there, the following code snippet works on both Windows and Linux.
Examples that use SOL_IP will cause errors on Windows for Python versions >3.x.12.
Many examples don't include setting IP_MULTICAST_IF.  This can be important for systems with multiple interfaces.  On Windows IP_MULTICAST_IF is required to specify the network interface because Windows cannot bind to the multicast address.
import socket
import platform
from contextlib import closing

address = "22.214.171.124"
port = 6000
network_adapter = "172.16.0.93"

with closing(socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)) as sock:
    # SO_REUSEADDR: allows binding to port potentially already in use
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

    # linux binds to multicast address, windows to interface address
    ip_bind = network_adapter if platform.system() == "Windows" else address
    sock.bind((ip_bind, port))

    # socket.IPPROTO_IP works on Linux and Windows
    # IP_MULTICAST_IF: force sending network traffic over specific network adapter
    # IP_ADD_MEMBERSHIP: join multicast group
    sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_IF, socket.inet_aton(network_adapter))
    sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, socket.inet_aton(address) + socket.inet_aton(network_adapter))

    # send recv examples
    # sock.sendto(b"Hello World", (address, port))
    # data, server = sock.recvfrom(2**8)

Comment: I was discussing this very thing today, I'm glad I saw your post,  I was pushing  for socket.IPPROTO_IP, socket.IP_MULTICAST_IF,  and I didnt have a good argument against using SOL_SOCKET, but you just gave me one, thanks man.
Answer: tolomea's answer worked for me. I hacked it into socketserver.UDPServer too:
class ThreadedMulticastServer(socketserver.ThreadingMixIn, socketserver.UDPServer):
    def __init__(self, *args):
        super().__init__(*args)
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
        self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.socket.bind((MCAST_GRP, MCAST_PORT))
        mreq = struct.pack('4sl', socket.inet_aton(MCAST_GRP), socket.INADDR_ANY)
        self.socket.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)

How do you UDP multicast in Python?


Windows .inf files: how do I set the default Network Connection name during network driver install?

Question: I'm trying to adapt the open source TAP-Win32 driver for my project.
When it installs (at least on Windows 7, and I think Windows XP too) it creates a device named "TAP-Win32 Adapter V9" in the Devices control panel.  This is easy to change by editing the OemWin2k.inf file that comes with it.
However, the device then gets attached to a network in the Windows Networks browser, where it is named by default something like "Local Area Connection 2."  I can easily rename this using the GUI: just click on the network and press F2.
But my problem is this: the network device I'm working on is definitely not a "Local Area Connection", it's actually a virtual network device.  What can I do to make the name by default show up using a more descriptive name of my choosing?
Is there any general documentation about this I should be reading?
Answer: Have you tried the script attached here, it's from Open VPN community and I use it after installation to make everything a little bit nicer.


How can I analyse all the tracks contained in a folder with Traktor 2?

Question: I want to analyse all the tracks contained in a folder with Traktor 2. Using right click on folder (in Traktor's browsing window) + "Analyze (Async)" only analyses tracks located at the root of the folder, and ignore the tracks located in the subfolders. How can I analyse all the tracks contained in a folder?
Comment: Looks like someone else had a similar problem on [this thread](http://www.native-instruments.com/forum/showthread.php?170575-T-Pro-2-Track-Analysis-%28Folders%29). Maybe the suggested solution will help you. I can't really say since I don't use Traktor.
Comment: @Dom Thanks, indeed it seems to be the only solution (I would have preferred not to have to import the tracks). I summarized the thread as an answer and added some screenshots.
Answer: Tested with Traktor 2.6.5 on Windows 7 x64 Ultimate:
Go to Traktor's preferences and check "Analyze news imported tracks".

Then in Traktor's browsing window, go the folder you want to analyze and right-click "Import to Collection". It will analyze all tracks contained in this folder including its subfolders (and recursively):

If anyone knows how to analyse all the tracks contained in a folder without having to import into the collection, please add it as an answer.


How to convert text from double path to single path as shown?

Question: Mainly, I'm using Blender and I think it can't do something like this so I need an extra online tool or something like that. I googled but still can't find what I'm looking for. I would like to convert text to be a single path (vector) like the letter "a" in the picture. How can I achieve something like that for free? I don't need it to be like the letter "H".
Comment: Not going to vote to close as a duplicate (because that would close this immediately)... but there *are* several questions here related to creating center-line, or single-line glyphs. Here's one: https://graphicdesign.stackexchange.com/questions/72043/central-simplified-pen-strokes-of-a-font-glyph
Comment: Note that blender knows how to make the skeleton line of the fobt with a bevel.
Comment: @joojaa great point but I need to animate something along the path of the text so... :)
Comment: @user2824371 manual drawing im afraid.
Answer: Inkscape has an Extension called Hershey Text which can convert text into single stroke letters.
Basically type some text with the text tool, and make sure the text box is selected. Then do Extensions > Text > Hershey Text, and choose one of the 1-stroke fonts.
Example
Answer: You can use the free multi-platform program Inkscape to accomplish your task. It is necessary to save the text as paths in SVG format.

Import the paths and use the stroke/fill tool (Shift-Ctrl-F) to set the stroke width to the desired size. (2nd image)
Use Path, Stroke to Path to convert the outline of the text to independent paths. (3rd image)
Use Boolean (Path, Union) to combine the segments into the final shape.
Image created by me.
Edit for incorrect interpretation of question:
I got your question reversed. What you seek is often called centerline trace. So far, it has been fairly difficult to locate a utility that works well. The newer versions of Inkscape provide for such a feature, but crashes on my computer. It's challenging for any software to manage a single line creation when, for example, the A in position number four has a cross member (which it does). The program is unable to determine how to make a continuous line when there is three directions from a single point.
Perhaps on your computer, the centerline trace extension for Inkscape will not crash.
Comment: Sorry for my english but I think you got my question wrong :) I want to convert the 2nd or the 4th image to the first one. (I need to reverse the process). Thanks anyway for your answer that was helpful too.
Answer: Just import the bitmap to Inkscape, Select the image, Right Mouse Click on Image, Choose "Trace Bitmap". The dialog will flash briefly in the sidebar panels.
I have included a screenshot of the GUI of the "Trace Bimap" Dialog. With the default settings enabled, a result was acquired: SVGshare link
autotrace in Inkscape, GUI:

(Weirdly, the traced image was behind the imported PNG. I had to remove the PNG downwards to unhide the SVG-trace. Or click on the eye symbol (Visibility on/off) in the Layers dialog.

Before I discovered this I tried to install autotrace, it has a <code>--centerline</code>-trace option.  Then you can vectorize your pixel-graphics, from the command-line.
However it was difficult to get the latest release to work properly on Linux. I have installed it from the .deb package, but there were dependency problems.
Recently I've noticed that Inkscape Inkscape 1.1.1 (I have 1:1.1+202109281943+c3084ef5ed for Linux)  comes with autotrace routines built-in (!)
Inkscape even makes the autotrace centerline-tracing option accessible. No need to install autotrace.


Derivation of derangement with inclusion-exclusion

Question: I read many articles on the derivation of the derangement formula but I can't understand them clearly. At first I read the Wikipedia article. I understand the recursive derivation of derangement. But I am interested in understanding the inclusion-exclusion based formula for derangements.
Answer: Suppose we want to count $D_n$, the number of derangements of $\{1,\cdots,n\}$.
Let S be the set of all permutations of $\{1,\cdots,n\}$, and
let $T_i$ be the set of permutations which leave $i$ in its natural position.
Then $D_n=\lvert T_1^c\cap\cdots\cap T_n^c\rvert$
$=\lvert S\rvert-\sum_{i}\vert T_i\rvert+\sum_{i<j}\lvert T_i\cap T_j\rvert-\sum_{i<j<k}\lvert T_i\cap T_j\cap T_k\rvert+\cdots+(-1)^n\lvert T_1\cap\cdots\cap T_n\rvert$
$=n!-\binom{n}{1}(n-1)!+\binom{n}{2}(n-2)!-\binom{n}{3}(n-3)!+\cdots+(-1)^n\binom{n}{n}(n-n)!$
$=\displaystyle n!-\frac{n!}{1!}+\frac{n!}{2!}-\frac{n!}{3!}+\cdots+(-1)^n\frac{n!}{n!}=n!\left[1-\frac{1}{1!}+\frac{1}{2!~}-\frac{1}{3!}+\cdots+(-1)^n\frac{1}{n!}\right].$
Comment: I couldn't understand it completely. I am familiarized with these notations but what is the meaning of the notations .
Comment: Let me know which notation you would like me to explain further, and I'll try to do that.
Comment: Straightforward method! +1


Extract field from content type in View and have it appear as a block next to appropriate node

Question: I need to pull a field from a content type and have it appear as a view in the sidebar next to the node it belongs to. I can't figure out what parameter to use in Views to indicate that my view block should appear by the node it was extracted from. Maybe something to do with relationships?
Answer: This can be done with contextual filters.

Set up the view to display whatever information you need; put the view in a block that only displays on the page for that content type
Add a contextual filter, selecting a field that contains the NID.  For example, this could be content: nid
For "when filter is not available" select "provide default value", then "content ID from URL"

After doing this, the view will only display the single result, where the NID field matches the NID of the node currently being viewed.
Comment: Thank you, it does seem to work, however it displays the view even when it is empty. Is there a way to work around that?
Comment: This is a side effect of the contextual filter.  There are a variety of ways to work around this; the best is to set the block itself to display only on the desired content page.  Another solution is to add another contextual filter for "This Block (Override)" using global: null, hide view when filter is not available.  Alternatively, you can set 'no results behavior' in the view 'advanced' settings to display a placeholder when there are no results.


What type of paint is best for an exterior door?

Question: This is a question about types of paints and their best applications, but more specifically about the best type of paint for an exterior door. Some context: I have a wood core exterior door that appears to be wrapped with a type of hard plastic (see photos). I found a can of paint in the garage that the last owner used to paint the metal door that preceded the current door. The can was specifically labeled as an enamel for exterior doors. Based on this, I assumed that there is indeed a special paint formulated to meet the demands of an exterior door, i.e. heavy use and traffic, movement of the painted material, exposure to the elements. Yet when I inquire with the paint department of a big box store I get puzzled looks and the reply is that most any exterior paint will work. Is this true? Or is there a best paint that will give me the best durability?
Comment: Alkyd paint (oil paint) cures in a week, whereas water based paint cures in a month. I suppose they're both more vulnerable to damage during the curing period, so that would make the alkyd paint superior. My expectation is that the prep work makes or breaks this work more than the cure time, though. Sand or at least degrease, prime, and paint.
Answer: A high quality gloss finish paint will give you the best durability. Whether a water-based or alkyd paint is "better" is a long-standing point of contention that I will not address beyond my points below, except that to mention that thinners/solvents for oil paints seem to have gotten very expensive, along with all the other extra work when using oils.

there are differences between "budget" paint and high quality paint. You don't mention color but for light colors, higher quality paints tend to have better hiding/coverage due to higher pigment (titanium dioxide) content. If a manufacturer elects not to reveal the pigment percentage on the can, one can often get an comparative idea by the weight compared to competing brands. They also tend to have higher-quality carrier (solvent) formulae as well as anti-fungal and flow-enhancing additives.
for water based finishes you should choose acrylic paint, preferably 100% acrylic if available.

As always (and as likely mentioned by others) surface preparation and use of high quality applicators will make a huge difference regardless of the paint.
Comment: Extra note- I would **not** recommend a polyurethane paint for that door. Polyurethane paints cure to a very hard finish that may crack due to expansion of the PVC cladding with temperature changes.
Answer: What you have looks to be a PVC clad door.
Most exterior paint will work on "most" exterior doors.  However metal clad doors would benefit from paint formulated for metal, such as an oil based enamel.
In your situation, you need to look for a paint suitable for a PVC clad door.
If you ask for paint for an exterior door, you will be presented with exterior grade paint.  Be specific and ask for an exterior paint that will be suitable for a PVC clad door. You may be better served looking in a paint store rather than big box.
In any event you will need to thoroughly clean the door and lightly scuff it with a light pad.  Whether or not you need primer will be under the advice of the paint store and the paint they recommend.


Dot notation for group extensions

Question: I came across the notation $A.B$ in many occassions while reading papers in Group Theory. However, I have not yet found any description of what this notation is supposed to mean. From context I suppose it means that if $G=A.B$, then $G$ is a solution to the extension problem $1\rightarrow A\rightarrow G\rightarrow B\rightarrow 1$, and the extension is not necessarily split. Is this the right way to interpret this symbol? In that case I suppose it would be useful in cases where the analysis does not depend on the particular extension.
Comment: @DietrichBurde but there is no $G$ specified enveloping both $A$ and $B$ in general. I could take $G$ to be $A\rtimes B$ (assuming I have some action of $B$ on $A$) or $A\times B$ and $G=AB$ in both cases. My question is more specifically if there are any assumptions on the way you glue $A$ and $B$ together when you write $A.B$.
Answer: This is known as ATLAS notation, and it was introduced and widely used in the ATLAS of Finite Groups. It has become a standard notation among (particularly finite) group theorists, and it is very concise and useful, but it should be used with care.
In fact you have guessed the meaning correctly. If $A$ and $B$ are groups (or isomorphism types of groups), then $A.B$ means any group with normal subgroup isomorphic to $A$ with corresponding quotient group isomorphic to $B$.
There are refinements. For example $A:B$ denotes a split extension, and you would normally use $A \times B$ if you knew that it was a direct product, but just writing $A.B$ does not imply that it is not split or a direct product, it probably just means that you do not know or care.
Other conventions include using a number to denote a cyclic group of that order (as in $3.A_6$or $A_5.2 = S_5$), or a number like $[12]$ in square brackets to denote an unspecified group of order $12$.
Comment: Thank you very much @Derek Holt for your answer. Indeed, I had also seen the : symbol and knowing its meaning is also really helpful.
Answer: In addition to Derek Holt's answer I am adding here a reference to a webpage by Tim Dokchitser that explains the ATLAS notation
https://people.maths.bris.ac.uk/~matyd/GroupNames/extensions.html
Edit: Thanks to Derek Holt who clarified the difference between the notation $A.B$ in the ATLAS and the page above. In the ATLAS $A.B$ is an arbitrary extension, whereas in the webpage it denotes a non-split extension.
Comment: Unfortunately, what it says on that webpage is not an accurate description of ATLAS notation. It says there that $N.Q$ denotes a non-split extension, whereas in fact it denotes an arbitrary extension. There is a notation $N ^{\large \cdot} Q$ that specifically denotes a non-split extension.

Dot notation for group extensions


If I resurface the engine block, do I have to replace the cylinder heads?

Question: My cars engine (1991 Honda Civic 1.5 liter) had a bad gasket leak and was running without oil for a week causing scoring on the inside of the cylinders. If I resurface the cylinders, is it possible to keep the old cylinder heads and resurface those or would I need to replace them entirely?
Comment: Do the heads have cam shafts with bearings that ran without oil ?
Answer: You should have the heads rebuilt as it highly likely that the lack of oil also caused damage there as well.  While resurfacing may not be needed, the valve guides, cam followers, and camshafts may be damaged and need to be replaced.
Answer: Confusing? You ask if you should resurface the engine block, then cylinders, then head faces…
Cylinders: if scored, they can be machined and honed or just honed if scoring is light.
Heads will only need resurfacing if they are warped, so you need to measure with a straight edge. The valve guides and any bearings need checking / replacing as necessary.
Block: same as heads, measure to be sure, but some engines have cylinder liners that can be replaced - and stick just proud of the block face.
If the cylinders were badly scored then the pistons may need replacing or machining.
Can all be done, but check and measure first.


A Perfect Hashing Function for an 8 by 8 board?

Question: I'm implementing a board with only 2 types of pieces, and was looking for a function to map from that board to a Long Integer (64 bits). I was thinking this should not be so hard, since a long integer contains more available information than an 8 by 8 array (call it grid[x][y]) with only 3 possible elements in each spot including the empty element. I tried the following:
(1) Zobrist hashing with Longs rather than ints (Just to test - I didn't actually expect that to work perfectly)
(2) Translated the grid into a 64 character string of a base 3 number, and then took that number and parsed it into a long. I think this should work, but it took a very very long time.
Is there some simpler solution to (2) involving bit operations of shifting or something like that?
Edit: Please don't give me actual code, as this is for a class project, and that would probably be considered unethical in our department (or at least not in Java).
Edit2: Basically, there are only 10 whites and 10 blacks on the board at any given time, of which no two pieces of the same color can be neighbors, either in the horizontal, vertical, or diagonal direction. Also, there are 12 spaces for each color where only that color may place pieces.
Comment: Perfect hashing is used when you have a predefined input and need to map a short value to a finished output. In your case it seems more like you are looking for an encoding scheme to store your values in.

You have 8 * 8 cells, each with 3 different values. which is too much for 64 bit without a compression scheme. It is however hard to say what a good algorithm would be without knowing more about how many pieces there and be, or how they can be distributed on the board.
Comment: Obviously your edit makes a difference to the question. But why insist on a 64 bit int?
Comment: Well I guess I wouldn't mind using a larger object if necessary. Just hoping to make it as small as possible so not as to get an out of memory error.
Comment: And also I wanted to avoid using massive amounts of computational resources on the hashing function.
Answer: If each tile in the game can be 1 of any 3 states at any point in the game, then the minimum amount of storage required for a "perfect hash" when hashing every possible state of the game board, at any given moment will
 = power(3,8*8) individual hashes
 = log2(3^64) bits
 = approx. 101.4 bits, so you will need at least 102 bits to store this info
At this point, you may as well just say there are 4 states for each tile, which will bring you to needing 128 bits.
Once you do this, its rather easy to make a fast hashing algorithm for the board.
E.g. (writtin as c++, may need to alter code if the platform doesn't support 128 bit numbers)

uint_128 CreateGameBoardHash(int (&game_board)[8][8])
{
    uint_128  board_hash = 0;
    for(int i = 0; i < 8; ++i)
    {
        for(int j = 0; j < 8; ++j)
        {
            board_hash |= game_board[i][j] << ((i * 8 + j) *2);
        }
    }
    return board_hash;
}

This method will only waste 26 bits (little more than 3 bytes) over the optimal solution of 102 bits, but you will save a LOT of processing time that would be otherwise spent doing base 3 math.

Edit Here's a version that doesn't require 128 bits and should work on any 16-bit (or better) processor

struct GameBoardHash
{
    uint16 row[8];
};
GameBoardHash CreateGameBoardHash(int (&game_board)[8][8])
{
    GameBoardHash board_hash;
    for(int i = 0; i < 8; ++i)
    {
        board_hash.row[i] = 0;
        for(int j = 0; j < 8; ++j)
        {
            board_hash.row[i] |= game_board[j] << (j*2);
        }
    }
    return board_hash;
}
Comment: Of course, you might be able to get a more optimal solution if you take into account the adjacency rules and piece limits that you specified in "edit2", but this also makes it much more difficult to work out an algorithm that will work efficiently (both memory and cpu usage).
Answer: It won't fit into a 64 bit integer. You have 64 squares and you need more than 1 bit to record each square. Why do you need it to fit into a 64 bit int? Are you targetting the ZX81?
Comment: +1 for mention of ZX81, -1 because ZX81 ints were 16 bits. :)
Comment: Well what happened was that we used a single board object for an entire tree search of say 100,000 board possibilities. Whenever we got to an attemptedMove, we simply temporarily applied that move, and backtracked out using an undoMove. To hash the board, I used a hashCode that took into account the current position of the board, say Hashtable.put(board1,score), but the problem was, that whenever there was a collision, it would think board1 = thisBoard since it stored a pointer to board1 == thisBoard (since we never create a new Board object, only edit the existing one).
Comment: To corret this, I was hoping to instead hash a unique value, say Hashtable.put(board1.UniqueNumber(), score), and use a Hashtable.get(this.UniqueNumber(), score), which would eliminate collisions all together, and any problems that would occur.
Comment: @Gabe the ZX81 had very limited RAM; -1 for you for not realising that was my point!  ;-)
Answer: How about a 16 byte array containing the bits? Each 2-bits, represent a position's value, so that given a position in the 8x8 board (pos=0-63), you can figure out the index by dividing pos by 4 and you can get the value by doing bit manipulation to get two bits (bit0=pos mod 4 and bit1=bit0 + 1). The two bits can be either 00, 01, or 10.
Answer: Reading your comments to David, it doesn't seem like you really need a perfect hash value. You just need a hashable object.
Make it simple for yourself... Make some hash for you position in the overwrite to GetHashCode(), and then do the rest of the work in the Equals function.
If you REALLY need it to be perfect, then you have to use a GUID to encode your data in and make your own hash that can use 128bit keys. But that is just a huge investment of time for little benifit.
Comment: I tried making hashable objects which contained a copy of the current piecesArray, but ran into out of JVM out of memory issues, after storing about 200k of these objects, though otherwise this approach did work.
Comment: 200k objects? Thats nothing, so you are wasting a ton of memory somewhere. With a int[8][8] you are using 256 bytes, plus lets say the same in overhead. For 200k objects, thats just around 100mb.


Sniffing USB traffic between an Android app and a connected device

Question: Is there any way to sniff USB traffic between an Android app and a connected device, like a drone controller?
Answer: On a regular non-rooted device this is impossible.
On a rooted device it might be possible (but I would not know how). The common Linux solutions for capturing USB traffic require a special kernel module. If your kernel has no module support this would require to build a custom kernel with the USB sniffing kernel module included).
In both cases you still have the possibility to perform a man-in-the-middle (MitM) attack on the USB connection, e.g. by placing a special device in between that allows you to access the USB traffic on "cable level":

https://www.csoonline.com/article/3087484/say-hello-to-badusb-20-usb-man-in-the-middle-attack-proof-of-concept.html
Or You could use a "Facedancer" board + software


Lippmann-Schwinger equation and $T$ expansion

Question: Lippmann-Schwinger equation, in operator form, is: $$
T=V+V\frac{1} {E-H_0+i \hbar \varepsilon} T=:V+V\Theta_0T,
$$
where $H_{tot}=H_0+{V}$ is the hamiltonian ($H_0$ is the free particle hamiltonian and $V$ a potential).
We can also obtain, by recursion, the following expansion: $$
T= V+V\Theta_0V+V\Theta_0V\Theta_0V+V\Theta_0V\Theta_0V\Theta_0V+ \cdots
$$  Gathering $V$: $$
T=V(1+\Theta_0V+(\Theta_0V)^2+(\Theta_0V)^3+\cdots)=V\sum_{k=0}^\infty (\Theta_0V)^k
$$ so, if $\| \Theta_0V\|<1$, and if what I'm doing makes sense..\begin{equation}
T=V\frac{1} {1-\Theta_0V}.  \end{equation}
My questions: was all this legitimate? I've never really seen the last expression in action, in scattering theory so far. One usually uses the $T$ expansion and leaves just the needed terms. Maybe the last form isn't so convenient? Is it correct? Also, is the convergence request  $\| \Theta_0V\|<1$ always fulfilled?
Answer: Your final expression is correct except that $V$ should be in front since it does not commute with $Θ_0$ in general.
In potential scattering ${Θ_0}V$ is often a compact operator and for large positive imaginary part of $z=E+iℏε$ its norm becomes arbitrarily small so the series converges. In certain cases one can do things a little differently by considering ${V^{1/2}}{Θ_0}{V^{1/2}}$ instead of ${Θ_0}V$ which then has a limit as $Imz$  tends to the real axis (so-called Rollnik potentials).See Simon "Hamiltonians as quadratic forms"  or the series "Methods of Modern Mathematical Physics" by Reed cand Simon.
The full expression for $T$ can easily be evaluated further for rank one potentials, $V=|f><f|$ where $f$ is an element of the underlying Hilbert space.
Comment: Oh! Freshman mistake! I'm correcting it, and thanks for the answer!


Retrieve text from JComboBox

Question: How to retrieve Text that is typed in JComboBox. This text need not be an existing item.
Answer: You can get the selected or typed value from a JComboBox by calling method getSelectedItem. If it is not an existing item, then you'll get a String object. Otherwise you'll get whatever object you populated the combo box with.
Answer: Simply use :
String value= comboBox.getSelectedItem().toString();

Other examples available here
Answer: You can try the following
String typedText = ((JTextField)myComboBox.getEditor().getEditorComponent()).getText();

Retrieve text from JComboBox


Learn about tensors for physics

Question: Can I have suggestions for some good book regarding tensors for physics.
Comment: Related: https://physics.stackexchange.com/q/309256/2451
Comment: [Some of these books](https://physics.stackexchange.com/q/363/25301) might interest you as well.
Comment: "Relativity Made Relatively Easy" by Andrew M. Steane.
Answer: I suggest that you read what is said about tensors in three General Relativity books:

Spacetime and Geometry - An Introduction to General Relativity - Sean Carroll - Chapter 1, specially sections 1.4, 1.5, 1.6 and 1.7, but it is good to read all of it. If you want to understand tensor fields, and not just tensors, then you should read the whole Chapter 2;
Gravitation - Misner, Thorne, Wheeler - Chapters 2 and 3. Specifically about tensors in general there is section 3.2, but I suggest reading the two chapters to actually understand the point. This one gives quite a nice geometric intuition, specially about differential forms (completely skew-symmetric tensors);
General Relativity - Robert Wald - Chapter 2 and specially Section 2.3 which gives a quite self-contained description of what are tensors in general and why the definition makes sense for physics. Again, if you want to understand tensor field, though, you should read the whole chapter;

Those books are certainly for physicists, as they cover standard General Relativity, and all they have inside then discussion about what are tensors and how to manipulate them in a modern way. Of course, it is not because they are GR books that what they say about tensors is specific to GR.
In other words: it is good to understand tensors as multilinear maps instead of as sets of components plus a transformation property. Furthermore, the definition as multilinear maps shows why, when working totally in coordinates, the transformation definition makes sense. Without it, the transformation definition seems like it came out of thin air.
Finally, if you want a more advanced treatment, I suggest you look at

Linear Algebra and Geometry - Kostrikin and Manin - Chapter 4.

But I would suggest you only do so after you feel comfortable with the usual approach.
This book is quite though with a quite abstract approach. For starters, in physics, the first approach is already quite good. There are advantages, though. In particular, it discusses the tensor product that appears in QM.
By the way, if you ever want to learn this other approach and find the definition of the tensor product confusing, I suggest to check out these questions on Math.SE:

Kostrikin's Definition of Tensor Product
Why is the tensor product constructed in this way?
Comment: For reference 4: aren't the authors Kostrikin and Manin?
Comment: @MBN, true, I forgot one. I've edited it. Thanks for pointing it out.
Answer: In my opinion, there are two major ways to learn tensors for physicist, depending on the desired depth of understanding. The first, learning it through a physics text, in which vector fields, one-forms, and tensor fields are introduced in a quite hand-wavy way using tons of pictures and illustrations. The benefit of this approach, is that you can learn it fast and you can do ton of calculations in GR without truly understanding what you are doing. To achieve this, i recommend Sean Carroll's text, as it is probably the more mathematically incline physics text.
The second approach, is to learn tensor fields through differential geometry, where it actually originated. The upside is that you will truly understand the geometrical aspect of general relativity and can further study to more theoretical topics later on. For this approach, i recommend Semi-Riemannian Geometry: With Applications to Relativity by Barrett O'Neill (chap 1-3) if you are in a rush. The pre-requisite is a working knowledge of basic general topology and multivariable analysis (Jacobian matrix etc).
If you have time, you can approach more elaborate texts such as John Lee's Smooth Manifolds (chap 1-3,8,12-13) + Riemannian Manifold's (as much as you need). John Lee's text are known to be verbose and friendly to readers, intutive but rigorous. The downside of his text's are, they are quite long. I believe his text's tend to attract theoretical physicist, given his style.   Another good mathematical text for physicist is Chris Isham's Modern Differential Geometry for Physicist text (chapter 1-3). Chris Isham was a leading theoretician in the UK, and his writing style is nice for physicist, where he focuses on intuition rather than rigirous proof's. Although he covers precisely the required structures. His text does'nt cover Riemannian geomtry though. If you would like to know where the inspiration of tensor products came from, the best book i've come across that elaborates completely this notion is Steve Roman's Advanced Linear Algebra (chap 3 & 14). I recommend learning all your linear algebra from Steve Roman honestly, its a wonderful exposition.
Lastly, if you want to learn tensors for special relativity purposes only, look no further, check out Éric Gourgoulhon Special Relativity in General Frames. Probably the best book to introduce some tensor notation in general relativity as well.
Answer: An Introduction to Tensors and Group Theory for Physicists is a good book, recommended to me by some professors in my institution. It doesn't go into too much of abstract algebra, other than what's absolutely necessary.
Another really good book would be A Student's Guide to Vectors and Tensors by Daniel A. Fleisch.
Some other recommendations for physicist approach of tensors may be found here. I'm not quoting from there, because I've already mentioned the best books.
Answer: I learned about tensors from Schutz's book about general relativity ("A first course in general relativity") and from Wald's general relativity book ("General relativity").
These are not strictly books about tensors, but since they form a lot of the mathematical apparatus of GR, they are explained well there (and with physical interpretations and applications).
Answer: See Nuclear Shell Theory by Amos de Shalit and Igal Talmi. The book is constructed from two parts and one for tensors a total of 586 pages. My thought is he dived into some confusing details which should be read carefully. The following parts consider applications that makes a good deal with mathematics.

Learn about tensors for physics


Change off contents with themes in Yii

Question: My problem is the next: when I create an application in Yii (with 'classic' theme) the contents of layouts are in URL/protected/views/layouts and this is perfect for me, when I install another theme (bootstrap in this case) the layouts are dependent of the theme and the basic layouts are in URL/themes/bootstrap/views/layouts, and this is a problem for me.
First: Because the aplication only have to manage modules (several) so I want the general content in the general app.
Second: I need work to try a theme
Third: Because in future the theme should be conditionated by User, User selection, and module.
I know that the view prelation is action->controller->theme->module->parent module->default-> none
So I think that it should be so easy as
public $layout='main';

in the top off the SiteControler,(/protected/controlers) but the 'main' layout that gets is the bootstrap one.
In order to modularize all the aplication I want to have and independent theme for the "principal" aplication and for each module (in several cases will be the same), and of course whitout remake the menu for each one.
I suposse that it is dependent of the default URLs that you configure,
Yii::setPathOfAlias('bootstrap', dirname(__FILE__).'/../extensions/bootstrap');

in /protected/config/main.php. Or other 'URL configurations'.
Somebody has an idea how may maintain the content indepedent of the themes in 'principal' aplications and modules.
Thanks a lot.
Answer: You can change the current theme in the controller (or anywhere before calling controller->render) by using:
Yii::app()->theme = 'yourThemeId';

Hope it helps

Change off contents with themes in Yii


Is Cauchy induction used for proofs other than for AM–GM?

Question: The proof by Cauchy induction of the arithmetic/geometric-mean inequality is well known. I am looking for a further theorem whose proof is much neater by this method than otherwise.
Comment: Every midpoint convex function is rationally convex (Jensen convex): [Midpoint-Convex and Continuous Implies Convex](http://math.stackexchange.com/q/83383) at Math.SE.
Comment: While not strictly Cauchy induction, I think one of the proofs of the Fundamental Theorem of Algebra is vaguely reminiscent of it: the proof uses induction not on the degree, but on the highest power of 2 dividing the degree.  The idea is that passing from a polynomial of degree $n$ to a polynomial of degree $n(n+1)/2$ is actually a *reduction* step in this style of induction. See an answer to http://math.stackexchange.com/questions/1354501/is-this-induction-proof-of-the-fundamental-theorem-of-algebra-rigorous.
Comment: I didn't know what Cauchy induction was, but the various examples of the thread suggest it plainly.
Comment: If a ring $R$ satisfies $\left(a^2 = 0 \Longrightarrow a=0\right)$ for each $a \in R$, then every nilpotent in $R$ is zero. There is a really easy proof by Cauchy induction (although it doesn't really get longer if you reword it using standard induction).
Comment: I vaguely remember that there may be a solution to Waring's problem along these lines: use Hilbert's identity to show that if Waring holds with exponent $k$, then it holds for exponent $2k$ and then pad out the intermediate exponents in some way...
Comment: Even if it's not only combinatorics, I added the tag because the question should involve at least one broad tag.
Comment: @YCor: While the distinguishing structural principle of Cauchy induction (CI) is combinatoric—as CI entails the idea that you can cover the natural numbers from zero if you can always make a big jump forward and walk back as many unit steps as needed—this combinatoric aspect is trivial, taken for  granted, and not the issue of concern here. Do you have a hunch that a proof by CI might feature somewhere in the field of combinatorics (where certainly induction is used a lot)?
Answer: A nice proof by Cauchy induction can be given for the identity
$$ \|A^n\|=\|A\|^n, $$
which holds for a bounded, self-adjoint operator $A:H\to H$ on a real Hilbert space $(H,\langle\cdot,\cdot\rangle)$. Here $\|\cdot\|$ denotes the operator norm.
Indeed, the inequality $\|A^n\|\le\|A\|^n$ is trivial by submultiplicativity of such norm. Let us turn to the converse inequality: if you know that $\|A^n\|\ge\|A\|^n$, then
$$ \|A^{n-1}\|\|A\|\ge\|A^n\|\ge\|A\|^n, $$
so the same holds with $n-1$ in place of $n$. Thus it suffices to show that, whenever it holds for $n$, it holds also for $2n$:
$$ \|A^{2n}\|=\sup_{\|x\|\le 1}\|A^{2n}x\|\ge\sup_{\|x\|\le 1}\langle A^{2n}x,x\rangle=\sup_{\|x\|\le 1}\langle A^nx,A^nx\rangle=\|A^n\|^2\ge\|A\|^{2n}. $$
This last line used Cauchy induction (i.e. the idea to prove $n\Rightarrow 2n$ rather than, e.g., $n\Rightarrow n+1$) in an essential way!
Comment: In the low-chance event that someone else as slow as me reads this answer, it might help to interpolate, before the first inequality in the final display line, the further inequality $\ge\sup_{\|x\|\le 1}(\|A^{2n}x\|\|x\|)$. (Actually, equality holds here.) The existing inequality then can be seen to  hold by Cauchy--Schwartz.
Answer: Assume that $f$ is a function defined in a certain interval $\Delta$ and you want to prove that $$\sum_{i=1}^n f(x_i)\geqslant nf(a),\,a=\frac1n \sum x_i,\tag 1$$ where the numbers $x_i$ in $\Delta$ are arbitrary or satisfy some additional condition U. Example of U would be '$x_i+x_j\leqslant 2b$ for $i\ne j$.' Then Cauchy induction allows to consider only the case $n=2$, which is often handy. In the above example we induct from $n$ to $n+1$ bit tricky: replace two largest numbers to the average and then add the total average.
Specific example: if $x_i$ are non-negative numbers and the sum of any two does not exceed $\pi$, then $\sum \cos x_i\leqslant n \cos a$.
In the case when there is no condition U, we have simply Jensen inequality, which gives AM-GM for $f=-\log$ or for $f=\exp$. Of course, for other convex functions $f$ it also works. Moreover, you may define, as Martin Sleziak writes in the comment, 'midpoint convexity' of $f$ by $f(x)+f(y)\geqslant 2f\left(\frac{x+y}2\right)$ (this is equivalent to convexity under additional assumptions like continuity), and deduce (1) by Cauchy induction.
Comment: Both [midpoint convex](http://books.google.com/books?q="midpoint+convex") and [Jensen convex](http://books.google.com/books?q="Jensen+convex") seem to be used quite often.
But [baby convex](http://mathoverflow.net/revisions/255512/4) is certainly a very nice name.
Comment: Condition U does have to satisfy certain conditions itself, like being convex, right?
Comment: @darijgrinberg of course it is not arbitrary. Strictly speaking, we have a sequence of conditions $U(n)$, and they should be chosen so that both forward and backward steps of Cauchy induction work somehow.
Answer: This is due to Noga Alon, recently popularized by Gil Kalai. I started a big-list thread motivated by this proof, and the answer by Federico Poloni reminded about this question.
Theorem. Let $G=(V,E)$ be a bipartite $r$-regular multigraph. Then $E$ is a union of $r$ perfect matchings.
Proof. At first, we prove it when $r$ is a power of 2, by induction. Base $r=1$ is clear. If $r>1$ is even, the number of edges in each connected component is even (sum up degrees of one part.) Take an Eulerian cycle in every connected component and color edges alternatively, we partition $E$ onto two $r/2$-regular multigraphs. Apply induction proposition for them.
Now assume that $r$ is not a power of 2. Take large $N$ and write $2^N=rq+t$, $0<t<r$. Replace each edge of our multigraph onto $q$ edges, also add extra edges formed by arbitrary $t$ perfect matchings. This new multigraph may be partitioned onto $2^N$ perfect matchings, and if $N$ is large enough, some of them do not contain extra edges. So, we have found a perfect matching in initial graph, removing it and repeating $r$ times gives a required decomposition.
Comment: Nice! So this theorem can be proven without Hall...
Comment: @darijgrinberg There is a short Hall-avoiding proof by studying the Birkhoff polytope of doubly stochastic matrices. Namely, replace a regular multigraph to a graph with positive weights on edges such that the total weight of edges in any vertex equals 1. If the graph is a forest, it is already a perfect matching (look at isolated vertex and its neighbor). If it has a cycle, replace the weights along the cycle by $+t,-t$ alternatively so that the minimal weight becomes equal to 0. Proceed this way.
Comment: The first stage looks pretty close to the stages "true for $n=0$" and "true for $n=k$ implies true for $n=2k\,$" of Cauchy induction. I wonder whether the second stage can be easily modified to fit the format of the other stage: "true for $n=k+1$ implies true for $n=k\,$".
Comment: @JohnBentin it is 'full Cauchy induction': for given $k$, if true for some $n>n_0(k)$, then true for $k$.
Answer: Here is a use of the Cauchy induction method to show a function that almost looks like a non-archimedean absolute value is a non-archimedean absolute value. [EDIT: This is used in the course of one of the proofs that the absolute value on a finite extension of a nonarchimedean complete valued field extends to an absolute value on each finite extension of that field.]
For a field $K$ suppose a function $|\cdot| \colon K \rightarrow \mathbf R_{\geq 0}$ is multiplicative, satisfies $|n| \leq 1$ for all integers $n$, and
$$
|x+y| \leq C\max(|x|,|y|)
$$
for all $x, y \in K$ and some $C > 0$.  We want to refine this
to $|x+y| \leq \max(|x|,|y|)$ for all $x, y \in K$. That is, we want to prove we can take $C = 1$ in the above inequality. (Note: For $K = \mathbf R$ the usual absolute value satisfies $|x+y| \leq 2\max(|x|,|y|)$ for all $x$ and $y$ in $\mathbf R$ and we can't replace $2$ with $1$ in that bound; thus the hypothesis $|n| \leq 1$ for all $n \in \mathbf Z$ is important.)
We of course can assume $C > 1$, since otherwise what we want is obvious.
First let's try something that will not work out (I think), in order to appreciate the Cauchy method that comes later. By induction on the number of terms it is not hard to show for all $x_1,\ldots,x_n$ in $K$ that
$|x_1+\cdots + x_n| \leq C^{n-1}\max(|x_1|,\ldots,|x_n|)$.
Then, using $n+1$ terms,
$$
|(x+y)^n| = \left|\sum_{k=0}^n \binom{n}{k}x^ky^{n-k}\right| \leq C^n\max_{0 \leq k \leq n} \max(|x|,|y|)^n
$$
since $|\cdot|$ is multiplicative and binomial coefficients have absolute value at most 1 by hypothesis. The left side above is $|x+y|^n$ by multiplicativity, so $|x+y|^n \leq C^n\max(|x|,|y|)^n$.  Take $n$th roots and we get $|x+y| \leq C\max(|x|,|y|)$, so we are back where we started and gained nothing.
Here is another approach.  If $n = 2^r$ is a power of 2 then any
sum of $n$ terms $x_1 + \cdots + x_n$ in $K$ can be broken up into
two sums with $n/2$ terms each, so by induction or $r$ we get
$$
|x_1 + x_2 + x_3 + \cdots + x_{2^r}| \leq C^r\max(|x_1|,|x_2|,|x_3|, \ldots,|x_{2^r}|)
$$
for all $x_1,\ldots,x_{2^r} \in K$.
For $x$ and $y$ in $K$ let's apply this to $|(x+y)^{2^r-1}|$.  The binomial expansion
$$
(x+y)^{2^r-1} = \sum_{k=0}^{2^r-1} \binom{2^r-1}{k}x^ky^{2^r-1-k}
$$
has $2^r$ terms.  In the $k$-th term we have $|\binom{2^r-1}{k}| \leq 1$  by hypothesis.  Therefore
$$
|x+y|^{2^r-1} \leq C^r\max_{0 \leq k \leq 2^r-1} \max(|x|^k|y|^{2^r-1-k}) = C^r\max(|x|,|y|)^{2^r-1}.
$$
Taking $(2^r-1)$-th roots of both sides,
$$
|x+y| \leq C^{r/(2^r-1)}\max(|x|,|y|).
$$
Letting $r \rightarrow \infty$, $C^{r/(2^r-1)} \rightarrow 1$ and
we get $|x+y| \leq \max(|x|,|y|)$.
While we did not actually need to go back and prove anything for a general number of terms that is not a power of $2$, I still think this argument has the spirit of the Cauchy idea.
Comment: Could you give an example of a nontrivial such nonarchimidean valuation?
Comment: @JohnBentin see my edit to the first paragraph: every extension of a nonarchimedean complete absolute value  on a field to a finite extension of that field is potentially a nontrivial example *in the course of proving* that extension really is an absolute value on the larger field, i.e., that it satisfies the non-archimedean triangle inequality after proving the other properties of being an absolute value.
Answer: Another inequality can be proved by Cauchy induction :$$\prod_{i=1}^n(x_0+x_i)\geqslant\left(x_0+\prod_{i=1}^nx_i^{1/n}\right)^n\quad\text{for all}\quad  n=1,2,...\;\text{and}\; x_0,...,x_n\geqslant0.$$ Details can be found here. I don't see a different easy way to do it. While this involves a geometric mean, it doesn't look much like the AM–GM inequality, because there is a product on both sides. Perhaps, though, it could be derived from AM–GM.
Edit:$\quad$As I have later learned, it can indeed be derived from AM–GM. First, write this standard inequality with variables $x_1,...,x_n>0$. Now replace each $x_i\,$ ($i=1,...,n$) respectively by $x_0^2/(x_0+x_i)$. In parallel, replace each $x_i$ respectively by $x_0x_i/(x_0+x_i)$. Add the two consequent inequalities, and the result easily simplifies to the inequality above. (The extension to $x_1,...,x_n\geqslant0$ is trivial.)


External Hard Drive not recognized on reboot

Question: Right now, I have an external hard drive that has its own power supply. When I first installed the system, it was able to recognize the hard drive, which I mounted and then added to the fstab. Every reboot after that however, the pi will not detect it at all. It doesn't show up at all through sudo fdisk -l. I initially thought that it was the SD but the same thing happened with another SD and a clean installing.
Answer: Hep; It sounds almost like a loose micro-usb as it works pretty well out of the box:
pi@raspberrypi ~ $ sudo fdisk -l

Disk /dev/mmcblk0: 7822 MB, 7822376960 bytes
4 heads, 16 sectors/track, 238720 cylinders, total 15278080 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x000b5098

        Device Boot      Start         End      Blocks   Id  System
/dev/mmcblk0p1            8192      122879       57344    c  W95 FAT32 (LBA)
/dev/mmcblk0p2          122880    15278079     7577600   83  Linux

Disk /dev/sda: 1000.2 GB, 1000204886016 bytes
255 heads, 63 sectors/track, 121601 cylinders, total 1953525168 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0xe8900690

   Device Boot      Start         End      Blocks   Id  System
/dev/sda1              63  1953520064   976760001   83  Linux

As you can see above sudo fdisk -l works fine.
With this we need a mount point:
pi@raspberrypi ~ $ sudo mkdir /media/usbhdd

From here we can open and edit the /etc/fstab, using:
pi@raspberrypi ~ $ sudo nano /etc/fstab

So you can add the last line of the fstab for your usb hdd. Your result should look like shown below (consult man fstab if you are in doubt about your filesystem).
pi@raspberrypi ~ $ cat /etc/fstab
proc            /proc           proc    defaults          0       0
/dev/mmcblk0p1  /boot           vfat    defaults          0       2
/dev/mmcblk0p2  /               ext4    defaults,noatime  0       1
# a swapfile is not a swap partition, so no using swapon|off from here on, use  dphys-swapfile swap[on|off]  for that
**/dev/sda1       /media/usbhdd   ext4    defaults          0       0**

The last line (above) is my fstab that automounts the external usb HDD at boot.
Now you can see the hdd using: df -h
pi@raspberrypi ~ $ df -h
Filesystem      Size  Used Avail Use% Mounted on
rootfs          7.1G  2.5G  4.3G  37% /
/dev/root       7.1G  2.5G  4.3G  37% /
devtmpfs        215M     0  215M   0% /dev
tmpfs            44M  236K   44M   1% /run
tmpfs           5.0M     0  5.0M   0% /run/lock
tmpfs            88M     0   88M   0% /run/shm
/dev/mmcblk0p1   56M  9.5M   47M  17% /boot
/dev/sda1       917G  366M  870G   1% /media/usbhdd

I hope this helps for checking that you didn't miss anything :-)


Can a rip on a suitcase be repaired with iron-on patches?

Question: While packing, I noticed a small tear (around 5cm) on the side of my suitcase. It's only in the outer lining, but I'm worried it could grow during (mis)handling. Getting a new one at this point would be an inconvenience. I have an iron-on clothes patch that's the correct size. Is it safe to apply it to the suitcase, or would the process cause more harm than good to the material? Any other ideas on how to repair it, or increase its chances of enduring one more trip?
Here is a picture of the suitcase on Amazon
Comment: this seems like a question for lifehacks.se :)
Comment: I'm sharing the proposal to move the question to lifehack.se
Answer: I would not trust the patch alone.  The frame of the suitcase does not provide a place where you can press the iron firmly down.
To make it endure another trip, you can take two towels and lay them flat inside the empty suitcase so that they overlap the outsides.  Then repack all your stuff.  Valuables go into a shopping bag in the centre.
Then to close the suitcase, fold the ends of the towels over your stuff so that they 'surround' the contents.
This will distribute the stress against the tear more evenly over a wider area.  Once shut, you can use a strip of duct tape or bungee cords (or whatever's handy) to wrap around the outside of the suitcase.  This will prevent the tear from snagging on something and becoming larger.
Comment: I followed the towels tip, along with tape and a luggage belt on the outside. It looks sturdy enough
Answer: I would prefer repair tape (easily available on Amazon or from camping supply stores) to an iron on patch. Plastic on the suitcase might melt when you use the iron. Here are some tape images:

I own some of the Tenacious tape myself but have yet to use it on a suitcase. I take it on long trips and all camping trips. Reviews suggest people repair tents, coats, and sleeping bags with great success and it would seem appropriate for a suitcase also.
Comment: I ended up using a [strong type of duct tape](http://www.tesa.com/consumer/renovating_repairing/ducttapes/tesa_extra_power_extreme_outdoor,c.html). Not exactly the one pictured, but it was available at a nearby store and worked well. Thanks for dissuading me from the iron-on patch


How to find straight line segments nearest to a straight line segment?

Question: consider an image matrix in which i have multiple line segments. And i have information's like start point, end points, length of the line segment, centroid and slope of all those line segments. In this scenario how do i find line segments that are nearest to a particular line segment. Also once i got nearest line segments is it possible to detect rectangles if they exist? .An example image is in this link sample.
Comment: You are mixing straight lines (infinite extent) and line segments (interval on a line). Please be specific about what you need. Line/segment or segment/segment distance ? [Line/line distances are 0, unless parallel.]
Comment: all of them are line segments only.  I need to find the line segments which are nearer to a particular line segment @YvesDaoust
Answer: The geometry of segment/segment distance is not so simple.
Imagine two line segments in general position, and dilate one of them. I mean, draw two parallel segments at a distance d and two half circles of radius d centered on the endpoints. This is the locus of constant distance d from the segment. You need to find the smallest d such that the other segment is hit.
You can decompose the plane in three areas: the band between the two perpendiculars through the endpoints, and the two outer half planes. You can clip the other segment in these three areas and process the clipped segments separately.
Inside the band, either the segments intersect and the distance is zero. Or they don't and the distance is the shortest distance between the line of support of the first segment and the endpoints of the other.
Inside the half planes, the distance is the shortest of the distances between the considered endpoint and both endpoints of the other segment, and the distance between the endpoint and the other segment, provided then endpoint projects inside the other segment.
ALTERNATIVE:
Maybe it is easier to use the parametric equations of the two segments and minimize the (squared) distance, like:
Min(p, q) ((Xa (1-p) + Xb p) - (Xc (1-q) + Xd q))^2 + ((Ya (1-p) + Yb p) - (Yc (1-q) + Yd q))^2 under constraints 0 <= p, q <=1.
Comment: In your first para what do you mean by smallest d such that the other segment is hit ? and i have drawn what u have said in first para let me know am i correct @Yves
Comment: Let me see your drawing
Comment: Quite correct. If you increase `d`, at some point you will meet the other segment.
Comment: on fine. Is there some good material to read about all these ? I dont know which math book to look into can u suggest some material ? @Yves
Comment: Check my other solution and read about "elementary vector calculus".
Answer: First, you have to encode all the points in homogeneous coordinates [x, y, 1]T since this creates a symmetric relations between lines and points. Namely, in homogeneous coordinates the intersection of two lines l1 and l2 is a point p=l1xl2, where x means vector product. By the same, coin a line that passes through two points p1, p2 is l=p1xp2. Line that lie on a segment can be expressed as l=p1xp2=[a, b, c]T. The line equation then will be lT.p=0 or in Cartesian coordinates a*x+b*y+c=0
As for your task, there are two cases:
1. segments cross and then their intersection can be simply calculated as l1xl2;
2. segments don't cross and then the closest points between two lines is the closest point between two of their 4 endpoints. To calculate 4 possible distances and choose the smallest distance between a line segment x1 and x2 and a point x0 use this formula: (x2-x1)x(x1-x0)/|x2-x1|
Comment: thanks for the idea i thought about using homogeneous coordinate system but i didnt find any good material with examples to understand it completely. If you know any book or website for reading about it please suggest me @Vlad
Comment: The best book for this and for Computer Vision in general is "Computer Vision" by Simon Prince (worth buying) http://www.computervisionmodels.com http://web4.cs.ucl.ac.uk/staff/s.prince/book/book.pdf; if somebody recommends you "Multiple View geometry" by Hartley and Zisserrman - it is classic but very badly written. Szeliski book is not deep enough (http://szeliski.org/Book/). Otherwise it depends on a section you are interested in.
Comment: try this for your problem: http://www.cs.utexas.edu/~fussell/courses/cs395t/slides/L3(ProjGeom).pdf
Comment: Thanks man i was trying to understand by reading multiple view geometry only it was quite hard though will look into that book @vlad
Answer: Let the segments be AB and CD, and running parameters along them p and q, such that 0 <= p, q <= 1.
Using vectors, the squared distance between any two points on the segments is given by:
D² = (AC - p AB + q CD)²

Let us minimize this expression by zeroing the derivatives wrt p and q:
AB.(AC - p AB + q CD) = 0
CD.(AC - p AB + q CD) = 0

When AB and CD are not parallel, this implies AC - p AB + q CD = 0, which gives you the intersection point by solving a 2x2 system, and the distance is zero.
But it can turn out that p (or q) falls out of the allowed range, let p < 0 (or p > 1). In this case, we recast the problem with p = 0 (p = 1). This amounts to finding the distance (A, CD).
D² = (AC + q CD)²

yielding
CD.(AC + q CD) = 0

even easier.
And if it turns out that q is also out of range, let q < 0, we end up with the distance (A, C):
D² = AC²

Similarly for the other out-of-range cases.
In case of parallel segments, the 2x2 system is indeterminate (both equations are equivalent). You need to solve:
CD.AC - p CD.AB + q CD² = 0

It suffices to try all four combinations with p/q  = 0/1 and see if the left hand side takes different signs. This proves that there exists a solution and the distance is the same as distance (A, CD). Otherwise, the answer is one of the endpoint-to-endpoint distance.


Why has the market got it so consistently wrong about interest rate rises

Question: I have seen this graph (or similar) in several places. It shows how the market has consistently and incorrectly predicted interest rates will rise back to normal levels. With the benefit of hindsight, has anyone produced a reasonable explanation as to why the market  got it so wrong?
Comment: between 2009 and 2015, were interest rates set by the market or by the Bank of England?
Answer: I'll give one technical and one economic reason:  first, if you believe in the zero bound for interest rates (bank of England will not set a negative short rate) then mathematically, if the current bank rate is close to zero (as it was post the 2008 crisis), then the distribution of rates 2-3 years forward is going to be biased upwards.  Secondly, what happened economically during this period was that central banks saw that even with rates close to zero, inflation was not being stoked and in fact deflation was more of a worry.  Hence the central banks never were able to raise rates as much as the forward curves expected.
Comment: I agree with the "technical" point. Your other point is about "inflation was not being stoked" - so presumably the market consistently thought "look out for inflation... here it comes any minute now..." and they were always wrong. Why were they wrong on that?
Comment: Well this is a very wide subject but to summarize I'd say that long term trends such as automation, globalization and demographics acted as disinflationary forces during this period. But there is a lot of literature on that.


Can you add the visual editor to the description field for custom taxonomies?

Question: Can you add the visual editor to the description field for custom taxonomies? It would be nice to have this option available when you edit an entry for a taxonomy be it core or custom.
Comment: The following solution from @Butuzov works perfectly [Replace Taxomony Description Field with Visual/WYSIWYG Editor](https://wordpress.stackexchange.com/questions/190510/replace-taxomony-description-field-with-visual-wysiwyg-editor/190854#190854)
Answer: Just wrote the function. It'll display the tinymce editor in every custom taxonomy description right now. Surely you can edit to show it for only some specific taxonomy.
/**
 * Display advanced TinyMCE editor in taxonomy page
 */
function wpse_7156_enqueue_category() {
    global $pagenow, $current_screen;

    if( $pagenow == 'edit-tags.php' ) {
        require_once(ABSPATH . 'wp-admin/includes/post.php');
        require_once(ABSPATH . 'wp-admin/includes/template.php');

        wp_tiny_mce( false, array( 'editor_selector' => 'description', 'elements' => 'description', 'mode' => 'exact' ));
    }
}
add_action( 'init', 'wpse_7156_enqueue_category' );

You can provide the first argument in wp_tiny_mce as true if you want a stripped version of tinyMCE
Comment: Its a bit outdated. This helped me: http://wordpress.stackexchange.com/questions/190510/replace-taxomony-description-field-with-visual-wysiwyg-editor
Comment: You nailed it Tareq, thanks! I'm pretty sure they're moving this in to a real API for 3.3, but for now this is a simple solution. I'll award the bounty tomorrow when WPSE lets me. :)
Comment: +1 for simplicity. Adding to my snippets and will try soon. Thanks
Comment: @Maugly, agreed. I tried it and you may want to modify it to work with the action=edit, because on the quick edit screen #description is used in the taxonomy table. #tag-description is used for the description text box on the quick edit screen, but your space is limited, because of the two column setup.
Comment: just a reminder to @hsatterwhite to award bounty
Comment: Thanks for the reminder, done and done. Have a good one!
Comment: This breaks the edit page for any term in wordpress 3.3+. https://wordpress.org/support/topic/wordpress-33-breaks-wp_tiny_mce
Comment: `Fatal error: Call to undefined function wp_tiny_mce() in`
Answer: Have you tried The Rich Text Tags Plugin?

It does exactly what you need.
Works with custom taxonomies.
Works well with images.
Includes the new WP internal linking.
It is regularly updated.

Screenshot:
Comment: I have not heard about this. I appreciate the answer and link with screenshot. In addition to the accepted answer, this is also a great solution. Thank you Maugly!
Answer: Not directly, no.
You could, however, write a custom javascript which applies the appropriate classes to the entry field for the custom taxonomy description.
If what you really want to do, however, is create a "many-to-many" relationship between posts (e.g. a post type of "Tires" and a post type of "Cars"), then WordPress doesn't (currently) have a facility for this. However, the Posts 2 Posts plugin does provide this functionality (and gives you a lot more flexibility to create complex relationships).
Comment: Thanks for the response, but I'm not trying to relate posts to other posts. I'm just trying to add the visual editor to the description field for taxonomies.


Manga where MC uses his own lightning magic on his mind to change his memories and personality

Question: I don't remember much of it but the Main Character (MC) uses lightning magic on his mind in order to wipe memories and change his personality. When he gets older he does it again out of despair and almost kills himself, but he is saved by a spirit and taken to their world to rehabilitate.
Comment: Mostly black and white
Comment: Hi, welcome to the site. Was this in full colour or mostly black & white?
Answer: This is Outcast Adventurer's Second Chance ~Training in the Fairy World to Forge a Place to Belong~

"Glen, your bad reputation is dragging the party down. We're kicking you out today." A party of adventurers formed from childhood friends. The day after a promotion exam, Glen was summoned to the guild and expelled by the party leader. ... This is a story about an adventurer trying to regain the things he has lost. Those who abandoned him will wallow in grief, while he moves forward with his new companions.

After being kicked out of his party, Glen zaps himself a second time and is rescued by fairies, and spends time recuperating in the land of the fairies. He had met them the first time he used the lightning magic on himself to alter his personality.
Comment: Thank you very much. I have started and read over 200 different manga and wanted to see if this one had any updates.


Cosine similarity--one to many

Question: I'm wondering if there's any good way to use cosine similarity to compare a single document with a set of documents. Obviously you could calculate the cosine similarity between the single document and every document in the set, but if you did this would you then take the average? Would you weight by the size of each of the other documents you're comparing the original document with? I'm also wondering if there's any way to combine all of the word counts in the set of documents you're comparing with so that in the end you only compute cosine similarity once; between the original document and the "aggregated" document. The reason I'm asking is that I have about 200,000 documents that I want to compare with a separate set of about 50,000 documents.Comparing each of the 200,000 with each of the 50,000 is a lot of calculating and I don't know if it's actually necessary if I'm just going to take some sort of average in the end anyway. Is my aggregated document idea a big no-no?
Answer: There is a way to speed this up significantly. The point is to notice that the word vectors are sparse. Thus you want to transform your documents into a table which is organized by word columns. One column per word. For each column you only store the non zero entries. That is one row per document that actually contains the word. Then you compute the partial sums by going through the columns and collect the results per document. This has the additional advantage that it is easy to parallelize.
To speed this up further you create a column per word per set and only compute and distribute the partial sums for the same word for documents of different sets.

Cosine similarity--one to many


Does there exist a continuous function such that f(x) is rational for every irrational x, and f(x) is irrational for every rational x?

Question: Does there exist a continuous function such that f(x) is rational for every irrational x, and f(x) is irrational for every rational x?
I can think of examples where this would be true, but I'm having a lot of trouble with the continuity.
Comment: @HamidRezaEbrahimi The question is simple and presented answers are OK. Why do you think the question is really deep and needs much more attention?
Comment: [Another answer](https://math.stackexchange.com/questions/55638/no-continuous-function-switches-mathbbq-and-the-irrationals).
Answer: There is no such a function. Your hypothesis imply that the image of $f$ is countable which is impossible for any non-constant  continuous function from $\mathbb R$ into $\mathbb R$.
Answer: That's elegant. The image of the irrationals is countable by hypothesis, and the image of the rationals is countable because the rationals are countable. The continuous image of the reals is either constant or an interval (which may be unbounded), and intervals are uncountable.
Answer: Suppose such a function $f(x)$ existed.  Define $g(x)=xf(x)$.  Observe that $g$ is continuous if $f$ is continuous, and whenever $x\not=0$ and $f(x)\not=0$, then $g(x)$ is a product of a nonzero irrational and a nonzero rational, hence it is irrational.
Let $z$ be a nonzero rational rational number.  Then $f(z)$ is irrational, so $g(z)$ is nonzero.  Hence, $g(z)$ is nonzero in a neighborhood of $z$.
Let $A$ be the set of points where $g(z)$ is nonzero (this includes all of $\mathbb{Q}$ except for $0$).  Since $g$ is continuous, this is an open set.  Let $I$ be the maximal subset of $A$ containing $1$.  Then $I$ is of one of two forms, $I=(a,b)$ or $I=(a,\infty)$, we note that $a>0$ since $0$ is excluded from $A$.
We begin by proving that $g$ is constant on $I$.  Suppose that $g$ were not constant on $I$, then there are $b$ and $c$ so that $g(b)\not=g(c)$.  Since, between any two numbers, there is a rational number, let $w$ be a rational number between $g(b)$ and $g(c)$.  By the intermediate value theorem, there is some $d$ between $b$ and $c$, so that $g(d)=w$.  This, however, is impossible because $g(x)$ is either $0$ or irrational.
Now, since $I$ is maximal, we know that $g(a)=0$ (otherwise, $I$ could be extended).  But then, by continuity, $0=g(a)=\lim_{x\rightarrow a^+}g(x)=g(1)$ since $g$ is constant on $I$.  But, this is a contradicton since $g(1)$ is nonzero.
Answer: I think the four year old answers did it.
If $w$ is irrational then $f(w)$ must be rational so there are only countably many such values.  If $v$ is rational there are only countably many rationals so there are only countably many such $f(v)$.  So there are only countably many possible outputs for $f$.
But $f(0) = a\not \in \mathbb Q$ and $f(\pi) = b \in \mathbb Q$ and $a \ne b$. So by intermediate value theorem there are values where $f(x_c) = c$ for all possible values of $c$ between $a$ a $b$.  But there are uncountably many values between $a$ and $b$ so that is impossible
As both Azarel and Syd Henderson pointed out 4 years ago.


Google Play music won't play album in order

Question: I've made a custom album/playlist and imported it onto my SD card on my phone. However, when I got to play the playlist, not only does it break up the album by artist, it won't even play in order. Every song has a track number, but it seems to be ignoring this. How I can I get it so the album is grouped together regardless of artist AND have it play the playlist in track order?
Comment: Check if the "random" button is on...
Answer: Sort by "time". Pick an album and set it. That will change the settings when playing the songs in the database. It will re-order the songs to the way they were loaded onto the memory card. They were originally loaded with a time stamp in sequential order, with one being slightly older than the other. It appears to be ignoring the proper order. That is how I got it to work without downloading another player. Nothing worse than trying to play "The Wall" out of order!
Answer: To play all songs by an artist when in Artist view, click the picture or album art to the left of their name. This will start playing a random song and then you can click the Mini Player at the bottom and you should then see the option to shuffle if it's not already enabled.


How can I transfer an NFT that is stored on openSea programmatically?

Question: I want to understand, how can I automate sending NFTs from any thirdparty hosts for example, opensea or thirdweb directly to the user who clicks on the claim NFT button on my website? I do not want to use reactJS for it. Is it possible with ethers.js? Basically I do not want to sign transactions manually everytime before transferring or sending the NFT to the user on my site. I am new to all this. Any help would be appreciated. Also what would I need to write in solidity to do this (even a stepwise algorithm would be super helpful)?
Answer: Take note of the following methods to achieve what is mentioned above:

OpenSea API: Since it is mentioned to transfer NFTs from OpenSea, this is the most logical option. Now you can choose any language for this. Sharing the Python and JavaScript examples here. First you will need an HTTP client library for making the requests. a) JS- for JS you can use axios or the native fetch API too.

// Fetch NFT data (e.g., a specific collection's assets)
async function fetchNFTData(collectionSlug) {
try {
const response = await fetch(<code>${apiUrl}/assets?order_direction=asc&offset=0&limit=50&collection=${collectionSlug}</code>,
<code>   {
      headers: {
        'X-API-KEY': apiKey,
      },
    });

    if (response.ok) {
      return await response.json();
    } else {
      console.error(`Failed to fetch NFT data. Status code: ${response.status}`);
      return null;
    }
  }

catch (error) {
    console.error('Error fetching NFT data:', error);
    return null;
  }
}
</code>
b) Python: For python you can go for the requests library.
2.Batch transferring contracts:

Multi-Signature wallets.


Turning LED light on with Pi

Question: I am looking to build a home security camera with a LED light attachment. Many people mention they use a IR Illuminator for the light source which often seem to be DC 12V. I am not sure how one would turn this on and off with a raspberry pi.
Comment: Use a ULN2003A or similar.  Probably the cheapest solution unless you have your own transistors/diodes spare.
Answer: Driving Relays directly from RPi GPIO might be a little dangerous. Additional circuit is required. Take a look at link below, it might answer all your questions in that topic.
http://www.openhomeautomation.net/control-a-relay-from-anywhere-using-the-raspberry-pi/
Answer: For connecting high power devices (like an electric kettle - don't ask why) to RPi, i use relays. Be sure the voltage needed to turn the relay on is ~5V - the standard voltage of GPIO output.
Comment: GPIO is driven by 3.3volts? Possibly your relay works on a range from 2V-5V which you are lucky I suppose.
Comment: @ppumkin i used a doubleelay. the small one was 2~5vdc and using pi's 5v it turned on the big relay.

Turning LED light on with Pi


What's the capitalization rule for tabulated entries?

Question: Do I have to capitalize each cell in a table, or only be consistent throughout the table?
Answer: There is no universal rule for formatting the entries in individual cells of a table; capitalization of those entries is strictly a style issue.
I checked three widely respected style guides (Chicago Manual of Style, Oxford Style Manual, and Words Into Type), and none of them has anything to say on this particular point. At the magazines where I've worked, the house style was to lowercase single-word and short-phrase cell entries, and to initial-cap (and end-punctuate) sentence-length entries. Nevertheless, this was strictly an in-house style decision; I've seen many instances where table cell entries are initial-capped even if they consist of a single word like Yes or No.
Both within a table and across multiple tables (if applicable), consistency is important, since it helps readers negotiate the sometimes challenging presentation of ideas that a complex or very succinct table may entail. Chicago, fifteenth edition (2003) has this to say on that point:

13.69 Consistency. However neat and orderly a table may appear, it must be checked not only internal consistency but for conformity to the text and to other tables in the same work. Column heads and stubs [entries in the leftmost column of the table] must match one another in style across a series of tables. Spelling, capitalization, punctuation, abbreviations, and symbols must likewise be regularized.
Answer: This might be better answered on the User Experience SE site. The general rule is "consistency": capitalize everything consistently.
Comment: I was refering to a printed report, not an app, but I guess it's the same :)


How to change tab stops for a single paragraph in Microsoft Word 2007?

Question: In previous versions of Word, I could just put my cursor into a paragraph or select the whole paragraph, and change the tab settings - it wouldn't change the settings of any other paragraph. In Word 2007, changing the tabs setting updates the whole document. How can I restrict my changes to a single paragraph?
Answer: Word 2007 didn't introduce any new behavior regarding this. When you select or place the cursor inside a paragraph, any paragraph-wide formatting will be applied to that paragraph only, retaining the integrity of the rest of the document.
Now, what you are almost certainly experiencing is a problem with the automated update feature for styles. This is an old feature (as old as styles in Word) that, once enabled, means any formatting changes to a paragraph using that style, will update the style definitions, which results in the remaining paragraphs using this style to be updated.
Let's get over with the simplest of cases:
This isn't happening to you on paragraphs using the Normal Style.
On this case:

just right-click the style from the
Ribbon Menu you are using on the
afflicted paragraph and select
modify.
Untick the Automatically update check
box

Hopefully this is enough for you. If not, read on...

Some users have this problem with the Normal style. Which is very odd.
I'm actually unsure as to why that would happen. If you right-click the normal style and select modify, you will see you don't have that checkbox. This style cannot be set to update automatically. But with some people it does(!).
To fix this issue:

Open the Document you are working on.
Press ALT+F11. This will open up
the VB Editor.
Go to the View menu of the editor
and select Immediate Window. This
is where we are going to type our
command to disable automatic updating
of styles.
Type: ActiveDocument.Styles(wdStyleNormal).AutomaticallyUpdate = False
Hit ENTER
Still on the VB Editor, click the
File menu and choose to save your document.

The new document will behave as you want it to.
EDIT:
Forgot one last bit of information...
It's possible that when you open a new Word document when firing word.exe, the problem will resurface either on the same regular style, or the Normal style (whichever was your case). To fix this, you'll need to update your Empty Document Template. To that effect:

Fire up Word from the executable or
icon in your Start Menu (do not
fire it up from an existing document)
Make the changes suggested above
again, whatever your problem was
(either a regular style, or the
Normal style).
After that, Right-Click again the style on the
ribbon bar and select Modify
Make sure Add to Quick Style list
is checked and check New Documents
based on this template
Click OK
Exit Word

New documents will now behave.
Comment: This sounds entirely plausible. I got the document from someone else, so it could easily be set up differently than everything I've done on my own. And yes, it was the Normal style. Unfortunately it will probably be Monday before I can try this out. Thanks!
Comment: Thank you, this worked perfectly even though AutomaticallyUpdate was already False. Unfortunately I was forced to use a table instead of tabs because of other formatting problems.


If the impulse response of a causal LTIC system is $h(t) = \delta(t) + \sin(t)u(t)$, is it marginally stable or unstable (BIBO)?

Question: If you take the $H(s) = \mathcal{L}[h(t)]$ the poles are on the imaginary axis so the system should be marginally stable, but is it?
Comment: The system is supposed to be causal so $h(t) = 0, \forall t < 0$. So yes, I meant $sin(t)u(t)$, sorry.
Comment: Okay, thanks for clarifying.
Answer: The Laplace transform of the given impulse response, i.e., the transfer function of the corresponding system, has two poles on the imaginary axis. According to the definition of marginal stability, that system is marginally stable.
It is, however, not BIBO stable, because given an input with a frequency equal to the frequency of the poles will result in an unbounded response. For a causal continuous-time LTI system to be BIBO stable, all its poles must be strictly in the left half-plane, i.e., their real parts must be negative.