Trouble unzipping .json.gz file in Node.js using zlib

Question: I'm downloading this AWS S3 object on my local Node.js server with this -
var url = "http://s3.amazonaws.com/cloudfront.s3post.cf/s3posts.json.gz";
var dest = "./s3posts.json.gz";

var download = function(url, dest, cb) {
    var file = fs.createWriteStream(dest);
    var request = http.get(url, function(response) {
        response.pipe(file);
        file.on('finish', function() {
            file.close(cb);
        });
    });
}

download(url, dest, function() {
    console.log('Download complete');
});

This successfully downloads a .json.gz object. I'm trying to unzip this object using zlib -
var gunzip = zlib.createGunzip();
var rstream = fs.createReadStream('./s3posts.json.gz');
var wstream = fs.createWriteStream('./s3posts.json');
rstream.pipe(gunzip).pipe(wstream);

However, this throws an error and the .json file that is created is empty -
events.js:163
      throw er; // Unhandled 'error' event
      ^

Error: unexpected end of file
    at Zlib._handle.onerror (zlib.js:355:17)

Weirdly, if I use only the download code to download the object and unzip it manually using gunzip s3posts.json.gz on the terminal, the created json file is filled with content and I can run my app successfully.
I'm not sure why I'm able to unzip manually but can't do it programmatically with zlib. It would be really helpful if someone can point out if I'm making a mistake.
The S3 object has the following metadata if it's relevant -
Cache-Control: max-age=31536000,no-transform,public
Content-Encoding: gzip
Content-Type: application/json

Answer: What happened is that you don't check for errors when you download the gzipped file so you end up saving an empty file. Then you try to decompress the empty file and you get an error, which is also unhandled and your program crashes.
Just handle all errors and you know what went wrong. From your example it's impossible to tell you anything more than that the .gz file is likely empty because apparently something went wrong with the download. But want exactly went wrong is a mystery because you don't check for errors in your code.
Comment: I just had to use the code for unzipping the file as a callback function. Thanks for your help.
Answer: Turns out that I wasn't waiting for the file to complete downloading before unzipping it; which was why the generated json was empty. I had to use the code for unzipping the file as a callback function -
download(url, dest, function() {
    console.log('Download complete');
    var gunzip = zlib.createGunzip();
    var rstream = fs.createReadStream('./s3posts.json.gz');
    var wstream = fs.createWriteStream('./s3posts.json');
    rstream.pipe(gunzip).pipe(wstream);
});

This also explains why I was able to unzip the file manually just using the download code, as the download was complete at that point allowing me to successfully unzip it on the terminal.


auto start, cross platform, background mobile web service with codename one or cordova

Question: I'm a newbie to mobile software development. I want to make a piece of software that:
1. I write once, and it runs on iOS, android, and windows mobile devices.
2. Has no user interface of its own.
3. Is like a web service, i.e. it lets other apps running on the same mobile device access its services via a common, language independent web service like interface.
4. Auto-starts at boot time, and runs in background all the time.

Given that i don't want to access mobile device features like camera, gps, etc. Just access to the file system, and network. Is this doable with codename one, or other CPTs like Cordova? If yes, can you please give me some pointers on how to go about making such a thing?
Answer: Codename One has builtin support for background polling of the web, notice that it isn't designed to run frequently as this is a battery drain.
See: https://www.codenameone.com/blog/background-fetch.html
You can also access all native device functionality via native interface calls.
However, Codename One and most mobile applications expect a user interface. What you are describing sounds a lot like a virus/spyware.
Comment: This is certainly not a virus! I'm making multiple apps. Each app may be built on a separate software stack. I want to extract all common code from these apps and run it as a service on mobile device, so that all apps, regardless of their software stack, can access the shared functionality in a consistent way. Its only strange that a desktop operating system provides ways to create a background service(daemon) without UI. Why should it be difficult to create one on a mobile operating system?
Comment: I didn't mean to offend, but you do understand the point on why this is discouraged. Apple doesn't allow these kind of apps. If it did we would have had apps like the Java virtual machine on the appstore and you would have been able to install Java apps. Apps live in isolation from one another and transferring data/control is really complex if at all possible. Android allows it but it's one of the most difficult pieces within that code. The problem with doing it has nothing to do with Codename One as this is a limitation of mobile programming in general.


Groupbox with a flowlayout panel inside and autosize = true shrinks like it is empty

Question: I have a groupbox that holds a flowlayout panel and the flowlayout panel holds a bunch of controls.  I set the flowlayout panel to dock with the parent.  Since I don't know how many controls will be in the panel, I set the group box autosize to true and autosizemode to grow and shrink.  When I do this the groupbox shrinks as if it is empty.  I need the caption so I can't remove the groupbox.  Anyone know why this is happening?
Answer: There's nothing that stops the FlowLayoutPanel from shrinking to nothing.  You'll at least have to set its AutoSize property to True as well.
Comment: thanks. that stopped the shrinking, but caused another problem. It grows horizonally causing the need to scroll side to side in the groupboxes parent container. previously scrolling was only vertical.
Comment: You can set the MaximumSize.Width on the FLP to avoid that.
Answer: I was trying to do the same thing today.  Below is the solution i came up with, which is to dock the FlowLayoutPanel inside of the GroupBox and then use the Resize and ControlAdded events of the FlowLayoutPanel to trigger resizing the parent GroupBox.
The resize handler finds the bottom of the last controls in the FlowLayoutPanel, and resizes the GroupBox with enough space to hold the bottom-most control(s) in the FlowLayoutPanel.
I tried using the AutoSize=true on the FlowLayoutPanel and the GroupPanel.  But unfortunately this allows the FlowLayoutPanel to grow horizontally.
<code>public partial class UserControl1 : UserControl
{
    public UserControl1()
    {
        InitializeComponent();

        int numGroupBoxes = 4;

        for (int groupBoxIndex=0; groupBoxIndex<numGroupBoxes; groupBoxIndex++ )
        {
            GroupBox groupBox = new GroupBox();
            groupBox.Text = "Group " + groupBoxIndex;
            groupBox.Size = new Size(this.Width, 0);
            groupBox.Dock = DockStyle.Top;
            this.Controls.Add(groupBox);

            FlowLayoutPanel groupBoxFlowLayout = new FlowLayoutPanel();
            groupBoxFlowLayout.Dock = DockStyle.Fill;
            groupBox.Controls.Add(groupBoxFlowLayout);

            int extraSpace = 25; // the difference in height between the groupbox and the contents inside of it

            MethodInvoker resizeGroupBox = (() =>
            {
                int numControls = groupBoxFlowLayout.Controls.Count;
                if ( numControls > 0 )
                {
                    Control lastControl = groupBoxFlowLayout.Controls[numControls - 1];
                    int bottom = lastControl.Bounds.Bottom;
                    groupBox.Size = new Size(groupBox.Width, bottom + extraSpace);
                    groupBoxFlowLayout.Size = new Size(groupBoxFlowLayout.Width, bottom);
                }
            });

            groupBoxFlowLayout.Resize += ((s, e) => resizeGroupBox());
            groupBoxFlowLayout.ControlAdded += ((s, e) => resizeGroupBox());

            // Populate each flow panel with a different number of buttons
            int numButtonsInGroupBox = 3 * (groupBoxIndex+1);
            for (int buttonIndex = 0; buttonIndex < numButtonsInGroupBox; buttonIndex++)
            {
                Button button = new Button();
                button.Margin = new Padding(0, 0, 0, 0);
                string buttonText = buttonIndex.ToString();
                button.Text = buttonText;
                button.Size = new Size(0,0);
                button.AutoSize = true;
                groupBoxFlowLayout.Controls.Add(button);
            }

        }

    }

}
</code>
Here are three screenshots of the control resized to various different widths:
Comment: this works nicely, but its a good idea to resize the usercontrol itself when you resize the groupbox.
Answer: You state "I don't know how many controls will be in the panel". Do you have any controls in the FlowLayoutPanel at design time? If you don't, this sounds like expected behavior. The Panel has nothing so its desired size is zero, so the GroupBox's desired size is zero.
If this is the case, then it should all hopefully size up when you actually add controls at runtime.
Comment: Yes I have controls in it at design time.  Once i get everything working with a know number of controls. this code will be autogenerated based on an xml file. At which point I will not know how many controls there will be.
Answer: You set properties Anchor: Top, Bottom, Left, Right for groupBox.


How can I find an exact string in file contents across many folders from the command line on macOS?

Question: I tried all the recipes (double quotes, escaped double quotes etc.) in vain. I'm not interested in files containing any or all of these words, only the exact string. (EasyFind does the job.) I'm using macOS Catalina with zsh.
Is there a way to have mdfind detect an exact string, say "what I look for", in the content of files?
Comment: Super question Chris - I added a lot of "here's why everyone can easily get this wrong to my answer" - let me know if you need it clarified / shortened or you care about case and diacritic insensitivity or even more specific search needs.
Answer: Spotlight allows this and is my favored tool, despite how painful it is to learn how to do this from Apple's documentation alone. The man page for mdfind is almost criminally negligent for not mentioning how to search for a string, but I shall not rant too much more on that here.
mdfind 'kMDItemTextContent = "this exact string"'

