Bass neck have a crack, following wood lines

Question: First a couple pictures:

I have a bass that has a crack on the neck. It looks like it follows the wood pattern, but since it's so clean, I think it's more glue related.
This happened after transport and, realistically, this bass has been used as a tool, and not a museum piece, for a long time so it's not like I'm totally surprised.
I am in a lockdown area, so there is no 'going to the music shop' right now.
I guess the truss rod, and maybe the fretboard, hold it together right now. I can push back against the crack and see it close, so it's definitely loose.
Does that mean I need to get a new neck? or can this eventually be glued by a repair shop?
Answer: It is where a join in the neck was made. Were it mine, I'd open it up gently to see how much it's become unglued. Being careful not to crack the fingerboard. There were quite a few guitars and basses made this way, not sure it was a brilliant idea, but a lot survive!
Anyway, open up, and it should be possible to get two part epoxy into the joint, just enough not splodging it everywhere. Then using card or such, with some plastic bag over the joint, use clamps to hold it together for a day. Obviously take the strings off first!
If that's not something you'd be happy with, a luthier will be able to repair it - at a cost. A new neck would be an option - at a cost, but fitting won't be a simple diy job - the poket needs to be a snug fit. For me, the glue option would be the best, (I've done many broken necks) but it rather depends on how much of a diy-er you are!
Comment: I'll try the glue option, I have no problem hacking things around when needed :) I was wondering about the shape because I could imagine it to take more work to make two pieces that fit like that, and glue the, than doing a more straight shape
Comment: Thing is, the two parts (theoretically) were made for each other initially, so *should* fit back together with some epoxy resin. That's what I've used on all repairs like this. Without looking closely, I can't tell, but if it was really bad (don't think this is) I'd consider drilling a couple of small holes and putting screws in - each side of the trussrod, and filling over the heads, but that's in desperate case It ought to fit back quite well, if not, you'll be doing some sanding too...
Comment: I managed to get the glue, which was a bit complicated since we're in a lockdown area.. will experiment soon! I'm expecting some will come out and so I may have to sand the neck a bit.
Comment: Clamp it as tight as possible, in a big vice if you can, and scrape off the excess adhesive as it squeezes. Good luck.
Answer: Also use masking tape all around the area of the crack so there's less to clean up. Maybe even lay it over the entire area and then cut the tape with a razor to expose the crack.


PHP Include File and If Then Else Statement, Include File Not Printing To Browser

Question: I am attempting to change my menus depending upon the url.
I have tried a couple of different things to no avail.
I have tried using php to call to the code on the page, (see the code below, I used this but rather than calling to the include file I was calling to the code itself on the page) and the result was a blank page in the browser.
Then I tried calling to the include files that I created with the menu code in it.
The menu itself, has some PHP in it and I think this may be why it is not working. I tried a simple call to the menu include file and the menu did not print out to the browser.
<?php include("/wp-content/themes/wslh/inc/i_menu-wohl.php"); ?>

It stopped printing out as soon as the menu php started, so when I did a view source there was only this:

<a

The php that came after that was:
<?php nav_active( 'about' ); ?> href="/about/">ABOUT
WSLH

And the rest of the menu code, which is really long so I will not put it here. The menu itself works fine hard coded on the page when I am not trying to include it for this if then statement:
<?php
$url = $_SERVER["REQUEST_URI"];
if (strpos($url, "/occupational/wohl/") === 0) {
echo '<?php include("/wp-content/themes/wslh/inc/i_menu-wohl.php"); ?>';
} else {
echo '<?php include("/wp-content/themes/wslh/inc/i_menu-wslh.php"); ?>';
}
?>

Can anyone assist me with this? I have created if then else statements using ASP and have never run into this issue.  Thank you in advance for your help. Please let me know if you have any questions or I have not given enough info.
Comment: are you including the wp libraries in that file you're generating? you'er trying to generate PHP code on the fly, meaning you have to generate EVERYTHING , including the appropriate `include()`/`require()` directives so that nav_active() is actually defined when the generated code executes.
Comment: @Marc B, this may be the issue, but I am not sure how to do it. What I was thought was that I could simply bring the menu code into the page using the include and that it would work because all that is different is that the menu code will change a little depending on which one is brought in via include. Looking at the header, I am not sure what I should be adding to the menu include file. I imagine what I am trying to do is probably quite simple, I just do not have the PHP experience yet.
Answer: Firstly, this code will not do anything useful:
echo '<?php include("/wp-content/themes/wslh/inc/i_menu-wohl.php"); ?>';

What that will do is echo, to the browser, a string of PHP code. The browser won't know what to do with it.
All you actually need is to include the PHP file itself, like this:
include "/wp-content/themes/wslh/inc/i_menu-wohl.php";

