How can I remove rust stains from enamel sink?

Question: Is there a sure-fire way to get rust stains off of an enamel sink?
Comment: I tried lemon juice and salt but it didn't work
Answer: Not sure about "Sure fire" but a product called CLR (Calcium, Lime, Rust remover) is a good start.
Comment: Thanks for the tip! I'll pick some up on my way home tomorrow and give it a shot.
Answer: I've used CLR with some success.  You can also try a pumice stone.  The stone should be  gentle enough to not scratch the enamel, but tough enough to remove the discoloration.
I removed hard water stains from the inside of an old toilet pretty easily with this approach.
Answer: I previously tried using the CLR at Scott's suggestion, and it worked to some degree, but did not completely remove the rust stains.
I actually found the answer to my problem this week, pretty much by accident. I was cleaning a particularly stubborn patch on the tile floor, and ended up using a Mr. Clean Magic Eraser on it. While I had the 'eraser' out, I figured, what the heck, let's try this on the sink. It removed the rust stain almost completely, with just barely a trace of it left in a few places. If I didn't already know it was there, I don't think I could find it at all. I'm not sure what this did to the finish of the sink, since the eraser claims to use microscrubbers, which I assume is essentially a very fine grit sandpaper plus some chemical action going on. I couldn't find any trace of ill effects, and it's been about a week, and no buildup has occurred in the area I scrubbed.
Answer: Barkeeper's Friend.  It's a cleanser like Comet or Ajax.
Comment: I just tried this out and it worked very well - till I ran out.  I switched to Wright's Silver Polish, which worked...ok.
Answer: In my case, the rust seemed to be coming from the metal underneath the enamel. So I sanded the area to the bare metal (and sanded away all rust) then applied liquid enamel repair paint with a small brush. But the rust came back after about 6 months. Not sure what to do.
Comment: how does this answer the question? ... this site is not a forum ... you do not add your own question to where the answer is supposed to be ... if you have a question, the post your own question
Answer: I've used Lime away with a hard toothbrush; then put the stopper up and the last little bit filled the sink with an inch of bleach and let it sit (WARNING: do NOT use these two chemicals together; one at a time cause it is caustic).


user search engine - go back and forth

Question: I am working on a search engine. Users can search for other users givin specific parameters (such for example age, gender, city, hair color). He is also able to sort the results in different ways.
On the search result page you are able to see 10 profiles and if you click on them, you get to another page (profile page) where you have more information on that single user.
The user who's now on a profil page looking at a specific user should now have to possibility to go back and forth to the next or the previous user from the search result. So you would have to store the specific parameters the user chose and you would also have to run the whole search query over and over again as the user continues to go from one user to the next. This doesn't look nice to me and I thought about storing all user ids temporarily in a session (max 200 to previous users and max 200 to upcoming users) to avoid store the parameters and run the search query every time the user vists another profile page.
Is this a good way or do you have other solutions?
Best regards and thanks in advance for your help,
Freddy
Answer: You could simply store the id's as an array in a session, and then put next/previous links to the next/previous items in the array.
Comment: Also consider if the data is subject to change while a search is being viewed. ie 40 guy dublin blond changes to 20 girl new-york ginger LOL. Or adding a new entry (start of search order) makes the next record (all records move down one) display the current one again. +1 Brian
Answer: Wit small number of total matches (under 200 for example), storing IDs in the session is perfectly fine.  If you potentially expect a large number of results in the search (in thousands), then a better solution may be to implement a temporary table for the searches. When a search is performed, the IDs and names of the matches are stored in a temporary table against the session ID of the user.  You'd need to also have a script that runs periodically and cleans this table of old data.

user search engine - go back and forth


How to best avoiding capo introduced sharpening?

Question: In answer to a capo tuning question, one user suggested the use of a 'shim' (for lack of a better term, he actually suggested a .022" cut feeler gauge) between the fret board and strings under the capo near center between frets. I was thinking something similar as my capo clamps the strings to the fret board sharpening all 6 strings. Why isn't this answer 'liked' by the community at large? I'm going to try a few scraps of plastic or rubber of a thickness just less than the fret height to avoid the bend into sharpness and may get back with an answer (once given a nod by the Stack Exchange gods as a newbie).
Comment: Purchase a G7 capo, and play with unsharpened strings. One reason for the sharpening effect is a high action.
Comment: How is it that a capo sharpens the pitch but fingering the same note does not?  I suspect you have a problem with bridge and/or nut height.
Comment: I'm not sure how this question is distinct from the other capo tuning questions on this site. If you are asking about the drawbacks of the method in question, perhaps you could rephrase your post along those lines.
Comment: The distinction was that this shim idea seems like a useable solution to the capo induced sharps (without champion). Also, all capos introduce sharps regardless of setup. Higher action and larger frets increase the effect. Another user asked if fingering introduces sharps like capos do. Fingering does, as it deflects the string increasing its length and thereby its tension. This is reduced with a finger due to less deflection (rounded finger versus square capo) and less pressure (look w e-tuner). Playing with just enough pressure to get the string to contact the fret will mitigate effect.
Comment: To help clarify why I'm advocating the 'shim' idea. The physics of the guitar has always appealed to my engineering mind. I noted this problem not long after learning to tune a guitar and how that changes when adding a capo. The why became apparent and it also became apparent that there is no perfect solution here, but this 'shim' idea does physically mitigate it the best... IMHO. I'm contemplating modifying my capo to have the shim attached to it, sliding it under the strings while capo bar goes over and clamp under. I'll experiment and post my results.
Comment: Why do you think all capos introduce sharps? And why do you think capos have to have straight edges? Get a good capo, and it won't sharpen your notes, as it doesn't need to clamp all the way to the fretboard, and will have a rounded edge.
Answer: The first thing I would get checked would be the action on the guitar. If it is high, the capo will stretch the strings out of tune. That can be adjusted. Another thing that can cause sharpening with a capo is large frets. Even with a well adjusted action, a capo and large frets can result in sharpening the note. Large frets have their own advantages so the guitars I own with large frets, I try not to capo, and I use them when I want to string bend.


Transit visa in the UK and Canada for Libyan citizens

Question: Do Libyan citizens who live in Libya and don't hold any other nationality need transit visas for the UK and Canada? The plan would be to travel on British Airways from Istanbul, Turkey to the Dominican Republic, with stops in the those two countries.
Comment: @pnuts Not a totally worthless question, since it should be pointed out that he doesn't even need a Dominican visa.
Comment: See also: http://travel.stackexchange.com/questions/30522/is-there-a-way-to-find-out-if-i-need-a-transit-visa-for-canada
Answer: As stated in Timatic, the database used by Airlines, you will need a visa to change planes in Canada.
As stated on the GOV.UK website, if you change flights in the UK and have a valid Canadian visa, you do not need a UK transit visa.
Similarly, for the Dominican Republic, also according to Timatic, you can enter on a valid Canadian visa.
So, you only need a Canadian transit visa, and no other visas. No visa for the UK and no visa for the Dominican Republic.
If you're flying back the same way, then, when applying for the Canadian visa, tell them that you need to transit Canada twice, so they'll give you the correct visa.
Comment: I would want to double-check that a Canadian transit visa counts for the purposes of issuing a UK transit visa.
Comment: @DJClayworth Double check with whom? The GOV.UK Website clearly says "Rule clearly says "a visa for Canada, New Zealand, Australia or the USA (this can be used for travel to any country)"


What is being deprived when a photon is being watched in double slit experiment?

Question: How are photons being watched in the double slit experiment? What exactly does being observed mean, as it is obviously changes the state of the photon somehow - it must be depriving the photon of something or emitting something that interacts with the photon.
Answer: Usually the photon itself is absorbed, changing the state of some locus on the absorber.
For example, if the detector is a CCD, the photon is absorbed thus changing the state of charge carriers in the cell. Or the absorber could be a photographic film, which would change state of its emulsion in the neighborhood of the molecule which absorbed the photon.
So, in most cases the photon is deprived of its own existence.
Answer: I don't know which detectors are usually used for the detection of photons. But there's also a double slit experiment with electrons, i'll explain some stuff about that. You might be interested in particle detectors such as cloud, bubble or spark chambers. The detection is done as a result of the ionizing effect of the passing particle. You could see an 'observation' as some kind of physical interaction (collision, ionization, electromagnetic forces,etc...). Note that electrons interact with air (else a cloud chamber wouldn't work), so the experiment must be done in a vaccuum chamber in order for an interference pattern to appear. To make the interference pattern collapse, you could put tiny cloud chambers at the slits for example. For photons, a vaccuum chamber is not needed, since they pass through air without interacting with it (after all, air is transparent).
Comment: Tiny cloud chambers at the slits? 1. How could this be realizable? 2. Why would you want to observe electron _at_ the slit instead of the screen in double-slit experiment?
Comment: @Ruslan If u want the interference pattern to collapse, you need to have which path information, hence you'll need to observe the particle at the slit. Maybe tiny cloud chambers aren't really convenient, I just used it to illustrate. A better choice would be to use a spark chamber like detection (same principle as geiger counter).
Comment: Well, you don't want to _break_ the interference pattern. In particle-resolved experiment you just want to see the pattern to _build up_, watching collapse of the wave function of each subsequent electron. If you get the "which path" information, you'll get just two superimposed single-slit diffraction patterns.
Comment: I found this article intersting: http://iopscience.iop.org/1367-2630/15/3/033018/article
Where they simply adjust the width of the slits.


Siri Sounds Robotic in macOS Sierra

Question: Since I upgraded my MacBook Pro(mid-2012) to macOS Sierra the voice which is being used by Siri is unnatural.It sounds like the old iOS 6 Siri.I downloaded all the dictation voices but the problem persists.Somwhere on the internet I found a solution saying that enabling checkboxes under App Store auto-update fixes the issue but Siri still sounds the same.Does anyone have a concrete solution?
Answer: The Siri natural (enhanced) voice has to download. If you've got a slow connection it might be a few days before Siri has the voice that you have become accustomed to.
Comment: Is there any way to see the progress of the voice being downloaded?

Siri Sounds Robotic in macOS Sierra


Password protect google chrome

Question: Is there any way to password protect google chrome browser? So that I can do "Remember password" on sites browsing in chrome in a shared computer and others can't access it
Comment: How would you like it if you sat down at a shared computer and Chrome was restricted?
Answer: Depending on your system you could encrypt your Chrome Profile Folder (TrueCrypt in Windows, equivalent ones on other operating systems)
Before starting chrome, you mount your encrypted archive, then use
chrome.exe --user-data-dir="<location to profile>"

