How to make rpg map extend as player reaches boundary? Javascript HTML5

Question: Im struggling to find an answer for my question on google, so thought id post.
Im building a top-down tile-based rpg game using html5, javascript and jquery only.
I have set up images in an array. I have set up my map in an array and just looping through it to show the tiles on screen.
I want a 750px x 600px section of a large map to show on the canvas and when the player moves to one of the 4 boundaries the map will update and show the next part of the map or if no map is available stay as it is.
How would i implement this??
If you dont understand what im asking ill try to explain better :p but heres my code:
$(document).ready(function(){

var canvas = $("#TBG");
var context = canvas.get(0).getContext("2d");

var canvasWidth = canvas.width();
var canvasHeight = canvas.height();

//Player Controls -------------------------------------------------------------------------
$(window).keydown(function(e){
   var keyCode = e.keyCode;
    if (keyCode == arrowRight){
        Player.moveRight = true;
    }
    else if (keyCode == arrowLeft){
        Player.moveLeft = true;
    }
    else if (keyCode == arrowUp){
        Player.moveUp = true;
    }
    else if (keyCode == arrowDown) {
        Player.moveDown = true;
    }
});
$(window).keyup(function(e){
    var keyCode = e.keyCode;
    if (keyCode == arrowRight){
        Player.moveRight = false;
    }
    else if (keyCode == arrowLeft){
        Player.moveLeft = false;
    }
    else if (keyCode == arrowUp){
        Player.moveUp = false;
    }
    else if (keyCode == arrowDown) {
        Player.moveDown = false;
    }
});

function player() {

    this.x = 100;
    this.y = 100;
    this.vX = 0;
    this.vY = 0;

    var moveRight = false;
    var moveLeft = false;
    var moveUp = false;
    var moveDown = false;
}

var Player = new player();

var arrowLeft = 37;
var arrowUp = 38;
var arrowRight = 39;
var arrowDown = 40;

//End Player controls ------------------------------------------------------------------------------

//Map initialisation -------------------------------------------------------------------------------------

var images = new Array(3);

images[0] = new Image();
images[0].src = "images/player.png";

images[1] = new Image();
images[1].src = "images/wall.png";

images[2] = new Image();
images[2].src = "images/grass.png";

images[3] = new Image();
images[3].src = "images/floor.png";

var tileMap = [
    [3,1,3,3,3,3,3,3,3,3],
    [3,1,1,2,2,2,2,2,2,3],
    [3,1,1,1,2,2,2,2,2,3],
    [3,2,1,1,1,2,2,2,2,3],
    [3,2,2,1,1,1,2,2,2,3],
    [3,2,2,2,1,1,1,1,1,3],
    [3,2,2,2,2,1,1,1,1,3],
    [3,2,2,2,2,1,1,1,1,3],
    [3,2,2,2,2,1,1,1,1,3],
    [3,3,3,3,3,3,3,3,3,3]
];

//Animate Loop -------------------------------------------------------------------------------------------
function animate () {

    context.clearRect(0,0,canvasWidth,canvasHeight);

    Player.vX = 0;
    Player.vY = 0;

    //Player Animation
    if (Player.moveRight) {
        Player.vX =2;
    };
    if (Player.moveUp) {
        Player.vY = -2;
    };
    if (Player.moveDown) {
        Player.vY = 2;
    };
    if (Player.moveLeft) {
        Player.vX = -2;
    };

    Player.x += Player.vX;
    Player.y += Player.vY;

    if (Player.x < 0){
        Player.x = 0;
        Player.vX *= -2;
    }
    else if (Player.x + 64 > canvasWidth) {
        Player.x = canvasWidth - 64;
        Player.vX *= -2;
    };
    if (Player.y < 0){
        Player.y = 0;
        Player.vY *= -2;
    }
    else if (Player.y + 64 > canvasHeight) {
        Player.y = canvasWidth - 64;
        Player.vY *= -2;
    };

    for (var i = 0; i < 10; i++) {
        for (var j = 0; j < 10; j++){

            var tileId = tileMap[i][j];
            var tileWidth = 32;
            var tileHeight = 32;

            context.drawImage(images[tileId],i * tileWidth, j * tileHeight);
        }

    }
    context.drawImage(images[0], Player.x, Player.y);

    setTimeout(animate, 0);
}
// End Loop ------------------------------------------------------------------------------------------------

animate();

});
Im not great with Javascript but learning and know a comfortable amount about programming.
thanks in advance
Tom
Answer: Well there isn't really a particular way to do it(like anything in activity development), but perhaps I could provide some assistance as I'm creating a floor centered activity too. There isn't really anything unique to floor layers; it's just a phrase given to charts that can be padded on top of each other. You could even have one part in your whole activity, but you can see how that wouldn't perform out. If a there was a 5X5 position of lawn and you desired to put a shrub on it, then in between the divisions you would just see whatever color the qualifications is because you changed the lawn floor that was there before. Some individuals deal with this by including another part to position the shrub on. That way the first part has lawn on it, and the shrub looks like it's on top. You might have to use several levels for several plants that are the actual to get the impact you want though. Individually, I'm only having probably one floor part in my activity. This will be for primary scenery things lawn, dust, etc. Then I will have an item part where I will have pre-made objects(which can be plants, blossoms, bad individuals, homes, etc.) and my motor will take their roles and figure out how to sketch them.
For beginners, you could get your personality to conflict with the sides of the display. For example, to conflict with the remaining part of the display, you would examine if the performer's x position was less than 0, and if so, set it to 0.
Next you'll want to be able to sketch flooring on the display. You could signify a floor map using an range of integers. Different figures would signify different floor designs that you would have to sketch. So a 3X3 range of '0's would be a map that symbolizes a 3X3 lines of lawn flooring while '1's might be water or something. You could these figures from a text/binary computer file or an XML computer file or something. Since you were thinking about XML, it's generally just a human-readable way to shop details. XML details don't really do anything(in a sense), it's up to your system to understand it.
One more recommendation is that since you are using SFML, you can use "views" to shift the photographic camera around. Look into the SFML web page for how to use them.
Now for my best recommendation. My publish is relatively unexplained, but everything I described is protected in Chip Gravelyn's floor motor guides. It's published in C# and he does a lot more things developing a floor manager, but you can still implement his things to your C++/SFML activity. Look up "NIckGravelyn" online. com.
Comment: I think you need to improve your answer in some way with code or some help links.
Answer: You are almost there! I recently implemented something similar in a tile renderer for my own game.
In this loop:
for (var i = 0; i < 10; i++) {
    for (var j = 0; j < 10; j++) {
        var tileId = tileMap[i][j];
        var tileWidth = 32;
        var tileHeight = 32;

        context.drawImage(images[tileId],i * tileWidth, j * tileHeight);
    }
}

You need to 'center' your camera. In my game, every time the player moves I center it on their location, but you can do this however you like. You can center your camera by applying an offset to your world coordinates when drawing:
for (var i = 0; i < 10; i++) {
    for (var j = 0; j < 10; j++) {
        var tileId = tileMap[i + yOffset][j + xOffset] || tileIdForEmptyCell;
        var tileWidth = 32;
        var tileHeight = 32;

        context.drawImage(images[tileId],i * tileWidth, j * tileHeight);
    }
}

In your code, i and j represent your screen tile coordinates, those never change. To 'shift' the world, you just apply an offset to your world coordinates, which are used to perform the lookup into your tile map.
You will have to account for when the map ends, which is what the || tileIdForEmptyCell bit does.
Comment: Thanks for your reply! Excuse me for being naive but could you explain in more detail (dummy language) what this line is doing please and what the variables added should be holding.
Comment: {var tileId = tileMap[i + yOffset][j + xOffset] || tileIdForEmptyCell;}
Comment: Sure, so by adding an offset (xOffset, and yOffset) to your lookup into the tile map, you are effectively shifting it by xOffset and yOffset. Experiment with constants there if you want to see what I mean. By changing these values as the players move, the map will shift.
Comment: The `|| tileIdForEmptyCell` bit means that if the first part failed (the offsets were too large or small and the array did not have a tile at that location), it will default to `tileIdForEmptyCell`, which you should replace with the tile id of blackness, or whatever your background is.

This syntax: `var a = b || c` will return `c` if `b` is "falsely". For example `var a = undefined || c` will return c. This is the case where your tile lookup failed because the offsets cause it to go off the side of the map.
Comment: I assumed from your original question that you wanted to move the map as the player moved, is this not the case?


Meaning of 'uneingeleiteter Ergänzungssatz'

Question: What is the meaning of uneingeleiteter Ergänzungssatz? Does it refer to the use of dass in the sentence as a connector of two phrases and positioning the verb at the end?
Comment: Where did you encounter this term? According to Google, it is quite rarely used.
Comment: I am enrolled in A2 Language Course from Goethe Institute in Delhi.
Their content has this word. When I used google translator, it was not showing me the meaning for each word but if I combined them, then I would get the meaning as unaccompanied supplementary sentence, and I got completely confused with this meaning.
Answer:
Ich glaube, dass er recht hat.

I think that he is right.
This is a sentence with a main clause and a dependent (here: object) clause introduced by dass. The object clause serves as an object to glauben.

Ich glaube, er hat recht.

I think he is right.
This is a sentence with a main clause and an uneingeleiteter Ergänzungssatz – also a main clause. The meaning is identical to the above sentence with the object clause, though the second clause follows the rules of the main clause.
This kind of uneingeleiteter Ergänzungssatz is similar to the structures in English and should be no problem to you. Just mind the comma.

However, there is another kind:

Regnet es, bleibe ich zu Hause.

If it rains I stay at home.
The if is implicit. You can spot those uneingeleiteter Ergänzungssatz by the finite verb in front though it's not in Imperativ mode. Indikativ and Konjunktiv are possible:

Hätte ich das gewusst, wäre ich zuhause geblieben.

If I knew that I stayed at home.

There is a third kind, also with the finite verb in front:

Er wusste nicht, war das gut oder schlecht.

He didn't know whether that was good or bad.
Comment: *Uneingeleitet* means *without an introduction*, because there is no marker word as *dass* or *wenn*. *Ergänzung* means *addition*, so an *Ergänzungssatz* is *a clause with additions*.
Comment: In the examples with conditional V1-clauses (*Regnet es …* and *Hätte ich das gewusst …*), the dependent clauses function as *Angaben*, not *Ergänzungen*.
Comment: All these things are okay. I couldnt understand the third kind and one just above it, as I havent reached upto that level yet. When we say uneingeleiteter Ergänzungen, what does it refer to?
Answer: Janka's answer is fine, but let's examine the terminology a bit closer.
Let's take care of Ergänzungssatz first. Ergänzung is the German term for complement, i.e. subjects and objects; the complementary term is Angabe, English modifier.
For many verbs, the object may either be a noun phrase or a sentence. In the first case, the German term would be nominale Ergänzung (noun phrase complement).

