What are some optimized LAMP or LEMP stack scripts with email?

Question: In the "let's try not to reinvent the wheel" perspective, I've been looking for a packaged LAMP (or LEMP) stack for some time now, not only the basic Mysql, Apache , PHP etc... but ideally stuff like APC, Postfix... basically something that would implement recognized practices & standard for security, general performance. A standard default installation that would work out of the box with all the bells & whistles that one would need to get started.
It's usually fairly easy to find the basic configurations with Apache, Mysql, PHP etc... but surprisingly difficult to find anything that goes a step further.
The Mercury Project seems to have been absorbed by the Pantheon Project and it looks like it's not supported anymore, looking at the comments on the group's page, the install script seems out of date. There's also the BOA project that sounds excellent but goes way beyond what I'm looking for.
Linode.com has a few stackscripts but the LAMP stack doesn't implement a mailing solution ( I'm looking here for the basic notifications from the server )
And there's of course WHM/CPanel, but I've never been a fan and I'm not looking for a control panel.
Have I missed something?
Drupal optimization is a plus but not a deal breaker.
Answer: There are installer scripts that exist for web applications and supporting services, but most of them to my knowledge are focused on the web hosting world. For example Scriptaculous and Fantastico, to name just two.
There are also pre-baked virtual appliances made by places like JumpBox, BitNami, CloudZoom, and Turnkey Linux. Those can be variously deployed to cloud providers and be up and running in mere minutes.
Perhaps you could start with some of those projects and move forward, developing something more to your own tastes.
...but, wait...
If after reading all of the above you're left thinking "But wait, that's not exactly what I want" that's because what you want doesn't exactly exist yet. It appears that you want something that's more specific than a generic install script (Fantastico, etc.) but not quite as heavy a a drop-in virtual appliance.
I'm sure that something closer to what you want exists. For myself, there was a time when I was working on Wordpress installations a lot and had a fancy idea to create a spectacular installation script that went an extra mile or five to lock down permissions, edit directory structures and generally clean up after the installation to make things smarter, tidier and much more secure for the Linux OS, the MySQL database server, Apache and any caching / proxies involved.
I'm sure I'm not the only one that had an idea like that, so there was likely someone who had a custom Wordpress install script that I could have used or at least learned from and mutated to my own desires. I could have turned it into quite the github project, I think.
What I'm saying is that you'll really need to get down to the grass roots level of some kind of LAMP community that focuses on the needs of those who rapidly deploy multiple servers in the use-cases that you focus on. More than likely you'll be laying down a lot of your own pipe. You'll probably want to get some core group of contributors to help you. Make it a full on FOSS project.
Then you'll be known as That Amazing FOSS Guy and you'll never lack for roses at your feet! Or, something like that...
Comment: Thanks for a detailed & fun answer! I'll have to do without the roses at my feet though as I'm nowhere near ready to undertake such a project. You're right though, nothing fits the bill. I've had a good look at the options you mentioned. Bitnami's pretty close but I'm not confident about the upgrading process. TurnkeyLinux looks great for local development or Amazon deployment, but installing it on Linode is not so straightforward. Looks like I'll have to dig deeper and get my hands dirty :)
Answer: Wow, so updating this thread from 2012 is interesting — this page still shows up in search results for LEMP stack scripts for WordPress, and beyond.
These days we now have things like Docker containers, a growing PHP Composer (Packagist) ecosystem, plus several new cloud providers with built-in setup scripts for LAMP and LEMP.
That said, there is still (and I would argue, always will be) value in lightweight Bash oriented scripts to setup niche server stacks, because:

Security: the less bloat, the better security (and less maintenance)
Performance: the less bloat, the faster the speed (and less items that need optimization, etc)
Transferable: the less bloat, the easier to duplicate or migrate the build process
Usability: the less bloat, the easier the learning curve
Etc. (probably some other benefits too)

Remember: There's one thing installed on every single Unix machine in the world: the Shell :)

While there are dozens if not hundreds of basic scripts on GitHub and elsewhere, there are really only a handful of server deployment/provisioning scripts that are actively maintained, e.g.:

SlickStack — Ubuntu + LEMP + WordPress + MU Plugins + CloudFlare (Note: I'm the author)
CentminMod — CentOS + LEMP + tons of different options and add-ons
EasyEngine — Ubuntu + Docker + LEMP + WordPress
WordOps — fork of EasyEngine v3 (no Docker)
Webinoly — inspired by EasyEngine v3 but includes some non-WordPress options
VPSSIM — kinda like CentminMod but from Vietnam (Docs are limited)
HocVPS — also kinda like CentminMod and also from Vietnam


Why should you use propensity score matching?

Question: I have a question about propensity score matching and how it is used in analyzing non-randomized datasets. I understand how it is performed (I think!), but not why I should use it and not something else. Let me illustrate what I mean with an example.
Assume I have a dataset with a treatment (x, binary variable), an outcome (y, numeric) and one covariate (z, numeric). The task is to determine the effect of the treatment (x) on the output (y). Treatment was however not randomly administered, so we need to take the covariate (z) into account. A real world example would be y=sick days per year, x=some drug and z=age.
If I understand correctly, this is how you (can) go about if you apply propensity score matching:

Predict treatment x from the covariate z, e.g. using logistic regression
Group patients based on this predicted probability of treatment = propensity score
For each propensity score group, calculate the average outcome (y) for patients with the treatment (x=1) and without the treatment (x=0)
For each propensity score group, calculate the difference between x=1 and x=0 averages above and then average all those differences (maybe using some weighting scheme)
The average difference is the treatment effect

Please let me know if I got this part wrong!
Another alternative, not involving propensity score at all, would be like this:

Predict the outcome (y) from the covariate AND the treatment (x), e.g. using logistic regression
Study the size, sign of the coefficient in front of x, and also check if it is statistically significant
Done!

Will the two methods give me the same result (probably not)? If not, which one is preferred and why? Does it differ if I have more than one treatment or covariate?
I'd be very happy if you could find the time to help me with this one. And please keep in mind that I'm just a simple engineer, so please limit the number of difficult statistical words and formulas :-)
Comment: The first approach sounds like *stratification on propensity score*, not *matching*.
Comment: See also [Why match if you have the control data already?](https://stats.stackexchange.com/questions/455567/why-match-if-you-have-the-control-data-already/455585#455585), [Does normal linear regression in R overcome confounding?](https://stats.stackexchange.com/questions/432700/does-normal-linear-regression-in-r-overcome-confounding).
Answer: Let's suppose we could simply observe the joint distribution of $\Pr(Y,X,Z)$. We don't have to estimate anything. We can calculate anything we want from this joint distribution.
Our assumptions about how the outcome is determined (a causal model) say the treatment effect, $E[Y_{X=1} - Y_{X=0}]$ isn't equal to $E[Y|X=1] - E[Y|X=0]$. There's a confounding variable, $Z$, that contaminates the association of $Y$ and $X$ so that it doesn't just reflect $X$ affecting the value of $Y$.
But it also says that $E[Y_{X=1} - Y_{X=0}|Z=z]$, the treatment effect for units where $Z$ equals $z$, equals $E[Y|X=1, Z=z] - E[Y|X=0, Z=z]$. If we look at units where $Z$ is held constant, the association between $X$ and $Y$ does come about because $X$ affects $Y$.
So, what we want to do is calculate $E[Y|X=1, Z=z] - E[Y|X=0, Z=z]$. One thing that is annoying is that the treatment effect can vary with $z$ now. We need to either consider many different treatment effects, one corresponding to every value taken by $Z$, or average them with $\Pr(Z)$.
Now let's return to reality. We can't observe $\Pr(Y,X,Z)$, we have to estimate it. And typically, we estimate the conditional expectations directly, with regressions. Your alternative does exactly that. The average marginal effect of your logistic regression is an estimate of $\sum_z (E[Y|X=1, Z=z] - E[Y|X=0, Z=z]) \Pr(Z=z)$ where $E[Y|X=x, Z=z]$ is modelled as $\frac{1}{1 + \exp{(-\alpha - \beta x - \gamma z)}}$ and $\Pr(Z=z)$ as the frequency with which $Z=z$ occurs in your sample.
Propensity scores matching is primarily a way of controlling for $Z$ (conditioning on it in the regression) when $Z$ has many components. It turns out that conditioning on the propensity score $p(Z)$, a scalar, is as good, for some purposes, as conditioning on $Z$ even when it's a vector. It's as good for rendering the potential outcomes $Y_{X=1}$ and $Y_{X=0}$ independent from $X$ when conditioning on it. This is why propensity scores work.
Long story short: Yes, the two approaches should give similar results And if $Z$ is one-dimensional, there is, as far as I know, no reason to use propensity scores. You can easily use $Z$ directly. Even if $Z$ has many components, you can just all add them to a regression and this is a still a more widely used control strategy than propensity scores.
Comment: Thanks. Not sure I got all the statistics behind it, but at least I understand that I won't be too wrong if I use a regression on both Z and X (which I understand) instead of propensity scores (which I still don't fully).
Comment: If it's causality you want, the most important question is whether controlling for $Z$ is enough. Whether, once you've controlled for that, there is no other reason why $Y$ and $X$ might be correlated, except because $X$ affects $Y$. This has nothing to do with statistics, and everything to do with what you know about these variables, If yes, the regression on Z and X will generally give you a good idea of the effect of X. Even plain OLS, no logit.


Adding extra details to a webapi bearer token

Question: I am trying to learn the new webapi2.1 authentication pieces.
I have got the bearer token wired up and working with my webapi. My next thing I would like to do is be able to store some additional information within the token (if possible) so when the client sends back the token I can retrieve the details without the need of them sending multiple values.
Can the token be extended to contain custom data?
Sorry if the question is a little vague but I have had a big hunt around and can't seem to find any further information
Thank you
Answer: Since the token is signed with a "secret" key - only the issuer can add data to it.
You can amend something to the claim set after receiving the token in your Web API - this is called claims transformation.
I have a sample of it here:
https://github.com/thinktecture/Thinktecture.IdentityModel/tree/master/samples/OWIN/AuthenticationTansformation
In essence you are writing some code that inspects the incoming token and add application specific claims to the resulting principal.
<code>    // Transform claims to application identity
    app.UseClaimsTransformation(TransformClaims);

    private Task<ClaimsPrincipal> TransformClaims(ClaimsPrincipal incoming)
    {
        if (!incoming.Identity.IsAuthenticated)
        {
            return Task.FromResult<ClaimsPrincipal>(incoming);
        }

        // Parse incoming claims - create new principal with app claims
        var claims = new List<Claim>
        {
            new Claim(ClaimTypes.Role, "foo"),
            new Claim(ClaimTypes.Role, "bar")
        };

        var nameId = incoming.FindFirst(ClaimTypes.NameIdentifier);
        if (nameId != null)
        {
            claims.Add(nameId);
        }

        var thumbprint = incoming.FindFirst(ClaimTypes.Thumbprint);
        if (thumbprint != null)
        {
            claims.Add(thumbprint);
        }

        var id = new ClaimsIdentity("Application");
        id.AddClaims(claims);

        return Task.FromResult<ClaimsPrincipal>(new ClaimsPrincipal(id));
    }