to start the browser using that directory.
P.S.: You can put a specific link on your desktop with the parameter for the profile location, so others can use chrome with the default profile.
Comment: Sure, but if it's in a secure archive it is protected from others who use that computer.
Comment: I'm afraid that's only giving the illusion of security. It's very much like getting a new car and putting the keys in a safe. Chrome is not very secure password-wise. The userprofile is only one place Chrome can write to.
Answer: One more useful tool very similar to Truecrypt - Rohos Mini Drive. I'm using it's feature - Hide folder to password protect my Google Chrome profile - http://www.rohos.com/2010/12/how-to-password-protect-google-chrome-data-with-rohos-encryption-software/
Answer: Unfortunately Chrome doesn't allow you to password protect user profiles anymore.
Basically, you load your Chrome Profile from an encrypted volume using Veracrypt residing in the computer or your external USB drive. When you're done, close Chrome and simply unmount the volume. You can do similar for Windows or Mac OS but specifics may differ. You may need admin privileges to mount/unmount.
Here is my setup in my Ubuntu 18.04:
First create a new User Profile in Chrome.
Open Terminal
cd ~/.config/google-chrome
ls -al

You should see a new profile directory that is just created say, 'Profile 4'.
Sync to your Google profile and all Chrome extensions now if you like so you know roughly how much space to allocate on the encrypted volume. Example:
du -ch 'Profile 4'

Create encrypted Veracrypt volume file
Download GUI or Console version of Veracrypt for your OS distribution.
Create encrypted volume file somewhere not so obvious example:
touch ~/.config/profile.vc

Here is an example of using Veracrypt from the Terminal to create 256 MB (check your space requirement) Ext4 encrypted volume for your User Profile. You can use the GUI version if you want.
veracrypt -t -c --volume-type=normal ~/.config/profile.vc --size=256M --encryption=aes --hash=sha-512 --filesystem=ext4 --pim=0 -k "" --random-source=/dev/urandom

You will be prompted to assign your password. Also, enter administrator password if asked.
Mount Veracrypt volume you just created. Your mount directory now becomes something like /media/veracrypt1
After mount is successful, close Veracrypt GUI if you are in a shared computer.
Exit any running Chrome applications – important!
Move chrome profile directory to your encrypted volume.
mv 'Profile 4' /media/veracrypt1/.

Create a symbolic link.
ln -s "/media/veracrypt1/Profile 4" 'Profile 4'

Open Chrome and you can now switch to your user profile from encrypted volume.
When done, quit the whole Chrome application.
Then unmount your encrypted drive from Veracrypt and open Chrome again. You'll see your extra Chrome Profile avatar but can't switch into it.
Script for convenience
Create a bash script and make it executable.
touch ~/.config/profile
chmod +x ~/.config/profile
vim ~/.config/profile

Add the following to the bash file:
#!/bin/bash
VOL=~/.config/profile.vc
if [ $1 -eq 1 ]
then
    echo "Mounting..."
    veracrypt -t -k "" --pim=0 --protect-hidden=no $VOL /media/veracrypt1
    sleep 2
    nohup google-chrome --profile-directory='Profile 4' &>/dev/null &

elif [ $1 -eq 0 ]
then
    echo "Dismounting..."
    pkill --oldest chrome
    sleep 2
    veracrypt -t -d $VOL
else
    echo "Usage: ./profile 0 or ./profile 1"
fi

Usage
To mount encrypted volume and open Chrome using your user profile
. ~/.config/profile 1    # Prompts for your password :)

To close Chrome and unmount encrypted volume
. ~/.config/profile 0

Hope it helps!
Answer: Chrome's passwords are encrypted with your login password, at least on Windows, though very weakly. I'm going to have to say that it's a bad idea to use the browser's built-in password manager no matter what. Google Chrome can import Firefox's passwords even if Firefox's passwords are under a master password.
Use a dedicated password manager that is at least reasonably secure. The safest is probably KeePass because it's been around for quite a while. Lastpass is another option that is reasonably secure, but if you're working on the CIA, keep in mind that it hasn't been audited by any independent organization yet (KeePass hasn't been audited either, but it's open source, so thousands of people can and have read through the code for security flaws and those flaws are fixed very quickly).
In summary: if you're paranoid, use KeePass. If not, use LastPass.
Answer: You could try using the LastPass plugin to have an online and extremely secure password vault. Just turn off automatic login and your set. It even has the bonus advantage of a web interface and portability.
Answer: Use Discolock a freeware small utility, which password protect many applications.
Answer: On the Chrome toolbar
click on the '+" sign to open a new tab
left click on the "3" vertical dots at the far right with your mouse
when the menu opens, click on "settings"
the "search" bar will show a "navy blue chrome Icon"   followed by the word "Chrome", a vertical line, then chrome://settings
the menu that opens up after left or right clicking with your mouse on the word "settings" brings up a new menu that starts with the word "People" as a heading, followed by a vertical list starting with your Google sign in that shows "Syncing to email@example.com", etc. (see pic)
From this list, click on the "Passwords" word
Now you will see in the "address/search bar": "Chrome | chrome://settings/passwords"
From here you take your mouse and left click and "Hold" on the nave blue chrome icon in the "address/search bar".
"DRAG" that "navy blue chrome icon" to your toolbar where you have your "other" shortcuts and
VOILA !
YOU NOW HAVE A SHORTCUT TO YOUR PASSWORDS RIGHT ON YOUR TOOLBAR…
…it will now show a "navy blue 'settings' icon" with the word "Settings" next to it.
Now every time you open your Chrome browser, it will be there for you to access in "ONE CLICK"
Comment: The question asked how to prevent other people getting access to the passwords,not how to make them easier to access,
Answer: I'm using a Dashlane extension for Chrome which connects to Dashlane password manager.
Using this app, you can import all your Google passwords (since it's not clear how they're secured), and after importing consider removing them all as they're still stored in the cloud and you can see your of all passwords by going to https://passwords.google.com/
See also:

Dashlane Security White Paper [2018]
Security analysis of Dashlane

Password protect google chrome


Using cylindrical coordinates to find center of mass of solid of uniform density

Question: Using cylindrical coordinates to find center of mass of solid of uniform density given by
$$x^2 + y^2 \le \frac{1}{4},\quad x^2 + y^2 + (z-1)^2 \le 1,\quad z \le 1.$$
I don't know how to set up the integrals. Can someone please help?
Answer: Note that your solid is the intersection of a cylynder and  a hemisphere. It is given by
$$S:=\left\{(x,y,z)\in\mathbb{R}^3\::\; 1-\sqrt{1-(x^2+y^2)}\leq z\leq 1,\; x^2 + y^2 \leq \frac{1}{4}\right\}.$$
Moreover, by symmetry, the center of mass is along the $z$-axis.
Hence  you need to evaluate the $z$-coordinate only:
$$\bar z=\frac{\iiint_S z dxdydz}{\iiint_S  dxdydz}$$
Use the cylindrical coordinates.
Can you take it from here?


best practice: native table or inserted figure

Question: I have a relatively small table of data I would like to insert into my thesis. Is it better to natively create a table, or to externally create the figure and insert it?
Comment: This is a matter  of opinion, but you must know there are packages which can make a LaTeX table from a .csv file, among which `csvsimple` and `datatool`.
Comment: Without knowing anything about the table it is impossible to say. You could ask the same about a paragraph of text, whether to typeset it with tex or typeset it in something else and include as an image. On the face of it, if you have chosen to typeset the document in tex, using tex for typesetting seems the natural choice unless there are constraints that you have not mentioned.
Answer: A table of LaTeX code is only a chunk of text that could be placed inside the main document or in an external file, at convenience, but as an image could be only a heavier file (JPG, PNG), placed externally, may be of medium (PNG), low (JPG) or good quality (PDF) but anyway you cannot edit the table directly, so should maintain also the source-s file to create that table (spreadsheets, etc.). Let'see: At least 3 files instead of only one for a small document with a single table. If the document have, said, 20 tables, the source files might be up to 41 editable/non editable files (surely many Mb) instead of a single file of ridiculous size.
Another issue is the quality of the table itself. Using images will be difficult match consistently the font sizes, font styles, interline spacing, spaces above/below the table, etc., with the rest of the document.
Finally, make tables in LaTeX need some learning, but then make/edit  elegant tables is easy. When you know enough, edit a table in a WYSIWYG word processor is pain.  If that is not enough, you can import data from external sources in several ways (as cited by Bernard, csvsimple, datatool, but also exist excel2latex, exceltex, odsfile ...) not to mention R/knitr for the automatic generation of LaTeX tables.
These aspects are not a matter of opinion, but it is how important are for everyone and the weight of the circumstances. It could be understood use a screenshot of a table taken from a web page, for instance, in case of emergency (experts),  ignorance (novices) or impatience  (bunglers), but for me (me and my circumstances) there are no doubt: never ever.
Comment: @CarLaTeX Why srtagne? Aaoccdrnig to a rsecheearr at an Elingsh uinervtisy, it deosn't mttaer in waht oredr the ltteers in a wrod are, the olny iprmoetnt tihng is that frist and lsat ltteer is at the rghit pclae. The rset can be a toatl mses and you can sitll raed it wouthit a porbelm. Tihs is bcuseae we do not raed ervey lteter by itslef but the wrod as a wlohe. `:)`
Comment: +1! What does ìt mean "blungers"?
Comment: @CarLaTeX It means I have dyslexia `:(`
Comment: That's why the meaning of what I found in the dictionary seemed very strange in this context! Hahaha!
Comment: @CarLaTeX Isn't it obvious?  Blungers are those who blungle their typing.
Comment: @Fran Do you spend your nights awake wondering if there is a dog?
Comment: @Fran Indeed, I have understood everything you have just written, and I'm not native English speaker, incredible!
Comment: @StevenB.Segletes :)
Comment: @StevenB.Segletes Yes, agnostic and insomniac  too.  `:)`


How can we encourage users to accept correct answers?