Die Wissenschaftler untersuchten das Phänomen gründlich.
  The scientists examined the phenomenon carefully.

In the second, Ergänzungssatz or Objektsatz (sentential complement or complement clause).

Die Wissenschaftler untersuchten gründlich, ob Pferde zählen können.
  The scientists examined carefully whether horses can count.

(I threw in gründlich in the above examples because it is an example of a modifier or Angabe; as is nicht mehr below.).
Now for certain verbs, there are two types of Ergänzungssatz possible:

Ich glaube, daß sie mich nicht mehr liebt.
  Ich glaube, sie liebt mich nicht mehr.
I think (that) she doesn't love me anymore.

How to distinguish them? It appears that there is a tradition that calls the first eingeleiteter Ergänzungssatz/Objektsatz/Nebensatz, as it is introduced by the subordinating conjunction daß, and the second uneingeleiteter Ergänzungssatz/Objektsatz/Nebensatz, as there is no subordinating conjunction.
However, I am not a fan of this terminology. Learners of German are trained to distinguish verb-initial and verb-final clauses from the get-go, so the position of the finite verb should be the most prominent feature. An alternative terminology uses abhängiger/eingebetteter Verbzweitsatz (dependent/embedded V2-clause) for the second case, abhängiger/eingebetteter Verbletztsatz (dependent/embedded verb-final clause) for the first.
This terminology has the advantage of highlighting the position of the finite verb. However, since abhängig/eingebettet is less precise than Ergänzung/Objekt , I'd actually prefer Verbzweitsatz als Objekt/Ergänzung (V2 complement clause), Verbletztsatz als Objekt/Ergänzung (verb-final complement clause).


Raspberry Pi4 with Planar PCT2235 touch screen monitor

Question: I'm fairly new to the raspberry pi world and I have a Planar PCT2235 22"touch screen that I would like to use with my raspberry pi4. The display works and the touch function sees the touch of my finger, but the pointer arrow and were it's press is registering on the monitor is about 3" away from my finger. Is there some kind of calibration that needs to be done or a driver that needs to be loaded. Thanks for any help you can provide.
Comment: The user manual does not mention how to calibrate the touch thing.  Questions: (1) Do you have the user Guide for Rpi4B? (2) Where do you download the driver for Rpi4B?  My learning Notes: https://penzu.com/p/7dbe461d
Comment: USB touchscreens generally do not require model specific drivers as the interface is standardized/generic.
Comment: Have you done anything with xinput-calibrator to set the boundaries of your touchscreen?
Answer: The Planar has a built in calibration tool. Just google it for your model number and it should resolve your issue.
Answer: It does have a calibration tool but only for windows, so unless you are planning to get windows into your Raspberry Pi that won't work.


Manual backup for mercurial repository

Question: I am using Mercurial with tortoiseHg, and I have few repositories around my computer (because i work with different languages at the same time).
I would like to have a backup of all my repositories that I would trigger manually (ideally with an icon on my desktop).
I am open to many backup solution, like using dropbox, or using another computer on the same network or both solutions at the same time.
Which is the best solution  and how can I implement it?
I am using windows 7
Comment: What operating system are you using?
Comment: windows 7 (sorry I forgot to mention it on the question)
Answer: One option is to import your repositories into a Mercurial hosting service like Bitbucket and then use the built-in push feature of Mercurial to periodically copy your local changes to the remote clone. You can find instructions on how to import an existing repository into Bitbucket here.
Answer: A repository hosting service like BitBucket will allow you to to not only backup your repositories but also get them off site giving you recovery options in case of a significant catastrophe plus allow you to easily share your work with others if you so desire.
If you just want to backup the repository, you can use any method you want (even just copying files) to grab a copy of the project's .hg directory.  At work, we use a central repository  on the corporate network that is backed up, fire and access protected.

Manual backup for mercurial repository


Properties of Validity in Logic

Question: Let $A$ be a structure, $T$ a theory (a set of sentences) and $F$ a sentence, where "sentence" means a formula with no free variables.
1) if $A \models T$ and $A \models F$, is it true that $T \models F$?
2) if $T_0 \subseteq T$ and $A \models T$, is it true that $A \models T_0$?
These questions may be trivial for you, but I am a beginner and very confused.
Answer: Statement (1) is false: Let A = { R, +, ., < } (i.e the real numbers with addition, multiplication, and linear ordering), T = <the set of all true sentences over R involving only the '<' operator>, and F = <any true sentence over R involving only the '+' operator>.  Then T is valid in A, F is valid in A, but T doesn't establish anything about F.
Statement (2) is true: If all sentences of T are valid in A, certainly the sentences of any subset of T must be valid in A.
Comment: What if $F$ is defined as the AND of all sentences in $T$? In this case statement 1) would be true?
Comment: Or better, if $F$ is defined as the AND of all sentences in $T$, does it follow that $A \models F$ and $T \models F$?

Properties of Validity in Logic


Health insurance for J visa