</code>
Comment: Thank you for your explanation. I have taken your example and added it to my project however it doesnt know about app.UseClaimsTransformation(TransformClaims); UseClaimsTransformation - What namespace is this in?
Comment: Sorry I didnt have the thinktecture packages referenced
Comment: Ahh Sorry one last question. Instead of having static data that is inserted for every claim is it possible to add custom claim values for each request? I have an application that contains businesses and I would like to store the persons businessId as a claim
Comment: Yes absolutely - the idea is that you analyze the incoming identity and create a new identity that contains the app/business specific claims.
Comment: i know this is almost a year old, but I have to do something similar - however not at app startup.  When user logs in, they are taken to a page to select a "tenant" in a dropdown.  I want that tenant ID to be saved in the bearer token as a claim...but at this point the token has been created. Is this possible?


Swift - Handling custom checkmark button state on multiple sections of tableview

Question: I have a tableview with multiple sections each section is having 3 cells , each cell contains the custom check mark button. Where user can change check and uncheck images of check button on click.
The problem is, i am changing the cell button image from uncheck to check when user click on button which is working fine. If i scroll the tableview that check mark image is adding to wrong cell.
I googled it and found the solution like saving clicked cell indexPath.row in array and removing from array if user click again on same cell.
It is not working as i have multiple sections.
Please provide me any suggestion to find out the solution for my problem.
// Button action.

func buttonTappedOnCell(cell: customeCell) {
        let indexPath : IndexPath = self.tableView.indexPath(for: cell)!

        if self.selectedIndexPath.count > 0 {

        for  selectedIndex in self.selectedIndexPath {

            if selectedIndex as! IndexPath == indexPath {

                self.selectedIndexPath.remove(indexPath)
            } else {

                self.selectedIndexPath.add(indexPath)
            }
        }
        } else {
            self.selectedIndexPath.add(indexPath)
    }

Code in cellForRowAtIndexPath
    for anIndex  in self.selectedIndexPath {

        if anIndex as! IndexPath == indexPath {
            cell.checkMarkButton.setBackgroundImage(UIImage(named: "checkMark"), for: .normal)
        } else {
            cell.checkMarkButton.setBackgroundImage(UIImage(named: "UnCheckMark"), for: .normal)
        }
    }

Comment: Maybe use Eureka forms?
Comment: can you show your code where you set property in table for your custom cell
Comment: You will need to save the `indexPath` in the array rather than just the row (or even better, use a `Set` rather than an array)
Comment: @LazyCoder check the use of this method in table custom class-: http://stackoverflow.com/questions/9362713/how-to-use-prepareforreuse-method
Comment: @Paulw11 updated the question with code and i am already doing as you suggested. But still i am facing problem
Comment: @LazyCoder I have similar problem. Try set properties in method with `willdisplaycell`.
Comment: @AdrianBobrowski accepted answer is working fine for me
Answer: You can simplify your code greatly by using a Set<IndexPath>.  There is no need to loop through an array.
var selectedPaths=Set<IndexPath>()

func buttonTappedOnCell(cell: customeCell) {

   if let indexPath = self.tableView.indexPath(for: cell) {
       var image = UIImage(named: "CheckMark")
       if self.selectedPaths.contains(indexPath) {
           image = UIImage(named: "UnCheckMark")
           self.selectedPaths.remove(indexPath)
       } else {
           self.selectedPaths.insert(indexPath)
       }

       cell.checkMarkButton.setBackgroundImage(image, for: .normal)
   }
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "identifier", for: indexPath) as! YourCellType

    ...

    var image = UIImage(named: "UnCheckMark")
    if self.selectedPaths.contains(indexPath) {
       image = UIImage(named: "checkMark")
    }

    cell.checkMarkButton.setBackgroundImage(image, for: .normal)

    return cell
}