(Note: I've removed the brackets, because include is not actually a function, and it can lead to bugs if you start thinking of it as one.)
Next, if the output is suddenly stopping where some PHP code is trying to run, you're probably getting an error, but have errors set to be logged rather than display.
Check out this answer and the other information on that page to help track down what the error was. If you're still stuck after that, post a new question, with the part of the code that produces the error and the exact error message it produces.


Laravel forcing json response for api

Question: I'm building an api at my company using laravel.
The problem I'm encountering is that if you send an api request without defining the correct header with the request you will get html back if there is a failure e.g. authorization failure or findOrFail() failure.
My thinking is that you never want to return html (even if the user has the wrong header).
I have a couple of solutions.  In BeforeMiddleware.php I can manually insert a header into the request such as:
// Check if we are on an api route
$apiRoute   = strncmp($uri, '/api/', 5) == 0;

// Insert the request header to force json response
if ($apiRoute){
    $language = $request->header->add('Accept', 'application/json');
}

The 2nd solutions would be to throw an error if they don't have the correct header.
What would be the best way to enforce a json response, what is a good practice for handling api responses in laravel?
Comment: Similar question raised in this question https://stackoverflow.com/questions/36366727/how-do-you-force-a-json-response-on-every-response-in-laravel
Comment: The request accepts header is set by the client. You as the server should respect what the client sends. If this is for debugging you can just use something like [postman](https://www.getpostman.com/) and send the headers correctly from within there or implement some unit tests instead.
Comment: The browser will let you know what they accept in the accept header. If the browser doesn't accept JSON what's the point of giving it JSON?
Comment: Also probably easier to check the api route by doing something like `$apiRoute = $request->segment(1) == 'api';`
Comment: @apokryfos Can you elaborate on this? What do you mean by 'The browser will let you know'. Is there a setting I can set in laravel to say that what it accepts?
Comment: If you want to force it to return json you can do this: in Handler.php add this in the render method: if (strpos($prefix, 'api') !== false) {
            if ($exception instanceof ValidationException) {
                return response()->json(['success' => false, 'error' => $exception->errors(), 'data' => null], 200);
            }
            return response()->json(['success' => false, 'error' => $exception->getMessage(), 'data' => null], 200);
        }
Answer: Once you detected that you are on your api path you are out of the woods and can indeed tackle your problem in the app\Exceptions\Handler.php file like suggested on How do you force a JSON response on every response in Laravel?.
For an open source project I created JSON exception objects by Microsoft format as output, but you can choose the jsonapi format (http://jsonapi.org/examples/#error-objects-basics) as you like:
https://github.com/StadGent/laravel_site_opening-hours/blob/develop/app/Exceptions/Handler.php
(note that on this implementation it is indeed depending from the headers, but you can use your path detection I think)

Laravel forcing json response for api


Como trocar o código quando o visitante é mobile?

Question: Estou desenvolvendo um site, quero que quando o usuário entre pelo telefone o código mude, pode ser com js ou com html.
Exemplo (Visitante usando o Telefone):

Exemplo (Usando o PC):

Gostaria que alguém me ajudasse a fazer isso.
Comment: Só de curiosidade, qual o objetivo disso? Que ele abra a página do Facebook dentro do app no celular do Facebook?
Comment: é, quero que quando ele estiver em telefone abra o app, e quando estiver no pc abra o site
Comment: De uma olhada em Progressive Web Apps https://developers.google.com/web/progressive-web-apps/
Comment: eu quero algo mais simples... que não envolvo apis nem bibliotecas externas
Answer: Você pode detectar se o dispositivo é um celular usando a função abaixo:
function ehMovel(){
    if(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|ipad|iris|kindle|Android|Silk|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(navigator.userAgent)
    || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(navigator.userAgent.substr(0,4))){
        return true;
    }

    return false;
}

Exemplo funcional:

function ehMovel(){
    if(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|ipad|iris|kindle|Android|Silk|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(navigator.userAgent)
    || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(navigator.userAgent.substr(0,4))){
        return true;
    }

    return false;
}

document.querySelector("a").setAttribute('href', ehMovel() ? 'fb://page/1703826839873386' : 'https://www.facebook.com/' );
link
Comment: Rapaz, o link não funciona
Comment: @LeoCaracciolo testado e totalmente funcional. Testa nos simuladores de celular do navegador.
Comment: Como é que faz isso?
Comment: @LeoCaracciolo https://i.stack.imgur.com/PHZGM.jpg
Comment: huahuahua  blz, saquei.com
Answer: Com Javascript pegando largura ou altura da tela.
Neste exemplo se a largura for menor que 640 ou altura menor 480  é considerado mobile

//essa linha abaixo não é necessário para o funcionamento
console.log(screen.width);

if (screen.width < 640 || screen.height < 480) {
    document.write('mobile');
} else {
    document.write('desktop');
}

Coloquei links que aqui são permitidos abrir, na sua aplicação coloque seus links

desktop

mobile


Question analysis so amazing

Question:
How this process has been calculated in a manner added.
Comment: The mistake is already in the second step: $$4-\frac92\neq\sqrt{\left(4-\frac92\right)^2}$$ since $\;\sqrt{x^2}=|x|\;$ , and in this case $\;4-\frac 92<0\;$ .
Answer: Note that
$$4-\frac 92\not=\sqrt{\left(4-\frac 92\right)^2}$$
Answer: $$\sqrt{\left(4-\frac92\right)^2}=-\left(4-\frac92\right)$$
More generally for real $a,$  $$\sqrt{a^2}=|a|=\begin{cases} a &\mbox{if } a\ge0  \\ -a & \mbox{if } a<0\end{cases}$$

Question analysis so amazing


Conjugating by an upper triangular matrix does not change the diagonal entries.

Question: This post https://mathoverflow.net/questions/49679/a-matrix-similarity-problem makes the claim that conjugating by an upper triangular matrix does not change the diagonal entries.  But how do I prove this for all n x n matrices?
Also, what about the converse.  Suppose A,B,C are invertible matrices and $ABA^{-1} = C$ where $B$ and $C$ have the same diagonal.  Must it be the case that $A$ is triangular?
Answer: The linked Mathoverflow question doesn't claim that conjugation of any matrix by an upper triangular matrix preserves the diagonal, and such interpretation would be, in fact, not true.
On the other hand, conjugation of the identity matrix by any invertible matrix gives also the identity matrix. Not to say the zero matrix also gives zero matrices under any multiplications.
So, −1.
Answer: the considered result is true only if the first matrix is also triangular.


Chance of receiving all elements of a set

Question: I have a set of $n$ different elements. I will select $i$ times a subset $S_j$ of $n/k$ elements randomly. Each element can only occur once in each $S_j$, but can be part of multiple different subsets $S_j$. I want to know the probability of having all elements in the sum of the subsets.

My attempt:
This would be a possible outcome of what I want to do:
$n= 4$ | number of different items
$elements = \{ A,B,C,D \}$ | set of items
$k=2$ | nr. of elements per subset
$ i=3$ | nr. of subsets generated
$S_1=\{A,B\}$ | 1st random subset
$S_2=\{C,A\}$ | 2nd random subset
$S_3=\{B,A\}$ | 3rd random subset
$total = S_1 \cup S_2 \cup S_3 = \{A,B,C\}$ | all elements in at least 1 subset
I am looking for the probability $p(n,k,i)$ for the event "Each element from $elements$ is contained in $total$"
Comment: I'm confused what $i$ is used for. You have $i=i$ which may be a typo?
Comment: To anyone reading this: are the dollarsigns working? for me, and only here, they do not work.
Comment: First you say each subset has $n/k$ elements. Then you describe $k$ as "nr. of elements per subset". Which do you mean? (It doesn't help that $4/2=2$...)
Comment: Related problem, for $n = 52$ & $k = 2$ (?):  [What is the average number of draws (2 cards per draw with shuffles in between) before I had seen all 52 cards in the deck?](http://math.stackexchange.com/questions/1405184/what-is-the-average-number-of-draws-2-cards-per-draw-with-shuffles-in-between/)  As was noted there, this is a generalization of the coupon collector's problem;  the method I described there using Markov chains could also be adapted (though doing so in generality would be pretty hairy.)
Comment: Fixed i, sry for that and done some explaining, hope this makes it a bit clearer
Comment: I'm assuming that each subset has $n/k$ elements, which is an odd choice of definitions.  But if that was an error, that is, the OP wants random $k$-subsets, then $p(n,k,i)=q(n,k,i)$ in my answer below.
Answer: Fix a nonnegative integer $n$, an integer $m$ with $0\leq m\leq n$, and a nonnegative integer $l$.  Let $q(n,m,l)$ be the probability that the union of random $m$-subsets $S_r$, for $r\in[l]$ with $[l]:=\{1,2,\ldots,l\}$, of the set $[n]:=\{1,2,\ldots,n\}$ is precisely $[n]$, where the random sets are chosen uniformly randomly and statistically independently.  Observe that, if $k\in\mathbb{N}$ is a divisor of $n$ and $i$ is a positive integer, then $$p(n,k,i)=q\left(n,\frac{n}{k},i\right)\,.$$  The event $E_{A,r}$ denotes the event that $A\cap S_r=\emptyset$, for $A\subseteq [n]$ and $r\in[l]$.  The notation $\mathbb{P}$ denotes the probability measure.  Also, for $A\subseteq [n]$, the union $\bigcup\limits_{r=1}^l\,E_{A,r}$ will be written as $E_A$.  Observe that $E_{A}\cap E_{B}=E_{A\cup B}$ for any $A,B\subseteq[n]$.
First, it is evident that $$\mathbb{P}\left(E_{A,r}\right)=\frac{\binom{n-|A|}{m}}{\binom{n}{m}}=\prod_{\mu=1}^m\,\left(1-\frac{|A|}{n-\mu+1}\right)\,.$$
for all $A\subseteq [n]$ and $r\in[l]$.  Thus, by statistical independence,
$$\mathbb{P}\left(E_A\right)=\mathbb{P}\left(\bigcap_{r=1}^l\,E_{A,r}\right)=\prod_{r=1}^l\,\mathbb{P}\left(E_{A,r}\right)=\prod_{\mu=1}^m\,\left(1-\frac{|A|}{n-\mu+1}\right)^l\,.$$
Finally, using the Principle of Inclusion and Exclusion, along with the fact that $\mathbb{P}\left(E_A\right)=\mathbb{P}\left(E_B\right)$ if $A,B\subseteq[n]$ are equicardinal, we obtain
$$q(n,m,l)=1-\mathbb{P}\left(\bigcup_{j=1}^n\,E_{\{j\}}\right)=\sum_{\nu=0}^n\,(-1)^{\nu}\,\binom{n}{\nu}\,\prod_{\mu=1}^m\,\left(1-\frac{\nu}{n-\mu+1}\right)^l\,,$$
under the convention that $0^0=1$. For $l>0$, the formula above is also given by
$$q(n,m,l)=\sum_{\nu=0}^{n-m}\,(-1)^{\nu}\,\binom{n}{\nu}\,\prod_{\mu=1}^m\,\left(1-\frac{\nu}{n-\mu+1}\right)^l\,.$$
I do not think that there is a nice simplification of the expression above.
For examples, $q(n,m,0)=0$ $n>0$ and $q(n,n,l)=1$ for $l>0$, as well as $q(0,0,0)=1$.  If $ml<n$ holds, then $q(n,m,l)=0$.  Also, the answer to the OP's example is $$p(4,2,3)=q(4,2,3)=\frac{19}{36}\,.$$  Anyhow, there is a good approximation when $m\ll n$ (see the hidden portion for a proof):
$$q(n,m,l)\approx\Biggl(1-\left(1-\frac{1}{n}\right)^{ml}\Biggr)^n\,.$$
Below is a comparison between the actual plot (blue circles) and its approximation (red squares) with $n=10$ and $m=2$.

  Here is a probabilistic proof of the approximation.  If $m\ll n$, then we can well approximate the selections $S_1,S_2,\ldots,S_l$ by randomly choosing elements $X_{\sigma,\rho}$ with $\sigma=1,2,\ldots,m$ and $\rho=1,2,\ldots,l$ and setting $S_r:=\left\{X_{1,r},X_{2,r},\ldots,X_{m,r}\right\}$ (as $m\ll n$, the chance that $\left|S_r\right|<m$ is slim).  For each element $j$ of $[n]$, the probability that $j$ is not in the union $\bigcup\limits_{r=1}^l\,S_r$ is roughly $\left(1-\frac{1}{n}\right)^{ml}$ (that is, each of the $ml$ random elements $X_{\sigma,\rho}$ must not be equal to $j$).  Hence, the probability that $j$ is in the union $\bigcup\limits_{r=1}^l\,S_r$ is approximately $1-\left(1-\frac{1}{n}\right)^{ml}$.  Using the statistical independence, we conclude that the probability that $[n]=\bigcup\limits_{r=1}^l\,S_r$ is well approximated by $\Big(1-\left(1-\frac{1}{n}\right)^{ml}\Big)^n$.
Comment: The case $l=2$ has a closed form and which I posted.
Comment: It looks like there is another closed form. (+1).
Comment: @MarkoRiedel  They are the same answer, though, almost without any manipulation, as $$\prod_{\mu=1}^m\,\left(1-\frac{\nu}{n-\mu+1}\right)=\frac{\binom{n-\nu}{m}}{ \binom{n}{m} }\,.$$  I was hoping for some nice and concise formula.  But your algebraic solution is also great.
Answer: Remark, added  later. I somehow  missed the fact that  the formula
below  is the  same  as in  the  accepted post.   Maybe the  alternate
derivation  can  facilitate  understanding  of the  problem.  Text  of
original version follows.
Here is a different formula.  Building on the work by @Batominovski we
use the  notation $$q(n, m, l)$$  for the probability  in the scenario
with $n$ elements, subsets of size $m$ and $l$ samples.
Use the variable $A_\nu$ to represent the type $\nu$ from among the
$n$ available  types. The generating  function for the  $m$-subsets is
given by
$$[z^m] \prod_{\nu=1}^n (1 + zA_\nu).$$
It follows that  the generating function for the  $l$ samples is given
by
$$\left([z^m] \prod_{\nu=1}^n (1 + zA_\nu)\right)^l.$$
Now  we  are interested  in  those terms  that  contain  at least  one
instance  of the  $n$  types. Evaluating  the  generating function  at
$A_\nu=0$ and subtracting that value yields the generating function of
the  terms containing  at least  one $A_\nu.$  So we  do this  for all
$A_\nu.$ Note  however that we  have now removed terms  not containing
$A_\nu$ and $A_\mu$ two times, so we must add those back in and so on.
We have by Inclusion-Exclusion for the desired generating function
$$\sum_{S\subseteq A} (-1)^{|S|}
\left.\left([z^m]
\prod_{\nu=1}^n (1 + zA_\nu)\right)^l\right|_{S=0.}$$
Actually doing  the substitution  and setting the  elements of  $S$ to
zero produces  $k = |S|$ factors  that are equal to  one. Then setting
the  remaining $A_\nu$ to  one because  we are  not interested  in the
classification but rather the count  produces $n-k$ terms that are all
equal to $1+z.$ This yields for the inner term
$$[z^m] (1+z)^{n-k} = {n-k\choose m}$$
and for the probability
$$\bbox[5px,border:2px solid #00A000]{
{n\choose m}^{-l} \sum_{k=0}^n {n\choose k} (-1)^k
{n-k\choose m}^l.}$$
Sanity check. With just one sample we should get probability zero
for $m\lt n$ and probability one for $n=m.$ Setting $l=1$ we obtain
$${n\choose m}^{-1} \sum_{k=0}^n {n\choose k} (-1)^k [z^m] (1+z)^{n-k}
\\ = {n\choose m}^{-1}
[z^m] (1+z)^n \sum_{k=0}^n {n\choose k} (-1)^k \frac{1}{(1+z)^k}
\\ = {n\choose m}^{-1}
[z^m] (1+z)^n \left(1-\frac{1}{1+z}\right)^n
\\ = {n\choose m}^{-1} [z^m] z^n.$$
This is indeed zero when $m\lt n$ and one when $n=m.$
Here is the Maple code for comparison of the two formulae.

Q1 := (n,m,l) ->
add((-1)^nu*binomial(n, nu) *
    mul(1-nu/(n-mu+1),mu=1..m)^l, nu=0..n-m);

Q2 := (n,m,l) ->
binomial(n,m)^(-l) *
add(binomial(n,k)*(-1)^k*binomial(n-k,m)^l, k=0..n);

Addendum. We now compute a closed form for the case $l=2.$
We get for the sum term
$$\sum_{k=0}^n {n\choose k} (-1)^k
{n-k\choose m}^2.$$
Introducing
$${n-k\choose m} =
\frac{1}{2\pi i}
\int_{|z|=\epsilon} \frac{1}{z^{m+1}} (1+z)^{n-k} \;dz$$
we obtain for the sum
$$\frac{1}{2\pi i}
\int_{|z|=\epsilon} \frac{1}{z^{m+1}}
(1+z)^{n}
\frac{1}{2\pi i}
\int_{|w|=\gamma} \frac{1}{w^{m+1}}
(1+w)^{n}
\\ \times \sum_{k=0}^n {n\choose k} (-1)^k
\frac{1}{(1+z)^k (1+w)^k}
\; dw \;dz
\\ = \frac{1}{2\pi i}
\int_{|z|=\epsilon} \frac{1}{z^{m+1}}
(1+z)^{n}
\frac{1}{2\pi i}
\int_{|w|=\gamma} \frac{1}{w^{m+1}}
(1+w)^{n}
\\ \times \left(1-\frac{1}{(1+z)(1+w)}\right)^n
\; dw \;dz
\\ = \frac{1}{2\pi i}
\int_{|z|=\epsilon} \frac{1}{z^{m+1}}
\frac{1}{2\pi i}
\int_{|w|=\gamma} \frac{1}{w^{m+1}}
(z+w+wz)^n
\; dw \;dz.$$
Extracting the inner coefficient produces
$$\frac{1}{2\pi i}
\int_{|z|=\epsilon} \frac{1}{z^{m+1}}
{n\choose m} (1+z)^m z^{n-m}
\;dz
\\ = {n\choose m}  \frac{1}{2\pi i}
\int_{|z|=\epsilon} \frac{1}{z^{2m-n+1}}
(1+z)^m
\;dz
\\ = {n\choose m} {m\choose 2m-n}.$$
This yields for the probability
$$q(n, m, 2) = {n\choose m}^{-1} {m\choose n-m}.$$
Comment: Thank you! These two formulae have a certain aesthetic appeal as well.
Comment: Nice answer! (+1)


Botão não aparece

Question:

a {
color: #fff;
text-decoration: none;
background-color: #007bff;
padding: 10px;
display: block;
width: 250px;
border-radius: 4px;
-webkit-text-decoration-skip: objects;
 }
 a:hover{
  background-color: #0f58a7;
  text-decoration: none;
  color: #fff;
 }
  PROSSEGUIR

Tenho esse botão, que deveria aparecer assim: http://prntscr.com/n54rd9
Mas por algum motivo que eu não consegui identificar, o botão não aparece para algumas pessoas que acessam a pagina. Haveria algo que possa ser feito para identificar o motivo disso acontecer? Em todos os navegador das pessoas que tem esse problema, nunca aparece...então não deve ser o navegador bloqueando algo.
Comment: 1º - Cadê o código de estilo CSS? Coloque o código CSS que formata o botão para que possamos ver. 2º - O botão não aparece para algumas pessoas ou aparece para você e para os outros não?
Comment: Acabei de adicionar o CSS ao post. Sobre a segunda pargunta, ele aparece para mim e diversas outras pessoas, cerca de 90%, mas para algumas pessoas ele não aparece de forma alguma.
Answer: O que provavelmente etá acontecendo é que vc está usando a versão SVG do FontAwesome. O FontAwesome tem uma versão que usa webfonte e uma versão mais nova que usa SVG. Porém se o browser do usuário não der suporte ao SVG e a forma como os métodos do JS do framework trabalha a fonte não aparece... Como vc pode ver na imagem abaixo retirada do site oficial: https://fontawesome.com/start
A versão em webfont é: https://use.fontawesome.com/releases/v5.8.1/css/all.css
A versão em SVG é: https://use.fontawesome.com/releases/v5.8.1/js/all.js
Confirme se vc está usando a versão .JS ou .CSS

Lista de suporte dos Browsers
https://fontawesome.com/how-to-use/on-the-web/other-topics/browser-support
Comment: @RafaelMacedo infelizmente acho que não vai resolver, apesar de eu recomendar sim que vc atualiza para versão mais nova! Essa atualização da v5.0 para v5.8, são alguns recursos extras e ajustes de alguns icones etc... Como vc já usa a versão .CSS do FW, não sei te dizer exatamente pq não aparece para alguns, além é claro da questão do suporte do Browser como falei e vc pode ver na imagem. Outro motivo menos provável é que essas pessoas por questão de segurança bloqueiam o acesso ao `href` de sites fora do domínio ou fora do *white list*...
Comment: Entendi, mas obrigado de qualquer forma.
Comment: Estou usando esta versão: http://prntscr.com/n58h9g (.css)
Nesta versão: v5.0.12
E a que você mandou ja é a 5.8.1. Será que atualizando para essa 5.8.1 ja resolve?

Botão não aparece


Sencha 2.0 App file size issue -

Question: I have developed a small Sencha Touch 2.0 app. Here is the url:
http://apps.swarnendude.com/sencha/iphonetest/iphoneTest.html?url=http://apps.innofied.com/sencha/gts
The app works in perfectly fine in Android 2.3, iPad, iPhone, Blackberry Playbook. But the app crashes while I test in Blackberry Torch (OS: 6.0) giving this error:
"The page you requested could not be loaded. It is too large for this device"
The production version of the file sizes are:
sencha-touch.js: 90.5Kb
app-all.js: 401.4Kb
app-all.css: 151.5Kb
Other resources: 10Kb
So, total around 650Kb. I think the sizes can be reduced more but I am not getting any other options. I am using the least css configs in SASS file and in JS too (only which are required). Is there anyone getting the same problem? Any solution?
Answer: It seems that you attempted to minimize your app, so in this case, there's not much you could do.
I'm using Blackberry Bold and occasionally see this when I use native browser. But in some cases, Opera Mini and Bolt Browser are good suggestions to pass those errors.

Sencha 2.0 App file size issue -


Migration from CSV: how to define a default value for autoincremental id field?

Question: I run migrations from CSV using Migrate Source CSV, Migrate Plus and Migrate Tools modules and it works fine.
The result of one of these migration is a custom entity which key is a 'id' field that has the 'AUTO_INCREMENT' property in the database.
Here is my migration_contractssubscriptions.yaml
id: migration_contractssubscriptions
migration_group: null
label: 'Contract Subscriptions migration from CSV'
source:
  plugin: csv
  path: /mypathto/migration_ContractsSubscriptions.csv
  delimiter: ';'
  enclosure: '"'
  header_row_count: 1
  keys:
    - id
process:
  id: id
  contract_id: contract_id
  member_id: member_id
  sharedwith_member_id: sharedwith_member_id
  comment: comment
  quantity01: quantity01
  quantity02: quantity02
  quantity03: quantity03
  quantity04: quantity04
  owner_id:
    plugin: default_value
    default_value: 1
destination:
  plugin: 'entity:contract_subscription'

I'd like to get rid of 'id' in my csv file and let the migration process handle the value of the resulting id.
I tried to remove keys: - id and id: id but I get an error...
How can I achieve that?
Comment: I assume `id` is the primary key of your custom entity, so simply removing `process: id: id` should work. Do not remove or change fields from `source: keys:` in production - Migrate's internal mapping table would get out of sync. If you change the source keys, rollback and drop the mapping table first. Look for `migrate_map_FOOBAR` tables in your DB.
Comment: Once removed `id: id` from `process:` I have this error:
`[error]  La migration a échoué avec l'exception de plugin source : id is defined as a source ID but has no value.`
Answer: I finally understood that keys in source is the way to make each row of the csv file unique. It may be anything.
So I changed to:
  keys:
    - contract_id
    - member_id

I removed id: idfrom processand it works!
The value of id field in the database is properly auto-incremented.
Comment: how do you deal with the required source:ids key then ?
Comment: I'm not sure to understand your question :-( As said in the answer, the source keys is made with `contract_id` and `member_id`.
Comment: I had an error saying that the ids key was required but not given. But it may be caused by something else as your code works today. ty


Is it possible to upgrade nokia lumia 510 to windows phone8

Question: I have nokialumia510,
is it possible to upgrade it to wp8, so that i need to test my app which i have developed in wp8 sdk.
Thanks.
Answer: It's not possible to upgrade any Windows Phone to Windows Phone 8. Your Lumia 510 only can be upgraded to Windows Phone 7.8.
WP8 is a new platform not related with old Windows Phone 7. If you want to test your app you must buy a new devide with WP8 installed.


Navigation bar back button text is not changing

Question: I am trying to change the text of the navigation bar back button text. I have tried the solutions offered here but I cant get the text I want on back button. In appdelegate I set these features:
 [[UINavigationBar appearance] setBarTintColor:[self colorWithHexString:@"e74c3c"]];
 [[UINavigationBar appearance] setBarTintColor:[self colorWithHexString:@"e74c3c"]];

[[UINavigationBar appearance] setTitleTextAttributes:
 [NSDictionary dictionaryWithObjectsAndKeys:
  [UIColor whiteColor], UITextAttributeTextColor,
  [UIFont fontWithName:@"Futura-CondensedMedium" size:19.0], UITextAttributeFont,nil]];

NSShadow *shadow = [[NSShadow alloc] init];
shadow.shadowOffset = CGSizeMake(0.0, 1.0);
shadow.shadowColor = [UIColor whiteColor];

[[UIBarButtonItem appearanceWhenContainedIn:[UINavigationBar class], nil]
 setTitleTextAttributes:
 @{NSForegroundColorAttributeName:[UIColor whiteColor],
   NSShadowAttributeName:shadow,
   NSFontAttributeName:[UIFont fontWithName:@"Futura-CondensedMedium" size:19.0]
   }
 forState:UIControlStateNormal];

[[UINavigationBar appearance] setTintColor:[UIColor whiteColor]];

And in every viewcontroller's viewdidload I set:
self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"SomeText" style:UIBarButtonItemStylePlain target:nil action:nil];

or
UIBarButtonItem *newBackButton =
        [[UIBarButtonItem alloc] initWithTitle:@"NewTitle"
                                         style:UIBarButtonItemStyleBordered
                                        target:nil
                                        action:nil];
[[self navigationItem] setBackBarButtonItem:newBackButton];

Any suggestions?
Answer: If I haven't misunderstood you you can do this to set the title of the back button. Suppose there are three view controllers: A, B and C. Now you want the title of the back button to be "MyViewA" when you navigate from A to B then you need to put this code in "viewWillAppear:" of your ViewController A (this will show the title of the back button as "MyViewA" when you are on view controller B).
 //viewWillAppear of ViewController A
 -(void)viewWillAppear:(BOOL)animated{

       //now set title of back button
       self.navigationItem.backBarButtonItem =
       [[UIBarButtonItem alloc] initWithTitle:@"YourTitle"
                                  style:UIBarButtonItemStyleBordered
                                 target:nil
                                 action:nil];
 }

Likewise if you are navigating from B to C and want to set the back button title for ViewController C, you need to put the above code in "viewWillAppear:" delegate of ViewController B. In short you need to set the title of the next view controller on your current view controller.
Answer: You can't change the value of the text in the backbutton. You have to set the button as the left or right barButtonItem (probably left if you want it as back button) like this:
[self.navigationItem setLeftBarButtonItem:newBackButton];

you can then attach an IBAction to the button by setting it when you init your button:
UIBarButtonItem *newBackButton =
    [[UIBarButtonItem alloc] initWithTitle:@"NewTitle"
                                     style:UIBarButtonItemStyleBordered
                                    target:nil
                                    action:yourBackFunction];

at least that would be a workaround and I have also used it before...
Answer: The back button belongs to the previous view controller, not the one currently presented on screen.
To modify the back button you should update it before pushing, on the view controller that initiated the segue:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Delete back item title in next controller
    UIBarButtonItem *newBackButton =
    [[UIBarButtonItem alloc] initWithTitle:@"New Title"
                                     style:UIBarButtonItemStylePlain
                                    target:nil
                                    action:nil];
    [[self navigationItem] setBackBarButtonItem:newBackButton];
}


How can I add a cancel button to the content add form for a single content type?

Question: I have several content types on a site and most of them are user-editable but not user-creatable.  However, one content type, Image, allows users to upload a picture.  Sometimes, however, users upload the wrong picture and they panic because they don't want that picture to be submitted to the site.
Of course they could always hit the browser's back button, but I'd like to add a Cancel button for additional assurance.
I found this thread that gives various solutions for adding cancel buttons on Drupal.org as well as this feature request for adding a cancel button to D8.  However, there are several different general approaches and I don't know how to limit one to a given content type (in this case, my_image).
Comment: There's a module for that!: http://drupal.org/project/nodeformsettings
... and this module is really fantastic. It's worth to check out.
Answer: I would use the following code.
function mymodule_form_my_image_node_form_alter(&$form, &$form_state) {
  // If the node is being created, redirect the users to the page where
  // they can choose the content type for a new node; otherwise, redirect
  // them to the page showing the node.
  $destination = (!isset($node->nid) || isset($node->is_new)) ? 'node/add' : "node/{$node->nid}";

  $form['actions']['cancel'] = array(
    '#markup' => l(t('Cancel'), $destination),
    '#weight' => 20,
  );
}

Notes

markup is the default form element type; there is no need to use #type = 'markup'.
In the node edit form, all the buttons are inside $form['actions']. The weights used from the buttons that form is using are 5 (Save), 10 (Preview), and 15 (Delete). I used 20 to show the link after those buttons, but you can change its weight to show it in a different position.
// Add the buttons.
$form['actions'] = array('#type' => 'actions');
$form['actions']['submit'] = array(
  '#type' => 'submit',
  '#access' => variable_get('node_preview_' . $node->type, DRUPAL_OPTIONAL) != DRUPAL_REQUIRED || (!form_get_errors() && isset($form_state['node_preview'])),
  '#value' => t('Save'),
  '#weight' => 5,
  '#submit' => array('node_form_submit'),
);
$form['actions']['preview'] = array(
  '#access' => variable_get('node_preview_' . $node->type, DRUPAL_OPTIONAL) != DRUPAL_DISABLED,
  '#type' => 'submit',
  '#value' => t('Preview'),
  '#weight' => 10,
  '#submit' => array('node_form_build_preview'),
);
if (!empty($node->nid) && node_access('delete', $node)) {
  $form['actions']['delete'] = array(
    '#type' => 'submit',
    '#value' => t('Delete'),
    '#weight' => 15,
    '#submit' => array('node_form_delete_submit'),
  );
}

There isn't the need to use arg() to understand if the form is for editing an existing node, or for creating a new one. I checked !isset($node->nid) || isset($node->is_new) is TRUE, to verify the node is being created. Drupal seems to simply check empty($node->nid), even though node_object_prepare() uses !isset($node->nid) || isset($node->is_new).
If $_GET['destination'] is set, the link added with l() will point to that path.
Comment: should we have to add the details in the `hook_menu()` when altering a node form(form adding a content type)
Answer: Each node form has its own unique id. It's consisted of node type's machine name followed by _node_form. So your my_image node type's form id is my_image_node_form
Here's a mock untested function (D6) to illustrate how to implement:
function HOOK_form_alter(&$form, &$form_state, $form_id) {
  $types = array(
    'my_image',
  );

  foreach($types as $type) {
    if($type.'_node_form' == $form_id) {
      if(arg(1) == 'add') {
        // If adding node link to node/add screen
        $link = l(t('Cancel'), 'node/add');
      }
      elseif(arg(2) == 'edit') {
        // If editing node, link to node view screen
        $link = l(t('Cancel'), 'node/'.arg(1));
      }
      $form['cancel'] = array(
        '#type' => 'markup',
        '#value' => $link,
        '#weight' => 0,
      );
    }
  }
}

If using Drupal 7 then change #value on the array to #markup.
Comment: I added this function to my custom module, replaced HOOK with my module's name, changed `my_image` to the machine name of my content type, saved, and cleared the cache twice, but, although Drupal outputs no error, I also don't get a cancel button.  I know you said it's untested code, but I'm unable to figure out what's wrong with this.
Comment: Are you using Drupal 6 or 7? If Drupal 7 then change `#value` on the array to `#markup`
Answer: All those solutions are for adding Cancel link not a button!
If you want to add the button instead of a link you should use this code for module cancel_button.module:
function cancel_button_form_alter(&$form, &$form_state, $form_id) {
    // node types for which Cancel button should be added
    $types = array(
      'biography',
      'faq',
      'draftlaw',
      'vocabulary',
      'draftlaw_page',
      'encyclopedia',
      'user', // if you want to add user's edit form too
    );

    foreach($types as $type) {
        if($type.'_node_form' == $form_id || $type.'_profile_form' == $form_id) {
            $form['actions']['cancel'] = array(
                '#type'   => 'submit',
                '#value'  => t('Cancel'),
                '#access' => TRUE,
                '#weight' => 55,
                '#submit' => array('cancel_button_form_cancel', 'node_form_submit_build_node'),
                '#limit_validation_errors' => array(),
                );
            }
        }
    }

    /**
     * cancel_button callback.
     */
    function cancel_button_form_cancel($form, &$form_state) {
        $link = '';
        $path = 'node';
        if('user_profile_form' == $form['#form_id']){
            $path = 'user';
        }
        if(arg(1) == 'add') {
            // If adding entity link to [user|node]/add screen
            $link = $path . '/add';
        }
        elseif(arg(2) == 'edit') {
            // If editing entity, link to node view screen
            $link = $path . '/' . arg(1);
        }
        $url = $_GET['destination'] ? $_GET['destination'] : $link;
        drupal_goto($url);
    }

Comment: Arguably, as "Cancel" is an action with no side effects (it's "idempotent") it should really be a link and not a button. Buttons (certainly in Drupal) typically submit forms via POST, which is intended for non-idempotent requests, so even if the end result is to do nothing they still fire up the server, defeat caches, add to logs etc. Links can always be styled as buttons for consistency.
Comment: The link was good enough for me, because I am using CSS to style my buttons anyway, and the link can be styled to look exactly the same way.
Comment: Good. My problem was the same, but with a button. So, maybe someone else likes my solution.
Comment: what's with the `node_form_submit_build_node`?
Comment: Sounds reasonable!
Answer: function mymodule_form_my_image_node_form_alter(&$form, &$form_state) {
  // If the node is being created, redirect the users to the page where
  // they can choose the content type for a new node; otherwise, redirect
  // them to the page showing the node.
  $destination = (!isset($node->nid) || isset($node->is_new)) ? 'node/add' : "node/{$node->nid}";

  $form['actions']['cancel'] = array(
    '#markup' => l(t('Cancel'), $destination),
    '#weight' => 20,
  );
}


Modifying CKEditor toolbar at runtime

Question: We have a requirement that our standard CKEditor toolbar omit a specific button on only one content type. It seems silly to create a brand new text format just for this. I'm able to modify the toolbar via a hook, but the modification gets saved and applied everywhere.
How can I programmatically modify the toolbar for just that content type?
Comment: Why exactly is it silly to create a separate Text Format for a specific use case? This is exactly why the capability to create new things through the UI exists. The Drupal way is always configuration over customization.
Comment: Because we need a default toolbar and this new one which is the same minus one button. By creating two text formats, any changes we would need in the future will need to be applied in two different places, vs my ideal solution of taking whatever the current toolbar is and removing the button we don't want
Answer: I think you will have to do this at the CKEditor level.  See:
https://ckeditor.com/docs/ckeditor4/latest/guide/dev_configuration.html#defining-configuration-in-page
On the Drupal side, this JS could be added by altering the content type edit form to add the JS.
Comment: Thanks CG. Any idea how it'd work if the use case was actually a different Paragraph type? So same content type, but if user adds Paragraph type A they get default toolbar, but f user adds Paragraph type B, they get modified toolbar. Thanks

Modifying CKEditor toolbar at runtime


Blocks with reference to self and instance vars

Question: What's the correct way to reference 'self' (and ivars) within blocks without the block creating a strong reference (and thus incrementing the ref count)?
For instance, I've found the following increments the ref count for 'self':
^(id sender) {
    [self.navigationController popViewControllerAnimated:YES];
}

In order to circumvent the above, I've been doing the following:
__weak WhateverController *weakSelf = self;
^(id sender) {
    [weakSelf.navigationController popViewControllerAnimated:YES];
};

And yes, I realize this is pseudocode.
Answer: Also, an indirect reference to self also creates a retain on self.  For example, if _ivar were an instance variable, accessing it is an implicit reference to self so the following would also retain self.
^(id sender) {
    [_ivar popViewControllerAnimated:YES];
}

Furthermore, to expand on your weak example, it is OK to send a message to a weak reference.  If it's nil, nothing will happen.  If not, then the compiler will generate code that ensures the reference remains valid through the invocation of the method.
So, this is fine:
__weak Foo *weakSelf = self;
^(id sender) {
    [weakSelf.foo doSomething];
}

because foo will either be nil or if not, it is guaranteed to remain non-nil throughout the execution of doSomething.
However, the following would be inadvisable because self could go to nil in-between calls, which is probably not what you want:
__weak Foo *weakSelf = self;
^(id sender) {
    [weakSelf.foo doSomething];
    [weakSelf.foo doSomethingElse];
}

In that case, you probably want to create your own strong reference inside the block, so you have a consistent value throughout the execution of the block.
On the other hand, if you access iVars directly through a weak reference, you must do the weak-strong dance because this code:
__weak Foo *weakSelf = self;
^(id sender) {
    weakSelf->_foo = bar;
}

will blow up if weakSelf is nil.
Thus, in the last two situations above, you want to do something like:
__weak Foo *weakSelf = self;
^(id sender) {
    Foo *strongSelf = weakSelf;
    if (!strongSelf) return;
    // Now, do anything with strongSelf, as it is guaranteed to be around
}

Of course, the iVar situation is only a problem if you actually access iVars directly...
Comment: In your second example, I think you mean `[weakSelf.foo doSomething]; [weakSelf.foo doSomethingElse];`
Answer: Apple's notation is sself but other than that - you're fine.
In a non arc project use the following code to prevent 'self' from being retained by the block:
__block id sself = self


Web Applications under Apache Tomcat with multiple directory contexts

Question: I have two webapps, prod-1.2.1.war and test-2.0.0.war.
If I put these straight into the "tomcat/webapps"-folder, they'll get deployed as;

hXXp://localhost/prod-1.2.1/
hXXp://localhost/test-2.0.0/

This works but really I would like them to show up as;

hXXp://localhost/vegshop/prod/
hXXp://localhost/vegshop/test/

As you see I somehow would like the "vegshop" to be included in the context path.
I also would like the version-numbering to disappear without having to rename the WAR-files.
Thank you.
This is Apache Tomcat v6.0 under Linux 2.6, running SUN JDK 1.6.
Answer: You can't include the include the /vegshop/ part in the URL like you want with Tomcat.  Webapps are not mere files that can be placed where ever one wants.   With Tomcat,  /vegshop/ is either:

a discrete webapp
a folder under the ROOT webapp (the default, if there is no webapp.

The best you can do is something like be renaming your .war files.  E.g. prod-1.2.1.war to  vegshop-prod.war

http://localhost/vegshop/
http://localhost/vegshop-test/

If this /vegshop/prod/ thing is really, really important to you, then the only option I would consider is to proxy Tomcat with a web server (like Apache httpd) and rewrite the URLs.  There might even be a way to code something wild with Tomcat, but all of this feels over the top for such a cosmetic change.  Is it really that important?


Print custom user fields

Question: I want to display a custom field, and i've done it with this code
<?php
 global $user;

 $user_fields = user_load($user->uid);

 $customfield = $user_fields->field_navnn['und']['0']['value'];

 print  t("Custom field value is " . $customfield. ' ') ;
?>

but it dosn't show when im logged out.
Thanks
Answer: You are using the global variable $user which represents the logged-in user.

An object representing the user currently visiting the site.
Contains preferences and other account information for logged-in
  users. When a user is not logged-in, the $user->uid property is set to
  0.

You could use the user id from the URL on the user profile page by calling arg(1).
Here is the possible fix for your code:
<?php
 $uid = arg(1);

 $user_fields = user_load($uid);

 $customfield = $user_fields->field_navnn['und']['0']['value'];

 print  t("Custom field value is " . $customfield. ' ') ;
?>

I do not concern with your user profile template. This is just for your code fix.
Comment: Awesome it also worked for my other problem thanks
Answer: That is because you are doing:
      global $user;

and loading the fields of user which will load fields of only logged in user.
If you are printing it on user profile , then you can directly do the following in your user-profile.tpl.php.
  $customfield = $field_navnn[0]['value'];

and then print it.
Comment: I've done this

but now it just gives me an error
Notice: Undefined variable: field_navnn in include() (line 67 of /home/www/modeindeks.com/sites/all/themes/modeindeks/templates/page--user.tpl.php).

Am i doing something wrong?
Comment: After you define `global $user` put a condition `if ( $user->uid)` { } , then only do other actions inside braces . This will solve your error message.
Comment: And if you printing name of currently logged in user, how would you expect it to be printed when user has logged out ?? :)
Comment: I'm pretty new to all this can you please give an example
Comment: Yes I will but before that Can you explain me more about what exactly you are trying to achieve ?
Comment: I want to print the name so when anonymous user visit the page they can see that field.
Every client has a user page, and on that page the field will be displayed in an  tag so it need to make that viewable by anonymous users, how can i achieve this?
Comment: let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/6801/discussion-between-sandesh-yadav-and-myrevenge)
Comment: I think you should create on template file `user-profile.tpl.php` in your themes/templates folder. And then `$customfield = $field_navnn[0]['value'];` and print it there. Can you please try this and let me know if it is workin. And dont foget to clear the cache after creating user-profile.tpl.php.
Comment: Yes lets du that

Print custom user fields


How can you set breakpoints in IDEA that are recognized by Chrome while using Gulp?

Question: I'd like to be able to set a breakpoint in javascript while using Intellij IDEA, but have it recognized by chrome's devtools. We are using gulp for our development web server. Is there a way to make it so that chrome recognizes the breakpoint I set in my IDE? Presuming yes please provide all of the steps required to do that.
Answer: If you type debugger; in your code chrome should stop at that point.


How to center labels inside a C3.js piechart

Question: The labels inside each piechart arc are at the edge. I want to make the text bigger using css (.c3-arcs text selector), but the text gets cut off. Is there a way to make the labels centered within each arc?
Here's a jsbin demo
Comment: That will be tricky actually to manipulate with css as they are rendered within the SVG draw...
Comment: @Pogrindis Is there another way besides css? I've been going through their docs, but unable to find any option to modify these positions.
Comment: it seems they use `d3.format()` method for this, but there doesn't seem to be any 'out of the box' solution to your question..
Answer: Coworker came up with a solution using text-anchor, which isn't perfect, but moves the labels closer to center.

<code>.c3-chart-arcs text {
    text-anchor: start !important;
}

.c3-target-Large text {
    text-anchor: end !important;
}
</code>
Updated jsbin


Variance of $x + \xi(x)$, where $\xi(x) \sim \operatorname{Bin}(x, p)$.

Question: Let $y = x + \xi(x)$m where $\xi \sim \operatorname{Bin}(x,p)$. We want to calculate $\operatorname{Var}(y) = \mathbb{E}(\operatorname{Var}(x + \xi(x)|x)) + \operatorname{Var}(\mathbb{E}(x + \xi(x) | x))$.
The second term is easy-calculated: $\operatorname{Var}(\mathbb{E}(x + \xi(x) | x)) = \operatorname{Var}(x + xp) = (1+p)^2 \mathbb{E}(x)$.
But the first one is more complicated: $\mathbb{E}(\operatorname{Var}(x + \xi(x) | x)) = \mathbb{E}(x^2 + 2\mathbb{E}(x\xi(x)|x) + xpq + x^2 p^2 - (1 +p)^2 x^2))$.
The key problem is $\mathbb{E}(x\xi(x)|x)$. Does there any chance to calculate it fast?
Answer: The key observation is that the variance of $x + \xi(x) \mid x$ is the same as the variance of $\xi(x) \mid x$ because the variance is conditioned on $x$, which only affects the location, and not the variance.
So you would have $$\operatorname{Var}[x + \xi(x) \mid x] = xpq,$$ and its expectation is $pq \operatorname{E}[x]$.

I should also point out that you have an error in your computation:  it should be $$\operatorname{Var}[\operatorname{E}[x + \xi(x) \mid x]] = \operatorname{Var}[x + xp] = (1+p)^2 \color{red}{ \operatorname{Var}}[x].$$


How can I check if an element exists in array of objects using lodash

Question: Suppose I have the following array:
var users = [
    {id: 3, name: "sally"}
    {id: 5, name: "bob"}
    {id: 40, name: "joe"}
    {id: 67, name: "eve"}
    {id: 168, name: "bob"}
    {id: 269, name: "amanda"}
]

I need to run a loadash function that would return true if, for example name == "bob" exists in the array regardless of how many times it exists in the array.
I would like to know is if there is one function I could use, possible using lodash (not necessarily though) that would return true or false indicating the existence of an object in the target array.
Thanks
Comment: This is very unclear.  The title for instance says "get true *or* false", the question only says "return true".  Given the array you provide, what is the output you expect?   I'm probably not going out on a limb saying you will probably want to use either `map`  or `filter`.  If you just want to know if "bob" is in the array whatsoever, `some` will work (or `_.find`)
Comment: In lodash `_.find(users, ['name', 'Bob"]);`
Comment: Using native JS: `var test = users.some(u => u.name === "bob");`.
Comment: @user3808307 See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some
Comment: Using lodash: `var test = _.some(users, ["name", "bob"]);`.
Comment: You're welcome! I've added a lodash way too. I recommend you use lodash's version as you are already using it.
Comment: @George Jempty I only need it to return true. I guess find is the correct answer.
Comment: Thank you @ibrahim mahrir! I guess some is better than find. That is exactly what I was looking for
Answer: You can use the filter function to search through your array and find the object with the given name.
var users = [
    {id: 3, name: "sally"},
    {id: 5, name: "bob"},
    {id: 40, name: "joe"},
    {id: 67, name: "eve"},
    {id: 168, name: "bob"},
    {id: 269, name: "amanda"},
];

function find(name) {
    return !!users.find(x => x.name === name);
}

More about the filter function can be found here
Comment: you could add a bit explanation
Comment: @entio explain a bit further please
Comment: @entio i misunderstood your comment, added a link and basic explanation


Change td data using jquery slider on scroll

Question: I have to display a table as 5x5 grid. But the data which I have as json data can have more than 5 columns of data.
Using jquery slider, how to change the data of the table > td based on the slider scroll.
i have the following json object:
var tData = [
    ["R1C1","R1C2","R1C3","R1C4","R1C5","R1C6","R1C7","R1C8","R1C9"],
    ["R2C1","R2C2","R2C3","R2C4","R2C5","R2C6","R2C7","R2C8","R2C9"],
    ["R3C1","R3C2","R3C3","R3C4","R3C5","R3C6","R3C7","R3C8","R3C9"],
    ["R4C1","R4C2","R4C3","R4C4","R4C5","R4C6","R4C7","R4C8","R4C9"],
    ["R5C1","R5C2","R5C3","R5C4","R5C5","R5C6","R5C7","R5C8","R5C9"]
];

by default the data looks like the below table.
 _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ __
| R1C1 | R1C2 | R1C3 | R1C4 | R1C5 |
|_ _ _ | _ _ _ _ _ _ | _ _ _|_ _ _ |
| R2C1 | R2C2 | R2C3 | R2C4 | R2C5 |
|_ _ _ | _ _ _ _ _ _ | _ _ _|_ _ _ |
| R3C1 | R3C2 | R3C3 | R3C4 | R3C5 |
|_ _ _ | _ _ _ _ _ _ | _ _ _|_ _ _ |
| R4C1 | R4C2 | R4C3 | R4C4 | R4C5 |
|_ _ _ | _ _ _ _ _ _ | _ _ _|_ _ _ |
| R5C1 | R5C2 | R5C3 | R5C4 | R5C5 |
|_ _ _ | _ _ _ _ _ _ | _ _ _|_ _ __|

on the slider scroll, the data has to be changed like the below.
 _ _ _ _ _ _ _ _ _ _ _ _ _ __ _ _ _
| R1C2 | R1C3 | R1C4 | R1C5 | R1C6 |
| _ _ _|_ _ _ | _ _ _|_ _ _ |_ _ _ |
| R2C2 | R2C3 | R2C4 | R2C5 | R2C6 |
| _ _ _|_ _ _ | _ _ _|_ _ _ |_ _ _ |
| R3C2 | R3C3 | R3C4 | R3C5 | R3C6 |
| _ _ _|_ _ _ | _ _ _|_ _ _ |_ _ _ |
| R4C2 | R4C3 | R4C4 | R4C5 | R4C6 |
| _ _ _|_ _ _ | _ _ _|_ _ _ |_ _ _ |
| R5C2 | R5C3 | R5C4 | R5C5 | R5C6 |
| _ _ _|_ _ _ | _ _ _|_ _ __|_ _ _ |

and on the next scroll it will change like,
 _ _ _ _ _ _ _ _ _ __ _ _ _ _ _ _ _
| R1C3 | R1C4 | R1C5 | R1C6 | R1C7 |
|_ _ _ | _ _ _|_ _ _ |_ _ _ | _ _ _|
| R2C3 | R2C4 | R2C5 | R2C6 | R2C7 |
|_ _ _ | _ _ _|_ _ _ |_ _ _ | _ _ _|
| R3C3 | R3C4 | R3C5 | R3C6 | R3C7 |
|_ _ _ | _ _ _|_ _ _ |_ _ _ | _ _ _|
| R4C3 | R4C4 | R4C5 | R4C6 | R4C7 |
|_ _ _ | _ _ _|_ _ _ |_ _ _ | _ _ _|
| R5C3 | R5C4 | R5C5 | R5C6 | R5C7 |
|_ _ _ | _ _ _|_ _ __|_ _ _ | _ _ _|

Could you please suggest how to do this using jquery and slider?
Answer: You can do this in more than one way: shifting the table inside a div that makes use of overflow, adding and removing data to and from the table, or what I opted for, showing and hiding specific columns.
HTML

CSS
.datatable {
  border-collapse: collapse;
  margin: .5em 1em;
}

.datatable tbody {
  font-family: Arial, sans-serif;
}

.datatable tbody tr td {
  border: 1px solid #ccc;
  padding: .2em .4em;
}

td.hide {
  display: none;
}

#slider {
  width: 280px;
  margin: 0 1em;
}

JavaScript
var tData = [
  ["R1C1", "R1C2", "R1C3", "R1C4", "R1C5", "R1C6", "R1C7", "R1C8", "R1C9"],
  ["R2C1", "R2C2", "R2C3", "R2C4", "R2C5", "R2C6", "R2C7", "R2C8", "R2C9"],
  ["R3C1", "R3C2", "R3C3", "R3C4", "R3C5", "R3C6", "R3C7", "R3C8", "R3C9"],
  ["R4C1", "R4C2", "R4C3", "R4C4", "R4C5", "R4C6", "R4C7", "R4C8", "R4C9"],
  ["R5C1", "R5C2", "R5C3", "R5C4", "R5C5", "R5C6", "R5C7", "R5C8", "R5C9"]
];

$(function() {
  var $t = $("#table-1");
  var maxCol = 5;
  var cell = 0;
  // Populate the table
  $.each(tData, function(k1, v1) {
    // Create Rows
    var $row = $("
", {
      id: "row-" + (k1 + 1),
      class: "row"
    });
    $.each(v1, function(k2, v2) {
      if (k2 < maxCol) {
        $("", {
          class: "show col col-" + (k2 + 1),
          id: "cell-" + cell++
        }).html(v2).appendTo($row);
      } else {
        $("", {
          class: "hide col col-" + (k2 + 1),
          id: "cell-" + cell++
        }).html(v2).appendTo($row);
      }
    });
    $row.appendTo($t);
  });

  $("#slider").slider({
    min: 0,
    max: tData[0].length - maxCol,
    value: 0,
    slide: function(e, ui) {
      var i = ui.value + 1;
      var m = ui.value + maxCol;
      // Hide all
      $(".show").toggleClass("show hide");
      // Show just specific columns based on slider value
      for (i; i <= m; i++) {
        $(".col-" + i).removeClass("hide").addClass("show");
      }
    }
  });
});