Pay attention to the double quote and single quote and also, when you are looking for help online - if the article mentions NSPredicate or that spotlight uses two different languages, you are on to the good stuff. If the article says "x can't be done" consider that perhaps "The author hasn't needed to learn how to do x, yet".
Here are some great places to start with predicates - the log man page, excellent programming references like https://nshipster.com which glosses over how hard "natural language" search expressions are - especially when you mix pcre/regex with SQL baggage.

NSPredicate is a Foundation class that specifies how data should be fetched or filtered.  Its query language, which is like a cross between a SQL WHERE clause and a regular expression, provides an expressive, natural language interface to define logical conditions on which a collection is searched.

https://stackoverflow.com/questions/30271328/how-do-i-get-mdfind-to-include-folder-matches-in-addition-to-files
https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/Predicates/Articles/pSpotlightComparison.html#//apple_ref/doc/uid/TP40002370-SW1

Basically, for reasons, spotlight can be very hard on newcomers, very confusing syntactically, but mostly gets it right for some easy things and finding a string in a file is more challenging than you might expect. The system was designed by programmers and then a second language was patched on and there's a lot of easy to search information that's just wrong or incomplete.
Thankfully there are some great explanations how to learn this powerful tool.

https://www.macworld.com/article/3264653/macos-how-to-use-spotlights-query-language-to-create-an-all-my-files-like-feature.html (Glenn writes very well)
https://support.apple.com/en-am/guide/mac-help/mh15155/mac (Narrowing your search help)
Comment: Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/108371/discussion-on-answer-by-bmike-find-exact-string-in-file-contents-from-command-li).
Answer: It might be easier to use tools dedictated for searching text within files, e.g. grep (part of macOS) or ag (brew install ag):
fgrep -r "Text to match" PATH
ag -F "Text to match" PATH

