Rails Count and Group to return count and values

Question: Using Ruby 1.9.3.
Assume this example, simple table "cars" in MySQL
id | Model
1  |  Ford
2  |  Ford
3  |  Mini

If I ran this query:
select count(*),model from cars group by model;

I would get
count(*) | model
2        |  Ford
1        |  Mini

Showing me that two entries in the database have the model of "Ford", and one entry has a model of "Mini".
I can't figure out how to get the results of that query in rails (other then using direct SQL to load up an array, etc).  Assuming a model called "Car" for table "cars", I've tried things like
Car.find(:all, :select => 'count(*),model', :group => 'model')"

but that just returns the models, not the matching count.
I am looking for a clean method to collect all of the count & model information from the "cars" table that does not require the full direct SQL being used, and then flattening the resulting array to make sense of it.  Something elegant. :)
(and if there IS an answer out there already for this question, please just show me where it is.  I've searched for a while and all of the questions asked don't seem to fit my bill)
Comment: Hilarious.  After finally posting the question, the "related" links showed me the exact answer:  Car.count(:group => :model).   Mods -- this is obviously a duplicate question now.  I leave it to you to decide to keep it or not.
Comment: I am getting the count by Car.count(:group => :model).How can I get the records other than count? I tried Car.all(group: :model)
Answer: Perhaps this can help you:
Car.all.group(:model).count

And here has other answer that can be useful:
rails 3 group by and sum


How do I get out of a Blender 2.77a Windows 10 infinite loop after setting a .jar default app setting by mistake?

Question: After some trubosquid downloads, I kept getting a "make default app" for .jar files notice. I clicked okay just to get it to go away. Now when I open Blender 2.77 on my Windows 10 machine the command prompt goes into an "invalid syntax" loop and opens blender window after blender window. It does not do that when I use 2.69 or older versions, but I tried uninstalling and reinstalling 2.77a and the problem persisted. Will changing the default app for .jar files work and how do I do that? What alternative solutions are there?
Comment: UPDATE: I tried the default program thing and I found it didn't work. It is an Import multiray thing and a numpy plugin thing. I deleted them and fount that it didn't work. So I installed 2.76 and installed the plugins I have and found the problem is with a plugin. How do I get to appdata to remove plugins in Windows 10? I can't seem to reach it.
Answer: I just found a tutorial on getting into hidden files on Windows 10, like Appdata. From there I just manually deleted all the plugins and reinstalled Blender. It works now.


Cookie manager PHP

Question: I own a Joomla commerce store and although I use Google Analytics in order to track visitors, I need to install a cookie manager in order to be able to track cookies that were installed on customer when he punctuate an order.
To be more specific , I am planning to join an affiliate network and I need somehow to track no only the last visit of a customer but if he has a cookie and from which affiliate network as well.
Answer: There are many components within the Joomla extension libaary which should be able to help, here is a couple as an example:

WizAffiliates
VM Affiliate - Requires Virtuemark

For even more check out Joomla extensions library for Affiliates
If you can't find something suitable then sadly your need to make your own or have someone do it for you.
Answer: I didnt install another 3rd party component in order to avoid extra "weight" on existing site, what i did was to create a few php lines in the head of the template where i was checking if current page had a parameter in the url similar to affiliate network has when drivers visitors from their network to my site. If page was same i was created a cookie with same life-time as affiliates.
Finally on every order that is punctuated in the site, i am checking my cookie is exists on that customer, if so that user should be from affiliate.
Its not ideal but its worked for me & i avoided any 3rd party component.

Cookie manager PHP


how to display new songs along with old songs in UITableView

Question: <code>-(void) mediaPicker:(MPMediaPickerController *)mediaPicker didPickMediaItems:(MPMediaItemCollection *)mediaItemCollection {

    [self dismissViewControllerAnimated:YES completion:nil];

    NSURL* assetUrl = [mediaItemCollection.representativeItem valueForProperty:MPMediaItemPropertyAssetURL];
    AVURLAsset* asset = [AVURLAsset URLAssetWithURL:assetUrl options:nil];

    AVPlayerItem* playerItem = [AVPlayerItem playerItemWithAsset:asset];

    myPlayer = [AVPlayer playerWithPlayerItem:playerItem];

    collectionMutableCopy = [mediaItemCollection.items mutableCopy];
    [self.myPlaylistTable reloadData];

    //[self updatePlayerQueueWithMediaCollection: mediaItemCollection];
    [myPlayer play];

}
</code>
I have a Button that allows me to select select songs from Iphone Library. I have another UIButton where it shows the list of selected songs from ipod Library.
I am displaying the selected songs in UITableview which is myPlaylistTable
when i select say two songs from iPod Library those two songs get displayed myPlaylistTable but problem happens when I try to add few more songs the two songs which was displayed earlier got disappear.
For ex if i select two songs first time and If I add another two songs it should show four songs .
Answer: Please considering doing the following.... It should help and resolve your problem.

self.clearsSelectionOnViewWillAppear = NO;

That will keep the row selected, unless you manually deselect the row or the user selects another row on the table.


Use widescreen format for embedded YouTube links

Question: On sites where you convert a YouTube link to an embedded player (which apparently doesn't include MSO, so I can't put an example directly in this post), can you use 16:9 aspect ratio instead of 4:3? It's much more common these days. Here's an example

How it is today

How it could be
Comment: so... why all the downvotes?
Comment: Yeah.... not sure about the downvotes on this one? Could someone explain? (+1 so it gets back on the homepage)
Comment: Maybe they don't care for widescreen. Maybe you didn't provide a good enough reason. Maybe there's no point. Maybe widescreen isn't as common as you think for those things that are illustrated via YouTube videos.
Comment: Downvotes here usually mean disagreement, so people probably don't like your proposal.
Comment: The YouTube API will actually give the video ratio, so SE shouldn't have to decide which ratio to use: it should ask YouTube.
Answer: For anyone who would like this, I wrote a Grease Monkey script to fix it. You can find it over on StackApps.
Edit: That StackApps link is dead, unless you have enough rep to view deleted posts. I deleted it because there's no need for it anymore; as noted in accepted answer, they made this change in the StackExchange code.
For anyone interested in the code from a purely academic perspective, here it is:
<code>// ==UserScript==
// @name           StackExchange embedded YouTube in 16:9
// @namespace      stackexchange
// @description    Changes YouTube videos embedded in StackExchange pages to use widescreen format.
// @include       http://stackoverflow.com/*
// @include       http://meta.stackoverflow.com/*
// @include       http://superuser.com/*
// @include       http://meta.superuser.com/*
// @include       http://serverfault.com/*
// @include       http://meta.serverfault.com/*
// @include       http://*.stackexchange.com/*
// @author         Kip Robinson - http://stackoverflow.com/users/18511/kip
// ==/UserScript==

(function() {

  function with_jquery(f) {
    var script = document.createElement("script");
    script.type = "text/javascript";
    script.textContent = "(" + f.toString() + ")(jQuery)";
    document.body.appendChild(script);
  };

  with_jquery(function($) {
      var attrs = {width: 640, height: 360};
      if($.browser.webkit)
        attrs.height = 390; //for some reason, embedded YouTube player uses different settings in Chrome
      $('embed[src*="youtube"],embed[src*="youtu.be"]').attr(attrs).parent().css(attrs);
    }
  );
})();
</code>
Comment: Thank you for this, +1 for the script
Comment: @DenilsonSá updated with the source code. Although you don't need a browser extension anymore to do this.
Comment: That URL has been removed. The link is broken.
Answer: Starting with the next build, youtube embeds will be 640x385px (25px for the player), a 16:9 ratio.
This won't affect existing posts, since the conversion is done at the time of a save/edit.  If you want a post to switch to the new format, simply edit it.


Nikon D5100 - lost or missing images on memory card

Question: After shooting all day and viewing the images on the camera, when I put the card into my PC and tried to open it, I did not have all the images from today. I did have all the old images, from yesterday and older. Is there any where for me to look for these lost images and retrieve them??
Answer: This is likely to be more diagnosis than recovery, I'm afraid.
First, if you haven't already, make sure you have copies of everything you can already see on the card, this process is destructive.
Next, use Photorec (freeware, cross-platform) to see if your newer pictures are potentially still there - my gut feeling is that they won't be, unfortunately.
Next comes the destructive test - this is to see if the card itself is still viable.
Do this even if you got your newer photos back using Photorec.
If an SD card has an error at write, then there is often firmware protection which will trigger to prevent further damage.  The symptom is that the card becomes unwritable - sometimes it will appear to write, but the next time the card is ejected & re-inserted it seems to 'magically' go back to its previous state.
This is, to all intents & purposes, irreversible.
To test..
Try to format the card.
Try it three ways - first in the camera, then in the computer as a 'quick format' then again as a long format.
After each test format, attempt to write a file or two to it. From the camera, take a couple of quick photos; from the PC, drop a couple of small text files to it, etc.
Check each time that the new files are still visible after you eject & re-insert the card. Check the photos are also visible to the PC.
If all of these tests fail, you can be fairly certain the card is in write-protect mode & your only solution is to bin it & buy a new one.


Can static IP address be used as a component of MFA?

Question: Can I use static IP address as a component of 2 factor authentication for SFTP login?
Answer: The traditional factors used for MFA are:

Something you know.
Something you have.
Something you are.

But location ("somewhere you are") is also sometimes considered as a fourth factor - which could include a static IP address.
But your question shouldn't really be "can it be used as a component of MFA?", it should be "does it provide the security I need?". And that will depend on both the context of your application, and on exactly how trusted the IP address is.
The main problem with using an IP address is that it doesn't represent a person, it represents a network. And if that's a corporate network, it could have hundreds of people on, who all come from the same public IP address using NAT. It could also include an open guest wireless network that anyone near the building can use.
Is that acceptable for your security requirements?
Comment: There are several problems with this answer. There are 5 MFA factors. Factors do not provide security; they provide factors of trust. The IP doesn't need to represent a person but a factor of trust, which can legitimately be a network. I think what you wanted to say is that it is a question of whether the factor is refined enough in this use case and the nature of the IP is sufficiently understood to function as an acceptable trust factor.