Comment: Sorry, that was a typo.  There is no need for a downcast there.
Comment: Thanks for your quick reply. It is working great and need small correction to your answer where need to change image name from checkMark to UnCheckMark in the following if condition.if self.selectedPaths.contains(indexPath) {  Because if NSSet contains indexPath we need to Uncheck the checkmark
Comment: Sorry. I got that the wrong way around. I'll update it.
Comment: @objc func checkBoxTapped(cell : CheckboxCell){
        if let indexPath = self.tableView.indexPath(for: cell) as CheckboxCell{}} // cannot convert value of type indexpath to type checkboxcell in coercion error, any idea?
Comment: `indexPath(for:)` returns an `IndexPath` not a `UITableViewCell` so your downcast is invalid.
Comment: YourCellType this means? Can you please update the code?
Comment: indexPath always returns nil. Any idea?
Comment: You should ask your own question, including relevant code
Answer: This happens because the cells of a tableView are reused to minimise memory usage.
If you are using a custom implementation of check button then you have to store the values for the cell which is selected in a data Structure like an array for example if you have 2 sections with 3 elements in each section with 2nd item in 1st section selected, then the data structure like an array can be like [[false, true, false], [false, false. false]].
Here I am setting true in case the cell is selected. Update the values of this data structure and check from it when applying the image in the cellForRowAt and apply the checkedImage only when the indexPath.section and indexPath.row for Array return a true Bool.
Hope this helps. Feel free to reach out in case of any doubts. Happy coding.
Comment: Ibrhim thanks for your suggestion and paulw11 answer working fine too
Answer: inside of your TableView DidSelect method just put
let cell = tableView.cellForRowAtIndex(indexPath).accessoryType = UITableViewCell.accessoryType = Checkmark

vice versa for DidDeselect method but change the Checkmark into None.
let cell = tableView.cellForRowAtIndex(indexPath).accessoryType = UITableViewCell.accessoryType = None

If you create more complex code for a simple method, It'll give you disaster.


Probability of getting an odd number of balls

Question: We have $n$ balls such that $k \ge 1$ of them are black and the rest are white. Consider the following procedure:
We first put all the balls in the bucket $B_0$. Then, we select each one of them with probability $1/2$ and put the selected ones in $B_1$. Next, we select each ball in $B_1$ with probability $1/2$ and put the selected ones in $B_2$. We continue doing that for $\Theta(\log{n})$ iterations.
What is the probability that at least one of these buckets contains an odd number of black balls?
Well, if $k$ is odd then it is easy to see that the probability is $1$, but how can we analyze this when $k$ is even?
Comment: The white balls seem to be totally irrelevant for the problem. Are you sure you got this right?
Answer: I will use the term round $i$ to describe the move to bucket $B_i$. Note that the probability of moving even number of black balls during any round is $\frac{1}{2}$ since you can move the first $x-1$ balls randomly and then pick the last one to fix the parity. Also, note that if you have even number of balls in all $B_{k}$ up to $i$ and you move even number from $B_{i}$ to $B_{i+1}$ you are ok. That happens with probability $\frac{1}{2}^i$.
So, the final answer is $1 - \frac{1}{2}^{\Theta (\text{log}n)}$
Comment: Is $1/2^{\Theta(\log{n})}$ the probability that all the buckets contain an even number of black balls or the probability that at least one of them contains an odd number?
Comment: "except if the bucket is empty" Better said: "except if there are no black balls in the bucket"
Comment: @arm46 You are right. I forgot to complement. I will edit. Thanks.
Comment: " the probability of moving even number of black balls during any round is $\frac12$" ... except if the bucket is empty.
Comment: @leonbloy You are right. I missed this. I silently assumed that there are only black balls since we have zero interest in the white ones. If $k = O(n)$ the result holds, I think. When $k$ is smaller, my guess is $1- \frac{1}{2}^{\Theta (\text{log} m)}$ but more work is required. Again, nice spot.


Ruby on Rails v5.1.1 Home Page

Question: I'm starting to develop in RoR and I have found the following problem:
Message
The command prompt:
Started GET "/pages/inicio" for 127.0.0.1 at 2017-06-22 22:43:24 -0300
Processing by PagesController#inicio as HTML
  Rendering pages/inicio.html.erb within layouts/application
  Rendered pages/inicio.html.erb within layouts/application (0.5ms)
Completed 500 Internal Server Error in 844ms

ActionView::Template::Error ():
    4:     <title>Pmo</title>
    5:     <%= csrf_meta_tags %>
    6:
    7:     <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track': 'reload' %>
    8:     <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
    9:
   10:
(execjs):1

app/views/layouts/application.html.erb:7:in app_views_layouts_application_html_erb__652431424_78968160'

The application.html.erb file is this.
The controller was generated in the following way:
rails g controller Pages inicio

Environment:

Windows 10
Nodejs v8.1.2
Rails v5.1.1
Ruby v2.3.3

Thanks in advance.
Comment: try https://stackoverflow.com/questions/12520456/execjsruntimeerror-on-windows-trying-to-follow-rubytutorial
Answer: per your error message, it looks like stylesheet problem (line 7) from your application layout, please check your stylesheets /app/assets/stylesheets/ make user your settings in application.css is correct
Comment: The application.css file contains the following code: `*= require_tree .
 *= require_self
 */
`
Comment: since you using windows, have you install node.js , if not then you can download and install from https://nodejs.org/en/download/

Ruby on Rails v5.1.1 Home Page


Asp .net Forms Authentication token using pure javascript

Question: How can I do something like this:
<code>Request.Cookies[FormsAuthentication.FormsCookieName].Value
</code>
in javascript?
Answer: You cannot do something like this in javascript. Authentication cookies are marked with the HttpOnly flag when emitted by ASP.NET meaning that client scripts cannot access them (and of course that's for security reasons). If there was not this HttpOnly flag you could access cookies in javascript using the document.cookie variable but as I said this doesn't apply for authentication cookies (they won't be part of it).


Combinatorics: Number of Integer Solutions for $x_1 + x_2 + x_3 + x_4 + x_5 + x_6 < 56$?

Question: Number of integer solutions for  $x_1 + x_2 + x_3 + x_4 + x_5 + x_6 < 56$ where:
a) $x_i \geq  0$, for $1 \leq i \leq 6$
b) $x_i \geq  -2$, for $1 \leq i \leq 6$
For part (a) the answer I got is $C(60,6) = 50,063,860$. Is this correct? I'm not sure how to do (b).
Comment: For (b), define $y_i=x_i+2$, then substitute. Note that $y_i \geq 0$.
Answer: Alternatively, for Part (a), let $$x_7:=55-x_1-x_2-x_3-x_4-x_5-x_6\,.$$  Therefore, we are to solve for $(x_1,x_2,\ldots,x_7)\in\mathbb{Z}_{\geq 0}^7$ from the equation
$$x_1+x_2+\ldots+x_7=55\,.$$
There are, by the star-and-bar method,
$$\binom{55+7-1}{7-1}=55525372$$
solutions, as confirmed by Anurag A.
For Part (b), with the substitution $y_i:=x_i+2$ and $$y_7:=67-y_1-y_2-y_3-y_4-y_5-y_6\,,$$
we are to solve for $\left(y_1,y_2,\ldots,y_7\right)\in\mathbb{Z}_{\geq 0}^7$ from the equation
$$y_1+y_2+\ldots+y_7=67\,.$$
As before, there are
$$\binom{67+7-1}{7-1}=170230452$$
solutions.
Answer: For (a). solutions to the inequality $x_1 + x_2 + x_3 + x_4 + x_5 + x_6 < 56$ are the union of the solution set of ALL of the following equations.
$$x_1 + x_2 + x_3 + x_4 + x_5 + x_6 = k \quad \text{ where } k \in \{0,1,2, \ldots ,55\}.$$
For a given $k$, the number of solutions are given by
$$\binom{k+6-1}{6-1}=\binom{k+5}{5}.$$
So the total number of solutions for the inequality will be
$$\sum_{k=0}^{55}\binom{k+5}{5}=\color{blue}{55525372}.$$
For (b), define $y_i=x_i+2$, then substitute. Note that $y_i \geq 0$. Now use the method of (a).


is it necessarily true that the map on $\pi_1$ induced by f is onto?

Question: This is a qual question and I have no idea how to begin.  Help is much appreciated.
Let $X$ and $Y$ be path connected spaces, and let $f : X \rightarrow Y$ be a continuous map. The mapping cone $Cf$ of $f$ is defined to be the quotient space of $Y \coprod (X \times [0, 1])$ obtained by identifying each point $(x,0), x \in X,$ with the point $f(x) \in Y,$ and identifying all points $(x,1)$ to a single point . If $\pi_1(Cf)$ is trivial, is it necessarily true that the map on $\pi_1$ induced by f is onto? Prove or give a counterexample.
Comment: How might Van Kampen's theorem help you here?
Answer: I'll add some more detail to the above hint: $Cf$ can be formed by gluing the cone $CX=C(\mbox{Id}_X)$ to the 'mapping cylinder' $M_f$ which is equal to the quotient of $Y\sqcup (X\times[0,1])$ by identifying $(x,0)$ for $x\in X$ with $f(x)\in Y$. Note that $C X$ is contractible, and $M_f$ deformation retracts onto the natural subspace $Y$.
We glue these two space together on their respective embedded copies of $X$ in the natural way and so their intersection as subspace of $C_f$ is $X$. If we take a small open 'thickening' of these subspace of $Cf$ we can apply Van Kampen's theorem because the necessary spaces are path-connected and open. I'll leave the conclusion to you.


Find dw in terms of all the variables: $\frac{1}{w} = \frac{1}{t} + \frac{1}{u} + \frac{1}{v}$

Question: So I understand how to find the differential of an explicit function $w = w(t,u,v): dw = \frac{\partial w}{\partial t}dt + \frac{\partial w}{\partial u}du + \frac{\partial w}{\partial v}dv$. How do I find it for implicitly defined functions?
As a side note, I know $dw \neq \Delta w$; instead, I view dw as the limit of $\Delta w$ when the independent variables, $dt = \Delta t, du = \Delta u, dv = \Delta v$ tend to zero. This is correct, right?
Comment: $$d\left(\frac{1}{w}\right) = -\frac{dw}{w^2}$$ Substitute for $w$ and isolated $dw$. This technique will work for all invertible implicit functions.
Answer: Do $w=\left(\frac{1}{t}+\frac{1}{u}+\frac{1}{v}\right)^{-1}$, then
$$dw=\frac{\partial\left(\frac{1}{t}+\frac{1}{u}+\frac{1}{v}\right)^{-1}}{\partial t}dt+\frac{\partial\left(\frac{1}{t}+\frac{1}{u}+\frac{1}{v}\right)^{-1}}{\partial u}du+\frac{\partial\left(\frac{1}{t}+\frac{1}{u}+\frac{1}{v}\right)^{-1}}{\partial v}dv.$$
Comment: you can make explicit for the other variables for example $$t=\left(\frac{1}{w}-\frac{1}{u}-\frac{1}{v}\right)^{-1},$$ and do the same for $dt$


Solving a system of equations with 3 unknows

Question: <code>X/Y = 5
X/Z = 2.5
Y/Z = 0.5
</code>
I don't want to check if this system is correct, but rather get actual values of X, Y, Z which could actually fit into this.
From my head I can think of examples like x= 5, y = 1, z = 2 and 50, 10, 20 would work as well here.
But what would be a formula to actually get numbers which would fit as x, y, z. DOesn't matter if its 5, 1, 2 or 50, 10, 20.
Any ideas?
Comment: Your example doesn't work. Have you tried multiplying each side of each equation by something to get rid of the fractions?
Comment: Just multiply the first equation by Y and the second and third by Z to get a linear system with the same solutions as long as Y and Z are not zero. I'm assuming you now how to sole linear systems?
Comment: No, I dont. What does this give me?
X = 5Y
X = 2.5Z
Y = 0.5Z
Answer: I suggest converting your system of equations into a 3 by 4 matrix and using Gaussian elimination (google it to find out how). You find that your system has an infinite number of solutions (one for each value of z), with $y = \frac{2z}{5}$ and $x = 5y = 2z$.
Comment: Thanks. I found out what I wanted.
Comment: No probs @raimis


is it possible to "group by" data in an SSRS tablix?

Question: I have a dataset that returns information on an individual - such as name - and all of the appointments that individual has.  I want to display two tablix (tablixes? tablii?) on my report - one that lists the individual sand another that lists the individuals and their appointments.
The only way I can seem to figure to do this is two separate datasets, but that just seems silly to me.  Plus the dataset takes a while to refresh, so it would double my query time.
Is there some way to get this individual list by using some sort of group by/distinct method that is eluding me?
Thanks!
Answer: Use the same dataset, and set it up tablix one with just the "individual" field and then the second tablix would be "individual" by "appointment":


Does dojo have deep mixin like jQuery.extend?

Question: I know jQuery has deep mixin such as
<code>var options = $.extend(true,target,object1,object2)
</code>
,does dojo have?if have how to use?if not how can i get the same functionality?thanks!
Answer: They have "lang.mixin" (http://livedocs.dojotoolkit.org/dojo/_base/lang#mixin), but it's not truly equivalent.
The following thread has more info:
http://dojo-toolkit.33424.n3.nabble.com/Deep-dojo-mixin-td3986157.html
And Ken Benjamin took the time to write this:
<code>    mixinDeep: function(dest, source) {
     //Recursively mix the properties of two objects
     var empty = {};
     for (var name in source) {
          if(!(name in dest) || (dest[name] !== source[name] && (!(name in empty) || empty[name] !== source[name]))){
               try {
                    if ( source[name].constructor==Object ) {
                         dest[name] = this.mixinDeep(dest[name], source[name]);
                    } else {
                         dest[name] = source[name];
                    };
               } catch(e) {
                    // Property in destination object not set. Create it and set its value.
                    dest[name] = source[name];
               };
          };
     }
     return dest;
}
</code>
However, it has some limitations with Arrays.
Answer: I recently had this same issue and decided to create Jake, which is just a small file porting over jQuery functions that Dojo doesn't offer.  So, now I can use this with my Dojo app (and in any other situation where I can't use jQuery).
Feel free to use it to drop in your project.
It currently supports:

extend
each
offset


How to implement this bubble piechart?

Question: I need to implement this:

Honestly I don't have any idea how to google this. I'm looking for a Vue/Nuxt solution or any hints in general on how to implement this.
EDIT: Sorry for bad question i guess. I was not asking for tutorial on how to do circle. I needed to do different charts using API. For anyone else looking for this i found Bubble Cloud Chart in vue-graph
Comment: In css, border-style: 1px solid black; border-radius:50%; width:100px; height:100px; something like this
Comment: Unfortunately, SO is not a how-to/place to ask for tutorials. You may need to look for graph/chart libraries. Try some words like that in your favorite search engine.
Answer: Using simple CSS:

#pie {
  width: 100px;
  height: 100px;

  border: 1px solid rgba(0,0,0,0.1);
  border-radius: 50%;
  background-color: #F3F3F4;

  /* Center text */
  display: flex;
  justify-content: center;
  align-items: center;
}

32%

Comment: Even if I totally agree with the answer, IMO the OP wants something simple to use where he could provide an array with some values and get the whole size/position done and not code something by himself.

How to implement this bubble piechart?


Can I use the mean value property for a function that is harmonic on only the interior of a ball?

Question: Let $f$ be a continuous function on the closure of $U$ where $U=\{ (x,y) \in \mathbb{R}^2 : x^2+y^2<1 \}$ and harmonic on $U$,  If $$f(x,y)=x^2y^2 $$ on $\partial U$ I want to find $f(0,0)$.
Now I could of course solve the Laplace equation on the disk and then calculate the value at the origin, but I was wondering if I could apply the mean value property.
Now the mean value property holds if the function is harmonic on the closure of $U$, but here it is harmonic on only the interior, but I  actually tried to compute the mean value and I got the same value that I got when I solved the Laplace equation on the disk and calculated the value at the origin, so I am guessing that the mean value property must hold.
Perhaps the fact that $f$ is continuous on the closure is helpful.
My question is, can I use the mean value property in this case?
Answer: The mean value property holds for any disk of radius $1-\varepsilon$ with $\varepsilon$ as close to zero as you want. Observe that all those means over the boundaries are equal, independent of $\varepsilon$, since all of them are $f(0,0)$. By (uniform) continuity, the limit of the integrals over circumferences of radius $1-\varepsilon$ is equal to the integral over the circumference of radius $1$, so the property holds.


Does SQL know to "cache" values, or seond query will cross the entire pipeline?

Question: UPDATE [User] SET SellerRating = SellerRating + {0} WHERE Id='{1}';
 SELECT SellerRating FROM [User] WHERE Id='{1}'", rating, toUserId);
When using an SQLCommand object to Execute scalar on the above query,
does SQL Server knows he have the value for the second query in it's hand ?
or will it start searching the index again?
and how can it know?
Thank you for your time
Answer: Database operations are independent of one another, so no, SQL Server doesn't consider the fact that you have two queries involving the same row(s).
Also, you need to parameterize your queries.
Answer: In fact, just to be clear, the return for the SELECT may not be the same as the rows updated in the UPDATE statement.
Between the two statements, another transaction may update, insert, or delete rows in the table.  As a general approach, SQL has to evaluate the second SELECT to take such changes in the data into account.
Of course, there are caveats, which are database- and configuration- specific.  These statements could be inside a transaction that has write locks on the table, for instance.  But, in general, the second statement has to be evaluated.
What does change, though, is that the data touched by the UPDATE statement may still be in the page cache.  If so, then the SELECT should run very quickly, since there would be no cache misses.
Answer:
does SQL Server knows he have the value for the second query in it's
  hand ? or will it start searching the index again?

Pretty much any respectable database in the world would 1) search again and 2) find the rows in the cache. So the the answer is  Yes to both questions. I think you're missing an important piece of knowledge and you must read about buffer pool and how it works.
Comment: thanks, i am kinda new to the SQL  Database World.
i will take a read.


Web service with Entity framework connection

Question: I have created a web site in C# 2010 with Entity framework, in the same i have also added one web service and deployed the same on server.
Now my web site is working good ,but when i open web service the asmx page will open up but the method which require database connection is not working.
I have used project dll in my web service for connection.
Now every time when i run web service method which connect to database it show me the message PAGE NOT FOUND.
Please suggest
Exception details:

System.Data.EntityException: The underlying provider failed on Open.
  ---> System.Data.SqlClient.SqlException: A network-related or instance-specific error occurred while establishing a connection to
  SQL Server. The server was not found or was not accessible. Verify
  that the instance name is correct and that SQL Server is configured to
  allow remote connections. (provider: Named Pipes Provider, error: 40 -
  Could not open a connection to SQL Server)
