Is there anyway to automate to publish all files in one instant?

Question: In my project we are accessing Tridion to publish the JS and CSS files, but in order to maintain consistency we need to publish all the required files every time. Is there any way to automate this, so that when run all related files in Tridion get published?
Comment: I would consider moving CSS and JS out of the CMS and making it part of web application deployment. On all projects I have worked on this has significantly reduced release management headaches
Answer: If you're using SDL Tridion 2013, yes: you can add all items to a bundle, and publish the bundle.
If you're using any version prior to 2013, the only way I can think of is to have a template that publishes all those items as part of the same transaction.
Answer: In another project we created a schema called 'Site Assets' here all site assets like css icons, stylesheets, js, ico files etc we're embedded into this component.
The scheme was then linked to a dynamic component template that contained the logic to push the items to a specific location (Structure group).
This helped the technical users in the system keep track and published all items in a single go.
Comment: I'd agree with Nuno that the bundle is the best way to go, i'd propose the above solution pre 2013.
Answer: Pre 2011 you could use the event system to detect one of the items being published and publish the others that way.
2013 a bundle is the best way....
Answer: Depending on how your CSS and JavaScript publishing is currently implemented, it may be worth investigating using a Custom Resolver.
From the online documentation (login required):

Customizing the resolving process involves manipulating the list of
  items to publish that results from a publish action.

Using a Custom Resolver, you could ensure that if a CSS or JavaScript file is published (from a specified Folder or Structure Group), then all of the other CSS and JavaScript files are also published.
If you use a Bundle in Tridion 2013, then there is still a risk that you publish just one of the JavaScript or CSS files (rather than the whole Bundle) and that things get out of sync.
Answer: on Tridion 2011, another way is to automate publishing process by CoreService API, you can read a predefined list file, or a UI to input a list, a background process to publish them on a schedule. let me know if you have any question to build.
Comment: Whilst it's possible, it would be nice that this is automatically managed, rather than scheduled, for example if a user publishes content, then has to wait for a schedule to run
Comment: yes, this is another option for UI based application, click to run an batch process, publish anything direct or indirect, or upon some business logic or dependencies. this is very customized way to automate publishing process.
Answer: If you are managing the css and javascript as binaries, I would go with a TBB at the end of your Page Template or Component Template (depending on how you trigger the publishing) and let that TBB take care of adding the "required" binaries to the package and publish them along with the others.
I am suggesting the use of a Template Building Block because (in my opinion) is the easiest and least intrusive way of accomplishing it.
Then the challenge would be to identify/define  which items should go together within the same publishing transaction, i.e. defining the publishing rule.
Once you figure that out it is a matter of organizing your binaries, for example, you could put them in a folder and publish any of the items in that folder will trigger the publishing of all the items in such folder; you could also have a page where you drop all the binaires as component presentations; you could use a bundle, you could use metadata to associate them, etc...
Comment: Maybe easiest and least intrusive, but the prospect of publishing JS/CSS as binaries is appalling. I would definitely stay away from it! Rather, implement Will's suggestion and move all JS/CSS outside of Tridion.
Comment: I think this would require quite some work to ensure publishing isn't automatically publishing binaries with each item.  Imagine publishing 3 pages and with each page the binaries are deployed, that would be a lot of extra publishing for no reason
Comment: It is just an option. I don't think publishing css/js as binaries is appalling, it depends on the requirement and/or implementation, maybe as part of the continuous integration process the css/js are automatically uploaded to the CMS and then published. And remember that Tridion supports by default the references to js and css using tcm links. That said, I'd only publish css/js as pages or component presentations if I need to modify their contents at publish time, otherwise, the binary is the way to go, as long as you want tridion to take care of the css/js deployment.
Comment: @johnwinter, the whole css/js publishing needs to be analyzed and implemented properly, as you say, you don't want your package for each page to contain all the binaries over and over, that's why you use, experienced consultants for these things :)
Answer: There you go, Rupesh. You got 6 answers (7, if you include Will's suggestion) so far. Let me give you the 8th :) I hope you're not overwhelmed.
I would go for a combination of event system and structuring your website in Tridion Content Manager.
1) The structure would imply grouping together all your JS/CSS under a common Structure Group. For example, you could have the following:

    + Root
        + Assets
            | JS
            | CSS

2) The event system would intercept the publish of a JS or CSS Page or Component and it would resolve the Structure Group where it belongs to (e.g. JS). It would then take the parent SG (i.e. Assets) that is in fact the common SG for all JS and CSS Pages and it would publish that Structure Group.
This would ensure that all JS/CSS would be published together in one transaction. Optionally, you could fail the initial publish action on the JS/CSS individual Page/Component.
Comment: Why use an event system when I can use a TBB? :)
Comment: because you should not implement a bad approach, just for the sake of simplicity in coding :)
Comment: For me, both, Event System and Templating are equally simple (or complex). I disagree Mihai.


If Superman died on Earth, would his body decompose?