UIViews display at wrong location in landscape mode

Question: I am working on an diagramming application which displays boxes as subviews inside a larger view. The user can move the boxes around. I am persisting the positions of these boxes using core data into a sqlite database by holding the height, width, x and y (of the top-left corner). When I open up a diagram I am reading these values from the database and using them to set the frame of the subview within the main view.
In portrait mode this works fine and the boxes are repositioned at the correct points on the display. However, when I rotate into landscape, or start the application in landscape and open the diagram, the positions of the boxes are wrong.
I have traced through the code and can see that the correct values are coming back from the persistent store and being used to correctly set the frame. However, once the UIView for the subview is on screen it is positioned at a different location (clearly visible and confirmed by checking the values in the frame of the view).
Now the odd thing is that instead of being a fixed pixel offset, the x co-ordinate is always 8.5% larger than the value used to create the frame, and the y value is always 9.1% smaller.
Does anyone have any explanation as to why this might be and how I might solve the problem?
If it provides any clues, the main view is inside a UIScrollView.
Answer: Okay, I found the answer. I needed to set Autoresize Subviews to false on the UIScrollView. Having done that (by un-checking the appropriate box in IB) everything seems to be working fine.


Bootstrap 5 Carousel swipe to slide interaction breaks with inner elements using overflow? (Vertical scrolling breaks left to right swipes)

Question: Been searching for a day and no one on the internet seems to have this problem. I have a Bootstrap 5 carousel, relatively vanilla setup except I removed the buttons to solely rely on swiping to navigate through carousel-items.
Swiping left to right works just like the samples, no problem, until I allow the content inside them to be vertically scrollable via overflow-y being set to either auto or scroll in CSS. Then it's like the inner element handles the pointer events and does not propagate them further to the parent elements. I can't find any way to force propagate the events.
What am I missing here? How can I get the carousel-inner (or carousel object in general) to continue processing swipe events with a overflow-y child elements?
The HTML:

The CSS:
.pool-carousel-inner {
    overflow-y: auto;
}

Probably irrelevant context: I am using stimulus to handle some other JavaScript needs, thus the controller attributes. I am explicitly calling the carousel constructor from there, per the bootstrap docs, just to get swiping working at all. I have to customize CSS via an inner class (pool-carousel-inner) because I use carousels in multiple other places that behave and look differently.
I've also done things like setting my pool-carousel-inner class width to 50% and can verify the swipe definitely still works on the "empty" space that the inner element doesn't take up (i.e. the space represented by the carousel-inner element that is NOT covered by the pool-carousel-inner element), so I know the carousel is setup correctly. But if I start a swipe/drag left-right over the inner content, it's like it's trying to scroll the whole browser window and the interaction events don't get handled by bootstrap.
Answer: I was able to find a workaround/fix for this. I had to take Bootstrap's most basic example and carefully watch what it was doing with class lists in the debug console to figure this out, because it's not well documented anywhere.
It seems when you put an overflow style on an element, it takes control of touch input away from the browser on some level and so pointer events stop propagating? I was able to restore it by adding a touch-action style to the inner element like so:
Solution
.pool-carousel-inner {
    overflow-x: hidden;
    overflow-y: auto;
    touch-action: pan-y pinch-zoom; // Have to re-set this little hidden gem that bootstrap hides in .pointer-event or swiping breaks
}


What is the evolutionary origin of euphoria and dysphoria?

Question: What kingdoms from the three domains haven't evolved something like the reward system in us? Couldn't we feel neutral all the time and undergo an involuntary push towards the right behavior instead, without the need for joy or distress?
Comment: One question at a time, there are at least 4 separate questions here in only three sentences.
Comment: "involuntary push" towards certain behaviors to satisfy biological needs sounds like a reasonable description of mesolimbic system we do have. Like how else would such drives manifest in cognitive beings? We'd need to retain cognitive mechanisms for prioritizing conflicted drives in real time such that we don't just drop everything when we get a little thirsty or tired, but also so those drives can increase based on the severity of the need. Without varying degrees of discomfort and contentment, what would that even look like?
Answer: Perhaps it's best to equate euphoria with dopamine, because if it can be found to control sex, food choice and foraging of invertebrates, that a major piece of the puzzle:
Dopamine is believed to have evolved around 600-700 million years ago in simple organisms like bacteria. At this stage, dopamine likely had basic functions related to cellular signaling and regulation.
For worms and insects, dopamine played a role in various physiological processes, including locomotion, feeding, and mating behaviors.
In bacteria, it has pretty simple functions in several species like Escherichia coli (E. coli) and Pseudomonas aeruginosa. Although dopamine levels in bacteria are relatively low compared to those in mammalian systems, its presence suggests potential physiological roles.
Bacterial dopamine biosynthesis pathways are similar to those in mammals, involving the conversion of the amino acid tyrosine into dopamine through a series of enzymatic reactions. Key enzymes involved in this process include tyrosine hydroxylase, which converts tyrosine to L-DOPA, and aromatic L-amino acid decarboxylase, which decarboxylates L-DOPA to dopamine.
In E. coli, dopamine is produced in response to oxidative stress caused by exposure to reactive oxygen species (ROS). Dopamine acts as an antioxidant.
Studies have shown that dopamine can enhance the production and stability of the extracellular matrix, promoting biofilm formation in various bacterial species.
Dopamine can modulate flagellar rotation and affect the motility of certain bacteria. In Pseudomonas aeruginosa, dopamine has been shown to enhance twitching motility, a form of surface-associated movement.
in the honeybee (Apis mellifera), dopamine is involved in associative learning and memory formation related to foraging. Dopaminergic pathways are activated when the bee receives a reward, reinforcing behaviors associated with finding food sources.
in insects like fruit flies (Drosophila melanogaster), dopamine is involved in fine-tuning flight behaviors, such as wing movements and flight initiation, and also in arousal.
Dopamine contributes to reproductive behaviors in many invertebrates. It can influence courtship behaviors, mate choice, and mating success. For instance, dopamine affects mating behaviors and receptivity in the nematode Caenorhabditis elegans.
Nematodes are some of the simplest invertebrates, so their use of dopamine for sexual reproduction suggests that the evolution of mammalian euphoria could go back 570 million years ago.
Answer: This is kind of a  philosophical question in my opinion.
First of all, what is 'right' behaviour?
Something that may be right in one culture may not be right in another.
It highly varies from individual to individual as well.
For example if you think focussed and planned studying is a right behaviour and your brain is caught in some kind of a reward loop in a useless activity like browsing the social media which is causing you distress.
So the question arises that does studying give humans some kind of an evolutionary or biological advantage such that nature may try to evolve our minds in such a way that it is consistently able to focus on studying? I don't believe it does. We are basically same from the survival point of view whether we are browsing social media or studing as your body is surviving and functioning appropriately which is the entire point of evolution itself. If hypothetically studing gave you better survival instincts then maybe evolution could take place in that direction.
However lets take another case;
Lets suppose certain variations exist in genes coding for muscle enzymes and proteins such that some people have better stamina or strength. Over the course of evolution they are likely to be selected as it gives them some kind of an evolutionary advantage.
But the development of the complex human brain is a huge evolutionary accomplishment in itself. Maybe the development of this reward system is itself a beneficial thing and helps us to focus? It basically puts the brain on autopilot mode where we don't have to think much and keep doing things repetitively, it could have evolved to save energy and maybe nowadays we have created things that take advantage of this exact same thing.
It could be that this reward system was actually evolved for our benefit but we humans have themselves learnt to take advantage of this in other humans.

Reward is a natural process during which the brain associates diverse stimuli (substances, situations, events, or activities) with a positive or desirable outcome. This results in adjustments of an individual's behavior, ultimately leading them to search for that particular positive stimulus.
https://www.ncbi.nlm.nih.gov/pmc/articles/PMC8992377/#:~:text=Reward%20is%20a%20natural%20process,for%20that%20particular%20positive%20stimulus.

If we follow along the lines of this definiton, then reward sytem development seems highly beneficial from the biological point of view.
It readily helps to distinguish between desirable and non-desirable stuff.
I strongly believe that evolutionarily it is in our best interests, it is we who are misusing it.
Another remarkable property of our brain is to get conditioned to what can trigger this response and what cannot.
Thank you.
Comment: It's not really philosophical. I wanted to ask what species did emotions like joy, sadness originate with. By "right behavior" I simply meant the things we naturally tend to do or avoid which increase our chance of survival and reproduction.
Comment: If you meant that by 'right' things then we are constantly evolving towards it. The development of senses of vision, hearing and smell and the development of reflexes are all directed towards it. Emotions are usually related with the frontal lobe and although other mammalian species and some other chordates feel emotions, humans are the ones with the most complex and complete set of emotions with the required capability and anatomical structures to express them as well. I would suggest you should read the development of frontal lobe, that will really help as well.


Disaster Response Unit cars not deploying?

Question: It will increase from 0 to 10 very quickly and go back to zero. I tried placing a couple of them and every once and a while ONE car will deploy to look for survivors, is anyone else having this annoying glitch? Only the 3 helicopters are working for me.
Answer: This question is old and it is possible your problem has been resolved by now, but I will put forth my findings anyway!
There are a couple of potential causes for your issue.

If you are using the auto bulldoze mod, you need to turn off burned buildings otherwise the disaster units will not search the rubble. You can also get this version of auto bulldoze which is updated to work with the Natural Disasters DLC.
If the roads are damaged and the ground vehicles cannot get to the disaster site, they will not leave. With that being said, helicopters should still deploy.


How to uninstall this blank icon?

