How does PHP send data to Ajax?

Question: I've been studying PHP for a while now, and Ajax for about a month or two. I still can't figure out how does PHP send data to Ajax and how does Ajax retrieve the data.
Can anybody post an example or something?
Maybe After submitting some text.. PHP sends the data to the Database, but how would Ajax also receive it and post it to a specified field without refreshing?
If it helps, I use jQuery a lot, so i'd be using it with AJax too,
Comment: HTTP is a call and response protocol. When the client uses AJAX to send a request to the server, have your PHP output XML, JSON or HTML.
Comment: Here's a link to a simple example of this: http://www.w3schools.com/PHP/php_ajax_php.asp
Comment: When you make a call to a PHP page with Ajax, anything that is on the page is passed back to your Javascript via XMLHttpRequest.responseText.  Read an Ajax tutorial and it will explain everything to you.
Comment: I understand that, I still don't get it.
Comment: What exactly don't you get?  How the protocol works?  The concept behind Ajax?  How to use the programming interface?
Answer: It's actually a lot less complicated than you may think.  Think of AJAX as just requesting any old webpage, the trick being that it does it behind the scenes, "on the fly," without regard to anything in the URL bar of the browser.
In that sense, you're almost asking the wrong question (almost) because it doesn't matter (sort of) how PHP serves the page.  AJAX can request any page that's served up from PHP.  So, for example, say you have a simple PHP page that looks like this:
<?php
$content = '
content
';
echo $content;
?>

And you save the file as /content.html
From another page, you can load that content dynamically, using AJAX, and as jQuery is your preference, that might look like this:
$('#result').load('/content.html #content');

.load() is specific kind of AJAX function (there are several, the most basic being .ajax() I believe) that loads HTML content directly into a given page.  In this case, what's happening above is that when you call the .load() function, it loads via AJAX /content.html into memory, looks for the element called #content (which happens to be a div), then inserts that loaded #content element into the #result element.
Note, that the reason I'm saying "almost" and "sort of" above is that it will matter, depending on what you're doing, how you format your PHP page.  For example, it's common to request pages with AJAX that are formatted in either XML, JSON, or just plain old HTML snippets.  That is, of course, a much more dense subject, but here are a couple example tutorials:
http://www.xoops.org/modules/news/article.php?storyid=5103
http://www.factsandpeople.com/facts-mainmenu-5/26-html-and-javascript/89-jquery-ajax-json-and-php
http://www.phpriot.com/articles/php-json-jquery-ajax-screencast
Hope that at least helps.  There are A THOUSAND tutorials online, however, and simply searching on Google should yield plenty of results.
Comment: Thank you for a very detailed answer. I understand much better now
Answer: If you make an Ajax request to a PHP script,

Anything you echo in PHP will turn up in the Ajax request's response body. As @webbiedave says, that can be for example clear text, or XML, or HTML, or JSON encoded data.
Any status code you throw in the PHP script (e.g. header("HTTP/1.1 404 Not Found")) will be reflected in the Ajax result. If you throw a non-successful HTTP status code (e.g. 404 or 500) the Ajax request will fail, and (if you use jQuery's Ajax) the error callback will be called.
Answer: It just sends a request to the server like a browser, only in the background, without reloading. The received data is the content of the page. The same you would see if you'd open the url in the browser.
Comment: Yes. This. **Ajax is just another HTTP request.**

How does PHP send data to Ajax?


Zonal statistics 2 ends up causing a fatal error. Is there an alternative?

Question: I have recently switched to using the "zonal statistics as table- 2" supplemental tool instead of the regular "zonal statistics" because I have overlapping polygons which zonal statistics does not deal with. However, I have attempted running zonal statistics 2 a couple of times now and after running for many hours through the night it ends up encountering a fatal error and will not finish. I am not sure how to ameliorate this issue. I am trying to calculate mean elevation within over 100,000 buffer polygons, and will need to do this multiple times with other raster layers. Is there an alternative or a way to get the tool to complete the command?
Answer: To solve this you'll need to split your polygons into groups without overlap. It is called graph coloring.
To make script below work a)install networkx package and b)run:
<code>PolygonNeighbors("POLYGONS", "neighbours", area_overlap="AREA_OVERLAP")
</code>
Script:
<code>'''
creates non-adjacent groups of polygons
'''
import arcpy
import networkx as nx
infc = arcpy.GetParameterAsText(0)
table = arcpy.GetParameterAsText(1)

sourceList=[f.name for f in arcpy.ListFields(table)]
FTO=sourceList[1:3]
fromto=arcpy.da.TableToNumPyArray(table,FTO)
try:arcpy.AddField_management(infc, "COLOR","Short")
except:pass
G=nx.Graph()
G.add_edges_from(fromto)

allGroups=sorted(nx.connected_components(G), key = len, reverse=True)

arcpy.AddMessage("%i connected groups found" %len(allGroups))
D={}
for item in allGroups:
    arcpy.AddMessage(len(item))
    subG=G.subgraph(item)
    d = nx.coloring.greedy_color(subG, strategy=nx.coloring.strategy_largest_first)
    D.update(d)
    with arcpy.da.UpdateCursor(infc,("OID@","COLOR")) as cursor:
        for row in cursor:
            if row[0] not in item:continue
            row[1]=D[row[0]]+1
            cursor.updateRow(row)
arcpy.AddMessage("Done")
</code>
will add and populate field "COLOR" with numbers in range (1..4). This is theoretical range, expect something bigger, depending on extent of overlaps. I'd say the worst case scenario is 7 colors. You might hard code input feature class (infc) and adjacency table (table) if you don't want to assign script to tool with 2 parameters.
Note that script skips island polygons, this will result in None or 0 value in field COLOR depending on the source of feature class:

You have a couple of options on how to proceed:

manually define n layers from POLYGONS using definition queries,e.g. "COLOR" = 1, run zonal statistics on each. Merge results.
Write script or develop model to automate above tasks.

I suspect that this is exactly what zonal statistics 2 does behind the scenes, not sure why it's failing, unless you messed up processing extent and cell size environment settings or use different projections on raster and buffers.
Answer: Whenever I run into problems similar to yours I immediately suspect that the vector data has corrupt geometry. Use the Repair Geometry tool and see if that solves your problem.


How serious is this tear in the tire sidewall?

Question:
I accidentally hit the sidewall of the curb and it caused a small looking rip/tear. Do you think the tire is still good or should I replace it. I have a 4WD.
Answer: I wouldn't worry about it, there's a lot of structural integrity baked into modern radial tires:

However, I would deem replacement mandatory if any of the following occur:

exposure of the radial plies (steel wireframe)
quick loss of tire pressure (5 psi within 2-3 days)

This link has detailed information on tire construction.
Comment: Following up on this answer: I'm looking at the picture and the scuffing on the tire is clearly moving diagonally across that crack in the rubber. I think that crack was likely present before the tire hit the curb.
Answer: Would you ever feel comfortable driving the car knowing that the tire is damaged like that?  I certainly wouldn't.
The damage could be a lot worse inside.  You also need to consider safety of other road users.
Replace the tire is the only advice anyone should give on here.
If you really need a second opinion, take it to a tire fitter and get their opinion.
Answer: Replace the tyre as you can't see what damage has been done to the sidewalls structure. The sidewall not only supports the vehicles full weight but it is also subjected to all sorts of stresses and forces in all directions, as well as heat/cold/moisture & grit.
A sidewall split is an open wound for all these wearing elements and as its not repairable you only really have one safe option.


Why enol content of ethyl acetoacetate is more in toluene than water?

Question:
Ethyl Acetoacetate has enol content of 0.4% in water and 19.8% in toluene. What is the reason behind this? Does this anything have to do with the intramolecular hydrogen bonding in the enol form?
Answer: The extent of enolization is affected by the solvent, concentration and temperature. Ethyl acetoacetate has enol content of 0.4% in water and 19.8% in toluene. This is because water reduces the enol content by hydrogen bonding with the carbonyl group making this group less available for intramolecular hydrogen bonding. The effectiveness of intramolecular hydrogen bonding in stabilizing the enol, with respect to the keto form is thus seen on varying the solvent and particularly on transfer to a hydroxylic solvent.
Answer: In water, due to more number of electropositive H present, the O will tend to H-bond with water molecules due to which enolisation hardly occurs although active methylene carbon. But in toluene, since it is a non-polar solvent, intramolecular H-bonding is more favorable due to which % enolisation increases in toluene. But since ester group has some resonance in ethylacetoacetate, the % of enolisation does not increase too much in toluene.
Answer: In non -polar aprotic solvents intra H.B is present in enol form hence, it is more stable but in polar protic solvents H.B is formed with polar solvent molecules hence, intra H.B is absent in the enol form


Mounting a basketball hoop on drywall

Question: I am thinking of mounting a standard basketball hoop like this on the drywall in my garage. Is it a good idea? I worry it might damage the drywall, particularly when the ball keeps hitting the rim and each hit has a little leverage that might eventually damage the wall.
Answer: Unless this is going to be mounted 3' off the ground for small children to use with a Nerf™ basketball, the ball hitting the drywall will destroy the drywall after a half-dozen or so shots. If it is to be mounted 3' off the ground for small children to use, expect the adults to smack into it on numerous occasions until it gets ripped out of the wall accidentally (or intentionally by someone tired of the bruised hip).
Get a backboard with a hoop. The backboard will come with a mounting bracket and that can be mounted to some 2x lumber that can be mounted across several studs in wall.
The advantages of this:

