Understanding Ryu OpenFlow Controller, mininet, WireShark and tcpdump

Question: I am a newbie to OpenFlow and SDN. I need help setting up the Ryu OpenFlow controller on a Ubuntu or Debian machine and understand a basic Ryu application.
Note: this question already has an answer.
Answer:
This is probably one of the longest posts I have written on Stack Overflow. I have been learning about OpenFlow, SDN and Ryu and would like to document my knowledge for a beginner here. Please correct/edit my post if needed.
This short guide assumes you already have knowledge of computer networks and major networking protocols. This guide will help you get started with OpenFlow from system setup.
1. What is OpenFlow and SDN?
Please read SDN / OpenFlow | Flowgrammable.
Further reading: The Future of Networking, and the Past of Protocols by Scott Shenker and Software-defined Networking, IEEE INFOCOM 2009.
Before you start:
The Infrastructure layer includes the routers and switches inside the network core.
The Control layer includes the PC that runs an OpenFlow controller along with the controller itself.
The Application layer includes the applications that run on top of that controller. In Ryu, these applications are written in Python.
OpenFlow is a protocol using which the Infrastructure and the Control layer interact. OpenFlow does not provide an API of itself. It is an open source protocol that is used by vendors who develop OpenFlow capable switches and by developers who write the controllers, like Ryu. The API is provided by the controller.
2. Setting up the Ryu OpenFlow controller on Debian 8
Prerequisites
You need internet access. If you are running Debian inside a Virtual Machine, issue the following command to automatically configure your Ethernet interface via NAT:
su
dhclient eth0

Enable sudo
Debian does not come with sudo by default. Some Ryu applications you'll use later on require sudo. You can install sudo and add yourself to the sudo'ers list as follows:
su
apt-get install sudo # you might need to do apt-get update first!
visudo

Find the line that says %sudo ALL=(ALL:ALL) ALL and add an entry immediately below it:
yourusername ALL=(ALL:ALL) ALL

Press CTRL+X and then press Y to save the changes to the sudoers file. Now you can logout as root to return to your own shell
exit

Enable Optimal Screen Resolution (VM Only)
If you are running Debian in Virtual Box, the default installation does not enable full screen resolution support for Virtual Box. You'll need a bigger screen later in section 3. It's a good idea to enable it now.
In the Virtual Machine's window, click Devices > Insert Guest Additions CD Image ...
Then cd to the directory containing the files
cd /media/cdrom

Debian won't let you run the script due to permission issues. Copy the files to your home directory, change the permissions, and then run it:
mkdir ~/VBOXGUEST
cp * ~/VBOXGUEST
cd ~/VBOXGUEST
chmod 755 *
sudo ./VBoxLinuxAdditions.run

Reboot
sudo shutdown -r now

Install Git
sudo apt-get install git

Install Mininet
Mininet allows you to virtually emulate various network interfaces on your laptop/PC. Install it using Git:
cd ~  # if you are in some other directory
git clone git://github.com/mininet/mininet
cd mininet
git tag  # this will list available versions
git checkout -b 2.2.1 2.2.1  # replace 2.2.1 with the version you wish to install
cd ..
mininet/util/install.sh -a  # default installation, includes all components, recommended

I recommend you install the OpenFlow Wireshark Dissector. You can later install Wireshark to analyze packets. The OpenFlow Wireshark Dissector helps Wireshark fetch as much information from OpenFlow packets as possible.
mininet/util/install.sh -h

Run the following command to check your mininet installation:
sudo mn --test pingall

Install Ryu OpenFlow Controller
An OpenFlow Controller communicates between the Control Layer and the Infrastructure layer using the OpenFlow protocol. Also, it's the controller that provides an API to develop SDN applications that run in the Application Layer (on top of the Control Layer). There are numerous OpenFlow controllers. Ryu OpenFlow controller is one that uses Python scripts as its applications. Again, install it using Git:
cd ~
git clone git://github.com/osrg/ryu.git

Install Wireshark
sudo apt-get install wireshark

Install the supporting Python modules
Debian 8.3 does come with both Python 2.7 and 3.4 installed by default. However, you need to install some Python modules that the Ryu applications (Python scripts) use. You can install Python modules using pip:
cd ~/ryu
sudo apt-get install python-dev python-pip python-setuptools
sudo pip install .

the above will automatically run setup.py located in this directory and fetch the missing Python modules from the Python Package Index. The script will automatically install all relevant modules. However, do run the following to make sure you aren't missing any module later:
sudo pip install webob
sudo pip install eventlet
sudo pip install paramiko
sudo pip install routes

Starting up
Start mininet to emulate 3 hosts and a switch using the following command:
sudo mn --topo single,3 --mac --switch ovsk --controller remote

You will see a mininet prompt. This prompt can be used to ping hosts, send packets between them, etc.
Open up another terminal window to run Ryu. In this example, we will run an application (simple_switch_13.py) that will emulate a simple layer 2 switch that will forward all received packets to all ports except the one received on.
cd ~/ryu
PYTHONPATH=. ./bin/ryu-manager ryu/app/simple_switch_13.py

Make sure you are in your home directory when you run this.
You are all set. To ping hosts and analyse the packet transmissions, please move onto the next section.
3. Experimenting with Wireshark and tcpdump
In this section, we will fire packets from one host to another using mininet, and analyze the resulting transmissions using tcpdump and Wireshark.
The way the packets get transmitted is exactly what we can control in Software Defined Networking. We do this by writing different applications that run on top of the controller. These applications form the Application layer of the SDN control plane.
Set up topology and run the controlling application
Note: In the earlier section, you created a topology with mininet, and started a Ryu application to control the transmissions. In case you rebooted, or exited any of them, I repeat the commands to create the topology and start the Ryu application here:
cd ~
sudo mn --topo single,3 --mac --switch ovsk --controller remote

and in a separate terminal window:
cd ~/ryu
PYTHONPATH=. ./bin/ryu-manager ryu/app/simple_switch_13.py

Play with packets
In the mininet prompt, issue the following to open a console window for each of the three hosts in the topology you created:
mininet> xterm h1 h2 h3

Stack these consoles so you can see them all simultaneously! Then in the xterms for h2 and h3, run tcpdump, a utility to print the packets seen by a host:
tcpdump -XX -n -i h2-eth0
tcpdump -XX -n -i h3-eth0

Note: If you have used Wireshark earlier, it's like capturing packets on the eth0 interface of these two hosts respectively.
When creating topology, mininet assigned the following IP addresses to the three hosts:
h1: 10.0.0.1
h2: 10.0.0.2
h3: 10.0.0.3

From host 1's shell, ping host 2 and host 3 and observe the effect on the other two consoles after each command:
ping 10.0.0.2
ping 10.0.0.3

Try pinging an unreachable (non existent host), and see the effect on the consoles:
ping 10.0.0.7