Question: A few days ago I tried to uninstall an app and now it won't reinstall. It just comes up with this blank icon and I can't reinstall it. I've tried to reset and hard reset, installing the app from iTunes and it won't remove. I don't know what to do. Can someone help me? I have iFunBox too. It also won't remove from Storage Settings. Here is what the icon looks like:
Answer: Thanks for all the help guys. I did firgue it out.  I had a copy of the.ipa flie on my pc of the app that was causing problems and I had to open ifunbox and install the app by selecting the flie on the computer and it worked and got rid of the blank icon.
Answer: Just restart your phone. It will be cleaned.
EDIT: Maybe try to Clean Cache or Memory Junk utilities within this free App :
https://itunes.apple.com/be/app/battery-doctor-must-have-battery/id615987910?l=fr&mt=8
Comment: I have. it wil not go away
Comment: nope did not work
Comment: @shane is your phone jailbroken?
Comment: never jailbroken in my life
Comment: Any other suggestions
Answer: Back up the phone. If it asks if you want to copy Apps do that as well.
once it is backed up, go into settings -> general -> reset -> erase all content and settings.
Once that is done (it will take maybe 5 minutes) plug it back into the computer, launch iTunes and restore from backup.
If rebooting, etc. did not work this should. It's an app that did not completely delete and all you can see of it is the blank icon.

How to uninstall this blank icon?


How to create ssh tunnel using netcat?

Question: I want to create reverse connection between two machines, but these is a firewall in the middle preventing all connections, except ssh. I want to create ssh tunnel using netcat, could you please tell me how to it?
Comment: You don't need to create an SSH tunnel to do this - all you need to do is get NetCat to talk on port 22, as that is all the firewall is likely to be blocking on. [man nc](http://linux.die.net/man/1/nc) should give you all the information you need.
Comment: netcat is not able to liste to port 22, because there is another application using it.
Comment: That is worth adding to the question - the more info you give us, the more likely it is that we can provide an answer.
Comment: now is it possible to create ssh tunnel using netcat, if yes, then how
Comment: Note, `netcat` sends *plaintext* over tcp
Answer: What's up?  Here's the meat and potatoes:
nurf@sessmacheen $ ssh -f -L localport:localaddress:remoteport \
    user@remoteaddress sleep 10; nc localaddress localport

This is assuming that sshd is listening on the remote box, which I think I can infer from your post.
Ok! So ssh is passed -f, which just backgrounds it after the connection is made, and -L.  I remember -L as 'Link'.  It creates a tunnel, wiring up a port locally to a port on the remote host (the localport:localaddress and :remoteport user@remoteaddress parts, respectively).
So ssh is reaching out and holding hands with sshd on the remote host (for 10 seconds, anyway), and it's sitting locally with it's hand outstretched waiting for something else to grab hold.  So we nc localaddress localport.  Et voila!
Granted the one liner above doesn't actually do anything except establish a connection and then run sleep 10 on the remote box.  Here's a more practical example, totally ganked from this article.
## let's pull a back up image  over the wire!                   ##
## first we set up the image for grabbing on the remote machine ##
## by piping it to nc which then starts listening on port 9000  ##

dude@remotebox $ cat backup.ico | nc -l 9000

## and now we tunnel! locally, ssh opens up on 9001, and        ##
## connects to 9000 on the remote machine where nc is waiting   ##
## with cat, ready to go.                                       ##

nurf@sessmacheen $ ssh -f -L 9001:127.0.0.1:9000 dude@remotebox \
    sleep 10; nc 127.0.0.1 9001 | pv -b > backthatthangup.iso;

## this is pretty sweet because after nc gets done with the     ##
## connection, ssh finishes running sleep and closes it so you  ##
## don't have to fool with it.  nice and tidy.                  ##

## pv is a handy little utility that tracks data across a pipe  ##
## and will show you a progress bar and whatever else you want  ##

Naturally, to create this connection in 'reverse', you just, you know, do it the other way 'round.  Backwords, if you will.  Let me know how it works!
Oh yeah, also: nc won't bind to 22 because sshd's oh-so-privileged self is already sitting there.  Hence the use of arbitrary ports outside the reserved ports range (i.e. anything above port 1024).  Since 22 is one of the reserved ports, you'd have to be root to bind to it anyway.
Comment: ok thanks, unfortunately i do not have root access on the target machine which equals to (nurf@sessmachee) in your example.
Comment: Shouldn't need root.  What are actually trying to do?
Answer: Beside the original post, you wrote you don't have root access to the computers, and that there is already a daemon listening on port 22.
In case you are in the sudoers group, nothankyou's solution is the one to go with:

sudo ssh -f -L localport:localaddress:remoteport user@remoteaddress
  sleep 10; nc localaddress localport

In case you don't, but somehow ( :O ) have access to the iptables (or similar) on the machine with SSH running already, try redirecting only the other computer ip to another local port where you will be listening with NC:
First, listen using the quoted code, or simply using NC:
nc -l -p 1234

Second redirect the incoming traffic to port 1234 in case of a familiar source ip address:
iptables -A INPUT -s <computer A's ip address> -p tcp --dport 22 -j REDIRECT --to-port 1234

In the reasonably case in which you don't have both some kind of root access and access to the local firewall rules, it is possible for non-root processes to bind to "privileged" ports (<1024) on Linux,use the following line to do so:
setcap 'cap_net_bind_service=+ep' /path/to/program

check this question from StackOverflow for more information. It might won't solve all your problems but it seems like a good hint until you'll give us a better description of your problem.

How to create ssh tunnel using netcat?


Residual variance: linear restrictions for $e_i$

Question: I know that the residual variance can be defined like this:
$$s_R^2=\frac{1}{n-2}\sum_{i=1}^ne_i^2$$
Apparently the denominator of the fraction is $n-2$ rather than $n$ because the $e_i$ have two linear restrictions:
$$\overline{e}=\frac{1}{n}\sum_{i=1}^ne_i = 0 \quad , \quad \sum_{i=1}^n x_ie_i=0$$
While the first restriction seems natural to me, I don't understand where does the second restriction come from, nor why does that formula work. Could someone help me undestand this?
Comment: The second equality ensures that the $x_i$ and $e_i$ are uncorrelated (check out their sample covariance). The errors are considered independant and identically distributed, and the residuals have zero mean (as a result of OLS).
Answer: Both restrictions are properties of regression hyperplane. They are easily proven after you minimise the square sum of residuals:
$\mathbf{X}'\mathbf{y} = \mathbf{X}'\mathbf{Xb}$ can be solved to obtain regression coefficient $\mathbf{b}=(\mathbf{X}'\mathbf{X})^{-1}\mathbf{X}'\mathbf{y}$, or to prove second (in yours description) property of regression hyperplane:
$$\mathbf{X}'\mathbf{y} = \mathbf{X}'\mathbf{Xb}$$
$$\mathbf{X}'\mathbf{y} - \mathbf{X}'\mathbf{Xb} = \mathbf{0}$$
$$\mathbf{X}'(\mathbf{y} - \mathbf{Xb}) = \mathbf{0}$$
$$\mathbf{X}'\mathbf{e} = \mathbf{0}$$
There is whole matrix $\mathbf{X}$ in this equation, and therefore this is a set of equations.
However in a model with a constant, the first column of matrix $\mathbf{X}$ is equal to vector of ones. Therefore if we pick only first equation of the whole set:
$$[1,...,1]\cdot[e_1,...,e_n]' = 0 $$
$$\sum_{i=1}^{n}e_i = 0$$
Again, as they are properties, they are always true if you use OLS (and a model with constant for the first described by you property).

The character $'$ stands for Transmutation; bold stands for matrix and vector notation.


Do empty orbitals have energy?

Question: Suppose we have the Na (Sodium) atom. It has half-filled the 3s orbital and unfilled 3p orbital. Does the empty 3p orbital have energy? also does the energy of 3p change if an electron occupy it?
Answer: Orbitals themselves are just labels for the states we can observe the electrons to be in. The electrons are what have energy, not the orbitals. So it doesn't make much sense to talk about the energy of an orbital itself. All you can talk about is the energy an electron would be observed to have it it was in a certain orbital.
Therefore, whether or not an electron is in an orbital does not change the energy associated with that orbital.
Comment: This is correct, but it doesn't quite go far enough. Itis important to note that the energy doesn't belong to any individual electron in any individual orbital - it can only be assigned to the full set of electrons in a given global configuration. There are some components of the energy that can be assigned to individual electrons (the kinetic energy and the nuclear potential), but they're fairly useless without the collective electron-electron repulsion, which can't be split that way.
Comment: @EmilioPisanty Thank you for the additional information :)
Answer: No, No, and No to your three questions.
When physicists talk about the energy of an orbital, they really mean the energy (kinetic energy plus potential energy) of an electron in that orbital. Orbitals just represent possible states for an electron. An empty orbital with no electron has no energy.
You should not think of the energy of an orbital changing when an electron occupies it, because the orbital itself is not something that can have energy.
You should think of an electron changing energy when it changes its orbital. For example, when an electron moves from 3s to 3p, it needs energy to do that, because in 3p it has more energy than it has in 3s. This extra energy has to come from somewhere, such as a photon hitting the atom.

Do empty orbitals have energy?


Deustch algorithm using one qubit

Question: Deutsch algorithm uses two qubits to determine the type of function. But what if we have only one qubit? How the algorithm would be implemented? And especially, how $U_f = |x\rangle |y \oplus f(x)\rangle$ would look like?
Answer: Unfortunately, as D.W. says, it's not possible to do Deutsch's Algorithm with only a single qubit.
The key is the line you quoted in your question: the quantum oracle for the function $f$ returns $\mid x\rangle \mid y \oplus f(x)\rangle$. This only works with two qubits.
Why can't we just make the oracle return $\mid f(x) \rangle$? Well, in quantum computing, all functions must be reversible (you can reconstruct the input from the output), and we have no guarantee that $f(x)$ is reversible. And if we force $f(x)$ to be reversible, then we know it's balanced, and the problem becomes trivial (return "balanced" every time).
The only way to make a reversible function out of a function that may not be reversible is to add "ancillary" or "garbage" qubits; this is how the Toffoli gate implements the non-reversible AND function. That's basically what the second qubit is doing here: without it, we can't even necessarily call the function.
Answer: You can't.  If the algorithm needs two qubits, you can't implement it with just one qubit.
Comment: I mean maybe it's possible to implement another algorithm to solve the same problem but using one qubit.

Deustch algorithm using one qubit