The backboard will protect the drywall
The mounting bracket will be designed by the manufacturer to properly hold up the assembly.
The dimensional lumber (2x) will spread the weight of older kids, their friends, drunken buddies, whatever, who decide to hang on the rim.

Attempting to mount anything more than a toothbrush holder directly to drywall (without hitting studs somewhere) will end up in the item pulling out of the wall sooner or later. A basketball hoop/backboard will be very much on the "sooner" end of the scale.
Answer: Unless your garage is the size of a basketball court, I assume that you are using this for children to play when it's rainy outside, and not to have a neighborhood-wide tournament.
Attach a piece of wood to the drywall first, for example a piece of 1x6. Or a piece of plywood if you want, but I'd be careful with making this look like a real setup, as it will tempt players to dunk, etc., and any type of rough game will destroy your garage.
Whatever piece of wood you use, just make sure the piece of wood is longer than 16", and use 2" screws to fix this piece of wood to the studs supporting the drywall. The exact length of the screws depends on the thickness of your drywall material (safely to assume 5/8" in a garage)+ the thickness of the wood you use (safe 3/4") + thickness of the metal attached to the rim. The idea is 1" penetration into the studs. You can go longer, but then you risk damaging any electrical or plumbing going through the studs, which by code must be 1" deep into the studs.
Then use the mounting hardware from the hoop to attach the hoop to the piece of wood.
Comment: I'd suggest a sheet of plywood much larger than 1x6, so there's a backboard behind the hoop that won't be destroyed. When the ball hits the wall.
Comment: @isherwood I changed the recommendation to 2". I am always afraid of recommend anyone bite more than 1" into studs, as plumbing and electrical can be installed after the 1" mark.

Mounting a basketball hoop on drywall


Evidence for $\epsilon_{0}$ and $\mu_{0}$ being invariant between different inertial frames

Question: Are $\epsilon_{0}$ (permittivity) and $\mu_{0}$ (permeability)  invariant between different inertial frames? If yes, what hard evidence does it support that? If no, why would $c$ (velocity of light) be invariant between different inertial frames and what is the need for Lorentz transformation?
Answer: To add to C.R. Drost's Answer: Given the experimental fact of the invariance of Maxwell's equations, the invariance of $\mu_0$ arises by definition; it defines our unit of current. An intuitive and covariant form of Maxwell's equations is:
$$\Box\,A^\alpha = \mu_0\,J^\alpha$$
where $A^\alpha$ is the (contravariant) four potential and $J^\alpha$ the four current.
You can see $\mu_0$ defines the relationship between our units for current and units for potential / EM field by telling us how much field we get for how much current. We define our units so that the ampere is the current that would, if present in two straight parallel conductors of infinite length, of negligible circular cross section, and 1 meter apart in vacuum, give rise to a force between these conductors of $2\times10^{-7}{\rm N}$ per meter of length of conductor. This definition of the ampere fixes $\mu_0$ to its SI value of $4\pi\times10^{-7}{\rm H\,m^{-1}}$. Implicit in this definition is that this scaling is defined in a frame at rest relative to the conductors. Given the empirical fact of the covariance of Maxwell's equations, we are free to choose a frame that is convenient for measurement, just as we define the invariant mass of a particle through its total energy in a frame at rest to the particle.
The invariance of $\epsilon_0$ then of course follows from that of $c$ and that of $\mu_0$.
Comment: More generally it's $\nabla_\beta F^{\beta\alpha}=\mu_0 J^\alpha$, but in a flat spacetime that reduces to your given equation provided we work in the gauge $\nabla_\alpha A^\alpha=0$.
Comment: @J.G. Absolutely true: The question was about inertial frames and I  simply wanted a form that most evoked a "one way" (in the sense of RHS + boundary conditions fully define the LHS) current to implied solution relationship. One strictly gets that with the more general form, but the quoted form is a little more obvious IMO.
Answer: The magnetic constant is fixed by our choice of SI units as $4\pi\cdot10^{-7} \text N/\text A^2.$
The electric constant could vary if $c$ varies and the hard evidence to suggest it doesn't is precisely the hard evidence that suggests a fixed $c$.


Will "apt-get upgrade" also upgrade my PHP version?

Question: Will sudo apt-get upgrade also upgrade PHP from 5.2 to 5.3 on my Ubuntu 9.04?
Answer: An upgrade will only install security updates. So the short answer is no.
The full answer is, that for 9.04 updates are no longer provided as it has reached the end of its life cycle last October. You should seriously consider updating to a newer release (using sudo do-release-upgrade). Using 10.04 (which is an LTS release) you will get php 5.3.
Answer: Ubuntu 9.04 is now out of the update loop, so you're stuck with whatever you've got currently unless you update it manually.
To check the current version, you can:

Check in Synaptic.
Make a new PHP page containing: <?php phpinfo() ?>, which tells you all about your current PHP configuration.
Install the apt-show-versions package, and then run $ apt-show-versions php5.