You should have observed the ICMP (ping) and ARP (who has this IP address) protocols live in this section! You can also do the above using Wireshark instead of tcpdump. That's a graphical alternative to tcpdump.
Note: The way the packets are forwarded ALL depends on the application running on top of Ryu. You could write an application to drop all packets. In that case, your pings would produce no effect on the other two consoles.
4. Understanding the basic Layer 2 Switch application
In this section, we analyze the working of a simplified version of a Layer 2 Switch application that controlled the transmissions of packets in section 3.
Working of a learning bridge (or a Layer 2 Switch)
I mentioned earlier that if you are reading this guide, I assume you already have knowledge of basic networking protocols, (which includes the working of a layer 2 switch, or a learning bridge, or an Ethernet switch!) I'll summarize it in a few lines below regardless.
A "learning" bridge stores a database of the hosts its connected to, against it's ports. The hosts are identified by the MAC address of their network card, which looks like this: ab:cd:ef:12:34:56 (it's in hexadecimal). The ports are identified simply by their number. For example, a switch with 4 ports has port 1, 2, 3 and 4.
If a switch receives a packet on its port 2, it will look at the destination MAC address (which host it's destined to) of that packet. It then looks into it's database to see if it knows which port is that host connected to. If it finds it out, it forwards that packet ONLY to that specific port. But if it doesn't have an entry in it's database yet, it floods that packet to ALL ports, and the hosts can check for themselves if the packet was destined for them.
At the same time, the switch looks at the source MAC address of that packet, and it immediately knows that host X is located at port 2. It stores that entry in that database. So now you know that if the destination host replies to the source host, the switch won't have to flood the reply packet!
Introduction to the Ryu API Python code
Instead of going directly to simple_switch_13.py, let's choose a very simple program that has no "learning" capability. For now, there is no forwarding database. The below program is just a simple layer 2 switch that transmits a received packet to all ports (floods the packet):
    from ryu.base import app_manager
    from ryu.controller import ofp_event
    from ryu.controller.handler import MAIN_DISPATCHER
    from ryu.controller.handler import set_ev_cls

    class L2Switch(app_manager.RyuApp):
        def __init__(self, *args, **kwargs):
            super(L2Switch, self).__init__(*args, **kwargs)

        @set_ev_cls(ofp_event.EventOFPPacketIn, MAIN_DISPATCHER)
        def packet_in_handler(self, ev):
            msg = ev.msg
            dp = msg.datapath
            ofp = dp.ofproto
            ofp_parser = dp.ofproto_parser

            actions = [ofp_parser.OFPActionOutput(ofp.OFPP_FLOOD)]
            out = ofp_parser.OFPPacketOut(
                datapath=dp, buffer_id=msg.buffer_id, in_port=msg.in_port,
                actions=actions)
            dp.send_msg(out)

The imports
I will not delve into the import statements yet. We will discuss the imports individually as we analyze the code that uses them.
The basic application skeleton
The following code is a perfectly complete Ryu application. In fact you can execute it too! It won't do anything though:
    from ryu.base import app_manager

    class L2Switch(app_manager.RyuApp):
        def __init__(self, *args, **kwargs):
            super(L2Switch, self).__init__(*args, **kwargs)

As an argument to the class, we pass ryu.base.app_manager.RyuApp import (imported in the first line). From the Ryu API handbook, app_manager class is the central management of Ryu applications. It loads Ryu applications, provide contexts to them and routes messages among Ryu applications.
The EventOFPPacketIn Event
A new method packet_in_handler is added to L2Switch class. This is called when Ryu receives an OpenFlow packet_in message. When Ryu receives a packet_in message, a ofp_event.EventOFPPacketIn event is raised. The set_ev_cls decorator tells Ryu when the associated function, packet_in_handler should be called.
The first argument of the set_ev_cls decorator indicates an event that makes function called. As you expect easily, every time a ofp_event.EventOFPPacketIn event is raised, this function is called.
The second argument indicates the state of the switch when you want to allow Ryu to handle an event. Probably, you want to ignore OpenFlow packet_in messages before the handshake between Ryu and the switch finishes. Using MAIN_DISPATCHER as the second argument means this function is called only after the negotiation completes. MAIN_DISPATCHER denotes the normal state of the switch. During the initialization stage, the switch is in HANDSHAKE_DISPATCHER state!
Now let's look at the body of the function. We'll break it down into two parts.
    msg = ev.msg
    dp = msg.datapath
    ofp = dp.ofproto
    ofp_parser = dp.ofproto_parser

ev.msg is a data structure that contains the received packet.
msg.dp is an object inside that data structure that represents a datapath (switch).
dp.ofproto and dp.ofproto_parser are objects that represent the OpenFlow protocol that Ryu and the switch negotiated.
    actions = [ofp_parser.OFPActionOutput(ofp.OFPP_FLOOD)]
    out = ofp_parser.OFPPacketOut(
        datapath=dp, buffer_id=msg.buffer_id, in_port=msg.in_port,
        actions=actions)
    dp.send_msg(out)

OFPActionOutput class is used with a packet_out message to specify a switch port that you want to send the packet out of. Since there is no forwarding database in this simplified application, we flood the packet to all ports, so the constant OFPP_FLOOD is used.
OFPPacketOut class is used to build a packet_out message.
By using datapath class's send_msg method, you can send an OpenFlow message object to the ports defined in the actions variable. I repeat, in this case, actions is built such that the destination includes ALL ports.
Events
You repeatedly saw the term event in the above code. In event driven programming, the flow of the program is controlled by events, which are raised by messages received by the system (e.g. EventOFPPacketIn is raised when the packet_in message is received by Ryu from the (OpenFlow enabled) switch). We earlier discussed that OpenFlow is a protocol using which the controller (Ryu, PC) and the infrastructure (or switch) communicate. Messages like packet_in are exactly what the communication between the two looks like using the OpenFlow protocol!
Next steps
You might want to go ahead and build your own Ryu applications. Learning the Ryu API (or the Python language, if you are not already familiar with it) might be a good point to start. Good luck!
Comment: The link to open networking foundation is broken. I checked the website, it does not seem to contain the resource you have mentioned.
Comment: If I remember correctly, that page was an introduction to OpenFlow which apparently is no longer on ONF website. The most relevant replacement now is http://flowgrammable.org/sdn/openflow. Also, another thing it linked to was the OpenFlow whitepaper which can be found here: https://www.opennetworking.org/images/stories/downloads/sdn-resources/white-papers/wp-sdn-newnorm.pdf
Comment: `nano /etc/sudoers` Please don't do this! Use `visudo` instead, otherwise you might lock yourself out
Answer: Something you may find useful for working with the Ryu controller is Ryuretic. Ryuretic is a modular, SDN-based, framework for network application development. It allows network operators to work directly with packet header fields at various levels of the OSI model, including L2, L3, L4, and shim layer protocols. The user simply chooses match fields and selects provided operations to update the OpenFlow switch.
The Ryuretic backend renders all events to the user as a pkt (a dictionary object), and the contents of the pkt are retrieved by providing the header field of interest (e.g, pkt['srcmac'], pkt['dstmac'], pkt['ethtype'], pkt['inport'], pkt['srcip'], etc.) Using the information from the pkt, the user can choose which fields to match and what action (fwd, drop, redirect, mirror, craft) to take when a match is found.
To install Ryuretic, simply copy the [files] (https://github.com/Ryuretic/RyureticLabs/tree/master/ryu/ryu/app/Ryuretic) to the directory /ryu/ryu/app/Ryuretic. If you installed Ryu, then you already have the /ryu/ryu/app directory. You just need to create the Ryuretic directory and copy the files there.
Ryuretic Labs provides setup instruction and some use cases for implementing security features on SDNs using Ryuretic. It also provides a Mininet testbed for testing your network applications on the VM provided by SDN-Hub.


What are the factors that affect detection when stealing in Fallout 4?

Question: In Fallout 4 (PS4), every now and then, when I'm trying to steal something, even if I'm Hidden, sometimes the owner still knows I stole from them. This happens even if I am completely Hidden and out of the line of sight. Anybody know why and how I can avoid it moving on?
Comment: I'm not sure about Fallout 4, but in Skyrim (another game by Bethesda), your success rate depends on the value of what you're trying to steal. The more it's worth, the more likely you'll be caught. For example, there were times I bought too much at once and became unable to steal my money back, so I'd load a previous save and alternate between buying one item, then stealing the money back, and repeating until I've got everything I wanted.
Comment: @Nolonar Oh my bad I should've clarified, I'm just talking about objects. Like for example, earlier I was trying to steal a Stimpak in a room completely separate from everyone in the house, but the second I walked back out they turned hostile.
Comment: Hidden a sin crouching?
Comment: Put points into Sneak.
Answer: Yes, as @Nolonar mentioned in comment, it depends on many things like: worth and how many objects in one turn if pickpocketing, on target level, his and yours Perception level, environment and daytime , your stealth skills, other NPCs around etc...
In case of looting diamond apartments timing is key, vendors homes when they working, upper class while they drink at bar. Recommend crouching before enter and when exiting, also good way in are roof hatches. With hyped thief skills is possible to steal fusion core from raiders or BOS wearing Power Armor, without it they exit and you can steal whole power armor.


Is there any in canon date of whether the goblins existed before normal human Wizards or Witches?

Question: Is there any in canon information at to whether the goblins existed before the Wizards and Witches or did human magic users exist before goblins?
Answer: As far as I know the furthest history we have of the goblins is that Ragnuk the First forged The Sword of Gryffindor "a thousand years ago" for Godric Gryffindor. Thereofre, it would be unclear which came first.

The sword of Gryffindor was made a thousand years ago by goblins, the magical world's most skilled metalworkers, and is therefore enchanted. Fashioned from pure silver, it is inset with rubies, the stone that represents Gryffindor in the hour-glasses that count the house points at Hogwarts. Godric Gryffindor's name is engraved just beneath the hilt.
The sword was made to Godric Gryffindor's specifications by Ragnuk the First, finest of the goblin silversmiths, and therefore King (in goblin culture, the ruler does not work less than the others, but more skillfully). When it was finished, Ragnuk coveted it so much that he pretended that Gryffindor had stolen it from him, and sent minions to steal it back. Gryffindor defended himself with his wand, but did not kill his attackers. Instead he sent them back to their king bewitched, to deliver the threat that if he ever tried to steal from Gryffindor again, Gryffindor would unsheathe the sword against them all.
Pottermore, Writing by J.K. Rowling, The Sword of Gryffindor


Question about mentioning gap year in SOP

Question: I took a gap year after my high school. It technically wasn't a gap year since I reappeared for my 12th grade(senior year) examination to increase my score. In 12th grade, I scored 62% in 2012 and then I improved it to 79% in 2013. The main reason I went for the gap year was to explore more about the 2 engineering fields I was confused about going into (CS and aeronautical engineering). During the gap year, I explored both the fields and decided to go with CS. Now, I've graduated. I'm applying to schools in the US for masters. Should I mention about the gap year in my SOP? If yes, what reason should I mention? Are universities very serious about this stuff?
Comment: In the intervening years did you earn a bachelor's degree?
Comment: Yes I did. I earned a bachelors degree in CS. The gap year was before undergrad
Answer: First, make your SoP forward looking, not backward. Only bring up past actions to support the idea that you are an excellent candidate who is well prepared and motivated and has excellent prospects for success. Your CV explains you past. Your SoP is for the future.
But I see no need to mention anywhere that you have a gap. Your transcripts and record will probably indicate something like that, so it isn't a question of deceit or hiding anything. It is (a) just too long ago to be very relevant and (b) too easily explained if anyone should ask about it.
Your record is what it is and you can't change it. Your future is your own to choose. Put the emphasis in the SoP on forward looking things and why they are achievable. Don't, in particular, apologize for anything in an SoP.
And, finally, I doubt most would notice the gap and fewer would care. Especially if you had some reasons - even a year in the South of France.
Comment: Thanks a lot! Yeah I have good academics and internship experience. The only bad thing was the gap year. Thanks. I appreciate it!


An example for a planar graph with different embeddings with different degree sequences of the faces?

Question: Let $G$ be a planar graph with a planar embedding with $f$ faces. The degree of a face $f_i$
is
the number $a_i$ of edges that are incident to $f_i$ (counting bridges twice). Assume that the
faces $f_1$, . . . , $f_f$ are ordered such that their degrees are non descending. Consider the degreesequence
($a_1$, . . . , $a_f$ ) of the faces.
Comment: Where is your question...?
Answer: Draw a convex hexagon $ABCDEF$ and two diagonals $AC$ and $DF$. Then you have degreesequence $(3,3,4,6)$. If you draw $AC$ as an arc outside of the heaxagon, you have $(3,3,5,5)$.
Comment: Hello @HagenvonEitzen!!! Do you maybe know what cooperating topological sortings are?
Comment: @evinda Whatever I can imagine they are, I certainly cannot relate that subject to this graph.theoretic question


Is it possible to upgrade old Mirage-III and Mirage-V variants with thrust vectoring engines?

Question: Is it possible to upgrade old Mirage-III and Mirage-V variants with thrust-vectoring engines so that they can match the maneuverability of F-16s?
Comment: Adding thrust vectoring to arbitrary airplanes is pretty much like adding rear wheel steering to arbitrary motor vehicles. Yes you get super maneuverability but more often it's just unstable and dangerous.
Comment: The simplest answer is NO. F-16s were designed and developed with such requirements. Whereas Mirages were never intended to do such manoeuvres. Even if you do so, you would end up compromising on the structural rigidity of the aircraft, which is already old by few decades.
Answer: Given enough tinkering, it is technically possible. But so many other modifications would be needed - strengthening, wing revisions to maintain the relationship between centers of lift and gravity, trim authority, managing the changes in stability, never mind the engine mounting and avionics refit, etc. etc. that really you would just be cannibalizing an old airframe to make an entirely new plane.
Somebody might conceivably do it as a short-life proof-of-concept prototype, if a new plane were proposed, the Mirage airframe was a good enough match, and a sophisticated digital control system was not necessary for these early tests. But in practice there is nobody in the world with all of the need, the industrial capability, the Mirages and the budget to embark on a new fighter programme that would require such a prototype.
Dassault did experiment with adding separate lift engines in the fuselage, in the Balzac V (which was just such a hacked-about Mirage III airframe) and the Mirage IIIV (which was twice the size), but it all went nowhere.


Image metadata in pdf

Question: Does pdf file contain metadata of used images? Is it possible to read metadata of images wich was used in pdf that file? Of cource pdf file was create by latex (texlive).
Comment: Do you want to know if it is possible to include such metadata, or do you want to know if such metadata is included and readable by default?
Comment: Second case. I want to know does I need to erase metadata from every my pictures before I use them to create pdf document.
Comment: I am not 100% certain, but I don't think metadata is added. You can check by decompressing the pdf (for example `qpdf --stream-data=uncompress input.pdf output.pdf`) and inspecting the raw pdf data in a text editor.
Answer: Yes
In principle, embedded JPG files in a PDF can contain valid EXIF metadata.
The responsibility of removing the metadata from images included in PDF files unfortunately relies on the user, unless the program used to generate such a PDF file includes a feature for that.
Amped, a software company specializing in software for image forensics, has an interesting blog post about this topic. Here's a quote from their example of a photo extracted from a PDF:

There are traces of processing with Adobe Photoshop left in the Exif metadata! Not only, Exif dates tell us that the image was captured well before February 2019, but it was edited on February 20th, 2019!
We notice there is plenty of Exif metadata: taking a look at them with the EXIF tool reveals that the image also contains GPS coordinates [...]
Comment: Both ImageMagick and GraphicsMagick can `-strip` metadata from images. In fact, this is a requirement if the PDF is in format `PDF/X-1a:2001` (print to paper, using some technologies). I assume that you (Andrea) arrived here via one of the graphic arts forums, where (I hope) this is well-known. But here at TeX, hardly anyone knows it.
Comment: @rallg correct. I often use said command line argument to strip the metadata. Given that the question asked if it's possible to **read** it, I thought I didn't need to mention how to remove it.
Comment: There is an old American joke. Something like this: Clem and Josh are small farmers (long ago). Clem says, "My horse has colic. When your horse had colic, what did you feed him?" Josh says, "When my horse had colic, I fed him alfalfa." The following week, they meet again. Clem says, "I fed my horse alfalfa, but the horse died." Josh says, "So did mine." My point: Clem asked what the horse was fed. He didn't asked if it helped.

Image metadata in pdf


FFMPEG Custom Read function reads all the data

Question: I'm trying to implement a custom read function for ffmpeg that will retrieve a buffer from local video ( from device in the future) and then deocde this buffer, etc..
So, here's my read function
int IORead(void *opaque, uint8_t *buf, int buf_size)
{
FileReader* datrec = (FileReader*)opaque;
int ret = datrec->Read(buf, buf_size);
return ret;
}

As for the FileReader :
class FileReader {
protected:
  int fd;
public:
  FileReader(const char *filename){ //, int buf_size){
     fd = open(filename, O_RDONLY);
  };

  ~FileReader() {
      close(fd);
  };

  int Read(uint8_t *buf, int buf_size){
    int len = read(fd, buf, buf_size);
    return len;
  };
};

and for the my execution :
FileReader *receiver = new FileReader("/sdcard/clip.ts");

AVFormatContext *avFormatContextPtr = NULL;
this->iobuffer = (unsigned char*) av_malloc(4096 + FF_INPUT_BUFFER_PADDING_SIZE);
avFormatContextPtr = avformat_alloc_context();
avFormatContextPtr->pb = avio_alloc_context(this->iobuffer, 4096, 0, receiver, IORead, NULL, NULL);
avFormatContextPtr->pb->seekable    = 0;

int err = avformat_open_input(&avFormatContextPtr, "", NULL, NULL) ;
if( err != 0)
 {...}
// Decoding process
  {...}

However, once the avformat_open_input() is called, the read function IORead is called and keeps reading the file clip.ts until it reaches its end and only then it exit and the decoding process is reached with no data to decode ( as all of it was consumed)
I don't know what is the problem especially that this code
AVFormatContext *avFormatContextPtr = NULL;
int err = avformat_open_input(&avFormatContextPtr, "/sdcard/clip.ts", NULL, NULL) ;

isn't blocking untill the end of the file is reached.
Am I missing something ?
I appreciate your help.
Answer: Most likely, avformat cannot determine the type of your stream. You should use something like
avFormatContextPtr->iformat = av_find_input_format("mpegts");


What is causing iTunes to open?

Question: Lately, I will go through periods where iTunes keeps opening itself repeatedly. It never plays anything or loads any files or URLs. But I can't figure out what is triggering it to open. Is there a log somewhere that shows why an app opened? Presumably it's due to a file association somewhere.
Comment: Same thing happened to me... I am running MacOS Sierra with iTunes 12.6
Answer: This is a super old question, but I can admit to giving up looking for a source for a rather long time. It turns out (in my case) that the magic "4th conductor" within the headphone port that is used for the microphone also is used for the remote control. ie: Vol up/down, Play/Pause, Next/Prev, etc. This works by shorting that 4th conductor in various ways. When the cord for my headphones, with only 3 conductors, wiggled in it's loose fit, my laptop thought that I had pressed the play button, which triggered iTunes to open up.
(I have also seen a similar thing happen with bluetooth headphones, as mentioned above.)
Answer: I was also experiencing this issue. I had turned off all the auto downloads in iTunes. Then, in System Preferences, I "delete"d iTunes Helper - which did not delete anything and may not have had any effect. I discovered later that it was when I turned on/connected Bluetooth headphones that iTunes opened without any notice in the background.
I haven't found a way around this yet, but at least I know what was causing it.
This was with iTunes 11.4 and OS X 10.9.5
Of course this may or may not be what is happening with your set up. I would be interested to know if other things also cause this.
Answer: I just had this problem start up. After an extremely frustrating troubleshooting process, I realized my Mac was accepting commands from my Logitech universal TV remote (which I was attempting to use with my TV). Every time I pressed the OK button on the remote, iTunes would start to play. I had never attempted to pair this remote with my Mac.
Answer: One thing I can think of that might help is to Open Console.app and filter (upper right corner) for "iTunes".
Another thought:  Is there an iDevice that is wifi syncing periodically on the same network?  Not sure how to test that other than turning off wifi.
Comment: AFAIK, iDevices won't let you sync over Wi-Fi if iTunes isn't open (it'll be grayed out).
Answer: As this is happening on my machine, I am guessing it is from a bluetooth speaker connection. As I've disabled any auto updates in itunes and removed the program from startup items. Also turned off any sharing on the computer. OSX 10.10.3  itunes 22.214.171.124. It's nothing really, but it's super annoying.
Answer: I have experienced iTunes app opening on it's own, too. I believe the external speaker connection is the culprit as well. Though, I did not have head phones connected, I did have external speakers plugged in.
I realized static electricity from a window fan directly next to my desk may've been responsible for the static & glitch. Avid users know to maintenance computer & auxiliary inputs against dust & static build up (i.e. avoid computer contact with carpet). Static electricity can flow from your finger tips too!
Having lived through reel to reel tape decks to record & playback music, I used my tape head de-magnetizer to eliminate static build up from my computer, screen & cables.  I do not recommend using a de-magnetizer because it may damage the hard drive and/or corrupt or erase stored data.
That said, a simpler & safer way to reduce and/or eliminate static charge to your computer & accessories might be to wipe w/ dryer sheet.  I can't attest to it's effectiveness but definitely think it's worth a try.
Answer: In my case, it was definitely the external speaker/headphone connection. I plugged in external speakers and iTunes kept opening on its own. I unplugged the speakers, no further problem.
Answer: if it's happening on your computer running the free program Malwarebytes might find and fix it -- if it finds any items have it remove them. Fast and easy.
Comment: It's not malware, this is a known MacOS 'behavior'.

What is causing iTunes to open?


K - means cluster always landing right on top of whole dataset mean

Question: I have a so so sized data set - 30 000 observations. I would like to run K-means on them but to restrict the center(mean) of the data. This is, I would like to push the clusters away from this mean. As I have noticed that independantly of the # of clusters, one ends up landing right on top of the mean of all the variables, like a smaller version of the whole data set. Is there a way to restrict K-means to not behave this way? By the way I have two different ways to initialize cluster centers, random starting points and means of random samples of the data. I run each 500 times and the solution seems stable enough but maybe k-means++ would have a different outcome? I wouldnt think so...
Comment: I may be a bit off-topic, but why can you not accept a cluster that happens to land at the overall mean? Is it known or obvious that there is no cluster there and it's somehow an artifact of the algorithm?
Comment: I can totally accept it as it clearly reflects a pattern in the data but I am doint this for someone else and "he" wants to see what happens if we try this. Is it is even possible. Greetings.
Comment: The next question would be, what program are you using to do K-means? R, SAS, Stata, SPSS? Each might offer different initialization options that might help you. (In R's default kmeans, for example, you can manually specify the initial cluster centers. I doubt that you can keep a center from migrating where you don't want it, but there may be other R implementations.)
Comment: Yes, I'm using R and I have used the initializations I described. But I would still like to "force" it, I don't know... force it out of the "center" or, restrict it to not be able to converge there; I'm not entirely sure it makes sense.
Answer: I can't see any way to do what you want with the basic k-means routines in R.
The best trick I can think of is to use one of the c-means routines and then at the end take all points that have their largest membership in your Forbidden Center Cluster and reassign each one to the cluster with its second-largest membership.
You could also look at flexclust and its kcca, or really dig deep into the mclust or fps packages and roll your own.
Or you might abandon k-means clustering and use something else. R has a whole boatload of other methods, but I'll point out that flexclust's cclust has a Neural Gas clustering option. I have always liked Neural Gas, if only because it's a cool name. No guarantee that a different clustering algorithm will work better then k-means, but it's worth a try.
Comment: What is c-means? I'll look into it, thank you!
Comment: @JEquihua: c-means is continuous rather than hard, so each point has a value [0, 1] for each cluster. So if a particular point has its highest value for your center cluster, you can look for its second-highest value and put it in that cluster. The problem is that near the center of your forbidden cluster all of the other cluster values may be very small and nearly the same.


Select to recycle worker processes after a specific period of inactivity

Question: Can anyone confirm that this statement "Select to recycle worker processes after a specific period of inactivity" in this Microsoft help file is wrong and should in fact not have the "of inactivity" at the end of it?
Answer: Yes, that seems wrong. As far as I'm aware, this option just recycles the processes regardless of whether they are idle or not.
This article seems to confirm that too.
Answer: The statement you quoted is correct. It's a way to allow you to free up resources that aren't being used.

When it is necessary to conserve
  system resources by terminating unused
  worker processes, you can configure a
  worker process to gracefully close
  after a specified period of time. You
  can use this feature to better manage
  the resources when the processing load
  is heavy, when identified applications
  consistently fall into an idle state,
  or when new processing space is not
  available. You can also start
  additional worker processes to replace
  a worker process that is finished.

http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/83b35271-c93c-49f4-b923-7fdca6fae1cf.mspx?mfr=true


Asymptotic behavior of convex functions

Question: Let $f:\mathbb{R}^n\rightarrow\mathbb{R}$ be a $C^2$ convex function which is strictly
positive. If $x_n$ is a sequence of points such that $f(x_n)\rightarrow 0$, show that (or
give a counterexample) the gradient $\nabla f(x_n)$ also tends to zero.
Comment: By an accident I posted my answer twice. And don't know how to delete
the second one:-)
Answer: A counterexample is
$$f=\sqrt{y^2+e^{-x}}.$$
You can verify by computing the second derivatives that this is convex.
As a sequence $x_n$ you can take $(n,1/n)$. Then $f(x_n)\to 0$ but the derivative with respect to $y$  tends to 1. Thus the gradient does not tend to 0.
Comment: Thank you very much. Now, if we suppose the gradient map of $f$ limited (which is the case I have in mind), do we get a positive answer?
This problem arose in the following setting: Suppose $\Sigma$ is a complete hypersurface in $\mathbb{R}^{n+1}$ such that the position vector is everywhere transverse to it and $\Sigma$ is locally strongly convex (whith the position vector pointing to the convex side). Then I was trying to show that the property of $\Sigma$ being asymptotic (or not) to the boundary of the convex cone $\mathcal{C}$ which it generates is equivalent to the property of its
Comment: (continuing....) conormal image $\Sigma^*\subset(\mathbb{R}^{n+1})^*$
be closed in $(\mathbb{R}^{n+1})^*$.

Asymptotic behavior of convex functions


Particle trapped in a double well potential and "slowly" increasing the height of the potential barrier

Question: Today I was musing over the following problem. Consider a non-relativistic particle confined in an one-dimensional double well potential of the form $V(x)=\kappa(x^2-a^2)^2$ where both $a$ and $\kappa$ are positive constants. As far as I know, it is not possible to analytically determine the position space wavefunction $\psi_0(x)$ corresponding to the exact ground state. However, the reflection symmetry of the Hamiltonian dictates that the ground state wavefunction $\psi_0(x)$ be either an even or an odd function of $x$ (there is no ground state degeneracy in this problem). Suppose the particle is prepared in the ground state at $t=0$. What will happen to the ground state wavefunction as the barrier between the wells (and therefore the Hamiltonian) is adiabatically (slowly) allowed to approach infinity by letting $\kappa\to\infty$ and $a$ fixed?
Answer: The behavior is known already. One study that does a numerical treatment of a double well problem is (http://iopscience.iop.org/article/10.1088/0143-0807/33/6/1651). Roughly speaking the ground state has a peak around each minimum of the potential. They deal with three approximations, square double-well, double well pasted with a cusp, and the "Sombrero" one you ask. They all share the same qualitative behaviour for the ground-state. Making $\kappa$ large will just change dimensions of the peaks. Infinity per se is unphysical, since you must have a potential which is defined in the region in which you intend to solve the Schrödinger equation. Making $\kappa$ infinity is equivalent to isolating the two wells completely.
P.D. I believe in one dimension the ground-states have to be even. (See Ground_state_has_no_nodes_in_one-dimension)


Getting time out error using NFS on Synology NAS

Question: I know this question has been asked a few times, but please bear with me. I'm new to Linux (only been using for a few months, but I like to think I have learnt fairly quickly, and am halfway confident using the terminal).
I recently purchased a Synology Diskstation 215j, and when I first set it up all things were working quite smoothly. A few days later, it would appear after an update on the diskstation, I can suddenly only access it through the web UI and FTP on my Ubuntu 15.10 laptop, and on my Raspberry Pi Openelec machine I can only access my media using Plex, whuich is not at all ideal. I would like to have the diskstation mounted at boot on both, if possible.
Running
mount 192.168.1.ip:/volume/share /media/destination

comes back, after quite some time, with an error message simply saying "mount.nfs: Connection timed out"
I have also tried mounting using SMB, which has consistently returned an error message either "error 22: invalid argument" or "error 115: operation in progress".
I have tried all sorts of variations on options, workarounds that people have used on this forum, specified "sec=" and changed settings on my NAS drive, installed helper programs, checked cables, all sorts. I've exhausted my own (meagre) knowledge and learnt plenty more while trying to sort this out, and now I'm totally stuck. Any help or suggestions would be fantastic.
Stuff I already looked at:

http://ubuntuforums.org/showthread.php?t=1906584
http://wiki.openelec.tv/index.php/NFS_Shares_with_Synology
The HowTo page for NFS.

Plus a few more I can't remember right now.
Thanks from a newbie.
Comment: Stupid question but the `mount` command you show above, is that how is exactly typed?
Answer: I've been looking for quite a bit to do exactly that (DS1621+, DSM7.0, Ubuntu 20.04.2 LTS), but would only get the dreaded 'Connection timed out' message.
After many unsuccessful attempts to troubleshoot, I finally bumped into this doc.
The instructions on this Synology help page are incorrect.
The actual mount command that made it work all of a sudden was:
sudo mount -t nfs4 -o proto=tcp,port=2049 nfs-server:/volume1/share /nfs/share

(Obviously do adapt the last two arguments as needed).


Is the fdisk partition type important when using lvm

Question: I have inherited a few LVM volumes and I noticed that fdisk reports the disks that make up the volume group as partition type 83 (Linux) and not 8e (Linux LVM).  Is this a problem and how important are the fdisk partion types?  Do they affect anything or are they just labels for convenience sake?  Thanks for your help.
Answer: LVM does not look at the partition table at all - it doesn't even knows it actually exist.
So you can set whatever "partition type" value you want there and it won't change anything as far as LVM is concerned.
LVM uses regular expressions in its config file to know what block devices to check for physical volumes, see the filter keyword in lvm.conf(5).
Some other tools do look at partition types, the linux kernel itself being the first example:

partition type 0x05, "Extended", tells the kernel to go look for an Extended Boot Record in the given partition, to find so called "logical partitions"
partition type 0xfd, "Linux RAID", tells the md driver in the kernel to try to autostart that raid volume, if it finds a suitable superblock in the given partition
Answer: The partition type is not important for lvm, md or mount. All of them are checking for signatures and internal structures to determine if they can use the device. Only user friendly partitioning programs might get confused. You can safely change the partition type if you want to be correct.
I think it is better not to use MS-DOS disk-label (partition table) at all if the disk is the 2nd disk in the system and you intend to use LVM. You can use LVM disk-label directly on the disk. For x86 and x64 architecture you need to use MS-DOS partitions (or GPT for UEFI systems) for boot disk, but the rest can have the LVM disk-label directly on the unpatitioned disk.
Comment: And the fact that you can do something in a different way does not means that is wise to do that.
Comment: is there any limit to the partition types i can change it to?  could i change it from type 83 linux to type b w95 fat32 ? or is it just within the minix/linux types (i.e. 8X).  thanks for your help.
Comment: You can have problems if you put it extended, because the kernel will search for logical partitions. It will actually search for a partition table at the beginning of the partition marked as extended. If you have 2 partitions marked as extended you can have more compatibility problems. I strongly suggest to use the right type. And you can change from a linux type to a fat/fat32 type without no problem in linux. But be careful because Windows will ask you to format those partitions.


Example of absolutely continuous function $f$ with $\sqrt{f}$ not absolutely continuous

Question: I'm looking for an example of a function $f$ that is absolutely continuous, but $\sqrt{f}$ is not absolutely continuous.
I've been playing around with the Cantor-Lebesgue function, but I feel like there should be something simpler.
Answer: I believe
$f(x) = x^2 (\cos \frac1x)^4$
is an example on the interval $(0,1)$. While a proof is certainly needed, the key observation is that sum of the infinitely many local maxima of $f$ converges (indeed $f'$ is uniformly bounded), but the sum of the infinitely many local maxima of $\sqrt f$ does not converge.
Answer: No Cantor-Lebesgue type of example will work, at least not on a closed interval $[a, b]$. This is because if $f(x)$ is absolutely continuous on $[a, b]$, then so is $(f(x))^p$ for any $p > 0$. The argument goes as follows: $f(x)$ is absolutely continuous on $[a, b]$ iff $f'(x)$ exists and is Lebesgue integrable almost everywhere on $[a, b]$, and $$f(x) = f(a) + \int_a^x f'(t) dt$$ for all $x \in [a, b]$.
Suppose $f(x)$ is a nonnegative, absolutely continuous function on $[a, b]$. $f(x)$ is absolutely continuous only if it is absolutely continuous on every finite subcollection of closed intervals of $[a, b]$. Since $f(x) \equiv 0$ on any subinterval of $[a, b]$ implies $\sqrt{f(x)}$ is also identically zero on that subinterval, hence automatically absolutely continuous there, WLOG we can assume the support of $f(x)$ is $[a, b]$. This implies that the set $Z_f := \{ x \in [a, b]: f(x) = 0 \}$ has measure zero in $[a, b]$.
Since $f(x)$ is differentiable almost everywhere on $[a, b]$, $\sqrt{f(x)}$ also has a Lebesgue integrable derivative almost everywhere on $[a, b]$, as $$\frac{d}{dx}\sqrt{f(x)} = \frac{f'(x)}{2\sqrt{f(x)}}$$
wherever $f'(x)$ exists and $f(x) \neq 0$, and $Z_f$ has measure zero. So to show $\sqrt{f(x)}$ is absolutely continuous, we just need to show that, if $g(x) = \frac{f'(x)}{2\sqrt{f(x)}}$ wherever this expression is defined and $g(x) = 0$ elsewhere, then $$\sqrt{f(x)} = \sqrt{f(a)} + \int_a^x g(t) dt$$ for any $x \in [a, b]$, since the set where $\frac{f'(x)}{2\sqrt{f(x)}}$ is undefined has measure zero. Since $[a, b] \setminus Z_f$ is open and has full measure, it follows that we may write $(a, b) \setminus Z_f$ as a finite or countable union of open intervals $\{ I_j \}_{j \in S} = \{ (a_j, b_j) \}_{j \in S}$ such that:

$\sum_{j \in S} (b_j - a_j) = 1$
$f(a_j) = f(b_j) = 0$ for all $j \in S$, except possibly if $a_j = a$ or $b_j = b$.

Here $S = \{1, ..., n \}$ for some $n$, or $S = \Bbb{N}$.
Clearly $g$ is Lebesgue integrable on each of the $I_j$, and $\sqrt{f(x)} - \sqrt{f(y)} = \int_y^x g(t) dt$ whenever $a_j < y < x < b_j$ for some $j \in S$. If we let $y \rightarrow a_j$, by continuity of $\sqrt{f}$, we can evaluate the improper integral $\int_{a_j}^x g(t) dt$ as
$$\int_{a_j}^x g(t) dt = \lim_{y \rightarrow a_j} \int_y^x g(t) dt = \lim_{y \rightarrow a_j} \sqrt{f(x)} - \sqrt{f(y)} = \sqrt{f(x)} - \sqrt{f(a_j)}.$$
A similar limiting operation letting $x \rightarrow b_j$ shows that $\int_{I_j} g(t) dt = \int_{a_j}^{b_j} g(t) dt = 0$ whenever $f(a_j) = f(b_j) = 0$. If $U$ is the $I_j$ with left endpoint $a$, we also find that $\int_U g(t) dt = -\sqrt{f(a)}$. So either $x \in U$, in which case $\int_a^x g(t) dt = \sqrt{f(x)} - \sqrt{f(a)}$, or else $x \in \operatorname{cl}(I_j)$ for some $I_j = (a_j, b_j) \neq U$, in which case
\begin{align*}
\int_a^x g(t) dt &= \int_a^{a_j} g(t) dt + \int_{a_j}^x g(t) dt \\
 &= \int_U g(t) dt + \sum_{I_k \neq U: I_k \subseteq [a, a_j]} \int_{I_k} g(t) dt + \sqrt{f(x)} - \sqrt{f(a_j)} \\
 &= -\sqrt{f(a)} + 0 + \sqrt{f(x)} \\
 &= \sqrt{f(x)} - \sqrt{f(a)}, \
\end{align*}
which shows that $\sqrt{f}$ is absolutely continuous. A similar proof shows that if $f(x)$ is absolutely continuous on $[a, b]$, then so is $(f(x))^p$ for any $p > 0$. That also implies that no positive power of the Cantor function can be absolutely continuous on an interval, since otherwise the Cantor function itself would be.


lattice-tool path issue

Question: I have downloaded and installed a perl tool (lattice-tool).
But it is in my local directory.
While I'm running it says can't locate Directed.pm(a lib file) which is available in lib folder of my local directory.
I hope it will be set right if I set path variable. If so, how do I set it?
Answer: For use lib you have to use full path, and you are should not use relativ path like this.
use '../lib';#not working in all times.

Scenario: Your scripts in something/bin/prog.pl, your lib is something/lib/lib.pm.
If you use relativ path, you should call your program like this:
cd something/bin/ && ./prog.pl

If you would like to use relativ path, use FindBin to find your current path:
use FindBin;
use lib "$FindBin::Bin/../lib";#your lib realitv to your script
use lib $FindBin::Bin;#your current script full path

Then you could call your program from anywhere it will always find its lib realtiv to itself.
cd ~
something/bin/prog.pl# ti will use the correct lib

Answer: In my scripts, I have the following (which I'm sure can be improved, but it has worked thus far):
my $mydir;  BEGIN { ($mydir) = ($0 =~ m#(.*)[/\\]#) or $mydir = '.'; }
use lib "$mydir/lib";

So the script tries to determine its own directory and then tells Perl to look for libraries within the lib subdirectory of that directory.
Answer: You need to add 'lib' to the directories perl searches for modules.  You can do this with the -I flag:
 perl -Ilib lattice-tool.pl

Comment: Another option is to set the `$PERLLIB` environment variable.
Answer: Use lib:
use lib 'lib';

lib also checks for architecture specific sub directories under lib to make sure machine-dependent libraries are loaded.
EDIT: Note that directories passed to lib are relative to your current working directory, so that if you want to execute your script from another location you should use use lib '/home/user1126070/lib'.
From perlvar:
The array @INC contains the list of places that the do EXPR , require, or use
constructs look for their library files. It initially consists of the arguments
to any -I command-line switches, followed by the default Perl library, probably
/usr/local/lib/perl, followed by ".", to represent the current directory. ("."
will not be appended if taint checks are enabled, either by -T or by -t .) If you
need to modify this at runtime, you should use the use lib pragma to get the
machine-dependent library properly loaded [...]

lattice-tool path issue


How does a CA send a digital certificate?

Question: I would like to know after approving the Certificate signing request, does the Certificate Authority send the Digital certificate to the applicant by converting the digital certificate to PEM format and sending it as a .crt file via email or does it send the digital certificate in some other way?
Answer: There is a standard for exchanging messages with CA, but it is rarely implemented in practice. Existing commercial CA that deal with many remote customers tend to organize the certificate issuance process through some custom interface (often Web-based) and the certificate-sending is part of that process. Various methods are used in practice, possibly combined:

Sending the certificate over email.
Make the certificate available to the user over HTTP (the URL being displayed in some Web page, or even sent by email).
A custom protocol between the CA and a CA-controlled component that runs on the user machine (Applet, ActiveX control, full-blown "management console" application...).
Any "manual transfer" protocol in some specific situations (e.g. when an offline root CA issues a certificate for an intermediate CA, the transfer must involve something like a USB key, since the root CA is offline).

The certificate itself is commonly encoded "as is" (X.509 DER, or PEM), or wrapped into a so-called PKCS#7 (CMS) object. CMS was never meant to convey certificates (it is an encryption and signature format) but it is traditional to use it to send a certificate and a set of "helper certificates" (intermediate CA for its validation).
Some CA generate the private key themselves (on the CA side), and, in that case, the private key must be sent to the requester; usually, a PKCS#12 (aka PFX) archive is used to contain both the certificate and the private key, with password protection (password-based encryption).
Since a certificate is signed and contains only public data, its integrity is readily verified upon reception, and it how it travels is unimportant for security. This is the main good thing about certificates.
Comment: CA-side private key generation makes sense for organization-specific CA, for encryption keys: encryption keys must be backupped (to avoid data loss when an employee becomes unavailable or when his machine crashes) and doing the key generation on the CA allows for a centralized unavoidable backup process.
Comment: "Some CA generate the private key themselves" - this should be avoided as of course negates the notion of *private* key. Even if say say so you *cannot* be sure that they don't keep it or forward it to NSA right away
Answer: Since certificates are tamper-proof by design, and only contain public information, they do not need to be delivered in a secure way. As you say, a PEM encoded certificate is just a file, so you can send it the same way you send any other file. Emailing it as an attachment would work, and I'm sure some CAs offer that as a delivery method.
Here we mainly use the Entrust CA, so that's the one I have the most experience with; with them you create an account on their site which gives you access to their shopping cart to order certs / upload CSRs. When the cert is ready they send you an email letting you know that you can log in again and pick it up (right-click "Save As" from the list of certs you've ordered).
Answer: CA is about evaluating data in the CRT and signing it, resulting in X.509 certificate of public key. Communication is not the major point. It could be email, http, directory (ldap) or whatever client would pick his certificate with. Format is not the point as well; binary DER-encoded and PEM are common solutions.


Accessing ivars of an objective-c class within c++ function

Question: I have an objective-c class, which has a string ivar which I need to change when a callback function is called. The trouble is that the callback is in c++, and I therefore cannot access the ivars of the objective-c class in that c++ function. The callback must be in c++ that, cannot change. I realize that there are other ways this could be done ie a global variable which is set by that function and read by my class, or a wrapper c++ class which contains the function and a string and is a member of my objective-c class. However I feel that simply setting the ivar within the callback would be the simplest and cleanest way to do it. Anyone know of a way to do such a thing?
Answer: I would use a getter/setter on the Objective-C class and pass it to the function as context info.
Answer: This seems you need to code c++ and objective C in the same code
so just add extension of the file as .mm and just can write c++ and objective c easily.


laptop suspend resumes immediately in ubuntu 13.04

Question: I have a lenovo IdeaPad P500 laptop. While running 12.10, it suspended and resumed just fine but after upgrading to 13.04 yesterday, when I suspend it (either by closing the lid or using the "cog" icon), it goes down, and then resumes immediately. Is there any fix for this?
Answer: Suspend from terminal.
<code>sudo pm-suspend
</code>
IIRC, it will print errors. You will have something to go on.


When can $\,x\bmod m\,$ be computed from $\,x\bmod n?$

Question: Can x mod (N - a) or x mod (N + a) be calculated just by knowing x mod N? where a is an arbitrary integer, and N is a prime. e.g. i know 22! mod 23 ≡ 22 using Wilson's theorem. lets say i want to know 22! mod 24, is there a way i can do so without solving the factorial?
Comment: I added an answer which discusses the general case.
Answer: If $\,d := \gcd(n,m)=1\,$ then there is no relationship between $\,a = x\bmod n\,$ and $\, b = x\bmod m\,$ since CRT $\,\Rightarrow\,x\equiv a\pmod{\!n},\ x\equiv b\pmod{\! m}\ $ is solvable for all values of  $\,a,b.\,$ This is true in your example $\iff 1 = \gcd(n,n\pm a) = \gcd(n,a).$
However, when $\,d > 1\,$a solution exists iff $\,b\equiv a\pmod{\!d},\,$ and this does place constraints on the values $\,b\,$ that $\,x\,$ can take $\!\bmod m$. Then $\,b\,$ is determined uniquely iff $\,m\mid d\iff m\mid n\ $ (i.e. iff $\,n\pm a\mid n\,$ in your example), hence $\,x\bmod m = (x\bmod n)\bmod m\,$ is uniquely determined. This arises frequently, e.g. knowing $\, u = x\bmod 10 = $ units digit of $x$ we can compute its parity by taking the parity of its units digit, i.e. $\ x\bmod 2 = (x\bmod 10)\bmod 2 = u\bmod 2,\,$ e.g. $\,123\bmod 2 = 3\bmod 2 = 1$.
Answer: For the specific case $22!$, the answer is easy: since $4 \leq 22$ and $6 \leq 22$ you have that $22! = 0 \pmod{24}$. However, we didn't use the fact we got from Wilson's Theorem, and it doesn't help us in general.
The answer to your question is no, and here is an illustrative example: suppose you know that $x = 5 \pmod{10}$. Then you could have, among many options, that $x = 5$, or that $x = 15$. In the former case, $x = 5 \pmod{12}$. In the latter case, $x = 3 \pmod{12}$.
Comment: But the answer can be yes too, e.g. $\,n=10,  n−a=5.\ $ See my answer for the general case.


How can I decrypt my files from "Cryptowall" encryption?

Question: I just got infected with "Crypt0L0cker" malware,virus or whatever that might be. They gave me a link (http://bica3zjnvl6fxkqf.tor-area.org/jrrk14.php?%20user_code=94aya99&user_pass=2616, the target site being suspicious the link is voluntary not clickable) to pay the ransom.
I don't know if is the "real" "cryptolocker or a copycat, but since I've opened the e-mail, (the virus was attached to a simulated electrical bill), it encrypted all my files in minutes.
One of the problems is that the external backup HD was also attached at the time.
I don't have any possibility to pay, and even if I would, I wouldn't pay them a nickle, since they will most certainly use the ransom money to develop an even more awful tool.
I've tried already "HexCmp2", "Decrypt_mblblock", "RakhniDecryptor", "ReactorDecryptor" and "TorrentUnlocker" but nothing seems to work.
Is there any way I could decrypt my files, any tool that will work?
Comment: Also - I am sorry to say, I just had to deal with this myself (for a family member, not myself) and sadly enough it looks like they are one of the few that got crypto right - which means there is no simple way to break it :-( I really hope to be proven wrong...
Comment: For one thing, stop running random programs you find on the internet - this is how you got caught in the first place! ;-)
Comment: For next time - https://crashplan.com
Comment: @CountIblis: it's been a while since "online activities" *weren't* part (most, even) of what I "normally work on". Which is not to say it's impossible to separate, but I think it's astonishingly inconvenient for most people. It's the fact the virus got to the only backup that's the real blow here, otherwise it wouldn't particularly matter that the "normal work" machine was trashed.
Comment: Try using shadow copy explorer and if not working, give a chance to forensic tools like scalpel or foremost.
Comment: Or use a separate device for online activities, e.g. your smartphone, another computer, your TV etc., you can connect to such a device from the computer you normally work on using programs such as VNC, TeamViewer, SmartView etc.
Comment: Other problem is that I've re-installed the Windows after I deleted the virus
Comment: I do not know if this malware is based on this, but the author of one of the biggest ransomware has published the keys. One may work for you if Crypt0L0cker is a fork.
Answer: I do not want to be pessimistic but the ransomware author is the only party that knows the needed private decryption key. CryptoLocker uses using a mixture of RSA & AES encryption. There are good security practices to prevent your computer from being infected by it, but once infected there is not something to do really about it for the moment. Do not waste money in buying tools pretending to be able to decrypt the files. But if you have done previous some restore point using System Restore of Windows then you have a big chance to recover your files.
Comment: Sadly, the solution I found was to nuke it. Trying to use the System Restore seems like a great idea, but it only works if it has the files. Usually, some programs when installed will create such point. But the System Restore isn't a great great resource, but may work. Notice that after trying to restore the system, you don't want to keep that Windows installation and you will really want a clean version. In short, try to use System Restore, copy whatever you can and format it.
Comment: Don't forget to wipe that bootloader. It's heaven for rootkits and it can survive formatting.
Comment: Saddly yeah, I've just saw a "sad" thing on "Boxcryptor" website : -" Cracking a 128 bit AES key with a state-of-the-art supercomputer would take longer than the presumed age of the universe. "
Comment: @Arx On the whole, that's not so sad, since pretty much all of e-commerce (and lots of other things that need to be secure) depend on that. If you could easily break AES, we'd have much bigger problems than Cryptolocker.
Comment: Thanks alot for the help, I've never used that tool before, but I'll give it a shot :)
Answer: One could recover from older infections by file-restoration programs and even decrypting the crypted ones (using the leftover deleted key).
None of these options work anymore (unless you pulled the powerplug/battary when your hd started to perform excessive work (nobody did or recognizes that, especially on non-tweaked FF/Win8 hd-killing software)).
After full encryption the key is shredded (no longer just deleted), as are the restore points and encrypted/deleted data.
The main point I'm posting this answer however is to warn: the machines that I've had to work on ALSO had infections in the system-recovery (I mean, 'back to factory' aka 'reinstall windows'), however on most machines this led system-recovery to fail entirely, thank [enter deity here], otherwise one could get the illusion one at least got their OS back.. (not realizing the hostage-software and identity-theft malware that is also shipped (hey these guy's and their 'support-employees' got to get payed even if the victem doesn't do it themselves..) would be ready for another go at it..)
If you got this pest, bring your pc to an advanced repair person/center to recover your OS license, wipe correctly and reinstall legally (you had a legal machine right?).
Also clean all your USB (I had one customer f up his machine the moment he got home with an infected USB stick) and external drives!
PS: don't waist to much time investigating your options, after a week the ransom will be double (and so on).

That being said (warned!!!), victims of older cryptolocker can visit: http://www.decryptcryptolocker.com/ to get their data back for FREE.

"All they have to do is submit a file that's been encrypted from that
  we can figure out which encryption key was used," said Greg Day, chief
  technology officer at FireEye.

Source: http://www.bbc.com/news/technology-28661463  (here you can also see a picture and the name of the one who did this to you.. (and stole over 3Milion $ from justice departments, law-enforcement, governments, corporations, and you and me).
It might pay off to backup the encrypted data securely and wait..
Comment: forgot to mention: it is known that about 5 to 20 % (on average, including the latest versions of cryptowall) of your files are *not* recovered using the decryptor the criminals send to you. They are lost forever (their 'support' is only 'helpful' to get you to pay, after that 'support' ends), so you need to take this into consideration! You can check your registry for a full list of your encrypted files (this key must remain intact if you want to pay the ransom and run the decryptor). The current list of encrypted file-extensions is not that big.
Comment: http://www.decryptcryptolocker.com/ doesn't work anymore. "We believe that our Decryptolocker site has served its purpose, and we have decommissioned it given that the threat landscape has evolved."
Answer: If the malware creator did his crypto correctly, there is no way to decrypt the files. Strong crypto is strong, no matter whether it's used for good or nefarious purposes.
Some of these ransomware happen to transmit the key over unencrypted HTTP to their remote server; in the rare case you had an HTTP proxy intercept the connection, you may look at the proxy's logs and see if the key is there.
Comment: Unfortunately, Cryptolocker uses PKI, and the private key is on the attacker's computer, so sniffing or intercepting traffic won't help.
Comment: Thanks you all for support, I think my problem is "unsolvable", at least for now, maybe I'll just save the encrypted files somewhere, it may come in handy if in near future someone will find a way to decrypt them, but I sincerely doubt it.


disable eclipse warning "Projects must be referenced by an EAR or a WAR to use classpath publish/export dependencies..."?

Question: I have a library that is used in several different eclipse projects (that I keep in different workspaces), some of which are Java EE projects (i.e. dynamic Web projects) and some which are plain Java projects. It is therefore present in multiple workspaces (that reference a shared subversion repository to keep the copies in sync).
In order to get the library's dependencies exported correctly for the Web projects, I've added the jar files it references to the project's deployment assembly tab with a path of "../" (using the Java Build Path Entries option in the deployment assembly tab). This works wonderfully for the Web projects, but when I open the project in a workspace that doesn't have a Web project, I get the following warning:
Projects must be referenced by an EAR or a WAR to use classpath publish/export dependencies whose runtime path (../) maps into the parent component.

Is there a way of disabling this warning, as the publish/export dependencies are basically irrelevant when I'm working with a plain Java project anyway?
Answer: I was able to eliminate that warning by following the instruction at https://www.eclipse.org/forums/index.php/t/172866/.
In the .classpath file, replace:
<attribute name="org.eclipse.jst.component.dependency" value="../"/>

with
<attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>


Citation key changes when syncing Mendeley with Overleaf

Question: I'm using Mendeley to manage references for a paper I'm writing in Overleaf. If I export a bibtex file from Mendeley, the citation keys match what I see in the program [AuthorYear]. However, if I sync my references directly from Mendeley using Overleaf, the citation keys of most are changed to [AuthorYearFirstLast] where First and Last are the first and last words of the title. Is this a bug with Overleaf? Is there a workaround either to change the default citation key for Mendeley or change how Overleaf imports citations?
Comment: I noticed that whenever a document is imported into Mendeley, it actually does not have a citation key associated with it. Whenever you generate a .bib file (like Paul Gessler mentioned) or copy the latex citations (like vbs mentioned above), Mendeley creates the key (see gif below). If there is no key, then the API just makes one whenever you pull the document into overleaf. As to why it picks to create the citation with [AuthorDateFirstLast], I have no idea. It seems like a bug, but at least you have two good workarounds.
Comment: In my case, the citation keys changed! Previously, Mendeley seemed to follow a AuthorYearTitle format which has changed to AuthorYear. I'm writing my thesis and this is a huge pain.
Answer: I found a workaround for this from the desktop version of Mendeley:

(I think this is optional, but useful) Go to Tools > Options > Document Details tab. For each relevant "Document type", or all, enable the Citation Key field and Apply.
Select all your documents and press Ctrl-K (copy as latex citation command). Now all your documents have a fixed citation key with the AuthorYear format.
Sync your changes

And that's it. If you now reimport the references from Overleaf all citation keys should be in the correct format.
Answer: (Disclosure: I'm on support staff at Overleaf.)
Overleaf imports .bib files via an export API provided by Mendeley, and unfortunately this does not send all the same data as when you download the .bib file directly using Mendeley's own web exporter or desktop application.
This can't be changed from the Overleaf side; we don't have any way to customize the data we request from Mendeley. In the meantime, it is probably simplest to sync with the downloaded version (where you have more control over the cite keys) via Dropbox.
Answer: A convenient way that automatically adds new references (in addition to generating keys for your existing library) is given by @birch's suggestion which had the described behavior for. This is my preferred method.

The citation key is only generated if you have Bibtex syncing enabled.
To enable it, go to Tools->Options and the BibTex menu. Tick the
checkbox next to "Enable BibTex syncing" and the radio button for
"Create one BibTex file for my whole library." Choose a location for
the BibTex file, then hit "Ok" or "Apply" and Mendeley will generate
Citation Keys for all entries and continue to do so for new entries
added to your database.


LAN world not showing up

Question: So, I'm trying to play on a LAN server with my sibling. When she or I click "Open to LAN" in the pause menu, it works, shows the port number. But I can't find it in the Multiplayer tab on the very bottom. We are both using a Mac. Help??
Answer: LANs work when a host hosts the world on a local network for others to join. The lan number is not useless.
Go to the play multiplayer screen, and click "Direct connect."
You should then be offered an entry called "Server Address" Enter the number displayed when you open to LAN.
I haven't used LAN for a while but I think this is the solution. Another thing is make sure that both are connected to the internet.

LAN world not showing up


Using fields in relationship table to return as part of Rowset Zend Framework?

Question: This question is related to another: Does a many-to-many relationship with a recursive one-to-many in mysql require at least 4 tables?.
My question is how can I use or return values that are in the junction / relationship table of a many-to-many relationship.
When using:
$row = $original_row->findManyToManyRowset('Model_New', 'Model_OriginalNew');

I only receive the related record, but I would like to acquire an extra field that is in the junction table of the form:
|  id  |  original_id  |  new_id  |  percentage |

I would like to get the percentage value, is that possible with active record or should I just make use of a Database Access Object?
Answer: Just use:
$user_row->findDependentRowset('model_Junction_Table_Name');


Popups & colorbox issues in Chrome

Question: Hoping for some guidance here. Sometime in the past few weeks, my inline modal popups stopped working in Chrome. I had Colorbox set up at the time, both hand coded inline links and views colorbox triggers. With views, the links now force a page refresh to the home page with the colorbox query appended:

i.e. ?width=500&height=500&inline=true#content

With hard links, the page refreshed on the existing page, with the same query string added.
After some investigation, I discovered that ONE page on the site still works, but it's part of a series of panel variants on a page. I've been through the variants with a fine toothed comb, but they're configured identically, so there's no clear reason why this one page should work when the others don't. I've also tested Chrome on two other (both older) laptops, with the same results.
I installed the Popup module to see if I could by-pass the issue, but the results are exactly the same. The popups work on the one rogue page but not on any of the others. So the problem isn't colorbox, but something else. Again, this is ONLY in Chrome. Firefox and IE both work fine.
I've tried creating solo links on basic pages, I've systematically turned off all the other components on all of the test pages ... nothing. I tried removing all of my custom jquery and disabled my custom modules. No dice.
Can anyone suggest another approach, or other possible conflict areas I can test?
Edit to add:
Looks like the working page is processing the link class as "colorbox-inline init-colorbox-inline-processed cboxElement", while the non-functioning pages are only rendering "colorbox-inline". It's the same block on all pages, so I'm not sure why it wouldn't be processed evenly.
The base colorbox inline code I'm using is adapted from the following:

Link to click

What ever content you want to display in a Colorbox.

Comment: Do you see any JS errors in Chrome's browser console?
Comment: Yes, there's:  "Uncaught SyntaxError: Unexpected token '<'
Comment: Looks like it's attached to the github prefetch call in the colorbox js
Answer: Turned out to be a conflict with the Superfish menu module. Leaving this here because several other people have reported similar issues and this might help.

Popups & colorbox issues in Chrome


PostgreSQL Role Inheritance behavior in AWS RDS

Question: I was familiarizing myself with how PostgreSQL (9.6) role management works and ran into a case that seemed to go against my understanding of the documentation.
I have an RDS instance and a master user with the rds_superuser role.  I used this role to create a "group" role called 'readwritegroup'. This role has NOLOGIN and CREATEDB granted to it so that anyone who is added to the group may inherit those permissions but cannot actually be used to do things on.
Using my master user I created a database and a new schema inside of it.  I granted CREATE and USAGE on the schema to the 'readwritegroup" role.  I then created and added 2 separate users to the 'readwritegroup' with only INHERIT as their grants.
I then used the master user to run the following on the schema:
<code>ALTER DEFAULT PRIVILEGES IN SCHEMA test
GRANT ALL PRIVILEGES ON TABLES TO "readwritegroup";
</code>
Using these two users I successfully created 1 table for each user and then attempted to SELECT from each user's table using the other user. So they are the owner of their respective tables. They are unable to see each other's tables however. (permission denied)
In fact, even my master user is unable to GRANT any permissions on the tables that they own (though I can change the ownership to my master user).
Is there any way to circumvent the authority of object ownership?  I don't really understand why the ALTER DEFAULT PRIVILEGES bit does not correctly modify the behavior to allow other users in the group to SELECT (or whatever grants are used).
Answer: Found the answer in this post: How to manage DEFAULT PRIVILEGES for USERs on a DATABASE vs SCHEMA?
The default privileges are set for the executing user unless otherwise specified with the FOR ROLE modifier.


My Xbox 360 powers on but doesn't load up?

Question: I have an Xbox 360-S. The green light comes on but that is it. It won't do anything. What do I do? I have tried to restart; taking it apart; but still nothing.
Comment: I assume you're certain your Xbox is properly connected to your TV and that the TV is listening to the correct port, is that correct? Also, from the way you write, I assume that your Xbox 360 S has never worked before (i.e. it is a new console).
Comment: What do you mean by "taking it apart?" You shouldn't be disassembling complex electronics like an Xbox unless you know exactly what you're doing. You could do more harm than good.
Comment: Also, check your [power supply](http://support.xbox.com/en-AU/xbox-360/console/check-power-supply). If you aren't getting enough power, it won't function as intended.
Comment: I changed power cords but nothing the green light come but nothing.  The lights in the cinter dose not go around. I was playing it last night
Comment: I would also recommend, if possible, the usage of the AV Cable port above the HDMI port, to see if the console can still transmit to the TV, or whether it needs serious repair
Answer: Try checking the HDMI cable, if it has been removed or it just moved and now is not plugged in correctly, then only the green lights turn on, but the system won't load.
Also, if it has been modified (RGH/JTAG), sometimes You have to wait longer for the system to load (up to 5 minutes).
If it has taken some damage (fallen off somewhere, got kicked over, etc.), You should take it for a repair.


Do I need a Schengen Visa to transit in both Amsterdam and Paris on the way flighting from Canada to Vietnam?

Question: I am Vietnamese. I am studying in Canada.
In this December I will fly from Canada to Vietnam.
In my fight schedule, I must transit in Amsterdam for 1.5 hours and then in Paris for 3 hours.
I wonder if I need a Schengen Visa to flight from Amsterdam to Paris in my schedule?
Comment: Related question: https://travel.stackexchange.com/questions/17385/is-a-schengen-visa-transit-visa-required-for-transit-flight-from-vienna-to-frank
Answer: Yes, a flight between two Schengen countries is considered a domestic flight, so you will need to pass border control in order to board your flight from Amsterdam to Paris.
Comment: Can you provide a link for answers like this? It's useful for someone to have their worries cleared with an official website, instead of someone on the internet (not saying you're wrong, just that links help)
Answer: You definitely don't need a visa to connect in Amsterdam, as their Schipol is a "single terminal airport". I.e. when you arrive from Canada, you will not cross the borders waiting for your plane to Paris.
In Paris everything depends on the terminals usage: if you depart from a different terminal than arrive from, then there is a chance you would have to cross the borders.
This would not be a definitive blocker yet: even in such a circumstance, borders officer may grant you a 24-hrs transit visa so you are able to continue your flight.
However, the best way to do it is to check with your airline.
Comment: -1 the OP will enter the Schengen area in Amsterdam and definitely need a visa
Comment: http://en.wikipedia.org/wiki/Amsterdam_Airport_Schiphol#Terminal -> Schirpol has only one terminal but 3 departure halls
Comment: And there are airports with just one terminal divided between Schengen and Non-Schengen with border control in between.


Real part of refractive index

Question: I would have a quite stupid question: What is the connection between complex refractive index and the "normal refractive index" that I find in every high school books? Is that the real part of the complex refractive index (and thus corresponding to transmittance?) or is it something like "absolute value", that already contains both real and imaginary part?
Thank you a lot for any answer, I´m really confused about the practical interpretation.
Answer: When using refractive indices we usually assume the materials are perfectly transparent and don't absorb any light. In this case we get a real refractive index that is just the ratio of the velocities.
However real materials always absorb some light, and when this happens happens we get a complex refractive index:
$$ \bar{n} = n + i\kappa $$
where $n$ is the phase velocity of the light and $\kappa$ is the extinction coefficient.
To get a feel for why this is and what it means we can do a simple calculation. The light wave is described by something like:
$$ E(x, t) = E_0 e^{i(kx - \omega t)} \tag{1} $$
This is just the usual equation for a plane wave with $k$ the wave vector and $\omega$ the angular frequency. To see how the refractive index is involved we note that the wave vector is given by:
$$ k = \frac{2\pi}{\lambda} $$
The wavelength, $\lambda$, is related to the wavelength in a vacuum, $\lambda_0$, by:
$$ \lambda = \frac{\lambda_0}{n} $$
and substituting for $\lambda$ gives:
$$ k = \frac{2\pi n}{\lambda_0} $$
Now we take our plane wave equation (1) and substitute for $k$. If we write $n$ as the complex refractive index, $n + i\kappa$, we get:
$$ E(x, t) = E_0 \exp\left(i \frac{2\pi (n+i\kappa)}{\lambda_0} x - i\omega t\right) $$
and rearranging this gives:
$$\begin{align}
 E(x, t) &= E_0 \exp\left(i \left(\frac{2\pi n}{\lambda_0} x - \omega t\right)\right) \exp(- 2\pi \kappa x) \\
         &= E_0 \exp\left(i \left(kx - \omega t\right)\right) \exp\left(- \frac{2\pi \kappa x}{\lambda_0}\right)
\end{align}$$
So what we've ended up with is a plane wave multiplied by the exponential damping factor:
$$ \exp\left(- \frac{2\pi \kappa x}{\lambda_0}\right) $$
And that's why $\kappa$ is the extinction coefficient.
Comment: Thank you for your detailed answer! But honestly, I still don´t understand. In the equation, you replaced "n" by "n + ik", but the "n" is not the same, is it?
Comment: Probably I did not formulate my question well, but my main problem is: I have some values of the refractive index as function of ω, that were determined experimentally. So, according to your answer, I can not suppose that these values are corresponding to the transmision?
Answer: Anne, It took me some time to understand this myself. But if you take a Newtonian system perspective, it makes this a little easier.
User128785 as well as John Rennie have answer your question beautifully.
Let me add :
Whenever we consider a moving wave in a medium, we (simplistically) assume forward motion. With random media of the type described above (for example glass slide which is partially transparent to a range of particular wavelengths), this simplistic assumption is challenged. Which means that the net motion may be forward , but the backward wave cannot be ignore (and it's intensity defines the net velocity of the system).These are the origins of the "effective medium theory". This means that for a particular set of wave (particle) the same media will behave one way and for another set of the things will be different. As a result we see dispersion ( of wave in a prism experiment).
It takes time to understand that the prism experiment is just a model of what might be going inside a thin film (made up of small-small prisms...if you will).So a signal consisting of a range of wavelengths come out of a thin film differently, except we should be able to decipher the interaction with high precision to say if the 'meta-material" thin film is absorbing or desorbing type.
You will have to think dynamically (a-la "riding on the boat on the wave analogy"...how so ever big or small the boat may be, effectively the system remains scalable). You realize that the Newtonian idea holds good here. With each particle(wave) of the media, facing forward (action) and backward (reaction) forces, as a result of the perturbation the problem reduces to the following statement : How does on represent this system Mathematically (this is what John Rennie has done)? At which point one must also consider the property of this interactive system a "net yielding" type or "net un-yielding" type, leading to the effective medium theory.
To answer your two specific question :

"n+ik"  approach ,helps in the developing this understanding that each forward push also sees a lesser (or bigger) reactive pull. If we keep taking the observations of  each wavelength point (rather difficult to do ,but nevertheless this is what they do, when they build spectrometers etc.,)  our experimental reduces to a plot of "big-data-points" and Signal to noise plots over a range of wavelength. The noise data is also plotted and  deciphered to add richness to our understanding.
when you plot , you will see a exponentially decaying or rising curve depending upon the nature of the interaction (I have seen people going to the extent that they compare each interaction exothermically or endothermically, depending upon the nature of particles and media involved).
\In the end you will see the data and realize if the media is "net" absorbing kind or "net " desorbing type for that range of wavelengths. The "n" represents the forward and the "k" represents the backward part of the interaction.

(HOPE this VERBOSE statement makes sense)
Vinamra
Answer: The real part of the complex refractive index is the normal refractive index, and is related to the part of wave that transmits through the medium. Let's see what the imaginary part of the refractive index would do to a wave of the form $Ae^{\iota k x}.$ The refractive index is part of $k$ in the medium, so that being imaginary will make the wave decay exponentially. You have your answer there: the imaginary part of the refractive index is related to the part of the wave that gets absorbed in the medium.

Real part of refractive index


What kinds of expenses should I have separately in family budget?

Question: What kinds of expenses should I have separately in family budget? Like food, medications, transport, clothes, housing, kids, personal expenses, sports, flat maintenance, loans, rent. There are simply too many things and probably some categories should be combined to a more general one. Please advise.
Answer: I'd suggest starting with some general categories like @MrChrister suggests.  Each month, as you compare actuals to budget, you'll probably find some categories where you really feel like you need more details, or you need to exercise a little more discipline.  Break those categories down further so that you can get the details you need.
For example, if you find that you're spending more money than you think you should on the Food category, you might break it down into Groceries, Restaurant Meals, Fast Food, and Work Lunches.
Comment: I should add here that it's a good idea to look at a very thorough budget form when first setting up the budget so that you can be reasonably sure you haven't missed anything important.  But for tracking purposes, less categories makes life easier as long as you're getting the information you need to make good decisions.
Answer: Are you meticulous?
If yes, then make lots of categories.  If you want a place to start, hook up mint.com to your accounts and start sorting your transactions into the categories they already have.  Sparingly add your own if you can't agree with theirs.
Once your transactions are categorized, mint will show you what you spend, and you can tweak a budget from there.
Make sure whoever else does the budget with you is helping make the decisions.
If you aren't wanting to be meticulous about your budget, here is my latest plan:  after doing the detailed thing for a while, I feel it doesn't gain me much compared to the following:

Required spending (things like rent, mortgage, utilities, insurance, dues and subscriptions)
Unexpected spending (things like doctors visits for sick kids)
Savings (the money in my paycheck I dedicate to savings)
Food
Fun money

Really food could be pushed out to required spending, but I am also tracking with sub cats if my food was work lunches, groceries or eating out. (Because this the part of the budget we feel like we should improve.)
You can add a couple more if you want, but there isn't a big reason to track how much my cell phone bill was, it just matters that I always owe it every month.
Answer: This budget worksheet from Vertex42.com is probably a good starting point.


Measuring Earth shadow size on Moon with geometry

Question: I'm asked to use "simple geometry" and appropriate approximations of astronomical distances and radii to explain why the shadow cast by Earth on Moon is only about 2.7 times of the Moon size, while in reality Earth is about 3.7 times as big. I'm really stuck with this problem, because there appears to be no way that I'm doing anything incorrectly, yet the results I've been getting are absurd.
My approach is this:
We can draw an isosceles triangle with the base of $2R_{Sun}$. Somewhere in this triangle there is Earth's diameter parallel to the base, as well as the Earth shadow's diameter parallel to the base.
Now, we need to find the height of the similar triangle, the line going from the Moon diameter to the vertex of the triangle, that is the median of this similar triangle. Let this be $y$. Once $y$ is found, we can find the radius of the Earth shadow on Moon; let it be $m$. The result will be the division of $R_{Earth}$ by $m$.
The constants as I defined for convenience are as follows:
$$d_{e-m}=380$$
$$d_{e-s}=1.5\times 10^5$$
$$R_{sun}=695.7$$
$$R_{earth} = 6.4269$$
Now, we can setup two equations, where $(d_{e-s}$ is the distance from Earth to Sun, $d_{e-m}$ is the distance from Earth to Moon, $h$ is the hypotenuse of the half of the isosceles triangle, and $x$ is the difference of $h$ and the hypotenuse of the similar triangle which is a half of the isosceles triangle, which has the base $R_{earth}$:
$$(d_{e-s}+d_{e-m}+y)^2 + R_{sun}^2 = h^2$$
$$R_{earth}^2+(d_{e-m}+y)^2=(h-x)^2$$
$x$ is found this way:
$$(R_{sun}-R_{earth})^2+d_{e-s}^2=x^2$$,
so $x=150002$.
Now, typing the above system of two equations into Wolfram Alpha I get two solutions, with $y$ being negative in every one of them. I've double-checked many times, and my setup is absolutely correct!
Please help!
Answer: We have
$$ \frac{R_{sun}-R_{earth}}{d_{earth-sun}}=\frac{R_{earth}-R_{shadow}}{d_{earth-moon}}$$
hence
$$\begin{align}R_{shadow}&= R_{earth}-\frac{R_{sun}-R_{earth}}{d_{earth-sun}}\cdot d_{earth-moon}\\
&=6371\,\text{km}-\frac{695700\,\text{km}-6371\,\text{km}}{149600000\,\text{km}}\cdot {384400\,\text{km}}\\
&\approx 4600\,\text{km}\\&\approx 0.72\cdot R_{earth}\end{align}$$
(and $\frac {2.7}{3.7}\approx 0.72$ as well).
Comment: Thanks. I didn't know about this relation.


Batch converting AIFF to WAV

Question: I have a few dozen AIF files that I need to convert to WAV. I have converted a few by opening them in Audacity and exporting them to WAV, but this is very slow. I would like to convert them all in batch. Is there a way to do this on OS X?
Answer: If you want to go for a shell solution, you can do it with ffmpeg.

Option 1: download ffmpeg and extract the executable ffmpeg file. Copy it to a directory that is in your executable path, e.g. /usr/bin.
sudo cp ~/Downloads/ffmpeg /usr/bin/ffmpeg
sudo chmod +x /usr/bin/ffmpeg

Option 2: Use Homebrew and brew install ffmpeg.

Now, in the folder with the AIF files, run this:
for f in *.aiff; do ffmpeg -i "$f" "${f%.aiff}.wav"; done

Comment: This worked, thanks! Is there any way I can add compression?
Comment: What kind of compression do you have in mind? WAV usually stores uncompressed PCM audio. ADPCM is sometimes used. You can also put MP3 data in a WAV container. Use the `ffmpeg -i input.aiff -c:a adpcm_ms output.wav`, for example, for Microsoft ADPCM. You can check `ffmpeg -encoders` for all encoders supported.
Comment: `brew install ffmpeg` is quicker than all of the downloading and modding the app.
Comment: @AbsoluteƵERØ True, I added that option.
Comment: slightly simpler command: `find . -name "*.aiff" -exec ffmpeg -i {} {}.wav \;`
Answer: You should be able to convert between the two formats using iTunes instead of manually writing something yourself:
1.Open iTunes Preferences.
Windows: Choose Edit > Preferences.
Mac: Choose iTunes > Preferences.
2.Click the General button, then click the Importing Settings… button in the lower section of the window.
3.From the Import Using pop-up menu, choose the encoding format that you want to convert the song to, then click OK to save the settings.
4.Select one or more songs in your library, then from the File > Create New Version menu, choose one of the following (the menu item changes to show what's selected in your Importing preferences):
Create MP3 version
Create AAC version
Create AIFF version
Create WAV version
Create Apple Lossless version

Source: http://support.apple.com/kb/ht1550
Comment: But this requires that you load the files into itunes. If you're using something like sound samples, that's not necessarily what you want to do, especially if you have itunes set to keep files organized.

Batch converting AIFF to WAV