Question: Do international students who are J visa have to get health insurance first, before getting J visa?
Or the students can have health insurance after they get into US?
Comment: I would ask either in expatriates or academia.stackexchange.
Comment: **Before voting to close or migrate,** please be aware that the existing question base has USA J-1 visa questions inconsistently scattered between both sites.  [Please discuss here](https://expatriates.meta.stackexchange.com/questions/348/do-usa-j-1-visa-questions-belong-on-expatriates-or-travel-se)
Answer: tl;dr - Ask your university (or other J-1 sponsor).
The US Department of State requires the J-1 sponsor to enforce the insurance requirements.  Your J-1 sponsor may require you to get insurance ahead of time, or may allow you to get insurance immediately upon arrival.
If you want to use your existing insurance, you should still check with your J-1 sponsor.  Your sponsor should accept your existing insurance if it meets the coverage requirements listed in the regulations at 22 CFR 62.14.  If your insurance meets all requirements except for evacuation and repatriation, you may be able to get supplemental insurance just for those (see Where to buy US repatriation and evacuation insurance only?).
US Department of State info for J-1 participants says:

Insurance
Participants and any J-2 dependents (spouses and minor unmarried children under the age 21) accompanying them are required to carry medical insurance at the minimum benefit levels stated in the program regulations. Program sponsors are required to ensure that all participants have the appropriate medical insurance. Sponsors will verify that the participant's medical insurance meets the regulatory requirements, and will facilitate the purchase of coverage for participants who do not have their own insurance, or whose coverage does not meet the requirements. Participants interested in obtaining appropriate medical insurance should contact the responsible officer of their sponsor organization sponsoring their program. Willful failure on the part of the participant and/or any J-2 dependents to maintain active insurance coverage is grounds for termination from the program. Please refer to the regulations for details. [22 CFR 62.14]

See also: US Department of State Info for J-1 sponsors (click 'Insurance')
Comment: and how about F-1? Is it required the same insurance?
Comment: @Kittiphot Nochot The regulations for F-1 don't mention insurance. But your university may still require you to have insurance, so the rule of thumb is still: ask your university (or other F-1 sponsor).

Health insurance for J visa


Does dew point change with change of ambient temperature?

Question: I know dew point is the temperature at which air becomes saturated with vapor that was already in the air. So if I take some unsaturated air in a container and lower it's temperature, eventually at certain temperature the air will become saturated with vapor. To my understanding that certain temperature also known as dew point should only depend on total amount of vapor per cubic meter of air, not the initial temperature of air. But I recently have came across a physics problem where for an initial temperature dew point is given and asked to determine dew point when the temperature was lowered to some value. I thought the dew point should be the same but the given answer suggest otherwise. Can any one explain to me why dew point should change.
Comment: Relative humidity depends on temperature and pressure.  So, I'd wonder if they are taking into account the change in volume of the gas. If you start with 1 liter of gas/water and lower the temperature then the volume of the gas decrease too, thus increasing the absolute concentration of water.
Comment: Did they mean lower the temperature, but keep the same relative humidity maybe?
Comment: Yes, the dew point temperature should only depend on the amount of moisture in a certain volume of air. Now it's possible to change the dew point by extracting moisture from the air, so if the physics problem were describing taking the starting air below its dew point and then warming up the same air, then the final air would then have a different (and lower) dew point because moisture would have condensed out of the air when the starting air went below its dew point.
Answer: The dew point temperature depends on 2 parameters: pressure and humidity.
It does not depend on temperature.
You can find it in a diagram where these two lines intersect:

Constant pressure line (at your level, usually 1atm).
Constant saturated vapor pressure line.

Because that means that you decrease temperature keeping constant pressure. At some point, lowering temperature like that will end up matching the exact point $(P,T)$ for which your actual humidity is the saturated one. Then water starts condensing.

A good way to see it is using the mass mixing ratio, which can be easily written in terms of mol mixing ratio:
$$w=\frac{m_{vap}}{m_{dryAir}}= \frac{n_{vap}}{n_{dryAir}}\cdot \frac{mm_{vap}}{mm_{dry}}\simeq \frac{n_{vap}}{n_{dryAir}}\cdot 0.622$$
So you can say that  $ w= \dfrac{n_v}{n_d} \cdot 0.622 $, but the moles ratio is the same as the pressure ratio:
$$w= \dfrac{P_v}{P_d} \cdot 0.622 = \dfrac{P_v}{P-P_v} \cdot 0.622 $$
There is a particular case, when the pressure is the saturated vapor pressure:
$$w_s= \dfrac{P_s}{P-P_s} \cdot 0.622 $$
Relative humidity is strongly related to this. In fact,
$$ \frac{w}{w_s} = \frac{P_v / P_d }{P_s/P_d} = \frac{P_v}{P_s}=RH$$
So, once you are given your three parameters: $(P,T, RH)$, you can go on. Humidity must be given anyhow: RH, w, or whatever, but you need to know humidity.
You'll obviously have your dew point when $w$=$w_s$.
So you have a first equation: $w_s=constant$. What constant? The one you're given initially, initial conditions.
So you have that
$$const= \dfrac{P_s}{P-P_s} \cdot 0.622 $$
and the saturated vapor pressure depends on $T$. A good model is
$$P_s = A\cdot e^{-B/T}$$
So now you decrease temperature with constant pressure until water condenses. That's an extra equation: $P=const$. What constant? The one you're given initially.
So you finally have the equation that
$$w_0= \dfrac{P_s}{P_0-P_s} \cdot 0.622 $$
$$w_0= \dfrac{A\cdot e^{-B/T_d}}{P_0-A\cdot e^{-B/T_d}} \cdot 0.622 $$
You can get $T_d$ from here.
The constants are
$A\simeq 2.53\cdot 10^9 mbar$; $B\simeq 5240 K$.


Circuit with voltage source, resistance and current source

Question: Suppose I have a (closed) circuit with a voltage source $V$, a resistance $R$ and a current source $I$ (in this order).
Is it true that the voltage across the current source is $V-RI$ ?
Comment: Although not stated, I assume you mean the circuit elements are series connected and then the answer depends on one's choice of reference polarity (for each voltage variable) and reference direction (for the series current variable).  In other words, draw a circuit diagram appropriately labeled.
Comment: Could you provide the values (just out of curiousity)?
Comment: I don't have any values
Comment: yes is true, is all you wanted to know?
Comment: Could also be V+RI, it depends on the direction of the voltage source and the current.
Answer: Your source voltage is a pressure of electrical charge, with a degree of resistance (obstruction) somewhere in-between zero and infinity, towards a lesser pressure of electrical charge.  If the source pressure is not kept constant, by electrical input to the source, then this source pressure will diminish for as long as your current is kept constant.  So any pressure released into the circuit will be maintained magnetically in the circuit itself, voltage loss being released in far greater maginitude at your current source.  In a given span of time, voltage loss is far greater than the magnetic force because I (current) is measured--in time. Constant Voltage / R = I.  Since V = IR, V across the supply circuit itself will equal the total pressure in the closed circuit minus the magnetic force between the voltage source and the point of supply.   So in reality, the voltage (electrical pressure) in your current source is maintained only in the magnetic force, which is in addition to your constant source voltage.   If a finger (God forbid) or something shorts the circuit, the source voltage will be imposed on, but the magnetic flux in the circuit is maintained.  The bases I'm using are books studied over time, one in particular titled simply, "Electricity," whose subtitle and author's name elude me at the moment, and some others including an elementary college physics course.


Can you create an Mac OS X Service with Python? How?

Question: Can you create an Mac OS X Service with Python? How ?
What I want to do is to know hook my Python-fu to the service system provided by Mac OS X.
Anyone knows how? If yes any working code snippet? Will work only on text or also on a given mimetype - defined object?
Answer:
Open Automator.app and create a new service.
Select "Utilities" from the left-hand actions list, then drag the "Run Shell Script" action into the workflow.
Choose /usr/bin/python as your shell.
Type some python.  For example:

:
import sys

for f in sys.stdin:
     print "Hello World: " + f,

Save the service as, say, "Test"
Try it out in TextEdit.app.  Type some text, select the text, then choose TextEdit -> Services -> Test from the menu.  It should prepend "Hello World: " to each line of the text (as per the python code for f in sys.stdin)

The above example works with text.  Presumably, it could be modified to work with other data types provided through the OS X Services system.
Comment: You need to select "Replaces selected text" checkbox for this to work. It will also only do one "Hello World"; not one for each line. You would need to break up `sys.stdin` to its component lines to return each line.
Comment: and where is "Replaces selected text" checkbox is located?
Comment: can this be exported to an application (ie downloadable .app)?
Answer: One way to build an OS X service using Python is to bundle your Python app with py2app and edit the Info.plist file to provide the menu entries you need in the Service menu.
A sample plist file can be found at https://pyobjc.readthedocs.io/en/latest/examples/Cocoa/AppKit/SimpleService/index.html
You need to build the functionality to accept the commands you defined in the Info.plist's NSMessage section (see link mentioned above). You can use PyObjC to do this.
This is a little bit trickier than using Automator, but has the advantage that you can bundle the whole functionality into a single App.
Answer: How to implement - I would say that there are three possibilities:

You could use the Automator and create a service from a run shell script action.
You could write an Automator action yourself using Xcode and use this in the Automator and create a new service out of it. The benefit would be that you could write an UI for it. You use bindings to bind it to the file's owner object. The binding keys are then reflected in the script as environment variables.
Create a stand-alone service or a service going along with an application. I have implemented one included in the application. There you can also define a separate UI just for the service.

Input types - If you want to define the service to only show up if certain things are selected, such as text or URLs, you would define this in the Info.plist of that service.  I think it should be possible to edit the Info.plist that was generated by the Automator if you want to further customize it.

Apple's Services Implementation Guide has a great example of debugging a service using TextEdit. It gives great help for debugging why a service is not showing up in the menu. See the Providing a Service | Testing section of the docs.
Comment: I can confirm that you can edit the Info.plist of the .workflow bundle (service) created by Automator.app. In fact, it is necessary if you want to rename the service's menu item.
Answer: I found this page when I was trying to make python service. I wanted to share my complete solution to save others a little time and maybe get some feedback from more experienced coders. I used System Preference>Keyboard:Keybindings to set an "Application Sortcut:All Apps" for this service so I can execute the selected text anywhere in the system using command-shift-return. You will notice that any Exceptions will cause the selection to be replaced with the original text. Works with UNDO if you didn't get the result you were after. So far, I like it a lot!
Create an automator workflow as a service, service receives selected text in any application, input is entire selection, output replaces selected text
Add a run shell script action, shell: /usr/bin/python  pass input: as arguments
This code goes in the box:
import sys #, random
try:
    print eval(' '.join(sys.argv[1:]))
except:
try:
        #This is a compound statement using variable assignment
        code = compile(' '.join(sys.argv[1:]), '<string>', 'exec')
        exec code

    except:
    print ' '.join(sys.argv[1:])

These are a few samples of how I might use this service. Again, this works in Mail, word processors and other apps.
Sample 0: Basic Math
>>> 42*24*60*60
3628800

Sample 1: Single line, compound statement
>>> import random; foo = range(17); random.shuffle(foo); print(foo)
[11, 14, 12, 3, 1, 4, 15, 7, 8, 13, 2, 16, 0, 10, 9, 6, 5]

Sample 2: Multiline
>>> import random
>>> foo = range(17)
>>> random.shuffle(foo)
>>> print(foo)
[5, 16, 14, 10, 3, 11, 7, 15, 12, 0, 13, 2, 4, 1, 6, 9, 8]

Sample 3: Loops
>>> for x in range(5):
...     print x
...
0
1
2
3
4


iOS MapKit Showing Many Places From File

Question: Im relatively new to iOS development and have been asked to make an app whereby I can place a load of pins on a map. I have been given an csv file with the lat, long, an identifier and some info for each of the places I need to plot but I'm not sure as to the best way to go from here. Any help is very appreciated!!
Answer: My Advise is to divide your task:
1 - Create a class to hold your coordinates and other useful information (name of the place, phone number, etc)
2- Create a parser, so you can parse your CSV file.
3- Add your data to your map.
Use the following links to help you out:

Import csv data (SDK iphone)
http://blog.objectgraph.com/index.php/2009/04/03/iphone-sdk-30-playing-with-map-kit-part-2/

Since you are new to this, take your time understanding what's going on. There are no shortcuts when learning. If you need more help, use my email so I can assist you.


How do I state why I am doing something?

Question: How can I say: "I am studying Japanese because I am going to Japan in October". The closest I have come is: "十月に日本に行きので日本語を勉強しています". But this sounds a little clumsy so I was wondering if there was a better (or different) way to express my reason than using ので and the nuances of this word (subtext; is it formal or casual, does it carry any implications?).
Comment: It should be 行**く**ので, not 行きので.
Comment: Or 行きます to sound a little more formal.
Answer: The correct (or one of the correct) answers would be 「十月に日本に行くので日本語を勉強しています。」Just replace 「行き」with 「行く」。「行く」in this sense translates to "am going"/"will go". Replacing 「ので」with 「から」also works in an informal sense - 「ので」is more formal than 「から」。


When is necessary integrate Apache httpd with apache tomcat (mod_jk)?

Question: Apache sites, recommend the integration of httpd and tomcat(mod_jk). The first for static and the second for dynamic content. What about the case that the entire page is dynamic. Does it still make sense to integrate both servers? What would be the advantages?
Answer:
It allows you to use the other features of HTTPd (e.g. rewriting via mod_rewrite).
It allows you to run Tomcat as non-root, preventing privilege violations.
Comment: There is no requirement to run Tomcat as root, so #2 is not really a good reason to use Apache httpd.
Comment: Other good reasons to use httpd/mod_jk:

1. load-balancing across multiple Tomcat backends
2. deploying webapps to different Tomcats/JVMs and still accessing them from the same port
3. offering a heterogeneous service environment: Tomcat for some webapps, PHP/Perl/CGI for others, since httpd is better for those


I need help with a Minecraft jukebox

Question: I like listening to music in Minecraft, so I was collecting music records from the creative menu. I put "blocks" into the jukebox, and no sound played. I waited, and nothing. I thought it might just be that one disc, so I tried listening to "cat" which I had heard earlier. Again, nothing happened. I tried turning up my jukebox/noteblock sound setting, but still nothing. I know it's not my computer, so what is it?!
Comment: Minecraft's sound engine a lot of times glitches out. Try restarting.
Answer: I also used to have this problem in my survival but when I restarted the game and tried again it was working sftlr though and I hope it works
Answer: I know you said you turned up the sound, but check one more time, make sure your main volume is also turned up. :)
Make sure your computer's sound is turned up too. Check your headphone jack to see if the sound is going into unused headphones also.
If none of that works, try restarting your minecraft window, and then your computer if that does not work. Good luck!

I need help with a Minecraft jukebox


Transfering data between Lua scripts and Java application with LuaJava

Question: I've read many great things about LuaJava (library). However, I still can't find any good documentation on how to transfer data between the Lua scripts and Java application. How is this done? I apologize if I missed a tutorial somewhere...
Answer: There's a reference manual here: http://www.keplerproject.org/luajava/manual.html.
The Java documentation is at the bottom.
Here's an example (although it might be a bit out-dated): http://lua-users.org/lists/lua-l/2003-12/msg00286.html
You might want to start with understanding the C interface to Lua. The LuaJava interface is built on that. The basic idea is that you have a stack and you first push the function, followed by arguments, and then you can execute a function in Lua. The results are then pushed on the stack and you can get data back from Lua that way.


1/4" Hardibacker cement fiber board for shower walls

Question: I'm preparing to lay tile in my new bathroom and I picked up the cement board but when I got home I realized I bought quarter inch instead of half inch thick sheets. The Hardibacker website says that you can use quarter inch but a lot of websites that I've looked at recommends half inch for the walls. Has anybody use quarter inch cement board for shower walls with large tile with good results?
another question I have is what is the preferred method for laying tile on concrete slab floor? Should I use cement board or the rubber mat uncoupling style? Any experiences are appreciated
Answer: 1/4" hardibacker alone is an unsuitable substrate for shower wall tile. If it were attached to properly waterproofed drywall, plywood, or plaster it would be fine. Think about it, one wayward elbow, knee, or hip bump and you may get flexion which would cause the grout (or tile) to crack.

what is the preferred method for laying tile on concrete slab floor?