Question: I have been reading the meta a little bit, and there are some questions about encouraging people to ask more questions, doing more voting-up for good questions, and the like.
I was wondering how can we encourage users to accept answers for their questions. The numbers (statistics) for the site look amazing. Questions are answered quickly, often get more than one answer and usually really well explained (I can tell that there's some users here that are real pros), but many of those questions don't have an accepted answer.
I think that accepting the answers (and voting up, of course) helps to show that users do find a quality answer for their questions, that they are happy with their experience on this site and that this stack is useful and a valuable tool. I'm also positive that it would be very good for the community and could help us to move further on getting beyond the beta phase.
How can we encourage users to accept what they think is the besta answer to each of their questions?
Answer: I don't think there's a good way.  There are a lot of fly-by question asking.  People will ask the question, then probably lose their log-in information and not come back to the site.  We could try to have a non-question-answerer suggest in a comment that they accept an answer (so as not to appear too biased), but if they don't log back on....


3.2 upgrade, drafts table error

Question: When I try to upgrade to 3.2 on my site I get an error saying the drafts table already exists.  Does anyone know of any plugins that use such a table?  I'm trying to sort out what's going on.
Answer: Sounds like you didn't completely roll the database back to 3.1 before re-trying the update. That table probably got created the first time you tried to update to 3.2.
Make sure the database is wiped 100% clean before rolling back to your 3.1 database. Then try updating again.
Comment: That'll be hard to do with a prod database, but I'll see what I can do with it.  Do you have any suggestions?
Comment: Do you have a copy of the database from before your first attempt?

3.2 upgrade, drafts table error


Why is Bitcoin address encoded in base58?

Question: Why does bitcoin address encoding use base58 instead of, for instance, base64? I don't see it is useful in any way.
Answer: Why base-58 instead of standard base-64 encoding?

Don't want 0OIl characters that look the same in some fonts and
 could be used to create visually identical looking account numbers.
A string with non-alphanumeric characters is not as easily accepted as an account number.
E-mail usually won't line-break if there's no punctuation to break at.
Double-clicking selects the whole number as one word if it's all alphanumeric.

Features of Base58Check

An arbitrarily sized payload
A  set of 58 alphanumeric symbols consisting of easily distinguished uppercase and lowercase letters (0OIl are not used)
One byte of version/application information. Bitcoin addresses use 0x00 for this byte (future ones may use 0x05).
Four bytes (32 bits) of SHA256-based error checking code. This code can be used to automatically detect and possibly correct typographical errors.
An extra step for preservation of leading zeroes in the data
Comment: "Future ones"... the v5 prefix is used for P2SH addresses, and has been since 2012.
Comment: For reference: This explanation is also inserted as a comment in the bitcoin source code, see https://github.com/bitcoin/bitcoin/blob/0.16/src/base58.h#L7-L12
Comment: **broken url** [https://github.com/bitcoin/bitcoin/blob/0.16/src/base58.h#L7-L12](https://github.com/bitcoin/bitcoin/blob/0.16/src/base58.h#L7-L12) 404 not found -- recorded on 2023-01-11


CakePHP input field for age range. Not sure about how to approach this

Question: I am creating an experimental search form with CakePHP, and I am reading the CakePHP manual and studying other tutorials on this subject.
There seems to be a LOT of ways searching is done, and I am trying to decide on the best pattern. In the meantime, coming up with some "unresolvable" questions.
I've read several tutorials and also tried the CakePHPDC search plugin with no luck at all. And most of the tutorials I found keep the query login in the Controller which seems like the model is the appropriate place...
I am a bit lost on all of this, so please any simple guidance or suggestions would be appreciated.
And back to my initial problem:
I am creating the age range input field like -
<code>echo $this->Form->input('Plan.age_id');
</code>
BUT the first parameter is treated as the Model.field name: Plan.age_id, so this is the field data that will be gathered.
But my Age table has: min_age and max_age fields. I need to run a comparison on the min and max based on the Plan.age_id data?
I am just not sure if I am approaching this right.
And excuse my ignorance, I am very new to messing with search queries in CakePHP.
Answer: Sounds like all you need to do is formulate an appropriate search query from the given data:
<code>$this->Plan->find('all', array(
    'conditions' => array(
        'Plan.min_age <=' => $this->data['Plan']['age_id'],
        'Plan.max_age >=' => $this->data['Plan']['age_id']
    )
));
</code>


How do you go to school or How do you get to school?

Question: Which is correct between How do you get to __ vs How do you go to ___? Can you also explain why it's the correct way to ask this question or how do they differ?
Comment: Please edit your question to tell what meaning you're trying to convey. Neither one is wrong, but they emphasize different things. To pick a different example (to eliminate the confusion with "attend school"): "... get to the store" vs "... go to the store": *get to* emphasizes arriving at the destination; *go to* emphasizes the process. I might "go to the store [in a hurry], or [while hungry]." But I "get to the store [by car, bus, or subway]."
Comment: You could use _get_ or _travel. Go_ sounds a bit odd to me, because _go to school_ often means _attend school_; but in some contexts it might be used for asking about the mode of transport.
Answer: Both:

"How do you go to school?" and
"How do you get to school?"

are grammatically acceptable.
The Cambridge dictionary has a page about "get vs go", including warnings and arguments can be made for why each sentence is preferred by some over the other, but both sentences are used commonly where I live (I was born and raised in Ontario, Canada and did my PhD in Oxford, England).


How could malware survive hard disk drive format without residing in the firmware?

Question: For example could it "trick" most partitioning/disk utility tools that it was successfully wiped, but with the malware still existing? Kinda similar to what would happen if you attempted to "clean" flash an infected BIOS, where it would inform you that you flashed it, but in fact nothing happened and it's still compromised.
Answer: Malware could survive without being in the firmware by hooking OS disk access calls and preventing anything from wiping it within the compromised OS.
If you were to live boot to a known clean OS or wipe the hard drive by removing it from the existing system (and you knew the malware was not residing in firmware), you could probably successfully wipe it, but there are caveats:
Do you know the hard drive itself isn't compromised?
The hard drive could theoretically be engineered with another chip that stores a copy of the malware and rewrites it after a successful wipe.  Yet another concern would be malware hiding in a different piece of hardware within the system (either via firmware infection, or hardware implant), thus effectively evading any attempts to clear it by wiping or replacing a hard drive.
The above mentioned process of using a live CD is also potentially fraught with potential peril.  Do you trust the BIOS?  What about the boot-up chain? Modern OSes often use a boot system called UEFI which is at least partially controlled by data that resides on the drive.  Though there are controls in place to try to prevent unauthorized tampering with the boot process, it may be possible for malware to inject itself into that boot chain. Even more low-tech, is malware running on a USB device or in a place to emulate a USB device, if the boot priority allows booting from USB devices before the hard drive.  Once again, the malware could load, and inject itself into any later boot processes, even transparently handing off booting to the "normal" OS after hooking it. If you've ever broken a Linux grub install, you may have experience booting to the grub shell via a live CD or USB, then manually typing code to hand-off execution to the Linux installation on the hard drive, which is similar to the process malware might employ.
Comment: I was thinking more about the possible entities of the hard drive  where the virus could persist but other than that yes, it would survive reformating if it was a UEFI or SMM malware and an HDD compromise wouldn't be necessary.
Answer: If your reformatting software was itself infected, then that would be one way. If the reformatting software is correct and has no backdoors and is ran from an external media and your BIOS is clean, then I think there aren't really any other places for the malware to trick you outside of the firmware itself, which you ruled out. The one exception would be if your hardware has the backdoor built into it.


Where is the PDF encryption key stored

Question: Assuming you have the user protected PDF file. Using the password, the cryptographic key is generated and the file encrypted. Where is the key stored, is it on the RAM every time the file is opened?
Comment: @schroedor The linked-to answer doesn't seem to answer this question. The linked-to question has to do with whether the sender of a PDFs necessarily has access to the sendee's password in cleartext, since that is what the sendee subsequently uses to open the PDF (and so the linked question asks whether the remote sender has a stored copy of the sendee's password). This question seems to be more about where the encryption key generated from the password is stored locally.
Answer: I am not an expert on either the PDF spec or PDF readers, but I would guess the encryption / decryption key for a cipher like AES is derived from the password using a Password-Based Key Derivation Function such as PBKDF2, and that the password and key are only held in memory long enough to decrypt the document. After that you can zero out both the password and the key and only keep the decrypted document in memory.

... some googling later ...
According to this old article describing the behaviour in PDF 1.3 (Acrobat 4.x -- 1999), it does seem to be the case that the content encryption key is derived on the fly from the password. I'm sure the ciphers and key lengths have since been updated to something more modern, but I would guess that the general scheme is the same.

The encryption key is generated as follows:

Pad the user password out to 32 bytes, using a hardcoded
32-byte string:
28 BF 4E 5E 4E 75 8A 41 64 00 4E 56 FF FA 01 08
2E 2E 00 B6 D0 68 3E 80 2F 0C A9 FE 64 53 69 7A
If the user password is null, just use the entire padding
string.  (I.e., concatenate the user password and the padding
string and take the first 32 bytes.)

Append the hashed owner password (the /O entry above).

Append the permissions (the /P entry), treated as a four-byte
integer, LSB first.

Append the file identifier (the /ID entry from the trailer
dictionary).  This is an arbitrary string of bytes; Adobe
recommends that it be generated by MD5 hashing various pieces
of information about the document.

MD5 hash this string; the first 5 bytes of output are the
encryption key.  (This is a 40-bit key, presumably to meet US
export regulations.)
Comment: +1.  I'm not an expert on PDF standards either, but I sure hope this answer is correct.  It doesn't make sense that the key would be stored persistantly.  I would assume that it works similarly to the way openssl does AES encryption and key derivation (see https://crypto.stackexchange.com/questions/3298/is-there-a-standard-for-openssl-interoperable-aes-encryption).

Where is the PDF encryption key stored


How do I setup an OpenShift route that will allow both 80 and 443 traffic to my app?

Question: I'd like to setup a route that will pass both 80 and 443 traffic to the same service in OpenShift. When I try to create a second route it errors out. I want this to be in a yaml like would be used with oc create -f route.yaml so I can submit it to our IaC code repo.
Comment: Could you add the logging?
Answer: You'll want to be sure your spec.tls section has the following two items to tell the router you want both secure and insecure traffic allowed in the edge.
apiVersion: route.openshift.io/v1
kind: Route
metadata:
  name: my-app-ui
  namespace: my-namespace
spec:
  host: my-host
  port:
    targetPort: http
  tls:
    insecureEdgeTerminationPolicy: Allow
    termination: edge
  to:
    kind: Service
    name: my-app-ui
    weight: 100
  wildcardPolicy: None


wmd-editor breaks in IE8

Question: We have recently started using WMD editor and found that in IE 8, it just goes on increasing the scroll size of the page by simply increasing the size of the textarea endlessly. The only option left is to close the browser after that causing lot of frustration. you can check wmd-editor demo here. does anybody know of any solution to this issue ?
Comment: This is the old script, try with some of the new versions: http://github.com/cky/wmd/tree/master   OR (mine) http://moowmd.awardspace.info/
Answer: after a lot of trial & error, we finally found the issue and fixed it ourselves. None of the  parent container of the div in which the wmd editor is placed into should have the css property position defined. else, it will break the editor in IE8.

wmd-editor breaks in IE8


Webservices are stateless?

Question: Why do we say that web services are stateless?
Answer: They don't persist any state between requests from the client.  i.e. the service doesn't know, nor care, that a subsequent request came from client that has/hasn't made a previous request.  Basically, its a 'give me this piece of info and forget about me' which puts the onus on the client to maintain any state.
Comment: The version I commented on was a lot shorter, and basically said "because they dont persist state." I'm deleting my comment plus here's an upvote.
Comment: @mike:  my bad.  I felt the same way.  That's why I updated it.
Comment: @brian: What about subscription streaming in EWS 2010 onwards? Does that keep some type of state like an open TCP connection from the EWS web server to the Exchange server? The reason I am asking is because of performance. Also with general request, is there an overhead on the server in terms of sessions left open from the EWS web server to the exchange server?
Answer: Because web services are based on HTTP, which is a stateless protocol.
Quoting wikipedia :

A stateless server is a server that
  treats each request as an independent
  transaction that is unrelated to any
  previous request.

i.e. each request is independant from the previous one : even if we use some "tricks", like cookies for instance, to preserve some state between requests, this is not something defined by the protocol.
Comment: There's a big difference between a stateless protocol and stateless web service. The application can be stateful (using "tricks", as you mention) while the underlying protocol is stateless. Also, web services do not necessarily imply HTTP. SOAP can work with SMTP as a transport layer, for example.
Comment: I would hesitate to call an SMTP SOAP service a "web service". There are lots of types of services, but to me, web service = HTTP or HTTPS. SMTP was around before the web. So I think Pascal's correlation is fine.
Answer: Because HTTP is stateless. After a client request is fulfilled by the server, no information is stored for use in future transactions.
Answer: The concept of a web serivce is to model a RPC (Remote Procedure Call) aka a Function. Thus you should not need to use session. In addition, the idea of being stateless comes from the need to scale out web servers into a server farm and thus enable higher capacity.
However, the choice of using state is dependant upon the technology and the developer. There is nothing to prevent you from creating an ASP.Net Web Service and setting "EnableSession=True" in the method definition.
This can be useful in some basic authentication scenarios, i.e. home-grown forms authentication or to provide automatic correlation for short-lived "workflow"'s. (However I strongly urge you consider more modern techniques will provide a higher level of security and performance).
Answer: Requests are independent from one another.

Webservices are stateless?


Heun's method: Why is it of second order?

Question: I want to get an intuitive understanding of Heun's method and why it has order of consistency 2, i.e. the error lies is in $O(h^{3})$ if $h$ is the stepwidth., I have read it everywhere, my professor says it without proving it. All the resources I have seen so far on the web either omit the proof as trivial, and the only one that does the proof does it wrong. I am at a loss. Can someone explain it to me in as much detail as possible?
Comment: You should be able to prove that by computing a Taylor expansion of the solution up to the 4-th order, with reference point $t_n$ and compare this expression obtained in $t_{n+1}$ with the actual Heun method final step, and see that the terms cancel out up.to the third order included.
Comment: i have tried to do that, but failed. Can you explain it to me in détail?
Comment: I'll try to write an answer later !
Comment: Do you understand that/why the composite trapezoidal quadrature has order 2? Do you accept in some way that a method with a local truncation error of $O(h^{p+1})$ has (if at all) a global error order of $O(h^p)$?
Answer: I am assuming you mean the explicit method given by
\begin{align}
&k_1 = f(t_n, y_n) \\
&k_2 = f(t_n + h, y_n + hk_1) \\
&y_{n + 1} = y_n + \frac{h}{2}\left(k_1 + k_2\right)
\end{align}
To analyze truncation error, assume $y_n = y(t_n)$.
From Euler's method we know
$$y_n + hk_1 = y(t_n + h) + O(h^2)$$
Therefore by Taylor expanding the y argument to the first degree
$$k_2 = f(t_n + h, y(t_n + h) + O(h^2)) = f(t_n + h, y(t_n + h)) + O(h^2)$$
Hence Heun's method is almost the trapezoid method for integration applied to $f$ to approximate $y(t_n + h) - y_n = \int_{t_n}^{t_n + h}f(t, y(t))\,dt$ except that it differs from it by $\frac{h}{2}O(h^2) = O(h^3)$. The trapezoid method is known to be $O(h^3)$ locally, so the error of Heun's method is $O(h^3)$ since it differs from the trapezoid method by $O(h^3)$.
Alternatively, Taylor expanding Heun's method and comparing it to the Taylor expansion of $y(t_n + h)$ will give you the result. This strategy can give the conditions for a Runge Kutta method to achieve a desired order.
For example for two stage methods of order 2:
Assume a method of the form
\begin{align}
&k_1 = f(t_n, y_n) \\
&k_2 = f(t_n + c_2h, y_n + ha_{21}k_1) \\
&y_{n + 1} = y_n + h(b_1k_1 + b_2k_2) \\
\end{align}
Then Taylor expanding $k_2$ to $O(h^2)$ gives
\begin{align}
k_2 &= f + f_{t}c_2h + f_{y}ha_{21}k_1 + O(h^2) \\
&= f + (c_{2}f_{t} + a_{21}f_{y}f)h + O(h^2).
\end{align}
where the arguments $(t_n, y_n)$ are omitted.
Hence
\begin{align}
y_{n + 1} = y_{n} + (b_1 + b_2)fh + (b_{2}c_{2}f_{t} + b_{2}a_{21}f_{y}f)h^2 + O(h^3).
\end{align}
On the other hand,
\begin{align}
y(t_n + h) = y_{n} + y'(t_n)h + \frac{y''(t_n)}{2}h^2 + O(h^3).
\end{align}
Since $y'(t) = f(t, y(t))$, we get
\begin{align}
&y'(t_n) = f \\
&y''(t_n) = f_t \cdot 1 + f_yy' = f_t + f_{y}f.
\end{align}
Therefore
$$y(t_n + h) = y_n + fh + \frac{f_t + f_yf}{2}h^2 + O(h^3)$$
Matching terms gives
\begin{align}
&b_1 + b_2 = 1 \\
&b_2c_2 = \frac{1}{2} \\
&b_2a_{21} = \frac{1}{2}.
\end{align}
Heun's method is $c_2 = 1$, $b_1 = b_2 = \frac{1}{2}$, $a_{21} = 1$.
Comment: Could you elaborate.on that "taylor-expanding Heun's method and comparing it to the Taylor expansion" is exactly where I always fail. I always have one factor of 1/2 too many, and I don't know where it comes from.
Comment: @TheThinWhistler I've added the Taylor expansion derivation for the easiest case of two stage methods of order 2 (Heun's method is one of them).
Answer: Here is my attempt at a proof of the order of the Heun's method using Taylor expansions.
Let's suppose $y(t)$ is the true solution of the autonomous ODE $d_t y = f(y)$ and assume $y$ is scalar for the sake of simplicity.
Let's suppose we have $y_n = y(t_n)$. The value at time $t_{n+1}$ given by the Heun's method is:
$$y_{n+1} = y_n + \frac{\Delta t}{2} f(y_n) + \frac{\Delta t}{2} f\left( y_n + \Delta t f(y_n) \right)$$
Let's express the last term using a Taylor expansion:
$$ f\left( y_n + \Delta t f(y_n) \right) = f(y_n) + (d_y f)(y_n) (\Delta t f(y_n)) + (d_{yy} f)(y_n) \frac{(\Delta t f(y_n))^2}{2} + (d_{yyy} f)(y_n) \frac{(\Delta t f(y_n))^3}{6} + O(\Delta t^4)$$
Inserting this expansion back into the first equation yields:
$$y_{n+1} = y_n + \Delta t f(y_n) + (d_y f)(y_n) \dfrac{\Delta t^2 f(y_n)}{2} + (d_{yy} f)(y_n) \frac{\Delta t^3 f(y_n)^2}{4} + O(\Delta t^4)$$
Now let's perform a Taylor expansion of the true solution:
$$y(t_{n+1}) = y_n +\Delta t (d_t y)(y_n) + \dfrac{\Delta t^2}{2} (d_{tt} y)(y_n) + \dfrac{\Delta t^3}{6} (d_{ttt} y)(y_n) + O(\Delta t^4)$$
which we can develop into:
$$y(t_{n+1}) = y_n +\Delta t f(y_n) + \dfrac{\Delta t^2}{2} (d_{y}f)f(y_n) + \dfrac{\Delta t^3}{6} ( (d_y f)^2 f + f^2 (d_{yy} f))(y_n) + O(\Delta t^4)$$
Comparing the terms of equal power of $\Delta t$ in the expressions of $y_{n+1}$ and $y(t_{n+1})$ we see that the local truncation error is  is of order 3, therefore the method is of order 2.
The answer provided by @mason is more elegant, but here we see what the term in $O(\Delta t^3)$ is.


Are there any languages that don't have/use auxiliaries?

Question: Question pretty much says it all, I'm curious as to whether every language uses/requires auxiliary verbs to express tense/modality/aspect etc.? Thanks.
Comment: Anixx, there are lots of IE languages, ancient and modern, that do not use "auxiliary verbs for the future". For example Greek, Latin....
Comment: I think what the question needs is "as opposed to what?". Adverbs/particles? Where do you draw the line between aux. verbs and conjugations/conjugational suffixes? By the way, I seem to remember having seen analyses that state that English modal verbs are more particles than verbs (based on some syntactic criteria).
Comment: @Anixx By morphological merger, an auxiliary in the past can become an inflected form. This is what happened with French *futur simple* (and hence French normally does not require an auxiliary for the future tense, though one is common for proximate future constructions).
Comment: Actually, no, it doesn't. Some people use `Aux` as if it were defined by law, while others use it for any grammatical particle in an analytic language, like serial/small verbs, articles, or prepositions.
Comment: Unlikely any Indo-European because PIE had no future tense and modern IE languages thus need auxiliary verbs for the future (at least).
Answer: The precise answer to that question will depend highly on what is the precise meaning intended for auxiliary verb. If you insist that an auxiliary verb is a separate word which expresses a precise grammatical property, then Japanese is a likely candidate. In this language, tense, mood and modality are expressed by a specific ending attached to the stem-verb. None of these endings may live a separate existence (see here for a reference), so it would seem very strange to call them auxiliary verbs.
On the other hand, as the same reference indicates, there are verbs in Japanese which have an independent meaning but can also attach to a stem-verb to convey a nuance, as in

食べきる (eat it all) vs 食べる (eat)

where the verb きる which ordinarily means to cut has been appended to the verb to convey the idea that the action was brought to full completion. Just as one would normally not consider finish in

I finished reading.

as an auxiliary in English, I would not consider these Japanese constructions to be real examples of auxiliaries (in the traditional sense of English grammar).
I'm guessing that using a restrictive definition of auxiliary, there are many more examples, for instance in synthetic languages.
Comment: @hippietrail Like you, I think it all depends on what you call an auxiliary, and in fact giving a precise cross-linguistically robust definition might be quite hard.
Comment: What about する used to form so many verbs from nouns, such as 勉強します, to study? I've always found the term "auxiliary verb" to be pretty fuzzy though.


Capacitors as sensor output data storage?

Question: Can we use capacitors to be the input of an opamp? If we have a sensor and we store the value of the sensor in a capacitor, and we do that 2 different moments of the day (different capacitors) can we compare those 2 values? And how we will connect the capacitors to the opamp? Do we need to ground the plates with negative voltage?
Comment: Given your time scale you'll want to use an MCU and an ADC to store the first reading digitally for the (what sounds potentially) *hours* until you compare it to the second.
Answer: Given a suitably modest accuracy requirement,  large capacitor, high-impedance op-amp and low leakage conditions, it is nominally possible to do as you suggest. But it is unwise for anything more than a short period.
The main problem is that charge leakage will be unpredictable and may vary a great deal, with environmental conditions affecting the conductivity of the air and even condensation on the hardware. Dirt will accumulate after prolonged use and further degrade accuracy. Military-style encapsulation would help, but requires skill and experience to do well.
Charge-coupled devices (CCD), once widely used as camera sensors, are capacitance-based and implement a more complicated variant of just the principle you describe, but the charge need be stable only long enough for the CCD array to be read out into digital storage via an ADC, a time measured in seconds at most.
In practice you would do better to go down a similar route. And if you are doing that, why bother with the capacitors?
Comment: It is interesting that leakages provide paths for the input biasing currents; i.e., there is some benefit from them...
Answer:
Can we use capacitors to be the input of an opamp?

Yes, you can connect charged capacitors to the op-amp (comparator) inputs. The only problem are the op-amp input bias currents that will charge (discharge) the capacitors. Fortunately, they are too small (nA). So, if your capacitors have significant capacitance... or if you make the measurement quickly enough, there will be no problem.
So your arrangement is quite simple - the two capacitors are grounded and connected to the two comparator inputs.
Of course, the "silly" solution to provide paths for the bias currents is to connect resistors with high resistance between the op-amp inputs and ground.
BTW there is a special "sample & hold" circuit designed for this purpose.
Comment: Time, time, time.  The question mentions two values over the course of a **day.** A capacitor based sample and hold may work for seconds or maybe minutes if you put enough effort into it.  Holding for hours is just not a reasonable expectation.
Comment: @JRE, Right... There are also cascaded S&H but even that will not be enough. It seems the only solution is to measure by analog-to-digital conversion (ADC) and then memorize...


How can I avoid this poor Postgres query plan for a sparse aggregate query?

Question: I have the following database schema:
CREATE TABLE foo(
  id  SERIAL  PRIMARY KEY,
  tag INTEGER NOT NULL,
  val INTEGER NOT NULL
);
CREATE INDEX foo_tag ON foo(tag);
CREATE INDEX foo_val ON foo(val);

CREATE VIEW tag_min(tag, val) AS
  SELECT tag, MIN(val)
  FROM foo
  GROUP BY tag;

Here's a query that inserts some dummy data that reproduces my problem:
INSERT INTO foo(tag, val)
SELECT random() * 50000 AS tag
     , random() *   100 AS val
FROM generate_series(1, 1000000);

ANALYZE;

The problem
I would like to make a sparse query on the tag_min view. That is, I want to obtain MIN(val) for a small handful of tag values. If I know the values ahead of time, I can do this very easily using a query such as the following:
SELECT val FROM tag_min WHERE tag IN (1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

As expected, this query is extremely fast, as it essentially just performs a partial index scan for the ten tag values and aggregates them:
Subquery Scan on tag_min  (cost=744.01..748.13 rows=206 width=4) (actual time=0.708..0.710 rows=10 loops=1)
  ->  HashAggregate  (cost=744.01..746.07 rows=206 width=8) (actual time=0.707..0.709 rows=10 loops=1)
        Group Key: foo.tag
        Batches: 1  Memory Usage: 40kB
        ->  Bitmap Heap Scan on foo  (cost=45.90..742.98 rows=206 width=8) (actual time=0.045..0.671 rows=203 loops=1)
              Recheck Cond: (tag = ANY ('{1,2,3,4,5,6,7,8,9,10}'::integer[]))
              Heap Blocks: exact=199
              ->  Bitmap Index Scan on foo_tag  (cost=0.00..45.83 rows=206 width=0) (actual time=0.026..0.026 rows=203 loops=1)
                    Index Cond: (tag = ANY ('{1,2,3,4,5,6,7,8,9,10}'::integer[]))
Planning Time: 0.308 ms
Execution Time: 0.769 ms

However, in my real program, I do not have the tag values directly in hand. Instead, I obtain them via a join with another query. To keep the example as simple as possible, here's an illustration using generate_series to represent the subquery (my real query is of course less contrived, but the behavior is the same):
SELECT val FROM generate_series(1, 10) n JOIN tag_min ON tag = n;

Surprisingly, this query performs enormously worse—over 500× worse! Here is the query plan:
Hash Join  (cost=0.65..47555.36 rows=2428 width=4) (actual time=0.062..405.515 rows=10 loops=1)
  Hash Cond: (foo.tag = n.n)
  ->  GroupAggregate  (cost=0.42..46863.22 rows=48555 width=8) (actual time=0.045..402.654 rows=50001 loops=1)
        Group Key: foo.tag
        ->  Index Scan using foo_tag on foo  (cost=0.42..41377.67 rows=1000000 width=8) (actual time=0.012..319.113 rows=1000000 loops=1)
  ->  Hash  (cost=0.10..0.10 rows=10 width=4) (actual time=0.009..0.010 rows=10 loops=1)
        Buckets: 1024  Batches: 1  Memory Usage: 9kB
        ->  Function Scan on generate_series n  (cost=0.00..0.10 rows=10 width=4) (actual time=0.005..0.006 rows=10 loops=1)
Planning Time: 0.075 ms
Execution Time: 405.533 ms

This query plan is terrible. The planner correctly estimates that the number of rows returned in the joined query is very small (exactly 10 in this example), but it still chooses to perform a hash join on a full index scan of tag_min instead of performing a partial index scan.
Perhaps this is not wildly surprising. After all, the first query used IN, but this query uses JOIN. However, rewriting my query to use IN does not actually change the query plan—the following query is executed essentially identically:
SELECT val FROM tag_min WHERE tag IN (SELECT n FROM generate_series(1, 10) n);

Other types of joins do not help, either. Even performing a correlated LATERAL subquery does not work! This query is executed in exactly the same way as the first one:
SELECT val FROM generate_series(1, 10) n, LATERAL
  (SELECT val FROM tag_min WHERE tag = n) tag_min;

An unsatisfying solution
The only way I have managed to force Postgres to use the better query plan is to perform a correlated subquery in result position, like this:
SELECT (SELECT val FROM tag_min WHERE tag = n) FROM generate_series(1, 10) n

This finally produces the query plan I want:
Function Scan on generate_series n  (cost=0.00..854.59 rows=10 width=4) (actual time=0.040..0.176 rows=10 loops=1)
  SubPlan 1
    ->  Subquery Scan on tag_min  (cost=4.59..85.45 rows=21 width=4) (actual time=0.017..0.017 rows=1 loops=10)
          ->  GroupAggregate  (cost=4.59..85.24 rows=21 width=8) (actual time=0.016..0.017 rows=1 loops=10)
                Group Key: foo.tag
                ->  Bitmap Heap Scan on foo  (cost=4.59..84.92 rows=21 width=8) (actual time=0.005..0.014 rows=20 loops=10)
                      Recheck Cond: (tag = n.n)
                      Heap Blocks: exact=203
                      ->  Bitmap Index Scan on foo_tag  (cost=0.00..4.58 rows=21 width=0) (actual time=0.003..0.003 rows=20 loops=10)
                            Index Cond: (tag = n.n)
Planning Time: 0.071 ms
Execution Time: 0.194 ms

However, I am somewhat wary of actually using this approach, for a few reasons:

It seems like a fairly heavy hammer, and I worry that it may deprive the query planner of making better choices if they are available in the future.

It is difficult to understand compared to the query using a JOIN.

It is very awkward to use this approach if I want to obtain multiple columns from the subquery. (Technically it is possible to do using composite types, but consuming the resulting values becomes annoying.)

Is there a better way to get Postgres to execute this query efficiently?
Comment: It seems that's a problem with the predicate pushdown on the view. When querying the table directly the plan looks good to me: https://explain.depesz.com/s/QJgt
Answer: You can rewrite your query to:
  SELECT tag, MIN(val)
  FROM foo, generate_series(1, 10) n
  where tag = n
  GROUP BY tag;

and you probably want to add an index on foo(tag, val), then you and avoid sorting and only fetch one index page for each tag value.
Comment: The query in my question is simplified. My real query is more complicated, and it joins with some other tables, so I cannot easily make it an aggregate query. But also, more broadly, my view is more complicated as well, and I would like to be able to query it so that I don't have to duplicate its logic elsewhere.
Comment: You need to post your real query and view definition if your question is about a specific problem. If you just need some general advice about how to materialize view result, you can achieve it by materializing view(you can do it by yourself using trigger if your database doesn't support materialized view).


RSA and ECDSA Certificate Sizes

Question: Is there a table (or a whitepaper from official sources) that compares the size of X509 certificates generated with RSA (starting from 1024 bits) and ECDSA (starting from 160 bits) ? Thanks for the support.
Comment: Ohhh. I totally misunderstood your question. I'm sorry. I think there have been one or two certificate size-related questions here or Crypto, but I don't have any information off the top of my head. I suppose you could create some certs and find out. It can be pretty variable depending on the meta data in the cert, no? (e.g. the length of your domain, of the CA's name...).
Comment: I do think that they should have mentioned that you would need point compression to reach those kind of differences. But personally I think that they just equated key strength with key size. I mean, I don't see any numbers for the domain parameters or public exponent either. Please take with a grain of salt. Note also that it makes quite a lot of difference if *named curves* are used or if the domain parameters are all present in the certificate; this makes comparison rather tricky.
Comment: @MattNordhoff I have found on IETF, this slide [Datagram Transport Layer Security
in Constrained Environments](http://www.ietf.org/proceedings/83/slides/slides-83-lwig-2.pdf). There are these certificate's sizes:
ECDSA P-256: 91 bytes
ECDSA P-384: 120 bytes
ECDSA P-521: 156 bytes
There aren't certificate's sizes of RSA 1024 (and lower and upper) and ECDSA P-160. How can i find these certificate sizes ?
Comment: @MattNordhoff Maybe i have found what i wanted: [An Introduction to the Uses of ECC-based Certificates](https://www.certicom.com/images/pdfs/cc_vol2_iss2.pdf) on the Table 2 at page 5. What do you think ? Thanks for your answers.
Comment: Why not try and create two otherwise identical certificates using OpenSSL command line? You can try yourself!
Answer: Building such a table would be very difficult, because certificate-sizes depend on a lot of (variable-sized) things, including but not limited to:

usage constraints
signatures
public keys
URLs to CRLs and OCSP-servers
Name, location and other identifiers of the key-holder
Name, location and other identifiers of the issuing CA

However, you can estimate the difference between a pure ECC certificate and a pure RSA certificate yourself using simple math.
The relevant properties here are the public keys, the signatures and the signature algorithms. Let's assume that the signature algorithm identifiers are equally large in both cases (e.g. it's a simple OID or an integer).
Now we need to figure out the public key sizes. But this is easy as a public RSA key usually consists of the pair $(n,e)$ of which the lengths are known. Usually $e$ is 2-3 bytes long and $n$ is roughly 2048/8=256 bytes long. Now add these sizes together and ignore the structural ASN.1 encoding overhead and we get roughly 260 bytes of public key of the key-holder for RSA. RSA signatures are as long as the modulus so that's another 256 bytes coming from the CA. So in sum we're at about 520 bytes for RSA.
For ECC, the public key consists of one point, of which we only need the x-coordinate and an additional byte and an identifier identifying the used (standardized) curve. The curve point usually is as large as the curve modulus, e.g. 256/8=32 byte with one extra byte to encode the compression type. The OID is about 9 bytes long. An ECDSA signature by itself consists of two points, so that's another 66 bytes. Summing up you end up at about 110 bytes with ECDSA.
Similar calculations can be done for the security parameters of your choice.
Comment: Nitpick: ECDSA signature is two integers up to the order of G (and sometimes small enough to encode shorter), which is either equal to or only a small factor smaller than the order of the curve. More significantly, the CA key may be requred to be stronger than the entity key, and then the CA signature is bigger than an entity signature would be.
Comment: Yup, the key size *and even type of the key* of the CA doesn't have to correspond at all to the one of the certificate of the end-entity. Usually the key of the CA is stronger than the end-entity of course, but even that may not be the case if the CA uses RSA and the end-entity is using ECC.
Comment: The larger the size of the components, the higher the overhead of the DER (length) encoding. May not matter much, but it does make a difference.

RSA and ECDSA Certificate Sizes


How to solve a factorial using the Stirling Approximation?

Question: I'm working on a problem where I need to solve for b in terms of a and z, given $z = (a + b)!$. An approximate solution using the Stirling Approximation: $z = \sqrt {2\pi (a + b)}\left(\frac {(a + b)}{e}\right)^{(a + b)}$would suffice but I'm having trouble with the algebra and Wolfram seems to run out of compute time before generating a solution for me.
Answer: A solution is $b=\Gamma^{-1}(z)-a-1$ with the (functional) inverse of the Gamma function. If this looks like cheating or you have no access to the $\Gamma^{-1},$ you have to solve it numerically, e.g. with Newton's method. The (incomplete) inverse Gamma function is used e.g. in statistics.
For a numerical approximation see Is there an Inverse Gamma $\Gamma^{-1} (z) $ function? ,
for an approximation of $\Gamma^{-1}$ in terms of LambertW see
https://mathoverflow.net/a/28977


Condensation of water

Question: So I was wondering why does condensation occur at the molecular level. I can understand evaporation as the external atmospheric pressure being less than the vapor pressure ( energy of the water molecules). This would help the the molecules to escape the hydrogen bonding holding them. But I can't understand why would molecules want to attach nearby a cold surface as in condensation.
Comment: Actually, condensation occurs due to change in state of the water.  Perhaps I have read your query wrongly?
Comment: @QuIcKmAtHs well look, in the monsoon season when I keep something cold out in the open, after sometime I would find water droplets on the outside of the glass. This happens because of condensation. In evaporation due to higher energy state of the molecules they escape the liquid and 'evaporate'. Evaporation can also occur due to low atmospheric pressure. What actually causes the deposition of water molecules on a cold surface In condensation. I know it has something to do with the concentration of water molecules in the air(you wouldn't see this in summer because the air is very dry).
Comment: Condensation happens when water moves from gaseous to liquid state.   It is merely a state change.
Comment: @QuIcKmAtHs exactly, condensation is a state change but in the larger sense. I want to know what happens on the atomic scale.
Comment: @physics2000, note that the vapor pressure of water is less than atmospheric pressure until you reach or exceed the boiling point of water.
Answer: When water molecules in water vapour come in contact with cold surface, they transfer a part of their kinetic energy to the cold surface, which causes them to condense as water droplets.
When humidity is high, the air is saturated with water vapour, so condensation occurs pretty easily. When the vapour concentration in air is low, there are less chances of transfer of kinetic energy to take place, thus condensation is difficult.

Condensation of water


Native Magento search vs. SOLR vs. something else?

Question: At what point do I want to "upgrade" from the native Magento search engine to something like Apache SOLR, or a commercial product? Are there specific features I'd be looking for, or is it simply a function of traffic, SKU count, or something else?
Comment: Any movement on this? Anything I can do to help clarify an answer for you? Please update your question if you have more information that can help us close this out.
Answer: The distinguishing features of using Solr over the default Magento MySQL Fulltext engine are:

Weighted attributes (e.g. name is higher priority than description)
Fuzzy search capability (e.g "Did you mean?" functionality)
Spelling suggestion/correction
Indexing time
Speed, speed, speed (esp if you're using the ajax/lookahead search dropdown)
Category/layered navigation offloading

The community seems to lean toward Solr in general, though other search connectors have been made available.
3rd party search:
3rd party search products work in one of two ways: they replace your search and category pages with their own versions and typically host them under a subdomain on your site so as not to interfere with SEO (e.g. SLI), or, they iFrame search into your site (Picosearch). In my opinion I don't want my stores at the mercy of a 3rd party hosting on AWS; or worse yet on their own in-house datacenter.
I recently met a vendor wearing a funny hat who purportedly had a custom search tool who plugs into the Magento Solr connector but it runs as a SaaS cloud service with a control panel. This is not normally how the 3rd party search integrations work - I'm curious what the performance is like.
Timing/Deployment
There is no formula as to determine when to make the switch - when you should migrate is entirely up to you. Keep in mind it isn't a two-second implementation - your theme/plugins (especially any navigation plugins) may require tweaking or upgrading.
It's not going to give you miracle results overnight - like everything else in running your business it'll only be as good as the amount of time you invest into it.  You will still likely have to have indexed fields with keywords you want to optimize for. You'll have to play with the weighting settings heavily, too. It's not an overnight fix.
A note about performance
The distinguishing feature of the Solr integration over fulltext really is that Magento can utilize Solr to offload the layered navigation and category page results rendering to it. Because Solr is so highly optimized it incurs very little overhead to do so. This is handy to mitigate traffic spikes and to spread your load across more than just your Apache servers.
Comment: I think I know two 3rd party search providers, which are quite popular in Germany and offer a Magento module which forwards the query to a SaaS and gets back an list of product ids to be displayed in Magento.
Comment: Thank you very much for the thoughtful and detailed answer. I only have 30 products, and don't expect many more. I'm not sure if the benefit is there for me yet. Do I need a dedicated host to run SOLR, or can it coexist on the web server? (I suppose this is a different question)
Comment: I tried running Solr using Tomcat6 on a really dinky VPS, we have ~50,000 products in our catalog and we'd usually hit a deadlock at around 18,000 solr documents. Really, it's best to run it on its own server but for 30 products it's a little overkill to justify the $500 dollars for the only decent Solr extension available and the resources to host Solr on an LAMP. I had really good luck with the extension recommended by Alex http://magento.stackexchange.com/a/24699/26736
Comment: I should also add the Sphinx search can use MySQL without having to install Sphinx on a servlet which doesn't play well when the server is chrooting. That extension gives you the option to use an external server, internal, or even a Javascript. The only trade off is speed when indexing which is really poor when using MySQL.
Answer: SOLR is used by all the top stores and platforms including Magento EE and Hybris, it has Levenshtein Distance which provides up to 98% accurancy compare to Sphinx which gets in to the 60-80% accuracy range.
We use a SOLR install which costs $450 + $250 for the hosting per year, so if yo amortise it over three years ($450 + $250*3), at $400/yr and search is 5% of IT Spend and IT Spend is 5% of revenue, then you have $160,000 revenue per year where it makes sense to start using SOLR.
Comment: Cite a source for your statistics, because otherwise its clear you've just made up your answer. SOLR is no better than Sphinx (and vice versa), they are two totally different technologies and each have their own benefits. There is absolutely no way to compare search engines that are so radically different in functionality.


Partion Samsung T5 on MAc

Question: I have a 1G Samsung T5 that I would like to partition into 2 partitions so I can use one of them for Time Machine backup. However the Partition button in Disk Utilities is always grayed out for the T5 disk. It is not grayed out if I select the Machintosh HD. What do I need to do to partition the T5? (I am running newest MacOS).
Answer: You cannot partition a volume. You must partition a drive (device). To do so, click on the drive itself, located just above the partition you selected on the sidebar ("Samsung Portable...").
Then, you can partition the disk.
Edit: Back all data you want to keep up and Erase the disk as GPT (GUID Partition Table). Newer versions of DU for some reason don't want to work with MBR partition tables. Choose ExFAT as file system to be able to read and write to the disk from both Windows and macOS, or APFS if you only use Macs.
Comment: @JørgenRasmussen Back all data you want to keep up and Erase the disk as GPT (GUID Partition Table). DU for some reason doesn't want to work with MBR partition tables.
Comment: Unfortunately that does not help, partition button is still grayed out (see my updated question)
Comment: Yes this worked, but took forever because copying PhotoLibrary for some reason took 10+ hours to copy. Except I needed to use Journaled as file system as Time Machine does not accept APFS formatted disks.
Comment: @JørgenRasmussen Yes. Use HFS+ (macOS Extended Journaled for Time Machine AND for Apple Photos library folders, though the latter also work with APFS). If you're satisfied with the answer, please accept it by clicking on the checkmark :)

Partion Samsung T5 on MAc


Why are tall block stacks so hard to make?

Question: Consider a stack of wood chips: each  0.5cm thick and 2x2 cm in length and width. There are 200 of them all stacked on each other.  For some reason they all instantly fall. Evwn though their centre of gravity is at the centre of the stack and they have the extra added help of friction the further down the chips you go (because the second to bottom chip is squashed against the first because of the heavy load). So why does it fall?
Comment: It wouldn't if the blocks were perfectly shaped. But they aren't.
Comment: ... And if the floor was perfectly level
Comment: So what makes the building more delicate the taller it gets
Answer: First, let's assume the tower is a single solid rod. The tower will fall over when the center of mass extends past the base. For a longer tower, a smaller angular displacement is needed for this. This is because we want the horizontal displacement of the center of mass to be
$$x=\frac 12 H\sin\theta<\frac 12 w$$
where $H$ is the length of the tower, $w$ is the width of a block, and $\theta$ is the angle the tower makes with the vertical.
Therefore:
$$\sin\theta<\frac HL$$
The larger $H$ is, the smaller $\theta$ needs to be. This means that for a taller tower, smaller disturbances can cause it to fall.

Now our actual tower is not a single solid rod, but the same idea applies. Additionally, if the tower fails this at any section it will fall over, with taller portions falling onto ones below. This is why it seems like everything falls at once, as you have said. I'm not sure the friction between the blocks really matters, since there probably isn't a lot of shearing going on here.
Comment: Could you explain why those formulae are the way they are.
Comment: @yolo The $\frac 12 H\sin\theta$ is just from the triangle formed by the COM, the point directly below the COM on the ground, and the point where the center of the vertical tower would touch the ground. The $\frac 12 w$ is just the distance from the center of the tower to its edge.
Answer: An additional factor that I haven't seen mentioned yet is the fact that the environment acts upon a structure such as that. Errant air currents would have a deleterious effect on such a stack the higher it went. Even a tiny breeze would topple a perfect stack if it was beyond a certain height.
Comment: This is mentioned generally in my answer "This means that for a taller tower, smaller disturbances can cause it to fall."
Comment: Ahhh... I didn't see that. However, I did cover the topic in tiny bit more detail, in case other people don't see your full comment, or ruminate on the specifics of it, such as I did. Thanks though.


Yellow tomato leaves

Question: I planted tomato plants about three weeks ago - most of them have been doing really well, but this one is having some problems (pics attached). The watering system waters daily. I weeded the area + applied fertilizer- is it a nutrient deficiency or disease?
Answer: Unfortunately, you're not going to get a straight answer on this question but I'll try to help you. Yellowing leaves are typically caused by a nutrient deficiency.... However, yellowing leaves can be caused by under watering or over watering, under fertilizing or over fertilizing. It can be a fungus issue like blight or a virus caused by white flies etc. To make matters worst, when a gardener has an issue they tend to over correct and end up exaggerating the problem. Unfortunately without knowing exactly how much and what fertilizer you used along with other conditions with your soil it's tough to say with 100% certainty what your issue is.
What I can say to help is: try to grow varieties that are disease resistant or that are better adapted to your climate and area. For example, in my area (zone 7a NYC) cherry tomatoes varieties grow amazingly. When I try to grow other varieties I get mixed results.
The other thing you can focus on is to work on your soil health (add as much rich compost as you can afford to your soil). When I started making my own compost + vermicompost and adding that to my soil it was a game changer for my garden.
Hopefully this help. But I don't think anyone can answer this question by hitting the nail on the head.
Answer: Your tomato plant is likely suffering from more than one problem. Over fertilizing and over watering.
Unfortunately, fertilizer will NOT cure a unhealthy plant. It just causes more harm. Fertilizer should only be used on healthy plants that are growing vigorously. Even then, I always recommend that you use only 1/3 of the strength in the directions on the label. I prefer liquid fertilizers that I dilute with distilled water. It is 1 part liquid fertilizer to 2 parts distilled water. If using a granulated fertilizer, make the fertilizer according to the directions on the package and then dilute it just like a liquid fertilizer (1 part fertilizer/ 2 parts water). Using a diluted fertilizer can mean that you will have to fertilize more often but it is better to under fertilize a plant than over fertilize.
Unless the soil is getting dry everyday, you should not be watering it everyday. You should allow the top inch of the soil to feel dry to the touch and then water the plant thoroughly.
Prune back the yellow leaves and stems. Also check carefully to see if there is any sign of insects on the plant. An unhealthy plant is much more susceptible to insects than a healthy plant is. A population of insects, like aphids, can get really big, really fast and cause enough damage that the plant can't recover from. If you see any signs that uninvited guests are eating your plants, a safe way to keep the population of insects to a minimum is to spray the plants with soapy water. Mix a few drops of dish washing liquid (I prefer Dawn) with distilled water in a spray bottle. Spray the plant thoroughly. I usually spray my outdoor plants at least once a week
Answer: There are more than one cause for this symptom, but from your description, it seems you may be water >>too<< frequently.  For almost all plants, grass, etc. best watering approach is to soak them well >>infrequently<< and thereby help encourage root growth/expansion, increasing overall hardiness of the plant.  Repeat thoutrough soaking when top inch or so (not just the top) of dirt is dry to the touch.
Read this: https://www.gardeningknowhow.com/edible/vegetables/tomato/yellow-tomato-leaves.htm

Yellow tomato leaves


Runtime of algorithm to transpose a graph

Question: I am working with an algorithm to compute the transpose of a directed graph. Here is a rough overview of the algorithm: For each vertex in the graph, traverse each edge and add an edge from the neighbor to the parent node. The adding of an edge takes constant time, $O(1)$. And I figured, if I am traversing each edge, then the asymptotic run time should be $O(|E|)$. However, the run time of this algorithm is $O(|V| + |E|)$. The only way I can make sense of this is: once it reaches the final level of the tree (the roots), even though the nodes don't have any edges, the for loop will still iterate through those nodes. However, if I am taking this into account, then shouldn't it be $O(|V|)$. Why are we taking both $|V|$ and $|E|$ into account? Can someone can offer some insight to this?
Comment: Do you even need an algorithm to do this? In many contexts, you can just have a Boolean field for "The edges go the other way, now." Now, transposing the graph is $O(1)$ (flip the Boolean), and any algorithms that use your graph data structure just need to check the Boolean and behave appropriately.
Answer: It all depends on how exactly you store the graph. For example:

If you store the graph as an adjacency matrix, the complexity is $\Theta(|V|^2)$.
If you store the graph as a linked list of edges per vertex (i.e., adjacency lists), then the complexity is $\Theta(|V|+|E|)$.
If you store the graph as a linked list of all edges (and don't store the vertices explicitly), then the complexity is $\Theta(|E|)$.

The representations usually used are the first two. I have never heard of the third being used. In most cases, the number of edges exceeds the number of vertices, and so there would be the third method would have no advantage over the second one, but it would have many disadvantages.
Comment: I encountered the problem of finding transpose of graph G in CLRS book. There graph is represented by adjacency list.They say that time complexity is $O(V+E)$. I know that $Θ(V+E)->O(V+E)$.But why are they specifically using $O$ while they have used $Θ$ while dealing with DFS which actually is so.While analyzing algo of transpose I found it as $Θ$. for each vertex u in G we scan the adjacency list of it and for each of the adjacent vertex v of u, u is added to the front of adjacency list of v in transpose(G).By aggregate analysis i find that it $Θ$ as each and every edge in G is explored


How to install Thrift to work with Qt-Windows

Question: I'm working on the Windows build of a Qt-Widget application. I need to extend my app to interact with a 3rd-party web service that's built on Thrift. I'm not talking about hosting a web service (ie a Thrift-based server); just writing the client to connect to someone else's existing, live Thrift server.
Can anyone provide a checklist of things to integrate Thrift into Qt?
I'm looking for the bits and pieces that need to be installed, and where to get them. I've started the process of trying to get the two to work together, but it seems to be a non-trivial process since Thrift is a *nix-centric library. I was really hoping that there was a static library and some headers for Thrift, like with many other libraries, but this doesn't appear to be the case.
Answer: I have only found this: https://issues.apache.org/jira/browse/THRIFT-1348
Didn't look at it myself though yet.


How does Google detect nationality/language while I am in another country and in incognito?

Question: I am Danish, but currently located in Turkey.
I opened an Incognito window to test a project, and Google shows up in Danish. My user agent does not contain a language - as far as I am aware - and Geolocation puts me in Turkey. How does Google know that I speak Danish? Does Chrome send some sort of information about the language that I speak, even though I am in another country and in Incognito?
Comment: Perhaps being signed in makes chrome send accept-language header.. press F12 to get into developer tools, make a request and look at the network table.. it allows to inspect the headers of the request
Comment: @CaiusJard yup! My browser is sending a `ACCEPT_LANGUAGE` header with the value `da-DK,da;q=0.8,en-US;q=0.6,en;q=0.4`. That would be the solution.
Comment: Are you signed into chrome? If you inspect the http request, does it have an Accept-Language header that cites danish?
Comment: Signed into Chrome, yes. It does not show up whilst Incognito, however.
Comment: https://i.imgur.com/Xwouf3C.png [edit: oops, you already found it]
Comment: Thank you anyways, @Ryan
Answer: My guess is that Google remembers your IP address and most frequently submitted requests from it. This is what is happening to me, since I'm always going through the same VPN, either in incognito mode or not.
Answer: There is a way to check the browser language:
navigator.browserLanguage: browser language

Internet Explorer supports the following:
navigator.browserLanguage: browser language
navigator.systemLanguage: Windows system language
navigator.userLanguage: Windows user-specific language

Maybe the settings of your browser are on your native language.
Comment: This is what I get on mybrowserinfo.com:
    `Language:English`
    `System Language:Not detectable with this browser`
    `User Language:en-us`
Answer: Google Chrome sends a ACCEPT_LANGUAGE-header with the value da-DK,da;q=0.8,en-US;q=0.6,en;q=0.4. This would allow pretty much any site that inspects headers to detect language used.
It prioritises da-DK (Danish), then en-US (American English), and lastly en (I would assume Standard English or British English).
Thanks to Caius Jard for the suggestion.
Answer: This worked for me: https://productforums.google.com/forum/#!topic/chrome/3MdsRLXtGi0
In short, update the order of the list of the language that you've denoted as spoken.
PS I've nearly gone mad looking for a solution for this issue. A lot of tips are out there, all were misleading. I have even deleted completely my Chrome history. Finally got rid of Finnish though it's an amazing language :)


pass input text from view to controller

Question: i know there are a lot questions like this but i really cant get the explanations on the answers... here is my view...

@model IEnumerable<CormanReservation.Models.Reservation>
@{
ViewBag.Title = "Index";
}

    Select a date and see reservations...

     <input name="dateInput" type="text" class="alternate" />

i want to get the value of the input text... there's already a value in my input text because the datepicker passes its value on it... what i cant do is to pass it to my controller... here is my controller:
  private CormantReservationEntities db = new CormantReservationEntities();
    public ActionResult Index(string dateInput )
    {
        DateTime date = Convert.ToDateTime(dateInput);
        var reservations = db.Reservations.Where(r=>r.Date==date).Include(r => r.Employee).Include(r => r.Room).OrderByDescending(r => r.Date);
        return View(reservations.ToList());
    }

i am trying to list in my home page the reservations made during the date the user selected in my calender in my home page....
Answer: I don't see a Form tag in your View...or are you not showing the whole view? hard to tell.. but to post to your controller you should either send the value to the controller via an ajax call or post a model. In your case, your model is an IEnumerable<CormanReservation.Models.Reservation> and your input is a date selector and doesn't look like it is bound to your ViewModel. At what point are you posting the date back to the server? Do you have a form with submit button or do you have an ajax call that you aren't showing?
Here is an example of an Ajax request that could be called to pass in your date
$(function () {
    $(".datepicker").onselect(function{
          searchByDate();
        })
    });

});

function searchbyDate() {
   var myDate = document.getElementById("myDatePicker");

    $.ajax({
        url: "/Home/Search/",
        dataType: "json",
        cache: false,
        type: 'POST',
        data: { dateInput: myDate.value },
        success: function (result) {
            if(result.Success) {
               // do something with result.Data which is your list of returned records
            }
        }
    });
}

Your datepicker control needs something to reference it by
<input id="myDatePicker" name="dateInput" type="text" class="alternate" />

Your action could then look something like this
private CormantReservationEntities db = new CormantReservationEntities();

public JsonResult Search(string dateInput) {
    DateTime date = Convert.ToDateTime(dateInput);
    var reservations = db.Reservations.Where(r=>r.Date==date).Include(r => r.Employee).Include(r => r.Room).OrderByDescending(r => r.Date);
    return View(reservations.ToList());
    return Json(new {Success = true, Data = reservations.ToList()}, JsonRequestBehaviour.AllowGet());
}

Update
If you want to make this a standard post where you post data and return a view then you need to make changes similar to this.
Create a ViewModel
public class ReservationSearchViewModel {
    public List<Reservation> Reservations { get; set; }
    public DateTime SelectedDate { get; set; }
}

Modify your controller actions to initially load the page and then be able to post data return the View back with data
public ActionResult Index() {
    var model = new ReservationSearchViewModel();
    model.reservations = new List<Reservation>();
    return View(model);
}

[HttpPost]
public ActionResult Index(ReservationSearchViewModel model) {
    if(ModelState.IsValid)
    var reservations = db.Reservations.Where(r => r.Date = model.SelectedDate).Include(r => r.Employee).Include(r => r.Room).OrderByDescending(r => r.Date);
    }
    return View(model)
}

Modify your view so that you have a form to post to the Index HttpPost action
@model CormanReservation.Models.ReservationSearchViewModel

Select a date and see reservations...

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)
    @Html.EditorFor(model => model.SelectedDate)
    @Html.EditorFor(model => model.Reservations) // this may need to change to a table or grid to accomodate your data
    <input type="submit" value="Search" />
}

Comment: i dont have both... i thought i could simply pass the value of input text to the controller without the use of form, only by using scripts...
Comment: You can use a script but the script needs to call the action. This is what an Ajax request does, you tell it which action to call, which data to send and what to do on success or error. The script you have does nothing more than try to call a function that doesn't exist. Otherwise you need a form to hold your datepicker control and a submit button to post to a specific action. In your case your action is Index.. it's not even a method you can post to as it lacks the [HttpPost] attributes. You need to have a look at asp.net/mvc look at the pluralsight vids for learning MVC
Comment: should the return type of Search be JsonResult? you are also returning View, i think it would cause errors...
Comment: No you're not returning a view, you're returning data to your view, it's an Ajax call which means it's an asynchronous request. Have a look at the pluralsight vids. I'm guessing you haven't worked with MVC very much, correct?
Comment: See my update in the answer to accommodate being able open view, post data in a ViewModel to controller HttpPost action and return data to view

pass input text from view to controller


Merging tenancies in web & teams app

Question: I'm working on a Microsoft Teams version of our web app and looking for some guidance on the situation below.  The app is used by larger companies (250+ employees) to do work in virtual teams within the app, and share information across teams within the same company.
When a company registers on our WEB version, we create a Company ID so that all of their employees can be linked together and use paid features where users share the same Company ID.
Microsoft Teams provides a Tenancy ID which is effectively the same concept as our Company ID. To make the process more streamlined for users, when a user signs in from MS Teams the Tenancy ID replaces our Company ID and we can group users together by their shared tenancy, and that saves their IT team from manually managing their users in our app.
The problem is in larger companies there can be multiple departments that found the app on the web and started using it without any knowledge of each other.  Each department is assigned a Company ID and has a custom configuration.  They will get merged together if they all start using the Microsoft Teams app because they'll have a common Tenancy ID.  Ultimately this means we only keep the configuration settings for one of the Company IDs, leading to confusion, support calls etc.
This is an edge case, we haven't encountered it in the wild and doubt we ever will...but it is a scenario that came up in Microsoft Testing because they use multiple tenancies and shared accounts for their testing.
Is there any elegant way to handle this?  Is there a better way to group employees on the web (email domain for example) so we can identify if a company is already using our product when someone registers?
Answer: Regardless of what we suggest here, it is up to Microsoft to implement it. I don't know how customizable the Microsoft Teams platform is but the most straight-forward solution here would be to have a Company ID with multiple Department IDs, perhaps like an extension of it where there are some configurations set by the Company ID that cannot be overwritten by Department IDs.

Merging tenancies in web & teams app


Unity what are the rules for determining sizes of gameobjects

Question: I am making a game for windows phone. I am a newbie so currently I am unable to understand if I have to make a simple menu for a game targeting portrait mode always, what should I give the background size ,camera size ,button size , position? For example I have to set a background on renderer  full screen size in portrait mode and fis a gui test between it.. I am using 2d orthographic camera
Comment: Scroll down to the point where it talks about sizing the background sprite to fit into your viewport http://www.raywenderlich.com/61532/unity-2d-tutorial-getting-started
Answer: I would suggest that you design a UI according to a fixed screen size like (480X800 WP) then use GUI.matrix (see the script reference) to scale it to different resolutions.
GUI.matrix is really useful but a very heavy function. so make sure you use less OnGUI objects like buttons, boxes, and textures.
A better way to implement textures is using Quads. Quads are rendered by the camera and the Camera Scale is taken care by unity.


Silverlight ScrollViewer Not Scrolling

Question: enter code hereI have a ScrollViewer in Silverlight that is not scrolling vertically whenever I call the ScrollToVerticalOffset method from the code behind.
Basically, I have my View (UserControl) that contains the ScrollViewer.  I invoke an action from my ViewModel that triggers an event in the View's code-behind that sets the VerticalOffset to a specific value.
First of all, I know this is very ugly.  Ideally I wish that I could have an attachable property that I could bind to a property in my ViewModel, that, when set, would cause the VerticalOffset property (which I know is read-only) to be updated, and the ScrollViewer to scroll.
The ScrollViewer contains dynamic content.  So, if the user is viewing content in the ScrollViewer, and scrolls half-way down, and then clicks on a button, new content is loaded into the ScrollViewer.  The problem is that the ScrollViewer's vertical offset doesn't get reset, so the user has to scroll up to read the content.  So, my solution was to be able to control the vertical offset from the ViewModel, and I have racked my brain and can't come up with a viable solution, so I am looking for someone to help, please.
By the way - I have included code from a class I put together for an attachable property.  This property binds to a property in my ViewModel.  When I set the property in the ViewModel, it correctly triggers the PropertyChanged callback method in this class, which then calls the ScrollToVerticalOffset method for the ScrollViewer, but the ScrollViewer still doesn't scroll.
public class ScrollViewerHelper
{
    public static readonly DependencyProperty BindableOffsetProperty =
    DependencyProperty.RegisterAttached("BindableOffset", typeof(double), typeof(ScrollViewerHelper),
    new PropertyMetadata(OnBindableOffsetChanged));

    public static double GetBindableOffset(DependencyObject d)
    {
        return (double)d.GetValue(BindableOffsetProperty);
    }

    public static void SetBindableOffset(DependencyObject d, double value)
    {
        d.SetValue(BindableOffsetProperty, value);
    }

    private static void OnBindableOffsetChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        ScrollViewer scrollViewer = d as ScrollViewer;

        if (scrollViewer != null)
        {
            scrollViewer.ScrollToVerticalOffset((double)e.NewValue);
        }
    }
}

Comment: I don't see why this solution would not work... are you just trying to pin the viewport to the top or bottom of the panel of elements anytime something new is added? Are you sure OnBindableOffsetChanged is getting called every time you add a new element? If you are just setting the view model property to 0.0 every time (to scroll to the top) I could see why it might only get called the first time and never again.
Answer: This approach is a little bit funky in my opinion, as I think of both a ScrollViewer and a VerticalScrollOffset as "View" entities that should have very little (or nothing) to do with a ViewModel. It seems like this might be forcing MVVM a little too much, and creating a lot of extra work in creating an attached dependency property and basically trying to keep a bound Offset ViewModel property in sync with the readonly VerticalScrollOffset of the ScrollViewer.
I am not exactly sure of what you are trying to achieve, but it sounds like you are trying to scroll to a specified offset when some dynamic element is added to the underlying panel of your ScrollViewer. Personally, I would just want to handle this behavior with a little bit of code in my View and forget about tying it to the ViewModel.
One really nice way to do this type of thing in Silverlight 3 is with Blend behaviors. You write a little bit of behavior code in C# and then can attach it declaratively to an element in XAML. This keeps it reusable and out of your code-behind. Your project will have to reference the System.Windows.Interactivity DLL which is part of the Blend SKD.
Here's a simple example of a simple Blend behavior you could add to a ScrollViewer which scrolls to a specified offset whenever the size of the underlying content of the ScrollViewer changes:
public class ScrollToOffsetBehavior : Behavior<ScrollViewer>
{
    private FrameworkElement contentElement = null;

    public static readonly DependencyProperty OffsetProperty = DependencyProperty.Register(
        "Offset",
        typeof(double),
        typeof(ScrollToOffsetBehavior),
        new PropertyMetadata(0.0));

    public double Offset
    {
        get { return (double)GetValue(OffsetProperty); }
        set { SetValue(OffsetProperty, value); }
    }

    protected override void OnAttached()
    {
        base.OnAttached();

        if (this.AssociatedObject != null)
        {
            this.AssociatedObject.Loaded += new RoutedEventHandler(AssociatedObject_Loaded);
        }
    }

    protected override void OnDetaching()
    {
        base.OnDetaching();

        if (this.contentElement != null)
        {
            this.contentElement.SizeChanged -= contentElement_SizeChanged;
        }

        if (this.AssociatedObject != null)
        {
            this.AssociatedObject.Loaded -= AssociatedObject_Loaded;
        }
    }

    void AssociatedObject_Loaded(object sender, RoutedEventArgs e)
    {
        this.contentElement = this.AssociatedObject.Content as FrameworkElement;

        if (this.contentElement != null)
        {
            this.contentElement.SizeChanged += new SizeChangedEventHandler(contentElement_SizeChanged);
        }
    }

    void contentElement_SizeChanged(object sender, SizeChangedEventArgs e)
    {
        this.AssociatedObject.ScrollToVerticalOffset(this.Offset);
    }
}

You could then apply this behavior to the ScrollViewer in XAML (and specify an offset of 0 to scroll back to the top):
   <ScrollViewer>

            <local:ScrollToOffsetBehavior Offset="0"/>

        ...Scroll Viewer Content...
    </ScrollViewer>

This would be assuming that you always want to scroll to the offset whenever the content size changes. This may not be exactly what you are looking for, but it is one example of how something like this can be done in the view using a behavior.

Silverlight ScrollViewer Not Scrolling