Working Example: https://jsfiddle.net/Twisty/3osy7fvh/
Comment: Slider example vs using Overflow: https://jsfiddle.net/Twisty/3osy7fvh/12/
Comment: Dude. Excellent. I will try to fine tune little bit similar to jqGrid. Instead of hiding the td, those td's data has to be replaced. If you have time, kindly go through the jqGrid paramquery. While there are more number of columns, during the slider dragging, there is a delay in rendering the data. It has been overcome in jqGrid.


Sub-Select com MAX / SUM / INNER JOIN?

Question: Preciso fazer um SUM dentro de um MAX para retornar o maior faturamento do produto dentro de uma sumarização.
Consegui fazendo isso:
SELECT MAX(Faturamento) MAX_Faturamento
FROM (SELECT SUM(P.preco * I.qtde) Faturamento
    FROM produto P
    INNER JOIN itens I ON P.cod_prod = I.cod_prod
    GROUP BY P.descricao) AS tabela_aux;

Porém também preciso trazer a descrição do produto, somente do produto que teve o maior faturamento. Tentei usando isso:
SELECT Descricao, MAX(Faturamento) MAX_Faturamento
FROM (SELECT P.descricao, SUM(P.preco * I.qtde) Faturamento
    FROM produto P INNER JOIN itens I ON P.cod_prod = I.cod_prod
    GROUP BY P.descricao) AS tabela_aux