It depends on the application. Concrete is porous, so for water applications (like a shower floor) there are specific established methods for waterproofing, sloping, and draining.
For dry area applications, concrete is the perfect tile substrate as long as it is clean and dry. Just apply thinset mortar using the application technique recommended by the mortar (and/or tile) manufacturer.
Comment: Cool, so would I still need plywood if I exchanged the quarter inch for half inch Hardy board? I just built a standard shower enclosure 60" long with 2x4s.
Comment: Nope, no plywood needed behind 1/2"! I always staple waterproof craft paper to the studs, arrayed horizontally starting at the bottom with successive runs overlapping the run below and with the bottom (first run) lapping out under the tileboard into the pan (picture if water were to penetrate and how the paper would allow that water to run down the paper and out into the pan). Tileboard goes over that.
Answer: If you're looking for the proper way to tile a shower, including pre-slope, pan, etc. take a look at this guy's YouTube channel.  It made me realize that building a tile shower takes a little more than just throwing up some Hardibacker and tile.
https://www.youtube.com/user/saldibs/playlists
Comment: That's funny you posted that,I was actually watching his channel about the tiling fails that led me to asking about the cement board. These guys are good.
Answer: I install 1/4" HB all the time right on top of 1/4" drywall.   Easiest way to do a tub surround.


How does corrosion occur at a temperature below 0 degrees Celsius?

Question: The ISO 9223 standard indicates that there should be no corrosion at temperatures below 0 degrees celsius. Independent researchers have however proposed to lower the minimun temperature stated in the standard to lower values in order to account for the actual corrosion observed in Nordic climates. What is the explanation for the observed corrosion at temperatures below the freezing point?
Comment: Well, for one thing, 0 C is the freezing point of pure water.  Adding salt (as in seawater) or other impurities can significantly lower the freezing point (down to -21.1 C for a salt/water solution).
Comment: Do you have a reference for these other researchers who are proposing to lower the temperature at which corrosion occurs?
Comment: What sort of corrosion? What material is corroding and what is the mechanism? I'm not familiar with ISO 9223 off the top of my head; can you include some information from the standard to provide context for readers?
Answer: As Dan mentioned in the comments, the presence of salt (and other pollutants) can alter the freezing point of water.
The ISO 9223 abstract states:

key factors in the atmospheric corrosion of metals and alloys. These are the temperature-humidity complex, pollution by sulfur dioxide and airborne salinity.

All of which are factored into the "time of wetness", which can increase in the presence of salinity (and other pollutants, acknowledged in the ISO standard itself) as found in observations made in Antarctica published in Uhlig's Corrosion Handbook, (p. 330):

..that in the presence of marine salt, liquid water monolayers could form under ice layers resulting in high corrosion rates in temperatures well below 0C

Sulfur dioxide is also identified in the ISO abstract, this a common pollutant from vehicles, industry etc. which according to can chemically react with water vapour, forming sulfuric acid, the basis of acid rain and acid snow.


On linear operators and their complex qualities

Question: In the Principles of Quantum Mechanics, Dirac states that all linear operators $\alpha$ over our vector field (over the complex numbers) can be expressed as the sum of a real and an imaginary part $\alpha=\beta + i\gamma$ where $\beta$ is real (that is $\beta=\bar{\beta}$ (where $\bar{\alpha}$ is defined s.t. if $|A\rangle=\alpha|B\rangle$, $\langle A|=\langle B|\bar{\alpha}$)) and $\gamma$ is imaginary ($\gamma=-\bar{\gamma}$). Can somebody help me prove this?
Comment: More on Dirac's book on QM: http://physics.stackexchange.com/q/101437/2451
Answer: Observe that
$$ A = \frac{1}{2}(A + A^\dagger) + \frac{1}{2}(A - A^\dagger) $$
where the summands are Hermitian and anti-Hermitian as desired.
Comment: @Ivan: Oh, in your notation, $A^\dagger = \bar A$ and Hermitian/anti-Hermitian are the properties $A^\dagger = A$ and $A^\dagger = -A$.
Comment: I am sorry, what is $A^{\dagger}$ and hermitian and anti-hermitian?
Answer: By definition $$\alpha^*=\bar{\alpha}$$ and is called a complex conjugate so for the real part, the complex conjugate is itself while the imaginary part takes on the opposite sign.
To prove that
$$\langle A|=\langle B|\bar{\alpha}$$ first define this equation to be the complex transpose of
 $$|A\rangle=\alpha|B\rangle$$
For the complex number alpha, the complex transpose is simply the complex conjugate. The complex transpose is just the complex conjugate of the individual components of A and B as well as turning the row vectors to column vectors or the column vectors to row vectors, also called the transpose of the vectors. Hence the name complex transpose (Refer to wikipedia complex transpose).
  If we denote a complex transpose as * because I don't know how to make that t cross sign thing, then
$$\langle A|=|A\rangle^*=(\alpha|B\rangle)^*=\langle B|\bar{\alpha}$$
$$_{Q.E.D}$$
P.S
I don't know if this violates the rule on giving near complete or complete answers so if it does please tell me and I will either delete or edit this post.
Comment: The question is why all linear operators can be expressed as the sum of a real and an imaginary part, not what you are doing here.
Comment: Well then it is similar to how complex numbers can be expressed as a sum of real and imaginary parts. The operators can also be split into real and complex parts. Sorry I thought he meant to help prove whatever I wrote up there.


Connecting geocoded point to an identify function

Question: I am using the esri javascript api to make a web map. I need to use an address locator to geocode a point and then depending on where that point lands information populates a side panel. I am assuming you have to pass the coordinates to an identify function but I have no idea how to do this. Basically, I want the person to enter an address, it zooms to the address and information about the area populates the side panel. The information in the side panel would come from attributes from various polygon layers on the map. Any sample codes would be appreciated. Especially how to take the geocoded result and populate a identify function with the coordinates. (Or however this is handled) Thanks
Answer: This should get you started:
<code>  var loc = new esri.tasks.Locator("http://...");
  dojo.connect(loc, "onAddressToLocationsComplete", onGeocodeComplete);
  locator.addressToLocations(address,...);

  function onGeocodeComplete(candidates) {
    // You'll want to find the best candidate by looping
    // through all the candidates and not just selecting first
    var geom = candidates[0].location;

    var identify = new esri.tasks.IdentifyTask("http://...")
    var idParams = new esri.tasks.IdentifyParameters();
    // Set your ID parameters here

    identify.execute(idParams, onIdentifyComplete);
  }

  function onIdentifyComplete(idResults) {
    // Add your code here
  }
</code>
Comment: This is the general workflow but leaves out a key detail:  set the idParams.geometry property to the geometry from the best location returned by the geocoder. You would also probably want to specify a tolerance. One more thing:  I like to be consistent dojo.connect() to add callbacks or by supplying them as arguments to functions. Personally, I prefer the latter.
Comment: @Derek: He'll need to set up the rest of the idParams as well, such as current map extent, etc.  As for consistency, I pulled the code from two examples (instead of my head :p).  I almost never use dojo.connect, instead I pass the function parameters, but I'd definitely agree with keeping consistent.  At least this way he sees both methods :)
Comment: So I did as you suggested and tried to set it up using two esri examples, but I am still missing something. This is what I have so far. http://busstops.provo.org/address.html If I had a working example to see how it is done that would help out so much. Thanks
Comment: @Stan I see this error coming back from the service when your identify request is sent:  "'mapExtent' parameter not specified" Try specifying a mapExtent such as identifyParams.mapExtent = map.extent. I would also zoom to your point before setting up your identify params, not after.


Location of Big Bang

Question: Can I point to somewhere in the sky where the Big Bang happened? A pathway so to speak on where we (and our progenitor elements) came from?
Comment: There's no point in space where the Big Bang happened, because the Big Bang made space itself (and time).
Answer: There is no such unique point, because a key element of the Big Bang model is called the "cosmological principle," which means that every point in the universe is taken as essentially equivalent to any other.  The idea there is that as the universe ages, it changes, but it changes in the same ways everywhere so there is nothing going on that distinguishes one region from another.  This is a simplifying assumption that is supported by the fact that we see no boundary to the universe, and we see no evidence that anywhere else is different from here, the differences we see appear to be due only to the fact that we are seeing farthing into the past as we look farther away.  This assumption means you could pick any point you want, point to it, and say "the Big Bang started there," and you would be no more right nor wrong than if you pointed anywhere else.

Location of Big Bang


making a color ramp cycle back and forth

Question: i have a particle system hooked up to a color ramp so that the particles change color based their age. the only problem is once the reach a certain age they stay a certain color because the color ramp value becomes greater than 1. is there a math function to make the value progress back to 0 once it hits 1 and vice versa so the colors can continually cycle back and forth?
Answer: Sounds like you want a sine wave! Just multiply your incoming value by sin (with a multiplication node and sine node, respectively) and you'll get your oscillation of 0 to 1 and back again. There's some official documentation on just that use case here: https://docs.blender.org/manual/en/dev/compositing/types/converter/math.html#using-sine-function-to-pulsate
Then, add one 1, and divide the result by 2. This is a much smoother way of interpolating between 0 and 1 while avoiding negatives, as Rich Sedman suggested!
In other words, this set-up should go between your existing "Divide" and "ColorRamp" nodes:
Comment: Much better solution, edited to use that!
Comment: It would be good to provide an image of the nodes for your solution so people can see what you mean and how to replicate it. Also, instead of using Absolute to avoid negatives, how about add 1 (so it varies between 0 and 2 instead of -1 and 1)then divide the result by 2 - this way it will vary smoothly between 0 and 1.


Are collars and EPP augmentations permanent?

Question: Both EPP augmentations and collars are items that can be attached to existing items. I would like to know if the attachment process is permanent, and if it is not, then do we get the previous item back once we attach a new item?
Comment: I would test this out myself, but both collars and EPP augmentations are relatively rare for me at this stage of the game.
Answer: EPP augmentations are lost when you upgrade your EPP (e.g: from radiation to heating). Once you have applied an augmentation, there is no way to get it back as an item; applying a new augmentation will overwrite it. The augmentation will stay on the EPP until you either upgrade the EPP or apply a new augmentation.
Pet collars work similarly, in that they will stay on the pet until you apply a new one to overwrite it, with the difference that pets cannot be upgraded.
Sources: Here, here, and personal experience.


2001 Honda Civic lx 2 door over heating I even put a new thermostat in it when taking the old one out there was nothing wrong with it