If you don't have it and want to upgrade Jaunty (9.04) to PHP 5.3, I found a guide.
As a bit of background: The Ubuntu package update philosophy is usually to avoid major updates to packages; you'll receive only security patches, bugfixes and minor release updates. I'm not really familiar with the decision-making process, but I assume that PHP5 releases, being following the 5.x.y pattern, would remain on the 'x' that came with the distribution release. The 'y' would be updated, though.
Edit: Hit submit early, added more info.
Answer: If you want actual version of PHP (now it's 5.4), you should add ppa repository or build packages yourself.
5.4 is not for production now(wait until 5.4.1 or 5.4.2), it's for development.
sudo add-apt-repository ppa:ondrej/php5
sudo apt-get update
sudo apt-get install php5
php5 -v


Do I need an electrician to restore the power to my bedroom on the other side of a wall I drilled into?

Question: How can power lost after drilling into
stud be restored? Is it costly?
Comment: Hello, and welcome to Stack Exchange. If your drilling into a wall cut the power, then you should definitely contact an electrician. It probably will just be the one spot which needs a fix, so it shouldn't be too costly. In any case, it will be necessary.
Answer: It sounds like you drilled into an electrical wire, which will need to be replaced. The amount of difficulty involved in repairing it (and the cost) is mainly going to depend on where the wire is and how easy it is to access.  For example, if it was between two outlets that are accessible from a basement or attic, it should be fairly straight-forward.  If it was a feeder line running through an exterior wall, probably less so.  Fixing it will basically require figuring out what is connected to each end of the wire and running replacement wire.
Answer: You should consult an electrician and in the time it takes for him to respond if you have not tripped a breaker or blown a fuse you should immediately go and turn the circuit breaker off or remove the fuse. A cut or drilled into wire can short out and cause a fire. Also an electrician may be able to tell you where the wire runs and how much a repair will cost.


Where can I find the locations of factories in the U.S. and Japan?

Question: Where can I find the locations of all or many of the factories in the world, including in Japan and the United States?
Comment: What do you mean by factory? Any place where good are made? Places of a certain size?
Comment: @fgregg thank you for asking and answering. here I meant factory as place for making goods by consuming a certain amount of energy and other resources.
Answer: In the United States, you might start by looking at water permits. Most large factories have to get permits for their waste and storm water runoff.
Here are discharge permits for Illinois. http://dataservices.epa.illinois.gov/dmrdata/dmrsearch.aspx
Storm water permits: Many industrial facilities have to get a permit for the pollution caused by water running off a location. Here's data for Illinois
Comment: thank you very much for your advice. that's a very good idea to check from regulation sides. I'll try this!
Answer: Datamyne is a great source for finding sourcing of suppliers(factories) based on commodity descriptions OR via a product HS code. We source our US data via US Customs and posses trade data from 50 other countries globally. We are also a certified silver partner with ESRI and currently possess a map with over 600,000 companies geocoded along with Duns and Bradstreet verifiable information. http://www.datamyne.com/our-product/
Comment: Subtracted a point on a ISO Certified Database that contains factories or suppliers of goods from Japan into the US ? Not sure of the logic there, and it will take the user longer to use a "water/sewage" permit listing I'm confident than our tool. Been around since 1992, kthanx.


Why we see upright images?

Question: Since it's convex lens there in our eyes so image formed on our retina is inverted, so how come that we see upright images?
Comment: Because we haven't drunk enough.
Answer: This is more of a psychology question.  After you start seeing things, you notice that a certain side of your vision is the part that will see your finger if you touch your forehead, and the other side will see your finger if you touch your lips. We designate the first as "up" and the second as "down".
The brain just gets a bunch of signals. "up" and "down" are artificial tags we attach, where "up" is the side of our forehead and "down" is the side of our lips.
Besides, if one was to wear glasses that inverted vision, the mind would indeed slowly adjust.
Answer: The brain turns it around. It can also adapt to other alterations of the visual field. It has nothing to do with physics.
Answer: I've heard several times the explanation that since the image is inverted on the retina, the brain has to turn it around somehow. This comes from intuitively and probably unconsciously picturing the head as something like a cabin where the brain lives, and sees on a display the image collected from the retina, image which it therefore has to turn around, in order to see it upright. But does the brain have an up or down sense?
What if we extract the brain from the skull, without disconnecting it from the rest of the body, and turn it upside down? Would it see the image upside down?
added
Let me put it differently. If the image would not be inverted (actually rotated), so if the mechanism was different than that of a camera obscura, nobody would have ask why we see upright. But if the image is inverted on the retina, we think that the brain should invert it back. But back with respect to what? There's no reference in the brain with respect to which the image on the retina is inverted. Why should the brain apply an algorithm to invert the image?
Comment: I think this experiment does not require touching a brain, because I heard that the balance and position sensor of human is in ears. So we can just disconnect ears and see.
Comment: @freude: I think that's not the point.

Why we see upright images?


Can there be too little unemployment for the health of the economy?

Question: The cyclical rate of unemployment can be negative, which implies that the business cycle sometimes produces too little unemployment. How can there be "too little" unemployment for the health of the economy?
Answer: Let me answer a simpler question first. Is it possible for there to be too little orange juice in the grocery store? Definitely.
Let's say that the price of OJ is set too low (\$1 per liter) and customers who arrive early in the morning buy all the OJ. Assume that those customers think buying all the OJ is a good deal and they figure they'll enjoy drinking it, but that at regular price (\$4 per liter) they'd buy much less, they wouldn't want any more at those prices, and there would be lots left on the shelves.
People who arrive later in the day want some OJ at \$4 per liter. If they could find them, the early OJ buyers would happily sell them the OJ at that price and pocket the profit (that follows by the demand schedule I sketched out in the second sentence of the last paragraph). That means that there are deals to be done that would improve the allocation of OJ (there are welfare increasing, Pareto-improving, trades to be made). But the early customers and the late customers have trouble finding each other and so the OJ stays in the early shoppers' refrigerators.
Just about everything I just said about OJ holds for worker labor. Surprise! If the price of labor is set below the equilibrium price then early buyers purchase an inefficient quantity. Later buyers can't find the workers they need even though the marginal value of those workers is higher than the price at which the early employers bought them. Because (or perhaps I should say if) it is less efficient to look for a job while you have a job, when unemployment is too low workers ended up employed by firms that do not employ them at their highest marginal product. If only alternative employers could be found output and welfare could be improved. In fact, using a Kaldor-Hicks mechanism it is possible to make the new employer, the old employer, and the employee all better off under such circumstances. Thus it is not efficient under production efficiency or welfare efficiency criteria.
Answer: Think of unemployed workers as a pooled/shared resource. Over the progression of the business cycle (economic expansion/contraction), business add to and draw from this pool as needed.
When cyclical unemployment is positive and high, unemployed workers linger in this pool for a long time, as job opportunities are hard to come by. Businesses have their choice as to whom they hire, for the worker pool is quite large, and workers have little leverage in the terms of their employment, as labor is plentiful. This situation would arise during the bottom of a business cycle, when the economy is contracting and/or just beginning to recover/expand.
When cyclical unemployment is positive and low, workers move out of one job into another with relative ease, staying unemployed for a relatively short amount of time. Business can add employees at will, though workers can now demand a small premium for their labor, as their particular skill set is harder to find among  the available workers. At this point, the economy is firmly on the upswing and growing.
When cyclical unemployment is negative, workers move directly from one job to another without being unemployed. Additionally, businesses experience underemployment, that is they have fewer workers than they want. Labor commands a large premium, as businesses must steal workers from one another in order to satisfy their employment requirements. The business cycle is peaking, and the deficit of available labor will soon work to slow growth/expansion.
Answer: As usual in economics, the question is perplexing when considered from a purely quantitative point of view. However, once we admit qualitative variation, the answer becomes self-evident.
It is possible for there to be too little unemployment when there are too many "bullshit" jobs that do not create value and merely keep people busy for the sake of employment. Arguably, it would be better - and in aggregate cheaper - for those people to be unemployed.
We might venture to call this the "European model".
Comment: This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. - [From Review](/review/low-quality-posts/6414)
Comment: The answer is that it is entirely possible to have too little unemployment if the employment available is generated at the price of misallocation of resources. This is self-evident.


Is "troppo è come niente" an Italian proverb meaning "too much is like nothing?"

Question: Is "troppo è come niente" an Italian proverb meaning "too much is like nothing"?
Comment: The few occurrences that can be found on the Internet rather suggest "il troppo è come il niente". The translation remains the one you cite. I've personally never heard this one.
Comment: Not AFAIK. It means "too much is like nothing", but it's neither a proverb nor an idiomatic expression as far as I know. There are many proverbs addressing the "having too much" thing, as explained in Davide Borsatto's answer, but I too didn't heard of this one. However I'm assuming you're not just asking this out of the blue, so where did you heard this in first place?
Answer: I'm Italian and honestly I've never heard of this, although if I had to guess then yes, it would mean something like "too much is like nothing".
Other proverbs with similar words are "il troppo stroppia" meaning "too much (of something) can be annoying" and "chi troppo vuole nulla stringe", meaning "who wants too much will get nothing". They are both much more famous proverbs about "troppo". I tried googling yours and I couldn't find anything of significance. Where did you find it?
Comment: @funforums Yes, I'm aware that they have two different meanings. I wasn't implying that they mean the same thing, I was just mentioning other proverbs about "troppo". Maybe the person who asked just misremembered the original proverb, and I was providing the most likely alternatives that actually exist. Also, I never said or implied that "troppo è come niente" is related in any way to "who wants too much will get nothing".
Comment: Benvenuto su Italian.SE, @Davide!
Comment: While I definitely agree with the answer in general, I would struggle to relate "troppo è come niente" to "who wants too much will get nothing". As a computer scientist, to me these are two completely different meanings. If I have to dig through an immense amount of possibilities and data, it's just as hard as having 'no' data at all to start from. This meaning does not relate to "wanting too much".


ORM mapper for Node.js

Question: Is there a cross database ORM mapper for Node.js which provides a consistent API for database access across different relational databases (say MySQL, MS SQL Server, Postgres, Oracle ..). The database page shows different libraries for database access, but I would like to use a library which lets me switch to any database during production.
Answer: Might also want to take a look at bookshelf.js (MySql, SQLite, PostgreSQL)
It's one of the only ones with transaction support and proper eager loading of relations.
Answer: Have a look at jugglingdb. RailwayJS project uses it.
Or sequelize (MySQL, SQLite and PostgreSQL)
Answer: For huge projects: http://bookshelfjs.org/
For small projects: https://github.com/knyga/light-orm
Answer: I just wrote my own ORM https://github.com/jbaylina/syncorm
Now there is only one driver for mySQL, but it should be easy to write other drivers for different databases.
The main difference with the rest of ORMs is that the whole database is loaded in memory.
You can access the database as regular javascript objects synchronously. (one object is one record). The objects can be related one each other ina one to many / many to one relation.
It is very useful to use Underscore to iterate thru the objecs.
To modify the objects, you just write in those objects and call commit() to save all the changes to the database in a single transaction.

ORM mapper for Node.js


Do hydrides, like NaH or CsH, also form H-bond?

Question: I know that when hydrogen acts as a cation, it can form H-bonds with the electronegative ions or groups. But, is this also true for anionic hydrogens? Will they form similar bonds, other than the existing ionic bond, with electropositive ions, like the alkali metals and alkalikne earth metals, or maybe some other electropositive group?
Comment: Do the bonds in B2H6 count?
Comment: And how are you imagining this? Do you know how hydrogen bonds work, because it sounds like you talk about something else.
Comment: Particularly bridging hydride ligand that @IvanNeretin mentions and are a very different thing then hydrogen bonds. There are also [agostic interactions](https://en.wikipedia.org/wiki/Agostic_interaction), which are like an analogue of hydrogen bonds, but "hydridic" instead of "protic".
Comment: The point of hydrogen bonds is they are something more then dipole interactions.
Comment: @Mithoron.. H-bonds are formed because of the polarisation effect due to unequal sharing of electrons between the ions.. if I'm not wrong, then shouldn't any molecule having a dipole moment show coulombic attraction among its neighbours?
Answer: On the surface, the answer is no, because that's not what we would call a hydrogen bond.
On a deeper level, the answer is... probably still no for NaH or CsH, because they are too ionic for this. Other hydrides, however, actually do have a thing which looks mighty like an "inverted" hydrogen bond (though we don't normally call it that, either).
Really, look at it this way: in $\ce{H2O}$ we have a hydrogen with partial positive charge, which gets attracted to a lone pair of another electronegative atom and forms something like a (3c, 4e) bond.
Now look at another scenario: a hydrogen in $\ce{BH3}$ (or better yet, in $\ce{AlH3}$) bears partial negative charge and gets attracted to a less electronegative atom with an empty orbital, so as to form a (3c, 2e) bond.
Whether to perceive these two scenarios as similar or as opposite is up to you.
So it goes.


Does eq. of continuity hold in vacuum too?

Question: When a streamlined flow of water flows down through an ordinary tap, it's cross-sectional area decreases according to eq. of continuity due to atmospheric pressure. If the same apparatus were to be arranged in a vacuum, would the cross-sectional area of the flow decrease? And if yes, which force pushes it inwards?
Comment: Presumably the argument is that in a vaccum the water stream could remain the same radius and voids could form within it. I suspect surface tension would prevent this but I don't know enough about the subject to risk an answer.
Answer: It would be difficult to begin with to set up such an apparatus to produce a stream of water because for a flow of water from a nozzle there would need to be a pressure difference. As such the water would instantly vaporize once exposed to the vaccuum. So technically, the cross-sectional area of a stream of water would expand to fill the vaccuum it is contained in.
While mass is obviously conserved even in a vaccuum, the continuity equation is undefined in a vaccuum because it is based on a continuum assumption which does not hold when the mean free path of particles is too large (which is the case in a vaccuum)
Answer: Equation of continuity is basically mass conservation.
It can write more simply in case of incompressibility, but it can still be written with varying densities.
BTW interstellar medium and nebula can be considered as fluids, at the appropriate scale of time and space.
Comment: You seem to be using a different continuity equation for your answer than Apoorv is for his question.


Magento 2.4 Custom Sort Order to Print Multiple PDF Invoices (Grouped Print sorted by Customer Name, then by order date)?

Question: Is it possible to select a range of invoices, apply a sort (say by Customer Name), then to print the selected range in that order?  We have customers placing numerous orders in a week that we list view manually on screen to bring them together.  We need to then print all invoices due to despatch that day in that order (grouped / sorted) by Customer.  This ensures they are consolidated for despatch and and none are missed.  Many thanks
Answer: It is possible to sort or filter the invoices in admin via any of the columns or filters available. Select some or all of the invoices and then export them as a single pdf file.
You can then print out this pdf file.
Answer: Great answer thank you, but is there a way that the exported pdf file has the invoices in it in the sort or filtered order you selected in the admin panel?  We need to group customer invoices together so we can pick them all at the same time.


How can you give a player fireworks?

Question: I'd like to give some firework items to a player, using a dispenser, or via some similar mechanism. How can I do this? Is it possible?
Comment: Put a firework in a chest with a sign saying "fireworks here".
Answer: The Dropper block, available since Minecraft 1.5, can be used for this purpose. It is similar to a dispenser, except that it does not "activate" items like arrows and fireworks, so they will be dropped for the player to pick them up instead.
Comment: This is definitely the right answer.
Answer: There are several ways to give a player on your server Fireworks.
Of course, the obvious way is to simply craft them from Firework Stars and give them to the player. This requires materials, requires you to walk up to them, etc. You could leave them in a Chest, but that still isn't automatable.
You can try putting the Fireworks in a Dispenser, but it will fire them off rather than give them. Instead, the Dropper can be used to properly dispense Fireworks that a player can pick up and use.
The most flexible option, however, is the /give command. It requires being an Operator on the server, but the power it has in customizing the fireworks is incredible.
#Using /give with Fireworks
Using a command of the form
/give <PLAYERNAME> fireworks <AMOUNT> 0 <DATA>

you can create arbitrarily complex fireworks, using colours not even present in the game, and give them to a player. It works both directly typed in, or through Command Blocks, though direct typing has much more strict character limits. Command blocks can use all the usual @p selector stuff in place of PLAYERNAME.
Explosion Data
The data format is as follows:
{Fireworks:{Flight:<FLIGHT LENGTH>, Explosions:[<EXPLOSION INFO>]}}

Flight length is a number, corresponding to the duration the firework should fly. Explosions will be of the following form:
{Type:<TYPE>, Colors[<COLORS>], Flicker:<0 or 1>, Trail:<0 or 1>}

And you can add multiple explosions by just putting commas between them. The Type is a number, with 0 for Small Ball, 1 for Large Ball, 2 for Star Shaped, 3 for Creeper Shaped, and 4 for Burst. Flicker and Trail (Which control the effects normally gained from using a Diamond or Glowstone Dust in the Firework Star)are 0 to not be used, 1 to be present, and can be omitted entirely.
The Colors section is a series of numbers, with commas between them. Each corresponds to a single colour used to create the firework. The numbers are in the form
Blue + 256 * Green +  256256Red
Where Blue, Green, and Red are numbers between 0 and 255. So 255 is solid blue, 65280 is solid green, and 16711680 is solid red.
Putting it together
So, putting it together, a /give command to give my character a single firework, with a fuse length of 3, and a single small-ball explosion of stark blue sparks, should look like:
/give wmailman fireworks 1 0 {Fireworks:{Flight:3, Explosions:[{Type:0, Colors:[255]}]}}

Whereas, a command to give me three fireworks, with a one-length fuse, with two explosions, one a red star, the other a green and blue large ball, would become:
/give wmailman fireworks 1 0 {Fireworks:{Flight:1, Explosions:[{Type:2, Colors:[16711680]}, {Type:1, Colors:[255, 65280]}]}}

And, just for one last example, you could use
/give wmailman fireworks 1 0 {Fireworks:{Flight:3, Explosions:[{Type:0, Colors:[255], Flicker:1, Trail:1}]}}

to create a version of the first fireworks, but with the explosion having both the flicker and trail effects.
Caveats

The colour listed on any firework created this way will be named "Custom" in the item, unless you use the exact colour codes created by crafting in-game. Unfortunately, I do not know what those numbers are exactly.

Almost everything in the data is case-sensitive.

Firework Stars
You can also do this with Firework Stars. The data tag will be in the format
{Explosion:<EXPLOSION INFO>}

Where the Explosion Info is the same as described for Fireworks.
Pictures
Because this post turned into a bit of a wall of text, here's some example shots of me using /give:

Once that command is typed in, the resulting firework is added to my inventory:

The command used here was
/give wmailman fireworks 1 0 {Fireworks:{Flight:3, Explosions:[Type:0, Colors:[255, 65535]}]}}

This means a single firework, fuse length of 3, with one Small Ball explosion, with two colours, one solid blue, the other blue-green.
Despite the names of the colours displaying as Custom, the resulting explosion has nice pretty blue and blue-green sparks, as I expected:

Sources:
The Minecraft Wiki Page on the player.dat format has a small section on Fireworks. The colour numbers are described elsewhere on that page. Most of the work lies in turning the result into the JSONish format Minecraft expects. Which is basically just leniently-parsed JSON.
Answer: When using a dispenser, the fireworks leave the dispenser armed, so that isn't much good.

Also, because the fireworks all share an ID (401) command blocks can't be used (it just spawns a firework with no explosion in it).
You can, however, use spawners to spawn the dropped item entity (one of Seth Bling's scripts can be used.) These are harder to control, though, and limiting the amount of items the player gets can be tricky.

Note this technique can be used to spawn any custom item, such as enchanted weapons and custom potions.
Comment: @MBraedley Fireworks don't even have data values, due to the number of different combinations of stars and fuse lengths it'd be impractical, they have the type of firework stored in their tile entity, like how books store their text.
Comment: Can't you use the data values with the /give command?
Comment: This could be updated to mention the new Dropper.
Answer: If you're playing on a CraftBukkit server, the Essentials plugin has a /firework command. You could give your players fireworks through the /give (item code 401) command and then let the players "customise" the fireworks with the /fireworks command.
The syntax for the command is (and will be applied to the stack of fireworks currently held in-hand)

/firework color:color fade:color shape:shape effect:effect

You can choose three colours for the inital burst using /firework color:red,blue,green. You can also choose the shape by using /firework shape:star,ball,large,creeper,burst (one of those 5) and change the effect with /firework effect:trail,twinkle. Power (flight) settings can be ajusted with /firework power:1,2,3
So, do a /give 401 for 64 fireworks, and then for a firework which bursts red, blue and green, does a large ball effect, twinkles/crackles and has maximum flight height you can use:
/firework color:red,blue,green shape:ball effect:twinkle power:3
Comment: This could be combined with command blocks, too.
Comment: @SevenSidedDie, would (or do) Command Blocks work with plugin commands?
Comment: I can't confirm from experience, but they seem to from what I've read.
Answer: I have not tried this yet but I was thinking you could do this with a few Bukkit plugins - WorldEdit, Citizens, and Denizen.

Create a chest and fill with the various fireworks you wish to give out.
Using WorldEdit copy and save the chest as a schematic.
Using Citizens and Denizen create a script that creates and uses a NPC (Non-Playable Character) to ask and offer the fireworks to players.
In the Denizen script loads and reloads the chest schematic each time a player interacts with the NPC or just automatically reloads the chest after a set period of time.

I believe this should work as Denizen scripts allow you to load WorldEdit schematics.
Answer: You may leave it in a chest. then he will get it.
Answer: Because fireworks have weird metadata I made a tool to make fireworks easy. They are saved as kits so if you want players to have them, just give them access to the kit. You can find the tutorial at

 and the download link will be in the description.
It's really simple to make complex and custom fireworks using this method.
Answer: Just write in a command block: give @p 401 1 color:red,blue,green shape:ball effect:twinkle power:2

How can you give a player fireworks?


What are the drawbacks of fully-convolutional neural networks?

Question: It is possible to replace the fully-connected layers of a CNN with convolutional layers, making it fully convolutional. Fully-convolutional networks (FCNs) can be applied to inputs of various sizes, whereas a network involving fully-connected layers can't. Still, for the input size the network was designed for (e.g. 224x224 in the case of VGGNet) the mathematical operations performed are exactly the same in both. What are the drawbacks of a FCN? Can we just throw away all fully-connected layers and replace them with their convolutional counterpart?
Comment: How would you classify different labels then? If you have 4 outputs for example, not each of those outputs will have access to the same field of the previous convolutional layer; label 'cat' won't see everything label 'dog' sees. Interesting: https://people.eecs.berkeley.edu/~jonlong/long_shelhamer_fcn.pdf and http://cs231n.github.io/convolutional-networks/#fc
Comment: @ThomasW No, that's not what you would do. You would have two filters (one for each label). This means each filter can have different weights, but they have exactly the same receptive field. The receptive field means how much of the input can be used for the computation of the output. The computation itself can be totally different.
Comment: Thanks for the useful links, especially the second one is a good resource for FC->FCN conversion in general. Classification is usually done by averaging, this is outlined in the VGGNet paper: https://arxiv.org/pdf/1409.1556.pdf. That's the same as classifying crops and averaging the predictions, just with a single forward pass. If the input is "native" (224x224 for VGGNet) though, there will be only a single output vector.
Comment: @ThomasW Why should the output labels have different perceptive fields in FCNs?
Comment: @thertweck As far as I understand it, you can simply replace every fully connected layer by a convolutional layer in a CNN. No drawbacks as far as I know.
Comment: @MartinThoma well that's how how CNN's work, right? You slide a receptive field over the input, it then computes one output for each field with the same weights as the other receptive fields. If you would have 2 labels, then you would have two receptive fields. If you would have the same receptive fields for each lable, you would have the same output for each label (because each receptive field has the same computation)
Comment: @MartinThoma true, but if you have one seperate filter for each label with its own weights, of which the receptive field is the same (must be the whole previous layer dimension to classify the label), that is a fully connected layer :)
Comment: @ThomasW No, a convolutional layer is not the same as a fully connected layer. The crucial difference is that fully connected layers expect the same input size all the time. In contrast, you can apply FCNs to bigger images than they are trained for.
Comment: @MartinThoma I invite you to reread my comments. I never said that a convolutional layer is the same as a fully connected layer. I said that if your last (classification) layer is a convolutional layer with one filter per label with the receptive field being the entire dimensions of the previous layer,  *then you basically have a fully connected layer*. Here: http://i.imgur.com/2p9VS0C.png. These two are exactly the same!
Comment: @ThomasW Yes, but this is only true for "native" sized inputs. If you run a FCN VGGNet on a 10x224x224x3 input the output is 10x1x1x1000 (just as if it was fully connected). If you run the *same* net on a 10x256x256x3 input, the output is 10x2x2x1000 (basically predictions for 4 crops), this is not possible when the net has fully connected layers.
Answer: All-convolutional network is a great idea exactly because it has much more advantages than disadvantages. Most of modern convolutional networks are designed to use CONV for everything. If you are focused specifically on disadvantages, here're a few:

An FC to CONV layer replacement means great reduction in the number of parameters. It's cool to save the memory, but it's loss of flexibility nevertheless. In my experiments, CIFAR-10 classification accuracy dropped slightly after this single change, though it was certainly within one standard deviation. But I'm sure there are cases when this loss of flexibility makes a bigger impact.
A convolution is a significantly slower operation than, say maxpool, both forward and backward. If the network is pretty deep, each training step is going to take much longer.
The network is a bit too slow and complicated if you just want a good pre-trained model. That's why the researches still use AlexNet and VGGNet for experiments. They are simple (in terms of architecture), well-known and provide good performance - that's exactly needed.


Non-Uniform Circular Motion

Question: If an object travels an elliptical path about a point, say a roller coaster with an elliptical bottom, how would one computer the radius of that path when applying the equation: $F = mv^2/r?$ Would it just be the average radius along that elliptic curve?
Answer: The radius of curvature of the ellipse varies from point to point. It is not the distance to the center of the ellipse. You need to know the parameters of the ellipse (the two semi-axes) and where on the elliptical path is the point you are interested in. The easiest way to find the formula for the radius of curvature would (in my opinion) to use the parametric equations of the ellipse
$$ x= a \sin \theta $$
$$ y= b \cos \theta $$
and use the formula for radius of curvature
$$ \rho= \frac{(y'^2 +x'^2)^{3/2}}{x'y''-x''y'} $$
where x',y' are first derivative in respect to $ \theta $ and x",y" are the second derivatives. If you get a negative value for the radius you just take the absolute value. You will get a formula for the radius as a function of the polar angle $\theta$. At the two extreme points on the long axis $\theta= 0 \ or \  \pi $ and at the two extreme points on the short axis $\theta= \pi/2 \ or \  3\pi/2 $.

Non-Uniform Circular Motion


Compare Two Multivariate Data sets

Question: I have two multivariate data sets, one is simulated, and I want a test to compare how similar their distributions are. The data set is discrete and the distribution is unknown. In other words, I am looking for an alternative for KS, AD or similar univariate statistical tests that cab be applied for multivariate data.
I appreciate your answers.
Comment: There are innumerable ways that distributions can differ, even within univariate distributions. This will be even more so w/ multivariate distributions. No test could assess all possible ways 2 distributions could differ. So the key question is, what kinds of differences are you most concerned about?
Answer: Compute a distance metric between your two observed matrixes. Then to determine if that distance is significant, you use a permutation test. You can refer to this, it seems that your question is a duplicate of this one.
Comment: I have read all posts I could find regarding this question but the answers were still insufficient to me. Can you name an appropriate distance metric that I can use for the method you proposed?
Comment: The distance metric could be anything, you can take the L2 norm between the datasets and decide upon a threshold based on your problem. You can do this per feature based and add the distances up in the cost function. Take a look at https://normaldeviate.wordpress.com/2012/07/14/modern-two-sample-tests/
Answer: Use the nearest- neighbour classifier on each point.
If the two sets are from the same statistical source and have the same number of points, then you would expect all the data points to have a nearest neighbour with equal probability of belonging to each of the two groups.
So a robust method, but computationally tedious, is to remove each point from the data set in turn and apply it to the to the remaining data using the nearest neighbour rule. This will find which of the two sets it most likely belongs to.  Expect to get a near equal score. A simple coin-toss test with p = 0.5 and n, the total number of points will give you the likelihood of the sets being From the same source.
This approach is valid for multi dimensional scatter plots with no assumption of normality, so it is very robust. No doubt it can be used where the two sets have different numbers where p would be represent the ratio.

Compare Two Multivariate Data sets


What are some major military successes the Soviet Union achieved against the Western World?

Question: What are some major military successes achieved by the former Soviet Union against the Western World that shook the US and its Cold War allies?
Comment: Are we counting WWII? Defeating Germany and [marching into Berlin](https://en.wikipedia.org/wiki/Battle_of_Berlin) with a massive army and shockingly good equipment would definitely be one of them. That, and their unwillingness to withdraw from Eastern Europe, started the Cold War.
Comment: @JoeHobbit - The Americans consider the Berlin Airlift a victory for their side, tho: American logistics vs. Soviet ground forces. In retrospect, both sides probably thought they "made a point" - the Cold War was weird like that.
Comment: @RISwampYankee except the only point the Soviets made during the Berlin Blockade was to reinforce what heartless b*stards they were.
Comment: The Soviet blockade of Berlin was enough to cause the Berlin Airlift.
Answer: There were none. Likewise, the U.S. never scored any military victories over the Soviet Union.
The Cold War was a war by proxy. One superpower was a combatant in Afghanistan, Korea, and Vietnam, but the other did not send troops to the other side — partly out of fear of escalation into global conflict. Rather, they provided support to their allied local factions, as both did in the numerous other conflicts of the Cold War.
That is not to say that other military conflicts did not shake the Western powers. The single most significant development was the defeat of the Nationalists in the Chinese Civil War and the declaration of the People's Republic of China in 1949. The shock and the ensuing bitter debate over who had "lost" China colored American policy for a generation.
Comment: +1. The entire meaning of "Cold" War is that there is no direct warfare between the two parties. Its all carried out with propaganda and bluff, and very occasionally with proxies.
Comment: @T.E.D The "Cold" war was not entirely fought with proxy wars.   It is more accurately described as proxy and clandestine wars.   Soviets fought in [Korea](https://en.wikipedia.org/wiki/Soviet_Union_in_the_Korean_War#Soviet_Pilots) and [Vietnam](https://www.reddit.com/r/AskHistorians/comments/8usq6u/during_the_vietnam_war_the_soviet_union_had_16/),  and Americans undoubtedly were in [Afghanistan](https://en.wikipedia.org/wiki/CIA_activities_in_Afghanistan).
Comment: First off, those numbers are supposedly from "declassified Soviet Records" that were presumably classified for a reason. Secondly, I'm not sure how much I trust info from a website "exploring the link between mind and matter". But of course there's always a certain amount of fudge in keeping it "cold", and you aren't going to shock me (or probably anyone else) with a claim that the Soviet side was fudging more than the US one.
Comment: @VivaLebowski - The official story is that they were only there as advisors, which both sides were invested in keeping as the official story (because admitting otherwise would be a public admission of a *hot* war, which would require a very different response to save face). This is how things worked back then.
Comment: @JMS - Quite, but only in a limited role as "advisors". There was always some level of remove. If there were significant #'s of US soldiers in a war zone personally shooting Russian soldiers, we couldn't really call it a "cold" war anymore.
Comment: @T.E.D..   Soviet involvement in [Korean War](https://thesanghakommune.org/2017/01/20/soviet-casualties-during-the-korean-war-1950-1953/) was beyond advisory.  "12 divisions of the Soviet Red Airforce – numbering an over-all figure of 72,000 combat (and supporting) personnel throughout the 3 years of the war – peaking with 26,000 operating in 1952. During that time, Soviet pilots shot-down 1097 enemy planes, and the Soviet Anti-Aircraft Artillery shot-down 212 enemy planes. The Soviet Airforce lost 335 planes and 120 pilots.  Over-all, the full Soviet casualties are listed as 282 people."
Comment: @T.E.D But I think any "number fudging" is besides the point; it is a fact that members of the Soviet military intentionally engaged in direct combat with US pilots. This does not mean it was a large involvement, but does that not necessarily contradict your statement "only in a limited role as advisers"? These were not accidental incidents, an adviser getting caught in a warzone, these were, as JMS alluded to, deliberate acts that the Soviets attempted to obscure.
Comment: @T.E.D Did JMS imply that he was talking about the official accounts of the time rather than the facts on the ground?
Comment: @T.E.D  The numbers are good.  Here is a better source.  From the Woodrow Wilson Center for International Studies;  The Cold War International History Project:  [Cold War in Asia](https://www.wilsoncenter.org/sites/default/files/CWIHP_Bulletin_6-7.pdf):  pg 35:  "Gen. Georgii Lobov, who commanded the 64th Fighter Aviation Corps in Korea, stated in an interview in 1991 that approximately 70,000 Soviet pilots, technicians and gunners served in the corps over the course of the war."   The Soviets were not just advisors in Korea they were an important and potent participant.
Answer: The answer to your question depends heavily on how you define "Military". As Choster implies, the Cold War was never "hot" by definition, so that excludes any direct military confrontation, and thus no soviet military "successes" against the West if we define a success as such.
But given that you are asking the question, I assume you are not defining it in that narrow way and IMHO, it is absurd to argue a military cannot achieve a success against its opponents except in active combat since that excludes any peacetime activities of that military which might nonetheless have a huge effect in an economic, technical or strategic sense. Military funding is not provided just to fight wars and train for future wars after all.
So, to your question, there are two areas of achievement. I'm sure we could find more.
One, the Soviet space design bureaus were in large part driven by military needs, supported by military funds, and worked in coordination with the Soviet military. Someone with more expertise than I can tell us exactly how military any particular part of the Soviet space effort was (for example, rather a particular bureau was part of a formal military structure or an academic/scientific group that was working with the military, but it is a fact that these partially military program(s) made huge strides, often ahead of the US, that shocked the West and enhanced the USSR's prestige, technical strength, etc. etc. That the demands of the Soviet military often clashed with the more scientific/academic goals of the prominent Soviet scientists does not mean that these strides were not in part attributable to the Soviet military. To name a few:

First ICBM
First artificial satellite in orbit
First human in space
First human to orbit the earth
First pictures of the far side of the moon
First interplanetary probes

Two, direct Soviet military aide was given via advisers and equipment to prop up and defend allies and satellite states.

Support for the CCP in defeating the US backed Kuomintang in the Chinese Civil War.
Direct support for the DPRK in the Korean War (including direct support via Mig fighter jets piloted by Russians), a war which forced the US/UN forces into a stalemate
Deployment of nuclear missiles in Cuba which eventually resulted in US withdrawing it's nuclear missiles from Turkey.
Advisers and equipment support for the victorious North Vietnamese during the Vietnam war.

The pattern here is that the Soviet military in peacetime (if we can call risking nuclear Armageddon and fighting proxy wars "peace") was employed to spread and defend communist governments and enhance the soviet unions strategic deterrence, rarely through direct military activity (though on rare occasions it was!) but through advisers and equipment. By doing so, the Soviet Union gained friendly markets for exports/imports, friendly votes in the United Nations aligned with it's interest, military allies to strengthen its strategic deterrence, etc. etc. Of course these were more than just military achievements (they were diplomatic as well) and of course in some cases these allied states turned on the Soviets (as in the Chinese) but they were at least short term victories if not always long term.
Answer: I am not sure to understand the question, but one possibility could be:
- How did the armies of both sides impress the other by their success against pro-Western or pro-Eastern ennemies?
First, the Korean War was a good news for the Soviet: their pilots, on homemade Mig-15, were able to fight the US Air Force and the Chinese, on the ground, effectively fight UN's troops, despite enduring heavy casualties. This situation was a factor of proudness for the Soviet army, plethoric and objectively better in hardware and training than the Chinese army.
Then came all the Israeli-Arab wars, were the Soviet hardware in Arab hands get all the time beaten. But often, Soviets thought that the Arab difficulties in training and command were enough to justify the defeat. The Vietnam war and the initial success of their DCA in the Kippur war lead the Soviets to be very satisfied of their doctrine. Basically, it consisted in:
- an heavy assault aviation for first line operations
- plethoric and mobile DCA to protect the offensive groups (GMO/OMG)
The Vietnam war were, as Korea, an occasion for Soviets to think: "Our allies, with our materials, beat the US Army so we will beat the US Army". But they missed in the process the numerous ameliorations, on tactical and operative plans, that US forces implemented as a reaction to their defeats.
Note that Soviet navy only got pointless indications during these events, such as the fight between light missile launcher aircraft, while the US Navy reinforces its training and its fighting aviation aboard the carriers. Even the Falkland Wars did not involve proper doctrine or hardware to be very relevant for Soviet navy.
Air forces of both sides got numerous the lessons from these proxy wars.
Finally, the Iraq-Iran war showed to the Soviet, providing hardware to Iraqian army, that it was efficient as a robust and easy to use hardware. But they had to note that the US-armed Iran Air Force was able to effectively repel Iraqi hardware, until French Mirages entered the game.
Finally, the very important difficulties of Soviet Army during the War in Afghanistan were a way for the NATO to increase the importance of the special forces and light weapons like mortars, antitank missiles or Manpads. It also showed the disintegration of the Soviet Army, and USSR in general.
To conclude, the proxy wars were factors of gladness and deception for both sides, but notably the NATO sides, especially the US Army, got very important lessons in the proxy wars, even defeat like in Vietnam. The British special forces, aviation and navy got infos in the Falkland Wars, and the French army in its multiple engagements in Africa, against Soviet armed-movements.
Comment: There were no NATO troops (second paragraph of answer) in the Korean war. They were UN troops.
Comment: Thank you, you are perfectly right. Speaking of NATO and US forces, I missed my words


What is limit on the size for a particle in a fluid medium to experience Brownian motion?

Question: I am trying to study diffusion and Brownian motion, I found that diffusion is the macroscopic version of Brownian motion and also that if particle in a fluid medium is really small then the force excreted by the random motion of molecules will be unequal in some dimensions leading to net force and net motion.
My question is related to this concept: Do we have a formula or quantitative analysis to tell that particle of 'this'  size in terms of molecules' size of fluid media or Diffusion coefficient, or some other quantities, can undergo Brownian motion but not larger than that?
Please also include your references.
Comment: Large particles undergo Brownian motion which is so small that you cannot observe. Very small particles undergo Brownian motion but the particles are too small to observe.  These links might help you? http://advlabs.aapt.org/bfy/files/AJPBrownianPaper.pdf and http://www2.pitt.edu/~jdnorton/lectures/Rotman_Summer_School_2013/Einstein_1905_docs/Einstein_Brownian_English.pdf
Answer: The colloidal particels of a colloidal solution when viewed through a ultramicroscope show a constant zig-zag motion known as Brownian movement.
$Size\space of\space colloidal\space particles :1nm - 100nm$
Brownian movement is a characteristic property of colloidal particles. This motion is independent of the nature of the colloid but depends in the size of particles and the viscosity of the solution. Smaller the size and lesser the viscosity, faster the motion. The motion becomes intense at higher temperature.
The Brownian movement is due to the unbalanced bombardment of the particles by the molecules of the dispersion medium. As the size of particles increases, the probability of uneven bombardment decreases and the Brownian movement becomes slow. (Here particles refer to colloidal particles)
The Brownian movement has a string effect which does not permit the particles to settle and thus, is responsible for the stability of sols.
Comment: Is there a formula showing its exact relation ship with viscosity, or is it a general rule that for particle of  size 1nm−100nm there will be Brownian motion irrespective of anything(viscosity, diffusion coefficient) etc. Also does increase in viscosity decreases randomness of Brownian motion, and is there quantitative analysis for this too?
Comment: Einstein gave the formula for Brownian motion. I dont understand the formula part but the theory that is have posted in my answer is correct. Check this out https://en.wikipedia.org/wiki/Brownian_motion


Will simply adding a 'Allow Cross Origin Requests' to my node app work?

Question: I'm trying to make a 'frontend web scraper'. I had the idea of setting up a node app that had a dynamic route that used Request (the NPM package) to scrape pages and displayed them as it's own. Then my JS plugin would add an invisible iframe to whatever page it's used on with of 'nodeapp.com/[URL-TO-SCRAPE]'. Then use the inter page getElementById() function to get the text. The reason I ask this question is because I know that you can't use getElementById() across multiple origins, but if I was able to get the page on a heroku app with a 'Allow Cross Origin Requests' header would this work? I know my question is very confusing.
Answer: What you're describing is a reverse proxy.
CORS allows cross-origin reading of resources, but it does not allow cross-origin iframe reads. However, if your reverse proxy serves permissive CORS headers (e.g., Access-Control-Allow-Origin: *), then the contents of your reverse proxy will be readable with an Ajax request. You simply need to make an Ajax request to nodeapp.com/[URL-TO-SCRAPE], load the fetched HTML into a document, and then find the element with myNewDocument.getElementById.
Note that if the page reading the iframe is on the same origin as the reverse proxy, CORS isn't even necessary. (If they're different origins, then CORS on the fetched page is sufficient to allow the proxy content to be read.)
Note also that reverse proxies will not use the user's cookies when making the request to the page. So, for example, when your reverse proxy fetches gmail.com, it will show the user the Gmail login page, not the user's inbox. If the content you're trying to read is not protected by credentials (i.e., it can be read without logging in), then there won't be any issues.


If gyroscopes are used as resistance devices, where does energy put in go?

Question: If two gyroscopes were to be started with parallel angular momentums, linked by a rotating tube (one perpendicular to the axle), then a second pair added that is the exact reverse such that it has opposite gyroscopic precession, the two linked such that they may not move relative to each other, and then each gyroscope moved by the rotating tube in the opposite direction of the one on the opposite end for each pair, where would the energy go that was used to force the gyroscopes to move away from their original orientation?
I can add a drawing of the apparatus if it would help.
Comment: Force is not energy.  A gyroscope hanging horizontally by one end will precess.  The gravitational force pulling down will cause the precession.  But since the COM stays at the same height (and the disc doesn't change speed), there is no energy transfer.
Comment: Changing the rotation axis of a gyroscope does not take energy.
Comment: From my current understanding, when a gyroscope is in operation to force it to move around axes other than its vertical does require significant force, and in fact this many times slows down the moving part of the gyroscope. What part of this perception is flawed?
Comment: OK, so considering that, with precession redirecting force at 90 degrees when hanging from one end but a gravitational force not actually pulling it down while the disk's speed remains unaffected, doesn't that break the law of conservation of energy? If a net force doesn't result in net motion in the direction it's applied (so a constant force from a spring could do this) then could that precession be harnessed for energy?
Comment: What net force?  $mg$ is pulling down and there is an equal magnitude normal force from the support pushing up.
Comment: But if you had a gyroscope inside a box, supported on one end by a rope and pulled down on the other by a spring towards the opposite side of the box where is the force that causes precession coming from if the spring never moves -- it simply exerts pressure
Answer: In general, energy is not required to change the direction a gyroscope is rotating.  Similarly, it doesn't require any energy to redirect an object with linear momentum either (we don't consider there to be energy transfer when a billiard ball caroms off a cushion).
In the case of the bouncing ball, there's no energy transfer because we consider the wall/cushion to be fixed in place.  So the force applied happens over zero distance.
In the case of the gyroscope, the gyro precesses at right angles to the applied force.  Again, the cross product of the force and the distance moved is zero.
You raised a question in comments about a spring pushing on a gyroscope.  I don't think I understood the geometry.  A diagram might help.

Your diagram shows a spring pulling down, so there is force beyond just the weight of the gyroscope.  We could do the same thing by adding a weight to the unsupported end of the gyroscope.
So the statement that it doesn't take energy to move the axis is correct.  But it does take a bit of energy to start moving it.  (just like it takes some energy to accelerate a ball, but none to keep it rolling, sans friction).  This energy comes from a slight drop in the gyroscope.
The gyroscope falls slightly.  As it falls, it picks up speed sideways.  The greater the downward force, the faster it moves sideways.  The faster it moves sideways, the more it counters the downward force until it reaches an equilibrium.  Lowering the force would reduce the sideways speed.
Comment: Here's a link to a diagram (kind of, made it with a trackpad so it came out pretty bad): http://postimg.org/image/yczpwk0hb/4d9c7fb5/
Answer: This is quite old question, but recently I came across a problem which was describing a setup with multiple gyroscopes that counteract each other and a question of how energy would transfer.
The accepted answer is correct, however counterintuitive it might be. I would like to expand upon it by providing a bit of high level explanation and visual demonstration.
You see, precession and nutation are vital parts of gyroscopic effect, and for them to work, the gyroscope needs to be able to rotate freely in the space. In your setup gyroscopes are rigidly connected to each other and their precession cancel each other out. This would be effectively the same as removing one of degrees of gyroscope's freedom (specifically the one used for precession movement). This leads to gyroscope losing its properties and acting basically the same way as if it wasn't spinning at all.
You may look at it as if you had a force, that was acting directly against precession direction. Such force would have its own momentum, and if you do vector product, this momentum would be aligned with the original force, that caused precession in the first place.
I found an old Soviet demonstration video that clearly shows this effect:
https://www.youtube.com/watch?v=j7IdaK-rERI
At first, the gyroscope's base is locked and can't rotate. When the scientist pushes on the ends of gyroscope axis, it rotates freely with little resistance and slows down due to friction. Then the base is unlocked and suddenly the gyroscope shows strong resistance when attempting to changes its orientation. You may also notice, that in the first half some attempts to push the gyroscope actually DO show resistance and others seem completely effortless. If you look closely, this is because the base is not completely locked and has some slack, which gives the gyro a bit of room for precession, which causes this small bit of resistance.
I hope this will help those who may be interested in this small but very important aspect of gyroscope behavior, which is not discussed in lot of details for some reason


How do I retain good connections with upper management if I do not intend to stay after my internship?

Question: The graduate level, long term internship historically leads to full time employment.  I intend to look for work in a different location within the same field.  When asked directly about my future career intentions how do i diplomatically field questions by upper management who I want to retain connections with?
Comment: Keep in mind that it's less of a big deal for interns to move on than it  is for permanent employees.  Don't overthink this. Thank them for the opportunity to work with them and for all you've learned. Tell them you hope to stay in touch.
Answer: Generally, the exact same way you'd respond if you weren't an intern and were just a regular employee seeking a job elsewhere.  In other words, diplomatically and as far away from 'Here are all the reasons I'm not happy here' as possible.
You're not leaving because of reasons X, Y, and/or Z.  You're leaving because you got a great opportunity with Alternative Inc, where you'll get to do A, B, and C - and you're really excited about it.  You loved working with them at CurrentTech, but you feel the best move for your career development is with Alternative Inc, because you're going to get to learn L, M, and maybe N.  Etc.
If you're asked these questions before 'Alternative Inc' is lined up?  Then you're in the same boat as a regular employee that intends to quit but doesn't have another job yet: don't say anything at all.  Worst case... imagine that the end of your internship rolls around... but you can't find any companies willing to hire you for what you want to do.  You've already announced you don't want to stick around... but don't actually have a new job to go to.
If it helps, think of it this way: the higher-ups you're worried about care a heck of a lot less about this than you do.  Keep in mind, you leaving at the end of an internship is far less of a hassle than a longer-term employee quitting.  As long as you're respectful, professional, and courteous?  Then they're not going to have anything against you.
Comment: I have heard this advice echoed in the site before and it is good to hear it reaffirmed in my case.  It's conducive to talk about the positive reasons you're making a step towards something else rather than the negative reasons you're leaving or escaping something even if all related to the same action.


Bash script to loop over all sub-directories, check existence of a script directory, and run a script there

Question: I'm new to bash scripting and I'm trying to make a script which uses a for loop to find all the folders in the directory where it is started, and then use an if statement to find another folder within them which has a name templates, in which I then want to run a python command to execute python scripts stored in that folder.

My directory structure looks like this:
all/
    this_script.sh
    one/
        templates/
                  render_j2.py
    two/
        templates/
                  render_j2.py

What I've tried for this_script-sh is
for file in *; do
  if [[ "$file"==*"templates"* ]];
  then
    cd $file
  fi
done

and also tried this:
for file in *; do
find . templates
python render_j2.py;
done

My main issue is that I can't enter the templates folder, and even when I can, the python command cant find the python files to run.
Answer: Since you are already using find, why not offload the entire task to it? You could try the following:
find . -type f -path "*/templates/render_j2.py" -execdir python render_j2.py \;

This will search for all files render_j2.py in a directory templates below your starting point, and in the directory where the file was found, execute your python command.
Answer: There's a number of things wrong with this:

Neither version is testing if $file is a directory
When the first version uses cd $file then $file will not be a valid path in the next iteration of the loop, because you changed directories;  putting cd in a subshell (using parentheses) along with things you want to do in that directory would fix this.
In the second version, the find syntax is wrong to do what you want
it doesn't make sense to run find in a loop like this, find does its own loop internally

Something like this might work:
find . -name templates -type d -execdir python {}/render_j2.py \;

This would be equivalent to
(cd all/one && python ./templates/render_j2.py )
(cd all/two && python ./templates/render_j2.py )
...

which still might not be exactly what you want.
Answer: This is kind of a non-answer but this seems like an over complicated setup. If you have an unstated reason you must or just want (to learn perhaps) the loop then this isn't going to be your answer but...You can do this sans loop with the find command.
Something like
find $HOME/my/folders -type d -name templates -exec my.py {} \;

Comment: Almost! It looks like the python script needs to be run from within the directory where the `render_j2.py` is located, that's whythe other answers used `-execdir`.
Comment: These three answers were typed pretty much simultaneously.  I almost included --exec instead of -execdir


How to get the authorization code for Google drive API access programmatically?

Question: I need to download a file from Google drive. I got the code to do that here. In this code they launch a web browser process with an URL which asks user to authorize the API access. After authorization, it provides authorization key which needs to keyed in to our process to actually continue (This is typical oath-2.0 procedure). I want make the entire procedure automated without any user interaction. Thanks in advance.
Comment: try mode = offline and consent = auto
Answer: You can use a service account to get API access without user interaction, however there seems to be no official .NET implementation for it right now.
Someone created a sample here on how to use a service account with Google Analytics in C#.


Magento 2 bespoke category page.

Question: Is it possible to create a bespoke category page with only select filter options that won't affect other category pages?
Answer: You could make a CMS page containing a 'Catalog Products List' widget. This widget allows you to specify a set of conditions with which to generate a grid of applicable products.

Magento 2 bespoke category page.


Binary subtraction with numbers in 2's complement

Question: How can i perform binary subtraction of two numbers that are already in 2's complement?
I have to subtract 01010011 from 10100110,both numbers are in 2's complement.
I know that 10100110 is -90,and 01010011 is 83,so the result should be -173.
So if i use 8 bits that means that there's overflow.
But i don't get how can i perform the subtraction when both the numbers are in 2's complement.
If i just perform the subtraction i get the same number 01010011. How do i show the result and that there's overflow?
Answer: You cannot represent –173 using 8 bits, since the range is –128 to 127.
To subtract two numbers in two's complement, you use the identity $a - b = a + (-b)$. In your case, $a = 10100110$, $b = 01010011$, and $-b = 10101101$. Adding $a$ and $-b$, there is overflow, so you know that the number is outside the range.
Answer: You need to subtract 01010011 from 10100110.
10100110 - (01010011)
So find the 2's complement of 01010011 which is 10101101 and just add it to 10100110
<code> 01011000   <=carry bits

 10100110
+10101101
----------
101010011 <= Result, but the extra 9th bit to the left of MSB is stored outside a register in a special carry out flip-flop

</code>
Now the carry-in and carry out of the MSB of the 8 bit register are different and so the result is overflow... (the carry in is 0 ,above the two 1's in the MSB and the carry out is 1 which is left to the MSB in the result)
If and only if the XOR of the carry-in and carry-out of the MSB is 1 then overflow.


Add Watermarks when Files are Opened or Downloaded in SharePoint 2019 on-premises

Question: Can I Add Watermark contains "user information" when Files are Opened or Downloaded in SharePoint 2019 on-premises. I need the best solution for this and if anyone use third-party tool to achieve this requirement. Please Advise
Answer: You could add the related column as a label in information management policy to document content type, when you open, download or print the file using this content type, the label will exist.
For detailed information, please refer to follwoing article, this is a sample about displaying version column, you could change it to createdby column.
https://www.ilikesharepoint.de/2014/06/sharepoint-display-sp-version-number-in-a-word-document/


Who will win, 2 pairs on the table or one pair in hand and one pair on the table?

Question: Table: 7, 7, 6, 6, 4
Me: 5, 4
Opponent: 9, 8
Who  wins?
Comment: @TobyBooth If "Top five cards" as a rule covers EVERY possibility" then it cover full house.  No need to get confrontational.  You got my input.
Comment: But this is not duplicate.    This is not a split pot.  This has a kicker.  The duplicate does not have a kicker.   This site needs a good answer on order of hands rather than a narrow *catch all*.
Comment: @Frisbee The suggested question to review, and many subsequent answers definitely cover the concept required to answer this question. The concept is the stated here as the "Top Five Card" rule. It applies to this case too. To Tatiana, check it out. You'll find what you're looking for there.
Comment: @TobyBooth Cool  but the link does not address two pair. Based on "concept"  I don't get how a full house question http://poker.stackexchange.com/questions/6673/full-house-highest-trip-or-card would not be a dup.  It is just a polite feedback - not meant to criticize.
Comment: @Frisbee Personally, & particularly at this stage of the sites development, it's a flexible policy. I'll try to explain my reasoning. If a question is from a newer user, is well formatted, is a little different from other similar Q's in terms of content, I often decide to leave it open. I'd like these new users to gain some reputation points, get their answer, & continue to use the site more in the future. Closing all duplicate Q's doesn't seem productive in that sense. In the future, better more comprehensive answers will inevitably rise beyond these types of Q's. It's an evolving process.
Comment: @Frisbee RE: your Two Pair comment, [this](http://poker.stackexchange.com/a/405/88) answer covers that possibility. "Top five cards" as a rule covers EVERY possibility. Obviously this example is Texas hold 'em. Other games will vary. If it's still not clear, and you don't think there is a definitive answer... or question about this, please write one up :)
Answer: Best 5 cards every time
Your 4 does not play because it is lower than the 2 pair on the table
You:  7, 7, 6, 6, 5
Opponent : 7, 7, 6, 6, 9
You lose because your opponent has a higher kicker
If the board was J, 7, 7, 6, 6 you both would have played the board and it would be a tie = split the pot
WIKI list of poker hands
Answer: Either the pair in hand (if that is bigger than at least one of the community pairs) or if it is smaller than both of them, the 5th card will come into play.
So, your opponent by 5th card "9" wins in the scenario given.


Can I mimic Arduino Ethernet library through serial?

Question: I'm ordering an Ethernet Shield for a project I have planned, but before make the investment, I want to make sure the project will work. Eventually it will communicate with a website via ethernet, but I was wondering if I could test this through my PC, using it simply to route page requests, so that I can easily adapt it for the ethernet shield.
Answer: I'm not sure if the Arduino can do it, but you can look at the possibility of implementing SLIP. It's designed to layer TCP/IP over serial communications.
You can configure a PC as the SLIP server, for the device to login and route packets through.
Edit: Turns out there's an Arduino SLIP library that does that exactly!
Comment: That does look like my best option. I tried it out but I couldn't get it to show up on my network, and I can't ping it. My PC is running Ubuntu, and I followed the instructions. I don't know what went wrong.
Comment: can't help you there as i dun use the arduino. however, SLIP is the technique used.


Keep track of all files accessed by a specific process?

Question: There has recently been a (publicly unconfirmed) report that Skype is accessing files that it shouldn't be, without user intervention. I have no idea if this is the case with Skype on linux, but it would be good to be able to find out. Is there a way to keep track of all files accessed by a specific process?
Answer: Given the PID of the Skype process, you can do:
for fd in /proc/$skype_pid/fd/*;do
    echo -n "File descriptor $fd points to "
    readlink "$fd"
done

For a given process, /proc/$PID/fd contains symbolic links to all the files the process currently has open. The links are named after the file descriptor number. So, to find a out where a process is getting its stdin for example, you can readlink /proc/$pid_of_process/fd/0. The above will tell you about all files opened by the Skype process.
If you're not sure about the PID of your process, try
$ pgrep skype

first to find out.
This will only work on systems that have a procfs, of which GNU/Linux is one.
Answer: Launch your process through strace:
strace -fe open skype

You will see the list of each open() syscall, that is every file (or connection) the processes opens during its life.
Looking at currently opened file descriptors will not provide a log but only a "snapshot" of what the process accesses right now.


How to make Unity 2D workspace button trigger Compiz expo view mode?

Question: I am using Unity 2D with Compiz. And I want the workspaces button to trigger the expo view mode in Compiz. Can anyone help me?
Answer: For the record, Unity 2D should work with Compiz too. There very likely is some glitches here and there as the developers of Unity 2D do not spend time testing with Compiz but only with Metacity.
Answer: The workspace button won't do the trick, but you can add to the launcher bar a custom button that will trigger the compiz Expo effect (thanks to Andrew from webupd8.org ).

Install xdotool (and compizconfig-settings-manager if you don't have it already) by typing in a terminal:

sudo apt-get install xdotool compizconfig-settings-manager

There is also a unity 2d tweak program, from which you can enable compositing and some other tweaks for unity 2d:

http://marianochavero.wordpress.com/2011/04/20/a-simple-gui-for-unity-2d-settings-ubuntu-11-04/

Start Compiz Config Settings Manager and set up your desired compiz effects and keyboard shortcuts.
WARNING: Do NOT enable the desktop cube or the Unity plugins, as these will break the classic session. (enabling desktop cube disables all compiz plugins together with all their settings). Switching the compiz profile to "unity" instead of "default" inside the Preferences section of Compiz Config Settings Manager also breaks the classic session.
Make a expo.desktop shortcut to launch the following command:

xdotool key --clearmodifiers super+s

This will start the Expo effect. Replace super+s with the actual keyboard shortcut if you changed it. (And you can use the same procedure for other effects - I use also another launcher to trigger super+w, the Scale plugin)

You can also find a ready-made desktop file in the original post:
http://www.webupd8.org/2011/05/create-custom-unity-launcher-to-trigger.html
Answer: You can't. The whole point of Unity 2D is for use without Compiz. If you want Compiz support, use Unity 3D.
Answer: Use Unity 3D (instead of unity 2D, if you are using compiz).
Comment: @Evan, not that surprising, some of the older cards lack features needed for unity 3D. You could file a bug report on Unity 2D, but it's unlikely to be added as a feature.
Comment: unity 3d doesn't work with my very old ati graphics card
Comment: but surprisingly compiz does