(In context of Indian parliament) what do the words "demand" and "grant" mean in the phrase "demand for grant"?

Question: My book has explained the phrase "demand for grant" in the chapter "Indian Parliament" but i do not understand what do "demand" and "grant" mean. I tried googling them but did not find any valuable resource. What do they mean?
Answer: A Demand for Grant is a bill (i.e. piece of proposed legislation) seeking approval for estimated expenditures for a particular department or sub-department of a large department of the national or state or territory government from the national government's general fund, each of which must be approved separately by the Lok Sabha in order to authorize that spending pursuant to Article 113 of the Constitution.
"Revenue expenditures" (which are tax breaks that would be called "tax expenditures" in U.S. public policy parlance), "capital expenditures", intergovernmental grants, loans and advances against already approved expenditures for future time periods, must have a Demand for Grant approved as well.
In this context the word "Demand" means a formal request, and "grant" means a dispersement of money by a government or charity that is not legally obligated to disperse the money in any particular amount. So, a "demand for grant" is a formal request that money be voluntarily dispersed by the government as part of its annual discretionary general fund budget.
See here.
Comment: Can you please clarify what you mean by disperse and dispersement?
Comment: "Dispersement" means a transfer of money or application of a credit against money otherwise owed. "Disperse" mean the act of making a "dispersement".
Comment: Is "dispersement" commonly used in this way? I would have thought transfers of money would be a "disbursement"...
Comment: Yes. For example, if you have a trust at the same bank where you have credit card debt and the trust pays off the credit card debt via a credit against the amount you owe the bank that would be called a dispersement even though actual money doesn't change hands.


How to hide the python code from users?