Question: still keeps running hot it had been in the shop 4 times with it over heating and the mechanic said this Honda  makes it look like he knows nothing about cars.. but changed everything out on it.. the hand will go all the way up to the H also.. but sometimes when I stop at a red light it will go up but when I start to go it will go back down some..
Comment: Welcome to Motor Vehicle Maintenance & Repair! Unfortunately, I'd like to tell you it's probably the head gasket which is at fault. I have an '03 Civic LX with the D17A1 engine just like yours (well had, it now has a JDM D17A2 in it). As long as I kept the coolant up to level in the radiator, it wouldn't do what you're talking about. Drive it two days, level goes down, acts just like what you're saying. Two things: bleed the system correctly. Air in the system causes what you're describing. Second, head gasket was the only fix. This is a common issue for the D17A1 engine.
Comment: Now it did have a crack in the head but they fixed it
Comment: The motor is a 1. 7
Answer: Based on your description (happens at low speed with poor airflow), that typically means one of the following is happening:
1 - The radiator can't remove heat fast enough. That could mean a fan that is inop, or not moving enough air (I had an old Accord that had a partially working fan that would kick on, but would not provide sufficient airflow). Your civic should have two fans, are they both turning on? What happens if you cycle the air conditioner? It should force both fans on, even if the A/C system doesn't work.
2 - Insufficient coolant flow at low engine speeds. This would point to a restricted hose or bad water pump. It could also mean you are low on coolant.
3 - Related to #2, you might have air trapped in your coolant preventing sufficient heat exchange.
4 - Also related, if you have a bad radiator cap or have some other issue that prevents the system from building pressure, your coolant might be boiling. You are using a 50/50 mix of coolant, right? (using 100% water can cause corrosion and other problems, and using 100% coolant does not transfer heat as well.)
5 - You might have a mechanical problem that is causing your engine to expel too much heat. This could be something like running lean (makes the engine run hot), or a blown head gasket (directly forces hot gases into the coolant), or a cracked/warped head.
Some troubleshooting you can try:
A. Does turning the heater on help? This dumps some of the engine heat into the cabin.
B. Are you sure the coolant level is full, stable, and has been bled? If there's any question, get a pressure tester from Autozone (for free) and check for leaks. You can also check the plugs to see if you are burning coolant.
C. Does engine temperature rise at low vehicle speeds, or low engine speed? This helps narrow down if it's airflow related or coolant flow related.
D. Any check engine light or codes?
Answer: sounds like your fan isn't running.  It gets air flow when you are moving so it runs cooler.
Comment: The fans kicks on just fine so I know it not that just had fan switch put on it
Comment: was that "fan switch" put on before the problem or after?  If you have a new issue, always suspect whatever the last fix was.   Anyway, even if the fan switch is new, it still points to the fan not always being on.  I would thoroughly check connectors and grounding as an intermittent problem points to a loose wire.  To be thorough though, did you check your water level?  Probably the best check to do though would be put a thermometer in the water.  It may not actually be overheating.  You could simply have a bad temp sending unit.


nanomaterials, metal oxide nanoparticles