Comment: System.Data.EntityException: The underlying provider failed on Open. ---> System.Data.SqlClient.SqlException: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)
Answer: The web.config file needs the connection string for the Model, plus some bits and pieces. Make sure that it contains the following, and change the connection string to have your own server, database, and authentication details:
  <configSections>

  </configSections>

  <connectionStrings>
   <add name="YourModelNameHere" connectionString="metadata=res://*/RCMarketModel.csdl|res://*/YourModelNameHere.ssdl|res://*/YourModelNameHere.msl;provider=System.Data.SqlClient;provider connection string="Server=Your Server Name;Database=Your Database Name;Integrated Security=SSPI;Trusted_Connection=False;Encrypt=True;Connection Timeout=30;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
  </connectionStrings>

  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="v11.0" />
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>

These are probably best copied from yout web site web.config file, rather than from the above, but you need the three sections:
<ConfigSections>, <connectionStrings>, and <entityFramework>
Comment: Problem remain the same i had alter the web config of Dataentity with the above detail. But its show error "The underlying provider failed on Open."
Comment: OK. A bit more detail. Are the web site and Web Service on the same server? Are you using the same user for both?
Comment: yes,now i tell you that i have created a dot net project with entity framwork then i have added one more project for web service. the web service use the same entity connection what web project is using. but at the time of dubigigng the web service it gives me error "entity exception was unhandled by user code the underlying provider failed on open"                      but the same thing is working if i give direct connection without entity connection to my web service.


Creating user alert node on User Alert module

Question: The steps for using the User Alert module are the following:

Enable User Alerts
Set the appropriate permissions for selected roles
Set the User Alert block in the appropriate region of your theme.
Create a user alert node.

How can you create a user alert node in Step 4?
Answer: The module defines a "User Alert" content type; when you go to http://example.com/node/add/user_alert (replace example.com with the domain name of your site), you are going to create a node of that content type, if you have the permission to create nodes of that content type.
<code>/**
 * Implements hook_node_info().
 */
function user_alert_node_info() {
  return array(
    'user_alert' => array(
      'name' => t('User Alert'),
      'base' => 'user_alert',
      'description' => t('A User Alert is a short Twitter like message displayed at the top of the site, alerting users to critical information like an online sale, new blog post, or breaking news. After viewing it, they can click and close the message.'),
      'has_title' => TRUE,
      'title_label' => t('Title'),
      'disabled' => FALSE,
    )
  );
}
</code>
Check on admin/people/permissions you have at least the "User Alert: Create new content" permission; that is the permission to create nodes of that type. Then, you need the "User Alert: Edit own content" permission to edit the nodes you created.


Media queries de largura aplicadas incorretamente em dispositivos móveis

Question: Estou tentando usar media queries em um site pensando em dispositivos móveis, mas estou enfrentando um problema: embora as regras especifiquem o que fazer quando a largura for pequena - e as mesmas se apliquem corretamente quando se vê num browser com o tamanho da janela reduzido - nos dispositivos móveis ele é apresentado com uma largura um tanto maior, ficando minúsculo na tela. Como não tenho experiência desenvolvendo pra essa mídia, não sei o que estou fazendo de errado.
Meu CSS (simplificado) é:
.parede {
    width: 332px;
    margin: 0 auto;
}

.meio2, .meio4, .meio5 {
    display: none;
}

@media all and (min-width: 540px) {
    .parede { width: 530px; }
    .meio1 { display: none; }
    .meio2 { display: inline-block; }
}

@media all and (min-width: 700px) {
    .parede { width: 690px; }
    .meio3 { display: none; }
    .meio4 { display: inline-block; }
}

@media all and (min-width: 860px) {
    .parede { width: 850px; }
    .meio5 { display: inline-block; }
}

Essencialmente ele muda o tamanho de uma div e exibe/oculta alguns elementos conforme o tamanho da tela. Mas o problema não está nas regras em si, e sim no fato delas não estarem sendo seguidas: quando visto num dispositivo móvel (ex.: Galaxy S4), ou mesmo na simulação de um dispositivo móvel (ferramentas de desenvolvedor do Chrome), todas as regras são ativadas, embora que eu saiba a largura da tela deveria ser 360px.
O link pro site é esse. Note que, visto num browser comum, redimensionar a janela faz com que a parede fique mais estreita e mais alta (comportamento esperado e alcançado).
Minha suspeita é que alguma coisa no cabeçalho esteja "forçando" a largura a ser maior do que ela precisa ser. O cabeçalho é uma lista comum utilizando flexbox - que até onde eu saiba é bem suportado nos principais dispositivos móveis. No browser os itens mudam de linha normalmente quando a janela é estreita (flex-flow: row wrap) - melhor no Firefox que no Chrome - mas no smartphone fica tudo na mesma linha.

CONTATO:
                    ... |
                    ...

sobre

currículo

portfolio em pdf

            </li

Parte do CSS aplicável ao cabeçalho:
.ajustar {
    overflow: auto;
}

.flex-container {
  padding: 0;
  margin: 0;
  list-style: none;

  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;

  -webkit-flex-flow: row wrap;
  -moz-flex-flow: row wrap;
  flex-flow: row wrap;

  justify-content: space-around;
}

.flex-item {
  padding: 5px;
  margin-top: 10px;
  text-align: center;

  flex-shrink: 0;
}

.todo {
    width: 100%;
}

Se faltou algo no CSS acima, favor ver no site completo (não fui eu quem fez esse cabeçalho, ao revisar só achei as regras acima [potencialmente] relevantes, as outras só mudam cor ou coisas assim). Não notei nada de anormal nas ferramentas de desenvolvedor, as regras estão sendo aplicadas e tudo mais - só que a largura está em 964 pixels e eu não entendo por que.
P.S. Pensei também ser algo relacionado a device pixel ratio, mas pelo que entendi desse post o viewport deveria continuar tendo 360px de conteúdo, estou errado?
Answer: Por favor, verifique que seu html contenha a seguinte tag dentro do seu:
<meta name="viewport" content="width=device-width, initial-scale=1">

Essa tag é importante porque sem ela seu dispositivo móvel vai ignorar o media queries e redimensionar o conteúdo do seu site.
Comment: Funcionou, obrigado! Estava totalmente perdido em relação a isso...
Comment: Ainda bem que era simples. O seu media queries tava certo demais pra ser problema no CSS.
Answer: Você pode usar o @viewport dentro de uma media query para determinar o tamanho que a visão terá em determinada resolução. Exemplo:
@media all and (min-width: 540px) {
    @viewport {
          width: 480px;
    }
}

Dessa, forma, quando o tamanho da tela for pelo menos com 540px, a tela vai se comportar como se o tamanho total fosse de 480px.
Link: http://tableless.com.br/manipulando-metatag-viewport/
Comment: O problema é que a media query de 860px está sendo ativada mesmo num device de 360px... De todo modo, vou experimentar sua sugestão, se tiver sucesso volto a postar aqui.
Answer: Tente trocar o min-width por max-width no seu css. Caso não funcione, faça um teste, force colocando um !important depois da regra. Exemplo:

@media screen and (max-width: 540px) {
    .parede { width: 530px !important; }

}
Comment: Acho que vocês não estão entendendo, o problema não é com as regras, elas estão ok, o problema é que no mobile o viewport está sendo "forçado" a ficar maior não sei por que (o que faz com que as regras que só deveriam ser ativadas em telas largas ativem, ainda que o dispositivo só tenha 360 pixels de área útil). Tal como na [sugestão do Gabriel](http://pt.stackoverflow.com/a/104470/215) (que não funcionou, como eu já esperava), vou testar a sua também por via das dúvidas, assim que puder, e se tiver sucesso eu dou um feedback.


growth rate of sequence and series convergent

Question: Let $a_{n}$ be a real sequence, $b$ be a real number with $\lim_{n\rightarrow\infty}a_{n}=b$ but $a_{n}\neq b$ for all $n$. Let $c_{n}$ be a bounded sequence. I have shown that $n(a_{n}-b)=O(n)$ with big O notation. Consider the series $\sum_{n=1}^{\infty}\frac{(n(a_{n}-b)+c_{n})^{2}}{n(n+1)}$, is there any possibility that the series converges? If I understand correctly, $(n(a_{n}-b)+c_{n})^{2}=O(n^{2})$, so the series is eventually summing $\frac{n}{n+1}$ which diverges. But if we expand $(n(a_{n}-b)+c_{n})^{2}$ into $n^{2}(a_{n}-b)^{2}+c_{n}^{2}+2c_{n}n(a_{n}-b)$, both $n^{2}(a_{n}-b)^{2}$ and $2c_{n}n(a_{n}-b)$ diverge, may be they can cancel each other?
Answer: If you are asking for one example where it converges, take $a_n=\frac 1 {n^{2}}, b=0, c_n=-\frac 1 n$.


ServiceMix: ESB or "OSGI Application Server"?

Question: For an integration project I am working on, I started looking at java integration technologies/ESBs. Mule and ServiceMix seemed to fit my needs. I chose ServiceMix but found my self using Camel exclusively (inside ServiceMix). And then this question arose:
Is serviceMix an ESB (which I thought it was) or an Application server like Spring DM Server?
Or may be it is an Application Server fine tuned for Integration?
Sorry if my question feels silly :/
Answer: Karaf is the OSGi container, Servicemix is built on top of Karaf and has out of the box support for ActiveMQ, Camel, CXF, Ode, etc (via pre-installed features, bundles and configuration).
Long story short, Camel provides the integration/EIP backbone, but OSGi (Karaf or Servicemix) is a container to deploy it in.  Camel can also be deployed in other ways as well: in a webapp (Tomcat, etc), in ActiveMQ, standalone, with Spring, etc.
I asked a similar questions as to whether to use Karaf or Servicemix...
Apache Karaf vs. Servicemix


Chord transitions

Question: In A Nightingale Sang In Berkeley Square, fake book notation a D13(#11) chord is followed by /C chord.  This is an awkward transition. How is this /C change for D13(#11), played on piano?
Answer: Assuming by /C it means a D13#11/C, play D, F#, (A), C, B and G# between the hands, with D as the root, and then drop the left hand lowest note to the C just below.Leave out the A if you want, and put the C and B in the first chord as far apart as you can. It doesn't have to be so in the slash chord, as the lowest note is C. Play around with the voicing till you find one that sounds good to you.

Chord transitions


Dell Replay Manager vs/Actifio or Veeam

Question: I am not very familiar with SAN storage.  The company I work for is evaluating a backup solution that will utilize two Dell Compellents.  We currently have one Compellent, but are considering purchasing another for a warm site.  The quote for the second Compellent includes two instances of Dell Replay Manager.  My understanding is that Dell Replay  Manager can be used to take snapshots, which is understandably a good idea.  We are also evaluating Actifio and Veeam as backup solutions.  The Dell Replay Manager is pretty expensive and I am wondering if it is even needed if we will be using Veeam or Actifio for a backup solution.
Could anyone offer any insight as to why, or why we would not, want to eliminate the Dell  Replay Manager from our purchase IF we proceed with a true backup solution (Veeam or Actifio) ?
Apologies if this question is naive and better suited for a different forum.
Thanks
Comment: Turns out that we probably don't need Replay Manager if we implement Actifio as a backup solution.
Answer: You don't need Dell backup as long as you operate with virtual systems and VMs (VMware or Hyper-V hypervisors). Veeam is a standard of backup solution there. Veeam supersedes its analogs, offering backup and virtualization 2 in 1, any storage as a backup target, plus some cool features like backup encryption and backup to cloud. And it's cheaper...
If you, however, deal with physical or hybrid systems, that's another case.

Dell Replay Manager vs/Actifio or Veeam


Highlight Field in Views

Question: I just created a Views table with a few columns. I would like to create a rule that enables Views to highlight certain fields if information is missing/blank. What would be the best way to do this?
Answer: In your view's settings, click on the field that might be empty and open up NO RESULTS BEHAVIOUR. Uncheck everything in the dropdown (perhaps leave Count the number 0 as empty depending on your use case) then add text like this in the No results text

Comment: Nothing happened. I added .empty class as background-color: #000000; and the cells did not turn black.
Comment: Propably a CSS issue. Try this for a start: .empty {
  display:inline-block;
  background-color: #000;
  height:100%;
  width:100%;
  margin:0;
  padding:0;
}
Comment: Nope, it still doesn't work.
Comment: Look at the browser dev console (inspect element). If the class is in there it is a style issue, else a views issue.

Highlight Field in Views


How can I create a 3D Grid in scenekit

Question: how can I make a grid with 3d objects(box). I already know how to setup scnscene and how to create an object. But I don't know how to make the layout. The grid should look like this one, with 3d object in a 3D space.
Here's what I tried:
           convenience init(create: Bool) {
        self.init()

        let geometry = SCNBox(width: 0.8 , height: 0.8,
                              length: 0.1, chamferRadius: 0.005)
        geometry.firstMaterial?.diffuse.contents = UIColor.red
        geometry.firstMaterial?.specular.contents = UIColor.white
        geometry.firstMaterial?.emission.contents = UIColor.blue
        let offset: Int = 10

        for xIndex:Int in 0...2 {
            for yIndex:Int in 0...2 {
                // create a geometry copy
                let geoCopy = geometry.copy() as! SCNGeometry

                var images:[UIImage]=[]
                for i in 1...5 {
                    if let img = UIImage(named: "\(i)"){
                        images.append(img)
                        let material = SCNMaterial()
                        material.diffuse.contents = img
                        geoCopy.firstMaterial = material

                    }
                }

                let boxnode = SCNNode(geometry: geoCopy)
                let boxCopy = boxnode.copy() as! SCNNode
                boxCopy.position.x = Float(xIndex - offset)
                boxCopy.position.y = Float(yIndex - offset)
                self.rootNode.addChildNode(boxCopy)
            }
        }
    }

But I only see one box.
Thanks!
Picture of my Images:
Answer: You need to create one geometry, one box node and then copy that boxNode. You use clone when you have node with children and flattenedClone when you want to merge geometries/materials of the entire subtree at the node. In your case, copy should suffice. Just change the position of your copied node.
GameScene
import Foundation
import SceneKit

class GameScene: SCNScene {

    override init() {
        super.init()

        let geometry = SCNBox(width: 0.6 , height: 0.6,
                               length: 0.1, chamferRadius: 0.005)
        geometry.firstMaterial?.diffuse.contents = UIColor.red
        geometry.firstMaterial?.specular.contents = UIColor.white
        geometry.firstMaterial?.emission.contents = UIColor.blue
        let boxnode = SCNNode(geometry: geometry)
        let offset: Int = 16

        for xIndex:Int in 0...32 {
            for yIndex:Int in 0...32 {
                let boxCopy = boxnode.copy() as! SCNNode
                boxCopy.position.x = Float(xIndex - offset)
                boxCopy.position.y = Float(yIndex - offset)
                self.rootNode.addChildNode(boxCopy)
            }
        }
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
}

In your view controller, viewDidLoad:
override func viewDidLoad() {
        super.viewDidLoad()

        // create a new scene
        let scene = GameScene()

        // retrieve the SCNView
        let scnView = self.view as! SCNView

        // set the scene to the view
        scnView.scene = scene
        scnView.pointOfView?.position = SCNVector3Make(0, 0, 100)

        // allows the user to manipulate the camera
        scnView.allowsCameraControl = true

        // show statistics such as fps and timing information
        scnView.showsStatistics = true

        // configure the view
         scnView.backgroundColor = UIColor.white

    }

Note that I have just pushed the camera point of view back on the +Z axis to have a better view of your grid.
The grid screenshot

Edit: New material for each geometry
If you want to assign a new material to each geometry, you need to create a copy of the geometry and assign a new material to that geometry copy. See the code below which randomly assign a UIImage for each diffuse property, from a set of seven images named 1.png to 8.png.
import Foundation
import SceneKit

class GameScene: SCNScene {

    override init() {
        super.init()

        let geometry = SCNBox(width: 6 , height: 6,
                              length: 6, chamferRadius: 0.5)

        for xIndex:Int in stride(from: 0, to: 32, by:8) {
            for yIndex:Int in stride(from: 0, to: 32, by: 8) {
                // create a geometry copy
                let geoCopy = geometry.copy() as! SCNGeometry

                // create a random material
                let r = arc4random_uniform(7) + 1
                let img = UIImage(named: "\(r).png")
                let mat = SCNMaterial()
                mat.diffuse.contents = img
                geoCopy.firstMaterial = mat

                // create a copy node with new material and geo copy
                let boxnode = SCNNode(geometry: geoCopy)
                let boxCopy = boxnode.copy() as! SCNNode
                boxCopy.position.x = Float(xIndex - offset)
                boxCopy.position.y = Float(yIndex - offset)
                self.rootNode.addChildNode(boxCopy)
            }
        }
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
}

Screenshot
Comment: thank you!! But I have on last question. I'm trying to add a SCNMaterial() on each geometry, how can I do it? The material is different for every node I just have 15 nodes. Thanks. I just updated my question.
Comment: @John Updated the answer so that each node has a different material.
Comment: Thanks, really appreciated. But how can I do it with images. Just updated my answer.
Comment: The contents of a material property can be any of color, image or even animated content. So setting `mat.diffuse.contents = UIImage(named:"some.png") will also work. You can assign a separate image for each node, just as we are doing with colors. Hope this helps. See: https://developer.apple.com/reference/scenekit/scnmaterialproperty/1395372-contents
Comment: I tried but I see the same image on each geometry. check my question. Thanks
Comment: There is something wrong with your images then. See my updated answer. I assign random image from a set of seven images and they work fine. My suspicion is that every time you are reading image for i = 1 and hence seeing the same image.
Comment: It's working when I use the "let r = arc4random_uniform(7) + 1" but it's not working with the For loop. Can you try it just one last time with the For loop please? Just one last time. Thanks
Comment: I tried with your code and as I suspected, it is always image number 5 that is applied. Your code also clearly indicates that you loop from 1 to 5 and as all 1.png to 5.png exist, it is 5.png that is applied to each node.  Basically you are overwriting each node's material with images 1.png to 5.png, always ending with 5.png. You need to fix your code so that each node gets a different image. The problem is not with UIImage or anything, but with your logic that applies the image to the material.
Comment: I understand, but somehow I still can't find a way to put it in code. If I don't use a For Loop what can I use? Sorry I'm a beginner. Thanks
Comment: How to create a 3d floor like attached image in scenekit https://blog.pusher.com/wp-content/uploads/2017/08/building-ar-with-arkit-and-scenekit-10-blender-cube.png
Answer: You need to put the statement -let boxnode = SCNNode(geometry: self.geometry) - inside the loop. If you wish to use the same materials, you can use the same geometry for all nodes (just store the geometry in a variable and assign it). Otherwise, if you wish to have different materials, copy the geometry and assign different materials each time.
Comment: You also need to move the addChildNode part of your code inside the loop. Each new node created during iteration must be added to your scene.
Comment: Thanks @Karl Sigiscar, I just updated my question. But it doesn't work. I still see just one box. Can you help me?

How can I create a 3D Grid in scenekit


How can I estimate model predicted means (a.k.a. marginal means, lsmeans, or EM means) from a GEE model fitted in R?

Question: I am trying to obtain model-predicted means and CI's for a categorical predictor in a GEE model fitted with the geeglm function (geepack package). The model is fitted with no problem, but where I am stuck is when trying to estimate the model-predicted group means. This is something fairly easy to do in other software packages (i.e., SAS and SPSS), but my point is to try to do this in R (also I was a bit disappointed to find no direct way to obtain overall tests for a categorical predictor other than fitting reduced and full models separately and then comparing them; but on the other hand I was able to find an easy way to compute the QIC with the MESS package).
Anyway, I searched around to see if perhaps this was done with another package (there's a package called lsmeans, but it seems not compatible with geepack or gee packages). I am surprised I have not been able to find something as common as estimating model predicted means for a GEE model in R, so I was wondering if someone knows a solution for this. I tried contacting the geepack maintainer, but no answer.
Why GEE instead of a mixed model (marginal means for a mixed model can be computed using the lmerTest package)? well, it has fewer assumptions, and is more robust with small samples.
Comment: I've ran into this problem since I don't think `predict` methods are defined for `gee` objects. A quick cheat for getting around this is just to fit the analogous `lm` or `glm` model. The coefficients are exactly the same, the standard errors are what differ between the two.
Comment: Also, one of the key relaxed assumptions of GEE is that of possible heteroscedasticity. Plugin estimates of residual variance are used to compute standard errors for linear models. So post-hoc tests of specific contrasts cannot necessarily be computed because you have to re-introduce assumptions about the distribution of errors around predicted values.
Comment: FWIW, I am adding support for gee, geeglm, and geese objects in the next update of the lsmeans package. It'll be on CRAN in a couple of weeks.
Answer: The LSmeans function in the doBy package may be helpful.
Here is a simple modification of an example in the vignette.
library(doBy)
library(geepack)
warp.gee <- geeglm(breaks ~ tension, id=wool, family=gaussian, data=warpbreaks)
LSmeans(warp.gee,effect="tension")

Comment: Thanks, it works great. Did not know doBy had those capabilities.
Answer: The emmeans package now provides estimated marginal means for GEE models:
library(geepack)
library(emmeans)
warp.gee <- geeglm(breaks ~ tension, id=wool, family=gaussian, data=warpbreaks)
emmeans(warp.gee, ~tension)
 tension   lsmean       SE  df asymp.LCL asymp.UCL
 L       36.38889 5.774705 Inf  25.07067  47.70710
 M       26.38889 1.689200 Inf  23.07812  29.69966
 H       21.66667 2.042753 Inf  17.66294  25.67039

plot(emmeans(warp.gee, ~tension), horizontal=FALSE, ylab="Estimated mean")

Answer: The spind package offers a predict function similar to other uses of predict:
https://www.rdocumentation.org/packages/spind/versions/2.1.3/topics/predict.GEE
# load packages
library(geepack)
library(spind)

n <- nrow(warpbreaks) # number of cases
trainIndex <- sample(1:n, n*.60) # random subset of 60% of cases (training)
testIndex <- setdiff(1:n, trainIndex) # rest of cases not in training (testing)

# model fit
warp.gee.fit <- geeglm(breaks ~ tension, id=wool, family=gaussian, data=warpbreaks[trainIndex,])

# predict test cases
predict(warp.gee.fit, warpbreaks[testIndex,])
```


Bound on maximum of product of matrix and vector

Question: I need to bound the absolute maximum of each entry of a matrix-vector product:
$\max_{|x|_{1}=1} |Ax|_{\infty}$
I tried to pose this in terms of the induced infinity norm of $A$, as in $|Ax|_{\infty} \leq |A|_{\infty}|x|_{\infty}$ but that doesn't have the decay properties I need. It is known that $x_i \geq 0$, but $A_{ij}$ may be positive or negative. I was wondering if there's a known bound on the above quantity when the entries of vector $x$ are known to be non-negative. Here $|x|_1 = \sum_i x_i$ and $|x|_{\infty} = \max_i |x_i|$. Any help would be appreciated.
Answer: Notice that if $|a_{km}|=max_{i,j}|a_{ij}|$ then $|Ae_m|_{\infty}=|a_{km}|$, where $e_m$ is the column vector with 1 in the $m$ entry and $0$ otherwise.
It is clear that $|Ax|_{\infty}\leq |a_{km}|$, if $x\geq 0$ and $|x|_1=1$ .
So $max_{|x|_1=1\ ,\ x\geq 0}|Ax|_{\infty}=max_{i,j}|a_{ij}|$
Comment: That was easy! Now I feel like an idiot.:)


Programmatically customise fields in node views

Question: I'm developing a module that exposes a node type (by the usual hook_node_info() and hook_install()) and a set of custom fields.
I would like to programmatically define what/how those fields have to be shown in the node views (at least "full"). For example: the field XYZ should be hidden in the "full" mode, and the field ABC should have the lable inline (I'm able to do this by UI, but I would like to define it programmatically).
In any case my need is to exactly modify the view mode (not to always hide a field), in order to allow users to modify the default visualisation way after installation, if necessary.
I can't figure what hook I have to implement, or what code I have to write in the hook_install.
Thank you for your help
Answer: I want to share the solution I found, in order to help future readers.
In Drupal 7 the concept of "formatter" helpt to control the output of a field. For example this tutorial allow you to programmatically define a custom formatter for a given field.
Then by UI site admins (by admin/structure/types/manage/<nodetype-name>/display) are able to chose that formatter (or others) for any specific field.
If you want to declare a default formatter for a field, the best way seems to be while the install phase of the module.
In that moment (At least in my case and in all tutorial I found on the Internet) you use a field_create_instance method to add a specific instance of a given field. According to the official documentation, you can also add the display options that exactly allow you to define the formatter to be used for a specific display (or the formatters if want to declare for more than one display).


Python - tokenizing, replacing words

Question: I'm trying to create something like sentences with random words put into them. To be specific, I'd have something like:
"The weather today is [weather_state]."

and to be able to do something like finding all tokens in [brackets] and than exchange them for a randomized counterpart from a dictionary or a list, leaving me with:
"The weather today is warm."
"The weather today is bad."

or
"The weather today is mildly suiting for my old bones."

Keep in mind, that the position of the [bracket] token wouldn't be always in the same position and there would be multiple bracketed tokens in my string, like:
"[person] is feeling really [how] today, so he's not going [where]."

I really don't know where to start with this or is this even the best solution to use tokenize or token modules with this. Any hints that would point me in the right direction greatly appreciated!
EDIT: Just for clarification, I don't really need to use square brackets, any non-standard character will do.
Comment: Might be a stupid suggestion, but have you looked at string formatting with `{}`s?
Answer: You're looking for re.sub with a callback function:
words = {
    'person': ['you', 'me'],
    'how': ['fine', 'stupid'],
    'where': ['away', 'out']
}

import re, random

def random_str(m):
    return random.choice(words[m.group(1)])

text = "[person] is feeling really [how] today, so he's not going [where]."
print re.sub(r'\[(.+?)\]', random_str, text)

#me is feeling really stupid today, so he's not going away.

Note that unlike the format method, this allows for more sophisticated processing of placeholders, e.g.
[person:upper] got $[amount if amount else 0] etc

Basically, you can build your own "templating engine" on top of that.
Comment: That's great, I like how I how it's clean and efficient. It does it job and being a Python beginner understanding it gives me an advantage. :) The smart thing would be to write a dictionary file, save it on disc and load it into the "words" dictionary here... Any pointers on how a dictionary file syntax would look like in a file? Many thanks!
Comment: @bitworks: the simplest and most convenient option is json: http://docs.python.org/2/library/json.html
Answer: You can use the format method.
>>> a = 'The weather today is {weather_state}.'
>>> a.format(weather_state = 'awesome')
'The weather today is awesome.'
>>>

Also:
>>> b = '{person} is feeling really {how} today, so he\'s not going {where}.'
>>> b.format(person = 'Alegen', how = 'wacky', where = 'to work')
"Alegen is feeling really wacky today, so he's not going to work."
>>>

Of course, this method only works IF you can switch from square brackets to curly ones.
Answer: If you use braces instead of brackets, then your string could be used as a string formatting template. You could fill it in with lots of substitutions using itertools.product:
import itertools as IT

text = "{person} is feeling really {how} today, so he's not going {where}."
persons = ['Buster', 'Arthur']
hows = ['hungry', 'sleepy']
wheres = ['camping', 'biking']

for person, how, where in IT.product(persons, hows, wheres):
    print(text.format(person=person, how=how, where=where))

yields
Buster is feeling really hungry today, so he's not going camping.
Buster is feeling really hungry today, so he's not going biking.
Buster is feeling really sleepy today, so he's not going camping.
Buster is feeling really sleepy today, so he's not going biking.
Arthur is feeling really hungry today, so he's not going camping.
Arthur is feeling really hungry today, so he's not going biking.
Arthur is feeling really sleepy today, so he's not going camping.
Arthur is feeling really sleepy today, so he's not going biking.

To generate random sentences, you could use random.choice:
for i in range(5):
    person = random.choice(persons)
    how = random.choice(hows)
    where = random.choice(wheres)
    print(text.format(person=person, how=how, where=where))

If you must use brackets and have no braces in your format, you
could replace the brackets with braces and then proceed as above:
text = "[person] is feeling really [how] today, so he's not going [where]."
text = text.replace('[','{').replace(']','}')

Comment: I decided to stay away from `format(**locals())` here because it would not make it clear exactly how the substitution was being made. But if you did have hundreds of variables, `format(**locals())` would be the way to go.
Comment: This `person=person, how=how, where=where` thing can get really stupid if they have hundreds of them.

Python - tokenizing, replacing words


define a function with parameter based on another javascript file

Question: I have some common js functions with parameter, which I will reuse, so I thought, that I create another js file and store the common code here and in the target html I define these functions with parameters and if the functions are called, then they are executed.
I have this common function in a separate js file:

function add_onClick(url) {
    $.ajax({
        url: url,
    }).done(function (response) {
        var popup = $("#entity-popup").dxPopup("instance");
        popup.option("contentTemplate", function (content) {
            content.append(response);
        });
        popup.show();
    });
}

If I define the function in the target html like this:
var add_onClick = add_onClick('/MasterData/Sender/NewSender')

then the function is executed on every page load, not on button click.
If I define the function like this:
var add_onClick = function () { add_onClick('/MasterData/Sender/NewSender'); };

Then I get the error 'javascript maximum call stack size exceeded'.
How should I define the function in the target html in order to execute only if the user clicks the add button?
Unexplaninable extra request:

EDIT:
The /MasterData/Sender/NewSender targets an action, which returns a view with a new Sender object like this:
public IActionResult NewSender()
    {
        ViewBag.Mode = "new";
        Sender Sender = new Sender();
        return PartialView("Sender", Sender);
    }

I think, this should be the extra traffic in the network window. But I don't get this extra line, if the add_onClick function isn't in a separate file.
Answer: var add_onClick = function () { add_onClick('/MasterData/Sender/NewSender'); };

This is an infinite loop. It just continuously calls itself.
Maybe like this?
document.getElementById('myButton').addEventListener('click', () => {
  add_onClick('/MasterData/Sender/NewSender')
})

<button id="myButton">Click me</button>

Comment: Yes, I already realized this, because I searched the error message. But the question remains.
Comment: Well, it works, but now in the console I get this: `https://localhost:44355/MasterData/Sender/[object%20Object]`, status code 404. This is a bit strange, because the called view appears correctly. Have you an idea why I get this error?
Comment: Does the `url` contain what you want it to? Does the `response` contain what you want it to? `console.log` both and debug from there.
Comment: Add a `catch` function to the ajax call. Perhaps that can help you a bit with error handling.
Comment: Yes, the url contains the right string and the response too. I have added a picture to the post, where we can see, that we have an extra request with this object thing. And of course in the controller there is no such action method and that's why I get 404 error (also tested with catch function).
Comment: Somewhere you are sending in an object to the url. You need to double check your code.


Formal structure of a proof with the goal $\exists x P(x)$

Question: In How To Prove It?, Velleman explains that, in order to prove a statement with a goal of the form $\exists x P(x)$, we must declare an arbitrary variable $y$ and assign a value $a$ to it and use the assignment to prove the substitution instance $P(y/x)$ of the goal. Hence, assuming $\Gamma$ is a well-founded formula, we have:

$\Gamma \rightarrow \exists x P(x)$
$(\Gamma \land (y=a)) \rightarrow P(y/x)$

My question concerns the formal structure of such proof technique and the relation between statements 1 and 2.
My first attempt was this one: since $P(a)$ is logically equivalent to $\forall y[(y=a) \rightarrow P(y)]$, then $\Gamma \rightarrow P(a)$ is equivalent to $\Gamma \rightarrow \forall y[(y=a) \rightarrow P(y)]$. If $y$ does not occur in $\Gamma$, then the last statement is equivalent to $\forall y[\Gamma \rightarrow ((y=a) \rightarrow P(y))]$, which means $\forall y[(\Gamma \land (y=a)) \rightarrow P(y)]$.
Now, since $\Gamma \rightarrow P(a)$ implies $\Gamma \rightarrow \exists x P(x)$, it is fair to believe that the relation between statements 1 and 2 is $\forall y[(\Gamma \land (y=a)) \rightarrow P(y)] \rightarrow [\Gamma \rightarrow \exists x P(x)]$.
However, some members on this site informed me that this implication is a weaker version of the more general assertion $\forall y[[(\Gamma \land (y=a)) \rightarrow P(y)] \rightarrow [\Gamma \rightarrow \exists x P(x)]]$. In this case, $y$ appears as a free variable, whose quantification ranges upon the entire proof. However, I can't tell how it is possible to derive such stronger implication, especially because the formula $(\Gamma \land (y=a)) \rightarrow P(y)$ seems meaningless to me.
Answer: IMO, your analysis of Existential Introduction is unnecessarily complicated...
The intuitive reasoning is the following:

if we know that Socrates is a Philosopher, then we are licensed to assert that a Philosopher exists.

In symbols:

$\dfrac { P(s) } { \exists x P(x)}$.

Thus, there is no need to add a "declaration" about the term (i.e. a "name") $s$.

Things are different with Existential Elimination, where we have $\exists x P(x)$ as premise.
In this case, we introduce a new term $a$ to "temporary" refer to the unknown individual that we know to exists.
The "new" condition is formalized through the proviso that $a$ must not be used in the "context" $\Gamma$, nor in the conclusion of the proof.

With ref to Velleman's book, page 112, I do not see big differences...
The author says:

"Try to find a value of $x$ for which you think $P(x)$ will be true."

This amounts to saying: "let $x= \text {Socrates}$".

"... and proceed to prove $P(x)$ for this value of $x$."

This amounts to saying: "prove $\text {Philosopher}(\text {Socrates})$".
Then apply EI to conclude that $\exists x (\text {Philosopher}(x))$.
Comment: @TylerD007 - Frankly speaking, I'm not sure that that is the right reading of  Velleman's text... He has a predicate $P(y) =: (y+2x=0)$ and he wants to prove $\exists y P(y)$. In order to do so, he assume $y=a$ for a suitable $a$; in this case the suitable value is $a=-2x$. Then he check (no special logic here: only algebra) that $P(a)$ holds, i.e. that $a+2x=0$. Thus, having proved $P(a)$, he apply EI to conclude with $\exists y P(y)$.
Comment: I totally agree with you, Mr Allegranza, but that's what Velleman does, he uses value assignments to prove goals of the form $\exists x P(x)$. All I want is to establish the relation between statements in which such assingments are assumed and the original proofs. EDIT: I suppose my original problem does not relate with existential elimination, at least not at this point of the proof.
Comment: About your second edit: I think that's not exactly what Velleman proposes. He says, if we have a proof like $\Gamma \rightarrow \exists y (y + 2x =0) $, then we assume a value of a free variable y that makes the formula $(y + 2x =0)$ true and that implies $\exists y (y + 2x =0)$. Like I said, a member of this site told me that the first implication as a whole implies the existentially quantified goal. Hence,  $[(y = -2x) \rightarrow (y + 2x =0)] \rightarrow \exists y (y+2x=0)$. However, that reasoning makes little sense to me, even after much consideration about it.
Comment: Your reasoning makes much more sense to me. The two problems that I formalize in my post are: 1) from where does Velleman introduce the value assignment into the proof? 2) does he really use EI to derive $\exists x P(x)$ or does he use this kind of "stronger" implication?
Answer: Suppose you are trying to prove $\exists y(y+2x = 0)$.  Here are two ways you might write the proof:

Prove $(-2x)+2x=0$.
Start with the sentence "Let $y = -2x$" and then prove $y+2x=0$.

The logic of these two approaches is exactly the same; the difference is merely stylistic.  In the second approach, the letter $y$ is just being introduced as a notational shorthand for $-2x$.
Which style is better?  It may depend on the example, and it may be a matter of taste.  But if the conclusion of the theorem being proven has been stated with an explicit existential quantifier, then I think many mathematicians would prefer the second style.
For example, suppose you are giving an $\epsilon$-$\delta$ proof of a limit statement--say, $\lim_{x \to 2} 3x = 6$.  The statement to be proven is $\forall \epsilon>0 \exists \delta>0 \forall x(0 < |x-2| < \delta \to |3x-6|<\epsilon)$.  I think most mathematicians would start the proof like this:  "Let $\epsilon$ be an arbitrary positive number.  Let $\delta = \epsilon/3$.  Then $\ldots$."  There is really no need for the sentence "Let $\delta = \epsilon/3$."  One could simply prove that $\epsilon/3$ has the property required for $\delta$, and then conclude that the limit statement is true.  But most readers would find the sentence "Let $\delta = \epsilon/3$" helpful, because it tells the reader that $\epsilon/3$ is the number that is being proposed as the value of $\delta$ in the $\epsilon$-$\delta$ definition.
Note that How To Prove It is not a book on formal logic, although there is some logic in the book.  It is a book about how to write proofs in English.  So although the proof techniques that are discussed often correspond to rules of formal logic, the explanations focus on how to use those techniques to write proofs in English, not how to write proofs in formal logic.


Display HTML 5 Validation message via Program

Question: I would like to display the html 5 validation message manually (i.e. via code). According to my understanding, there is no direct way to invoke this message. However, we can bring it via submit button click.
I tried to bring the validation message (if the field is invalid) when you click on the html body:
// if url is invalid, display the error message.
if(!$('#theurl')[0].checkValidity()){

    console.log('Button Click');
    $('#btn').click();

}

Here is the jsfiddle for the same. Unfortunately, the above code is getting crashed. I have no idea why. Instead, if you click on the fake button manually it works fine.
Please help me to accomplish this.
Comment: Why don't you right you own validation?
Comment: Well, I can do that but I prefer to take the advantage of native API at the moment. Also, now I'm bit curious about the reason for browser crash (an unexpected infinite loop).
Answer: The problem is that your Click function is taking the parameter 'e', but you're looking for the parameter "event".
$('body').click(function(e){

The call
    $(event.target)

Change it to 'e.target' and it works:
http://jsfiddle.net/wLCdz/3/
Also, the checkValidity function is called from the form, not from the individual items within the form.  So, if you call the checkValidity function like this:
document.forms[0].checkValidity()

it will stop crashing for that reason.
Answer: In your jsfiddle, the code on line 22 is causing an infinite loop, which ends up causing the script to crash:
$('#btn').click();

If you comment out that line it no longer crashes. Triggering a click on the button like you are doing is also causing another click to be triggered on the body element.
To see what I mean, comment that line out, put a bad url in the form and click on the body. Each click writes a message to the console.
Comment: I think @Richard's answer is what you want
Comment: Ya, I am aware that the browser is crashing because of an infinite loop (see my comments on the question) but I was not sure why. I am returning from the handler if the clicked element is button.
Comment: Well, the issue is solved now. I was using the wrong parameter(i.e. `event` instead if `e`). Thanks anyway you are right at your point :-)
Answer: Try this:
<form id="formId">
...
</form>

$('body').click(function(e){

    // ignore, if clicked on the url
    if ($(event.target).closest('#theurl').length) {
        return;
    }

    // ignore, if clicked on the email
    if ($(event.target).closest('#theemail').length) {
        return;
    }

    // ignore, if clicked on the button
    if ($(event.target).closest('#btn').length) {
        return;
    }

    // if url is invalid, display the error message.
    if(!$('#formId')[0].theurl.checkValidity()){

        console.log('Button Click');
        $('#btn').click();

    }

});

Comment: why are you downvoting to me? I suggest to call checkValidity function  from the form and not from individual items.


Can a Java applet create a new folder on the client's machine?

Question: If an applet is running in the browser, can it create folders or files on the client machine?
Answer: Yes, but the applet must be signed.
A lot of manufactures download manager works like this.


Add margin to Appcompat actionbar popup menu

Question: I am using appcompat actionbar. I want to add top margin to the overflow menu that opens on the top-right. Hence, increasing the spacing above it as you can see in the picture below. Right now the dropdown menu open on top of the 3 dots. How can I push it down?
Thank you.
Answer: If you are referring to Activity's default OptionItem menu, I guess you can't do it programmatically as the APIs just let you inflate it, thus adding/removing elements. Spacing should be fine tho, as the menu is standardized across every kind of layout.
What is the spacing problem you're having? Could you add a screenshot of your desired result?
A possible solution, not too dirty, would be using a custom style:

Comment: This is not what I am looking for. Please check the updates to my question. @Shine
Answer: You can Toolbar instead of ActionBar

<android.support.v7.widget.Toolbar
     android:id="@id/toolbar"
     android:background="@color/color_notification_toolbar"
     android:layout_width="fill_parent"
     android:layout_height="@dimen/abc_action_bar_default_height_material">

    <TextView
          android:textSize="@dimen/abc_text_size_title_material_toolbar"
          android:textStyle="bold"
          android:textColor="@color/color_notification_title"
          android:layout_gravity="center"
          android:id="@id/tvTimeLineTitle" android:layout_width="wrap_content"
          android:layout_height="wrap_content" android:text="@string/title" />

  /* add your menu items here as simple text views and
    and give as much margins and paddings as you want  */

</android.support.v7.widget.Toolbar>


How does one actually show from associativity that one can drop parentheses?

Question: I've always heard this reasoning, and it makes obvious sense, but how do you actually show it for some arbitrary product? Would it be something like this?
$$(a(b(cd)))e=((ab)(cd))e=(((ab)c)d)e=abcde?$$
Do you just say that the grouping of the parentheses now corresponds to just multiplying straight through? Thanks.
Comment: Well, you can say that, but you should prove it if you're unsure. The idea is generally to define a "preferred" parenthesization (e.g. the last one you've got there) and show that associativity implies that all parenthesizations are equivalent to that one.
Comment: http://www.proofwiki.org/wiki/General_Associativity_Theorem
Comment: One might want to note this only necessarily works for structures only where we have a single "product" or "binary operation" at work, and no other binary operations. Even if we have two associative products "@" and "^" at work, you'll still need parentheses (in infix notation). Define "@" as "pseudo-modular" over "^" if (x@(y^z))=((x@y)^z) and correspondingly "^" as "pseudo-modular" over "@" if (x^(y@z))=((x^y)@z). If you have more than one associative product, it at least looks like you'll also need that each product is "pseudo-modular" over any other one to drop all parentheses (in infix).
Answer: You can prove by induction on the number of factors that all such products are equal. We show that if you have $a_1,\ldots,a_n$, then any way to place the parenthesis will yield the same result as $a_1(a_2(\cdots(a_{n-1}a_n)\cdots))$.
If the number of factors is $1$ or $2$, then the result is immediate. If the number of factors is $3$, then it follows precisely by associativity: $(a_1a_2)a_3 = a_1(a_2a_3)$.
Assume the result holds for any $k$, $1\leq k\lt n$, and you have some product of $n$ elements $a_1,\ldots,a_n$, in order, with parentheses placed in some arbitrary (but valid) manner. Then there exists $k$, $1\leq k\lt n$, such that the product is of the form
$$w_1(a_1,\ldots,a_k)\cdot w_2(a_{k+1},\ldots,a_n)$$
where $w_1(a_1,\ldots,a_k)$ is just an expression involving the product of $a_1,\ldots,a_k$ with parentheses placed in some fashion, and similarly with $w_2$. (We are just looking at the "last" product to be done; e.g., if you have $((a_1a_2)a_3)(a_4a_5)$, we would have $k=3$, $w_1(a_1,a_2,a_3) = (a_1a_2)a_3$, and $w_2(a_4,a_5) = a_4a_5$; if you have $a_1((a_2a_3)(a_4a_5))$, then $k=1$, $w_1(a_1) = a_1$, and $w_2(a_2,a_3,a_4,a_5) = (a_2a_3)(a_4a_5)$; etc).
By induction we can write
$$w_1(a_1,\ldots,a_k) = a_1(a_2(\cdots(a_{k-1}a_k)\cdots))$$
so
\begin{align*}
w_1(a_1,\ldots,a_k)w_2(a_{k+1},\ldots,a_n) &= \Bigl(a_1\bigl(a_2(\cdots(a_{k-1}a_k)\cdots)\Bigr)\cdot w_2(a_{k+1},\ldots,a_n)\\\
&= a_1\cdot\Bigl(a_2(\cdots(a_{k-1}a_k)\cdots)w_2(a_{k+1},\ldots,a_n)\Bigr) \\\
&= a_1\cdot\Bigl( a_2(a_3(\cdots(a_{n-1}a_n)\cdots)\Bigr)
\end{align*}
where the last equality follows from the induction hypothesis applied to a product with $n-1$ factors, and the immediately preceding equality by simple associativity of three factors, applied to $a_1$, $a_2(\cdots(a_{k-1}a_k)\cdots)$, and $w_2(a_{k+1},\ldots,a_n)$.  (Note: If $k=1$, then you can skip directly from the first line to the last line without having to invoke associativity; the argument still holds.)
Thus, any expression of a product of $a_1,\ldots,a_n$, in that order, with parentheses placed in an arbitrary but valid manner, is equal to
$$a_1(a_2(\cdots(a_{n-1}a_n)\cdots)),$$
This completes the induction and the proof.
Since all ways of associating a product of $n$ factors, $a_1,\ldots,a_n$ yield results that are equal to one another, we may freely write any such product simply as $a_1\cdots a_n$ to represent their common value.
Comment: Arturo is a canonical example of an enterprising soul! :)
Comment: And yet, a downvote... Go figure.
Comment: @Mariano: You are affirming the consequent! Your statement was basically "If $X$ is enterprising, then $X$ might post a proof"; I posted a proof, it does not follow I am enterprising...(-: (Besides, I was in the middle of it when your post came through...)
Comment: I knew of your enterprisingness (?) long before this question came along! :)
Comment: I tried to formulate a proof like this, but failed to spot the last induction applied to the $(n-1)$ elements, which I find rather beautiful.  This is a really nice proof.
Comment: Thank you Arturo. A wonderful answer, much obliged.
Comment: We got one each. For my part, I have to say there is much worse company to be in :)
Comment: @Mariano: And here I was just thinking the same thing... I now call today's meeting of the MAS (mutual admiration society) to a close. (-:
Answer: Hint $ $ It's easy: iteratively push ')'s rightward via the rewrite rule $\rm\, (xy)z\ \to\ x(yz).\,$ This process terminates with the right-associated normal form where all ')'s are at the right end,
namely $\rm\ a(b(c(d(\cdots))),\, $ written $\rm\ abc\cdots $ (unambiguous - since every bracketing rewrites to it by below).
Proof $ $ (sketch) $ $ by strong induction on the length $\rm\:\ell(Z)  = $ number of operands (factors)
$\rm \ell(Z)\, =\, 1\!:\ \ \  Z = a\ $ is in normal form $ $ (base case).
$\rm \ell(Z)\, >\, 1\!:\ \ \ Z = XY\ $ where $\rm\:\ell(X),\ell(Y)< \ell(Z)\,$ splits into $2$ cases:
$\rm\ \ \color{#90f}{\ell(X)\! =\! 1}\!:\ \ \ XY = a\color{#c00}Y = a(\color{#c00}{b(c(\cdots))})\:\ $ by $\:\rm\color{#90f}{X= a},\,$ and $\rm\color{#c00}{induction}$ applied to $\rm\color{#c00} Y$
$\rm\ \ \ell(X)\! >\! 1\!:\ \ \ \color{#c00}XY = \underbrace{(\color{#c00}{a \bar X})Y = a(\color{#0a0}{\bar X Y})}_{\rm \color{darkorange}{associative}\ law} = a(\color{#0a0}{b(c(\cdots))})\ $ by $\rm\color{#c00}{induc}\color{#0a0}{tion}$ applied to $\rm \color{#c00}X,\, $ then $\rm\color{#0a0}{\bar XY}$
Only $\rm\color{darkorange}{associativity}$ $\rm\, (AB)C = A(BC)\,$ was used, so the proof works for any associative operation.
Comment: @Downvoter You didn't say what was not clear, so I'll guess it was the most complex inductive step, when $\rm \ell(X)>1,\,$ which I have now clarified via color emphasis.
Answer: That «one can drop the parentheses» really means that «no matter how you put the parentheses in, the result will be the same».
To prove such a statement, what one usually does is pick one specific way of putting in parentheses, and shows that any other way gives the same result as the one we picked. This is done by induction in the number of factors.
Some enterprising soul might post a complete proof...
Comment: For reference, the proof is sketched in "Alegbra" by Dummit and Foote page 19.
Answer: We argue by induction on the number $n$ of factors, assuming, as we may, $n\ge4$.
By induction hypothesis, we know that, for $k < n$, any product of the factors $b_1,\dots,b_k$ taken in this order can be written unambiguously as $b_1\cdots b_k$.
Then a product of any given sequence $a_1,\dots,a_n$ is necessarily of the form
$$
c_k:=(a_1\cdots a_k)(a_{k+1}\cdots a_n)
$$
for some $k=2,\dots,n-1$, and we only need to check
$$
c_p=c_q\quad\forall\quad1 < p < q < n,
$$
which we do as follows:
$$
\begin{matrix}
&(a_1\cdots a_p)&(a_{p+1}\cdots a_q& a_{q+1}\cdots a_n)\\ \\
=&(a_1\cdots a_p)&((a_{p+1}\cdots a_q)&(a_{q+1}\cdots a_n))\\ \\
=&((a_1\cdots a_p)&(a_{p+1}\cdots a_q))&(a_{q+1}\cdots a_n)\\ \\
=&(a_1\cdots a_p&a_{p+1}\cdots a_q)&(a_{q+1}\cdots a_n).
\end{matrix}
$$
Answer: Here is a geometric version of a proof:
First, note that parenthecizings of a product of length n  are in bijection with triangulations of convex (n+1)-gon $A$. This is illustrated in the picture below, copied from p. 240 of the book "Discriminants, Resultants, and Multidimensional Determinants" of Gelfand Kapranov and Zelvinski.

In words, to go from triangulations of $A$ to  parenthecizings of $x_1x_2\ldots x_n$, label all but one edges of  $A$ in order as $x_1, x_2, \ldots, x_n$, leaving the last edge as "output edge". Then a triangulation of $A$ gives a parenthesizing in an inductive manner:  Take the triangle $T$  incident on the output edge; then $A$ with $T$ removed is a union of two polygons $A_l$ and $A_r$ (one of which could be degenerate, i.e. a segment), each of which is incidents on one "non-output" edge of $T$. Then assign to our triangulations the product of parenthecizings assigned to $A_l$ and $A_r$.
One can easily go back in a similarly inductive manner, by thinking of a parentecising $p$ as a product of two subparenthesizings $p_l$ and $p_r$, and correspondingly  getting the triangulation associated to $p$ by "inserting a triangle $T$" into the triangulations of smaller polygons associated to these $p_l$ and $p_r$.
Now that we have a geometric interpretation of parenthecizings, we can give geometric interpretation of single application of associativity law. This is known as a flip — in a given triangulation, one takes two triangles sharing an edge, thus forming a quadrilateral,  and replaces this edge with the other diagonal of this quadrilateral.
Thus the question becomes: can we connect any two triangulations of a convex polygon by a sequence of "diagonal flips"? The answer is yes, and again is best illustrated by a picture, this time stolen from page 7 of book "Triangulations" by Jesús A. De Loera, Jörg Rambau, and
Francisco Santos.

In words, pick any vertex  $i$ and make triangulation by drawing all diagonal from that vertex. To connect any triangulation to that "i-standard" one, make flips that increase the degree of $i$: as long as you are not at  "i-standard" triangulation, there exists a triangle $T$ with vertex $i$ and opposite edge not an edge of $A$ (but rather a diagonal); complete $T$ to a guadrilateral, and flip the diagonal.
This shows that "the graph of
flips of the triangulations of the n-gon" is connected (thus establishing what we want).
QED!
In fact much more is true. The graph of flips is just the union of 1 dimensional faces of a convex polytope, all of whose faces correspond to incomplete triangulations/incomplete parenthecisings, the one open face corresponding to incomplete triangulation with no triangles/incomplete parenthecising with no parenthesis.
What we proved is simply that one can get from any vertex of this polytope to any vertex by following some edges. This is of course true for any convex polytope (take the straight path and push it to faces of lower and lower dimension, for example by projecting "radially" from a point of the face not on the path; this is an easy version of cellular approximation theorem in algebraic topology).
The polytope in question is called an associahedron, or Stasheff polytope, and its existence follows from various direct constructions, notably it is constructed by Gelfand-Kapranov-Zelevinsky as the secondary polytope of a convex n-gone in the plane (this is described in the same book where the first picture came from).

On a related and more ridiculous note, existence of a permutohedron (secondary polytope of the prism $I\times \Delta^n$ on the simplex $\Delta^n$) shows that commutativity law allows one to write products of any number of elements in any order (this is equivalent to showing that the permutation group is generated by transpositions).
Comment: The polyhedra show up when one relaxes commutativity/associativity to their [homotopy versions](https://en.wikipedia.org/wiki/E%E2%88%9E-operad).
Answer: A more formal pedantic version of part a very small part of Mariano Suárez-Alvarez' answer.
Associativity is a property of multiplication, which is a binary operation. More precisely, multiplication is a map $m:R \times R \to R, (a,b) \mapsto m(a,b)=ab$.
The associative law says that (ab)c = a(bc). Using m, that is the same as m(m(a,b),c) = m(a,m(b,c)). (Note that m takes exactly two elements of $R$ as "input"). A consequence of the associative law is that there is no ambiguity in writing abc, since «no matter how you put the parentheses in, the result will be the same».
Edit:As Arturo writes in a comment below: "associativity is not a property of multiplication per se ([...] addition [is] associative [as is] composition of functions) but rather, a property that a binary operation may or may not have." Of course, Arturo's proof in his answer works for any associative binary operation.
Comment: Hmm. A *more formal version* would have been an actual proof that there is ambiguity.
Comment: Fair enough. I've edited accordingly.
Comment: @Bart: As long as you are editing, associativity is not a property of multiplication per se (isn't addition associative also? composition of functions?) but rather, a property that a binary operation may or may not have.
Comment: Of course you are right. I was actually debating whether to include something like that, but wasn't sure how helpful it would be.  I just wrote about multiplication because the OP mentions "product" and "multiplying."
Comment: @Mariano: In your comment, did you mean something like $3-(5-2) \neq (3-5)-2$, therefore $3-5-2$ is ambiguous without the _convention_ that we go from left to right, i.e. the convention that $3-5-2 = (3-5)-2$ ?
Comment: @Bart, @Mariano: Hope I'm not speaking out of turn, but I suspect Mariano meant to write "an actual proof that there is *no* ambiguity", as opposed to merely affirming "as a consequence, there is no ambiguity..."
Comment: What Arturo said.
Comment: @Arturo, @Mariano: I was not claiming to give a full answer (proof) to the OQ. My intent was merely to make somewhat more "formal" Mariano's statement (_That «one can drop the parentheses» really means that «no matter how you put the parentheses in, the result will be the same»_) in the case of three factors, by pointing out that because the multiplication is a binary operation, an expression like $abc$ is a priori not unambiguously defined. It seems I failed. Better luck next time.