Comment: "hidden": in plain sight in a txt file. ag did OK in a matter of seconds. fgrep hangs after declaring 1 "permission denied".
Comment: fgrep failed to find what I had hidden. ag failed to install.
Comment: @ChrisImpens Hidden how? If you need to search in `.dot` files an additional option might be required. For `ag`, see updated answer.
Comment: Actually, fgrep -r "Text to match" PATH is OK, is PATH is something like ./*.*


How to become a krunker police officer?

Question: In the game krunker.io , i was wondering how can you enroll to become a kpd officer and what are the requirements?
Answer: From the Krunker wiki, "To apply to the K.P.D, press the police icon next to your username and fill out the form. You must be level 50 to send an application."
Comment: oh thanks !! it must take a while to get to that level though !
Comment: Yah, it does. This is probably to prevent random players that arent experienced do it.
Answer: The minimum requirements to join KPD are:

Account is at least Level 50
Must have at least 20 helpful reports
Ability to record 720p stable framerate
Access to Windows operating system

Once these requirements are met you can fill out the KPD application found here. To increase your chances of becoming KPD, try re-submitting your application at a higher level or more helpful reports. Furthermore, having a good reputation in the community increases your chances by a lot. Streaming, creating content, being active in communities, etc are favorable qualities for candidates.
If you aren't accepted within 60 days you can submit a new application with updated material. These requirements may change overtime but you can refer to the application link for the most up to date information.

How to become a krunker police officer?


How to promote the site at a local crypto party?

Question: Short question, what would the best way to promote the site at a local crypto party?
Answer: If you are up for doing a bit of work beforehand, you could print out a few cards having the URL and QR code of the site, and hand them out at the party.
A tangible reminder will be more effective.
Also, the folks over at Graphic Design (chatroom) are pretty helpful. I am sure any of them will help you out if you want to make a good looking card ;)
Answer: Handing everyone the site url (http://tor.stackexchange.com) and ask them kindly to contribute perhaps?


Ki'bolo Kach Polto

Question: Why can't a utensil that became trief at, say 150 degrees be kashered with water that is 151 degrees? Why must the water be boiling?
Comment: This need a better title. Also I thought it was כבלעו not כדי לבלעו
Comment: How do you know it must be?
Comment: Supra liminal heat is perhaps the principle
Comment: I think the "as absorbs, so emits" is a categorical halacha. So there would be temperature levels like "Yad Soledet Bo" and "Boiling", rather than continuous values. There's still the question of why you have to go up a level in temperature (Boiling rather than Yad Soledet Bo)
Answer: R Ezra Friedman from OU Kashrut brings an answer to your question (here)

It would seem logical based on the principle of kebol'o kach polto
that not only would the method of kashering be based on the form of
absorption but the temperature as well. For example, if a utensil
absorbed non-kosher soup at low heat, one might assume that the hot
water used in the kashering process to remove the absorbed flavor
would only need to be slightly hotter than the temperature that the
soup was cooked at. However, it is clear from early authorities (see
Rabeinu Yona Hagalat Keilim 40) and codified in the Shulchan Aruch and
Rema (OH 452:1) that this is not the case. In order to remove absorbed
flavor from the utensil, the water must be boiling hot, even if the
original absorption occurred at a lower temperature.
This concept is explained by Rav Aharon Pfeuffer in his book Kitzur
Shulchan Aruch Basar Bechalav (volume 2 appendix:1). When our Sages
codified the rule of kebol'o kach polto, it related to the form of
absorption such as water or fire and not the temperature needed to
remove the flavor. In order to remove absorbed flavor, a higher
temperature is needed than the temperature in which the food was
cooked. The temperature of the water must be boiling in order to
remove all of the flavor. It should be noted, however, that Rav Moshe
Feinstein (Igrot Moshe YD 4:36) and other poskim ruled that in
situations of severe need, hag'alah may be done using water only
slightly hotter than the temperature at which the food was absorbed.
The OU does not rely on this leniency.
Comment: The Shulchan Aruch and Rama are in siman 452, not 552.
Comment: Thanks, appreciate the correction

Ki'bolo Kach Polto


The opposing member inadvertently plays two card that are stuck together and it is discovered later

Question: What is the penalty if the opposing team inadvertently plays two cards on a trick because they stick together. It is discovered later.
Comment: Related post: [What is the penalty for failing to follow suit?](https://boardgames.stackexchange.com/q/4802/22373)
Answer: Assuming you are playing rubber bridge, the Laws of Rubber Bridge apply.
If the irregularity is discovered part way through the hand, was a misplay by a Defender, and during discovery of the misplayed card it was ever placed such that Offender's Partner could have seen the card then it becomes an exposed card subject to the Penalty Card
rules.
Additionally, if the irregularity is discovered any time before the play is complete and the cards collected for shuffling, then the possibility of a revoke must be checked whether Offender was Declarer or a Defender. The card played in error must be regarded as being in the Offender's hand continuously from the trick of the misplay until noticed and restored. This can result in a revoke for the misplayed card. The applicable rule is:

Law 67 - Trick Either Appropriate in Error or Defective
A trick containing more or fewer than four cards is defective. When one player is found, during play, to have fewer or more cards than all of the other players, the previous tricks should be forthwith examined, face down; if a defective trick is discovered, the player with a correspondingly incorrect number of cards is held responsible.
The defective trick is inspected face up and
...
B. after the responsible player has played to a subsequent trick, the ownership of the defective trick cannot be changed and

....
if the offender has played more than one card to the defective trick, he withdraws all but one card, leaving the highest card he could legally have played to that trick. A withdrawn card may become a penalty card (Law 50); such a card is deemed to have belonged continuously to the offender's hand and failure to have played it to an earlier trick may constitute a revoke.
Comment: I believe that rule applies when the extra card was taken as an extra card played to the trick, not one that was hidden during the trick and exposed later.
Comment: @L.ScottJohnson: No! A *defective trick* is a a simple consequence of there being a number of attached cards <> 4, not of the *reason* or *excuse* for how the defect occurred: "*A trick containing more or fewer than four cards is
defective.*"
Comment: +1 , but note that unlike Duplicate, there are *no* globally accepted rules for Rubber Bridge; your citation is a booklet written by the ACBL.
Comment: @TimLymington: That is at best only loosely accurate. As those Laws state (pp iii-v): "*In 1947, by mutual agreement [with **Whist Club of New York**, **Portland Club of London**, and **Commission Française Du Bridge of Paris**], the **American Contract Bridge League** became the sole promulgating body*"; "*In collaboration with the **Portland Club***"; and "*Approved by the **World Bridge Federation***". There are no greater authorities on the game than those five bodies, all of whom endorse these rules as **The Official Rules of *Rubber Bridge***.
Answer: This is basically an "exposed card" issue (assuming it was clear which card was intended to be played, as it must have been to have only been "discovered later").
And if the card being "lost" (stuck) causes another misplay before it is found (a revoke, for example), then that misplay will also have to be handled, of course. The misplay does not grant immunity to the other rules.
If the exposed (stuck) card was played by the declarer, no penalty (the declarer is not restricted).
If the exposed card was played by a defender and the partner could see its face, then it is subject to Law 49 and becomes a penalty. It remains exposed in front of its player until rectification (Law 50).
If it's below the rank of an honor, it's a minor penalty card. If it's an honor card, it's a major penalty card.
Minor: the player may not play any other card of the same suit below the rank of an honor until he has first played the penalty card, but he is entitled to play an honor card instead.
Major: A major penalty card must be played at the first legal opportunity, whether in leading, following suit, discarding or trumping. If the player's partner is to lead, then the declarer chooses whether the partner must lead the penalty card's suit or if he is to be prohibited from doing so.
Note: links are to duplicate bridge laws, but the same laws (and same numbers) apply for rubber bridge, as @ForgetIWasEverHere notes: https://cdn.acbl.org/wp-content/uploads/2015/02/Laws-of-Rubber-Bridge.pdf
Comment: You have referenced and described the appropriate Laws for Duplicate Bridge - I suspect that OP is playing a Rubber Bridge game, where [somewhat different Rules](https://cdn.acbl.org/wp-content/uploads/2015/02/Laws-of-Rubber-Bridge.pdf) apply.. There is also a strong likelihood of a subsequent revoke penalty applying, whether by Declarer or Defender, as the misplayed card must be presumed to have always been in the player's hand.
Comment: Ah, certainly true.  I'll update the references. And, of course, if there are other irregularities (like revokes or whatever), then those irregularities would also have to be handled; I was just answering the question at hand where the OP only indicates the one irregularity.


Is friction affected by gravity?

Question: Some people said that moving a car on the moon would make the tires spin a bit more compared to Earth's. But then I started thinking that if static friction and gravity are perpendicular to each other, how can gravity affect the 'more' spinning on the wheels? Since the forces act perpendicularly, shouldn't they be independent of each other no matter what?
Comment: It would probably be better if you wrote your question and multiple sentences, instead of the single run on sentence it is now, (and capitalised your "i" s!) Also, I wasn't the guy who downvoted: this is a good question, it just needs to be formatted a bit nicer.
Answer: The force of friction depends on the force that acts perpendicular to the surface. This is called the normal force $F_N$, and it basically just describes how strongly the car is being pushed into the inclined plane by its own weight. The force of friction $F_F$ is directly related to the normal force: $$F_F = \mu F_N$$
$\mu$ here is the coefficient of friction, it's a number between 0 (very strong friction, body doesn't move at all) and 1 (body moves without friction).
How do we calculate the normal force? If you have a body sitting on a flat surface, the force of gravity $F_G = mg$ acts in the same direction as the normal force - perpendicular to the surface, i.e. straight downwards. In such a case, $F_N = F_G$.
On an inclined plane, the force of gravity still goes downwards, but it is not in the same direction as the normal of the plane. Instead, $F_N$ and $F_G$ form an angle (the same angle as the inclination $\alpha$). In such a case we can write:
$$F_N = cos(\alpha) \cdot F_G$$

So, as you can see, if the normal force is lower, also the friction decreases. Under what circumstances is the normal force lower?
For once, we can increase the angle $\alpha$: we make the plane more inclined, which in turn means that $\cos(\alpha)$ approaches 0 as soon as we get closer to 90°. In the limiting case of 90°, the normal force is 0 and we get frictionless...falling.
The other way is to decrease the force of gravity: $F_G = mg$. If we keep the mass $m$ constant, the only other option is to decrease $g$, the acceleration due to gravity. On Earth this is also fixed at $9.81 m/s^2$, but on the moon it has a much lower value of $1.63 m/s^2$, or about a sixth of Earth's. With this new value, at the same angle and mass, the normal force is now lower, and so is the force of friction.
$$F_F = \mu \cos(\alpha) m \cdot g_{moon} < \mu \cos(\alpha) m \cdot g_{Earth}$$

Now what about the tires? In the case of non-slipping tires, the contact point where the wheel touches the ground should be stationary momentarily. If it did move, we would see that the point is being dragged across the ground.
How fast does the wheel need to spin then to not slip? The rotation of the tire needs to be matched to the forward speed of the car. During one rotation the center of the wheel moves $$x_{center} = 2\pi r = x_{car}$$ where $r$ is the radius of the tire. We can divide both sides by the time of one rotation to get expressions for the velocity.
$$v_{center} = \omega r$$ where $\omega$ is the angular velocity of the tire. Finally, we reach an expression (through differentiation with respect to time) involving accelerations: $$a_{center} = a_{car} = \alpha r$$
What forces act on the wheel? We have a force $F$ acting forwards on the wheel itself (at the center), and a force of friction $F_F$ acting at the contact point. This force of friction also depends on the coefficient of friction and the weight of the car, which is where gravity comes in again.
With gravity being lower, the force of friction at the contact point is reduced, while the force forward is still the same. This means that the wheel does not "feel" enough friction at its contact point to gain the necessary torque (it doesn't turn fast enough), and hence slips.

TL;DR
The force of friction depends directly on the normal force and consequently on the force of gravity. A lower force of friction increases slipping of the tires (all other parameters being equal).

Is friction affected by gravity?


How to intentionally move to second jhana

Question: I have mastered the 1st and wish to move now to the second. But all the books and sources online confuse me. Some say it happen naturally other say it's something you can focus on to bring about the second jhana like thoughts on how unpleasant the 1st is. So how can i summon the second at will?
Answer: Ajahn Brahm gives a very nice explanation about how to get into higher Jhnanas. Imagine that you are in a long corridor with soap water on the floor and you play the game where you come running and slide on the slope water in order to get to another side of the corridor. In this case, the more energy you will slide within the beginning the farther you will get, and in all process, you have to Let-go. So as per my information, you have to further Let-go, to get there. You cannot summon it with the will, the will has to be dropped.
I will recommend you to read Mindfulness, Bliss and Beyond by Ajahn Brahm -- that will answer the question in great detail.
And maybe this will help: The Basic Method of Meditation (by Ajahn Brahm)
Comment: Thank you for the source. So to reach the second jhana abandoned applied and sustained thought this happen when you end attachment to 1st by seeing the flaws and annoyance of it after emerging from it. Then moving your attention away from the object to a the pleasant sensation. That will lead you to the 2nd. Allow rapture and pleasure to fill the whole body
Comment: Take me with a pinch of salt but I think you will enter the second directly from the first not by emerging out of it. But idk. I think you emerge out, you mark it as experience and second time go back with more energy in first, let go, and it should take you in second. But idk.
Comment: BTW congrats bro...you acheived great feet...just 3 more and you are done....best wishes!
Comment: So maybe i already have lol. And thanks bud it took a while. This site truly helped me


Real tracking app for iPhone?

Question: Is there an app that can tell me someone else's exact or general location by entering their phone number, no matter if they give permission or not? (Preferably not.) Or is there some other device, software, etc. that I can purchase? Something that is real and not just for entertainment purposes.
Comment: "If they must give permission or not (preferably not)" sounds SO VERY MUCH like illegal activities. Can you explain the comment to make this much more palatable for other readers?
Answer: Not on the App Store. Something like this is a likely violation of privacy laws as well. There's no way Apple would allow it.
Answer: The only functionality that you'll find for a non-jailbroken iPhone is the Mobile Me Find My iPhone service.  For Jailbroken iPhones there's Navimote, Undercover Mobile, and quite a few others.

Real tracking app for iPhone?


Providing mathematical proof for a patent?

Question: I have  friend that I will ask for his mathematical analysis of my work, it's somewhat complete but needs further analysis using mathematics, if my friend does that, would he/she be considered a co-inventor? Even though they contributed nothing to the idea?
Answer: To be valid, a patent application must be "enabling". If your friend's work is critical to the implementation of the invention, then s/he should be named a co-inventor. If his work is for optimizing the solution, and such optimization is not part of the claim, then you could possibly leave him/her out. You should consult your patent attorney if you have doubt.


Can I move selected features in ArcMap with arrow keys?

Question: I would like to be able to move features by small (preferably predefined) increments using the keyboard arrow keys?  Can this be done?
Comment: Is arcobjects an acceptable solution?
Comment: I was hoping for an out of the box solution but yes, ArcObjects is acceptable. (VB.Net)
Comment: I'm not sure about using the keyboard, but you can move a feature based on the XY by going to Editor -> Start Editing. Select your feature you would like to move, then click on Editor -> Move. Enter in your Delta XY in map units and this will move your feature without using the mouse.
Answer: There is no way of doing it with the arrow keys.
But you can do precise movement by specifying a delta offset as Mintx suggests.  The one problem with the delta movement is that it leaves your feature's origin un changed and that might be undesireable.
However, a left-of-field quick-and-dirty solution that would not require any programming could be to create a fine mesh over your data (you can get ESRI to do it with 'Create Fishnet' or Hawth's Tools) and then use snapping.  Obviously this is VERY 'Heath Robinson' and would be unworkable for huge areas but could be serviceable.
Comment: Specifying delta offset is not what i am looking for because i want to to move the polygons many time in small increments and I want to do it visually without having to enter numbers. The fishnet sounds like an interesting solution. I will try that but the problem with moving a polygon is that I will snap to vertices on the polygon perimeter whereas i want to snap the centroid along either X or Y.
Comment: That's OK.  when you are moving the whole feature, it will snap to the centroid


How can I change my steam address?

Question: I recently moved to a different location. How can I change the address listed in my steam account?
Answer: You don't actually save your address anywhere in Steam.
You can change your location in by modifying your Steam profile, and you can fill out a new billing address when you buy a new game. Before you buy anything, your address isn't used for anything.
Comment: Indeed.  The address in the profile and stored billing information is disregarded to the point that Steam won't use local servers for downloading files unless you specify it in the client preferences.  It's never been autodetected for me, either.
Comment: I've had it auto-detected for me before; usually when I switch to Taiwan (or somewhere equally remote) to download new TF2 patches when the NA servers are all "too busy to process your request".
Comment: Not true. Steam is prefilling my billing address with an old one, even though I deleted the payment method a long time ago/never actually added it.
Answer: The only addresses stored in Steam are billing addresses linked to payment methods. So if you don't have a payment method saved, you won't have any kind of an address.
A billing address can be changed by deleting a previously saved payment method and replacing it with a new one. Payment methods are managed in the Store & Purchase History section of the account details page (available by browser, or via the Steam client at Steam → Settings → Account → View Account Details).

How can I change my steam address?


How can I reduce echo and produce good quality sound in my room?

Question: I'm using 500W speakers in a medium sized room. Even though it's filled with furniture, whenever I increase the volume it sounds worse. How can I get good quality sound by modifying my room?
Answer: If the problem is in acoustics, you need to reduce the sound reflection from the walls. So you need to put sound absorbing material on the walls, or acoustic diffusing material. You can buy specially made for this purpose products. As you are asking here maybe you want to know what you can make yourself.

Acoustic curtains
The acoustic curtain material must be thick and highly porous.  You must select the thickest, heaviest fabric your budget will allow. The pores act as thousands of tiny sound traps, capturing the energy. Find a fabric that could soak up and absorb water, or has a plush, velour surface. Another option would be to use multiple layers of a thinner material.

Acoustic Diffusers
"They are an excellent alternative or complement to sound absorption because they do not remove sound energy, but can be used to effectively reduce distinct echoes and reflections while still leaving a live sounding space. Compared to a reflective surface, which will cause most of the energy to be reflected off at an angle equal to the angle of incidence, a diffusor will cause the sound energy to be radiated in many directions, hence leading to a more diffusive acoustic space." - from Wikipedia.
You can make them with wooden panels. Search for a template for acoustic diffusers with the correct sizes.

A variation of diffuser can be if you have shelves with books on the walls, just pull some of them a bit at different level, not to be aligned.

Bass Traps
Bass Traps are acoustic energy absorbers which are designed to damp low frequency sound energy, which are reducing LF resonances in rooms. They are usually placed in the corners of the room.

Acoustic treatment of rooms is a whole science which is difficult to be explained in a single answer here. You need to do deeper research about how to make diffusers, absorbers, traps ...


Person or Group Column Type Broken after Renaming 'Title' Site Column

Question: I made the all-too popular mistake of renaming a title column and pushing out the changes via inheritance.  I quickly reversed the change by renaming it back to Title.  Now, when I use the Person or Group column type in a list or content type, the Check Names functionality doesn't work.  It looks like one of the hidden fields that makes up the P or G type has been renamed from "Name" and is now "Title" which is causing my grief.  Is there any way to reset the P or G type or rename just that field back to "Name"?
Answer: If your solution is truly what you need to accomplish you may be able to do this via powershell or the utility SharePoint Manager.
Comment: Thanks, tylerrrr07.  SPM solved the "Title" column problem but not the check names which means they're not related.  I posted some detail below on using SPM to fix the lookup and marked this as answer since your suggestion of using the tool is dead on.
Answer: Who knew that after putting in 9 hours in on this it would only take 1 more hour to solve?
The Person or Group column type is actually base type Lookup.  It looks its values up from the "User Information List" ({7c68ed5b-0cd0-4848-8796-839dd18c240b})--you know, the one that shows the people list when setting permissions.  There are 4 occurances of the "Title" column ({fa564e0f-0c70-4ab9-b863-0177e6ddd247}) in this list that were changed as a result of renaming the parent (they must be custom columns based on the OOTB Title field).  They have static (internal) names of Title, LinkTitle, LinkTitle2, and LinkTitleNoMenu but ended up with display names of "Title" instead of "Name".  Once I changed their Title attribute from "Title" back to "Name" (using this indespensible little tool - http://spm.codeplex.com), the P or G column type was back to normal but I STILL couldn't get the Check Names functionality to work.  It must be due to some JavaScript I'm using on the page.  Hopefully this little exercise will at least help others get their P or G column back to normal.


Do short journal papers ("brief reports") count less than regular papers in psychology?

Question: Many journals in psychology feature articles of different lengths, often labelled as "brief report" (4000 words) vs. "regular article" (12000 words). Are shorter articles generally considered as equally valuable and important as long articles, i.e., do they count as a "full" publication in the field of psychology?
Answer: I think this will depend completely on who's doing the "counting".  For purposes of faculty evaluation, tenure, promotion, etc, different departments may have different rules, so there won't be any general answer.
One would like to think that each article would be evaluated on its signficance, rather than length, and that decisions would be made based on overall contribution to the field, rather than a number of papers.  Of course, this doesn't always happen.
Comment: Ask your advisor/faculty mentor.
Comment: So there are departments that care about these issues? Is it necessary or am I even expected to specifically mark short papers as such in a CV?


Comparing concentrations of proteins in controls and people with a certain disease

Question: Concentrations of 50 proteins were measured in 50 normal persons and 150 patients. I am just wondering what kind of analysis will be most appropriate to finding out which protein concentration is most different.
Comment: What is your interval between measurements , daily ? weekly ?
Comment: It was measured only once for each person.
Comment: Because your question mentions change, this does not appear to be able to be answered with your data - you would need at least two measurements for each protein, one of which is some type of baseline. This is required so individual variation in starting protein levels is taken into account in the analysis.
Comment: @Michelle, I think this may just be a language issue. I suspect the OP may simply be interested in differential expression between cases and controls.
Comment: I think ANOVA might be useful.
Comment: Have you a time measure for disease duration? I'm assuming that the patients are not all measured at the same disease progression point. Time could go in as a covariate.
Answer: I would suggest the following approach:
First run unpaired t tests on each of the 50 proteins. Record the P value from each comparison, but ignore any statements about statistical significance.
You next will divide the 50 proteins into two groups, those where you suspect the difference is real ("discoveries") and those where you suspect the difference is a coincidence. To decide where to draw the line, you need to choose the maximum false discovery rate (FDR) you feel comfortable with. This is the probability that a protein that you think shows a real difference is in fact a coincidence of random sampling, a false discovery.
Once you have decided on your desired maximum FDR (a fraction between 0 and 1, usually abbreviated Q), you can easily divide your 50 proteins into "discoveries" and "not discoveries" using the method of Benjamini and Hochberg. Briefly, the method first sorts the P values from high to low. The comparison with the largest P value is considered to be a "discovery" if it is less than Q. The second largest is a discovery if the P value is less than Q*(24/25), ... and the comparison with the smallest P value is a discovery if it is less than Q/25. (Why 25? Because there are 25 comparisons in your example). Once you find a comparison to be a "discovery", also call all other comparisons with smaller P values to be discoveries (without doing more calculations).
Note that the term "significant" is not used with this FDR method.
GraphPad Prism 6 can do all this with its multiple t test analysis. But so can lots of programs. It also wouldn't be hard to do it all with Excel.
Answer: I think that your problem could be analysed thought a multivariate approach. It is a shame that the n are inequal. Permanova (permutational ANOVA) is a powerful tool design for mutivariate analysis though permutation techniques (www.stat.auckland.ac.nz/~mja/Programs.htm)
there are extensive manuals on that web site.
I would conduct a one-way permanova (on eucledian distances - on 50 dv (proteins), and if you find statistical diferences between those two group, i will follow analysis of which variable/s are responsables for the major differences. These techniques are very studied in ecological situations (replace proteins type by species; and then it is always important to know which species (or proteins) are responsable of the differences between sites (or groups)), i will search for IndVal techniques or SIMPER rutine.
please excuse my english!


How does pseudo-random noise increase DCF77 accuracy

Question: A few years ago the Germans added a pseudo-random noise signal (from a LFSR) to their time reference DCF77. I heard this should allow you to get a more accurate signal at the receiver side. But the signal delay due to the distance (up to 2000 km) and due to the electronics is the same for the basic AM signal as for the pseudo-random noise, isn't it?
How can I use the added pseudo-random noise?
Answer: According to Meinberg:

The carrier frequency of 77.5 kHz is amplitude-modulated (AM) with time marks at the beginning of each second. Radio clocks decode those time marks in order to yield the current date, time, and status. Since the AM signal is often superimposed by interfering noise, there received signal must be filtered with low bandwidth, causing a skew and a jitter of the demodulated time code in the range of 10±3 ms.
This accuracy is often not suitable for modern applications, so the PTB introduced an additional modulation which allows for increased accuracy using correlation techniques for the receiver.
In addition to the AM, the carrier signal is phase-modulated with a pseudo-random noise sequence (PZF, PRN). The PRN sequence contains 512 bits which are transmitted by phase modulation between the AM time marks, including the same number of logical '0' and logical '1' bits to keep the average phase of the carrier signal unchanged. The maximum phase deviation is ±10° and the length of one bit corresponds to 120 periods of the 77.5 kHz carrier frequency, i.e. 1.55 ms. The complete PRN sequence is transmitted once every second, starting 200 ms after the beginning of a new second and ending shortly before the next one.
The phase modulated signal can be received with higher bandwith than the AM signal. The radio clock generates the same PRN sequence locally and uses correlation techniques to derive the time frames with a dispersion of a few microseconds only. Additionally, correlation technique provides a high degree of immunity against interference and electrical noise.

(my emphasis)
More details of the PRN algorithm etc are at the usual place
Even more details in PTB paper 1988
Comment: If you're 300 km from Mainflingen you have a delay of minimum 1 ms (more added by electronic components). How relevant is microsecond dispersion then? OP seems to ask how or if the pseudo-random noise will solve this.
Comment: Delay isn't the problem, as it's easily corrected by adding a constant. The problem, as the first paragraph says, is the low-pass filtering. *The phase modulated signal can be received with higher bandwith than the AM signal*, thus the jitter is less.


Play .mp4 in WebView

Question: Is it possible to play .mp4 videos in WebView? I cant use VideoView due to some application requirements. (I want the video in a frame)
Answer: Android webkit is not powerful enough to support playing of video in webview or browser. trick is only that you have to call Videoview to play. Android native browser does the same.

Play .mp4 in WebView


Chat room list layout changes when zooming out

Question: On the chat page, when I use zooming (ie, zoom page size to anything less than 100%) the box alignment of the chats shifts to a 3-column fit on webkit.
Answer: I can't reproduce this now.  (I realize it's been 5 years since the question was asked.)  The whole page zooms, preserving four columns, in both directions.  Other things break, but the number of columns doesn't change.  This is 6 zoom levels out:
Comment: Zoming in doesn't change the number of coloums either. A slider bar comes up but the number of columns still stays the same
Comment: That is weird... I checked both FF and Chrome (for Mac) on Sunday and the problem still existed then. See image here: [Sort "favorite" chat rooms by strict recent activity rather than by type of room](https://meta.stackexchange.com/q/303452/284336)
Comment: @Catija huh, that's weird -- I just took that screenshot in Chrome on a Mac.  And I see the four columns + horizontal scrollbar all the time if I zoom in, on both Firefox (Mac and WIndows) and Chrome (Mac).  Oh, and tablet too, now that I think about it.  I've never seen a different number of columns.  I wonder what's different for you?
Comment: Yeah... :/ It doesn't reduce to three columns on Chrome for Windows, either... so I'm really confused now... :(
Comment: Well.. balpha is now in active bug watch duty, so maybe he silently fixed it. /cc @Catija. :-)
Answer: Stack Exchange does not support zooming, as officially said here:

We do not support zooming - either in or out.

(Post author was SE employee/developer when writing that answer)
So, this bug is most likely status-declined as well.


how should I handle a permanent job offer after working as a temporary contract through staff agency?

Question: I have been working for a company for two months through a staffing agency. The company offered me a permanent position which I will work directly to the company, not through a staffing agency.
I am very interested in it and considering to say "yes".
However, I am currently an employee of a staffing agency which I think I should inform and discuss with the agency about the offer.
I don't know how should I handle to have great terms for all of us. How should I discuss with the agency before accepting the offer? Does anyone know any related policies of a staffing agency and of a company in term of this matter?
What will happen with a staffing agency if I accept the offer? Have anyone been in my situation? I am new to the workforce so I would appreciate your advice.
Answer: I'd start by asking the company you're contracting for and which is offering you a permanent job.  They should have an agreement in place with the staffing agency about hiring contractor to permanant.
There normally shouldn't be anything for you to do other than paperwork; your future employer may have to make a payment of some sort to the staffing company as a de facto recruiting fee.
Comment: Exactly so. Temp-to-perm is a very common occurrence for staffing agencies. Your manager and HR department at the company, and your agent at the staffing place all know exactly what to do about this. It's not your responsibility to deal with it. Seriously.  Congratulations, by the way.
Comment: @O.Jones Yes, but it is useful to actually ask the manager or HR at the company and talk to the agent at the staffing agency, because I have heard of things not going well when one of these people who's supposed to know exactly how to handle this failed to think about it. In those cases, most of the time it was just an annoyance for the person who forgot to file the paperwork, but if your HR rep has to do three times the paperwork and pay twice the recruiting fee because they messed up, they may be a little disgruntled in general.  So it's good of the OP to ask.
Comment: @EdGrimm good point. You're right.


iPad app using Xcode, how to take user text input and display it in another text field

Question: I am rather new to iOS coding and am trying to make an application where when the user types in some text the app output their text in ASCII art.
I just want to know how I can get the app to realise when the user types "The" that it has to realise that there is a T a H and an E and put out a certain list of characters.
I am making this for the iPad, using a "Tabbed application" pre-made workspace.
Answer: Make sure your viewcontroller is the delegate of the "entry" text field. Implement textField:shouldChangeCharactersInRange:replacementString: and make the equivalent changes to the string of your "art" text field. Make sure you return YES at the end so that the entry text field can actually be updated.


Should I avoid using too many static methods in PHP?

Question: As we all know, static methods can be called without instantiating the class. So I wonder if static methods will be loaded into memory before I use them. If that, in my view, I should use more intance methods instead of too many static methods. Anyone advice? I am not familiar with the underlying mechanism of PHP.
Comment: A static method is just a regular function with a fancy name (and restricted access if it is not `public`). Static methods are not OOP, they are procedural code in disguise. The code of the main script is loaded in memory and compiled when the page is requested. It loads in memory and compiles the [`include`](http://php.net/manual/en/function.include.php)-d files when (and if) the `include` statement is executed.
Comment: Yes, you should avoid too many static methods in PHP, but not for memory management reasons. Because it's a signal you're not doing OOP right. And this will hurt you more in the long run than a few extra bytes of used ram (which I'm not sure is even the case).
Comment: The question of using a static method or working with objects is typical one of the actual scope of what logic you try to implement. That should be your first concern: that people can understand the logic when it gets more complex, that you are able to implement special cases without making the code appear bloated by too many runtime arguments. Questions like memory footprint should not always be ignored, but they usually are not that important any more these days. If you work in an environment having issues here, then why do you use OPP at all?
Comment: of course, from the perspective of OOP, I should avoid too many static methods. just wonder if they will be loaded into memory before I use them??
Answer: A static method is just a regular function with a fancy name (and restricted access if it is not public).
Static methods are not OOP, they are procedural code in disguise.

Should I avoid using too many static methods in PHP?

It depends how many do you think are "too many". For pure OOP code, one static method is already "too many". But sometimes it's unavoidable (read "easier") to write a static method for some functionality.

So I wonder if static methods will be loaded into memory before I use them.

No matter if you run a PHP script using the CLI or it is invoked through the web server to serve a web page, the text of the script is loaded into memory and compiled. If the compilation is successful (i.e. there are no syntax errors), the interpreter starts executing it.
Everything that is defined in the script is already in memory at this moment, but only the items defined in the main script. The inclusion statements (include, include_once, require, require_once) are not processed during the compilation phase.
The file referred by a include statement is loaded in memory, compiled and executed when, and if, the include statement is reached during the execution of the script. The entire content of the included file is loaded, parsed and converted to opcodes, no matter if it contains functions, classes or global code. There is no differences between instance methods and static methods from this point of view.
Comment: soga. help me a lot
Answer:
So I wonder if static methods will be loaded into memory before I use them.

When a class is loaded, all of its methods are always loaded. This happens regardless of whether those methods are class methods or instance methods, or whether they are being used by the application.
Use whatever type of method is most appropriate for your design.
Answer:
I should use more intance methods instead of too many static methods.
  Anyone advice?

Well sometimes you need to define a static method, if you need to call it without creating an object of that class but this should be limited.
When to use static methods:

You can use static methods as factories to create an object according to the context or sharing resources with other instances.
If there is no relation with your purpose and an instance

If you are planning to use public static properties, I would recommend to use CONST in some cases unless you don't want to change its value.
Why?

Consts are on the class and object scope and its always immutable (You cannot change its value) and which is safe to use.
Static properties not on the object scope but on the class scope and its mutable (can be change) and which is not safe to use.

And alternatively you can check the Singleton pattern to see how to use static methods on resource sharing.


Need Tips for Mounting screw-in Slider electrical Boxes

Question: I know they've been around awhile but I'm still kind of new to them. I occasionally have to mount these Allied slider boxes in new and old work situations, and sometimes they go in perfectly with no problems. However, yesterday I couldn't get them straight to save my life. Yesterday was an especially difficult case because the upward angle of the screws and proximity with the countertop made mounting fairly awkward.
I just find it too easy to get one screw slightly off course, and then the slider twists the whole box. This causes the box to telescope forward at odd angles when you try to slide it out later. Once a screw sinks into wood, it really wants to find that same hole again even if I try to readjust away from it. Anyway, I'm  looking for tips from anyone who knows what I'm talking about.How do you get these things dead on, every time?
Comment: Your last 2 images appear to be identical, did you mean to upload something else?
Comment: @FreeMan, thanks for the ideas. The boxes are a bit tricky in some locations but I'm finding they aren't bad if I am able to hold them firmly in place with one hand and run the impact driver with the other. I think I need to find a clamp of some kind to act as a third hand if I ever have to use the right angle attachment again (which requires two hands just to operate). The boxes are nice for tight places where it's difficult to drive nails, and they slide out to the extra depths of layered finish, such as tiled backsplash. Another con: the slider sometimes hinders wide devices such as dimmers
Comment: yes, thank you. I've swapped the duplicate out and added another view.
Comment: I think I need to find some of these! They're certainly not at my local big-box. Those look _so_ much easier to use and adjust than either nail in new work or "wing-and-flange" old work boxes.
Answer: Use a small angle head drill and drill pilot holes - as you say the screw follows the existing hole.
Comment: I could see sacrificing one as a "starter" piece by pulling the slider out and removing the screws so you've got the spacing and the alignment right. Of course, you may be able to do that, then reinsert the sliding piece and the screws and not have to sacrifice the box at all.
Answer: I would like to suggest that, as with many things, it just takes practice. If you do it enough times you will learn just how much to hold the box proud of the wall surface when starting the screws - knowing that the screws will tend to pull the box into the wall cavity some as they tighten down.
When working in less than optimal positions such as under a counter it takes some additional skills as a contortionist and knowing when to bring in additional lighting.


Email sent confirmation in Thunderbird

Question:
I am the tech-support for my 93-year old grandpa. He starts to have difficulties with sending emails.
He says everytime he wants to send an email it suddenly is gone. Of course it's not, he just thinks it is and then calls me all upset.
So my question is, is there an Addon for Thunderbird that just opens a pop-up dialog after the email has been sent saying "Email sent"?
All i found is confirmation dialoges before sending but not after.
Thanks in advance for your answers!
Comment: For me, thunderbird reports successful sending of an email in the sending dialog that opens while sending. It says "Mail sent successfully", but it only displays very shortly (less than a second actually) so that's hard to pay attention to. Maybe you can tell him to check the "sent" folder in case he is unsure?
Comment: I would like to add that usually after replying to a mail a "replied" icon appears next to the mail in the overview, maybe you can point him in that direction.
Answer: In Thunderbird Account Settings, Copies & Folders, an email address can be specified to receive "carbon copies" on sending a message.

This might be of help in two ways:

If an alternate account for your father is set, and alerts are set on receiving a message, he'll get notified when the mail goes into the alternate account, and it will be shown in bold until read.
If he doesn't mind your looking at his mail, you could also get an alert, so that should he be concerned, you can confirm it was sent.

A possible disadvantage is that confirmation may take a few minutes. The delay can be made shorter by adjusting Check for mail every xx minutes in the  Server Settings for the account set to receive the Cc:, but cannot be completely eliminated.
Answer: Or change account settings to put sent mail in the Inbox. Then sent messages immediately appear in the folder that grandpa is accustomed to looking at, no CC required.

Email sent confirmation in Thunderbird


! Package inputenc Error: Unicode character ḱ (U+1E31)(inputenc) not set up for use with LaTeX

Question: I'm having this error while compiling. I do not know how to Declare this character in order to make it visibile so I can delete it.
Comment: I discovered that the problem is in my bibliography, when i do not print it I have no error. Hope this can help
Answer: if you type h to the error prompt it tells you:
! Package inputenc Error: Unicode character ḱ (U+1E31)
(inputenc)                not set up for use with LaTeX.

See the inputenc package documentation for explanation.
Type  H <return>  for immediate help.
 ...

l.5 ḱ

? h
You may provide a definition with
\DeclareUnicodeCharacter

adding
\DeclareUnicodeCharacter{1E31}{\'k}

To your document allows it to run without error.
Comment: Since this character is used in transliteration of Macedonian, it might make sense to add it to `utf8enc.dfu`. The other Macedonian specific character is ǵ, that's already included.
Comment: @egreg I was wondering myself if we should do that, or perhaps the whole extended latin block, but maybe that's bigger than needed. upper and lowercase K ?
Comment: Several characters on the extended Latin blocks are there for completeness, I guess. I believe that characters used in Romanizations should be added to `utf8enc.dfu`. Maybe not complex things such as pinyin, for which there are specialized packages, but mappings alphabet to alphabet are simpler.
Comment: @egreg do you have a list?
Comment: I guess that we have a fairly complete coverage for Cyrillic European languages; I sent a list to the team.
Answer: Another solution is to replace your fontenc and inputenc declarations with \usepackage{fontspec}, and compile in LuaTeX or XeTeX. This will use Unicode natively. It cuts the Gordian knot of problems caused by TeX starting out as 8-bit software.
However, it is possible that your font does not contain this character.  The legacy behavior of TeX is to silently ignore this error if it happens and leave blank spaces in your document.  To turn this into an error, add \tracinglostchars=3  near the top of your document.
You would actually fix the missing character by defining the code to render it with newunicodechar, or by changing fonts.


What is the maximum likelihood estimator of the mean of two normally-distributed variables?

Question: Let $Z=(X+Y)/2$, where $X$ and $Y$ are independent normally-distributed random variables with known variances $\sigma^2_X$ and $\sigma^2_Y$ and unknown (and possibly different) means. Given a sample $x_1$ from $X$ and $y_1$ from $Y$, what is the maximum likelihood estimator of the mean of $Z$?
Comment: You should ask another question on the new issue instead of editing the existing one.
Answer: If $Z = \frac{X+Y}{2}$ then it must be that:
$Z \sim N(\frac{\mu_X + \mu_Y}{2} , \frac{\sigma_X^2 + \sigma_Y^2}{4})$
Thus, the mle of the mean of $Z$ given that we observe $z=(x_1 + y_1)/2$ is:
$\frac{x_1 + y_1}{2}$
Comment: I fixed the original question so that it make sense.


GCD of polynomials over GF(p)

Question: I have two polynomials:
$$
f(x)=(x^2+1)(x-2)
$$
$$
g(x)=(x^3+7)(x-2)
$$
I am supposed to find their GCD over GF(p) for some prime p.
I "understand" that their GCD is $(x-2)$ but what is the meaning to find the GCD over $GF(2)$ or $GF(3)$?
I know that $(x-2) \equiv x \pmod 2$, so the GCD(f,g) over GF(2) is $x$?
Am I right? wrong? Am I getting anywhere?
Thanks!
Answer: It means what it literally says; $f(x)$ and $g(x)$ are given as polynomials with coefficients in, say, $\mathbf{F}_5$. (any polynomial with coefficients in the integers can easily be converted to such a polynomial) Then, you compute their polynomial $\gcd$.
And the $\gcd$ might not be $x-2$. Continuing with the $\mathbf{F}_5$ example, it turns out that their $\gcd$ is $(x-2)^2$, because
$$ (x^2 + 1) = (x-2)(x-3) $$
$$ (x^3 + 7) = (x-2)(x^2 + 2x + 4) $$
and $x^2 + 2x + 4$ is relatively prime to $x-3$. But rather than factoring, the $\gcd$ can be easily computed by using the Euclidean algorithm.
Of course, $(x-2)^2 = (x+3)^2 = (x-2)(x+3)$, so any of those could be given as the $\gcd$.

One might be interested in the more sophisticated question of, given those two polynomials with coefficients in the integers, for which values of $p$ their $\gcd$ be $(x-2)$ after converting them into polynomials over $\mathbf{F}_p$.
The answer to this question can be solved with resultants; as polynomials over the integers, we have
$$ \text{Res}(x^2 + 1, x^3 + 7) = 50 $$
which tells us that these two polynomials will be relatively prime (after converting them into polynomials over $\mathbf{F}_p$) if and only if $p$ is relatively prime to $50$.
In particular, this means you need to rethink your statement of the $\gcd$ in the case of $p=2$!
(note that $\text{Res}(f(x), g(x)) = 0$ which tells us that $f$ and $g$ aren't even relatively prime over the rational numbers!)
Comment: What I'm missing is, probably, the notion that $(x^3+7)=(x-2)(x^2+2x+4)$ in GF(5)... I wonder how to calculate this. Plus- what do you mean calculating the GCD using the Euclidean algorithm? I have used this method go get my "original" $x-2$ answer... (f,g were not factored in the first place).
Comment: @bomba6 You don't need to compute such factorizations - see my answer. Please feel welcome to ask questions if anything is not clear.
Comment: @bomba6: Then either you made a mistake in the Euclidean algorithm, or more likely you computed the GCD by doing arithmetic in $\mathbb{Q}$ when you should have been doing it with arithmetic in $\mathbf{F}_2$. Did you ever divide by $2$ in your calculation? That's a sure sign that you were doing arithmetic in the wrong field. (because you *can't* divide by $2$ in $\mathbf{F}_2$... because $2=0$ and you can't divide by $0$)
Comment: @Hurkyl I need to compute the GCD over GF(p) for all primes < 31. I think I not supposed to run the entire algorithm so many times.
Comment: @bomba6: If you don't use my resultant trick, then what you can do is proceed by using only steps that work in *every* field. Then, when you want to do something special (like divide by $2$), then you can split the problem into two cases: one where you find it in $\mathbf{F}_2$, and one where division by $2$ is allowed.
Answer: Hint $ $  Use Euclid's algorithm $\rm\ gcd(a,b) = gcd(a,b\ {\bf mod}\ a)\ $
and this $\rm\:gcd(ca,cb) = c\,gcd(a,b)$
$$\rm\quad (x\!-\!2)\,gcd(\color{}{x^2\!+\!1},\,7\!+\!\color{#c00}{x^3})\, =\, (x-2)\,gcd(\color{#0a0}{x^2}\!+\!1,\,7\!\color{#c00}{-\!x})\, =\, (x\!-\!2)\,gcd(\color{#0a0}{7^2}\!+\!1,\,7\!-\!x)$$
where we used $\rm\:{\bf mod}\ \ \color{}{ x^2\!+1}\!:\ x^2\!\equiv -1\, \Rightarrow\,\color{#c00}{x^3\!\equiv -x};\: $  $\rm\:{\bf mod}\ \ 7\!-\!x\!:\ x\equiv 7\:\Rightarrow\:\color{#0a0}{x^2\!\equiv 7^2}$
Remark $\ \rm{GF}(p) = \Bbb F_p\:$ denotes the finite field of $\rm\:p\:$ elements. The Euclidean algorithm works for polynomials over any field, in the same way as it does over the classical fields, because polynomial long division-with-remainder algorithm works universally for polynomials that are monic (i.e. lead coefficient $= 1$). But, over a field, every polynomial is associate to a monic polynomial (multiply it by the inverse of the leading coefficient).
Comment: @bomba6 You don't know that $\rm\:gcd(ca,cb)\, =\, c\,gcd(a,b)\,?\ $  This is the gcd *distributive law*. $\ $
Comment: @Math Gems- I am a slow reader. Plus, my reputation is not letting me to vote up. I'm reading, still trying to figure out the best way to do it, without the trick of $(x-2)gcd(...)$ because we haven't learned this way.
Comment: @bomba6 [This answer](http://math.stackexchange.com/a/113045) has three proofs of the gcd distributive law - all of which work also for polynomials over a field.
Comment: @MathGems yes, my mistake... haven't noticed that.
Answer: Often things turn up in mathematics to have a natural ordering. In particular, when it comes to divisibility in commutative rings, we can say that "$\rm n$ is bigger than $\rm d$" if $\rm d\mid n$ (that is, if there exists some $\rm k\in R$ such that $\rm n=dk$). Given two elements $\rm a,b$ in a ring $\rm R$, we say $\rm d$ is a common divisor if it is a divisor of both, i.e. $\rm d\mid a$ and $\rm d\mid b$. Then we say $\rm c$ is a gcd of $\rm a$ and $\rm b$ if it's uniquely maximal among the set of common divisors - that is, if $\rm c$ is itself a common divisor of $\rm a,b$, and every other common divisor $\rm d$ of $\rm a,b$ divides $\rm c$ as well (i.e. $\rm d\mid a,b\implies d\mid c$).
The gcd is generally only defined up to multiplication by arbitrary unit $\rm u\in R^\times$. In the context of polynomial rings, $\rm K[x]$ where $\rm K$ is a field, of all of the gcds we choose the monic one so that the gcd is a well-defined function (spits out only one output for any set of inputs). In addition, for this setting we have a nice Euclidean algorithm (which is used explicitly below) that makes hand computations feasible, pleasant even.
See the Wikipedia page on polynomial gcds for more information. To summarize the Euclidean algorithm for computing gcds as succinctly as possible, I'd say this: add/subtract multiples of one argument to the other repeatedly in order to simply the expression - in particular, to reduce the degree of the polynomial in one or the other argument at each stage. Notice how in the integer setting the algorithm seeks to reduce the size of the arguments at each stage, whereas in the polynomial setting the algorithm seeks to reduce the degrees. The analogy between the absolute values of integers and degrees of polynomials runs surprisingly deep into number theory.
One useful trick is $\rm \gcd(an,am)=a\gcd(n,m)$. This allows you to reduce the problem via
$$\rm \gcd(f(x),g(x))=(x-2)\gcd(\color{Blue}{x^2+1},\color{Purple}{x^3+7})$$
$$\rm =(x-2)\gcd(\color{Blue}{x^2+1},\color{Purple}{x^3+7}-\color{DarkOrange}{x}(\color{Blue}{x^2+1}))=(x-2)\gcd(\color{Teal}{x^2+1},\color{Purple}{7-x})$$
$$\rm =(x-2)\gcd(\color{Teal}{x^2+1}+\color{Red}{x}(\color{Purple}{7-x}),7-x)=(x-2)\gcd(7x+1,7-x)$$
using the rules $\rm \gcd(\color{Blue}{a},\color{Purple}{b})=\gcd(\color{Blue}{a},\color{Purple}{b}\pm\color{DarkOrange}{n}\color{Blue}{a})$ and $\rm \gcd(\color{Teal}{a},\color{Purple}{b})=\gcd(\color{Teal}{a}\pm \color{Red}{m}\color{Purple}{b},\color{Purple}{b})$ (for arbitrary choices of $\rm \color{DarkOrange}{n},\color{Red}{m}\in K[x]$) repeatedly. Notice the above computation is valid in any field. Specializing to ${\bf F}_2$ aka $GF(2)$ (see here), $\color{Purple}{7}=\color{Purple}{1}$ and $\color{Teal}{2}=\color{Teal}{0}$ and $\color{Blue}{-1}=\color{Blue}{1}$ so the computation may be finished as
$$\rm (x-\color{Teal}{2})\gcd(\color{Purple}{7}x+1,\color{Purple}{7}\color{Blue}{-}x)=x\gcd(x+1,1\color{Blue}{+}x)=x(x+1).$$
Comment: Why this $(x−2)gcd(x^2+1,x^3+7−x(x^2+1))$? How did it come to your mind?
Comment: @bomba6 It's the idea behind the Euclidean algorithm, which I edited in a few words about just now. Recall in the integer setting, if you want to compute say $\gcd(100,23)$ using EA, you'd write $100=23\cdot4+8$ via the [division algorithm](http://en.wikipedia.org/wiki/Division_algorithm), so that you may write $$\gcd(100,23)=\gcd(100-4\cdot23,23)=\gcd(8,23).$$ Similarly $23=4\cdot8-1$ so $$\gcd(8,23)=\gcd(8,23-4\cdot8)=\gcd(8,-1)=1.$$ In the polynomial setting, to do the same, at each stage ask "what can I multiply one argument by and add/subtract to the other in order to *reduce degrees*?"
Comment: Continuing your example for GF(5), and the fact that 7=4(3), -1=2(3) and 1=-2(3) I get $2(x-2)gcd(x+2,x-2)$, but again, I'm stuck.
Comment: @bomba6 If you're going mod 3 then you're talking about GF(3) rather than GF(5). In this case (first of all ignore the 2 out in front; remember we want monic so we can ignore all scalar multiples of the entire expression by invertible elements), note that mod 3 we have -2=1 and 7=1 so $$\rm (x-2)\gcd(7x+1,7-x)=(x+1)\gcd(x+1,2x+1)$$ $$\rm =(x+1)\gcd(x+1,2x+1-(x+1))=(x+1)\gcd(x+1,x)=x+1.$$
Comment: Thanks, I'm going to try that... Lets see were I'm heading. Thanks for your help. (and I meat GF(3) indeed.
Answer: Hurkyl said:
Res(x2+1,x3+7)=50
which tells us that these two polynomials will be relatively prime (after converting them into polynomials over Fp) iff p is relatively prime to 50.
Could someone point me to a proof of said statement? Obviously for the general case not just this specific one..
Comment: This should not be posted as an answer to the initial question.
Comment: This should be asked as its own question: that way people can find it and benefit from the answer as well.
Comment: Yeah realized that after posting. Made a new question for that. Thx for the advice.

GCD of polynomials over GF(p)


Does flying to New York to join a cruise ship leaving from Brooklyn on the same day count as transit for ESTA purposes?

Question: I am travelling on a scheduled flight from London arranged by the cruise company who will be providing a shuttle bus directly to the ship.
Comment: Is there a difference? (are you using a official site, which ends with `.gov`? You need an ESTA also for transit. Note: probably the cruise ships stop in other ports in US (when departing from NYC). And if you are a crew member, ask your cruise line (there are some special/simplified procedures)
Comment: @GiacomoCatenazzi The ESTA application asks if you are transiting or not
Comment: @GiacomoCatenazzi a crew member can't use ESTA in lieu of a C-1/D visa.
Answer: The ESTA is the same regardless of your travel purpose. This is different from most transit visas which are easier to get than a visitor visa, but have much stronger constraints. So there isn't a very precise definition of "transit" in the context of an ESTA.
Since you aren't spending a night in the US, say "yes" to the transit question. This will let you skip the question of where you're spending your first night in the US (and instead you'll be asked how you continue your journey).
For nationalities that aren't eligible for an ESTA, the US have a transit visa which is distinct from a visitor visa. Your travel plans are compatible with a transit visa since you are meet the requirement of "reasonably expeditious departure of the traveler in the normal course of travel as the elements permit and assumes a prearranged itinerary without any unreasonable layover privileges".
Comment: A thought: As the cruise ship might be in a US harbor, the traveller might spend the night in the US (my understanding is that the ship has to be in international or other countries waters to not be in the US). So maybe the passenger should give the cruise ship as first night?
Answer: The ESTA is a document that allows you, as a citizen from a visa-waiver nation, to fly to the USA. That's it. And since there's no airside transit in the US, you have to enter the country, on the visa waiver. You will go from JFK to Brooklyn as a regular tourist. And then leave the country there, boarding the cruise ship.
TD;DR: The purpose of your flying to the US is irrelevant: you need to enter the country when you land.
Comment: The ESTA application asks if you are transiting or not
Comment: "The purpose of your flying to the US is irrelevant: you need to enter the country when you land": this is true, but not relevant to the question. You also need to enter the US if you are traveling on a C-1 visa.  The lack of airside transit in the US does not mean that the US doesn't recognize transit as a distinct immigration status or purpose of travel; it does.


Physics Standard Deviation

Question: I am a physics enthusiast and I have a question: Why is it meaningless to express the '$\pm$' (standard deviation) value as a percentage?
Answer: Standard deviation adds uncertainties to the measured value: $23.3\pm 0.4\,{\rm m}$. One can quickly look at the error (which has units of ${\rm  m}$ in my case) and think, The value could be as low as $22.9\,{\rm m}$ or as high as $23.7\,{\rm m}$ without much thinking. Modifying this to being a percentage of the value would be confusing.
Plus it would be arbitrary. As Martin Beckett points out, since the Celsius and Kelvin scales have identical temperature spacing but differing 0-points, making the error (std. dev.) scale to the value would be ridiculous:
$$20.0\pm0.1\,{\rm C} \to 20.0\,{\rm C}\pm0.5\%$$
$$293.0\pm0.1\,{\rm K}\to293.0\,{\rm K}\pm0.034\%$$
Same value in units systems would lead to differing uncertainties; this would bring about more confusion.
Answer: Depends what you are measuring.
If you are measuring the temperature of a glass of water to 20C +- 0.1C what would the percentage be?
Now what would it be if you measured it as 293Kelvin +- 0.1K
Comment: Perhaps, could you be more general?
Comment: He is telling that there are different units of measurements, and so the percentage in the error would vary.

Physics Standard Deviation


What is the derivation of the word "double-dome"?

Question: What's the derivation of the meaning of the word "double-dome," meaning intellectual?
Comment: I'm pretty sure I've heard "double dome" used in a context where I took it to mean "military brass".
Answer: It seem that it is just the image of a 'dome' similar to a bald  head at the origin of the saying:
Double-dome:

(slang) (mildly derogatory) Alternative spelling of doubledome An intellectual or scholar. (Wiktionary)

Origin:

The word conjures the image of two bald-headed men putting their heads together in an effort to solve a problem.

According to The Oxford Dictionary of American Political Slang and the The Routledge Dictionary of Modern American Slang and Unconventional English the term was in use in the 40's in the US.

1943 H.A. Smith Putty Knife Factory 207: Arthur Birsbane [ 1936]...was known among fellow newspapermen as Old Double Dome.

The term is a synonym of egghead where the reference to a bald head is similar.

1907, "bald person," from egg (n.) + head (n.). Sense of "intellectual" is attested from 1918

presumably fr the putative high, domed, egg-shaped heads of such persons; the term was used in a letter of Carl Sandburg about 1918]

Cupola (dome)  del Brunelleshi - Florence


Given a RxC grid, how to generate N 2D points randomly such that no 3 points are collinear?

Question: Context, I have a geometric algorithm that is sensitive to collinear points and receives as input a list of points in 2D generated randomly. Suppose that I have a Boolean function nonCollinear(x,y,z) that given three points returns true if they are non collinear and false otherwise. Is there an efficient algorithm to generate a list of random points such that no 3 points in the list are collinear? The points coordinates x y are integers, the amount of points is N and the grid size is RxC, I know that there is a restriction between N and R C, so I am fine if the algorithm relies in some assumption (e.g RxC is way bigger than N)
Comment: Do you need some restrictions on the distribution generated? Some fixed shapes (e.g., points along the edge of an approximate circle; in general, the vertices of any convex shape) can be easily generated to have no three points collinear
Comment: Ideally I would want the points closer to uniformly distributed
Comment: However any easy algorithm will do if it is random in some sense.
Answer: For simplicity , assume the grid is a square $N \times N$ grid and $N$ is a prime.
Its easy to see that from each row we can pick $\leq 2$ points only , so the maximum number of points we can chose is $2N$.
Now consider the set of points $\{(i,i^2\ mod\ n)\ |\ 0\leq i \leq n-1 \}$.
For any set of 3 points to be collinear (Lets call them $(x_1,y_1),(x_2,y_2),(x_3,y_3) , x_1 < x_2 < x_3$ ) we must have $\frac{y_3 - y_2}{x_3 - x_2} = \frac{y_2 - y_1}{x_2 - x_1}$ , putting in $y_i = x_i^2\ mod\ n$ , we obtain $x_3 + x_2 \equiv x_2 + x_1 \mod n$ and this is only possible when $x_1 = x_3$.
Hence we have a set of $N$ points where no 3 points are collinear and it is the best we can obtain upto a constant factor.
Since this is a deterministic construction , to get a random family of points , instead of choosing $i^2$ , we can take any random quadratic polynomial $p$ and take the set of points $\{(i , p(i)) \ mod\ n \ |\ 0 \leq i \leq n-1 \}$.
Comment: If you have $3$ points in a row, they will be automatically collinear and hence we have max of $2$ points in a row. In the line where it talks about equating slopes of two lines by choosing two points each from any group of three points, it shows why it works. Unless the points are the same, the slopes would not match.
Comment: You can pick random quadratic polynomial $p$ with leading coefficient that is coprime to $n$.
Comment: Some points in the answer there are not clear, as why only two points can be considered in a row. Also, why a particular function of $(i, i^2 \ mod \ n)$ is considered, when collinearity is to be avoided. States to take any random quadratic function, but does not give the reason why?
Comment: @MathLover Why only a particular quadratic value of $y_i = x_i^2\ mod\ n$ need be there, to check for collinearity, i.e. to get $x_3=x_1$. This particular value, seems to simply be based upon the algebraic fraction: $\frac{x_i^2 - x_{(i-1)}^2}{x_i - x_{(i-1)}}= x_i + x_{(i-1)}$ So, can we not chose other set of points than $(i, i^2\ mod\ n)$?
Comment: I think this approach doesn't cover cases with 3 points being on one diagonal


Prove $d(x,y)=\left|\frac{x}{1+\sqrt{1+x^2}}-\frac{y}{1+\sqrt{1+y^2}}\right|$ is a metric on $\mathbb{R}$.

Question: I have to prove that $d(x,y)=\left|\frac{x}{1+\sqrt{1+x^2}}-\frac{y}{1+\sqrt{1+y^2}}\right|$ is a metric on $\mathbb{R}$. I managed to prove the non-negativity, symmetry and triangle inequality, but I am stuck on proving $d(x,y)=0\Leftrightarrow x=y$. In my textbook I have the following indication: "prove that $f(x)=\frac{x}{1+\sqrt{1+x^2}}$ is a strictly increasing function". How this indication helps me, why do I have to prove that the given function is strictly increasing?
Comment: When you have that a function is strictly increasing it's injective, hence from $$f(x) = f(y)$$ it follows that $$x = y$$. Additionally you have $$d(x,y) = 0 \iff f(x) = f(y)$$ so alltogether you get $$d(x,y) = 0 \iff x=y$$
Answer: Since $f(x) = \frac{x}{1+\sqrt{1+x^2}}$ is strictly increasing, suppose without loss of generality that $x<y$.
$\implies f(x) < f(y) \implies d(x,y)=|f(x)-f(y)|>0 \qquad (1)$
The proof where $f(x)=f(y) \implies d(x,y) = |f(x)-f(y)|=|f(x)-f(x)|=0$ is trivial. In the other direction, given that $|f(x)-f(y)|=0$, if either $x<y$ or $y<x$ but $d(x,y)= 0$ then this presents a contradiction to (1).
Answer: Consider $f(x)=\dfrac{x}{1+\sqrt{1+x^2}}$. Its derivative is  $f'(x)=\dfrac{1}{\sqrt{1+x^2}(1+\sqrt{1+x^2})}$ is clearly positive then $f$ is increasing and consequently injective. So $f(x)=f(y)\Rightarrow x=y$ which proves the not obvious side of the separation axiom $d(x,y)=0\iff x=y$. The symetry $d(x,y)=d(y,x)$ is clear. It remains the triangular inequality.
We have $$\left|\dfrac{x}{1+\sqrt{1+x^2}}-\dfrac{y}{1+\sqrt{1+y^2}}\right|+\left|\dfrac{y}{1+\sqrt{1+y^2}}-\dfrac{z}{1+\sqrt{1+z^2}}\right|\hspace{10mm}(*)$$ By the triangular inequality in $(\mathbb R,|\space|)$ one has that $(*)$ is greater or equal than
$$\left|\dfrac{x}{1+\sqrt{1+x^2}}-\dfrac{z}{1+\sqrt{1+z^2}}\right|$$ so we have prove that
$$d(x,y)+d(y,z)\ge d(x,z)$$