Question: Why do the properties really change to an extreme level when they are made into nano size?
I was wondering why the metal oxides become highly porous when they turn into nano in size.
Comment: If these are two different questions, I suggest splitting them.
Answer: Band gap pictures indeed vary tremendously with the size of the particle. Usual band gap computations of bulk materials rely on the Bloch's theorem, or on the nearly free electron approximation. These approximations work best when the bulk material is infinite, and break as long as it is sufficiently small.
For example, quantum dots have wide optical spectra because their band gaps are controlled by the particle size. An intuituve understanding of this fact may come as follows: electrons in the quantum dots are trapped in a small piece of the material (they can't go outside), so it's a lot like a particle in a 3D box. Indeed, the rough dependence of the band gap width on the size of the particle follows a $\sim L^{-2}$ law of the particle-in-a-box model.

Quantum confinement effect on the band gap of a quantum dot. By Jpailee (Own work) CC BY-SA 3.0, via Wikimedia Commons
Another example, with less intuitive explanations, can be graphene nanoribbons.

Band diagrams of graphene nanoribbons, Stan et al, 2009
Again, the wavefunctions of electrons in nanoribbons cannot be conventional Bloch waves; they are limited by the finite width of the nanoribbons, and the electron momentum is quantized in the transverse direction. Exact calculations are best done numerically. In general word, the presence of the edge changes the band diagram, because electrons can now propagate along the edge of the ribbon; new available states are introduced to the band diagram.


window.onbeforeunload - Only show warning when not submitting form

Question: I am using window.onbeforeunload to prevent the user from navigating away after changing values on a form. This is working fine, except it also shows the warning when the user submits the form (not desired).
How can I do this without showing the warning when the form submits?
Current code:
var formHasChanged = false;

$(document).on('change', 'form.confirm-navigation-form input, form.confirm-navigation-form select, form.confirm-navigation-form textarea', function (e) {
    formHasChanged = true;
});

$(document).ready(function () {
    window.onbeforeunload = function (e) {
        if (formHasChanged) {
            var message = "You have not saved your changes.", e = e || window.event;
            if (e) {
                e.returnValue = message;
            }
            return message;
        }
    }
});

Answer: Using the form's submit event to set a flag might work for you.
 var formHasChanged = false;
 var submitted = false;

$(document).on('change', 'form.confirm-navigation-form input, form.confirm-navigation-form select, form.confirm-navigation-form textarea', function (e) {
    formHasChanged = true;
});

$(document).ready(function () {
    window.onbeforeunload = function (e) {
        if (formHasChanged && !submitted) {
            var message = "You have not saved your changes.", e = e || window.event;
            if (e) {
                e.returnValue = message;
            }
            return message;
        }
    }
 $("form").submit(function() {
     submitted = true;
     });
});

Comment: I accepted this over @Derek's because I already had custom submit code and needed to check the two values separately.
Comment: I was using 1 variable before that, but it sometime works sometime not. Your solution working fine with 2 variables. Thanks
Answer: you could use .on() to bind onbeforeunload and then use .off() to unbind it in form submission
$(document).ready(function () {
    // Warning
    $(window).on('beforeunload', function(){
        return "Any changes will be lost";
    });

    // Form Submit
    $(document).on("submit", "form", function(event){
        // disable warning
        $(window).off('beforeunload');
    });
}

Answer: You can handle the submit() event, which will occur only for your form submission.
Within that event, set your flag variable formHasChanged to false to allow the unload to proceed. Also, just a suggestion, but since the purpose of that flag variable will have changed, so you may want to rename it something like 'warnBeforeUnload'
$(document).submit(function(){
    warnBeforeUnload = false;
});

Answer: I was looking for a better solution to this. What we want is simply exclude one or more triggers from creating our "Are you sure?" dialog box. So we shouldn't create more and more workarounds for more and more side effects. What if the form is submitted without a click event of the submit button? What if our click-handler removes the isDirty status but then the form-submit is otherwise blocked afterwards? Sure we can change the behaviour of our triggers, but the right place would be the logic handling the dialog. Binding to the form's submit event instead of binding to the submit button's click event is an advantage of the answers in this thread above some others i saw before, but this IMHO just fixes the wrong approach.
After some digging in the event object of the onbeforeunload event I found the .target.activeElement property, which holds the element, which triggered the event originally. So, yay, it is the button or link or whatever we clicked (or nothing at all, if the browser itself navigated away). Our "Are you sure?" dialog logic then reduces itself to the following two components:

The isDirty handling of the form:
$('form.pleaseSave').on('change', function() {
  $(this).addClass('isDirty');
});

The "Are you sure?" dialog logic:
$(window).on('beforeunload', function(event) {
  // if form is dirty and trigger doesn't have a ignorePleaseSave class
  if ($('form.pleaseSave').hasClass('isDirty')
      && !$(event.target.activeElement).hasClass('ignorePleaseSave')) {
    return "Are you sure?"
  }
  // special hint: returning nothing doesn't summon a dialog box
});

It's simply as that. No workarounds needed. Just give the triggers (submit and other action buttons) an ignorePleaseSave class and the form we want to get the dialog applied to a pleaseSave class. All other reasons for unloading the page then summons our "Are you sure?" dialog.
P.S. I am using jQuery here, but I think the .target.activeElement property is also available in plain JavaScript.
Comment: This appears to be browser specific. Works well in Chrome but the target in Firefox is always `body`
Comment: Just tested in Firefox 40, event.target.activeElement gives in fact the clocked element, as it does in Chrome. My solution works well in both browsers for me.
Comment: I like this approach but I couldn't get it to work in IE. But ignoring the event completely and using document.activeElement did the trick for me (only tested in Chrome and IE so far)


Using automotive R134A in my refrigerator?

Question: Can I use automotive R134A in my refrigerator without damaging anything?
Answer: The only difference is the thread on the automotive is different, they made the change to prevent shop mechanics from using the wrong type of Freon. Both auto and hvac r134 are chemically the same. I can usually find the automotive 134 a bit cheaper but legally it requires a licence. This sounds crazy when you think that air horns, freeze spray and canned air dusters are r134 but to put in an AC system it requires a license where all those other uses just dump Freon in the atmosphere but that is the law.


GetListItems in Visual Studio Workflow for SharePoint 2013

Question: I know there is a LookupListItem activity in Visual Studio Workflow for SharePoint 2013. Is there a GetListItems activity, which will return multiple list items based on a filter condition similar to GetListItems method in OM?
Answer: Out of the box, SharePoint doesn't have such functionality. I would suggest trying to use 3rd party product Plumsail Workflow Actions Pack it has Get Items by Query workflow action which allows you to this.
I'm one of the developers of the product and I'm proud of this.
PS: Alternatively you always can make REST query to select an items.


K-NN optimal value of 'K'

Question:
How can I find the optimal value of 'K' in K-NN using the cross_val_score function, with scoring metric as auc_score?
Do I need to plot AUC score vs k on both train & cross-validation data?
Answer: $k$ in $k$-NN is a hyperparameter to tune. You can try rules of thumb, like $k=\sqrt{n}$, where $n$ is a sample size, but better plot $k$ vs error metric as computed on validation set. The choice of the metric will depend on your needs, it can be any metric, or combination of metrics, that is appropriate for your problem (e.g. precision, recall, AUC).
Since it is quite primitive algorithm, that simply does majority votes (or averages in $k$-NN regression) given the nearest neighbors, it will overfit with smaller values of $k$, so this is something you should consider. On another hand, plotting training set error in here would show you exactly this relation and would lead to pretty obvious conclusions, so while people usually plot it, it isn't that helpful as with more advanced algorithms.
Comment: If a KNN classifier returns the most highly-voted class rather than a score, wouldn't it be the case that an ROC curve doesn't exist (so no AUC)?
Comment: @user20160 you can calculate fraction of each class among the $k$ nearest neighbors and you'd have the score (same thing happens in decision trees). But I'm not the greatest fan of AUC/ROC, so I probably wouldn't use it either.
Comment: That seems good. I will try this.

K-NN optimal value of 'K'


Preimages of coprime ideals

Question: Assume $R,S$ are commutative rings, $f:R\to S$ is a surjective ring homomorphism and $I,J$ are coprime ideals in $S$. Must $f^{-1}(I)$ and $f^{-1}(J)$ be coprime in $R$?
Answer: Yes.
If $S=R/K$, then $I=I'/K$ and $J=J'/K$. If $I', J'$ are not coprime, then there is a prime ideal $P$ such that $I'+J'\subseteq P$, and thus $I+J\subseteq P/K$. (Note that $P\supseteq K$ since $I',J'\supseteq K$.)
Answer: Write $1=i+j$ with $i \in I, j \in J$. Find preimages $u,v$ in $f^{-1}(I)$ resp. $f^{-1}(J)$. Then $1 \equiv u+v \bmod \ker(f)$. Since $\ker(f) \subseteq f^{-1}(I)$, it follows that $1 \in f^{-1}(I) + f^{-1}(J)$.
(Notice that the proof by user26857 uses the existence of enough prime ideals, which is independent from ZF.)

Preimages of coprime ideals


Foreign name writing in Katakana

Question: I was trying to figure out how the name "Saoirse" (pronounced as /Sur-sha/) would be written in Katakana characters. I was just a bit confused, although I know that Katakana bases on the literal pronounciation of a foreign word (ex: a name). Can someone help me with this one? I just got a little confused on how it'd be written in Katakana, thank you!
Comment: Perhaps the following answers your question. https://ja.wikipedia.org/wiki/%E3%82%B7%E3%82%A2%E3%83%BC%E3%82%B7%E3%83%A3%E3%83%BB%E3%83%AD%E3%83%BC%E3%83%8A%E3%83%B3
Comment: I listened to someone pronounce this name and don't see how it should be written as シアーシァ. The "sur" part is pronounced the same as in "surface". Then it would be better written as サーシャ. If you don't like it to sound like Sasha, セアーシャ would sound closer than シアーシャ.
Answer: I recommend checking the Japanese Wikipedia page of a famous person with the same name whenever you're unsure about how to spell a foreign name. For example, Saoirse Ronan's JP Wiki page spells her name as シアーシャ. Here's the link: https://ja.wikipedia.org/wiki/%E3%82%B7%E3%82%A2%E3%83%BC%E3%82%B7%E3%83%A3%E3%83%BB%E3%83%AD%E3%83%BC%E3%83%8A%E3%83%B3

Foreign name writing in Katakana


The 'Golden Rule' Paraphrases 'Treaty of Beersheba.'

Question: In Genesis 21:22-24, Abimelek offers a treaty to
Abraham based on honesty and kindness. "Treat
us with the same kindness we treated you." In
Matthew 7:12, Jesus says "Do to others as you
want done to yourself." These verses are almost
identical, but they are not linked in any bible.
Why?
Comment: "Hermeneutics" is "the branch of knowledge that deals with interpretation, especially of the Bible or literary texts." Your question, while very interesting does not relate to hermeneutics. (-1)
Answer: In the vast majority of cases when Old Testament Scriptures are recalled in the New Testament, it is the Greek (Septuagint) version and not the Hebrew that is recalled.  The Septuagint version reads (in Brenton's translation):

Now therefore swear to me by God that thou wilt not injure me, nor my seed, nor my name, but according to the righteousness which I have
  performed with thee thou shalt deal with me, and with the land in
  which thou hast sojourned.
Greek - κατὰ τὴν δικαιοσύνην, ἣν ἐποίησα μετὰ σοῦ, ποιήσεις μετ' ἐμοῦ

whereas the reader of the Greek version of Matthew reads:

Therefore all things whatsoever ye would that men should do to you, do ye even so to them: for this is the law and the prophets.
Πάντα οὖν ὅσα ἂν θέλητε ἵνα ποιῶσιν ὑμῖν οἱ ἄνθρωποι, οὕτως καὶ ὑμεῖς
  ποιεῖτε αὐτοῖς·

Given the difference in Greek phrasing, a reader would not have immediately recognized any parallel with Genesis 21:22-24.  Furthermore, Abimelech's request of Abraham is a request that Abraham do no harm to him in the future, more or less out of fear - a much different sense than the precept Jesus taught.
All that having been said, I think your point is interesting.  One might see in Abimelech's request out of fear that he be treated fairly a foreshadowing of Jesus' more perfect teaching of treating others fairly out of love.


How to display entire list as dropdown menu

Question: I am using SharePoint Online. I have a site with 2 basic lists. I am now creating a sort of "portal" page for users of the site to get information from the lists. Instead of displaying the entire lists on the portal page, i want each list to be displayed as a dropdown menu. If a user selects an item in the dropdown list, then it should then display that item from that list.  This will be for displaying information only - no editing would be done via the portal.  Is there any way to do this either OOB or via SPD (i am not a developer).
Answer: Unfortunately your requirement need to be done by coding so there is no way to get lists and insert them in dropdown and get listitems from specified list without code.


Packaging ActiveX Controls with Wix MSI

Question: I need to create MSI using Wix. My application has Active X control. When any user gets connected or visit the URL on the web my application needs to be installed in the user machine.
The path where I need to install is C:\Windows\Downloaded Program Files\CONFLICT.xx and this folder should contain the file ATL80.dll, app.dll, MSVCP80.dll MSVCR80.dll.
I saw few articles but got confused with them. please let me know how to start for this and what steps i need to follow in order to make MSI.
Comment: Please show us what you did.  Show some effort
Comment: Would you mind adding a comment to illustrate the solution you came up with?
Comment: I followed exactly the instruction given in the below comment by Glytzhkof. And it worked.
Answer: There is more to this: Packaging ActiveX Controls.
Essentially a web page will request a signed cab to be downloaded and installed via a CODEBASE URL, like this:
(sample from the Microsoft article linked above)
<OBJECT CLASSID="clsid:dcf0768D-ba7a-101a-b57a-0000c0c3ed5f"
    CODEBASE="http://webserver/time.cab"
    ALIGN="CENTER" WIDTH=270 HEIGHT=26 ID="T1"><PARAM NAME="Interval" VALUE=1000>
    <PARAM NAME="Enabled" VALUE=1></OBJECT>

The requested cab is downloaded (time.cab), and installed (standard Microsoft cab installation / extraction). The next time the web page is opened the Active X control should work as expected. That's the normal case (admin rights are required for this to work). A successful install here can be captured and packaged as an MSI. Heavy cleanup is required though, due to all the certificates that are involved to complete the install. None of the certificates are required in the MSI as I recall, since an MSI runs with admin / elevated rights and dump files straight in the folder. Quite a security problem if you ask me, but these cabs are rarely deployed this way. Unsigned cab files won't work though (unless IE is customized).
The CONFLICT folder that is created in this users case indicates that there are discrepancies between the installed files from the cab and the version of those files specified and expected by the web page. This causes IE to trigger a new CAB download. Upon discovering the same files already exist in C:\Windows\Downloaded Program Files\ a new CONFLICT sub folder is created each time, and the user gets prompted for a new Active X installation every time the page is opened.
You must work to resolve the file versions specified by the web page and the versions of the files found in the cab. These versions must match. I can't recall all the details, but it might be that all that is checked is the CAB file version:
(Sample from this Microsoft article)
<object id="CommonDialog1" width="32" HEIGHT="32"
    classid="CLSID:F9043C85-F6F2-101A-A3C9-08002B2F49FB"
    codebase="http://activex.microsoft.com/controls/vb5/comdlg32.cab
    #Version=1,0,0,0">
</object>

Comment: Thank you for such a nice and explanation.It gave me basic idea for proceeding ahead.
Answer: This is really a question about the Visual C++ redistributables because ActiveX controls installed from a web page don't need installing with an MSI. If that's all you're doing then the short answer is that you get hold of the VC 2005 redistributable and run it, this kind of thing:
http://www.microsoft.com/en-us/download/details.aspx?id=3387
This installs the C++ support files like ATL80.dll etc in the right places and it just works. You don't get much say in where they go:
http://msdn.microsoft.com/en-us/library/ms235316(v=vs.80).aspx
It's dangerous to have your private versions of those Dlls because there are security fixes for them, and if you have a private copy that the MS security updates can't find and fix then you effectively become responsible for maintaining them on the client systems.
On the other hand, I can't be sure from your question if you have a separate MSI file with a lot of other stuff in it (not the ActiveX) that you want to install by having people download it.
Comment: In addition to the runtime issues, it's the quirky world of Active X cab deployment via web pages: [Packaging ActiveX Controls](http://msdn.microsoft.com/en-us/library/aa751974(v=vs.85).aspx). See my answer, it might lack some details.
Comment: I'm aware of that, but the point is that there seem to be no WiX or MSI issues here at all, and the question seems to be about getting the VC++ runtimes onto the system. It's not obviously clear, but I think maybe he knows how to package AX controls in a web page and just needs the VC_++ runtime on the system. An update to the question might resolve that question.
Comment: The CONFLICT folder only shows up when something is wrong in the cab installation. He should try to capture this install instead of using Wix.
Comment: Just to wrap this up (I came across this again today): ActiveX installs can be captured and redistributed as an MSI in order to avoid all users having to install the ActiveX control manually with admin rights. I have done this several times, and know that it works (unless the handling of ActiveX installations changes in the web-browser). Effectively the signed ActiveX is verified on first launch / install and installation proceeds if you have admin rights. If you capture this process and the web page asks for the version of the file you install, all prompts disappear and the control is loaded.

Packaging ActiveX Controls with Wix MSI


Is there a curve for which a particle restricted to move within it under the gravitational force will always exhibit a pure harmonic motion?

Question: A simple pendulum, for example, is not  isochronous  for large amplitudes (that is, the frequency will depend on the amplitude). So a particle confined in a circumference will not always exhibit a pure harmonic motion.
Is there a curve for which the frequency will always be independent of the amplitude?
Comment: If memory serves me right the catenary has this property. I'll will try to find a source or a derevation
Comment: Sorry - a cycloid not a catenary. Here is the relevant [wikipedia](http://en.wikipedia.org/wiki/Tautochrone_curve) page
Answer: If you built a surface such that its height was proportional to a horizontal coordinate $x^2$, $h = k x^2$, then the potential energy at point x would be $mgh = m g k x^2$, which is a harmonic potential. In other words: yes, the curve exists and it's a parabola. This assumes uniform $g$, though, I guess if you want to be a stickler you could note that if the parabola were really big then that assumption wouldn't hold.


Calling Webservice in iPhone application?

Question: I am using soap webservice.
In that i am calling one webmethod. Here if i call  from one part of my code is working fine and calling service successfully and retriving data successfully.
But if i calling same method from another part of code of same class is not responding and not getting any data from service. Why is going like that can any one help me please.
Thanks in advance
In detail.m
<code>-(void) downloadAndParse:(NSMutableURLRequest *)sentReq  {

    conn =  [[NSURLConnection alloc] initWithRequest:sentReq delegate:self];

    if (conn) {
        webData = [[NSMutableData data] retain];
    }
}

-(void)fullBarcodeSearch:(NSString *)code {

    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
    URLRequest *r  = [[URLRequest alloc] init];

    NSMutableURLRequest *req = [r fullBarcodeSearch:code];
    [r release];
    [self downloadAndParse:req];

}
</code>
In URLRequest.m
<code>-(NSMutableURLRequest *) addHeaderToSoapXML:(NSString *) soapMsg {

    NSURL *url = [NSURL URLWithString:str];

    NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
    NSString *msgLength = [NSString stringWithFormat:@"%d",[soapMsg length]];
    [req addValue:@"text/xml; charset=utf-8" forHTTPHeaderField:@"content-type"];
    [req addValue:msgLength forHTTPHeaderField:@"Content-Length"];
    [req setHTTPMethod:@"POST"];
    [req setHTTPBody:[soapMsg dataUsingEncoding:NSUTF8StringEncoding]];
    return req;
}
</code>
if service not called then i am getting error like this
*oid _WebThreadLockFromAnyThread(bool), 0x6958130: Obtaining the web lock from a thread other than the main thread or the web thread. UIKit should not be called from a secondary thread.*
Please any one help me
Thanks in advance
Answer: You need an NSURLConnection to execute the NSURLRequest. Lookup the Apple Docs on the class.
Something like:
<code>[urlConnection sendSynchronousRequest:urlRequest returningResponse: &urlResponse error:&error]
</code>
Comment: what shoud have to write in the place of response  &urlResponse
Comment: oid _WebThreadLockFromAnyThread(bool), 0x6958130: Obtaining the web lock from a thread other than the main thread or the web thread. UIKit should not be called from a secondary thread.
 i am getting error like this Please help me thanks in advance


Remove old bathroom faucet

Question: Help! I am trying to replace the old ugly faucets in my house,  which was built in 2003. Only I can't figure out how to remove the old faucet.  It does not look like what is shown in all of the online videos I've looked at.  I've unscrewed all I can see to unscrew,  but am stuck.  Anyone familiar with this, who knows what I can do? Pictures attached.
Comment: Have you removed the water spout?
Comment: Are you sure that round ring under the brass ring doesn't turn?  Any notches in it? Can you grab it with a pair of channelocks?
Comment: So, I finally did.  I figured out this is a 'bottom mounted faucet'. I had to put a 5.5mm allen wrench into the hole in the faucet to unscrew it. Now I an trying thi figure out how to remove the rusted c clips.  This is a horrible faucet design
Answer: I suspect that you need to:

remove all possible trim and rings from the top.
unscrew a hex set-screw from the underside (see blue arrow) that clamps the unit to the deck by pressing up against the "hold-down plate" (see yellow arrow).
once loose, the hold down plate will slide away from the faucet body, allowing the faucet body to drop out from the deck, striking you in the nose, eye, or lip/front tooth.

Remove old bathroom faucet


How does High mu metal block a magnetic field?

Question: Fran De Aquino suggested VLF currents would trigger a mass shift in high mu metal.  But my question is how is a magnetic field actually blocked in high permeability metal?
Comment: Not sure I understand your question, but if you make an _enclosure_ of mu-metal to shield something that you place within, the enclosure does not _block_ the magnetic field:  Instead, it _diverts_ the magnetic field.  The magnetic lines of force prefer to follow the highly permeable mu-metal instead of the free space that is enclosed within the box.  (http://www.mecamagnetic.com/mumetal/images/softmag3.gif)
Answer: Magnetic forces aren't "blocked" in high permeability metal, rather redirected through it. Mu metal in particular, is made up of a combination of nickel, iron, molybdenum, and various other assortments. These combinations, along with a process called annealing, make for a very permeable metal that allows the magnetic field lines able to pass through the mu metal easier than open air. As with most things in nature, the path of least resistance is always the chosen path. Hope that helps.


create a view with selected items

Question: i'd like creating a view with items selected when i click on a ribbon action.
I'm abble to have the selected items but i'd like to know if there are a way to put this items in a particular view.
Answer: if I understand you correctly, you want to create a view where only specific items from a list are shown?
if you can filter the item list according to specific entries this can easily be done in the view settings menu, or you can create an additional column and set that to a value that you can filter for, you don't even have to display that column in the view.
this created view can be made default or linked to in the menu so it can easily be accessed later on.
hope this helps :)

create a view with selected items


How to solve this Limit Algebraically?

Question: $\lim_{x\to\text{-}\infty} xe^x$. This is limit can be easily be seen that it approaches to 0 using graphs. But how to solve it algebraically?
Comment: Are you allowed to use that $te^{-t}\to 0$ as $t\to+\infty$? Or, what do you know about the exponential function?
Comment: Given that it is a transcendental function, and you are doing a limit, what do you mean "alegebraically"? And how is it linear? And what do you mean "behavior?" There are too many words in the title and many of them seem to have been arbitrarily chosen.
Comment: i used a graph to see the limit.
Answer: Elementary answer:
(I assume constantly that $x<0$.)
We can reformulate
$$
xe^x = x\cdot 2^x \cdot \big(\frac e2\big)^x.
$$
We know that $\lim_{x\to\ -\infty}\big(\frac e2\big)^x = 0$, as $\frac e2 > 1$ (we can use it, I suppose?), so it remains to show that $2^x x$ is bounded, which can be done, in fact, by induction.
Obviously, $2^x x < 0$. Also:
$$
2^x x \geq 2^{\lceil x\rceil}\! \lceil x\rceil  = -\frac n {2^n} > -1.
$$
where I set $n= -\lceil x \rceil$ and the inequality $n < 2^n$ can be proved by induction for every integer $n\geq 0$.
Of course, $2$ isn't in any way significant, anything in $(1,e)$ would do, but the induction proof of the inequality $n<2^n$ is quite standard, I think.
Note: you can also use the inequality $n^2 < e^n$ for every integer $n\geq 0$, also provable by induction, whence $x^2 e^x < 1$ for $x<0$ and, similarly to above:
$$
0 > x e^x = \frac 1x \cdot x^2 e^x > \frac 1x \stackrel{x\to -\infty}\longrightarrow 0.
$$
Comment: thank you. but L'hospital rule would suffice
Answer: You need to use L'Hospital's Rule. Start by writing $xe^x$ as $\frac{e^x}{1/x}$. See https://en.wikipedia.org/wiki/L%27H%C3%B4pital%27s_rule
Comment: It's correct, of course, but no need to use such a heavy machinery. See my answer.
Comment: tHank you . But the way L'hosputal rule is applied is different.
Comment: Opps, sorry. It should have been $\frac{x}{e^{-x}}$

How to solve this Limit Algebraically?


Question About Speed of a Stone Underwater

Question: Why does the speed of a stone dropped into a lake increase as it moves to the bottom of the lake?
Comment: Speed needn't be keep on increasing till the stone reaches the bottom. Speed first increases then becomes constant if net weight of falling stone is balanced by opposing drag force acting on the stone. It often happens in deep waters like deep river, deep pond, sea, ocean etc.
Comment: If it starts from rest, the speed would increase.
Comment: Why do you think the speed of a stone _does_ increase? I'm not saying it doesn't -- it does up to a point -- but what makes you so sure of it?
Comment: Why would a stone in water behave radically different from one in air? Fluids dynamics applies fluids, gases, and plasmas.
Answer: Short Answer
Gravity.
Slightly Longer Answer
There are (as usual) opposing forces acting on a falling stone. The two that are relevant here are gravity, which will pull the stone toward the bottom of the lake, and drag which will oppose whatever motion occurs. The higher the objects velocity, and the more viscous the surrounding fluid, the stronger the force of drag will be.
What might be confusing you is the fact that when a stone is falling through air, because air is not very dense, it does not apply much drag. So the force of gravity overwhelms the force of drag, so it accelerates downward very fast, until the type of fluid surrounding it suddenly switches as it collides with the surface of the water. Once it is in water, it suddenly has a lot of drag because it has a high velocity and a high viscosity fluid surrounding it. So the drag force is stronger, slowing it down. Once it slows down a bit, gravity becomes the stronger force and then it continues on its merry way to the bottom of the pool.
Comment: Then we have now a bigger question here: why the stone is not slowed down to its terminal velocity in water? Why it is slowed to lower velocity than it will eventually reach, once submerged?
Comment: @Christian 1. the stone can't accelerate if it is already at terminal velocity, so it must be slower.
Comment: @lvella: 1. why do you think it's slowed below terminal velocity? 2. maybe surface tension?
Comment: Maybe it doesn't accelerate if the speed in air already was faster than the terminal velocity in water. Who says it does? Did you do an experiment?
Comment: Surface tension could have an effect. I think it will be slowed to its terminal velocity once its submerged, and then I would expect it to maintain that velocity until it reaches the bottom.
Answer: When stone enters the water net weight (weight in air-buoyant force ) of stone tries to accelerate it. As the downward velocity increases an opposing viscous drag force also starts increasing which directly proportional to the square of velocity. Thus the stone will keep on accelerating till the opposing drag force will be sufficient enough to balance the net gravity force acting downward.  Therefore stone will achieve a maximum constant velocity called critical velocity where these two opposing forces equate & stone will move with that velocity to the bottom.
The thing to be noted is that upward buoyant force doesn't depend on the velocity of stone.
Comment: The buoyant force does however depend on the relative densities, and the density of the water at the bottom of the lake will be a tiny bit more than that at the surface, water being about ten times as compressible as stone, so if you were to drop it in the ocean it would have sped up to terminal velocity then slow down a bit as it's 2% more buoyant by the time it reaches the bottom. Without specifying the lake depth or type of rock, hard to say whether it reaches terminal velocity or compression has any effect.
Comment: @htmlcoderexe: No , the buoyant force merely depends on the relative density & the submerged volume but not on the velocity of the object.
Comment: Isn't that terminal velocity?
Answer: These are the basics,
A force is either a push or a pull,
force causes acceleration,
acceleration causes a increases velocity(which is basically speed with direction)
Now,
Let's imagine you simply release a stone on the surface of water. i.e it starts its journey with zero velocity. Gravity applies force on it, which causes acceleration of stone downwards and the stone goes downwards with increasing velocity(If you think carefully this happens in air too).
But, the stone goes down slowly as compared to air.
This is because of the buoyant force which acts in a direction opposite to the force exerted by gravity. The buoyant force is increases with an increase in the volume of the solid on which it acts(Which is why it is difficult to push a beach into water than a football) . And the buoyant increases with an increase in density of the fluid(Which is why you can easily float on dead sea which is a lot more dense than the water in your swimming pool).
Now if Buoyant force greater than force exerted by gravity the body rises up else the body sinks.
The net force in case you drop a stone in water will be,
$$F_{net} = F_{gravity} - F_{buoyant}$$
In air the buoyant force is negligible due to the  low density of air(compared to water).
So, the net force in air is much greater than in water hence more acceleration in air and more velocity.
But we missed another thing,
which is the drag force
The drag force too acts in the direction opposite to gravity and further decreases the net downward force.
One interesting fact is that the drag force depends upon the velocity of the body(greater the velocity greater the drag force). As a body moves down due to acceleration its velocity continuously increases and thus the drag force increases. A point comes when the sum of drag force and buoyant becomes equal to the gravitational force that is,
$$F_{grav} - (F_{buoyant} + F_{drag}) = F_{net} = 0$$
As you can see the resultant force becomes zero,
Acceleration becomes zero then and velocity stops increasing and remains constant(leading to the drag force remaining constant too). And hence the body moves down with a constant velocity called the Terminal Velocity. At this point the body keeps moving downwards at constant speed until it hits bottom.
If you observe since air is also a fluid this happens in air too but the effects are less noticeable than in water.


Why do teeth decay of sugar?

Question: Sugars is a common component in diet of mammals. Why then their teeth did not develop resistence to sugar decay?
Answer: The reason for the decay are ever evolving bacteria, which happen to be very hard to overcome, even nowdays. There is a lot of research centered towards protein interactions, even mapping whole interactomes, which would help us get rid of decay, yet naturally our system wasn't able to evolve as fast as technological advances, but bacteria did.

Why do teeth decay of sugar?


Why, in a horizontal plane, is normal force equal and opposite to gravity even though they are not a reaction pair?

Question: I know that normal force and gravity are not a pair of forces, However, when an object is in equilibrium normal force and gravity are equal and opposite. Why is that? Is there any reason other than that they have to be in order for the system to be in equilibrium? Is there any other relationship between normal force and gravity?
Comment: Because they have to be for it to be in equilibrium?
Comment: What is a "pair of forces"?
Answer:
when an object is in equilibrium normal force and gravity are equal and opposite. Why is that?

That's not necessarily true. Consider a 500 N box resting  on the (horizontal) floor,(in equilibrium in an inertial reference frame) attached to a vertical rope with a tension of 100 N. The normal force the floor exerts on the box is only 400 N. And we know it's 400 N because the box is in vertical equilibrium, so that $$\Sigma F_{\mathrm{vertical}}= ma_{\mathrm{vertical}}=0.$$
And, yes, the normal force is taken to be whatever is needed for the observed net acceleration.
There is no specific, unique relationship between weight and the normal force.
Answer: This is a very primary question, really as you said, they are not action and reaction pairs, although they are same sometimes. When a box is on a horizontal table the vertical forces acting on the box are
* the Mg * Normal force by the table
As the equilibrium of the system they should be same to each. But you think that a situation which the box is pulling downwards when it on a table, then exactly the normal force and the Mg is not same due to the equilibrium.
Consider a situation which the box is on a inclined plane. Then you can understand it more....
Answer: The floor up on an object just hard enough to keep the object from penetrating the floor. That is, the floor pushes back just as hard as the object is pushed against it.
The object stays in contact with the floor, with vertical component of velocity $0$. This means the vertical component of acceleration is $0$, and the vertical component of force is $0$. The upward reaction force from the floor is the same as the downward force from gravity.
Answer: Honestly, the true answer to this question is that they are actually not equal in general. This is confusing, since in those first-year physics problem we indeed always say they are equal; but bear with me.
Let's think about this box on a table - indeed it doesn't move, so by Newton's first law the gravitational and normal forces have to be equal, as you said. Notice two things about this observation: first, it comes from the first law, not the third, and second and more importantly, it is an experimental observation - we know those two forces have to be equal simply because we know, from our everyday life and observation, that boxes stay on tables. So this is not a law of physics at all, and as such you shouldn't be able to derive it from Newton's third law (or from any law) - as you mentioned. It is at this point simply an experimental observation, which we generalize in order to help us solve physics problems.
Now let's imagine increasing the box's mass. At some point, the box will become so massive, that the table will break and the box will fall down. You see? This is again, a second experimental observation, and it tells us that our first proposition (that the normal force is equal to gravity) is false - these forces are not equal in general, which is how I began my answer. At some point there's a maximum normal force, and when it is passed, the forces are not equal anymore, and the table breaks. Thus we see that our first experimental observation is in fact not true, but it is true in some cases - that is to say, when the box is not too massive. In order to solve problems, we will usually assume this - that the box is light enough for the forces to be equal, and thus our experimental observation is true and can be used. But notice: it is still an experimental observation and not a law of nature, and it is only useful sometimes - in other cases, it falls apart.
Now, the analysis in the above paragraph is usually called a first-order model. If we now think more carefully about increasing the mass of the box gradually, we will see that actually, the table doesn't just break at one single critical point - instead, at some mass the box starts to distort the shape of the table, making it go down bit-by-bit; until at some point it can't support the stress anymore and breaks apart. We may try an experiment to see how the shape of the table changes with the mass of the box, and deduce the normal force from that. This would be a higher order model, but it is still an experimental observation.
So this is the annoying, but true, answer: the normal force is not, in general, equal to the gravitational force; they are only equal in some cases, and we can utilize that to solve problems and model the world around us. The fact that they're equal in those cases comes not from any law but from experiment; and thus you can't expect to derive it on the basis of Newton's third law. THe fact that they're equal doesn't have anything to do with Newton's third law and doesn't come from it, and it doesn't come from the first law, either - it's just that we use the first law (but definitely not the third) and our experimental observations, to deduce that they must be equal in the cases we see. But again, this is an experimental and not a theoretical result.
Of course, in the end, we do want physics to be complete, and thus we want to be able to show that the normal force is approximately equal to the gavitational force in those restricted cases, from our theory - from our known laws of physics. And inded the theoretical reaon for that is known - but it probably involves more physics than you're ready for at this level. I will give you a hint though: it has to do with the electrical repulsion between the nucleii of the atoms that make up the box, and the nucleii of the atoms that make up the table. In general, any force in our everyday lives, except gravity and bouyancy (and perhaps also the tidal force, depending on how you look at it) is electromagnetic in origin - that is, originates from electric (or magnetic) forces.


Dual of a projective module

Question: Let $R$ be a noncommutative ring with unit, let $P$ be a projective left $R$-module, and denote $^{\vee}\!P := \,_R\mathrm{Hom}(P,R)$. One often sees it written that projectivity implies an isomorphism
$$
\mathrm{ev}:\,^{\vee}\!P \otimes_R P \to R, ~~ \phi \otimes p \mapsto \phi(p).
$$
But I don't see that this is well defined! Consider
$$
(\phi.r) \otimes p \mapsto \phi.r(p) = (\phi(p))r
$$
where we have used the definition of the right $R$-module structure of $^{\vee}\!P$. Compare this with
$$
\phi \otimes (r.p) \mapsto \phi(r.p) = r \phi(p),
$$
where we have used the fact that $\phi$ is a left $R$-module map. Now since $R$ is not commutative, these two values are not guaranteed to be equal, and the evaluation map is not guaranteed to be well-defined. What is wrong here?
Comment: Sorry for my misunderstanding earlier.  Your question, and the answers below, seem to be connected to Exercise 2.20(4), in T.Y. Lam's "Lectures on Modules and Rings".  When $P$ is a f.g. projective left $R$-module, then $P^{\ast}\otimes_R P\cong {\rm End}(_RP)$.
Comment: Did you mean to say "morphism" instead of "isomorphism"?
Answer: You are right.  There is no such a map as the one you are trying to describe.
Here is a map that actually exists.  Let $R$ and $S$ be two noncommutative rings with units, and let $P$ be an $R$-$S$-bimodule.  Consider the $S$-$R$-bimodule $Q={}_R\mathrm{Hom}(P,R)$.  Then the evaluation is an $R$-$R$-bimodule map
$$
 \mathrm{ev}\colon P\otimes_S Q\to R, \qquad (p\otimes\phi)\mapsto \phi(p),
$$
with the tensor product taken over the ring $S$.
In particular, if you do not have an $R$-$S$-bimodule but only a left $R$-module $P$, you can take $S=\mathbb Z$.  Then you get an $R$-$R$-bimodule map
$$
 \mathrm{ev}\colon P\otimes_{\mathbb Z}Q \to R,
$$
with the tensor product taken over the ring integers.
Notice that the $S$-$R$-bimodule $Q$ is (generally speaking) very different from the $S$-$R$-bimodule $Q'=\mathrm{Hom}_S(P,S)$.  For the bimodule $Q'$, the evaluation is an $S$-$S$-bimodule map
$$
 \mathrm{ev}\colon Q'\otimes_R P\to S, \qquad (\psi\otimes p)\mapsto \psi(p).
$$
Comment: Thanks for the answer. But it seems that $Q \otimes_R P$ is well defined as a $\mathbb{Z}$-module. So is the issue here that $Q  = \,_R\mathrm{Hom}$ is really a "right dual" for $P$ and not a "left dual"? (Here I mean right and left dual in rough analogy with the monoidal category sense.)
Comment: I've added a paragraph at the end of the answer which is relevant to your question in the comment.  Yes, this is the difference between the left and right duals.
Comment: I think that clears it up - thanks!
Answer: Doc, you ain't write no evaluation map. If $R$ is commutative, you write the trace map. If $R$ is noncom, god knows what you write. The evaluation map, that is an isomorphism for a finitely generative projective generator and a homomorphism of $R$-$R$-bimodules, in general, is
$$
p \otimes \phi \mapsto \phi (p), \ P \otimes_{End_RP} P^{\vee} \rightarrow R \, .
$$
Use it with care.
In terms of Leonid's answer, you have a canonical $S:=End_RP$, lying around.
Comment: Taking $S$ to be the endomorphism ring of $P$ over $R$ is a good idea, but still the evaluation map is not an isomorphism for every finitely generated projective left $R$-module $P$ (not even in the commutative case).  Take $P=0$ to see that the evaluation map does not need to be an isomorphism for a finitely generated projective.  I guess the evaluation (with $S={}_R\mathrm{Hom}(P,P)^{\mathrm op}$) is an isomorphism when $P$ is a finitely generated projective generator of $R{-}Mod$.
Comment: A generator, which is finitely generated and projective. See https://en.wikipedia.org/wiki/Generator_(category_theory)
Comment: A projective left $R$-module $P$ is a generator of $R{-}Mod$ if and only if for every nonzero left $R$-module $M$ there exists a nonzero $R$-module morphism $P\to M$.  Equivalently, for every left $R$-module $M$ there exists a surjective left $R$-module morphism onto $M$ from a direct sum of sufficiently many copies of $P$. The general definition of what it means for an object of a category to be a generator is slightly more complicated; see e.g. the link above.
Comment: Right! I will add this condition
Comment: What is a "finitely generative projective generator "?

Dual of a projective module