Question: I am developing a paid application in python. I do not want the users to see the source code or decompile it. How can I accomplish this task to hiding the source code from the user but running the code perfectly with the same performance.
Comment: Possible duplicate of [Should I spend time preventing piracy of my app?](http://programmers.stackexchange.com/questions/267981/should-i-spend-time-preventing-piracy-of-my-app)
Comment: Possible duplicate of [How do you prevent the piracy of your software?](http://programmers.stackexchange.com/questions/10340/how-do-you-prevent-the-piracy-of-your-software)
Answer: To a determined user, you can't.
From a practical standpoint, you can do some tricks, such as wrapping it into a binary executable or using obfuscation.
See here for full details: https://stackoverflow.com/questions/261638/how-do-i-protect-python-code
Answer: There's no use in doing that.
If your application is not incredibly small and simple, then even if the client (or other programmers they hired) were to work on that code, they'd still need a lot of your help with it.
If it is incredibly small and simple, don't even bother with it. The client could just get someone to rewrite it from scratch anyway.
Answer: I was in a similar situation to this not too long ago. But i managed to find a way to hide my source code, at least, enough to deter most from trying to hack it.
Contrary to common belief, obfuscation and/or encryption of interpreted language scripts is possible. The question is, do you have the time (and motivation) to devote to it? You'll need to make sure whichever "obfuscation/encryption" method you use is very difficult to crack, and that it does not slow down the execution time of the script in any noticeable way.
If you wish to encrypt a python script, without having to do any work on your end, you can do so using this site.
I tested the following script using the aforementioned site and it produced a very intimidating output, which worked (at least for my purposes):
#!/usr/bin/env python2
# vim: ft=python

import sys, json, urllib2

URL = 'http://127.0.0.1:8080/optimization/resources/_harness/status?_fields=health.summary'

try:
    response = urllib2.urlopen(URL).read()
except:
    print('HEALTHCHECKS CRITICAL - Error fetching health check at %s' % URL)
    sys.exit(2)

parsed = json.loads(response)
resource = parsed["resource"] if "resource" in parsed else parsed
status = resource["health"]["summary"]["status"]
incidents = resource["health"]["summary"].get("incidents", [])
warning = len([incident for incident in incidents if incident["status"] == "WARNING"])
critical = len([incident for incident in incidents if incident["status"] == "CRITICAL"])

if warning or critical:
    print('HEALTHCHECKS %s - %d WARNING - %d CRITICAL' % (status, warning, critical))
else:
    print('HEALTHCHECKS OK - no incidents')

print(json.dumps(resource, indent=2))

sys.exit({"OK":0, "WARNING":1, "CRITICAL":2}.get(status, 3))

Can the obfuscated code produced be broken into? Maybe, maybe not. But it is sure to deter most people from even attempting it.
If you do have some time on your hands and wish to encrypt your script on your own using your own improvised method, you'll want to use the openssl command. Why? Because it appears to be the one encryption tool that is available across most Unix systems. I've verified it exists on Linux (ubuntu, centos, redhat, mac), and AIX.  SunOS i believe uses the "crypt" command instead.
The simplest way to use Openssl to encrypt a script is:
1. cat <thescript> | openssl aes-128-cbc -a -salt -k "specify-a-password" > thescript.enc

OR

2. openssl aes-128-cbc -a -salt -in <path-to-your-script> -k "yourpassword"

To decrypt a script using Openssl (notice the '-d'):
1. cat thescript.enc | openssl aes-128-cbc -a -d -salt -k "specify-a-password" > thescript.dec

OR

2. openssl aes-128-cbc -a -d -salt -in <path-to-your-script> -k "yourpassword" > thescript.dec

The trick here would be to automate the supply of password so your users need not specify a password each time they wanted to run the script.
Comment: Your solution to prevent your script from being accessed is _giving it away_ to a third-party website you don't trust? Or decrypting it on the fly with a command the user can see and easily run himself to get the original source code? That doesn't seem like a very good solution.
Comment: Does this "premium" website cost money?  If so, perhaps your answer should mention that more clearly ;)
Comment: AES? I suggest using ROT26 for enhanced security.

How to hide the python code from users?


Raileasy split ticketing purchased

Question: have bought but they have not reserved any seats as requested saying it is not possible.Will be travelling in 10 weeks time. Can I take tickets to the station of departure and ask for reserved seats in the meantime?
Comment: I travel on trains every day (West Coast Virgin Trains and London Northwestern) and normally there's always at least one seat that will be free.  Even if the train is packed there's always one seat somewhere. However, if you are travelling with a lot of luggage then you can probably ignore my comment as indeed a reservation makes life easier (though to an extent - if the train is packed there might not be space for luggage next to your reserved seat and you might have to shoo away the person who is sitting in the seat that is reserved for you).
Comment: If you tell us which train operator this is for we should be able to tell you if seat reservations would normally be possible.
Comment: nottingham via peterborough to norwich on east midland rail
Answer: Yes, although you'll need to collect the tickets first and take them to the ticket office. It doesn't need to be the station of departure, any ticket office will be able to do so.
Although consider that whatever problem lead RailEasy to be unable to reserve may also effect the ticket office. Remember not all trains are capable of being reserved.
Source: Done so many time repeatedly, it's also mentioned on this national rail page: https://www.nationalrail.co.uk/times_fares/ticket_types/46581.aspx
Comment: Agree with some trains it might not be possible to reserve a seat.

Raileasy split ticketing purchased


macOS / BSD - add dir to locate database?

Question: How do I add a directory to be indexed by locate.updatedb on macOS / BSD so that I can find files in that directory with the locate command?
I read the man page of locate(1) on Mac, but didn't find anything useful.
Answer: The locate(1) man page tells you how to use the locate command to look stuff up. As the indexing is done by locate.updatedb, you should read the locate.updatedb(8) man page instead.
But on a macOS Big Sur at least, the information relevant to your question is rather limited. Basically it just says:

The contents of the newly built database can be controlled by the /etc/locate.rc file.

By default, all the settings in /etc/locate.rc seem to be commented out. The relevant lines for your question are:
# directories to be put in the database
#SEARCHPATHS="/"

# directories unwanted in output
#PRUNEPATHS="/tmp /var/tmp"

# filesystems allowed. Beware: a non-listed filesystem will be pruned
# and if the SEARCHPATHS starts in such a filesystem locate will build
# an empty database.
#
# be careful if you add 'nfs'
#FILESYSTEMS="hfs ufs apfs"

Assuming the file follows the convention of presenting the default settings as commented-out examples, it seems that everything located on HFS, UFS or APFS filesystems will be indexed by default, except the contents of /tmp and /var/tmp.
If the directory you wish to add is located on one of those filesystem types, and is not under /tmp or /var/tmp, the directory should automatically get indexed the next time locate.updatedb runs.
Note that many variants of locate will check for access permissions when displaying the results, and will only show you files you would have permission to see.
Comment: Since Spotlight is the primary search engine on macOS and `locate` is just something that was inherited from macOS's BSD origins and probably hasn't received much attention, I think that's a good assumption to make.
Comment: I did some tests, and it seems that not all files on the (APFS) filesystem on macOS Big Sur 11.5.2 (Intel) are indexed - `locate` can find `/usr/local/Homebrew/Library/Taps/homebrew/homebrew-cask/Casks/google-chrome.rb`, but not `/usr/local/Homebrew/Library/Taps/homebrew/homebrew-cask-versions/Casks/google-chrome-canary.rb`, and it can't seem to find contents in `~/my-custom-dir`.
Comment: According to the `locate.updatedb(8)` man page, the database is updated only *once a week* by default - did you run the update task manually for testing?
Comment: No, I didn't run `locate.updatedb` before the tests. But these brew tap dirs and `~/my-custom-dir` has been on my mac for months, so they should be indexed, right?
Comment: Hmm. Also, on macOS you can use the `mdfind` command that utilizes the Spotlight search engine and its databases, which might be a better option than relying on the very basic `locate`.
Comment: I found something interesting. When limiting search inside a large dir, like `/usr/local/Homebrew/Library/Taps`, `find -name ...` is as fast as `mdfind -onlyin ... -name`, and twice as fast as `locate ...` without limiting search scope.
Comment: Maybe `locate` is not too reliable on newer macOS versions and I should avoid using it?


Lenovo A850 bricked while flashing stock ROM

Question: My phone Lenovo A850 (MT6582) bricked just now. I accidentally pulled out the USB cable when it was flashing stock ROM by using Smart Phone Flash Tool. Now it's not charging and won't turn on, like a dead phone. I can get into MTK Meta Mode by pressing Volume Up & Volume Down then connect the USB, with and without battery. But when I try to flash anything, it gives error 4032. Please help me this is not my phone and I broke it! It does nothing when I press power button.
Comment: Does it vibrate or display shows anything at least when you attempt to power it on?
Comment: Nothing happen when i press the power button ,
Comment: Are you sure that is the correct ROM for that variant of the phone you are trying to flash?, try changing varants if you are not sure because this problem mostly arises if the ROM isn't compatible with your phone, if you are sure of the model then I think the problem might be incompatible variants
Answer: Is your PC showing preloader devices connected in devices and printer menu
when you put the USB cable in your device without battery (press volume key 3 or 4 time)?
If it is showing, then you can flash your stock ROM again.


Creating bootable USB from a compromised OS. Is it safe?

Question: If we buy for instance a laptop with an OS pre-installed e.g. Ubuntu and but the original seller was not reputable and there are doubts with the preinstall.
My question is: if we use the laptop to download Ubuntu and create a USB bootable iso to wipe out and re-install the OS, is this process safe if we assume the installed OS we currently use for this process is compromised?
Answer: Theoretically speaking, it's not safe. If I'm downloading another OS from the compromised install, then there could be code installed that patches an exploit into the image being downloaded or written to the drive. If you want to check it with a hash sum program, then the program could be patched to report a false hash on the patched files. If you build the hash program from source, then the compiler could be patched to add the fake reporting to the hash sum program, and also to the compiler and to the kernel itself. For any way you can think of checking the integrity of the download from within the system itself, there is a way to make the computer fake the response to you.
In practice, all of these steps would require a rather high level of sophistication and targeting. The attacker would either have to know for sure what OS you're going to download, so that the patch can target it accurately, or else make the patch very generic across thousands of OSes that you may want to download. Patching the hash programs is similarly difficult, and patching the compiler is perhaps even more so, because then the compiler would have to know to add the bad behavior to everything it touches -- and checking whether two programs are the same is a non-decidable computational problem.
If you're not a particularly valuable target, (especially if the attack is targeted at any buyer of the laptop and not yourself specifically), then any potential system compromise would probably be used for low-stakes credential stealing or botnets, which would get wiped out by a system reinstall and would not have the means to survive one.
If you want to be particularly paranoid, you could use the compromised system to download an extremely obscure OS and version, write that to a flash drive, then install that OS onto the system drive, then use this new system (which could be compromised, but it is unlikely) to download a new OS image, then flash and install that. You can also use checksums at every step of the process, perhaps checksumming random parts of the file to compare them to a known good one (though if you have access to a computer with a known-good file version, you should just use that one instead of going through all this).

Another option that has even more paranoia and a spy-thriller vibe involves finding a super-small Linux distro (for example, Tiny Core Linux's Core will give you a busybox shell, a DHCP client and a few other things for 18MB, even less if you get one of the older versions), downloading it on your phone, then manually typing it into the computer. Then you know the data you input is safe, and the malware that would try to mess with the data wouldn't see the entire file at once, and even if it does there's not enough space for it to hide its work.
The current download has 17870848 bytes, which is double that in hex digits. At my top typing speed of 250CPM, this comes out to 2382 hours, or just over three months of non-stop typing. At a wage of $7.25/hour, this would cost a bit over $17k. With that sort of money, you could just buy a new computer from a reputable supplier and not have to worry about this particular supply chain attack.
Or just buy a pre-made Debian installation medium. Similar offers are available for other distros.
Comment: What is an example of `extremely obscure OS and version`?
Comment: @Jim That's mostly up for you to pick -- it is basically something that the theoretical replacement exploit wouldn't think to include, or wouldn't have the ability to. If I were doing it, I'd go on https://distrowatch.com/ and pick whichever one I've never heard of. The idea being that if I haven't heard of it, then the hackers probably wouldn't have either.
Comment: What if I have already a USB bootable with Ubuntu and boot from there. Can plugging the USB corrupt it at the boot process? Is that possible?
Comment: @Jim If you plug it in to a running system, then it could theoretically be -- the same very theoretical possibility as if it gets downloaded on the system. If you only boot from the BIOS/UEFI, then a compromised OS won't get a chance to intervene, but a compromised firmware might: [this already exists](https://www.tomshardware.com/news/moonbounce-malware-hides-in-your-bios-chip-persists-after-drive-formats), though it usually targets Windows and is developed by APT-level agents and is, again, something I wouldn't be worried about in my day-to-day operations.


Using Mobile SIM card with an iPad Mini

Question: If I buy a Wifi and Cellular iPad Mini, could I cut down my mobile SIM card and use its cellular data with the iPad?
Comment: Since the iPad mini takes a nano-sim - it's not clear if you are looking for hardware to help steady your hands while cutting or if you don't know what cards are used in the device. http://www.amazon.com/s?ie=UTF8&keywords=nano-sim&page=1&rh=i%3Aaps%2Ck%3Anano-sim
Answer: A simple question but there is no simple answer.

You'll need to know the frequencies and protocols used by your carrier and ensure they are supported on your iPad. 3G is highly likely to be OK but it's not 100% (for exampled, much of T-Mobile's 3G network runs on a frequency that's not compatible with the current iPad/iPhone
As noted, you'll need to cut the card down to nano-SIM size.  If you screw it up, the SIM is toast and will need to be replaced. You'll also need an adapter if you want to put it back into the phone.
The iPad needs to be configured with the proper data/APN settings for your carrier.
Your carrier has to not care that you are doing it.  I've heard stories about carriers detecting that a phone SIM is being used in a tablet and disabling the SIM.

Using Mobile SIM card with an iPad Mini


How can I show in a report or otherwise both the field name and field alias for a feature?

Question: I am trying to create a report that will list both the field name and the field alias for every table we have in our geodatabases.  I know there is no existing tool that can do this and I have found several python scripts that can do things such as batch edit the alias field but I am just looking to display both fields for each table or a null value in the case of no alias shown. I am working in Arc 10.3.1.
Answer: You can use the following Python function below to create an excel spreadsheet report:
import os
from xlwt import Workbook, Borders, Font, XFStyle
import arcpy

def createFieldReport(fc, out_excel):
    """create an excel spreadsheet showing field names and alias

    fc -- feature class
    out_excel -- output excel spreadsheet (should end in .xls)
    """
    if not out_excel.endswith('.xls') and not out_excel.endswith('.xlsx'):
        out_excel += '.xls'

    wb = Workbook()
    ws = wb.add_sheet('Sheet 1')

    # width dict, to autofit columns
    widths = {0: 11, 1: 12}

    # set header styles
    fntHeaders = Font()
    fntHeaders.bold = True
    fntHeaders.height = 220

    # write headers
    ws.write(0, 0, 'Field_Name')
    ws.write(0, 1, 'Field_Alias')

    # freeze headers
    ws.set_panes_frozen(True)
    ws.set_horz_split_pos(1)

    # write values
    for i,f in enumerate(arcpy.ListFields(fc)):
        ws.write(i+1, 0, f.name)
        ws.write(i+1, 1, f.aliasName)

        # update width if wider than last or default
        if len(f.name) > widths[0]:
            widths[0] = len(f.name)
        if len(f.aliasName) > widths[1]:
            widths[1] = len(f.aliasName)

    # autofit width (reads width dict in case you add more fields)
    for i, w in widths.iteritems():
        ws.col(i).width = w * 350

    wb.save(out_excel)
    return out_excel

if __name__ == '__main__':

    fc = r'C:\some_path\togeodatabase\featureclass'
    output = r'C:\Temp\test.xls'
    createFieldReport(fc, output)
    os.startfile(output)

To apply this to an entire geodatabase you could simply iterate through each feature and call the createFieldReport() on each feature class and create a unique name by grabbing the feature class name.
Comment: If this solved your problem please click the green tick Accept button next to it to thank the answerer for their effort.
Answer: X-Ray for ArcGIS will do this, although it may output far more information than you require.

X-Ray for ArcCatalog will help you:

Develop and refine geodatabase designs
Analyze the differences between two geodatabase designs
Merge two different designs in to a new consolidated geodatabase design
Check for reserved RDBMS field names in your design
Replace and reorder fields in a current geodatabase (via GP Script)
Import a design with geoprocessing
Localize field aliases and descriptions in your geodatabase
Populate workspace descriptions for your design
Create a data dictionary and diagram for your design


Can I use 2.5v bulbs in a holiday light string designed for 5v bulbs?

Question: I've got a lighting fixture that says it wants 5v .6w bulbs.  literally every one burned out, so he two spares aren't enough.  All the other ones I see now are 2.5 V.  Can I swap these in?  My guess is yes - they'll just draw whatever current makes sense, and since they're lower voltage won't generate more heat.  Just want to make sure, for safety reasons.
Comment: There's a reason they all burn out.  Your fixture sounds very old and it may be time to rewire it for modern bulbs, preferably LEDs.
Comment: @isherwood I've had a couple of strings fail in a similar way.  As each bulb fails, it's supposed to short out so it doesn't interrupt power to the rest of them.  The problem is that this decreases the total resistance of the string, increasing the current through it.  This increases the failure rate of the rest of the bulbs.  Once you lose enough bulbs, the failure rate goes very high and the remaining bulbs die pretty much all at once.  If you buy cheap lights (like I do), one of the bulbs likely won't short properly and a few bulbs survive.
Comment: How does one arrive at a state where *every* bulb is burned out? Did you actually leave the string in service as they, one-by-one, went dark? Or did something in the string fail, like a fuse?
Comment: you could rewire them, putting two 2.5v in series to make a 5v one. that sounds like a lot of work for cheap lights though...
Comment: @Harper it's not that old. It's more cheap than old. Not made for 24/7 use.
Answer:
My guess is yes - they'll just draw whatever current makes sense, and since they're lower voltage won't generate more heat.

No, that's not how it works.
Bulbs that are made for 2.5V can't be supplied with 5V, they'll draw twice as much power and burn very bright, but will probably burn out very quickly.
If you underpowered the bulbs - used a 2.5V power supply on 5V lights - that would likely just make them glow dim - but they'd probably last a long time.
Comment: The constant (or nearly constant) is the resistance.  V = IR so if you double the voltage, you double the current. Power = VI so if you double the current, you quadruple the power.


What is high caffeine coffee in Turkey?

Question: I live in Istanbul, I love espresso, but most espresso here is 100% Arabica. Robusta coffee is hard to find.
What alternative coffee do you recommend to get the right caffeine during the day?
Comment: option 1: most instant coffee is made from Robusta so if the only requirement is to have high caffeine then that may suit you. option 2: find suppliers of quality coffee in the local market, and if they can not sell the beans direct to you then ask them for details for some of their clients. they may tell you because it is more sales for their product.
Comment: take a double shot ?
Comment: Have you tried Turkish coffee? In my experience it packs more of a punch than a typical latte (which I know isn't a perfect comparison.)
Comment: I do not like the taste of Turkish coffee and it does not give me the pleasure I have to drink espresso coffee, here Starbucks also serves 100% Arabica.
I also saw all the physical and online markets, only one of which had 40% Robusta
Answer: A possible different approach.  Getting the perfect flavor is hard enough.  The more constraints and tangential variables you introduce, the harder it is to produce a desired flavor profile.  You say most espresso in Istanbul is made from 100% Arabica, and you love it.  Your objective is just to get more caffeine.  My suggestion would be to not mess with the flavor you love as the mechanism to get more caffeine.
Robusta has more caffeine, but it also has a different flavor.  There are also some Arabica varieties with more caffeine.  But caffeine is very bitter, and if you substantially increase its content in the brew, the result will be  noticeably more bitter.  So you may sacrifice the flavor you love to get more caffeine from that source.
An alternate approach would be to just take a caffeine tablet when you want the pick-me-up.  You can even wash it down with coffee that still tastes good.  :-)
Answer: You could try to find Vietnamese coffee in Turkey. Many kinds have high caffeine content. If you find them, you could get a phin for the preparation. Then these coffees will test best.
Answer: How about Taft coffee? They are known for their high caffeine levels. You can order online.
Just checked their website here, they claim to have 23.2 g caffeine per 1 kg of coffee. Actually I also buy Taft Coffee. I am not really considerate about caffeine levels yet it tastes really good.
Comment: Thanks, I edited that into your answer.
Comment: Can you elaborate a bit more to support that they have high caffeine levels? Are you affiliated with this brand?
Comment: @JJJ nope I am not. Just check their website here https://www.taftcoffee.com/  they claim to have 23.2 g caffeine per 1 kg of coffee. Actually I also buy taft coffee. I am not really considerate about caffeine levels yet it tastes really good.

What is high caffeine coffee in Turkey?


Geometry Nodes: subdividing specific edges

Question: For a project about differential growth, I need to do two things: subdivide edges that are above a certain length, and then subdivide their adjacent faces. For the subdivision, I can't manage to do it without having disconnected geometry or losing faces.
For now, my method consisted of separating the selected edges, subdividing the, and rejoining them with the geometry. Is there a way to do it "correctly"?
Comment: If this works for your needs, it's correct.  Does it not work for your needs?  If not, how?
Comment: The problem is that it doesn't work as expected. After the edges are subdivided, the faces are lost, as you can see in the image. The goal is to transform the triangular face into a quad and then triangulate it, but that can't happen if the face is lost.
Comment: What about if instead of separating the edges you want subdivided, you separate the *faces* you want subdivided-- "subdivide edges ... and then subdivide their adjacent faces."  Doing the latter will do the former.  Will that work for you?
Comment: I've tried the method you're suggesting, unfortunately it doesn't work, since each face gets subdivided into 3 quads, which is not the result I'm looking for. What I want is subdivide an edge and split it's adjacent triangular faces into two triangular faces. With the method you suggested I end up with 6 quads instead of 4 triangles. In addition, the disconnected geometry problem is still present with this technique.
Comment: So then, all input faces are triangles, you subdivide long edges, and join them to the opposite vertex of each face containing that edge?  Just trying to make sure I know what you're after.
Comment: Exactly ! Here's what I'm looking for in a clearer form [link] (https://imgur.com/a/R8148fJ)
Comment: Ok, one more question (sorry!)  Will there ever only be one edge per face at most that needs to get subdivided?  Only two at most?  Or can all three need to get subdivided?
Comment: No worries! The subdivision will happen based on a test selection: if an edge is longer that x, then subdivide and triangulate adjacent faces. So sometimes two edges of the same triangle might reach the subdivision threshold, but I think two at most. Here's an illustration of a two edges subdivision case: [link](https://imgur.com/a/ablBwuY)
Answer: Okay.  This will probably be a little more complicated than it ought to be, but it's how I've figured out how to do what you want.
You have a mesh composed of triangles and an input length.  For each triangle, if the longest edge is longer than the input, divide that longest edge into two, and then join the longest edge to the far vertex, creating two two triangles.
You may have two edges that are longer than the desired length.  If you do, you'd like to handle this as an ordered process rather than simultaneous, as given by the picture you provided in comments:

The new edges don't intersect; first we make one edge, then the other.
I'm going to make one more assumption, which is that you have no faces where the longest edge length is shared by two faces.  This would create ambiguity in the order in which you split the triangles.  With that assumption, note that I also rule out any zero-area faces-- any degenerate triangles, with two coincident vertices.
So first, we'll subdivide the longest edge and join to the opposite vertex; then, we'll repeat that process for faces containing the second longest edge.
First thing, we're going to have different topology-- more faces-- than our input geometry, so we'll have to make triangles.  I'll start by making a node group that will create a triangle with vertices at arbitrary positions:

Now, let's figure out how we can populate those positions, starting with a single triangle and cutting it in half:

Base geo on left.
I identify the longest edge with an attribute statistic node, which lets me separate into two distinct chunks of mesh: the longest edge, and the vertex that is not part of that edge.  To get one position, I take the position of the edge; to get the second position, I take the position of the second vertex of the edge at index 0 (there's only one edge); and to get the third position, I take the point position of the vertex.
And to get the other half of the triangle, I can just take the position of vertex 1 of the edge instead of vertex 2.  Which I can demonstrate by grouping this up, except for the relevant Edge Vertices node, and joining the output:

Now, we've got to repeat it for the new triangle, that contains the second longest edge of the original triangle.  Let's go into our Split Tri node group and get it to output whether the triangle we created indeed, contains our second longest edge, as well as the length of that second longest edge:

I'm making a copy of my input geometry that gets rid of my longest edge and my shortest edge, and then sees if the output triangle contains any edge that is at the same location.  And while I'm at it, I'm going to remember what the length of that edge actually is, so we can check it against a threshold.
Now, we can use that to iterate, splitting our faces twice:

We split the face into two tris; then, we split those two triangles into two more triangles.  But if one of those first tris doesn't contain the second longest edge, we use the unsplit triangle instead.  The input triangle is split along the longest edge, and then the triangle containing the second longest edge is split again.  We can finally add a threshold input to our modifier to prevent that second longest edge from being split:

Because that second longest edge is shorter than 1 unit here, there's no second splitting going on.
Okay, but we got a lot of faces!  And we haven't set a threshold for the first split.  Let's group everything up again and then set that group aside.  We'll start by separating our geometry into only the faces that contain edges longer than our threshold:

Then, using a repeat node, we'll iterate over every face in that selection:

I send my base geo into my repeat zone and out of my repeat zone.  I keep track of the count of the repeat, starting at 0, and check the face index of the source geometry so that I can split every triangle, in order, and join them to a running total of that geometry.  And the input for the threshold for the second split is set from the original modifier's input.
After that, we have a little clean up.  We can realize instances and weld the vertices back together, then repair any normals for triangles that got made upside-down:

A little bit of testing, and I see that precision errors are causing some problems for the comparison tests for edge lengths, where I'm measuring that the distance is greater than 0.  I'll change this to 0.001.  Inside my "splitTris" node group:

This is certainly more complicated than I'd like.  It's entirely possible that there are some errors and some corner cases I haven't considered.  Even though I'm providing the file, it's not intended to do the work for you, but as an adjunct to the text and pictures in this answer.  The general principle: iterate over faces; measure the positions of long edges to find two triangles; instance new triangles at those positions; do it again on sub-triangles that meet certain criteria.  There is a lot of evaluating things in different domains here, sometimes by specifying a domain, sometimes by capturing a domain, sometimes by evaluating on a domain, and these don't always act exactly the same (nor am I perfectly aware of how they differ: there's a lot of trial and error for me in getting Blender to recognize the domains I want to measure.)  Hopefully, even if there are some errors, if you understand the overall plan, you'll be capable of addressing them yourself, or of asking question on a sub-problem.  Because, frankly, this was a lot of work that I don't want to revisit, and I probably never would have done it save for a sense of duty after asking so many questions to clarify the problem :)
Comment: If only it was easier to patch Blender... https://projects.blender.org/blender/blender/pulls/113427
Comment: There's no "triangle vertices", but there's "corners of face" and "vertex of corner"
Comment: @MarkusvonBroady Without fully understanding the proposed commit-- I don't want to invest much effort into understanding things that may never be-- I'm not sure how much help it would be.  Making tris or ngons isn't really *that* hard.  But trying to store a bunch of data in different domains: edge lengths, vertex positions, on faces-- ended up being pretty hard.  And actually, the normal repair was bizarrely difficult, trial-and-error to get right, to get it to compare something like face normals to face normals.  When odds are it doesn't even matter for Mansour's purposes.
Comment: @MarkusvonBroady And, I'm disappointed in needing the repeat zone.  It seems like it should be unnecessary, but I don't see any "triangle vertices" like we have "edge vertices", so I couldn't figure out how do without.  Oh well, it probably doesn't really make a noticeable difference, just to my own sense of how things should be done.
Comment: @Nathan First I'm sorry for the late reply. Second, I can't begin to thank you for the amount of effort you invested in this, I certainly didn't expect to make anybody spend that much time on this, so thanks again. I'll try to profit from your setup as much as possible, even if it isn't the ideal setup but it will help me understand better working with geometry nodes. I really liked how you used the repeat zone as a foreach loop! Hopefully, we'll get an actual foreach loop node/zone soon.
Comment: The code I was trying to "replicate" is [here](https://github.com/inca/blender-differential-growth/blob/main/op_grow.py), in the script of a differential growth add-on, 25 lines of code (82-107). Hopefully, we'll also get script/code integration in geometry nodes, since it might help simplify setups like in Houdini. But, I'm a beginner in geometry nodes, so I'm not sure that this will be the case.


Smart navigation

Question: What is smart navigation in .NET?
Answer: SmartNavigation is a property of the Page class in System.Web.UI. When a request comes in to Internet Explorer 5.5 or higher and SmartNavigation is turned on (set to true), the following actions are performed:

The flash caused by navigation is eliminated
The scroll position is persisted when moving from page to page
Element focus is persisted between navigations
Only the last page state in the browser's history is retained

Here is a good article about it.
Warning It doesn't work on other browser than IE. Should not be used for public website.
Comment: Well, with IE when you go back, the speed is pretty fast. Otherwise, it's the same.
Answer: A feature of ASP.NET that allows a web page to do a postback and display new content without flickering or skipping back to the top of the page.
I don't see that it has much place now that AJAX exists.

Smart navigation


What is the best way to include Matlab graphics?

Question: Which way of exporting Matlab graphics delivers the best result for inclusion in LaTeX? Is it possible to export scalable vector graphics, or even LaTeX graphics?
Answer: In case the kind of graphics you wish to export is supported by matlab2tikz, there is only one way to go: matlab2tikz.
You get true vector graphics in TikZ, i.e., no fiddling with PostScript, being restricted to latex, no going back and redoing graphics when your font or color scheme changes, small changes in for instance the legend are done in-place, ...
Answer: Some updates on using plot2svg in MATLAB R2014b as of Mar 2015:
Jürg hasn't updated his awesome script for a while. For those of you who got an error while using plot2svg in R2014b, the simplest solution is just changing every str2num function in the original plot2svg to str2double, and problem solved.

(Original post)
matlab2tikz is the best vector graphics solution for small dataset graph as Pieter said in his answer. However, in some situations, using matlab2tikz to generate codes is not an efficient solution IMHO.
Here I will show two examples where using matlab2tikz to export the graphics is less than ideal a solution.

First is with a large dataset like in the following triangulated sphere:

matlab2tikz generated a tex file with 3k lines of codes and took minutes to compile for once.

Second is when there are lighting, alpha, and blur in Jürg Schwizer's blog post:

matlab2tikz's output gives me:

For these situations: either you have a large dataset like a complicated triangulation/flow fields, or you have options such aslighting, camproj,FaceAlpha, etc in your MATLAB codes, or other Axes/Patch/Quivergroup properties tweak. The best way to include these graphics is:

(Step 1)Use plot2svg in MATLAB to get an svg file.
(Step 2)Use Inkscape to convert it to eps or pdf
(Step 3)Use \includegraphics in graphicx package of any TeX-distributions to include eps or pdf

plot2svg is a small pkg in MATLAB to produce scalable vector graphics by Jürg Schwizer.
There is a large thread of How to include SVG diagrams in LaTeX? on TeX.SE, the step 2 is what is in the accepted answer, if you are using Linux, once you installed Inkscape, you could use these shell scripts to convert svg to pdf/eps/png file formats.(Beware: the sh in the link is using zsh shell)

Other advantages of using this approach to export MATLAB figures:

For scientific publications, most publishers are still using ancient TeX-distributions which doesn't include tikz pkg, for example: SIAM requires authors to use PostScript figures in the submission.

Inkscape has a UI for editting svg files also.
Comment: I can't describe how much this answer saved my ass, I'm exactly in the above situation. 10+ :)
Comment: @ShuhaoCao Thanks for your reply, I was asking to avoid testing myself (: I'm with matlab2tikz now but plan to use your approach for the next paper (just because changing something in inkscape does not involve 1.5 hour debugging sessions, like it does for me to fiddle with tikz output).
Comment: @Shuhao_Cao I see that MATLAB2015b can save figures directly to SVG. Does this render the plot2svg step redundant?
Comment: @HennadiiMadan Thanks for the heads up. I had several tests. MATLAB's own built-in output seems superior in the test case where I use LaTeX as renderer for texts. For the triangulated surface example, MATLAB generates a much bigger file though. Still for the bounding box, the output is not ideal for MATLAB's built-in version, you have to edit it in Inkscape for a better pdf output. I may update my answer later.
Answer: There are two Matlab packages for exporting graphs to EPS plus psfrag, which replaces the labels inside the figures with strings that are typeset by LaTeX. They are laprint and matlabfrag; I recommend the latter as it will work for more graphic types, and laprint is no longer supported.
The support for surface-plot output may well make this a better option than the tikz based converters, otherwise the quality will be largely the same.
To include these types of graphics into pdfLaTeX, use the pstool package.
Answer: There is a great library called pgfplots, which creates great looking plots directly in latex. This package is used by matlab2tikz.
You can write the data you want to plot in an ascii table, and create legends, axis labels and such directly in latex, very much like the code you would have written in Matlab anyway.
You can easily change the contents, colors (for example for B/W prints), width and heigh, resolution, and much more without having to recreate figures.
Comment: This is in fact the way I do it nowadays.
Answer: The print command in Octave allows several devices for LaTeX output: -dtex, -depslatex, -depslatexstandalone, -dpstex, and -dpslatex. Making plots using Octave, gnuplot, and LaTeX by  Marco De la Cruz-Heredia has some good examples.
The print command in Matlab can write to eps (see Elenaher's comment), so that is another option.
Comment: The print command in Matlab can write to [many output formats](http://www.mathworks.de/help/techdoc/ref/print.html#export_formats), including not only eps but also vector formats pdf, svg, emf and bitmap formats png, jpg
Answer: In MATLAB all labels and titles, you can use LaTeX interpreter to make your plot more professional.
% for
text(2,2,'$e^{2\log(x)}$','interpreter','latex','fontsize',18)

% for legend
s =  legend('$x^3$','$x^2$');
set(s,'interpreter','latex');

Then the best way to include MATLAB plots into your latex document you have to follow these steps

save a picture as eps files;
use epstopdf to convert eps to pdf, then you can use both formats.

You should not save picture in pdf format since the bounding box will be not correct.
Comment: Matlab will create cropped PDF graphics if you set the papersize correctly: http://tex.stackexchange.com/questions/5559/how-to-avoid-large-margins-around-matlab-plot-in-pdf/5562#5562
Comment: @Robertson I think eps and then epstopdf is better in any cases since you may need eps for latex and pdf for pdflatex.
Answer: If you want to have scalable results, the better way is maybe to use the vectorial format eps (encapsulated postscript) but you will have to compile with "classic" latex and not pdflatex.
I am pretty sure that matlab is able to generate eps.
Comment: Matlab can also create PDF.
Comment: I use the matlab command `print(gcf,'-deps2c',myfilename)` to print a figure to encapsulated postscript in color, which I then include with \includegraphics.  Couldn't be easier.  but it does require using latex and not pdflatex, as mentioned.  If you do this, the font sizes you specify in matlab for text on the graph will be maintained in the eps file.
Answer: you may also have a look at the export in pstricks : fig2tex together with the provided links.
Answer: I really like the print command. To avoid margin and text resizing problems: I like to take a lot of control when exporting my figures by pre-defining the margins and paper-size to be my desired figure size. This makes fonts size correctly, and lets you choose the margins you want.
First I define my figure width and height (these are in metric, but you can use US units also).
FigW=13.49414;
FigH=21.08462*.3;

Next, I set my figure properties. First I define the text interpreter to be latex, and then I set the paper size. You can define margins in the paper position parameter, but i prefer to do that later. if you want to use inches, that's fine here. Finally the 'Position' option just makes the figure on screen look identical to what will be printed to PDF. The first two parameters in 'Position' are the screen position and the second are the width and height of the figure.
Figure1=figure(1);clf;
    set(Figure1,'defaulttextinterpreter','latex',...
                'PaperUnits','centimeters','PaperSize',[FigW FigH],...
                'PaperPosition',[0,0,FigW,FigH],'Units','centimeters',...
                'Position',[1,10,FigW,FigH]);

I then use the subaxis package from the mathworks file exchange to take control of my margins, padding and spacing of all my subplots. For one plot this might look like:
subaxis(1,1,1,'Margin',.1);

Finally, I export to PDF using the print command in matlab:
print('-dpdf','-r500','filename.pdf')

Answer: The easiest way is to use export_fig that convert Matlab figures to PDF automatically with some nice and useful features.
For both advanced and enthusiastic Matlab users, the possible way is to run through 11 pages of recommendations in "How To Make Pretty Figures With Matlab" manual.
Comment: Notice that the author also warns for *Note that export_fig does not transparency in patch objects in vector formats. Only a transparent background is supported.*. In general MATLAB is not a good collaborator. Better practice is to take the data to gnuplot or other scientfic plotting platforms.


Search console can't detect structured data after adding through google tags

Question: Will adding them manually instead of using tag manager help. They all passed the validation test in the Google Structured Data testing tool. I have included two tags. One for implementing products rich card and another a Knowledge Graph Card
Answer: Tag manager writes in using the document.write() method.
Googlebot is learning to render a limited amount of Javascript before scraping the page - however, it's extremely sketchy. Tests have shown that you can add in things like  tags or json data using document.write(). However it's so unreliable that it's still better to insert them into the HTML you're sending the client.
Hopefully, some day soon, Google will render Javascript and we can stop using workarounds. Ask this again in a year or two and the answer might be better!


What's the link between optimization and classification?

Question: I am learning about machine learning and one of the things that still not clear in my mind is how classification is done via optimization? In the couple of papers I read I just don't get how authors manage to model their problems, how does minimizing a function lead to clustering or classification, how do they know they are dealing with the right function?
Answer: Optimization in classification tasks
I would suggest to start to check the 0-1 loss, which is the goal of the classification task. In other words, the objective of the classifier is trying to classify objects "correctly" / minimizing the wrong classifications or 0-1 loss.
In real world problems 0-1 loss is hard to optimize directly, therefore there are other loss functions to "approximate" 0-1 loss. (A related discussion can be found here: What are the impacts of choosing different loss functions in classification to approximate 0-1 loss) Logistic loss is one of them. And the classifier based on logistic loss is logistic regression.

Optimization in clustering tasks
The goal of clustering is putting objects into groups/clusters. But what grouping strategy is good? This is the essential question answered by the optimization formulation.
In generally, we want objects in one group are "similar" to each other and between groups are "different". The optimization objective is trying to "maximize" the similarity within groups and "maximize" the difference between groups.
Answer: There is another, in my mind more intuitive way, of thinking about it:

Optimization algorithms can be thought of as minimizing or maximizing an objective function.
They can also be thought of as search algorithms: They search through a large space of possible values for the the best set of values.

If you think of optimization as search, then the connection between optimization and classification becomes clear: You are faced with a large space of possible models (as described by their parameters: NNet weights, Regression coefficients, etc....), and your optimization algorithm searches for the best model amongst all possible models.
Answer: Once you model your classification problem as assigning probabilities to each class (so regressing to a probability distribution over the classes) you can use cross-entropy as a loss function that when minimizing will try to get the probabilities closer to the actual class and further away from the wrong classes. In that regard, classification becomes an optimization problem. Non-gradient based methods could use other objectives. Tree based methods could look for splits that increase the accuracy most, in that regard you are optimizing accuracy.


Wrapping flat artwork onto a sphere with no distortion to create a football

Question: Apologies if this is a very dumb question but I don't even use blender at all but I'm hoping it will be a solution to problem I keep coming across. I get asked to design footballs so I need the ability to design flat artwork to supply factories as well as render a 3D model for an accurate visual. I must have the ability to create different panel shapes too so that all footballs aren't simply the common 32 panel ball for example.
Is this all possible with blender?
Comment: It seems that you are searching for [UV unwrapping a mesh](http://blender.stackexchange.com/questions/38651/what-does-unwrapping-a-model-do-and-why-is-it-important) to map image onto 3d model.
Answer: Yes, you can model and texture a football in Blender with any shape you like.
The 32 panel standard ball is probably the easiest to accomplish, since there's a standard primitive (the Icosphere) that pretty much resembles it's shape.
Here is a tutorial explaining how to do it https://www.youtube.com/watch?v=AYC69tt-KMI
Other shapes can also be accomplished too, but it's process can be more or less involved depending on the complexity of the shape.
About texturing, as mentioned by Mr Zak what you need is probably UV Unwrapping, this can also be accomplished inside Blender. It is the process of "unfolding" or "flattening" an 3D geometry into a 2D shape so that an image texture can be mapped over it's surface as desired with minimal distortion.
Depending on how big your design is, or how much of the ball it covers unwrapping could be a very simple process. For a simple logo that sits only on a side of a ball a simple view-based direct projection could be enough. For designs that cover the whole ball it could be a more complex process.
Either way you could probably model a few different predefined football geometries with the most commonly used shapes, and unwrap them in the most convenient way to simplify the surface design. You could then use that UV layout as a template save it as an image or even export as vector using the SVG export addon (if you work on vector graphics design software) and reuse it whenever you need to design a ball for a specific geometry.
All you need to do then is import that layout into your graphic design application (Inkscape, GIMP, Photoshop, Illustrator, whatever) and draw over it so the parts of the design match the desired corresponding area in the ball surface.
The base 3D models can also be reused as asset libraries to easily render your designs whenever you need. You can even have a set of predefined files with your scene (grass, field, product studio, etc), material, and lighting setup all ready to render, and all you need to do is apply your new surface image texture to it and render your design. You only need to set it up once.


What steps do you need to take to translate UIPanGestureRecognizer touches to ScrollView zooming?

Question: I am creating a gesture recognizer to handle zooming in a scroll view (scrolls along only one on axis at a time). I have the gesture recognizer working but I'm having trouble using the data from the gesture recognizer to transform my views properly. This is what I do right now:
<code>- (void)handlePinch:(GPinchGestureRecognizer *)pinchRecognizer
{
 CGSize contentSize = [[self scrollView] contentSize];

 if (pinchRecognizer.pinchType == VerticalPinchZoomIn || pinchRecognizer.pinchType == VerticalPinchZoomOut)
 {

    [[self scrollView] containerView].transform = CGAffineTransformScale([pinchRecognizer transformBeforeTouches], 1, [pinchRecognizer scale]);
    [[self scrollView] setContentSize:CGSizeMake(contentSize.width, [pinchRecognizer initialContentSize].height * [pinchRecognizer scale])];
 }
 ...
 ...
}
</code>
This resizes the view nicely, however, it lets it get to strange positions on the screen, and sometimes the scroll view won't be able to scroll all the way to the edge of it (it thinks its boundary is in the middle of the view somewhere and bounces back).
So basically, my question is, what other properties of what other objects and whatnot do I need to operate on to get this working right? View.transform, ScrollView.contentSize, what else? If only Apple's UIScrollView implementation file was open source xD
Answer: U do need to add UIPinchGestureRecognizer or neither maintain it.
Just follow this link to add image in scrollview for zooming


Where can I find different stat potions in Realm if the Mad God? And of which can i find early on?

Question: Where can i find different stat pots from different bosses and dungeons. Please leave answers with difficulty of the dungeon/boss or god.
Comment: At this point, I would expect this information to be readily available with minimal searching.
Answer: Stat potions are consumable items that permanently increase a specific stat (like attack, defence or speed). They are not soul bound so they can be traded between players without any problem.
There are 8 different stat potions.
Most dungeon and event bosses are guaranteed to drop a stat potion, the drop locations I have noted below are the most common ways to get them. Most gods in the god lands have a low chance to drop stat potions, so another easy way to get pots is to farm in the god lands, I shall also note the gods in the god lands that drop stat potions.
These potions are:
Potion of Attack (+1 ATT) which drops from flying brains, white demons and in the manor of the immortals.
Potion of Defence (+1 DEF) which drops from Beholders, Leviathans, Ent gods, Slime gods, in the Abyss of demons and in the Mad Lab
Potion of Speed (+1 SPD) which drops from Medusa, Djins, Ghost gods, in the Snake Pit and in the Cemetery
Potion of Dexterity (+1 DEX) which drops from Sprite worlds and The Nest.
Potion of Vitality (+1 VIT) which drops from the Abyss of Demons, the Hermit God and in the Cemetery
Potion of Wisdom (+1 WIS) which drops from the Mad Lab, Undead Lair and in the Cemetery
The above potions can all be dropped by Oryx (1&2) and event bosses. The following stat pots can not be dropped by these bosses.
Potion of Life (+5 Max HP) which drops from the Tomb of the Ancients and the Shatters.
Potion of Mana (+5 Max MP) which drops from the Ocean Trench, the Crawling depths, the Shatters and the Ice Cave.
These are all the stat pots that are currently in the game, running dungeons or farming in god lands is the easiest way to get them, but trading with other players for items works as well.
For your first dungeons which can give you stat potions, I would advise the Sprite World and the Snake Pit, later on trying the Cemetery,  Mad Lab and Abyss of Demons are going to be fun and rewarding. I would stay away from the Ocean Trench, Tomb, Shatters, Crawling Depths and Ice Cave for the time being.
Source: My own experience from playing the game for a couple of years and the Realm of the Mad God wiki page
Comment: Please don't talk condescendingly to other users in your answers. I removed it this time and left the actual answer, but you may want to review the [Be Nice policy](https://meta.stackexchange.com/help/be-nice).
Comment: Also, link-only answers are discouraged, as links decay and die over time, so unless you've quoted from the source, your answer may become useless in the future. You should add relevant information from the link, perhaps a handful of stat potions from bosses that can be fought early on, as the asker seemed to be concerned with.
Comment: did any of your answer come directly from the wikia page you'd originally linked? You should probably still include that, either way, as a reference.
Comment: This is a much better answer, +1
Comment: For some reason it cut off the first part of my message, It is supposed to say: "Dear E-Potato,"   My apologies
Comment: Okay, thank you for correcting me. I will edit my answer and keep this in mind next time. I only joined the website a short time ago, so these comments really help!
Comment: Dear Vemonus, could you read/review my answer again? I would like to know if this is in accordance with the rules, so I can keep that in mind during my following reviews.
Comment: Thank you very much, your comments helped and I will keep them in mind for the future!


Laravel4 + Iron io: How to send mail using Mail::queue?

Question: I have a laravel app with a form that when it is submitted will send a mail.
The mail configuration is working properly since the mail is received.
But since the process was quite slow i decided to use Queue.
I have set up Iron mq account and set it up on Laravel4.
So instead of Mail::send i switch to Mail::queue. Here is the code:
      return \Mail::queue($this->view, $this->data, function($message) use($self)
    {
        $message->to($self->email, $self->to)->subject($self->subject);
    });

And in the routes there is simply:
  Route::post('booking', 'HomeController@booking');
  Route::post('rezervesana', 'HomeController@booking'); // This is for the latvian version

When i submit the form, the queue is received in Iron mq dashboard and apparently fired.
But no mail is received..
If instead i do something like this:
  Route::post('booking', function()
  {
        return Queue::marshal();
  });

Then magically it will work in the latvian version (rezervesana) but of course than the english version page does not even open anymore..
So I am quite confused.
The question is: How can I send properly a mail using Mail::queue and how to deal with it in the routes?
I think that the code regarding the Mail::queue is correct, what is wrong can be in routes.
So the real question can be: How I have to set up the routes to make queue working properly?
Which is the proper place for Queue::marshal?
Thank you guys!
Sorry if it is confused.
Hope you can clarify it to me!
Answer: I've used SQS before but not Iron, maybe you should use this?
Route::post('booking', array('before'=>'csrf', 'uses'=>'HomeController@booking'));