Question: If Superman died on Earth, would his body decompose?
Comment: It seems to me that there is a direct correlation between his relative invulnerability (and power derived from the Sun) and biological immortality. I wonder if he can even die of natural causes.
Comment: @Paperjam: Mmm, reminds me somehow on the fact that in the *Luis and Clark* TV series he needed to use its own heat vision, reflected by his bathroom mirror, to shave his beard. Anyway, if you would get buried with a rock of kryptonium ...
Comment: "If Superman died on Earth" - [if?!?](http://en.wikipedia.org/wiki/The_Death_of_Superman)
Answer: He gets his powers and invulnerability by metabolizing the light from our yellow sun. If he is no longer alive, then his body won't be metabolizing that energy. In Tow of Babel for example this is exploited.
I don't think there has ever been evidence to suggest that the yellow sun affects his cells directly regardless of if he is alive or dead.
So, if Superman was dead and not metabolizing, he would then not have his powers, so I would expect he would decompose in the normal way Kryptonians decompose.
Answer: Alright, let's say he dies (Kryptonian cancer).
I'm not going to talk about his soul, so let's assume that the soul isn't an agenda here.
The absorbed sunlight in his body would still power a great deal of his cells, so it would take him some time if not years, to actually die (that is, if DC doesn't find a way of saving him again).
His Kryptonian cells would slowly vaporise, so his body wouldn't have the same odor as of a human body. So in short, he would pose as a giant energy container waiting to burst.
Having all this energy in one spot (presuming he is still in one piece), he would be like a dwarf star imploding into a black hole (there are also other possibilities here, turn into a neutron star, a magneter, burst/explode). What would happen to Earth and the human kind?
However, if I'm not correct and his organs really somehow decompose. His body would emit an amount of thermal radiation (an effect known as Hawking radiation), in the end leading to evaporation of his body.
Comment: This seems like non-canon conjecture with garbled physics concepts.
Answer: I know I'm kinda late to the party on this one, but if you're willing to accept an answer from the DCEU:

 At the end of Batman v Superman: Dawn of Justice, Superman dies. When his corpse is later recovered during the events of Justice League, enough time has passed that it should have started to decompose, but instead it's in seemingly-perfect condition. Bruce Wayne even predicts that Superman's corpse won't have decayed (though I can't remember his reasoning).

From that evidence, he would decompose either much slower than a human corpse, or not at all.
Comment: I haven't been able to find an exact figure, but somewhere in the region of 12-18 months. I might as well ask that in a separate question.
Comment: How much time, exactly, had passed before his body was found?


Can we move mouse cursor by keyboard command in Ubuntu?

Question: Suppose my mouse suddenly get died while working on a live web page. But my mouse cursor is present there. Now can I move the cursor by keyboard command and , select any option on that web page?
Answer: If you indeed want do that from the command line, then you can install xdotool (it is packaged in Ubuntu 16.04 at least) and issue commands like this:
xdotool mousemove 10 500 && xdotool click 1

Answer: While not exactly what you want, most applications (including your browser) can be fully controlled by a keyboard.  For example, use the Tab key to jump from a highlighted text to another, type space to activate a link.  With Pgage Up and Page Down you can scroll within the page.   To access the menu hold Alt, the underlined letters are the shortcut to activate the corresponding menu.  For example Alt with F opens the file menu and then you can navigate the menu with the arrow keys.
That said, if you really need to activate the Mouse Mode, you can do that as described in the wiki.
Comment: I wanted to say if I could move my mouse cursor symbol by keyboard command?
Comment: I understood that.  See the wiki entry I linked to.  I gave you two solutions to the problem you have: the inability to move a mouse cursor.  I gave you the first one, because knowing how to navigate computer programs without a mouse is a fundamental part of computer literacy.
Answer: I don't know what browser are you using, but there is an add-on in mozzila called vimkeybindings, so that will give you a possibility of using vim key to navigate your browser, on crome this tool is called vimium.
This is from the small docs:

About this Add-on Vi(m) directional keybindings for Firefox.
h : scroll left
j : scroll down
k : scroll up
l : scroll right
g : go to the top of the page
G (shift-g) : go to the bottom of the page

Answer: while your mouse in a specific app might be frozen because the app itself is frozen or for other reasons, a simple solution in desktop environment which at least allows you to switch between apps is Alt-Tab. Like mentioned before, if you can't Cntrl-Tab (or similar motions) inside your app, I think probably you won't be able to click with mouse in this app even if you controlled your mouse with keyboard


Are airplanes involved in defense if they are on an aircraft carrier?

Question: In AAA, if you are defending against a sea attack, and you are defending with an aircraft carrier, do the airplanes on the carrier contribute to the battle or are they considered cargo? The rulebook doesn't seem to define a specific rule for this scenario.
Answer: The air units that are on an aircraft carrier participate in the defense, they are not considered cargo. On page 20 of the rulebook under Order of Play.

Air Units: A given air unit may participate in the sea combat or the land combat portion of the amphibious assault; it may not do both. The attacking player must declare the air units involved in the land and sea combats and cannot change their assignments later. Attacking air units, whether involved in the sea or land combat, may retreat
according to the normal rules. Defending fighters on aircraft carriers can defend only in the sea combat. Defending air units in a territory can defend only in the land combat.

And in the Appendix (page 30) under Aircraft Carrier, or (page 27) under Fighter the example image.

The Sinking of a Defending Carrier: The attacking Japanese submarine sinks the U.K. carrier, then submerges after the defenders Fire. Both the U.S. and U.K. Fighters can Fly 1 space to safety. They can land at New Zealand (a friendly territory), or on the U.S. carrier (a friendly carrier). Otherwise they are destroyed.
Fighter Defense: Whenever a carrier is attacked, its fighters (even those belonging to friendly powers) are considered to be defending in the air and can be chosen as casualties rather than the carrier. (However, a fighter can't be chosen as a casualty from a submarine hit, because submarines can attack only sea units. See Submarines, on page 32.)

and from the online FAQ:

If my fighters are on an ally's carrier, when do they move and fight?
Your fighters move along with the carrier when it moves. They can't fly out to attack on your ally's turn, but they fight normally if the carrier's sea zone is attacked. If the carrier moves into an enemy sea zone to attack, however, your fighters can't be part of the attack but they can be taken as losses, if you agree to sacrifice them.
Answer: Depends on your version. I am playing the 1981 version where the rulebook has 31 numbered pages not including the back cover. There is a misprint on page 13 in the illustration showing where a tank can and cannot blitz (The tank cannot blitz in either illustration as there is an industrial complex preventing blitz).
On this page, (p.13), under "Aircraft Carriers: "...Fighters belonging to a friendly power on board another power's carrier (guest fighters) must remain on board as cargo in the carrier moves in this phase. (Combat Movement) They cannot take part in combat and are destroyed if the carrier is destroyed."
That seems to refer only to attacking, as on page 26, under "Aircraft Carriers" it states: "...Fighter Defense: Whenever a carrier is attacked, its fighters (even those belonging to friendly powers) are considered to be defending in the air and fight normally..."
So there you have it: All fighters on aircraft carriers DEFEND but only fighters which belong to the same power as the aircraft carrier may ATTACK.
You could also choose to have the fighters fly to another battle or location away from the battle and return to the aircraft carrier (if it is still there!) after battle resolves.


Can anyone identify this drupe fruit & seed?

Question: This fruit & seed was given to me to identify -no leaves etc. Fruit is 4cm (1 inch) long, 3cm wide. Ribbed seed 3cm long with 1 seed per fruit. Drupe fruit flesh is brownish inside & faintly apple scented -it's mid August (late winter in New Zealand) so probably bletted. Phyllis
Comment: Thanks Michelle - I just looked online for Eleagnus varieties and think it is probably Elaeagnus x ebbingei. The colour of mine is darker and browner than described but, as I said, I think it is over-ripe and bletted. The unusual ribbed stone certainly looks like this Eleagnus.
Comment: It looks like an Elaeagnus fruit, but I'm not certain which one. Do you have any more info on or pictures of the shrub it came from?
Comment: No sorry-  an acquaintance walked out in town streets at lunchtime, came back with this fruit and seed and asked another friend what it was - she gave it to me! The flesh is quite soft inside.
Answer: It looks like a jujube.
I had a difficult time identifying this fruit for my parents as well. The fruit starts to grow as a green color. As it ripped it turns brown although at a distance the drupe looks red.
I hope this helps.
Comment: Thanks Nancy for your comment. I've looked online and feel that though there are similarities with my fruit, the blotches are much larger than the regular darker spots on my fruit and the stem ends are different. I still tend to think mine is an Eleagnus.


How to extract zip code from reverse geocoding in PostGIS

Question: I have a bunch of lat/lng coordinates that I can reverse geocode, after having installed PostGIS and the relevant Tiger files.
I throw in a query like this:
select reverse_geocode(ST_Point(lng, lat))
from plus_viewable
limit 5

And so far, get results like the following:
({0101000020AD10000041F2CEA10C2055C08AE76C01A1F54040},"{""(1343,,Franklin,Dr,,,Marietta,GA,30067,)""}","{""Cobb Pkwy S""}")

I just need to be able to extract the zip code.
How would I be able to do that?
Answer: You pull in the ZCTA, and then you do a point-in-polygon search on it with something like ST_Intersects.
These isn't exact, but because the USPS doesn't release a dataset it's as good as you can get. It's good enough for the Census for what it's worth.


KVM-QEMU Migration Code

Question: My lab setup is: 3 HP Servers each of 4 GB RAM. Server 1 and Server 2: installed with Virtualization using KVM on Redhat 6.5 System. On top of this I am using libvirtd for managing virtual machines. NFS server is installed on Server 3 for shared disk image. VM migration is working correctly. Now i need to do some changes in "migration.c" but did not find any source code of KVM-QEMU migration.
Where I can find the migration source code for KVM-QEMU. All are requested to help me for this issue.
Answer: kvm is a kernel module in linux. now you should download and compile qemu source code. follow this link to do that :
https://wiki.qemu.org/Hosts/Linux
.when you install libvirt, it will install qemu too, but for changing migration code you need to build qemu yourself.
migration code is available in qemu source code too.
good luck

KVM-QEMU Migration Code


Calculate charge time of a capacitor through a current limiting power supply?

Question: Is there a formula or a way to calculate Charge time of a capacitor given that it is charged by a current limiting power supply. This would lengthen the charge time but is there a way to calculate this due to the power supply limitations. Let's say that we are charging a 1uF Capacitor to 5,000VDC through 20kOhms of resistance in series.
Comment: I realize it is just an example, but I'd be a *tiny little bit* careful when charging capacitors to 5kV on your work bench. Otherwise good question.
Answer: As it is not a piecewise continuous system, you'll need to calculate, in two steps:
First: you'll need to calculate the time of charging the capacitor until it reaches
$$ (Vb-Vc)/R = Imax $$
with constant current of Imax.  if the current is constant that capacitance does not change this is a simple straight ramp curve upto the point where the current is no longer limited by the constant current.
Second: you can use the equations for power supply without limited current power supply.
Which are the exponential curves from that point onward to the asymptote.
Comment: This is not an answer. You should comment to my answer instead.
Comment: OK. My fault... but I can't comment yet.
Comment: Jean this is a perfectly good answer, and you're welcome to create your own.
Comment: @rawbrawb: Camil's complaint was about a comment I made to him (in my answer, since i could not comment others commentaries yet) that there was a current limitation, then Imax could not be Vb/R. I edited the answer then.
Comment: @JeanWaghetti I edited your answer, if you don't like please rollback, just some feedback.
Answer: No, there is no formula to calculate charge time of a capacitor. Or yes, there is: \$t_C=\infty\$: the capacitor will never get 100% charged. What you can do is calculating the charge on a given moment, as shown here:

Specifically interesting is the formula for Q as shown in the graph:
$$Q=CV_b(1-e^{-\frac{t}{RC}})$$
We have \$C=0.001F\$, \$V_b=5000V\$ and \$R=20000\Omega\$. We can calculate our time constant, \$RC=R\cdot{}C=0.02s\$. Our formula now is:
$$Q=0.001\cdot5000\cdot(1-e^{-\frac{t}{0.02}})=5\cdot(1-e^{-\frac{t}{0.02}})$$
We can rewrite this so that t becomes a function of Q:
$$t\approx-0.02 log(0.2 (5\cdot-Q))$$
Now, just fill in the charge you want to reach and you'll get the time needed.

As rawbrawb mentions in the comments, we generally use as a rule of thumb that the capacitor is loaded after 5 to 6 time constants. So, in your case, that would be 0.1 to 0.12 seconds.
Comment: In a purely mathematical sense, yes charge time is \$ \infty \$ but the general rule of thumb is 5 to 6 time constants.  Because in reality there are noise floors or even the precision of the system.
Answer: If it is a normal PSU with a current limiter then your cap will charge linearly. Think of it as charging a cap with a current source.
$$Q = C\cdot{}U = 1\mu{}\textrm{F} \cdot{} 5000 \textrm{V} = 5\textrm{mC}$$
$$ t_{charge} = \frac{Q}{I_{lim}}$$
Assuming 250mA current limit (\$5\textrm{kV}/20\textrm{k}\Omega{}\$) your cap will charge in approximately 20ms.
Comment: 20ms is only true when there is only current limiting and no series resistance.


How to convert 9v supply to 5v?

Question: I am making half adder circuit for my school project but I saw their datasheet and it says maximum supply volate is 5.25v and I have 9v battery, How do I use it if I want to test my circuit without burning ICS?
I watched this video to complete my project but he didn't specify the battery he used. Pls help
Video link -: https://youtu.be/rNG_KD1hfpc. Thank you
IC I used : Ic 7408(SN74LS08N) , IC 7432 (SN74LS32N), IC 7404 (SN74LS04N) . thank you
Comment: In fact the first answer to this question should tell you all you need to know: [Reducing voltage with resistors](http://electronics.stackexchange.com/questions/127525/reducing-voltage-with-resistors). Took all of 10 seconds to find using the search box at the top.
Comment: Google "Voltage Regulator".
Answer: For low power load applications (such as your case) you could use voltage regulator
https://www.soselectronic.com/productdata/17/71/6/17716/L78S.pdf
For more demanding devices use switching step-down regulator
https://www.soselectronic.com/productdata/93/80/4/93804/ltc1767.pdf
Take the links as example only.
Answer: Instead of building a power supply to convert 9V to 5V, there are other alternatives.  You can get a 5v wall mount PS at your local supermarket for about $10.  That is, don't use batteries, but, if you must, your circuit will probably work with three 1.5 volt batteries in series.  A real longshot solution would be to use different ICs.  The original 4000 series CMOS ICs worked with Vdd 5 to 15 volts and many types are still available. They might be hard to find, and they probably would have different pinouts.

How to convert 9v supply to 5v?


PowerShell: Store Entire Text File Contents in Variable

Question: I'd like to use PowerShell to store the entire contents of a text file (including the trailing blank line that may or may not exist) in a variable. I'd also like to know the total number of lines in the text file. What's the most efficient way to do this?
Answer: On a side note, in PowerShell 3.0 you can use the Get-Content cmdlet with the new Raw switch:
$text = Get-Content .\file.txt -Raw

Comment: @MatteoSp `Get-Content` did, but it wasn't until 3.0 that it got `-Raw`. Without that, it gets stored as a array of lines.
Comment: This is should be the accepted answer. By the way, I'm pretty sure Get-Content worked even in earlier versions.
Comment: This does not fully answer the original question (needs to add how to calculate line numbers).  It is a useful piece of information though.
Comment: This should absolutely be the accepted answer. It doesn't help that the [documentation](https://technet.microsoft.com/en-us/library/hh849787.aspx) says that the `-Raw` parameter isn't implemented by anything native.
Answer: To get the entire contents of a file:
$content = [IO.File]::ReadAllText(".\test.txt")

Number of lines:
([IO.File]::ReadAllLines(".\test.txt")).length

or
(gc .\test.ps1).length

Sort of hackish to include trailing empty line:
[io.file]::ReadAllText(".\desktop\git-python\test.ps1").split("`n").count

Comment: Thanks! `$content = [IO.File]::ReadAllText(".\test.txt")` appears to do the same thing as `$content = (gc ".\test.txt" | out-string)`. Since the second of the two is shorter, that's what I prefer.

Unfortunately, neither of the methods you provided for calculating the total number of lines takes trailing blank lines into consideration. Any other ideas?
Comment: @Nick In .Net (and windows), any line with `\r\n` will be counted.
Comment: I was doing some experimenting and came up with the same thing as your updated answer, but I wouldn't have gotten there without your help, so thank you so much!
Comment: Is there a way to transparently combine this with `Invoke-WebRequest`?
Answer: Powershell 2.0:
(see detailed explanation here)
$text = Get-Content $filePath | Out-String

The IO.File.ReadAllText didn't work for me with a relative path, it looks for the file in %USERPROFILE%\$filePath instead of the current directory (when running from Powershell ISE at least):
$text = [IO.File]::ReadAllText($filePath)

Powershell 3+:
$text = Get-Content $filePath -Raw

Comment: To use relatives paths, resolve it first eg: `[IO.File]::ReadAllText((Resolve-Path $filePath))`
Answer: One more approach to reading a file that I happen to like is referred to variously as variable notation or variable syntax and involves simply enclosing a filespec within curly braces preceded by a dollar sign, to wit:
$content = ${C:file.txt}

This notation may be used as either an L-value or an R-value; thus, you could just as easily write to a file with something like this:
 ${D:\path\to\file.txt} = $content

Another handy use is that you can modify a file in place without a temporary file and without sub-expressions, for example:
${C:file.txt} = ${C:file.txt} | select -skip 1

I became fascinated by this notation initially because it was very difficult to find out anything about it! Even the PowerShell 2.0 specification mentions it only once showing just one line using it--but with no explanation or details of use at all. I have subsequently found this blog entry on PowerShell variables that gives some good insights.
One final note on using this: you must use a drive designation, i.e. ${drive:filespec} as I have done in all the examples above. Without the drive (e.g. ${file.txt}) it does not work. No restrictions on the filespec on that drive: it may be absolute or relative.
Comment: I have never got this to work unless I put a backslash after the drive name.
Comment: @CharlesAnderson: It is not clear which of the three examples you are referring to, or perhaps all of them... nonetheless, I just confirmed that all 3 work with a relative path (i.e. no backslash) in PowerShell V3. Further, at the time of my answer I was using V2, so perhaps there is something else causing an issue in your environment.
Comment: I meant examples like ${C:file.txt}, which I have to write as ${C:\file.txt}. Yes, I presume it is something about my environment, but I have no idea what.
Comment: When using as L-value, it uses the system's default encoding.
I tried to set $OutputEncoding with no effect.

When using as R-value, it produces a string[] array.
Comment: It seems you can only use a literal pathname; you can't use a variable or something like a Join-Path expression inside this. Which is annoying, because when piped through ConvertTo-Json, there is a world of difference compared with Get-Content (and the ${...} result is what I was hoping for. I'm not sure if this is the same as Get-Content | Out-String though
Comment: @CameronKerr Yes that seems to be the case. I might just edit this answer to note that.
Comment: How do I get this to work on a filesystem that doesn't have drives, like on UNIX systems? I'm using Powershell 7.2.5 on Linux. Thank you.
Answer: Get-Content grabs data and dumps it into an array, line by line.  Assuming there aren't other special requirements than you listed, you could just save your content into a variable?
$file = Get-Content c:\file\whatever.txt

Running just $file will return the full contents.  Then you can just do $file.Count (because arrays already have a count method built in) to get the total # of lines.
Hope this helps!  I'm not a scripting wiz, but this seemed easier to me than a lot of the stuff above.
Answer: Read binary file:
This is not exactly what was asked, but some might find this useful for their use case anyway. Get-Content -Raw yields a string, so if you want byte[]:
Get-Content c:\file.bin -Encoding Byte -ReadCount 0

-Read-Count tells how many lines go through the pipeline at a time (default is 1), and 0 does everything in one operation which boosts performance.
The credits shall go to Shay Levy who has published this solution: (see Shay's post here)


How are bond angles determined?

Question: Electron microscopes cannot clearly depict the exact shape and structure of atoms and molecules, even though it does show a vague, cloudy image. In my AP chemistry class, I learned that the bond angle of some molecules is 109.5 degrees. How is this bond angle determined so precisely, if the bonds cannot be accurately observed through a microscope?
Comment: https://en.wikipedia.org/wiki/Molecular_geometry
Answer: The positions of atoms respective to each other in a crystal lattice (solid) can be determined by X-ray crystallography. From these positions bond lengths and bond angles can also be calculated accurately.
Probably the most memorable case of solving the geometrical structure of a molecule was Franklin and Gosling's X-ray crystallography of DNA, information later used by Watson and Crick to solve the mystery of DNA's structure.
For many simple (binary) compounds molecular shapes and bond angles can also be determined theoretically (see link).
Comment: I'd like to add that bond angles (as well as bond lengths) of (simple) molecules in the gas phase can be determined by rotational spectroscopy. When one takes the rotational spectrum of a molecule, one can determine the rotational constants that depend on the masses of the atoms and the relative positions of the atoms. When one or more atoms are substituted by another isotope (e.g. D for H) the Born-Oppenheimer approximation tells us that the relative positions of the atoms in the molecule do not change (in the electronic SE all nuclei are considered to be of infinite mass to first order).
Comment: The rotational constants do change of course and from the change in those the relative positions can be determined. Of course, the bigger the molecule, the more substitutions are needed. The equations needed are called the Kraitchman equations.
Answer: We use valence-shell electron-pair repulsion (VSEPR) model to predict the geometry of covalently bonded molecules and ions. After the predicted model and angles are determined we perform calculations using the non-relativistic Schrodinger equation based on the vibrational modes of the molecule and compare those to the spectroscopic data for agreement.
Quoting from this tutorial,

The VSEPR model can be explained in the following way. We know that an atom has an outer shell of valence electrons. These valence electrons may be involved in the formation of single, double, or triple bonds, or they may be unshared. Each set of electrons, whether unshared or in a bond, creates a negatively charged region of space. We have already learned that like charges repel each other. The VSEPR model states that the various regions containing electrons or electron clouds around an atom spread out so that each region is as far from the others as possible.

You mention an angle of 109.5 degrees. This angle refers to Structures with Four Regions of High Electron Density around the Central Atom.
The following Lewis structures show three molecules whose central atom is surrounded by four clouds of high electron density:

Image source
Quoting again from here,

These molecules are alike in that each central atom is surrounded by four pairs of electrons, but they differ in the number of unshared electron pairs on the central atom. Remember that, although we have drawn them in a plane, the molecules are three-dimensional and atoms may be in front of or behind the plane of the paper. What geometry does the VSEPR theory predict for these molecules?
Let us predict the shape of methane, CH4. The Lewis structure of methane shows a central atom surrounded by four separate regions of high electron density. Each region consists of a pair of electrons bonding the carbon atom to a hydrogen atom. According to the VSEPR model, these regions of high electron density spread out from the central carbon atom in such a way that they are as far from one another as possible.
You can predict the resulting shape using a styrofoam ball or marshmallow and four toothpicks. Poke the toothpicks into the ball, making sure that the free ends of the toothpicks are as far from one another as possible. If you have positioned them correctly, the angle between any two toothpicks will be 109.5°. If you now cover this model with four triangular pieces of paper, you will have built a four-sided figure called a regular tetrahedron. Figure 7.8 shows (a) the Lewis structure for methane, (b) the tetrahedral arrangement of the four regions of high electron density around the central carbon atom, and (c) a space-filling model of methane.

Image source
Once you predict the appropriate bond angle from the VSEPR model then based on this model, one can begin to perform calculations of energy associated with different vibrational modes of the molecule using the non-relativistic Schrodinger equation.
One then compares those results to those values observed in spectroscopic data that verify that the model is correct.
Comment: `@`StarDrop, note that when using text or images directly from other sites, the very least you can do is acknowledge the source and cite it. You should ideally also check that the content is appropriately licensed, but it is good scholarship to acknowledge your sources.

How are bond angles determined?


LU decomposition implies Gaussian Elimination without pivoting

Question: If Gaussian elimination can be carried out without pivoting for A, then A has an LU decomposition. Is the converse true: if A has an LU decomposition, then Gaussian elimination can be carried out (in exact arithmetic, disregarding stability issues) without pivoting? If yes, can somebody explain carefully why this works in the other direction as well? Im new to numerical methods, thanks.
Answer: Look at the construction of LU. You're basically doing the Gaussian elimination (forward step) and computing the elements of L and U along the way. Thus, having L and U means that you can do the forward step of Gaussian elimination.
Answer: Gaussian elimination and LU decomposition are a single method ! The only difference is that LU stores the elimination coefficients in the zeroed triangle of the matrix, so that no information is lost (the original matrix can be reconstructed). But the elimination itself is the same.
If pivoting is used, permutation information must be kept as well to restore the original order of the unknowns.


How to set up cloud image in VirtualBox?

Question: I would like to turn the disk image from a cloud image (former UEC image) into a bootable VirtualBox (for Vagrant). I can run the image in kvm (using https://help.ubuntu.com/community/UEC/Images as a starter), but how can I turn the .img disk file into a bootable VirtualBox disk? I would rather not use the floppy as boot.
Answer: Perhaps this is useful?
http://en.wikibooks.org/wiki/QEMU/Images#Exchanging_images_with_VirtualBox
Comment: Then you have to solve this problem just like you would with a real computer and load a live cd/usb image, chroot your target disk, and install the boot loader and kernel. Start there, get it working in KVM **then** convert it to a VirtualBox image.
Comment: While certainly useful, it does not help with the current problem, as the disk file from cloud images is not a **bootable** disk. It works in KVM because I can boot a specific kernel file, and tell it where the root file system is. What I need is a way to turn the disk image into a **bootable** disk.
Comment: @ppetraki want to make that an answer for upvoting?
Comment: @Tom: Sorry, I don't use Vbox anymore.
Answer: The solution is indeed to make the image itself bootable.  After days of searching the interwebs I found that the solution is to use the package extlinux, which is a derivative of syslinux — a solution for making FAT disks bootable.  extlinux works on e2fs and derivatives, this works perfectly on any old ext2 system.
mkdir /mnt/image
mount -o loop cloud-image.img /mnt/image
mkdir /mnt/image/extlinux/
extlinux --install /mnt/image/extlinux/
echo "DEFAULT /vmlinuz" > /mnt/image/extlinux/extlinux.conf
echo "APPEND root=/dev/sda init=/usr/lib/cloud-init/uncloud-init" \
     "ubuntu-pass=ubuntu ds=nocloud" >> /mnt/image/extlinux/extlinux.conf
umount /mnt/image

This will make the image bootable, and disable built-in cloud initialization techniques and so on.
Notes: I haven't worked out how to specify an APPEND which allows it to use the "root=LABEL=cloudimage-rootfs".
The resulting image can then boot using qemu, kvm or vmware, without additional floppies, kernels, or anything.  And from what I understand, apt-get upgrading the kernel will make that kernel active the next boot.
edit: I forgot to mention the obvious that you need to perform this loop-back mounting on the raw disk image, and then convert the resulting file to a VDI using vboxmanage convertfromraw cloud-image.img cloud-image.vdi
Comment: root=LABEL=cloudimage-rootfs can be replaced with

root=/dev/disk/by-label/cloudimg-rootfs

not tested but I'll assume the initrd is using udev

as far as I know LABEL tends to be an init script variable, meaning its dependant on ubuntu's init scripts which I do not know enough about.
Comment: Why not just booting the VM and installing grub?
Comment: The point was to be able to do this without having to boot it, so as to support things like cloud-init in a non-cloud environment, using stock UEC images.  I think this answer might be obsolete, as I've seen that UEC images actually are bootable as-is (which was not the case a couple of years ago).
Comment: If you want to use VirtualBox, you can use `VBoxManage internalcommands createrawvmdk -filename cloud-image.vmdk -rawdisk cloud-image.img` to create a meta description file for using the image with a new virtual machine.
Answer: There is now an Ova formatted image that works after importing into VirtualBox, see my long search below. I still haven't figured out how to boot an image in Virt-manager, and would like to, but extlinux didnt help. It's not seeing the kernel file locations with Direct Boot.
What are the different versions available as Ubuntu cloud-images?


Fetch data from database and show in custom block

Question: I have created my own simple block.I want to show some data from user table of database of logged in user to the block.I want to show it programmatically and not want to use any module. How can I do that?
One more question related to block is, can I add my custom theme to my custom block (like .tpl.php file for custom module)?If yes how can I do that?
Comment: blocks will follow the theme of the page - if your page uses your custom theme, so will your block
Answer: depending on the information you want to retrieve, Views is probably your simplest option:

You need Views if
You like the default front page view, but you find you want to sort it
  differently. You like the default taxonomy/term view, but you find you
  want to sort it differently; for example, alphabetically. You use
  /tracker, but you want to restrict it to posts of a certain type. You
  like the idea of the 'article' module, but it doesn't display articles
  the way you like. You want a way to display a block with the 5 most
  recent posts of some particular type. You want to provide 'unread
  forum posts'. You want a monthly archive similar to the typical
  Movable Type/Wordpress archives that displays a link to the in the
  form of "Month, YYYY (X)" where X is the number of posts that month,
  and displays them in a block. The links lead to a simple list of posts
  for that month. Views can do a lot more than that, but those are some
  of the obvious uses of Views.

Views allows you create a block or a page in order to display formatted data.


Adding energies vs. adding momenta

Question: Suppose we have a (time and space) translationally invariant system with the Fock space for a Hilbert space. Temporal and spatial translation invariance implies that energy and momentum are good quantum numbers. In the free theory, the momenta and energies of one-particle states simply add to get the total momentum and total energy of the system. Why is it that, for an interacting theory, we can (always?) add the momenta of the one-particle states to obtain the total momentum given that we can't do the same for the energy?
Comment: The momentum doesn't naively add at all; for instance the gluon field binding quarks together carries lots of momentum, so the momentum of a proton is not even close to the momenta of the free quarks.
Comment: Both energies and momenta of asymptotic states in S-matrix elements, and also one-particle states appearing in interaction vertices inside Feynman diagrams are always conserved, so that the total energy and momenta add as one would expect. Note this has nothing to do with whether these are onshell or not. So i'm not sure i understand your question.
Comment: I realized that I could have probably written the question in a simpler form, so I'm sorry if my intention is unclear. My question is that: given two 1-particle eigenstates of momentum, the combined two-particle state has total momentum equal to the sum of the individual momenta. However the total energy is not equal to the sum of the individual energies. Why is this the case?

I can try to edit my question to make this clearer.
Comment: so your question is about why the energy of  bound states is different from the sum of energies of the constituents, right?, as i don't know of any other situation where this would occur. here the energy difference is the binding energy (when one goes to the rest frame). in a boosted frame the momenta will also differ (by Lorentz covariance). at least this is my understanding, maybe somebody can add more detail.
Comment: (by the way, time translation invariance is not sufficient for energy-momentum conservation, you also need spatial translation invariance)
Comment: You're right of course, I edited the question for clarity. And are bound states the only time when the sum of energies is different from the constituents? I would've thought that it occurs even (say) in scattering contexts due to interactions.
Comment: Also, in the case of a bound state, I'm not sure how that would be described within the Fock space context... or if it can be described that way at all. I don't know much about bound states.
Comment: @knzhou thanks for the explicit example. I guess the contexts that I've studied never had anything like a bound state, and I thought that the question applies even in those situations.
Comment: Also, in that case: if I were to add up the individual momenta of each gluon and add it to the momenta of the quarks, would I obtain the total momentum? What about for energy?
Answer: In quantum mechanics, the linear momentum is represented by a one-body operator: the momentum of the $i$-particle only depends on the variables of this particle, $\hat{\bf p}_i = -i\hbar \nabla_i.$ So, the total momentum of the system is simply defined by the sum of the momentum of each particle. Of course, if the particles are immersed in some field (like an electromagnetic one), it would be necessary to sum the field momentum to the momenta of the particles.
On the other hand, the interaction energy terms correspond to two-body operators, for example, the repulsion between two electrons corresponds to $\hat{V}({\bf \hat{r}}_1, {\bf \hat{r}}_2) = \frac{e^2}{|{\bf \hat{r}}_1-{\bf \hat{r}}_2|},$ and it involves, naturally, the variables of both particles. For these reason, the total energy is not additive, as the interaction terms "belong" to the two-particles, and not to each particle separately. It doesn't matter if the particles form bound states.
Other energies are additive (one-body operators), for example, the kinetic energy, the potential energy in an external field.
Comment: Thanks! Does this cause any problem in a relativistic theory, where the energies and momenta can mix together? Does momenta remain strictly a one-body operator in that case? My intuition says that it does, but I can't see how that would actually work.

Adding energies vs. adding momenta


One Odd-Sized page in Pages Document for PDF

Question: Need to embed a Numbers spreadsheet in a Pages doc that will "live" as a PDF. Generating a scaled image that I then embed results in mediocre resolution.
Answer: If there's no way to scale your numbers doc small enough to fit on a pages sized page, you'll have to use a larger paper size (e.g. legal).
If you only want your numbers doc to be a different size, you'll need to handle them separately. I'm not aware of any way to change the dimensions of a single page in pages directly but...
If the document will "live" as a PDF, why not export the pages doc to PDF in standard Letter or A4 size without your spreadsheet.
Then create a custom page size in your Numbers doc to fit the spreadsheet as a whole and export that to pdf.
Finally, use preview to combine the two documents.
Comment: Thanks!

Had no idea Preview could do this!


Tracing the node process executing my script from "npm start"

Question: I am attempting to debug a cli node project. Its easier to do npm start than npm install -g . && libgrabber. However, I'd like to run strace on the process. The output of strace -f on the npm start is much more verbose than the call to node itself. Is there a way to invoke strace from the npm start call without all the output from npm itself and just the call to node executing the main script?
Answer: Tried Strongloop's Node Inspector yet?  Basically it uses Chrome's DevTools to debug Node's JavaScript.  Won't help once data leaves Node, but will help you with what I think you're really trying to do; see what is going on 'under the hood'.


external SD card unmounted lost everything

Question: I unmounted my SD card before resetting my phone when put baxk in nothing came up. No pictures or music. I have a Galaxy S3. Can I retrieve them some how?
Answer: Something similar happened to me and afterwards i found all my photos, videos, etc. were in a folder on the sd card called LOST.DIR. To make it more difficult unfortunately the file extensions were removed and the file names were meaningless e.g. 'holiday.mpeg' became '1g2h3j4k5'.
Check for this folder then copy it's contents to your laptop or whatever. You can see the file sizes and you know what you had on there so try something like adding a .mpeg extension to the large files and .jpeg to the smaller ones.
It took me some time to get them all back but in the end i got through it.


What is the construction in this headline: "Millionen syrische Kinder leiden unter psychischen Störungen"

Question: I don't understand why this isn't ,,Millionen von syrischen Kindern......" or "Millionen syrischer Kinder...." instead of ,,Millionen syrische Kinder...", that is to say, either using dative or a more obvious genitive.
Comment: @Janka No, that's not the answer to the problem. Of course the subject here is the nominal-phrase [Millionen syrische Kinder]. *Millionen syrischer Kinder* would be a Genitivus Partitivus and correct as well. The question is, why it is not obligatory to use Genitivs Partitivus here.
Comment: *Millionen syrische Kinder* is the subject. **Who or what** suffers? So it has to be in … nominative. It's not the *Millions* who belong to some *syrische Kinder*.
Answer: The construction behind

Millionen syrische Kinder

is called "Apposition mit Kasusangleichung".

Millionen syrischer Kinder

would be "partitiver Genitiv (Genitivus Partitivus)". Both constructions are grammatically correct and denotate very much the same thing (1 million of Syrian children), but they have a different grammar. For more information see de:wikipedia: Apposition and canoonet
Comment: So, does that only apply to the nominative subject position like your comment under the question implies? I'd say it works in object position only with those inflections that are homonym between genitive and dativ, that is everything but masculin singular, because the apposition can be read as parenthetical, repeating the flexion: *Ich möchte ein Glass, [eine] wässrige Lösung*; the same sounds wrong with *flüssiger Stickstoff*. Of course there is no singular countable noun following quantifiers like *Millionen*.
Comment: You mean the meaning is _more than_ one million children
Answer: I came across the same thing a while ago when I saw ein Glas Wasser and wondered why there is no von used there. Surprisingly, I realised that in my mother tongue, Persian, we use it in the same way with no preposition:
یک لیوان آب بده لطفا Give me a glass of water please.
And if in Persian we add ِ ,  the meaning could change in some circumstances:

یک لیوانِ آب بده لطف Give me a glass which I can use for drinking
  water.

The persian equivalent of "of" shown by a small slanted dash in the second example changes the meaning in Persian, but whether it is also the case in German I highly doubt it.
Answer: The question should be why Genitivus Partitivus was permittable at all. Kinder are in principle countable, and in subject position it will always be zwei syrische Kinder; It's the indefinite Millionen that's tricky. The casing depends on whether you want to stress uncountability or not; also, if definitely uncountable, e.g. Millionen grüne Liter Asbest (nonsense), would in my humble opinion more  likely continue in active voice.
The nonsense-phrase "hier werden sie geholfen" (hier wird Ihnen geholfen werden) comes to mind, because it's the logical continuation (though whether that's etymologically true is a different question) of the mish-mash that you get from

Millionen Syrischer Kinder wird geholfen

as it's uncountable to boot, it has to take the singular flexion. Substituting a noun phrase that commands plural inflection, like the pronoun "sie", we get

Hier werden Sie geholfen
Comment: The Finnish language actually has a distinct partitiv case (Partitiivi) which follows after any number except for 1. Countability doesn't matter.


Is it possible to calculate chromacity coordinates using absorbance values?

Question: I have absorbance values for blood plasma. Absorbance was measured in range of 380 – 600 nm every 5 nm ending up with absorbance values for 45 wave lengths.
I was browsing through literature, and  I came  across chromacity coordinates (XYZ) and this seems to be a very convenient way of summarizing data about color in just two data points.
I have been reading some literature about different colorimetric systems, but since my background is in genetics, it didn't make much sense for me.
Therefore, I would like to ask you if it is possible to calculate these chromacity coordinates using my absorbance values and if so does anyone now some kind of software for this or exact formulas on how to do it?
Comment: Actually, it is pretty obvious. The wiki article about CIE color space has precise definition how to calculate color. However, having absorbance values does not give spectrum of reflected light, only of light passed through. There is a difference.  Moreover, the layers of blood with different thickness will have different colors. So, short answer is: no, you cannot.
Comment: What a great question! This said, I suspect you'd have better luck on phys.SE with this one as there are some people quite knowledgable in colorimetry who hang out there.
Answer: This is a partial answer to your question.  I have used chromaticity coordinates for various scientific endeavours (air quality mainly).  I found that it is a very powerful means of determining colour differences.
A bit of searching and there is somewhat of a precedent for using chromaticity for blood plasma.  An example is the article Features of Color Characteristics of Blood Plasma of Patients with Liver Cirrhosis in the Colorimetric System XYZ as Compared with Healthy People (Dolomatov et al. 2012) - even though it may be a different context to your study, but does show that it can and has been done before.  Specifically, their method was

by colorimetric method, based on absorption electromagnetic radiation in visible area.

There are several more examples of how it can be used.
Comment: Thanks and sorry for a late reply. I also found that article (those guy have some  very interesting papers on this topic ). However, in the meantime I changed my mind and went only for a specific range of wavelengths which correspond to peak values of plasma components which are of my interest.


How to bake Frozen French Fries

Question: I bought a couple of packets of frozen fries and I absolutely can't fry them. My only option is to bake them. I have access to oil if necessary.
How do I bake the fries to make them resemble (as far as possible) the McDonald type fries ?
What I have tried:

Preheating oven to 250C, throwing them in (on a baking tray) till they look golden. Didn't work, they tasted weird and were soggy-ish. Maybe lack of oil? Citation Here
Same as above but with an added step before throwing them in : gently pouring oil over them and mixing them by hand. Result was not very different.
Comment: Similar question: http://cooking.stackexchange.com/questions/14600/how-can-i-bake-normally-fried-foods
Answer: I take a piece of aluminum foil, crumple it up then smooth it out somewhat still leaving slight concave and convex angles for the fries to crisp evenly without the need of flipping halfway through baking.
Comment: That's a really cool trick that could be used for a lot of different foods. Thanks for sharing.
Comment: It's also what ATK recommends. See http://cooking.stackexchange.com/questions/78898/when-making-french-fries-can-i-precut-them-before-baking-or-frying-them
Answer: The problem with baking frozen french fries is that they lie on their side on the baking sheet, and the side that touches the sheet never gets a chance to become crisp. To solve the problem, make sure that you lay the fries out in a single layer on the baking sheet. Pull the sheet out of the oven about halfway through the baking process and give 'em a good toss. That will turn enough of the fries over that you shouldn't get too many soggy spots. If your diet allows, toss the cooked fries with salt to taste.
Frozen french fries will have already been fried once at the factory. They may not have the same hot-from-the-fryer coat of fat that you get from deep-fried fries, but a bigger difference is probably the moisture content. The hot air in an oven tends to dry fries (and anything else) out. The hot fat in a fryer pushes against the steam inside the fries, not exactly trapping it, but keeping more moisture inside the fries while still crisping the outer surface. Frying and baking are simply different processes that produce different results.
Answer: as well as laying the chips out in a single layer on a baking tray, try heating up the tray first too and also the last 2 or 3 mins of roasting leave the tray in the oven but turn the oven off and leave the door open, this often helps crisp them up too.
Answer: I've also noticed that using a hotter oven helps with making fries crispy, say around 450*. I've done this with left-over deep-fried french fries and it re-crisps them nicely, and I've also done homemade baked fries and they come out nice and crispy.  Not sure if the pre-made frozen fries will react the same way, but maybe you can tweak it some. :)
The hotter oven makes sense to me since deep friers at places like McDonalds and Burger King tend to run about 350-365*.  Recipes that you can find online for baked fries also suggest higher temps: http://allrecipes.com/recipe/baked-french-fries-i/.  I suspect that using higher heat helps trap in some of the moisture because the outside crisps up more quickly, but I could be wrong about that.
Comment: OP said 250 C which is approximately 480 degrees Fahrenheit, which I presume you're using.
Answer: frozen french fries are handy, but not necessarily tasty.  try partially thawing first, patting dry, put in large bowl (gently), add a little olive oil, sea salt, toss gently, then put them on a baking cooling rack (the type w/ little squarishish grids), on top of a cookie sheet, this allows air to circulate, and get all sides - preheat oven to 400-425F, depending on whether you have fat or skinny fries (fat ones on higher temp.).  cook for 15 -25 minutes...keeping checking, it just depends on the size of the fries. it's worked for me, although real french fries are just still the best.mc in oakland
Answer: DO not use olive oil for your fries. in a deep fryer fries reach best crispness at 160+. olive oil has a smoke point of 120* the lowest of all the cooking oils. Special deep fryer mixes are available which have a high smoke point, Best results is no cover the fries in oil and salt then put them on a griddle in layers in the oven. You can criss cross them to get more on but this just seems like a lot of work for something that is supposed to be quick and easy and all that work for not graet results seems a waste.
Comment: Could you please check: do you mean "no cover" or "to cover" (in the middle of the text). I suspect a typo but hesitate to edit... Welcome to the site!
Answer: Well, I'm sorry to say that Baked french fries rarely have the same texture of freshly deep-fried ones. One trick you may want to try is an egg white wash. This helps lots of baked goods brown and crisp as they bake. Try beating 1 tsp water with 1 egg white and brushing this on your fries before they go in the oven.
Answer: I love tossing them with a ranch packet with canola oil. Do not use olive oil it is not made for crisping it will just make them soggy. Also do not let them thaw; that's the worst thing you can do. Just coat with plenty of seasoning and oil. Cook about 15 minutes longer than instructions tell you to, but at the same temperature. Pull out after 3/4 of the baking time, pour in a heat resistant bowl, shake well, then continue baking. Nice and crisp with great flavor.
Answer: I had some frozen hashbrowns one time which had different preparation instructions and were great.  The next time I got frozen fries, I tried the same method.  Every time i prepared frozen french fries according to the standard instructions, they tasted like cardboard.
I like Cajun fries so I used the seasonings.

Put the amount of frozen fries you will use into a freezer box.
Add the Cajun seasonings and toss.
Thaw in the microwave.
Heat a non stick skillet or griddle plate.
Add some butter or other type of fat as you prefer.
Toss the fries around with a couple of spatulas until brown.
Add salt to taste and enjoy what tastes just like freshly made fries.

This is the one exception I make to following the instructions, since I do not enjoy cardboard for dinner.
Comment: What is a freezer box?

How to bake Frozen French Fries


Chunk error when upgraded to mongodb 2.6 while uploading doc

Question: I was trying to upgrade mongodb 2.2 to 2.6 and upon testing 2.6 received chunk out of order error..
I recieve an unexpected error from the server: exception: chunks out of order at /home/ps203k/.perlbrew/libs/perl-5.20.2@oasis-gsp_oss/lib/perl5/x86_64-linux-thread-multi/MongoDB/GridFS.pm line 236.
it is standalone.. and not sharded..
only once instance of mongodb running in one sever..
the server has old mongodb version : 2.2 and may be old perl version..
package MongoDB;
{
$MongoDB::VERSION = '0.46.3';
}
so we have 0.46.3 driver version of perl..
so do you think that this chunk out of order we are getting because of old driver version...? we need to upgrade perl driver and perl versions..
Answer: Did you follow the guidelines?

To upgrade an existing MongoDB deployment to 2.6, you must be running
  2.4. If you're running a version of MongoDB before 2.4, you must upgrade to 2.4 before upgrading to 2.6.

I have upgraded from 2.4 to 2.6 with no issues on a sharded cluster.


Citation of a book chapter that was put online

Question: I am trying to cite, using the ACS format, https://www.intechopen.com/books/cancer-causing-substances/heavy-metals-and-cancer, but I don't know whether it is considered a book or ebook chapter. How am I supposed to tell them apart? The link is under "books" on the website, but seeing as it is online, wouldn't it be considered an ebook? If I cite it as a book, it'll be pretty weird for me to include a link and the date accessed, won't it?
Answer: I would cite this as a book section, including the DOI (because that's where you found it/how others will be able to find it) but not including "date accessed", because that is intended for more volatile resources like web pages. (If a reference has a DOI you can usually treat it as non-volatile.)
Sticking as precisely as you can to a reference format is important, but the most important thing is to make sure that the information is present that allows readers to (1) attribute credit appropriately and (2) re-locate the original source.

(1) Carver, A.; Gallicchio, V. S. Heavy Metals and Cancer. In Cancer Causing Substances; Atroshi, F., Ed.; 2018. https://doi.org/10.5772/intechopen.68247.
Answer: A book is a written work distributed by a publisher, in physical or digital form. (Books and eBooks needn't be distinguished, they contain the same content.) Book drafts are distinguished, they are distributed by authors.


Macbook Pro doesn't wake up from sleep, RAM slot empty after force restart

Question: My mid-2009 Macbook Pro, running Mountain Lion, very often does not wake up from sleep. When I open the lid, there is a black screen, but the fans are still running. My only option is to force reboot by holding down the power button. When It finishes rebooting, only half of the installed RAM is recognized - System Information shows that Bank 1 is empty when there is actually a stick of RAM installed. I have tried swapping out the RAM, booting from other disks, reinstalling, and searching for evidence in the log files, but the problem persists. The Apple Genius Bar didn't even know what was wrong with my computer. I am at a loss - what could be the problem?
Comment: You don't mention if the MBP ever uses the full RAM installed, and if so, what do you do to make it work.
Comment: After a blackout, if I restart a few times, the full 2x4GB is recognized until there is another blackout.
Comment: I have been having the same exact symptoms on the same model, to which I have administered the same fix attempts – to no avail. I'm glad to finally read about someone else having this issue. Have you made any progress in discovering the cause, or a solution? Any info would be greatly appreciated. Sorry I can't offer any myself.
Comment: It turns out the problem was in fact a faulty logic board. The computer, while four years old, was still in good shape so I had an Apple store ship it out and repair it for a flat fee of around $250. I had it back within a few days. If you decide to do the same, make sure you have them ship it out instead of repairing it in-house because if you ship it out they will repair any non-cosmetic damage for a flat fee.
Answer: If you've tried reinstalling and resetting PRAM / SMC etc and it's still occurring on a clean install then that rules out a software issue. If you've tried another ram stick that rules out faulty ram.
Sorry to tell you, but it sounds like a motherboard issue, which means $$$. That's the only other thing I realistically think could be causing the ram fault.


RSNNS neural network prediction for raster image classification in R

Question: I'm trying to harness the power of neural networks for image classification of big rasters using the RSNNS package in R.
As for the data preparation and training of the model, everything works perfectly fine and the accuracies look quite promising.
Subsequently, I'm trying to classify the raster values using the function predict with the trained model. Having a quite big amount of data (rasterstack with the dimension 10980x10980x16), I'm processing the data block by block. And here's the problem:
The prediction of the class values is extremely slow. I'm working on a quite powerful machine (Windows x64, 32GB Ram, i7 3.4GHZ quad-core) but still the process is almost literally taking ages. I already reduced the size of my blocks, but still the amount of time needed is unacceptable. Currently I split the data in blocks of 64 rows per block. That would result in a total of 172 blocks. If I assume a linear processing time for each block (in my case 33 minutes !!!), it would take me almost 95 hours to process the whole image. Again, that can not be right.
I've tried other neural network packages and for instance nnet classifies bigger blocks like these in under one minute.
So please, if you have any pointers on what I'm doing wrong, I'd greatly appreciate it.
Here's a working example similar to my code:
library(RSNNS)

#example data for training and testing
dat <- matrix(runif(702720),ncol = 16)

#example data to classify
rasval <- matrix(runif(11243520),ncol = 16)

dat <- as.data.frame(dat)

#example class labels from 1 to 11
classes <- matrix(,ncol=1,nrow=nrow(dat))
classes <- apply(classes,1,function(x) floor(runif(1,0,11)))

dat$classes <- classes

#shuffle dataset
dat <- dat[sample(nrow(dat)),]

datValues <- dat[,1:16]
datTargets <- decodeClassLabels(dat[,17])

#split dataset
dat <- splitForTrainingAndTest(datValues, datTargets, ratio=0.15)

#normalize data
dat <- normTrainingAndTestSet(dat)

#extract normalization variables
ncolmeans <- attributes(dat$inputsTrain)$normParams$colMeans
ncolsds <- attributes(dat$inputsTrain)$normParams$colSds

#train model
model <- mlp(dat$inputsTrain, dat$targetsTrain, size=1, learnFunc="SCG", learnFuncParams=c(0, 0, 0, 0),
             maxit=400, inputsTest=dat$inputsTest, targetsTest=dat$targetsTest)

#normalize raster data
rasval <- sweep(sweep(rasval,2,ncolmeans),2,ncolsds,'/')

#Predict classes ##Problem##
pred <- predict(model,rasval)

Answer: yes, unfortunately RSNNS can be very slow when predicting. The new version 0.4-8 (not on CRAN yet, but you can get it from github) should speed things up a bit but the general problem is that every row of data needs to be passed separately into the SNNS kernel, and resolving this issue would mean reimplementing some things in the kernel. Not impossible but some work to do.


Peru Tourist Visa for Indian national in US with F-1 visa

Question: I am a Indian national currently residing in the US with a valid F-1 visa.
I am interested in travelling to Peru for a trip. Would I need a tourist visa?
Their embassy website does not give a clear picture of this.
Answer: Yes you need a tourist visa, visa requirements are tied to your citizenship and not any residence status in a third country. India is on the list of countries that are required to obtain a visa before travelling to Peru, according to the Peruvian consulate in San Francisco.
You can find the requirements for obtaining a Peruvian tourist visa on their website.
Answer: As of March 2017, any Indian national with a valid visa from United States, Canada, the United Kingdom, Australia or any Schengen State, can visit Perú visa-free [1][2].
I visited the country last month. Both me and my wife have a Canadian tourist and US work visa, immigration officer checked my US visa and my wife's Canadian visa.


Two preloaders of images

Question: I'm doing animation in javascript/jquery+html and the code looks something like this (simplify version).

html:

Testing animation 1

        execute

Testing animation 2

        execute

javascript:
var imgCount[0]=30; //number of images for Testing animation 1
var imgCount[1]=1000; //number of images for Testing animation 2
var progressWidth=0; //default progressbar width
var imgArray=new Array(); //array which will hold image sources strings
var checkProgress;
var goAnim;

//if user choose an animation
$('#animationList li span').click(function() {
  //need to stop older animation
  if(goAnim) clearInterval(goAnim);
  //ensure just one checkProgress interval is running (doesn't work)
  if(checkProgress) clearInterval(checkProgress);
  //get animation id
  animId=$(this).parent().parent().index();
  //call index function
  start();
});

function start() {
  //clear array with image sources
  if(imgArray.length>0) imgArray.length=0;
  //check progress status
  checkProgress=setInterval(checkProgWidth,10);
  //execute images preloader
  loadImageset(1);
};

//check progress percentage
function checkProgWidth() {
  //start animation after progress percentage is 100 (if all images are loaded)
  if(progressWidth==100) {
    clearInterval(checkProgress); //stop this function
    goAnim=setInterval(animation,1000); //execute interval for animation function (won't write it here, it's not important)
  }
};

//preload images to browser's cache
function loadImageset(i) {
  //merge img source
  imgSrc=animId+'/'+i+'.jpg';
  //create image object
  var imgCaching=new Image();
  //fill image object source
  imgCaching.src=imgSrc;
  //insert image source into array
  imgArray[i]=imgSrc;
    //do this stuff after image is loaded
    imgCaching.onload=function() {
      //count progress percentage
      progressWidth=Math.round((i/imgCount)*100);
      //set css of preloader div
      $('#statusBar').css({
        width:progressWidth+'%',
        backgroundColor:'#fff'
      });
      $('#statusBar').text(progressWidth+'%');
      //load next image...
      if(i<=imgCount[animId]) {
        i++;
        loadImageset(i);
      }
      //...or return
      else return;
    };
};

Point is that I have one div with list of animations and in other div is container for animation (animation=changing the background-image of this container). Click on some of span from first div executes the animation, it means load images to browser's cache and while images are loading there is an interval function checkProgWidth() which counts the progress percentage -> if it's equal to 100 (all images are loaded) then stop the interval and start the animation.
Demo on http://hlavsene.sav.sk/test/sos.
Problems:
1.) When images of one animation are loading (when progressbar is in move) and during that I choose (click on) the same or another animation I need to stop the loading images of first animation and start the loading of the second one. But I can't do that. You can see it on animation 3 and 4 (they have a lot of images so the loading is long) on the demo site. The progressbar starts to going mad, I think browser starts to load images from the both of animations, it means it doesn't stop loading images from the first animation. Or maybe there is another problem.. Do you have any advice what should I do?
2.) Sometimes there is a blink between changing images, sometimes not. Do u know why?
I'll really appreciate any help. Thank you, guys.
Answer: 1) there's no reliable and guaranteed way for stopping loading images once you said the browser to start the download.
A workaround is to download them with AJAX, and once downloaded re-download (they will actually be taken from the browser's cache) by setting img src
Additionally you should probably keep a kind of animation object, and a way to stop it from at least altering the 'canvas', something like
animation = {
  stopped: false,
  start: function () {
    for (var i = 0; i < imgCount; i++) {
      if (!this.stopped) {...}
      else return;
    }
  },
  stop: function () {this.stopped = true;}
}

Two preloaders of images


Poisson Distribution interarrivial time

Question: It is obvious that given that in the interval $(0,t)$ the number of arrivals following Poisson process is $N(t)=n$, these $n$ arrivals are independently and uniformly distributed in the interval. It is also clear that the interarrival time of the events following poisson process follows the exponential distribution. Here is my point. I think If $n$ arrivals follows uniform distribution, the interarrivail time of them should follow uniform distribution as well. Am I doing wrong? Anybody have an Idea, pls explain it to me.
Comment: "If n arrivals follows uniform distribution, the interarrivail time of them should follow uniform distribution as well" Frankly wrong. Did you try to check the case n=2? None of the three intervals is uniform...
Answer: The joint distribution of inter-arrival times is uniform on $\{x_1+\dots + x_n<t\}$ conditionally on the fact that $N(t) = n$. Unconditionally, they are independent and have exponential distribution. There is no contradiction; you can try to verify this fact yourself, it's not that hard.
Moreover, as @Did wrote, while the joint (conditional) distribution of the inter-arrival times is uniform, the individual (conditional) distribution of each inter-arrival time is not.
The reason of this non-uniformity comes out of the fact that, conditionally on $N(t) = n$, the inter-arrival times are no longer independent. If they were, then, naturally, you would be able to deduce the uniformity of marginal distributions from that of their joint distribution.
Another way to put this. The conditional distribution of the arrival times is uniform on $[0,t]^n$, so indeed they can be understood as iid uniform random variables on $[0,t]$. However, if you are interested in the inter-arrival times, then you should first arrange the arrival times in the increasing order. And at this point you already lose independence of individual components.
Comment: What is the reason of voting the answer down? Can the downvoter explain?
Comment: No idea. +1 from me as soon as I am not out of votes anymore.
Answer: Following @zhoraster's answer, the interarrival time distribution of n arrivals uniform in $[0,T]$ is equal the 1st arrival time distribution by symmetry - the marginal distribution of time between any 2 consecutive arrivals is an integral of the uniform joint distribution over the same volume. Therefore, the interarrival time cdf equals the 1st arrival time cdf  $F(t;n)=F_\mathrm{Beta}(\frac{t}{T};1,n)$.
We can recover the exponential cdf from $\mathrm{lim}_{T\rightarrow\infty} F(t;\lambda T)$. Alternatively, $\frac{\sum_{i=1}^\infty f_{Poi}(i; \lambda T) F(t;i)}{\sum_{i=1}^\infty f_{Poi}(i; \lambda T)}$ gives the $[0,T]$-truncated exponential cdf as the 1st arrival time cdf conditional on 1st arrival being before $T$; $\sum_{i=1}^\infty f_{Poi}(i; \lambda T) F(t;i) + f_{Poi}(0; \lambda T) F_T(t;\lambda)$, with $F_T(t;\lambda) = \frac{F_{Exp}(t;\lambda)-F_{Exp}(T;\lambda)}{1-F_{Exp}(T;\lambda)}H(t-T)$ being the $[T,\infty]$-truncated exponential cdf, gives the exponential unconditional interarrival time cdf.
Conversely, if n arrivals in [0,T] have exponential interarrival times, the conditional pdf of the i-th arrival time is the product of the pmf of n arrivals conditional on the i-th arrival time and the Erlang pdf of the i-th arrival time, divided by the Poisson pmf of n arrivals:
$$
f_i(t;n)=\frac{f_{Poi}(n-i;\lambda (T-t))}{f_{Poi}(n;\lambda T)}f_{Erlang}(t;i,\lambda)
$$
The uniform pdf is recovered as the conditional arrival time pdf from mean $f_i(t;n)$.

Poisson Distribution interarrivial time


UINavigationController with static navigation bar

Question: I'm working on an educational iPhone application and am looking for advice on what is the best architecture for a specific portion of my app.
I'm working with iOS 5 so I can use container view controllers. I want to do as much as possible in the storyboard.
Here's what I want to do:

some data items are listed in a table view controller.
when the user clicks on one of these items, we start a study session by presenting its main view controller modally.
a study session is composed of 4 view controllers that are pushed from the right, one after another.
these four screens have a navigation bar with:

the same title.
the same left item: a "Close" button that will dismiss the whole modal study session.
two of them have a screen-specific right item, the other two don't.

the transitions between these four screens should be animated in a UINavigationController style, but the navigation bar shouldn't be animated.

Here is a way I'm thinking of for implementing this behavior:
Showing modally a custom container view controller that would contains:

a UINavigationController without navigation bar, where I would push my screens
a separate UINavigationBar that would stay above the navigation controller.

The screens would define their navigation bar's right item if any, and the container view controller would be responsible for putting it in the navigation bar.
Does someone have an opinion on this method, or an elegant alternative to suggest?
Thanks. Have a great day!
Comment: Did you find any solution? I am also looking for same implementation
Answer: you can use Single View based project for this purpose. Add a navigation controller to push when user clicks on tableview content. By pushing with animation, your view will be transitioned from tableview to another view controller.
Now you can show up your first chapter and add a swipe gesture to your view so as to change the page.


How often does the treasury department issue bonds and at what prices?

Question: How often does the u.s treasury department issue bonds and at what prices?  Does it issue bonds throughout the year with the same annual yield regardless of current bond prices in the bond market, as long as the Fed is not changing the interest rate ?
Comment: Not sure if you are aware of the US Treasury auction results: https://treasurydirect.gov/instit/annceresult/press/press_secannpr.htm and https://treasurydirect.gov/instit/annceresult/annceresult.htm
Comment: @Morrison Chang thank you! another question: how many parties profits from this treasuries, I mean in stocks there are (1-the exchange market 2- the market maker 3- broker .. for example) , here (..4- the investor who won auction.. the guy who I buy the bond from him as I'll not be the first holder of it ...) ?
Comment: I linked to [Treasury Direct](https://treasurydirect.gov/) which allows direct retail purchases (non-competitive bid) of US Treasury product from the US Treasury. Beyond the accepted answer, it may help to read: [Why would anyone buy U.S. Treasury Bills?](https://money.stackexchange.com/q/103839/14319)
Answer:
How often does the u.s treasury department issue bonds and at what
prices?

The US Department of the Treasury runs actions for these new securities:
They range from T-bills:

Treasury bills are issued for terms of 4, 8, 13, 26, and 52 weeks. Another type of Treasury bill, the cash management bill, is issued in
variable terms.
4-week, 8-week, 13-week, 26-week, and 52-week bills are auctioned on a regular schedule.
Cash management bills aren't auctioned on a regular schedule.

To Treasury Notes

Treasury notes, sometimes called T-Notes, earn a fixed rate of
interest every six months until maturity. Notes are issued in terms of
2, 3, 5, 7, and 10 years.

They also issue Treasury Bonds:

Treasury bonds pay a fixed rate of interest every six months until
they mature. They are issued in a term of 20 years or 30 years.

The list of upcoming auctions is at Treasury Direct:
These are auctions:

Overview of the Auction Process
Treasury sells marketable securities (bills, notes, bonds, FRNs, and
TIPS) through regular public auctions, by which the rate, yield, or
discount margin of these securities are determined.
The process begins several days before the scheduled auction when the
Treasury announces the details of the upcoming issue, including the
amount to be auctioned and the maturity date. When you participate in
an auction, you have two bidding options – competitive and
noncompetitive. TreasuryDirect allows noncompetitive bidding only.
Noncompetitive bidding is limited to purchases of $5 million per
auction. Bidding limits apply cumulatively to all methods
(TreasuryDirect, banks, and brokers) that are used for bidding in a
single auction.

With a competitive bid, you specify the rate, yield, or discount margin you will accept.
With a noncompetitive bid, you agree to accept the high rate, yield, or discount margin set at auction.

At the close of an auction, Treasury accepts all noncompetitive bids
that comply with the auction rules, and then accepts competitive bids
in ascending order in terms of their rates, yields, or discount
margins (lowest to highest) until the quantity of accepted bids
reaches the offering amount. All bidders, noncompetitive and
competitive, will receive the same rate, yield, or spread as the
highest accepted bid.

Unless you are going to invest a ton of money, you just get them at the market rate set at the auction with a noncompetitive bid.


What is the name of DB design pattern which support only soft-deletes and soft-updates?

Question: I heard that there is some DB design in relational databases where updating a record will create a new record with different timestamp or status. Also, deletion will be soft-delete (it updates the status or effective date to past date). It does not actually delete the record. I would like to know if there is a name for such a design pattern. In which scenarios do we need to use such patterns?
Answer: The concept you're looking for is probably "data versioning". It can be useful when it's important for auditing to keep track of all changes made to certain entities (think of configuration parameters, bank accounts of vendors or accounting records in general). To list all possible scenarios would not be practical in a Stack Exchange answer.
Here is an example article explaining how automatic data versioning works for a certain type of database (MariaDB). Articles like these might save you from reinventing the wheel; you don't want to roll your own versioning system except maybe for very simple cases.
Answer: This would be called a rather crude form of audit-trail.
Answer: Tuple versioning? ie. https://en.wikipedia.org/wiki/Tuple-versioning
As for the question when to use, "it depends". In many systems it is crucial that
all changes to state can be tracked and/or restored, but cost is pretty high (both space- and operation wise)
Answer: A term often used is temporal tables. The data contains additional columns holding the time a row became into use and the time that row stopped being current. These columns can be explicit, under the control of a developer, or system-generated when the DML operations set the begin and end values.
Time can be measured by clock-time or internal measures like CPU ticks and log sequence number (LSN). Clocks are preferred because the value measured is not affected across system re-starts. It can also be compared with reasonable accuracy between systems. When using a clock it is important to have sufficient resolution that concurrent updates to a row can be distinguished.
History can be stored in the same on-disk structure as the current value or separate structures. It is possible to implement temporal stores using normal tables and triggers.
If all tables in a database have temporal functionality then the DB can be queried as it was at any point in the past. This allows, say, point-in-time reporting with concurrent updates (HTAP). Such a scheme could increase the freshness of reports and save cost by eliminating dedicated reporting infrastructure.


Feeling of closeness with something you adore/love so much

Question: How do I say that I find a person or place so good or you love it so much that you think it gives you feeling of closeness to it? Or what?
E.g I like my friend's mother so much, it's like motherly vibes come out of her.
Or
I like a place so much, it gives me homely/comfy feeling, seems like a second home to me.
What is this feeling called?
Comment: You can just say that this place makes part of your life, or you are very close to a person or to someone, or simply say that someone/thing is very special for you
Comment: No, there got to be some term for It ?
Comment: I guess not, there is no term for this, you can use different words to emphasize that someone/thing is very special for you by saying things like: _I see you as if you were my sister, we are so close_ - _I feel like this place was my home, I always feel better when I get here_
Answer: There is no unique term, e.g. from psychology, for feelings like that.  There are a few for feelings of unification with the world or entire universe and all creatures in it, but not for deep feelings of closeness and identification with one person or one place.  The best you can do is describe the feeling.
Use relationship and/or emotional terms:

"She's like a sister to me".
"My friend's mum is so nice that I feel (like / as though) she's my mother too"
"I love Minneapolis.  It's as though I've lived here all my life"
Answer: There is a single word to describe such a feeling, and that word is intimacy, and this can be used in reference to a person, or a location.

intimacy:

a state marked by emotional closeness (the intimacy of old friends)
a quality suggesting closeness or warmth (the cafe's intimacy)
something that is very personal or private (They shared little intimacies in their letters.)

However, intimacy (the state of being intimate) is most often used these days to describe physical intimacy, which comes from having a sexual relationship, and one must be careful when using the word to describe a platonic relationship that the listener does not interpret your sentence in this fashion. telling your friend, for example, that you have an intimate relationship with his mother, without further clarification, may not end well.
Is you wish to err on the side of caution , (and most people do), another term might be a safer bet, such as affinity.

affinity: a feeling of closeness and understanding that someone has
  for another person because of their similar qualities, ideas, or
  interests

Or, as other comments have suggested, you can simply describe the connection witht is person or place as closeness, or being close.
Answer: I have frequently heard the word "nostalgic" being used for some of feelings you describe. However, the dictionary definitions seem to omit the all the 'sweetness' of the feeling.
Nostalgia - (noun)
1. a wistful desire to return in thought or in fact to a former time in one's life, to one's home or homeland, or to one's family and friends; a sentimental yearning for the happiness of a former place or time.
nostalgic - (adjective)
1. experiencing or exhibiting nostalgia, a sentimental or wistful yearning for the happiness felt in a former place, time, or situation.


Under which conditions do PCA and FA yield similar results?

Question: Under which conditions can principal components analysis (PCA) and factor analysis (FA) be expected to yield similar results?
Comment: To put it in other words: when PCA happens to isolate variable-specific noise from signal (common factors) as succesfully as factor analysis regularly does it. PCA, unlike FA, is not intended to do this job, however under some conditions it often appears to do it. Some of these conditions: 1) `p` is large; 2) noise is small for all variables; 3) noise is about equal for all variables.
Comment: Let $\bf L$ be the _loadings_ (not eigenvectors) of the `p-m` last principal components - those that you drop in PCA (`p` is the number of variables and `m` is the number of of components or factors you decided to extract). If $\bf LL'$ is nearly diagonal, then your PCA results are similar to FA results. Some questions for you to read: http://stats.stackexchange.com/q/123063/3277, http://stats.stackexchange.com/q/94048/3277.
Answer: This is an excellent question, but unfortunately (or maybe fortunately?) I have only recently written a very long answer in a related thread, addressing your question almost exactly. I would kindly ask you to look there and see if that answers your question.
Very briefly, if we just focus on PCA and FA loadings $\mathbf W$, then the difference is that PCA finds $\mathbf W$ to reconstruct the sample covariance (or correlation) matrix $\mathbf C$ as close as possible: $$\mathbf C \approx \mathbf W \mathbf W^\top,$$ whereas FA finds $\mathbf W$ to reconstruct the off-diagonal part of the covariance (or correlation) matrix only: $$\mathrm{offdiag}\{\mathbf C\} \approx \mathbf W \mathbf W^\top.$$ By this I mean that FA does not care what values $\mathbf W \mathbf W^\top$ has on the diagonal, it only cares about the off-diagonal part.
With this in mind, the answer to your question becomes easy to see. If the number $n$ of variables (size of $\mathbf C$) is large, then the off-diagonal part of $\mathbf C$ is almost the whole matrix (diagonal has size $n$ and the whole matrix size $n^2$, so the contribution of the diagonal is only $1/n \to 0$), and so we can expect that PCA approximates FA well. If the diagonal values are rather small, then again they don't play much role for PCA, and PCA ends up being close to FA, exactly as @ttnphns said above.
If, on the other hand, $\mathbf C$ is either small or strongly dominated by the diagonal (in particular if it has very different values on the diagonal), then PCA will have to bias $\mathbf W$ towards reproducing the diagonal as well, and so will end up being quite different from FA. One example is given in this thread:

Why do PCA and Factor Analysis return different results in this example?
Comment: In your answer, you state that ``minimizing $||C−WW^T−\Psi||^2$'' yields the factor analysis loadings. (I interpret $||\bullet||^2$ as the squared Frobenius norm.) Where can I find a proof for this statement?  For PCA, this follows from the Eckart-Young theorem, but I can't see how this applies to FA.
Comment: Related, ttnphns claims that minimizing $||X−X_k||^2$ is equivalent to minimizing $ ||X^TX−X_k^TX_k||^2$. How can this be shown?
Comment: To your first question. Yes, it's Frobenius norm. Unlike PCA, FA is more of a framework than one precisely defined method; there are different "methods of factor extraction", resulting in non-identical results. So of course there cannot be any proof for all versions of FA. However, one of the oldest/simplest/widespread methods is to find $W$ and $\Psi$ *directly* by minimizing this cost function (initialize $\Psi$ randomly, solve for $W$ via PCA, update $\Psi$, etc. until convergence). This is called "iterated principal factor" method, or smth like that. Then nothing remains to be proved :)
Comment: To your second question. Not sure if this is true in general (maybe it is, maybe not), but I never use it in my linked answer. Look at my "Update 2" carefully, this statement is not needed.


How to execute batch based on records refresh?

Question: Requirement: Here I have Contacts, each of them is may/may not self-related to another Contact. Terminology: Primary Contact and Secondary Contact. Here Primary Contact is a self lookup field on the Contact object.
I am trying to push(using Upsert) some Opportunity records using data loader. For the newly created/updated Opportunity, if there is an OpportunityContactRole with a Secondary Contact(one which has a lookup to another Contact),  check if there an OpportunityContactRole for the Primary Contact in regards to that Opportunity. If there is none, Create a new OpportunityContactRole for the Primary Contact.
Question: Things I am trying to achieve:
Opportunity records that are

Within a specific day range: Last 14 days/Last month
Last Modified/Created by a specific User(through out all dev orgs including Prod).

This is the query I had so far:
 Map<Id, Contact> relContIdsMap = new Map<Id, Contact>(secondaryCons);
 List<Opportunity> relatedOpps = [Select (Select OpportunityId From OpportunityContactRoles), Name
                                From Opportunity Where Id IN
                                (Select OpportunityId From OpportunityContactRole
                                Where ContactId =: relContIdsMap.keySet())
                                AND (Opportunity.LastModifiedBy.LastName =: 'Data Load User' OR Opportunity.CreatedBy.LastName =: 'Data Load User'  )];
  System.debug('newOpps: ' +relatedOpps); //Returns the Opportunities of the Secondary contacts.

How can I get the day range requirement full-filled? Any suggestions are welcome.
Background: I am trying to implement a Batch class which inserts new Contact Roles on the Opportunity based on:

User who updates the Opportunity, i.e., Data Load User
Last Modified date of the Opportunity record
If there is no Contact Role existed on the Primary Contact.
Answer: To fulfill the date range of Last 15 days or last month, use Date Literals LAST_N_DAYS:n or LAST_MONTH
Map<Id, Contact> relContIdsMap = new Map<Id, Contact>(secondaryCons);
 List<Opportunity> relatedOpps = [Select (Select OpportunityId From OpportunityContactRoles), Name
                                From Opportunity Where Id IN
                                (Select OpportunityId From OpportunityContactRole
                                Where ContactId =: relContIdsMap.keySet())
                                AND (Opportunity.LastModifiedBy.LastName =: 'Data Load User'
                                OR Opportunity.CreatedBy.LastName =: 'Data Load User' )
                                AND CreatedDate >= LAST_N_DAYS:15];

Also note that, this approach is good if you are running the batch with either 15 days or monthly interval respectively, so that same records will not be pulled twice.


WKWebview's javascript call returns nil

Question: I'm trying to migrate from using a UIWebview to a WKWebview, and I need to invoke various Javascript functions that live in the webview.
In the UIWebview I have no trouble doing this, but the WKWebview throws an WKErrorDomain Error 4 for any and all calls. I thought it might be a race condition where I was calling functions that didn't exist in the DOM yet, but I added a debug statement to make those same calls once the page loaded and they're not working. I even did a 'document.body.innerHTML' which returned nil when there's clearly content being displayed in the webview.
The twist is that when inspecting the web code via Safari Web Inspector, everything works well and all calls work.
Why and how could this be? I do initialize the WKWebView with a WKWebViewConfiguration so that it'll share cookies across different webviews, so there might be something there, but I'm stumped.
This is how i initialize the WKWebView
WKWebViewConfiguration* config = [[WKWebViewConfiguration alloc] init];
config.processPool = [[WKProcessPool alloc] init];
WKUserContentController* userContentController = WKUserContentController.new;
WKUserScript * cookieScript = [[WKUserScript alloc] initWithSource: @"document.cookie = 'cookie1=value1; domain=blah; path=/;';" injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO];
[userContentController addUserScript:cookieScript];
config.userContentController = userContentController;
WKWebView *webView = [[WKWebView alloc] initWithFrame:CGRectMake(0,0,50,50) configuration:config];

Here's a debugging statement where I log the document's innerHTML into the console log, which prints (nil) instead of the HTML.
NSLog(@"%@", [self.webView evaluateJavaScript:@"document.body.innerHTML" completionHandler:nil]);

Comment: Can you share code snippets so that we have little more to look at please?
Answer: WKWebView executes JS async unlike UIWebView;  You cannot print like how you are doing..
Try this
  [self.webView evaluateJavaScript:@"document.body.innerHTML" completionHandler:^(id result, NSError *error) {
    NSLog(@"Error is %@",error);
    NSLog(@"JS result %@" ,result);
}];

WKWebview's javascript call returns nil