GROUP BY Descricao;`

Porém ele me retorna todos os registros e eu preciso somente do que teve o maior faturamento.
Comment: MAX ORDER BY SUM DESC LIMIT , tente algo assim
Answer: Obrigado, Motta! Consegui usando as ferramentas que você me proporcionou. Ficou mais ou menos assim:
'SELECT Descricao, MAX(Faturamento) Faturamento FROM (SELECT SUM(P.preco * I.qtde) Faturamento, P.descricao FROM produto P INNER JOIN itens I ON P.cod_prod = I.cod_prod GROUP BY P.descricao) AS tab_aux GROUP BY Descricao ORDER BY Faturamento DESC LIMIT 1;'

Comment: marque sua resposta como correta ;)

Sub-Select com MAX / SUM / INNER JOIN?


Number of ways to get a flush from shuffled cards

Question: How many different ways are there to draw a flush from a well shuffled full deck of cards?
If correctly counting, I suppose the answer is $\frac{13\times 12\times 11 \times 10 \times 9}{1\times 2 \times 3 \times 4 \times 5}$, but would like to know your thoughts on it.
Comment: Cf. https://en.wikipedia.org/wiki/Poker_probability
Comment: Add the totals of royal flush, straight flush and non-royal/straight flush in the link (since all three cases are disjoint).
Comment: See the columns "Frequency" and "Mathematical expression of absolute frequency".
Comment: But what exactly is the number of ways to choose any flush from shuffled cards?
Comment: Should we sum straight flush, or not? Since cards are not the same suit?
Comment: "A straight flush is a hand that contains five cards of sequential rank, **all of the same suit.**" From the same link
Comment: Yeah I also agree on that definition. I just saw the picture and guessed it is sth. wrong
Answer: You can select $5$ cards from a suit in $\binom{13}5$ ways, and since there are $4$ suits, multiply it by $4$, which you did not.
Comment: Oh I see, I added up "straight" cards as well. Yes, it is absolutely correct! Thank you
Comment: So, the answer is $\binom{13}{5} x 4$, right?
Comment: Yes, it is the same value you would end up getting if you were to add the totals of royal, straight and non-royal/straight flush in the link in the comments.
Comment: But according to previous post, we have to sum up all straight, royal, and non-royal/straight flushes to get the answer, which seems to be higher than you proposed one.
Comment: @AnarRzayev Are you sure you are adding the values correctly? $\binom41+\left[\binom{10}1\binom41-\binom41\right]+\left[\binom{13}5\binom41-\binom{10}1\binom41\right]=\binom{13}5\binom41$


C# - TransactionScope outside of a using block?

Question: The query I have is a little more complex than the title lets on. Perhaps this is a foolish question, but I couldn't find any certain answer when searching online. Currently, I'm implementing the Repository/Unit-of-Work pattern in my own flavor and it looks a little like this:
// Note: methods are async for conventions, not because
// they're truly async
public interface IUnitOfWork
{
    Task Begin();

    // The Task<int> is the numbers of rows affected by this commit
    Task<int> Commit();

    Task Rollback();
}

The repository can more or less be expressed as such:
public interface IWriteableRepository<T>
    where T : class
{
     EntityEntry<T> Insert(T item);

     // Other CRUD methods removed for brevity; they're
     // of similar signatures
}

The idea is that an IUnitOfWork will hold some TransactionScope instance internally and handle the respective logic.
I then have two concerns. First, if each IUnitOfWork and IWriteableRepository<T> instance is injected with different instances of a DbContext (I'm using EntityFrameworkCore for the time being), will calling DbContext.BeginTransactionAsync() produce a transaction scope for both in the following code?
await this.UnitOfWork.Begin();

this.Repository.Insert(someEntity);

var rows = await this.UnitOfWork.Commit();

In other words, does the repository only operate on the transaction created in the call to Begin(), or will it operate completely independently?
The second concern I have is in relation to implementing the IUnitOfWork interface. My approach thus far has been roughly
public class UnitOfWork : IUnitOfWork
{
    public UnitOfWork(DbContext context)
    {
        this.Context = context;
    }

    private DbContext Context { get; set; }

    private TransactionScope Transaction { get; set; }

    public async Task Begin()
    {
        if (this.Scope == null)
        {
            this.Transaction = await this.Context
                .Database
                .BeginTransactionAsync();
        }
    }

    public async Task<int> Commit()
    {
        if (this.Scope != null)
        {
            var rows = await this.Context.SaveChangesAsync(false);

            this.Scope.Commit();

            this.Context.AcceptAllChanges();

            return rows;
        }
    }

    public Task Rollback()
    {
        if (this.Scope != null)
        {
            this.Scope.Rollback();
            this.Scope.Dispose();

            this.Scope = null;
        }

        return Task.CompletedTask;
    }
}

I'm mostly unsure whether the Rollback() method could be improved. I feel like disposing the object explicitly isn't correct. Is there any other way that I should go about handling getting rid of a TransactionScope?
Comment: If you are using entity framework, my honest opinion is you should ditch the repository pattern and Unit of work all together, save your self a maintenance nightmare hiding simple logic behind mystical abstraction layers.  EF already implements these designs and patterns for you. Additionally if you are just wanting to roll back DB transactions, use the more modern TransactionBegin in EF. There is really no good going to come form your approach other than having to redesign it all in the future.
Comment: May be helpful: https://stackoverflow.com/a/51781877/5779732
Answer: In my case, this is the solution I've come up with - I would definitely not recommend following it and I'm sure there are catches that my team will have to solve when they come up...
Because we require multiple database engines (Mongo and EF/SQL), we've wrapped our interactions with the database in the repository and unit-of-work pattern. All our repositories are implemented per-database-engine, e.g., IMongoRepository<T> : IWriteableRepository<T>, and the methods that cannot be abstracted by IWriteableRepository<T> implemented by IMongoRepository<T>. This works out rather well and I don't mind using this pattern.
IUnitOfWork is also implemented per-database-engine because Mongo, SQL, etc. will handle transactions differently. The concern about contexts being shared while maintaining injectable objects has been solved by using a factory, i.e., something like
public class FooService
{
    public FooService(
        IUnitOfWorkFactory<EntityFrameworkUnitOfWork> factory,
        IRepositoryContext context,
        IWriteableRepository<Bar> repository)
    {
        this.UnitOfWorkFactory = factory;
        this.Context = context;
        this.Repository = repository;
    }

    private IUnitOfWorkFactory<EntityFrameworkUnitOfWork> UnitOfWorkFactory { get; set; }

    private IRepositoryContext Context { get; set; }

    private IWriteableRepository<Bar> Repository { get; set; }

    public bool RemoveBar(int baz)
    {
        // IUnitOfWorkFactory<T>.Begin(IRepositoryContext)
        //     where T : IUnitOfWork, new()
        //
        // 1) Creates a new IUnitOfWork instance by calling parameterless constructor
        // 2) Call UseContext(IRepositoryContext) on UoW, passing in the context;
        //        This causes the UoW to use the passed-in context
        // 3) Calls .Begin() on the UoW
        // 4) Returns the UoW
        using (var unitOfWork = this.UnitOfWorkFactory.Begin(this.Context))
        {
            var bar = this.Repository
                .Query()
                .First(x => x.Baz == baz);

            this.Repository.Remove(bar);

            var (success, rows) = unitOfWork.Commit();

            return success && rows > 0;
        }
    }
}

The EntityFrameworkUnitOfWork (or any IUnitOfWork) is allowed to implement Begin, Commit, and Rollback however it wants. IUnitOfWork also implements IDisposable to ensure the underlying transaction objects get cleaned up. Using the same context also ensures that transactions will surely apply to the repositories using that context.
Additionally, an IUnitOfWork instead of a factory could be passed in if it has checks to ensure that it only has one transaction open at a time; but, to remove this coupling to the implementation, we've created a factory instead. Not only does this ensure that we have only one transaction each using block, we're given the ability to have a using block without touching the constructor for an IUnitOfWork in our consuming code.
As a disclaimer, I whole-heartedly agree that you should not wrap ORM's in repositories. It will muddy up your DB code and add unnecessary complications. We are using these repositories in an effort to make our database interactions agnostic when doing simple things. Otherwise we get more specific in our repository implementations, removing a lot of the magic that other repository pattern implementations suffer from. Generally, once methods get beyond individual-record operations, the database engines and drivers have different ideas how to go about it.
A final note: it may be obvious that if you inject a repository that doesn't fit with the context you inject (e.g., IMongoContext and a IEntityFrameworkRepository<Bar>) your code won't not be run in transactions with the database. The reason this isn't a concern is

using a different context than the one in your repository is already nonsensical in most cases
you must manage the context and repository in the consuming code, and thus will be aware of conflicting contexts


Given a victory condition and a set strategy, what are the chances of winning on a given turn in a game of Magic: The Gathering?

Question: Tl;DR:  You have winning cards. To win, you must be able to play those cards, and have them in your hand. Your hand is randomly drawn. When might you win? How could find the answer to this (very complex) problem?
(I realize that my question isn't very formal, but I'm not exactly sure how to correctly pose the question. Feel free to edit. Also, draw3cards or Boards & Games don't like math questions)
The decklist
(If you know  magic, you should skip the next section, and probably the one after that, too)
Basic Rules

You have a 60-card deck, which has just been shuffled.
At the beginning of the game, you draw 7 cards. From then on, each turn you draw one card.
All cards except lands require mana to play. Mana is drawn from your mana pool. A land card on the field can be tapped (used) to add a mana of a color to your mana pool. (Mana either has a color, or is uncolored. Islands for blue mana, Swamps for black).
Colored mana can always be turned into uncolored mana.
Each turn, you may put no more than one land from your hand onto the field. It can immediately be tapped for mana.

Combo explanation

You have your Myr. As the decklist shows, you have Silver and Leaden myr, which can be tapped for Blue or Black mana, respectively. They cost two mana each, of any color.
In the same vein, Alloy Myr grants one mana of any color, and Palladium Myr grants two uncolored mana
You also have the Myr Galvanizer. For one mana and being tapped, it untaps all other Myr.
If you have one Galvanizer, and your mana-myr can be tapped for more than one, you can get an extra mana
If you have two Galvanizers, and your mana-myr can be tapped for more than one, you can have infinite mana
If you have infinite mana, you can win with Exsanguinate (which requires two black mana - so if you have two Galvanizers and a Palladium Myr, but only one swamp, you can't win with Exsanguinate)
...or you could win with Blue Sun's Zenith, which requires 3 blue mana. It can also be useful without infinite mana, since it allows you to draw cards (one card for every mana of any color you pay beyond 3 blue)
You also have three shapeshifters - Cackling Image (one mana of any color, two blue mana), Cryptoplasm (same), and Evil Twin (two uncolored, one black, one blue). All of these can make a copy of a creature on the field
You also have Diabolic Tutor, which gives you any card you want for two black mana, two uncolored mana
The other cards are irrelevant.

Question
Given that you try to get mana-myr on the field first, what chances are there of winning on what turn? I realize that this is a very tricky question that probably involves quite a bit of work, so an explication of how to get an answer is almost as good an answer itself.
Also really useful would be a generalization of this.
For extra points, ideas about finding the optimal number of each card (keeping the irrelevant defensive cards, and no more than 70 cards) would be very appreciated.
Comment: The best way to answer such a question is probably through simulation.  Write a computer program that implements such a strategy, run it with a large number of randomly shuffled decks, and count what fraction result in a win.  It will probably be quite difficult to produce an exact value for the probability, and even more difficult to get one in closed form.
Comment: Is there a way that you can generalize your question (say, "I have 60 cards with 7 X's, 10 Y's, 30 Z's, and the rest irrelevant. What are the odds that...?")? This would help you get a better understanding of any solutions given, and would probably help those who would answer.
Comment: @TheChaz: Part of my question (as I state in the parentheses) is how to generalize this. I guess I'll edit it to make this more obvious, however. Several people tell me that a big part of answering questions is posing them well, and that's part of what I'd like help with.
Comment: @NateEldredge: I was really hoping for a strict definition, because that would be faster to calculate, and far more interesting, then a plain simulation. However, the idea of at least getting an approximate method would be very nice. If I don't get that, I'll write a simulator.
Comment: I think this question is off-topic here, as it deals too much with the particulars of M:TG.
Comment: @AustinMohr: It would be more off-topic in any Boards & Games (or draw3cards), since the question itself is about math. I could of used meaningless identifiers, but I think that would be just made it harder to understand.
Comment: If you are concerned about making the question hard to understand, it's hard to imagine it could any more obscure for this site than it already is. I am already baffled by the third "basic rule".
Comment: @KCd: Is this better?
Comment: I would be surprised if there aren't decent/excellent MtG simulators out there already. If there aren't, I'll have to talk to some iOS developers :) (@NateEldredge, since you mentioned simulation)
Comment: @TheChaz: Perhaps. There's definitely a playtesting utility, although that requires human participation.
Comment: You say you have a Diabolic Tutor but I don't see it on the decklist. You don't mention Forbidden Alchemy but it's relevant as a tutor.
Comment: @Charles: I kinda gave up on this question, and started improving my deck independently. The decklist has changed quite a bit since I asked this question.
Answer: This question is almost certainly impossible to answer precisely, because Magic the Gathering can simulate an arbitrary Turing machine.  In particular, there is a small but non-zero probability that randomly chosen hands will force the players into an infinite loop that cannot be predicted even with complete information.
Comment: A turing machine couldn't happen, since I don't have the mentioned cards (and my opponent is assumed to do nothing but discard cards). How could the game reach an infinite loop?
Answer: I'm not sure this question is possible to answer at this time. Similarly to the fact that the number of winnable solitaire games is not known, there are some problems with this question. Maybe I can explain a little some difficulties with an answer.
1) Since you're going to win the game using one of several specific combinations, it is perhaps not so difficult to determine the probability of drawing the cards needed for any one given combination in a set number of turns. By the time the last card is drawn, you have completed the combination. However, I am not sure you can write down a way to express that as you are working on combination (a), you pull enough cards that it now becomes favorable to work on combination (b) instead.
2) M:TG is not as straight forward as "draw one card per turn until you have sufficient cards to win." The order you play these cards will matter, and since you only get 20 life, you have to keep yourself afloat with whatever defenses you have available until then. Although I'm not familiar with these cards in particular, I highly doubt any of them reads "give up x number of y mana, you win the game." So, in short, you have to go through n turns to gather the cards, and, assuming you can play them as soon as you get them without losing them, defend them until the combination wears down your opponent. This brings me to the third issue.
3) Your opponent exists. I know that sounds snarky, but you have only two options as for how to go about playing your Exodia combination.
a) Play nothing but lands and mana giving cards until you can lay down your whole combo at once. This is obviously bad - you'll just die before you get them out, or have low chances of surviving.
OR
b) Play the cards as you go (or in some collection of short bursts, i.e. maybe two at a time). In this case though, you also have to consider that there are now probabilties of drawing/having any defensive cards needed to stop your opponent from killing your combo before you get it out. In this case, we would have to know the content of the other person's deck to calculate the probability in this case.
I guess what I'm getting at is, even though it is obvious from elementary probability that such a value exists, it has too many factors to be computed by hand. You would be best off running a simulation of all possible ways the cards can be drawn in both yours and your foe's deck, and estimate the probabilities this way instead. This is how we approximate the number of games of Solitaire that can be won, and that game is much simpler, with only 52 cards instead of two 60 card decks.
Hope that helps.
Comment: This assuming that your opponnent does nothing.
Comment: I am OP. The question was assuming that the other player does nothing.
Comment: If you have to assume your opponent does nothing, then it's not a very good deck :P.
Comment: You are correct, and I am silly.


Issue installing Microsoft Azure Storage Library for PHP via composer

Question: we are trying to install Microsoft Azure Storage Library for PHP but getting some weird errors which we googled and it returned nothing, here is what we did

Cloned the repo from github
composer install (see image for error)

here is what we got as result of that(for seo purpose or in case image is not loaded correctly)
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - theseer/phpdox 0.8.1.1 requires ext-xsl * -> the requested PHP extension xsl is missing from your system.
    - theseer/phpdox 0.8.1 requires ext-xsl * -> the requested PHP extension xsl is missing from your system.
    - theseer/phpdox 0.8.0 requires ext-xsl * -> the requested PHP extension xsl is missing from your system.
    - Installation request for theseer/phpdox ~0.8 -> satisfiable by theseer/phpdox[0.8.0, 0.8.1, 0.8.1.1].

  To enable extensions, verify that they are enabled in those .ini files:
    - /etc/php5/cli/php.ini
    - /etc/php5/cli/conf.d/05-opcache.ini
    - /etc/php5/cli/conf.d/10-pdo.ini
    - /etc/php5/cli/conf.d/20-curl.ini
    - /etc/php5/cli/conf.d/20-gd.ini
    - /etc/php5/cli/conf.d/20-json.ini
    - /etc/php5/cli/conf.d/20-mysql.ini
    - /etc/php5/cli/conf.d/20-mysqli.ini
    - /etc/php5/cli/conf.d/20-pdo_mysql.ini
    - /etc/php5/cli/conf.d/20-readline.ini
  You can also run `php --ini` inside terminal to see which files are used by PHP in CLI mode.

After this as instructed we ran php --ini

here is the exact output(for seo or image not loaded properly)
Configuration File (php.ini) Path: /etc/php5/cli
Loaded Configuration File:         /etc/php5/cli/php.ini
Scan for additional .ini files in: /etc/php5/cli/conf.d
Additional .ini files parsed:      /etc/php5/cli/conf.d/05-opcache.ini,
/etc/php5/cli/conf.d/10-pdo.ini,
/etc/php5/cli/conf.d/20-curl.ini,
/etc/php5/cli/conf.d/20-gd.ini,
/etc/php5/cli/conf.d/20-json.ini,
/etc/php5/cli/conf.d/20-mysql.ini,
/etc/php5/cli/conf.d/20-mysqli.ini,
/etc/php5/cli/conf.d/20-pdo_mysql.ini,
/etc/php5/cli/conf.d/20-readline.ini

Now according to our assumption, required extensions are there but we are unable to find what exactly is the problem.
Comment: According your error message, the dependency requires `xsl` extension, but which you haven't installed or enabled in your PHP runtime. Can you make sure you have enabled the `xsl` extension in your PHP runtime?
Comment: @GaryLiu-MSFT i got overwhelmed by those errors that i ignored `the requested PHP extension xsl is missing from your system` this line, thanks mate for pointing out
Answer: Ok so all those errors have one hidden line in them the requested PHP extension xsl is missing from your system which i somehow didn't see due to the size of this error, in case you are struggling, here is what you should do

check if xsl is enabled by typing in your command line php -m
now this is going to give huge list, make sure if xsl is there, if not follow step 2
If xsl is not enabled / installed type this command sudo apt-get insitall php5-xsl and after that make sure it is enabled by typing php -m

hope it will save your six hours :)


Environment variable to change cipher for openssl

Question: I want to use a particular cipher for a HTTPS connection. The client (phantomjs) statically links openssl. The only way to do it is using environment variables, as there are no command line arguments for doing it.
Does anyone know of the environment variable that can cause a particular cipher to be used? SSL_CIPHER doesnt seem to work.
Comment: PhantomJS has the `--ssl-ciphers` command line argument - how come this isn't sufficient?
Comment: Tried it. Doesnt seem to have any effect.
Answer: You can specify ciphers in the OpenSSL config file (usually /etc/ssl/openssl.cfn).
Look for a string like CipherString = DEFAULT@SECLEVEL=2 in the [system_default_sect] section and change it as you need.
P.S. If there's no such a string or even section you can add it by yourself. In Debian 10 this section looks like:
[system_default_sect]
MinProtocol = TLSv1.2
CipherString = DEFAULT@SECLEVEL=2


Convex Homotopy

Question: Suppose $f , g : X \to U \subset \mathbb R^2$ are two mappings from a topological space $X$ to a convex set $U$.
Prove that $f$ and $g$ are homotopic, using only the definition of the product mapping.
Here, I get the homotopy to be $(1-t)f(x) + t g(x)$, but I am not able to prove the continuity of this mapping.
Answer: The function $$H:[0,1]\times \mathbb{R}^2 \to\mathbb{R}^2 $$ defined $$f(t,u.v)= (1-t) u +tv$$ is continuous and hence the composition $$H(t, f(x) ,g(x))$$ is also continuous.
Comment: ...did you read the question? OP already found this homotopy, but wasn't able to prove that it is continuous (something you asserted without proof).
Answer: @Scar,
Notice that the convex set $U \subset \mathbb{R}^2$ is contractible. This means that there is only one element in the homotopy equivalence class $[X,U]$.
To prove this, let $f,g \in [X,U]$. Then, by contractibility of $U$, there exists some homotopy $H: U \times I \to U$ that is the homotopy from the identity map in $U$ to a constant loop in $U$. But now we can define a homotopy $F: X \times I \to U$ defined by $F(x,t) = H(f(x), 2t), \space t \in [0, 1/2]$ and $F(x,t) = H(g(x), 2-2t), \space t \in [1/2, 1]$. Notice that $F(x, t) = H(f(x),1) = c = H(g(x), 1)$ at $t = [1/2]$, where $c$ is the constant loop in $U$. So $F$ is continuous by the Pasting Lemma, and defines a homotopy between the maps $f,g : X \to U$

Convex Homotopy


How do I set Symfony's env to prod via Scalingo's dashboard?

Question: Description:
I attempted to deploy my symfony project on Scalingo, and got an error saying that

[RuntimeException]
  An error occurred when executing the "'cache:clear --no-warmup'"
  command:
  PHP Fatal error:  Uncaught
  Symfony\Component\Debug\Exception\ClassNotFoundException: Attempted to
  load class "SensioGeneratorBundle" from namespace
  "Sensio\Bundle\GeneratorBundle".
  Did you forget a "use" statement for another namespace? in
  /build/205190f5c7174087665005026b4d9f8d/app/AppKernel.php:29

According to the scalingo devs, it's because I need to:

You can update this variable via the dashboard:
  https://my.scalingo.com/apps/websurg/variables or by using our
  CLI : 'scalingo -a websurg env-set SYMFONY_ENV=prod'

I'd like to do this via the dashboard, but unsure how it works.
Question:
How do I set Symfony's env to prod via Scalingo's dashboard?
Answer: The SYMFONY_ENV variable is just a normal environment variable (like the ones you are using on linux).
To set it on your scalingo dashboard, click on your app, then go to "Environment" and in the text area add SYMFONY_ENV=prod to the other environment variables.
Then you'll need to click on the Update button and

re-deploy your application (if this variable is needed for the deployment)

or

just restart your application (if this variable is needed for the runtime).


finding the slope of a line connecting two given Terminal points

Question: Say that Point X is the terminal point of Angle $\alpha$  and Point Y is the terminal point of $\beta$ on the unit circle.
"Terminal point", in this case, is the point that is obtained by rotating counterclockwise from point (1,0) on the unit circle.
Point X is in the first quadrant. Point Y is in the second quadrant.
$\tan \alpha = 1$ and $\tan \beta = -7$. Find the slope of $\overline{XY}$.
What I have so far:
$\alpha$ is $\frac{\pi}{4}$. since cos x = the x coordinate of the terminal point, would I have to find $cos \frac{\pi}{4}$ to get $\frac{\sqrt{2}}{2}$?
I am not sure what $\beta$ is in reduced terms because doing $arc tan(-7)$ results in -1.4288999... but finding the cos of that is $\frac{1}{5\sqrt{2}}$ (or is it $-\frac{1}{5\sqrt{2}}$?).
I am assuming that they both will have the same y coordinate, so would the slope be $\frac{\sqrt{2}}{2} + \frac{1}{5\sqrt{2}} = \frac{3\sqrt{2}}{5}$?
Comment: As it stands, this question doesn't make sense. I need to have particular points $X$ and $Y$ on the respective terminal sides of the angles in order to have a well-defined $\overline{XY}$.
Comment: Point $Y$ is in the second quadrant, I think (what's about $B$ ?). Moreover the slope of a line, not of a point $\dots$
Comment: @TonyPiccolo The slope of XY, so what I was referring to was if there were $X=(x_1, y_1)$ and $Y=(x_2, y_2)$, the slope would be $\frac{(y_2)-(y_1)}{(x_2)-(x_1)}$
Comment: Sure and the abscissa of $Y$ is negative.
Comment: @TonyPiccolo abscissa? the x coordinate of the terminal point Y?
Comment: Yes. I used that name to avoid confusion.
Comment: @TonyPiccolo ah, ok. is $\frac{3\sqrt{2}}{5}$ correct?
Comment: How did you get that value ?
Comment: @TonyPiccolo see above in my original post
Comment: @TonyPiccolo nevermind, it's incorrect. do you see any mistakes in my original post?
Comment: Upload a picture can clear things up a bit. I suspect that X and Y are on the circumference of the same (probably the unit) circle.
Comment: @Mick: Ted helped me with the problem in the chat, the misunderstanding was in what I meant by "terminal point", which in this case, is the point that is rotated counterclockwise from point (1,0) on the unit circle.
Comment: what exactly does "Point $X$ is the terminal point of $\alpha$" mean? What is $\alpha$?
Comment: Good. That is exactly what I have guessed.
Comment: @robjohn: $\alpha$ is the angle in the unit circle.
Comment: @MathyPerson: so $X$ is the point on the unit circle with angle $\alpha$: $(\cos(\alpha),\sin(\alpha))$ and $Y=(\cos(\beta),\sin(\beta))$? That is not clear from the question.
Comment: @robjohn: Yes, that is correct. I will edit my op to avoid further confusion.
Comment: In any case the system $$\begin {cases} a^2+b^2=1 \\ \\ \dfrac ba=k \end {cases}$$ has two solutions $(a,b)$. Choose the right one for $k=1$ and $k=-7$.
Answer: Since $X$ and $Y$ are on the unit circle, we have
$$
X=(\cos(\alpha),\sin(\alpha))
$$
and
$$
Y=(\cos(\beta),\sin(\beta))
$$
The slope of $\overline{XY}$ would be
$$
\frac{\sin(\beta)-\sin(\alpha)}{\cos(\beta)-\cos(\alpha)}
$$
Since $\tan^2(x)+1=\sec^2(x)=\frac1{\cos^2(x)}$, we have
$$
\cos(x)=\frac{\pm1}{\sqrt{1+\tan^2(x)}}
$$
Also $\sin(x)=\tan(x)\cos(x)$. Therefore,
$$
\sin(x)=\frac{\pm\tan(x)}{\sqrt{1+\tan^2(x)}}
$$
The choice of $\pm$ depends on the quadrant. Use $+$ in quadrants I and IV and $-$ in quadrants II and III.
Answer: The secant ( not tangent) joining X and Y intersects x-axis at an angle $ > \pi/2 $ but $ < \pi $ in second quadrant in an anti-clockwise direction.  Hence its tangent should be negative. The angular bisector of these directions is perpendicular to this secant line.The bisector makes $ (\alpha + \beta )/2 $ to x-axis.
$$ slope = \tan ( \pi/2 +(\alpha + \beta )/2) = -\cot ((\alpha + \beta )/2) $$
To further simplify use tan of half angle with Trig formula of double angle $(\alpha + \beta ) $ on right hand side:
$$ tan\, x = \dfrac {(1 - cos\, 2 x)}{sin\, 2 x} $$
to take it further from there.


como faço para montar um select com dois campos usando colletivehtml no laravel 5.5?

Question: Boa tarde.
Eu uso o laravel 5.5 e para formulários eu uso o laravelcollective.
Eu monto um select desta forma:
$locals = Local::get()->pluck('codigolocal', 'id');
e o resultado é um select com o value = id e descrição igual ao código.
Meu problema é que preciso mostrar além do código, também a descrição:
Algo como $locals = Local::get()->pluck(['codigolocal','descricaolocal'], 'id');
Tem como fazer isto?
Obrigado.
Comment: Qual é o banco?
Comment: Uso o mysql 5.6
Answer: Faça com o comando CONCAT do MySQL para unir os campos e com o método selectRaw do Builder Eloquent para escrever um select igual a esse:
Local::selectRaw("id'CONCAT(codigolocal,' ',descricaolocal) as n")->pluck('n','id');

Outros exemplos:

Extensão de função no laravel
Concatenar campos em uma string
UTILIZANDO CONCAT NO MYSQL

Referencias:

12.5 String Functions
Builder
Database: Query Builder
Comment: Ok. MAS FUNCIONOU OK. Fiz uma alteração aqui e funcionou. Obrigado.
Comment: Veja: Não funcionou:
Comment: Controller:         {$locals             = Local::selectRaw('id'CONCAT(codigolocal," ",descricaolocal) as n')->pluck('n','id');
        $fornecedor         = Fornecedor::get()->pluck('descricao', 'id');
        $fabricante         = Fabricante::get()->pluck('descricao', 'id');

        return view('admin.equipamento.create-edit', compact('titulo', 'centrocustos', 'tipoequipamentos',
                'tipogas', 'locals', 'fornecedor', 'fabricante'));}
Comment: E chamo a view
{
            Selecione o Local
            {!! Form::select('local_id', $locals, ['class' => 'form-control']) !!}
        }
Comment: Coloque todo o `controller` na pergunta! e também qual **a mensagem do problema**, isso é pra funcionar sim @MarcosBirro
Comment: **Qual é a mensagem de erro** @MarcosBirro **e o que não funcionou**


Drupal form menu

Question: I have a menu callback, and I want to add a form on it using the following code.
function parking_calculator_menu() {
  $items['admin/parkingcalculator'] = array(
    'title' => 'Node parkingCalculator',
    'description' => 'Adjust node parkingCalculator options.',
    'position' => 'right',
    'weight' => -5,
    'page callback' => 'get_form',
    'access arguments' => array('administer site configuration'),
  );

  return $items;
}

function get_form() {
  $form['short-term-parking'] = array(
    '#title' => t('Short term parking'),
    '#type' => 'fieldset',
    '#description' => t('Short term parking.'),
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
  );

  $form['short-term-parking']['free_time'] = array(
    '#type' => 'textfield',
    '#required' => TRUE,
    '#title' => t('Free time'),
    '#default_value' => variable_get('free_time', 1),
    '#description' => t('Please enter Free time.')
  );

  $form['short-term-parking']['long-term-starts'] = array(
    '#title' => t('Long term starts'),
    '#type' => 'textfield',
    '#default_value' => variable_get('long-term-starts', 1),
    '#required' => TRUE,
    '#description' => t('Please enter Long term starts.')
  );

  $form['short-term-parking']['first-hour-cost'] = array(
    '#title' => t('First hour cost'),
    '#type' => 'textfield',
    '#default_value' => variable_get('first-hour-cost', 1),
    '#required' => TRUE,
    '#description' => t('Please enter First hour cost.')
  );

  $form['short-term-parking']['each-hour-cost'] = array(
    '#title' => t('Each hour cost'),
    '#type' => 'textfield',
    '#default_value' => variable_get('each-hour-cost', 1),
    '#required' => TRUE,
    '#description' => t('Please enter Each hour cost.')
  );

  $form['long-term-parking'] = array(
    '#title' => t('Long term parking'),
    '#type' => 'fieldset',
    '#description' => t('Long term parking.'),
    '#collapsible' => TRUE,
    '#collapsed' => FALSE
  );

  $form['long-term-parking']['free_timel'] = array(
    '#type' => 'textfield',
    '#required' => TRUE,
    '#default_value' => variable_get('free_timel', 1),
    '#title' => t('Free time'),
    '#description' => t('Please enter Free time.')
  );

  $form['long-term-parking']['long-term-startsl'] = array(
    '#title' => t('Long term starts'),
    '#default_value' => variable_get('long-term-startsl', 1),
    '#type' => 'textfield',
    '#required' => TRUE,
    '#description' => t('Please enter Long term starts.')
  );

  $form['long-term-parking']['first-hour-costl'] = array(
    '#title' => t('First hour cost'),
    '#type' => 'textfield',
    '#default_value' => variable_get('first-hour-costl', 1),
    '#required' => TRUE,
    '#description' => t('Please enter First hour cost.')
  );

  $form['long-term-parking']['each-hour-costl'] = array(
    '#title' => t('Each hour cost'),
    '#type' => 'textfield',
    '#default_value' => variable_get('each-hour-costl', 1),
    '#required' => TRUE,
    '#description' => t('Please enter Each hour cost.')
  );

  $form['valet-parking'] = array(
    '#title' => t('Valet parking'),
    '#type' => 'fieldset',
    '#description' => t('Valet parking.'),
    '#collapsible' => TRUE,
    '#collapsed' => FALSE
  );

  $form['valet-parking']['first-hour-costv'] = array(
    '#title' => t('First hour cost'),
    '#type' => 'textfield',
    '#default_value' => variable_get('first-hour-costv', 1),
    '#required' => TRUE,
    '#description' => t('Please enter First hour cost.')
  );

  $form['valet-parking']['each-hour-costv'] = array(
    '#title' => t('Each hour cost'),
    '#type' => 'textfield',
    '#default_value' => variable_get('each-hour-costv', 1),
    '#required' => TRUE,
    '#description' => t('Please enter Each hour cost.')
  );

  return system_settings_form($form);
}

With this code, I get the following error message:

Recoverable fatal error: Argument 1 passed to drupal_attributes() must be an array, null given, called in /var/www/html/APIG01JO2012039/includes/form.inc on line 3252 and
  defined in drupal_attributes() (line 2366 of /var/www/html/APIG01JO2012039/includes/common.inc). The website encountered an unexpected error. Please try again later.

Why am I getting that error?
Answer: The page arguments hook_menu() expects is an array, not a string.
function parking_calculator_menu() {
  $items['admin/parkingcalculator'] = array(
    'title' => 'Node parkingCalculator',
    'description' => 'Adjust node parkingCalculator options.',
    'position' => 'right',
    'weight' => -5,
    'page callback' => 'drupal_get_form',
    // You used:
    // 'page callback' => 'get_form',
    // The correct value is the following one:
    'page arguments' => array('get_form'),
    'access arguments' => array('administer site configuration'),
  );

  return $items;
}

Drupal form menu