Finding the probability that at least 8 houses in a row are of same colour.

Question: There are 400 houses in a row. Each house is to be coloured with any of the following five colours: red, blue, green, yellow, and white. The colour of each house is to be chosen randomly from among these five colours and independent of any other selection. Now, what is the probability that at least 8 houses in a row will have the same colour?
My idea is to first calculate the number of ways in which there are at least 8 red-coloured houses in a row. Then do the same for green, then blue, yellow and white (${R}\to{G}\to{B}\to{Y}\to{W}$). Suppose, $ n(R) $ denotes the number of ways that there are 8 red-coloured houses in a row.
So, $$n(R) = (number\ of\ ways\ to\ choose\ one\ row\ of\ 8\ houses\ from\ 400\ houses)\times(number\ of\ ways\ rest\ of\ the\ houses\ can\ be\ painted) = \mathrm{393}\!\cdot\!\mathrm{5^{392}} $$
Now, $$ n(R) = n(G) = n(B) = n(Y) = n(W)$$
Initially I was careless to conclude that the required probility will be,
$$ p = \frac{n(R) + n(G) + n(B) + n(Y) + n(W)}{5^{400}}$$
But a few moments later I realised that there is a lot of double-counting in this solution. (For example, when calculating $n(R)$, you can take 1st 8 houses to be red, and the rest the 392 houses are randomly coloured. This will include the case that last 8 houses in a row are red. So, when you come to choose last 8 houses to be red, there will be an occasion when first 8 houses become red-coloured. Similarly there are so many ways that double counting is happening.) What should be done?
Comment: To get rid of overcounting , exponential generating function can be good way .I will write an answer for you
Comment: By "at least 8 houses in a row will have the same colour" do you mean $8$ **successive** houses ?
Comment: This problem has been asked tons of times here.
Eg
https://math.stackexchange.com/questions/48560/
https://math.stackexchange.com/questions/2480924
https://math.stackexchange.com/questions/48560
Comment: I expect it is easier to work backwards.  Count the number of strings in $5$ letters of length $n$ such that there are no single character blocks of length $≥8$.
Comment: yes. 8 consecutive houses
Comment: @leonbloy: I don't think this is a duplicate.
Comment: @epi163sqrt I think it's exactly the same as this one (except for different parameters) https://math.stackexchange.com/questions/48560/ , and the answer is indeed the same.
Comment: @leonbloy:  Sorry! Now I see, you are right.
Answer: Consider a random process that starts by painting the first house with a random color. At each step it paints the next house with a random color out of $m=5$ colors. We are looking for the event that there are $k=8$ same-colored houses in a row.
Let's say that we are in state $s \in \{1,2,\ldots,k-1\}$ if the last $s$ houses but not $s+1$ were of the same color (no matter which color). Initially, with one house, we are in state $1$. Add another state $k$ that indicates that somewhere in the sequence there are $k$ consecutive houses of the same color.
This is a Markov chain with the following transition probabilities: For $s=1,\ldots,k-1$ we have

$P_{s,s+1} = \frac{1}{m}$ (next house has the same color: now one more house)
$P_{s,1} = 1-\frac{1}{m}$ (next house has different color: back to one house)

State $k$ is absorbing ($P_{k,k}=1$) because if ever we find the $k$ same-colored houses, we are happy and don't care what happens later.  All other transition probabilities are zeros. So the transition matrix with $m=5$ colors and $k=8$ is
$$
P_{8 \times 8} = \begin{bmatrix}
4/5 & 1/5 & 0 & \ldots & 0\\
4/5 & 0 & 1/5 & \ldots & 0\\
\vdots &&& \ddots & \vdots \\
4/5 & 0 & 0 & \ldots & 1/5\\
0 & 0 & 0 & \ldots & 1
\end{bmatrix}
$$
Start with the initial state vector $S=[1,0,\ldots,0]$, multiply it $n-1$ times by the transition matrix from the right, and you get the state vector when we have $n$ houses. The last entry is the probability that we are in the absorbing state.
With $n=400$, $m=5$, $k=8$ we get $0.004\,019\,088\,139$ (to 12 decimals; of course we can also do the matrix multiplication in $\mathbb Q$ and we get the exact probability as a rational, but its denominator has more than 200 digits).
Matlab code:
n=400; m=5; k=8;
s = [1 zeros(1,k-1)];       % Initial state
U = ones(k-1, 1);
P = [U*(1-1/m) diag(U/m);
    zeros(1,k-1) 1];        % transition matrix
s = s * P^(n-1);            % apply transition n-1 times
p = s(k)                    % probability of state k

Comment: I refactored your Matlab code into Python code that does the same thing in an edit to my answer [here](https://math.stackexchange.com/a/4247539/964832).
Answer: $\mathbf{NOTE=}$ This answer needs a little bit wolfram-alpha or any other sofware to calculate this torturus exponential generating function calculations.
By using P.I.E , we calculate at least $8$ red or at least $8$ blue or at least $8$ green or at least $8$ yellow or at least $8$ white
The exponential generating function for at least $8$ red : $$\bigg(\frac{x^8}{8!}+ \frac{x^9}{9!}+ \frac{x^{10}}{10!}+\frac{x^{11}}{11!}..\bigg)$$
The others can be shown by $e^x$
Then , when there are at least $8$ red house , find the coefficient of $x^{400}$ in the expansion of $$\bigg(\frac{x^8}{8!}+ \frac{x^9}{9!}+ \frac{x^{10}}{10!}+\frac{x^{11}}{11!}..\bigg) \times e^{4x}$$ and multiply it by $400!$
By P.I.E ,we know that it will be applied for the other colors , so find $$5 \times [x^{400}] \bigg[\bigg(\frac{x^8}{8!}+ \frac{x^9}{9!}+ \frac{x^{10}}{10!}+\frac{x^{11}}{11!}..\bigg) \times e^{4x}\bigg]$$
When two color have at least $8$ house ,then $$\bigg(\frac{x^8}{8!}+ \frac{x^9}{9!}+ \frac{x^{10}}{10!}+\frac{x^{11}}{11!}..\bigg)^2 \times e^{3x}$$
We know that we can select any of two by $C(5,2)=10$ ways , so $$10 \times [x^{400}] \bigg[\bigg(\frac{x^8}{8!}+ \frac{x^9}{9!}+ \frac{x^{10}}{10!}+\frac{x^{11}}{11!}..\bigg)^2 \times e^{3x}\bigg]$$
When three color have at least $8$ house ,then $$\bigg(\frac{x^8}{8!}+ \frac{x^9}{9!}+ \frac{x^{10}}{10!}+\frac{x^{11}}{11!}..\bigg)^2 \times e^{2x}$$
We know that we can select any of three by $C(5,3)=10$ ways , so $$10 \times [x^{400}] \bigg[\bigg(\frac{x^8}{8!}+ \frac{x^9}{9!}+ \frac{x^{10}}{10!}+\frac{x^{11}}{11!}..\bigg)^3 \times e^{2x}\bigg]$$
When four color have at least $8$ house ,then $$\bigg(\frac{x^8}{8!}+ \frac{x^9}{9!}+ \frac{x^{10}}{10!}+\frac{x^{11}}{11!}..\bigg)^4 \times e^{x}$$
We know that we can select any of four by $C(5,4)=5$ ways , so $$5 \times [x^{400}] \bigg[\bigg(\frac{x^8}{8!}+ \frac{x^9}{9!}+ \frac{x^{10}}{10!}+\frac{x^{11}}{11!}..\bigg)^4 \times e^{x}\bigg]$$
When five colors have at least $8$ house ,then $$\bigg(\frac{x^8}{8!}+ \frac{x^9}{9!}+ \frac{x^{10}}{10!}+\frac{x^{11}}{11!}..\bigg)^5 $$
We know that we can select any of three by $C(5,5)=1$ ways , so $$1 \times [x^{400}] \bigg[\bigg(\frac{x^8}{8!}+ \frac{x^9}{9!}+ \frac{x^{10}}{10!}+\frac{x^{11}}{11!}..\bigg)^5 \bigg]$$
By P.I.E $$5 \times [x^{400}] \bigg[\bigg(\frac{x^8}{8!}+ \frac{x^9}{9!}+ \frac{x^{10}}{10!}+\frac{x^{11}}{11!}..\bigg) \times e^{4x}\bigg] - 10 \times [x^{400}] \bigg[\bigg(\frac{x^8}{8!}+ \frac{x^9}{9!}+ \frac{x^{10}}{10!}+\frac{x^{11}}{11!}..\bigg)^2 \times e^{3x}\bigg] +  10 \times [x^{400}] \bigg[\bigg(\frac{x^8}{8!}+ \frac{x^9}{9!}+ \frac{x^{10}}{10!}+\frac{x^{11}}{11!}..\bigg)^3 \times e^{2x}\bigg] -5 \times [x^{400}] \bigg[\bigg(\frac{x^8}{8!}+ \frac{x^9}{9!}+ \frac{x^{10}}{10!}+\frac{x^{11}}{11!}..\bigg)^4 \times e^{x}\bigg] +[x^{400}] \bigg[\bigg(\frac{x^8}{8!}+ \frac{x^9}{9!}+ \frac{x^{10}}{10!}+\frac{x^{11}}{11!}..\bigg)^5 \bigg]$$
Unfortunately , you should use worlfram-alpha to calculte it or any software .After that divide the solution by $5^{400}$
$\mathbf{EDITION=}$ Thanks to @Mike Earnest , I realize that there is an another condition such that the houses must be consecutive. I could not realize it. My answer does not cover the restriction about being consecutive .
$\mathbf{EDITION-2=}$ I spend a little time to find easier way , but i could not. Hence , i am writing this cumbersome solution. This solution needs some knowledge from Enumerative Combinatorics. My method is called Goulden-Jacson-Cluster method. By utilizing @lulu's comment , we will find the number of strings which do not contain single character blocks of length $\geq 8$
I am putting here a article about Goulden -Jackson : https://arxiv.org/abs/math/9806036
I will solve only for length $8$ , the rest is for you , but i highly recommend using a software for it.
The number of strings that do not contain any single block of legth $8$ :
Our alphabet $V= \{R,B,G,Y,W\} \rightarrow |V|=5$ . Moreover our bad words are $\{RRRRRRRR,BBBBBBBB,GGGGGGGG,YYYYYYYY,WWWWWWWW \}$
$$A(x)=\frac{1}{1-dx-\text{weight}(\mathcal{C})}$$
$$\text{weight}(\mathcal{C})=\text{weight}(\mathcal{C}[RRRRRRRR] +\mathcal{C}[BBBBBBBB] +\mathcal{C}[GGGGGGGG] +\mathcal{C}[YYYYYYYY] +\mathcal{C}[WWWWWWWW])$$
$\text{weight}(\mathcal{C}[RRRRRRRR])= -x^8-(x+x^2+x^3+x^4 +x^5 +x^6 +x^7)\text{weight}(\mathcal{C}[RRRRRRRR])$
So , $$\text{weight}(\mathcal{C}[RRRRRRRR])= \frac{-x^8}{(1+x+x^2+x^3+x^4 +x^5 +x^6 +x^7)}$$
The other are the same if you calculate , then $$\text{weight}(\mathcal{C})= \frac{-5x^8}{(1+x+x^2+x^3+x^4 +x^5 +x^6 +x^7)}$$
So , $$A(x)=\frac{1}{1-5x-\frac{-5x^8}{(1+x+x^2+x^3+x^4 +x^5 +x^6 +x^7)}}$$
When , you find the expansion this fraction , you need to find the coefficient of $[x^{400}]$ . It will give you the number of strings that satisfy the desired condition in  $8$ consecutive houses.
$\mathbf{WARNING=}$ I know that i did not get in calculation details in "edition $2$" , because it take much time to explain the all process in Goulden -Jackson , so i put a link above. You can ask any question if you do not understand the process in the link. This edition is just for giving an approach.
Comment: You seem to be ignoring the "in a row" condition. $8$ red houses is only a problem if they are consecutive.
Answer: We interpret $8$ houses in a row as runs of $8$ consecutive houses. The following answer is based upon the Goulden-Jackson Cluster Method. We consider the set of words of length $n\geq 0$ built from an alphabet $$\mathcal{V}=\{R,G,B,Y,E\}$$ and the set $B=\{R^8,G^8,B^8,Y^8,E^8\}$ of bad words, which are not allowed to be part of the words we are looking for. We derive a generating function $A(z)=\sum_{n=0}^\infty a_nz^n$ with the coefficient of $z^n$ being  the number of words of length $n$. Since we want to count the number of words which do have runs of length $8$, the resulting generating function is
\begin{align*}
\frac{1}{1-5z}-A(z)&=1+5z+5^2z+5^3z+\cdots-A(z)\\
&=\sum_{n=0}^\infty \left(5^n-a_n\right)z^n\tag{1}
\end{align*}
The wanted number of $400$ houses is the coefficient $[z^{400}]$ of the series in (1).
According to the paper (p.7) the generating function $A(z)$  is
\begin{align*}
A(z)=\frac{1}{1-dz-\text{weight}(\mathcal{C})}\tag{2.1}
\end{align*}
with $d=|\mathcal{V}|=5$, the size of the alphabet and $\mathcal{C}$ is the weight-numerator of bad words with
\begin{align*}
\text{weight}(\mathcal{C})=\sum_{t\in\{R,G,B,Y,E\}}\text{weight}(\mathcal{C}[t^8])\tag{2.2}
\end{align*}

We calculate according to the paper
\begin{align*}
\text{weight}(\mathcal{C}[t^8])&=-z^8-\left(z+z^2+\cdots+z^7\right)\text{weight}\mathcal{C}([t^8])\tag{2.3}\\
\text{weight}(\mathcal{C}[t^8])&=-\frac{z^8(1-z)}{1-z^8}\qquad\qquad t\in\{R,G,B,Y,E\}\tag{2.4}
\end{align*}
so  that according (2.2) and (2.4)
\begin{align*}
\text{weight}(\mathcal{C})&=\sum_{t\in\{R,G,B,Y,E\}}\text{weight}(\mathcal{C}[t^8])\\
&=\sum_{t\in\{R,G,B,Y,E\}}(-1)\frac{z^8(1-z)}{1-z^8}\\
&=-\frac{5z^8(1-z)}{1-z^8}\tag{2.5}\\
\end{align*}
The additional term on the right-hand side of (2.3) takes account of the overlapping of $t^8, t\in\{R,G,B,Y,E\}$ with parts of it.
We obtain according to (2.1) and (2.5)
\begin{align*}
\color{blue}{A(z)}=\frac{1}{1-5z+\frac{5z^8(1-z)}{1-z^8}}
&\;\;\color{blue}{=\frac{1-z^8}{1-5z+4z^8}}
\end{align*}
We finally get
\begin{align*}
\frac{1}{1-5z}-A(z)&=\frac{1}{1-5z}-\frac{1-z^8}{1-5z+4z^8}\\
&=5z^8+\color{blue}{45}z^9+325z^{10}+2\,125z^{11}\\
&\qquad+\cdots+\color{blue}{\left(5^{400}-a_{400}\right)}z^{400}+\cdots\tag{3.1}
\end{align*}
where the last line was calculated with some help of Wolfram Alpha.

A small example: The blue marked coefficient of $z^{9}$  shows there are $\color{blue}{45}$ words of length $9$ over the alphabet $\mathcal{V}=\{R,G,B,Y,E\}$ which do contain runs of length $8$. These $45$ words are
\begin{align*}
\begin{array}{ccccccccc}
R\color{blue}{RRRRRRRR}&R\color{blue}{GGGGGGGG}&R\color{blue}{BBBBBBBB}\\
G\color{blue}{RRRRRRRR}&G\color{blue}{GGGGGGGG}&G\color{blue}{BBBBBBBB}\\
B\color{blue}{RRRRRRRR}&B\color{blue}{GGGGGGGG}&B\color{blue}{BBBBBBBB}\\
Y\color{blue}{RRRRRRRR}&Y\color{blue}{GGGGGGGG}&Y\color{blue}{BBBBBBBB}\\
E\color{blue}{RRRRRRRR}&E\color{blue}{GGGGGGGG}&E\color{blue}{BBBBBBBB}\\
\color{blue}{RRRRRRRR}G&\color{blue}{GGGGGGGG}R&\color{blue}{BBBBBBBB}R\\
\color{blue}{RRRRRRRR}B&\color{blue}{GGGGGGGG}B&\color{blue}{BBBBBBBB}G\\
\color{blue}{RRRRRRRR}Y&\color{blue}{GGGGGGGG}Y&\color{blue}{BBBBBBBB}Y\\
\color{blue}{RRRRRRRR}E&\color{blue}{GGGGGGGG}E&\color{blue}{BBBBBBBB}E\\
\\
R\color{blue}{YYYYYYYY}&R\color{blue}{EEEEEEEE}\\
G\color{blue}{YYYYYYYY}&G\color{blue}{EEEEEEEE}\\
B\color{blue}{YYYYYYYY}&B\color{blue}{EEEEEEEE}\\
Y\color{blue}{YYYYYYYY}&Y\color{blue}{EEEEEEEE}\\
E\color{blue}{YYYYYYYY}&E\color{blue}{EEEEEEEE}\\
\color{blue}{YYYYYYYY}R&\color{blue}{EEEEEEEE}R\\
\color{blue}{YYYYYYYY}G&\color{blue}{EEEEEEEE}G\\
\color{blue}{YYYYYYYY}B&\color{blue}{EEEEEEEE}B\\
\color{blue}{YYYYYYYY}E&\color{blue}{EEEEEEEE}Y\\
\end{array}
\end{align*}

Result: We find according to (3.1) and Wolfram Alpha the wanted number of words is
\begin{align*}
\color{blue}{5^{400}-a_{400}}&=[z^{400}]\left(\frac{1}{1-5z}-\frac{1-z^8}{1-5z+4z^8}\right)\\
&\,\,\color{blue}{=1.556\,428\,\ldots\cdot 10^{277}}
\end{align*}
and the wanted probability is
\begin{align*}
\color{blue}{\frac{5^{400}-a_{400}}{5^{400}}=4.019\,088\ldots\cdot 10^{-3}}
\end{align*}
Comment: I wonder something , question says that at least $8$ houses , so should we not count for $n \geq 8$ , please look at @lulu's comment and edition $2$ part of my answer. Have a nice day
Answer: For the complementary event, the row of houses decomposes into monochromic of length between $1$ and $7$, where the colors of adjacent sections are different. I will write this as
$$
\text{bad sequence = leftmost group + (sequence of non-left groups)}\tag1
$$
The generating function for the first left-most sequence is
$$
\text{leftmost group g.f. : }\quad5\cdot (x+x^2+\dots +x^7),\tag2
$$
since there are $5$ choices for the color, and the length can be between $1$ and $7$. Each subsequent section has generating function $$\text{non-left group g.f. : }\quad 4\cdot (x+x^2+\dots +x^7),\tag3$$ since the color must be different from its neighbor to the left. Finally, it is well known that if a combinatorial object has generating function $f$, then the g.f. for sequences of that object is $$\text{g.f. for sequence : }\quad 1+f(x)+f(x)^2+\dots=\frac1{1-f(x)}.\tag4$$ Therefore, combining $(1)$ to $(4)$, the number of bad sequences is
$$
\text{# bad outcomes}=[x^{400}]\left(5\cdot (x+\dots +x^7)\times \frac{1}{1-4\cdot (x+\dots+x^7)}\right)
$$
Here, $[x^{400}]$ is the most important operator for generating functions, the coefficient extraction operator, and it just means the coefficient of $x^{400}$ when the inside function is expanded as a series. Using a CAS like Wolfram|Alpha, you can verify that
$$
P(\text{8 of a color in a row})=1-\left(\frac{\text{# bad outcomes}}{5^{400}}\right)=0.00401908813
$$
Here is a Wolfram|Alpha computation of # bad outcomes.
Answer: EDIT: I really liked @Jukka Kohonen's answer. I created a python script to do what he did in Matlab:
Python Code:
import numpy as np
# import pdb
n=400; m=5; k=8;
temp=np.zeros((1,k-1))
temp2=np.array([[1]])
s=np.concatenate((temp2,temp),axis=1)      # Initial state
U = np.ones((k-1, 1));
temp=np.multiply(U,(1-1/m))
flattemp=np.concatenate((U/m,),axis=None)
temp2=np.concatenate((temp,np.diag(flattemp)),axis=1)
temp=np.zeros((1,k-1))
temp=np.concatenate((temp,np.array([[1]])),axis=1)

P = np.concatenate((temp2,temp),axis=0)      # transition matrix
temp=np.linalg.matrix_power(P,n-1)      # apply transition n-1 times
ss = np.matmul(s,temp)[0] # set ss = s * P^(n-1) and convert to 1D array
initstate=s      # s is a reserved keyword in pdb, so set initstate=s
# pdb.set_trace()
prob = ss[k-1]      # probability of state k
print(f'the answer is {prob}')

Hint: Take a look at Time taken to hit a pattern of heads and tails in a series of coin-tosses to help with understanding this question. There is also some good material in Probability of finding a particular sequence of base pairs.
I'm still working on this, but here's how I'm thinking of it:
If there were only $n=8$ houses, the answer would be simple: $5*(20\%)^8$. That's because each house has a 20% chance of being a particular color, and 8 of them have to be that color (hence $(20\%)^8$), but since that logic can be followed with any of the 5 colors, that bit is multiplied by 5.
Now the question is how to extend that to 9,10, and on to 400 houses. I'm working on this. I believe that similar to the logic in Probability of finding a particular sequence of base pairs., with 9 houses, we would have a 2 looks at 8-house-groups. So finding the sequence of all the same color would be twice as likely, but to keep from double-counting, we need to subtract the probability of having a sequence that both starts with and ends with the same color, which would be $(20\%)^9$. So the probability with n=9 houses would be:
$5[2(20\%)^8 - (20\%)^9]$
To extend that to n=10 houses,
$5[(n-7)(20\%)^8 - (n-8)(20\%)^9]$
And for n=400 houses:
$5[(393)(20\%)^8 - (392)(20\%)^9]$
$=0.00402688 \approx 0.4\%$
Comment: Close, but no cigar. Your approach is correct with $n=10$ and even up to $n=15$, but starting from $n=16$ it overcounts, although ever so little. With $n =16$ you can have a sequence of 8 white houses *and* then 8 red houses; your formula counts this as two events. (And same for other color pairs.) With $n \ge 17$ you can also two or more separate runs of 8 white houses, etc.
Comment: @JukkaKohonen true. And, your approach is very powerful and easy to understand. But, I still found the answer to within $0.19$%.


Does the blocksize (bs) value in swap settings matter? If yes, is there a command to show current settings about swap block size?

Question: This post gives this command to resize swap
sudo dd if=/dev/zero of=/swapfile bs=1G count=8

Does the blocksize (bs) value in swap settings matter? If yes, is there a command to show current settings about swap block size?
If swap block size really affect something, I would like to know what it would be before I modify the settings.
If not, please explain a little bit why swap block size would not actually affect the performance of swap.
Some additional reference would be better.
Comment: I don't think the blocksize (`bs`) value that you pass to `dd` has any effect on the properties of the swapfile that's generated - it just tells `dd` what sized blocks of zero bytes to read and write when initializing the file. (A file doesn't really have a blocksize - that's a property of the file*system* on which it resides.)
Comment: @steeldriver  Thanks a lot! Please move your comments to answer, I'll accept it.
Comment: I'll wait a bit in case anyone who understands it better provides an answer...
Comment: What makes the file a swap area is the `mkswap`-command which is issued after the `dd`-command.
Answer: According to the following link, this is the way to read the NUL bytes in /dev/zero (using blocks), only the bs x count value matters.
https://www.cyberciti.biz/faq/linux-add-a-swap-file-howto/
Answer: According to https://www.cyberciti.biz/faq/linux-add-a-swap-file-howto/ the block size is the number of bytes to read and write at a time.
Most places recommend 1k (1024).
The following article shows a way to determine the best block size.


How to remove entry of ubuntu 12.04 from Windows bootloader while used (wubi installation)?

Question: A few months I decided to install Ubuntu 12.04 on my PC alongside with my Windows 7 partition. In order to do that and avoid any mistake, I followed the steps of this tutorial.
Everything was going well until I decided to update to the 12.10 release. I don't know what happened, but after I updated my Ubuntu, it stopped working, it didn't even launched, when I turned on my PC and choose to run "Ubuntu 12.04" on the Grub Screen, a weird messaged appeared.
Well, so I decided to install the Ubuntu 12.10 and forget about the 12.04 partition, no problem.
I erased the partitions used for the Ubuntu 12.04 with EaseUS partition Manager.
However, when I start my PC, there is still the option of "Ubuntu 12.04" to chose, is that bad?
And what about now, can I use the Windows Installer of Ubuntu to install the Ubuntu 12.10 ? What should I do to have Ubuntu 12.10 and Windows 7 in dual boot again?
Answer: Put the Windows Vista or Windows 7 installation disc in the disc drive, and then start the computer.
Press a key when you are prompted.
Select a language, a time, a currency, a keyboard or an input method, and then click Next.
Click Repair your computer.
Click the operating system that you want to repair, and then click Next.
In the System Recovery Options dialog box, click Command Prompt.
Type following commands in cmd
<code>bcdedit /export C:\BCD_Backup
c:
cd boot
attrib bcd -s -h -r
ren bcd bcd.old
bootrec /RebuildBcd
</code>
This will remove your old Ubuntu 12.04 entry.
After that you will able to boot Windows. Make fresh Installation of Ubuntu 12.10.
Good luck.
Comment: Thanks, I will try that.

And about what you said about using Wubi, is Wubi any less eficient than the regular way of installing Ubuntu? Why?
Comment: It is just for trying Ubunutu Not permanant way to install Ubuntu.
Comment: Sure?
I understood things in a diferent way in this link http://www.ubuntu.com/download/help/install-ubuntu-with-windows
The last image is a picture from a boot screen, so I tought that it was a way of permanant istall of Ubuntu. Am I wrong?
Comment: No , It's wubi installation.
Comment: I cannot cd into boot because there apparently is no such directory. What to do now?
Answer: Step:

Make a recovery disc for your Windows OS and this should save all the files you have when you create the recovery disc for Windows. follw this link for info on making a recovery disc http://windows.microsoft.com/is-is/windows7/create-a-system-repair-disc
After the disc is created and fininshed leave the recovery disc in the cd-rom/dvd-rom drive
With the recovery disc inserted into the cd-rom/dvd-rom drive and restart your computer
Click/choose Repair your computer  when prompted.
Click the operating system that you want to repair, and then click Next.
In the System Recovery Options dialog box, click/choose Command Prompt.
Type following commands in cmd lines in the Command Prompt

bcdedit /export C:\BCD_Backup
c:
cd boot
attrib bcd -s -h -r
ren bcd bcd.old
bootrec /RebuildBcd
8 - This will remove your Ubuntu OS and Your Windows OS.
9 - restart your computer
10 - Upon start up enter into the computers BIOS by pressing whichever F# key is needed for you computer (the F# key will be displayed on the main screen when the computer starts up)
11 - In the BIOS screen arrow key over the the tab/section named BOOT, move the cd-rom/dvd-rom to the top of the list and then save all changes when prompted upon exiting the BIOS
12 - With the Windows Recovery disc in the cd-rom/dvd-rom drive restart your computer and follow the recovery prompts for Windows OS Recovery, after its finished you should only have Windows OS on your computer along with all your files
13 - After you have successfully recovered/restored you Windows OS your done, ENJOY!!!


Trouble generating PDF's from dynamic content using jsPDF

Question: I'm having a problem generating PDF's.
Our client wants to generate PDF documents containing selected content from the data provided by the users of the site. I'm trying to use a client-side solution using javascript, jQuery and jsPDF but I'm having some troubles.
The content that can be displayed in the document are text, images, colors and others.
This is the rough screen of the document generator.

The column on the left shows the selected content which can be displayed on the document. Each element has a button (the black area inside each one) which clones the full element using jQuery to the document container (the white box). Everything works fine and after cloning elements to the document container, I use the Export To PDF button to call a jQuery event to use the jsPDF library and generate the document. But this is where everything goes wrong.

If I click the Export button, the Save File dialog pops in and asks me to save or view the file. When I open that new PDF file, the document is full blank, it doesn't have any elements. BUT, if I didn't add any selected content to the document container, the saved PDF file shows the header content of the document, which is the default content of every file.
I don't know what I'm doing wrong. The javascript console doesn't show any error messages.
Each selected item has the class grid__item, the document container has the class document-page.
My code is the following:
<code>$(document).on('click', '.js-add-element-to-document', function () {
     $(this).parent().parent('.grid__item').clone().appendTo('.document-page');
} );
$('.js-export-to-pdf').on('click', function () {
    var pdf = new jsPDF('p','pt','a4');
    pdf.addHTML( $('.document-page'), function () {
        var string = pdf.output( 'datauristring' );
    });
    if( typeof pdf !== 'undefined' ) {
        setTimeout( function () {
            pdf.save( 'travel-document.pdf' );
        }, 500);
    } else {
        alert(' Error on generating document ');
    }
});
</code>
Am I ignoring something else? Is there something that is breaking the content of my generated document? Thanks.
Answer: addHTML() is an asynchronous function. You will have to call "save" inside the callback you are passing.
As you have a lot of content, addHTML might not have been completed when you are calling save. That is the reason saved pdf is blank.
example -
<code>pdf.addHTML($("#someDiv"), function(){
   //addHTML completed
   pdf.save("test.pdf");
});
</code>


Run ant as a different user

Question: If i run a task as root, is there a way to detect its being run as root and run certain tasks as a different user.
I have certain tasks that need to run as root but others that just need to run as the current user.
Answer: You can use something like the following to only run certain targets if the current user has a certain name, such as 'root'.
<condition property="rootTasksEnabled">
    <equals arg1="${user.name}" arg2="root" />
</condition>

<target name="do-stuff-if-root" if="rootTasksEnabled">
    <echo>Doing root stuff</echo>
</target>

As for running Ant as a different user, you could use <exec> with the su command to spawn another Ant process:
<target name="do-stuff" depends="do-stuff-if-root, do-other-stuff" />

<condition property="rootTasksEnabled">
    <equals arg1="${user.name}" arg2="root" />
</condition>
<property name="targetToRunAsOtherUser" value="do-stuff-as-other-user" />
<property name="otherUser" value="johnny" />

<target name="do-stuff-if-root" if="rootTasksEnabled">
    <echo>Doing root stuff</echo>

    <exec executable="su">
        <arg value="-c" />
        <arg value="${ant.home}/bin/ant -buildfile ${ant.file} ${targetToRunAsOtherUser}" />
        <arg value="${otherUser}" />
    </exec>
</target>

<target name="do-other-stuff">
    <echo>Doing normal build stuff</echo>
</target>

<target name="do-stuff-as-other-user">
    <echo>I am running as ${user.name}</echo>
    <echo>My home is ${user.home}</echo>
</target>

This example only works under Unix.  To do this in Windows you could probably use the runas command instead of su.

Run ant as a different user


Is a 2x4 strong enough to hold up a porch swing?

Question: I'm hanging a porch swing, but the beams run the wrong direction for the support hooks.  I've looked up in the attic, and there's a 2x4, lying flat, that runs the correct direction.  Will that be strong enough to support, say, 500 lbs?  Due to the angle of my roof, I can't actually reach the board so there's no hope of supporting it from above.
There's really nothing stopping me from getting a different style of support hook (one that drills into the wood at a single spot instead of two), but if possible, I'd like to use what I've got.
Comment: I'm a bit confused about how the beams could run in the wrong direction.  Perhaps I'm being dense, but if they were parallel to the swing, you could drive the hooks into two spot on the same beam; if the beams were perpendicular you could drive into two boards.  What am I missing?
Comment: The more I think about it, the less likely I am going to be able to use those hooks.  I guess I'm just looking for confirmation.  :/
Comment: As the 2x4 is flat, it's not going to be particulary strong.  You also didn't mention how long the 2x4 is, as a short run is going to have less moment on it than a long run.  (assuming that only the ends are well supported)
Comment: Get me some dimensions/schematic and I'll calculate the max stress on the 2x4  for ya. Us engineers are useful sometimes. :)
Comment: @Rod: I've only got a pair of hooks, the chains on one side both attach to the hook on that side. The problem is (with the particular hook I had) is that the hook has a very wide base that can only be attached perpendicular to the direction of swing, and since the beams run parallel, I ended up needing something different.
Comment: Is the 2x4 laid across the ceiling joists?  How widely spaced are the joists?
Answer: There are several issues to consider - whether the 2x4 itself is strong enough to bear the load you're putting on it in the direction that you're loading it (so the grade/type of wood is important, not all 2x4's are created equal), whether the fastener/hook you use will overstress the wood in the 2x4 at the point where it attaches, and whether the load on the 2x4 will overstress/exceed the capacity of whatever it is that's attaching the 2x4 to whatever it is that it's attached to/supported by.
My unscientific, short answer is "no", I wouldn't depend on a 2x4 of unknown provenance to support the weight of 2 adults (or any number of children) + the weight of the swing, especially given wear & degradation over time.
If it was a short run of 2x4 and the swing was attached really well and the 2x4 is attached really well to something strong, yeah, it'll probably work, but if it were my house/family involved, I'd look for a stronger way to hang the swing.


composer require silex.phar

Question: Is it possible to require the latest stable silex.phar from within composer?
I found silex/silex dev-master / 1.0.x-dev on packagist but that seems to be the latest unfolded silex code.
Answer: At this point it isn't possible. Maybe/probably one day it will be, but I can't say when. That said, having "unfolded" code isn't such a big issue I'd think?
Comment: yes its not possible since phars fetched as repositories/dist get extracted.
there is a PR to prevent such behaviour: https://github.com/composer/composer/pull/537
but as Igor states in the comment this could result in troubles with dependencies included in the phar and others from composer.
well i guess i go unfolded ;), phars seemed so handy thou
Comment: We'll see later if we can add support for packaged phars because it'd be nice, but it needs some thinking to come up with a foolproof solution.

composer require silex.phar


Confusion With Executor Service Freezing

Question: I am trying to run a swing worker using the Executor Service and something strange is happening. I am currently using the method newSingleThreadExecutor(); as well as doing the following;
Future<?> f = execService.submit(swingWorker);
JOptionPane.showMessageDialog(null, "Created Future");
f.get(120, TimeUnit.SECONDS);

What happens is that my swing worker code runs perfectly so long as I don't close the dialog message box. If I close the dialog box then my application just completely freezes. I believe the thread is getting blocked but am unsure for what reason.
If I run the swingworker on its own without the help of a execService it works perfectly, but of course the timeout feature is not available which is the whole purpose of this. Should I just use timer instead?
Thanks
Comment: Pls provide a little bit more information what is the purpose of the swing worker, which might help to identify the cause for a deadlock.
Comment: Can you post a short but *complete* program which demonstrates the problem?
Answer: If it looks something like:
public void closeDialog(){
    SwingUtitilies.invokeLater(new Runnable(){
      public void run(){
          Future<?> f = execService.submit(swingWorker);
          JOptionPane.showMessageDialog(null, "Created Future");
          f.get(120, TimeUnit.SECONDS);
      }
    });
}

You are blocking (suspending) the EDT.  f.get() will block until the Future's processing completes.
Answer: Future.get() is a blocking call. It waits until the task has completed, or until the timeout has elapsed. So, by calling it in the EDT, you're doing exactly what you try to avoid by using a SwingWorker.
Answer: I'm not a swing expert but in Java Concurrency in Practice it is mentioned that swing uses it's own thread for UI management, and you shall not interfere with it. May be that's the problem.


string replacement of fixed positions in python

Question: i'm trying to do a Trivia program and i'm getting issues with the answers.
What i want is to replace the characters of the answers to display as hints. Example:
answer = "I am just an example"
hintwouldbe = "I a_ j___ a_ e______"
hint2mightbe = "I am j___ an e_a___e"

i am not really sure how to make it. Tried with loops (for c in answer) and string.replace methods. Also tried with some re.translate and dicts but i'm getting really big codes and hard to understand. Ther must be an easer way so... here i am.
Which way do you think would be the most efficient/easier to accomplish that?
Edit It would be great if i could choose what positions to replace. for example: if the word has 6 characters, replace 1,3 and 6 characters with a _
Edit2: Right answer
After a bit change, i choose Thomas Orozco answer as valid, is quite easy to understand and re-create:
    from random import random
    answer = "anything in here"
    pista = [char if random() < 0.8 else "_" for char in answer]
    pista2 = "".join(pista)
    print(pista2)

Answer: A string isn't an appropriate representation for what you're trying to do, a list would do better.
import random

def make_hint(chars, frequency):
    hint_chars = [char if random.random() < frequency else "_" for char in chars]
    return "".join(hint_chars)

answer = "I am just an example"

print make_hint(answer, 0.3)
print make_hint(answer, 0.5)

Of course, this is only an example. Here, I'm using random to display 30% or 50% of characters, but you could use a different implementation.
Remember that you could first call .split() on answer to split it in words before running the transformation:
print " ".join(make_hint(word, 0.3) for word in answer.split())

Answer: You should place the logic you have in mind (as in your example, in words of 6 letters replace 1-st, 3-rd and 6-th) into structures (e.g. dictionaries). Then, split the sentence into words and apply your logic to them.
Here's the function that exchanges the needed positions in the word with _:
def exchange(word,positions):
    chars=list(word)
        w=""
    for i in range(1,len(chars)+1):
        if i in positions:
            w+='_'
        else:
            w+=chars[i-1]
    return w

Put the logic into dictionary (7 - to catch the word 'example', and 4 to catch 'just'):
d={7:[1,3,6],4:[range(2,4+1)]}

And finally apply the logic:
words=answer.split() # split the sentence into word
' '.join(map(lambda x: exchange(x,d.get(len(x),[])),words)) # apply the logic and join results
>>> 'I am j___ an _x_mpl_'

Answer: Substitute characters at prescribed positions:
answer = "I am just an example"
''.join('_' if i in (1,3,6) else answer[i] for i in range(0, len(answer)))

To avoid substituting white spaces:
import string
answer = "I am just an example"
def pr((c,i,L)):
 if (i in L and c in string.letters + string.digits):
  return '_'
 else:
  return c

''.join(map(pr,((answer[i],i,(1,3,6)) for i in range(len(answer)))))

and randomly (assuming you don't want to substitute white spaces):
answer = "I am just an example"
import string
import random
''.join('_' if random.randint(0, 1) and i in string.letters + string.digits else i for i in answer)

Answer: This method automatically replaces all but the first letter of each word with '_', then will allow an index based re-fill of the hint letters.  It uses three list comprehensions:
def hint(a, hidxs):
    return ''.join(c[i in idxs] for i, c in enumerate(a))

a = zip(' '.join(w[0] + '_'*(len(w)-1) for w in answer.split()), answer)
_idxs = [i for i, c in enumerate(hint(a, [])) if c == '_']

Here is how to use them:
>>> answer = "I am just an example"
>>> a = zip(' '.join(w[0 ]+ '_'*(len(w)-1) for w in answer.split()), answer)
>>> _idxs = [i for i, c in enumerate(hint(a, [])) if c == '_']
>>> _idxs #list of indexes for every '_'
[3, 6, 7, 8, 11, 14, 15, 16, 17, 18, 19]
>>> hidxs=[]
>>> print 'Hint 1:', hint(a, hidxs)
Hint 1: I a_ j___ a_ e______
>>> hidxs=[6]
>>> print 'Hint 2:', hint(a, hidxs)
Hint 2: I a_ ju__ a_ e______
>>> hidxs=[6, 14]
>>> print 'Hint 3:', hint(a, hidxs)
Hint 3: I a_ ju__ a_ ex_____
>>> hidxs=[6, 14, 17]
>>> print 'Hint 4:', hint(a, hidxs)
Hint 4: I a_ ju__ a_ ex__p__
>>> print 'Answer:', hint(a, _idxs)
Answer: I am just an example

A program that randomly hints would be:
from random import shuffle
def hint(a, hidxs):
    return ''.join(c[i in idxs] for i, c in enumerate(a))

def all_hints(answer):
    a = zip(' '.join(w[0 ]+ '_'*(len(w)-1) for w in answer.split()), answer)
    _idxs = [i for i, c in enumerate(hint(a, [])) if c == '_']
    shuffle(_idxs)
    hints = []
    print 'Press enter for next hint:'
    for i in _idxs:
        print 'Hint:', hint(a, hints),
        hints.append(i)
        raw_input()
    print 'Answer:', hint(a, hints)


How to create TimePickerDialog android

Question: I want to create TimePickerDialog and theme is sample dialog.
but I follow this link

http://www.android-examples.com/create-timepickerdialog-to-select-time-in-12-hours-format-android/

result is not simple dialog
result is

I want

How to set this ?
and sorry My image is so large.
Comment: http://www.android-examples.com/change-timepickerdialog-theme-in-android-programmatically/ follow this link
Comment: @komalakhani perfect!
Comment: Time picker is platform theme dependent
Comment: You may try to find your answer [here](https://stackoverflow.com/questions/29250086/custom-time-picker-dialog-in-android) and [here](https://stackoverflow.com/questions/32967424/how-can-i-put-date-and-time-picker-in-a-dialog-in-android).
Comment: kitkat version only will give your expected output.
Comment: https://github.com/ugurtekbas/dialTimePicker and https://github.com/jjobes/SlideDayTimePicker refer this link you may get some idea.
Answer: I have made one method for old TimePickerDialog...i have same situation like you..this is working great for me..
Use below method
    public void showHourPicker() {
            final Calendar myCalender = Calendar.getInstance();
            int hour = myCalender.get(Calendar.HOUR_OF_DAY);
            int minute = myCalender.get(Calendar.MINUTE);

            TimePickerDialog.OnTimeSetListener myTimeListener = new TimePickerDialog.OnTimeSetListener() {
                @Override
                public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                    if (view.isShown()) {
                        myCalender.set(Calendar.HOUR_OF_DAY, hourOfDay);
                        myCalender.set(Calendar.MINUTE, minute);

                    }
                }
            };
            TimePickerDialog timePickerDialog = new TimePickerDialog(getActivity(), android.R.style.Theme_Holo_Light_Dialog_NoActionBar, myTimeListener, hour, minute, true);
            timePickerDialog.setTitle("Choose hour:");
  timePickerDialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
            timePickerDialog.show();
        }

Hope this will help you...let me know if you need any help
Comment: @LokeshDesai The proper way to use `TimePickerDialog` is to create it in `onCreateDialog` of a `DialogFragment`. Calling `show()` directly on a Dialog will leak context when config changes happen.
Comment: @ARR.s can u tell me why u rejected this answer?
Comment: Calling `show()` on a Dialog is always wrong. You should use a `DialogFragment`.
Comment: @PaulBurke ? Please check difference between TimePickerDialog and DialogFragment
Comment: @paul Yes agree that can be good way. Thanks for knowledge sharing.
Answer: Try the below code. It looks almost similar to what image you have provided. Either use this
<TimePicker
    android:id="@+id/simpleTimePicker"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:timePickerMode="spinner"/>

or this.
 final Calendar calenderInstance = Calendar.getInstance();
    int hr = calenderInstance.get(Calendar.HOUR_OF_DAY);
    int min = calenderInstance.get(Calendar.MINUTE);
    TimePickerDialog.OnTimeSetListener onTimeListner = new TimePickerDialog.OnTimeSetListener() {
        @Override
        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
            if (view.isShown()) {
                calenderInstance.set(Calendar.HOUR_OF_DAY, hourOfDay);
                calenderInstance.set(Calendar.MINUTE, minute);
            }
        }
    };
    TimePickerDialog timePickerDialog = new TimePickerDialog(MainActivity.this,
            android.R.style.Theme_Holo_Light_Dialog_NoActionBar,
            onTimeListner, hr, min, true);
    timePickerDialog.setTitle("Set Time");
    Objects.requireNonNull(timePickerDialog.getWindow()).setBackgroundDrawableResource(android.R.color.transparent);
    timePickerDialog.show();

Answer: you may try datePickerMode spinner like below code in date time picker
android:calendarViewShown="false"
android:datePickerMode="spinner"

Answer: Change this line:
timepickerdialog = new TimePickerDialog(MainActivity.this,
new TimePickerDialog.OnTimeSetListener() {

to this:
timepickerdialog = new TimePickerDialog(MainActivity.this, AlertDialog.THEME_DEVICE_DEFAULT_DARK,
                    new TimePickerDialog.OnTimeSetListener() {

It allows you to theme your TimePicker
Answer: Custom TimePicker:
You can make a class DateTimePickerCustom which contains the method you can use anywhere through out your project:
    public static void getTimePicker(Context context, final int position, final PickerClickListener pickerClickListener) {
          final Dialog dialog = new Dialog(context);
            dialog.setContentView(R.layout.dialog_time);
            dialog.show();
            final TimePicker timePicker = (TimePicker) dialog.findViewById(R.id.timePicker);
            timePicker.setIs24HourView(false);
            Button buttonOk = (Button) dialog.findViewById(R.id.buttonOk);
            Button buttonCancel = (Button) dialog.findViewById(R.id.buttonCancel);
            buttonCancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                }
            });
            buttonOk.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    try {
                        SimpleDateFormat sdf24 = new SimpleDateFormat("HH:mm");
                        SimpleDateFormat sdf12 = new SimpleDateFormat("hh:mm a");

                        String strTime = timePicker.getCurrentHour() + ":" + timePicker.getCurrentMinute();
                        Date time = sdf24.parse(strTime);
                        String formattedTime = sdf12.format(time);
                        Log.d(TAG, "formattedTime: " + formattedTime);
                        pickerClickListener.onTimeSelect(formattedTime, position);
                        dialog.dismiss();

                    } catch (ParseException e) {
                        e.printStackTrace();
                    }

                }
            });
}

XML code:
<EditText
       android:id="@+id/editTextStartTime"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_centerVertical="true"
       android:editable="false"
       android:focusable="false"
       android:singleLine="true"
       android:textSize="14sp" />

Call this method in MainActivity as :
 @OnClick(R.id.editTextStartTime)
    public void startTimePicker() {
        DateTimePickerCustom.getTimePicker(context, 0, this);
    }

Answer: You can use Custom time picker and i have more customized it here like S-planner

How to create TimePickerDialog android


how to use the /execute command to make it so if a mob has a radius to another mob it will execute a /summon command

Question: So to explain this. Im trying to make it so if a player places a tnt minecart. And if any player, mob or animal is at the maximum distance of 1 it will summon a primed tnt. But every time i try to do it, it either lags my entire game with tnt explosions or only executes if the command block has a certain radius of what i inputted.
Answer: You should test that the minecart doesn't have a tag, then give it a tag and summon the primed tnt. This way it will only summon once
Another option is to kill the minecart
For the commands it depends on your version of minecraft, I will assume 1.13, if you are in 1.12 let me know
<code>execute as @e[type=minecraft:tnt_minecart,tag=!exploded] at @s if entity @e[distance=..1,limit=1] run function explode
</code>
Which calls this function
<code># explode.mcfunction
tag @s add exploded
summon minecraft:tnt ~ ~ ~
</code>
Comment: I certainly can, although I don't like just giving people the commands (I'm a verified helper on the minecraft commands discord, and on there we have a policy of first explaining the logic first, and only if they can't figure out the commands from that then we start giving commands.
(I'll start writing the commands now)
Comment: Welcome to the site! could you exapnd you your answer by providing steps on how OP might tag the TNT and summon a primed tnt?
Comment: Done, commands added
Comment: Thanks for the edit, it is good to have some more people who can write and explain Minecraft commands around! One thing to keep in mind though when answering is that you aren't just writing an answer for the OP. Arqade is also a reference that lots of other people might come to to get their answers, so full and complete answers tend to do a lot better. That isn't to say that every question should be answered, but generally un-researched/lazy  questions just get down-voted and eventually closed.


How to use ApiClient.Default.CallApi()?

Question: Looking through the Autodesk.Forge Reference Properties, I have discovered a method called CallApiAsync(), which I would like to use to sent requests such as GET the properties of an Autodesk BIM 360 Project.
Below are the parameters that CallApiAsync() uses but can someone explain what each of them are and how I can null the parameters I don't need?
CallApiAsync(string path,
             RestSharp.Method method,
             System.Collections.Generic.Dictionary<string, string> queryParams,
             object postBody,
             System.Collections.Generic.Dictionary<string, string> headerParams,
             System.Collections.Generic.Dictionary<string, string> formParams,
             System.Collections.Generic.Dictionary<string, RestSharp.FileParameter> fileParams,
             System.Collections.Generic.Dictionary<string, string> pathParams,
             string contentType)

Comment: Thanks for the source code, after using a couple of code I was able to get my method to work as expected from the CallApiAsync() function
Comment: You can check the source for this here https://github.com/Autodesk-Forge/forge-api-dotnet-client/blob/master/src/Autodesk.Forge/Client/ApiClient.cs#L218 but probably you are not going to use this directly, instead you will use another method that call this one, like this https://github.com/Autodesk-Forge/forge-api-dotnet-client/blob/master/src/Autodesk.Forge/Api/ProjectsApi.cs#L496
Answer: If you look at the source code here it doesn't really check for null or fall back to any default value so you will need to provide an empty value for the args you don't need, such as
 CallApiAsync("Your:Api/path/", Method.GET, new Dictionary<string,string>(), new {}, ...)

Comment: Thanks for the source code, it was very helpful in creating the structure for the CallApi function.

How to use ApiClient.Default.CallApi()?


Why are steam radiators used in the USA?

Question: In the UK, we use water radiator systems when the boiler heats the water to about 70°C, this allows the boiler to get most of the energy out of the gas (or oil) by condensing the steam you get from burning gas.
I can't understand why anyone would design a system that could not operate with a condensing boiler – what am I missing?
Comment: Jeff Ferland gave a great answer, so I'll just leave this as a comment: systems evolve over time, and builders install whatever is current. My parents' 1906 house has steam, my 1937 house has hot water, and I don't remember seeing anything other than hot air systems in houses built in the 1960s and 1970s. In England, I suspect that the housing stock is either relatively new (post-1945) or very old; in the latter case, it would use whatever was popular when central heat was added.
Comment: @kdgregory, I think a big factor is that we don't have many basements in the UK, so a single pipe stream system will never have worked.  Hot air come in the UK for a few years, but it then want back to all being water based.
Answer: The US has a mixture of systems. I'm not sure what the prevalence is, but I've lived in homes with both steam and hot water heating.
Steam offers the following advantages:

One-pipe systems
More heat transfer for a given radiator surface
No distribution pumps

Steam offers the following drawbacks:

Furnace needs to be a low point
Corrosion
Finicky distribution

Modern installations tend to favor hot water. The New England region has a legacy of steam heat that stems from coal furnaces and basements. Those systems were selected a century ago, and refit would require replacing the entire system. Steam was the leading technology in New England during its greatest period of growth.
Further, New York City had a substantial influence in the area with its district steam heat operations. Also, another good article that discusses steam legacy, why replacement is a bear, and how steam works in general.
Finally, in large distribution environments, there's the high pressure factor. If you need to move a lot of heat energy, you can do so space-efficiently with high pressure steam (smaller pipes). Harvard's Blackstone Steam Plant heats over 160 buildings and drives a 5 megawatt turbine. At larger scales like this, the thermal loss at the chimney is far lower than the combined loss that would be had from running at sub-boiling temperatures.


Is there anyway to recover from being knocked down?

Question: Certain attacks will knock me down and I won't be able to get up for awhile. Some of the colossus will knock you down with everyone one of your attacks, and due to their attack patterns can result in being hit once being a game over, since the moment you get back up they attack. This is beyond annoying, and I'm curious if there is some way to get up that I'm missing.
Is there anyway to get up after such an attack?
Comment: Must. Resist. Urge. To edit. Title. To: "I got knocked down. Can I get up again?"
Comment: @LessPop_MoreFizz - These youngsters probably don't even get the reference.
Answer: If I remember correctly, tapping the jump button (triangle by default) should help you to get up faster.
Answer: Twirl that left analog stick after you get knocked down, you'll recover twice as fast.


Group dates based on specific number of days in R

Question: I have a DateTime series (see below as an example). I have to assign groups to these dates based on 8 days intervals. Basically, the group should be assigned as per the following rules (for any given year): - Group 1: (Jan 1 - Jan 8); Group 2: (Jan 9 - Jan 16); and so on. So, basically, there will be 46 groups (~(365 or 366)/8) in total in a year. The last group in a year will have only either 5 days or 6 days (365 or 366 - 45*8).  What is a convenient way to approach this?
    x <- as.POSIXct("2021-12-31") + as.difftime(c(1:10,50,100,350,364,470), units="days")

Comment: It might be nice to make example data that actually covers more than one group for testing.
Comment: @thelatemail I have edited the example data.
Answer: Using cut with a sequence of 8 day blocks, compared to the Julian days extracted from each date object.
Example data:
x <- as.POSIXct("2021-12-31") + as.difftime(c(1:10,50,100,350,364,470), units="days")

Cut and review results:
grp <- cut(as.integer(format(x, "%j")), breaks=c(seq(0,366,8), 366))
data.frame(x, grp)

#            x       grp
#1  2022-01-01     (0,8]
#2  2022-01-02     (0,8]
#3  2022-01-03     (0,8]
#4  2022-01-04     (0,8]
#5  2022-01-05     (0,8]
#6  2022-01-06     (0,8]
#7  2022-01-07     (0,8]
#8  2022-01-08     (0,8]
#9  2022-01-09    (8,16]
#10 2022-01-10    (8,16]
#11 2022-02-19   (48,56]
#12 2022-04-10  (96,104]
#13 2022-12-16 (344,352]
#14 2022-12-30 (360,366]
#15 2023-04-15 (104,112]

Comment: I was wondering how can we replace the current grp format with date. For example, (0,8] should be replaced by 2022-01-01, (8,16] with 2022-01-09, so on.
Comment: @raghav - you could take the `min(x)` for each `grp` using any of the many options for calculating groups - `group_by` in dplyr, `by=` in data.table etc.
Comment: @raghav: how about `library(lubridate); library(santoku); chop_width(x, days(8), labels = lbl_endpoints(fmt = "%y-%m-%d"))`.


configure FreeRADIUS rlm_rest module in CentOS

Question: I want to construct a 2 factor authentication system using freeRADIUS for proxy and privacyIDEA for authentication in server. I read some documents about  freeRADIUS  and privacyIDEA, and find that rlm_rest module could be helpful for this. I find this document in privacyIDEA webside:
http://privacyidea.readthedocs.io/en/master/application_plugins/rlm_rest.html#rlm-rest
and it just show how to install rlm_rest module in Ubuntu using apt-get, but my server is CentOS 7. So my first question is:
How to install the required packages of rlm_rest module in CentOS?
After that ,the document shows the configuration steps:
The authentication type needs to be configured in the /etc/freeradius/users file:

DEFAULT Auth-Type := rest

and the site configuration should invoke the module as follows:
authenticate {
    Auth-Type rest {
       rest
    }
    digest
    unix
}

And I don`t know where I should invoke the "authenticate {…}"module? Does it should be write in /etc/freeradius/users ? This is my second question.
Could you please give me some advice or some references? Any help will be appreciate.
Answer: The authenticate  section goes to your site configuration.
Also on CentOS this would be located in /etc/raddb/sites-enabled, which is linked to sites-available.
You should consider using the rlm_perl module, since this is more flexible.
http://privacyidea.readthedocs.io/en/master/application_plugins/rlm_perl.html#rlm-perl


In C# what does $ before and after a Class or Namespace Identifier mean?

Question: The C# Identifier rules specify that a name must begin with a Letter or Underscore but the code below works without error. Even the code display function on StackOverFlow below does not think names with starting or ending $'s are valid.
<code>namespace $safeprojectname$
{
    [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = nameof($saferootidentifiername$CodeRefactoringProvider)), Shared]
    internal class $saferootidentifiername$CodeRefactoringProvider : CodeRefactoringProvider
    {
    }
}
</code>
Comment: Visual Studio uses `$` for replacing variables in templates in a lot of places, but that's not valid c#. Where exactly do you think that code works?
Comment: What makes you think that "works without error"? it certainly doesn't even compile for me... are you sure you're actually compiling it? Is it possible that this is actually a template that is being run through a pre-processor, but is not actually C#? Even if I spoof the attributes and base class, I get no fewer than 25 compiler errors from that code
Comment: looks like a template value
Comment: So the question was solved, but there is another option that I'd like to mention for people finding this question in the future: there are actually some characters which are allowed in names in IL, but are not legal C#, such as `+`, `<`, `>` and `$`. The C# compiler uses them to generate names for things like generic and anonymous types. See for example this site explaining the process for auto implemented properties: https://wouterdekort.com/2013/10/08/desugaring-auto-implemented-properties/ So if you see these names you may be looking, for example, at a decompiled assembly.
Answer: Just realized I was looking at a template file that produced C# not a C# source file.


How to calculate the total number of buckets that have "value" greater than 0?

Question: I have this query that calculates the number of events per bucket. How can I calculate the total number of buckets that have value greater than 0?
GET myindex/_search?
{
  "size": 0,
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "PlateNumber": "111"
          }
        }
      ]
    }
  },
  "aggs": {
    "daily_intensity": {
      "date_histogram": {
        "field": "Datetime",
        "interval": "day"
      },
      "aggs": {
        "count_of_events": {
          "value_count": {
            "field": "Monthday"
          }
        }
      }
    }
  }
}

This is the output that I get. The expected answer that I want to get is 26, because there are totally 26 elements in buckets that have value greater than 0. Basically I do not need the output of all buckets, I only need this total number.
{
  "took": 237,
  "timed_out": false,
  "_shards": {
    "total": 5,
    "successful": 5,
    "failed": 0
  },
  "hits": {
    "total": 98,
    "max_score": 0,
    "hits": []
  },
  "aggregations": {
    "daily_intensity": {
      "buckets": [
        {
          "key_as_string": "2017-05-01T00:00:00.000Z",
          "key": 1493596800000,
          "doc_count": 3,
          "count_of_events": {
            "value": 3
          }
        },
        {
          "key_as_string": "2017-05-02T00:00:00.000Z",
          "key": 1493683200000,
          "doc_count": 1,
          "count_of_events": {
            "value": 1
          }
        },
        {
          "key_as_string": "2017-05-03T00:00:00.000Z",
          "key": 1493769600000,
          "doc_count": 4,
          "count_of_events": {
            "value": 4
          }
        },
        {
          "key_as_string": "2017-05-04T00:00:00.000Z",
          "key": 1493856000000,
          "doc_count": 6,
          "count_of_events": {
            "value": 6
          }
        },
        {
          "key_as_string": "2017-05-05T00:00:00.000Z",
          "key": 1493942400000,
          "doc_count": 0,
          "count_of_events": {
            "value": 0
          }
        },
        {
          "key_as_string": "2017-05-06T00:00:00.000Z",
          "key": 1494028800000,
          "doc_count": 1,
          "count_of_events": {
            "value": 1
          }
        },
        {
          "key_as_string": "2017-05-07T00:00:00.000Z",
          "key": 1494115200000,
          "doc_count": 5,
          "count_of_events": {
            "value": 5
          }
        },
        {
          "key_as_string": "2017-05-08T00:00:00.000Z",
          "key": 1494201600000,
          "doc_count": 6,
          "count_of_events": {
            "value": 6
          }
        },
        {
          "key_as_string": "2017-05-09T00:00:00.000Z",
          "key": 1494288000000,
          "doc_count": 2,
          "count_of_events": {
            "value": 2
          }
        },
        {
          "key_as_string": "2017-05-10T00:00:00.000Z",
          "key": 1494374400000,
          "doc_count": 3,
          "count_of_events": {
            "value": 3
          }
        },
        {
          "key_as_string": "2017-05-11T00:00:00.000Z",
          "key": 1494460800000,
          "doc_count": 0,
          "count_of_events": {
            "value": 0
          }
        },
        {
          "key_as_string": "2017-05-12T00:00:00.000Z",
          "key": 1494547200000,
          "doc_count": 3,
          "count_of_events": {
            "value": 3
          }
        },
        {
          "key_as_string": "2017-05-13T00:00:00.000Z",
          "key": 1494633600000,
          "doc_count": 0,
          "count_of_events": {
            "value": 0
          }
        },
        {
          "key_as_string": "2017-05-14T00:00:00.000Z",
          "key": 1494720000000,
          "doc_count": 1,
          "count_of_events": {
            "value": 1
          }
        },
        {
          "key_as_string": "2017-05-15T00:00:00.000Z",
          "key": 1494806400000,
          "doc_count": 3,
          "count_of_events": {
            "value": 3
          }
        },
        {
          "key_as_string": "2017-05-16T00:00:00.000Z",
          "key": 1494892800000,
          "doc_count": 0,
          "count_of_events": {
            "value": 0
          }
        },
        {
          "key_as_string": "2017-05-17T00:00:00.000Z",
          "key": 1494979200000,
          "doc_count": 1,
          "count_of_events": {
            "value": 1
          }
        },
        {
          "key_as_string": "2017-05-18T00:00:00.000Z",
          "key": 1495065600000,
          "doc_count": 3,
          "count_of_events": {
            "value": 3
          }
        },
        {
          "key_as_string": "2017-05-19T00:00:00.000Z",
          "key": 1495152000000,
          "doc_count": 2,
          "count_of_events": {
            "value": 2
          }
        },
        {
          "key_as_string": "2017-05-20T00:00:00.000Z",
          "key": 1495238400000,
          "doc_count": 1,
          "count_of_events": {
            "value": 1
          }
        },
        {
          "key_as_string": "2017-05-21T00:00:00.000Z",
          "key": 1495324800000,
          "doc_count": 1,
          "count_of_events": {
            "value": 1
          }
        },
        {
          "key_as_string": "2017-05-22T00:00:00.000Z",
          "key": 1495411200000,
          "doc_count": 5,
          "count_of_events": {
            "value": 5
          }
        },
        {
          "key_as_string": "2017-05-23T00:00:00.000Z",
          "key": 1495497600000,
          "doc_count": 16,
          "count_of_events": {
            "value": 16
          }
        },
        {
          "key_as_string": "2017-05-24T00:00:00.000Z",
          "key": 1495584000000,
          "doc_count": 4,
          "count_of_events": {
            "value": 4
          }
        },
        {
          "key_as_string": "2017-05-25T00:00:00.000Z",
          "key": 1495670400000,
          "doc_count": 6,
          "count_of_events": {
            "value": 6
          }
        },
        {
          "key_as_string": "2017-05-26T00:00:00.000Z",
          "key": 1495756800000,
          "doc_count": 1,
          "count_of_events": {
            "value": 1
          }
        },
        {
          "key_as_string": "2017-05-27T00:00:00.000Z",
          "key": 1495843200000,
          "doc_count": 5,
          "count_of_events": {
            "value": 5
          }
        },
        {
          "key_as_string": "2017-05-28T00:00:00.000Z",
          "key": 1495929600000,
          "doc_count": 4,
          "count_of_events": {
            "value": 4
          }
        },
        {
          "key_as_string": "2017-05-29T00:00:00.000Z",
          "key": 1496016000000,
          "doc_count": 5,
          "count_of_events": {
            "value": 5
          }
        },
        {
          "key_as_string": "2017-05-30T00:00:00.000Z",
          "key": 1496102400000,
          "doc_count": 2,
          "count_of_events": {
            "value": 2
          }
        },
        {
          "key_as_string": "2017-05-31T00:00:00.000Z",
          "key": 1496188800000,
          "doc_count": 4,
          "count_of_events": {
            "value": 4
          }
        }
      ]
    }
  }
}

Answer: You can use Bucket Script Aggregation & Sum Bucket Aggregation to achieve this. Try below query.
GET myindex/_search?
{
  "size": 0,
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "PlateNumber": "111"
          }
        }
      ]
    }
  },
  "aggs": {
    "daily_intensity": {
      "date_histogram": {
        "field": "Datetime",
        "interval": "day"
      },
      "aggs": {
        "count_of_events": {
          "value_count": {
            "field": "Monthday"
          }
        },
        "check": {
          "bucket_script": {
            "buckets_path": {
              "count": "count_of_events"
            },
            "script": "return (params.count > 0 ? 1 : 0)"
          }
        }
      }
    },
    "bucket_count": {
      "sum_bucket": {
        "buckets_path": "daily_intensity>check"
      }
    }
  }
}


Creating an Avro schema for a simple json

Question: I'm trying to build an avro schema for the following json:
{
  "id":1234,
  "my_name_field": "my_name",
  "extra_data": {
      "my_long_value": 1234567890,
      "my_message_string": "Hello World!",
      "my_int_value":  777,
      "some_new_field": 1
  }
}

The value for 'id' and 'my_name_field' are known but the fields in 'extra_data' dynamically change and are unknown.
The avro schema I had in mind is:
{
    "name":"my_record",
    "type":"record",
    "fields":[
        {"name":"id", "type":"int", "default":0},
        {"name":"my_name_field", "type":"string", "default":"NoName"},
        { "name":"extra_data", "type":{"type":"map", "values":["null","int","long","string"]}     }
    ]
}

My first idea was to make 'extra_data' a record with a map, but this does not work:
{ "name":"extra_data", "type":{"type":"map", "values":["null","int","long","string"]} }

I get:
AvroTypeException: Expected start-union. Got VALUE_NUMBER_INT

apache gives some nice examples in https://cwiki.apache.org/confluence/display/Hive/AvroSerDe but none seem to do the job.
This is the unit test I run to check:
public class AvroTest {
@Test
public void readRecord() throws IOException {

    String event="{\"id\":1234,\"my_name_field\":\"my_name\",\"extra_data\":{\"my_long_value\":1234567890,\"my_message_string\":\"Hello World!\",\"my_int_value\":777,\"some_new_field\":1}}";

    SchemaRegistry<Schema> registry = new com.linkedin.camus.schema.MySchemaRegistry();
    DecoderFactory decoderFactory = DecoderFactory.get();

    ObjectMapper mapper = new ObjectMapper();
    GenericDatumReader<GenericData.Record> reader = new GenericDatumReader<GenericData.Record>();
    Schema schema = registry.getLatestSchemaByTopic("record_topic").getSchema();
    reader.setSchema(schema);

    HashMap hashMap = mapper.readValue(event, HashMap.class);
    long now = Long.valueOf(hashMap.get("now").toString())*1000;
    GenericData.Record read = reader.read(null, decoderFactory.jsonDecoder(schema, event));
}

Would appreciate help with this,
Thanks.
Answer: If the list of extra data fields is really unknown using multiple optional value fields may help, like this:
{
    "name":"my_record",
    "type":"record",
    "fields":[
        {"name":"id", "type":"int", "default":0},
        {"name":"my_name_field", "type":"string", "default":"NoName"},
        {"name":"extra_data", "type": "array", "items": {
            {"name": "extra_data_entry", "type":"record", "fields": [
                {"name":"extra_data_field_name", "type": "string"},
                {"name":"extra_data_field_type", "type": "string"},
                {"name":"extra_data_field_value_string", "type": ["null", "string"]},
                {"name":"extra_data_field_value_int", "type": ["null", "int"]},
                {"name":"extra_data_field_value_long", "type": ["null", "long"]}
            ]}
        }}
    ]
}

Then you can select the extra_data_field_value_* value based on the extra_data_field_type for that field.


How to select an element in list box by selenium in python

Question: I am totally new in python. I want to select an element in list box. I know it is such an easy task but I don't know why it is not working on my computer.
The URL is:
https://biruni.tuik.gov.tr/disticaretapp/menu_ing.zul
how can I choose one of them with with select?
from selenium import webdriver
from selenium.webdriver.common.by import By
import time
from selenium.webdriver.support.ui import Select

driver = webdriver.Chrome('C:\Webdriver\chromedriver.exe')
driver.get('https://biruni.tuik.gov.tr/disticaretapp/menu_ing.zul')
time.sleep(2)

I try a lot to select by:
select.select_by_visible_text("Partner country/ Country Groups")

or
driver.find_element(By.XPATH,'//*[@id="yXAPg2-cave"]').click()

But it does not work! I don't know why! May you help me?
Answer: You can click the desired element by selecting the element on the text it contains. The following code should work fine.
element = driver.find_element(by=By.XPATH,value='//*[contains(text(), "Partner country/ Country Groups")]')
element.click()


How to find $\lim_{n\rightarrow\infty}(1+\frac{4}{n+8})^n$

Question: I try to find
$$\lim_{n\rightarrow\infty}\bigg(1+\frac{4}{n+8}\bigg)^n$$
So I did a ratio test,
$$\lim_{n\rightarrow\infty}\frac{\bigg(1+\frac{4}{n+8}\bigg)^n}{\bigg(1+\frac{4}{n+9}\bigg)^{n+1}}$$
$$\lim_{n\rightarrow\infty}\frac{\bigg(1+0\bigg)^n}{\bigg(1+0\bigg)^{n+1}}$$
$$\lim_{n\rightarrow\infty}\frac{\bigg(1\bigg)^n}{\bigg(1\bigg)^{n+1}}=1$$
But this is wrong.
What is the right way to solve this?
Thanks
Comment: @AbelWong Rather use $\lim(1+\frac4{n+8})^{n+8}=\lim(1+\frac4m)^m=e^4,$ and $\lim(1+\frac4{n+8})^8=1.$
Comment: Use $\lim(1+\frac{1}{n})^n=e$. Let $n+8=4x$.
Comment: Anyway, your step $\lim_{n\to\infty}\frac{\left(1+\frac4{n+8}\right)^n}{\left(1+\frac{4}{n+9}\right)^{n+1}}=\lim_{n\to\infty}\frac{\left(1+0\right)^n}{\left(1+0\right)^{n+1}}$ was not correct. With such an erroneous "method", you could derive that $\lim_{n\to\infty}\left(1+\frac4{n+8}\right)^n=1,$ whereas in reality, this limit is $e^4.$
Comment: Simplify the ratio before taking the limit.
Comment: @Rócherz how?  .
Answer: $\lim_{n\to∞}( 1 + \frac{4}{n+8} )^n$
$=\lim_{n\to∞}( 1 + \frac{4}{n+8} )^{(n+8) -8}$
$=\lim_{n\to∞}\frac{( 1 + \frac{4}{n+8} )^{(n+8)}}{(1 + \frac{4}{n+8})^8}$
$= e^4$
Answer: $$a_n=\left(1+\frac{4}{n+8}\right)^n \quad \implies \quad \log(a_n)=n \log\left(1+\frac{4}{n+8}\right) $$ Let
$$\frac{4}{n+8}=\epsilon\implies n=4\frac{1-2 \epsilon }{\epsilon }\implies \log(a_n)=4\frac{1-2 \epsilon }{\epsilon }\log(1+\epsilon)$$ Use the series expansion of $\log(1+\epsilon)$
$$\log(a_n)=4\frac{1-2 \epsilon }{\epsilon }\Big[\epsilon -\frac{\epsilon ^2}{2}+\frac{\epsilon ^3}{3}+O\left(\epsilon ^4\right) \Big]$$ that is to say
$$\log(a_n)=4-10 \epsilon +\frac{16 }{3}\epsilon ^2+O\left(\epsilon ^3\right)$$
Continue with Taylor series
$$a_n=e^{\log(a_n)}=e^4\Big[1-10 \epsilon +\frac{166 }{3}\epsilon ^2+O\left(\epsilon ^3\right)\Big]$$
Comment: More simply: $\log(a_n)=4\frac{1-2 \epsilon }{\epsilon }\Big[\epsilon +o\left(\epsilon\right) \Big]\to4$ hence $a_n\to e^4.$
Comment: @AnneBauval. If I want a better asymptotics to inverse the problem
Comment: I don't understand what you mean by "inverse the problem". In view of the original question, I am afraid these subtleties are beyond the OP.


How to select a text box and resize using VBA?

Question: I am trying to resize the text box size using VBA. To do that I change the rectangle number in the VBA every time which is not serving the purpose of VBA.
I need to resize the selected text box based on value in other cells.
Sub ResizeTextBox()
    Dim shp As Shape
    Set shp = ActiveSheet.Shapes("Rectangle 39")
    shp.Height = Application.CentimetersToPoints(Range("Y5").Value)
    shp.Width = Application.CentimetersToPoints(Range("Y6").Value)
End Sub

How do I resize the selected text box based on value in cell Y5 and Y6?
Comment: You say that you want to increase the size of a "text box", yet, your code shows that you are resizing a shape. Which is it?
Comment: `Set shp = Selection`
Comment: @Ahmad, I don't want to increase the text box size rather I want to resize, So the size would be increased or decreased.
Comment: @TimWilliams, thanks for your reply. I am not a pro coder but try my best to develop with some myself. But here I got stuck. Could you please help me to write the line?
Comment: Replace your existing line with my line.
Answer: You can do something like this:
Sub ResizeTextBox()
    Dim shp As Shape

    'check a range is not selected
    If TypeName(Selection) <> "Range" Then
        With Selection
            .Height = Application.CentimetersToPoints(Range("Y5").Value)
            .Width = Application.CentimetersToPoints(Range("Y6").Value)
        End With
    Else
        MsgBox "First select a a shape for resizing"
    End If
End Sub

Comment: Thank Tim. It means a lot to me. It is working perfect.


Why can't I use my custom loadouts in training?

Question: Whenever I start a training match against bots, the item server doesn't work and I can't access my loadouts.
I've tried everything I can think of, such as the heartbeat command, restarting TF2, reconnecting, and even waiting a few days.
Comment: Is this server set up with the default port? If it is not, then the port you used may be causing the server to interfere with the connection between your client and the server. (And even if it is a "local offline game", it is still set up as a server, just not available for anyone but you to join.)
Answer: Listen servers are currently bugged - I would recommend trying a dedicated server, but that may be more trouble than it's worth.
Comment: Is there a source that confirms this?
Comment: @Robotnik I don't have an official source but I just created a local listen server and was not able to use a custom loadout.


How to check if AVCaptureSession preset resolution is supported in Swift

Question: For instance, I may want to set it to hd1280x720, but only if it's supported, and use a lower res that is supported otherwise.
session = AVCaptureSession()
if(**my device supports hd1280x720**){
  session!.sessionPreset = AVCaptureSession.Preset.hd1280x720
}else if(**my device supports 640x480**){
  session!.sessionPreset = AVCaptureSession.Preset.vga640x480
}

Comment: What about https://developer.apple.com/documentation/avfoundation/avcapturesession/1389824-cansetsessionpreset ?
Comment: Very cool. Make an answer and I'll check it off
Answer: Use  AVCaptureSession.canSetSessionPreset(_:):

Returns a Boolean value that indicates whether the receiver can use the given preset.
Comment: This always returns true. Any other way?
Comment: @unobatbayar: Sorry, that is all I know.


Prolog Database Rules

Question: I have 2 questions about Prolog Programming.
I have a database that looks like this:
message(bob,kelly).
message(patrick,ann).

The database continues in this format. So my question is in SWI Prolog how can I write a rule and save it while the database is open that will find out if bob sent or received any message?
The other one is to write a rule to see if two people sent or received messages between them I have an idea how to do that but its really confusing using SWI Prolog.
All the help appreciated!
Comment: (1) put the `message` statements into a file, (2) run your prolog environment and include the file, (3) enter a query, such as `message(bob, X).` and you'll see Prolog will give you values of `X` that are indicated in your data.
Answer: I think you've been confused by the Prolog notion of "database." Usually "relational database" is understood to mean RDBMS, which is an acronym for relational database management system. Prolog provides you with a relational database, but it isn't in-and-of-itself, a database management system.
Prolog doesn't "open a database", it "consults a file." When you do [foo], it just opens foo.pl, parses the contents into memory, and closes the file. The file does not remain "open." If you asserta/1 or retract/1 on facts that originated in that file, the changes happen in memory, but Prolog doesn't know or care that they came from that file, and Prolog won't ever magically reconsult the file after it is changed or write a new file to disk in its place.
If you want Prolog to know that Bob sent Kelly a message, you're going to have to assert it. If you want the file to remain up-to-date after that, you're going to have to open the file and write the data to it. More importantly, perhaps, you have to understand that if you run multiple Prologs, they're not somehow going to connect to and share a single database. They're both going to operate on their own in-memory store. This means if you do go to the trouble to make your changes persistent, you have to ensure that you only have one process using the file. If you have more than one, they'll stomp on each other's changes.

Prolog Database Rules


Jquery form validation

Question: I am using this script to see if a user has left any inputs invalid clientside.
$('#login_submit').click(function() {

var login_email = $('#login_email').val();
var login_password = $('login_password').val();

if (login_email.length == 0) {

    $('#login_email').css('background', 'red');
}

if (login_password.length == 0) {

    $('#login_password').css('background', 'red');
}
});

One thing I cannot work out is how to stop the form submitting as it would. I have tried return false; but this then makes the input fields backgrounds just flicker red.
Regards,
Answer: do
<input type="submit" onsubmit="return submitValidate()" />

and change your JS to:
function submitValidate() {
var login_email = $('#login_email').val();
var login_password = $('login_password').val();
var submit = true;

if (login_email.length == 0) {
   submit = false;
   $('#login_email').css('background', 'red');
}

if (login_password.length == 0) {
   submit = false;
   $('#login_password').css('background', 'red');
}
return submit;
}

Comment: Ok will try this, can you explain why this is different? I do not understand thanks.
Comment: Instead of receiving the call for being clicked, you want to receive the call for being submitted. If you ask to receive the call for being clicked your form will say: Okay, so you are going to do this function when you are clicked, and then I will submit, whereas it now says: Okay, I have been clicked, but I want to submit, but before that I need to run this code. You understand it is all about order. If you just ask for onclick, it will still submit, but if you ask for onsubmit your form will not submit if you ask it not to.
Comment: This a bit old school. With jquery you can overwrite the click and submit functions.
Comment: I love jquery, but this is too simple for you to do, why use jquery, when you could just use old methods.
Answer: $('#your-form-id').submit(function() {

    var errors = 0;
    var login_email = $('#login_email').val();
    var login_password = $('login_password').val();

    if (login_email.length == 0) {
       $('#login_email').css('background', 'red');
       errors++;
     }

    if (login_password.length == 0) {
        $('#login_password').css('background', 'red');
        errors++;
     }

   return errors ? false : true;
});

Fiddle demo: http://jsfiddle.net/xjNut/
Just make sure you don't have an input with name="submit" in the form. All other attributes are fine to have in the input.
Comment: you understand that is just a jquery version of exactly what I said.
Answer: Your problem is most likely because you're using a submit button:
    <input type="submit" ... />
You need to change it to a regular button:
    <input type="button" ... />
Then in your function you'll need to submit the form when the code is valid:
    $('#formId').submit();

Jquery form validation


Integrating button to change divergent bar chart in d3.js?

Question: I'm a complete newbie to d3and trying to create a divergent bar chart with an update button. I've gotten this far with modifying other people's code but seem to have broken it somewhere along the way!
Code as below:
`


redirect_to :action => :index in Rspec

Question:
I tried to google for the exact solution for my problem but didn't found any appropriate result, so I'm asking for the solution here.
Here is the important information
Ruby Version : ruby 2.2.4p230 (2015-12-16 revision 53155) [x86_64-darwin15]
Rails Version : Rails 4.2.0
Rspec Version : 3.5.4
I've a controller which has an action called clearCart which basically functions to clearing the cart session
Here is my action
def clearCart
  session[:cart] = nil
  redirect_to :action => :index
end

The main aim for the above action is to test redirect_to :action => :index.
Routes for the same action (if needed)
get 'cart/clear' => 'cart#clearCart'

Here is the Rspec test to test the same action
describe "GET #clearCart" do
  it "should clear cart" do
    get :clearCart
    subject { get :clearCart }
    subject.should redirect_to :action => :index
    # expect(response).to redirect_to(:index)
    # response.should redirect_to :index
    # before { post :clearCart }
    # render 'index'
    # specify { response.should redirect_to('frontend/cart/index') }
  end
end

(comments are the possible way which I tried to execute the test)
Here is my index action (if needed)
def index
  render 'frontend/cart/index' ,layout: false
end

I usually refer RELISH for guidance.
Thanks in advance for help.
Comment: That's nothing to do with the question itself, but I would suggest using snake_case for method name and rename it to clear_cart (https://github.com/bbatsov/ruby-style-guide#snake-case-symbols-methods-vars)
Comment: @lightalloy your suggestion will be appreciated. Thank you :)
Answer: If you have expect matchers the following code should work
describe "GET #clearCart" do
  subject { get :clearCart }
  it { is_expected.to redirect_to(action: :index) }
end

In case of shoulda matchers use
describe "GET #clearCart" do
  before { get :clearCart }
  it { should redirect_to(action: :index) }
end

redirect_to :action => :index in Rspec


Cant boot - no bootable device found

Question: I have installed Ubuntu on an Acer laptop, and after working fine for 5 months, today a have boot problems: no bootable device
I checked the BIOS and i can see the hard drive, but the hard drive is not listed when i boot ubuntu from a live usb. I also try the ubuntu boot repair and the results are here:
http://paste.ubuntu.com/10997880
Any suggestions or advices are really appreciated!
Answer:   ,    ?
If your BIOS saw the hard drive, you have to restore the Master Boot Record.
Do you have access to a console?
if yes, run this:
bootrec /FixMbr

if it doesn't help run this:
chkdsk : /f /r

And you can use Partition Magic app, boot this from USB and restore MBR.
Maybe these will help you:

* No bootable device error message on UEFI after installation
* http://ubuntuforums.org/showthread.php?t=1820247
* http://geek.co.il/2013/04/22/how-to-fix-no-bootable-device-after-ubuntu-installation
Comment: Thanks for the answer. I dont know why but today the laptop magically boots again. I think something is phisically wrong with the hard drive. Inmediatly backed up all my important files. Not sure if its safe to keep using this hard drive, i'll run all test, search for bad sectors, etc. Once again, thanks for the answer.

Cant boot - no bootable device found


Cannot mount USB, Ubuntu 10.04

Question: Using my Vodafone WebBook running Ubuntu 10.04, it suddenly stopped showing USB when inserted. I tried using another USB device, even a mouse. This also didn't work. Charging my phone via USB also doesn't work any more. If I press Ctrl + Alt + F12 then insert a USB device it says "cannot enumerate USB hub/port 1". What is going on?
Answer: Ubuntu 10.04 hasn't continued support. I recommend to you install 12.04lts or better 14.04lts
1.- Inser't USB when all of system is loaded.
2.- See at kernel log or system log if there's new hardware:
(all with root privileges)
my kern.log :   tail -20 /var/log/kern.log  - to see last 20 lines
Mar  9 08:52:49 gilito-MS-AF1511 kernel: [  188.426947] nspr-2: sending ioctl 5393 to a partition!
Mar  9 08:52:49 gilito-MS-AF1511 kernel: [  188.426964] nspr-2: sending ioctl 5393 to a partition!
Mar  9 09:01:59 gilito-MS-AF1511 kernel: [  738.144354] usb 3-1: new high-speed USB device number 4 using xhci_hcd
Mar  9 09:01:59 gilito-MS-AF1511 kernel: [  738.274613] usb 3-1: New USB device found, idVendor=13fe, idProduct=1d00
Mar  9 09:01:59 gilito-MS-AF1511 kernel: [  738.274617] usb 3-1: New USB device strings: Mfr=1, Product=2, SerialNumber=3
Mar  9 09:01:59 gilito-MS-AF1511 kernel: [  738.274619] usb 3-1: Product: DataTraveler 2.0
Mar  9 09:01:59 gilito-MS-AF1511 kernel: [  738.274620] usb 3-1: Manufacturer: Kingston
Mar  9 09:01:59 gilito-MS-AF1511 kernel: [  738.274622] usb 3-1: SerialNumber: 5B740689B724
Mar  9 09:01:59 gilito-MS-AF1511 kernel: [  738.274948] usb-storage 3-1:1.0: USB Mass Storage device detected
Mar  9 09:01:59 gilito-MS-AF1511 kernel: [  738.275048] scsi8 : usb-storage 3-1:1.0
Mar  9 09:02:00 gilito-MS-AF1511 kernel: [  739.273732] scsi 8:0:0:0: Direct-Access     Kingston DataTraveler 2.0 PMAP PQ: 0 ANSI: 0 CCS
Mar  9 09:02:00 gilito-MS-AF1511 kernel: [  739.274360] sd 8:0:0:0: Attached scsi generic sg5 type 0
Mar  9 09:02:00 gilito-MS-AF1511 kernel: [  739.457335] sd 8:0:0:0: [sde] 2015232 512-byte logical blocks: (1.03 GB/984 MiB)
Mar  9 09:02:00 gilito-MS-AF1511 kernel: [  739.457477] sd 8:0:0:0: [sde] Write Protect is off
Mar  9 09:02:00 gilito-MS-AF1511 kernel: [  739.457482] sd 8:0:0:0: [sde] Mode Sense: 23 00 00 00
Mar  9 09:02:00 gilito-MS-AF1511 kernel: [  739.457620] sd 8:0:0:0: [sde] No Caching mode page found
Mar  9 09:02:00 gilito-MS-AF1511 kernel: [  739.457623] sd 8:0:0:0: [sde] Assuming drive cache: write through
Mar  9 09:02:00 gilito-MS-AF1511 kernel: [  739.459288]  sde: sde1
Mar  9 09:02:00 gilito-MS-AF1511 kernel: [  739.460031] sd 8:0:0:0: [sde] Attached SCSI removable disk
Mar  9 09:02:02 gilito-MS-AF1511 kernel: [  741.866529] FAT-fs (sde1): Volume was not properly unmounted. Some data may be corrupt. Please run fsck.

3.- Mount your new partition in my case /dev/sde1 : mount -t vfat /dev/sde1
/mnt/
If you don't see any new USB device inserted in your log, there's a problem with USB device or USB drivers or USB port PC.

Cannot mount USB, Ubuntu 10.04


Pasting a range from one workbook to another as an offset

Question: The problem I'm having is that I am drawing a blank on copying a known range from one workbook to another, but after the last row ---but as an offset(3,0).  This is the entire code and really you can ignore the first 3/4 of it.... and start by where I'm setting ranges.  I would think that setting the range and doing a row offset from there, but clearly I'm not doing it correctly.
This is the line giving me an error: Set rngFinalRange... I know it's wrong, but I'm stuck. Thoughts?  Thank you!
    Option Explicit
    Sub TEST()

        Dim auditfolder As String
        Dim dumpfile As String
        Dim FSO As Object
        Dim fldstart As Object
        Dim wbkAudit As Workbook
        Dim wbkdump As Workbook
        Dim rngDumpCols As Range
        Dim rngDumpFullRange As Range
        Dim strAuditName As String
        Dim strDumpName As String
        Dim fl As Object
        Dim rngAuditFileRows As Range
        Dim rngAuditCols As Range
        Dim rngFinalRange As Range
        Dim rngauditrows As Range
        Dim lastrow as range

        Set FSO = CreateObject("scripting.FileSystemObject")

        With Application.FileDialog(msoFileDialogFolderPicker)
                .InitialFileName = "\\networkpath"
                .AllowMultiSelect = False
        If .Show <> -1 Then
                MsgBox "No file selected. Exiting."
        Exit Sub
        Else
                auditfolder = .SelectedItems(1)
        Set fldstart = FSO.getfolder(auditfolder)
        End If
        End With

        For Each fl In fldstart.Files
                If Right(fl.name, 3) = "xls" Then
                    If InStr(fl.name, "5ESS") Then
                         strAuditName = fl.name
                    ElseIf InStr(fl.name, "SelectDataDump") Then
                         strDumpName = fl.name
                    Else
                      MsgBox "Missing either the audit or selectdatadump file"
                    End If
                ElseIf Right(fl.name, 4) = "xlsx" Then
                    If InStr(fl.name, "5ESS") Then
                         strAuditName = fl.name
                    ElseIf InStr(fl.name, "SelectDataDump") Then
                        strDumpName = fl.name
                    Else
                      MsgBox "Missing either the audit or selectdatadump file"
                    End If
                End If
        Next fl

        Application.ScreenUpdating = False

        Set wbkdump = Workbooks.Open(strDumpName)
        Set rngDumpCols = wbkdump.Sheets(1).Cells.Find(what:="*", After:=wbkdump.Sheets(1).Cells(1, 1), LookIn:=xlFormulas, LookAt:= _
                          xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious, MatchCase:=False)
        Set rngDumpFullRange = wbkdump.Sheets(1).Range("A1", rngDumpCols.Address)

        Set wbkAudit = Workbooks.Open(strAuditName)
        Set rngAuditCols = wbkAudit.Sheets(1).Cells.Find(what:="*", After:=wbkAudit.Sheets(1).Cells(1, 1), LookIn:=xlFormulas, LookAt:= _
                           xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious, MatchCase:=False)
        Set rngauditrows = wbkAudit.Sheets(1).Range("A1", rngAuditCols.Offset(0, -4).Address)
lastrow = wbkAudit.Sheets(1).Cells(65536, rngAuditCols.Column).End(xlUp).Row
        Set rngFinalRange = wbkAudit.Sheets(1).Range(lastrow.Offset(3, 0).Row)
                    rngFinalRange.Value = rngDumpFullRange.Value

        wbkAudit.Sheets(1).Columns.AutoFit
        wbkAudit.save

        MsgBox "Processing Complete!"

    End Sub

Answer: lastrow is declared in your code as a Range object but you are attempting to set it to a Long value:
http://msdn.microsoft.com/en-us/library/office/ff196952.aspx
Try changing this...
lastrow = wbkAudit.Sheets(1).Cells(65536, rngAuditCols.Column).End(xlUp).Row
Set rngFinalRange = wbkAudit.Sheets(1).Range(lastrow.Offset(3, 0).Row)

...to this...
Set lastrow = wbkAudit.Sheets(1).Cells(65536, rngAuditCols.Column).End(xlUp)
Set rngFinalRange = wbkAudit.Sheets(1).Range(lastrow.Offset(3, 0).Address)

Comment: I tried this, but ended up with crazy results. I did, however make some progress.  this piece of code gives me only one cell value, but it's starting in the right spot:   Range("A" & lastrow).Offset(3, 0).Value = rngDumpFullRange.Value   The problem is that it's not pasting the whole rngDumpFullRange, which is A1:O204.  Thoughts?
Comment: lastrow = 125, so it's giving me the right value in A125, but that's it.
Comment: Ok, so you have `Range(lastrow.Offset(3, 0).Address)` but really you need something like `Range(lastrow.Offset(3, 0).Address, lastRow.offset(rngDumpFullRange.Rows.Count + 3, rngDumpFullRange.Columns.Count))`.  Make sense?  I don't have a worksheet like yours so I cannot test.


Ubuntu 18.04 ignores my gtk.css file

Question: In Ubuntu 16.04, I created a file ~/.config/gtk-3.0/gtk.css to replace the skinny scrollbar (on both firefox and emacs) that widens when you hover with one that is always wide, change the color of the scrollbar to a dignified gray, and have buttons at the top and bottom to single step:
.scrollbar {
  -GtkScrollbar-has-backward-stepper: true;
  -GtkScrollbar-has-forward-stepper: true;
  -GtkRange-slider-width: 16;
  -GtkRange-stepper-size: 16;

  background-color: LightGray;
}

/*
.scrollbar.slider {
    background-color: DarkGray;
    border-radius: 1px;
}
*/

.scrollbar.slider {
    border-color: shade (@bg_color, 0.4);
    background-image: -gtk-gradient (linear, left top, right top,
                                     from (shade (@button_bg_color, 0.9)),
                                     to (shade (@button_bg_color, 0.8)));
    box-shadow: inset 1px 0 shade (@bg_color, 0.85),
                inset -1px 0 shade (@bg_color, 0.62),
                inset 0 1px shade (@bg_color, 0.9),
                inset 0 -1px shade (@bg_color, 0.62);
}

This file seems to have no effect on Ubuntu 18.04.  I would very much like to eliminate the skinny scrollbar that widens only when the mouse hovers, and to change the color from the default orange to nice gray.  Can anyone tell me how to accomplish this in Ubuntu 18.04?
Answer: I'm answering my own question because no one has had any suggestions but after long experimentation I have something that mostly works.  I have the following in ~/.config/gtk-3.0/settings.ini
[Settings]
gtk-application-prefer-dark-theme=0
gtk-primary-button-warps-slider = false

and the following in ~/.config/gtk-3.0/gtk.css
scrollbar slider {
    /* Size of the slider */
    min-width: 18px;
    min-height: 18px;
    border-radius: 15px;

    /* Padding around the slider */
    border: 1px solid #606307;
}

scrollbar trough {
    background-color: shade(@theme_bg_color, 0.5);
}

scrollbar button,
scrollbar button.vertical,
scrollbar button.horizontal,
scrollbar .button,
scrollbar .button.vertical,
scrollbar .button.horizontal {
    color: shade(@theme_bg_color, 0.10);
    background-color: shade(@theme_bg_color, 0.6);
}

scrollbar.vertical slider,
scrollbar.vertical .slider {
    background-image: radial-gradient(ellipse at center, DarkGray 0%, LightGrey 100%);
}

scrollbar.horizontal slider,
scrollbar.horizontal .slider {
    background-image: radial-gradient(ellipse at center, DarkGray 0%, LightGray 100%);
}

That gives me a wide scrollbar with a light gray slider on a dard gray background, in both firefox and emacs.  I wish I knew why this worked, but I haven't found any documentation that explains the various commands.  The one strange thing that this does is that, in emacs, the scrollbar is slim until the first time the mouse passes over it, at which point it gets wide and stays wide.  Also, the scrollbar in emacs sometimes appears to be a slimmer one partly overlaying a wider one, in a way that's still useable but very strange.
Answer: I'm sorry I don't have a better answer, however, for what its worth, I've been trying to establish a frame of reference for this, and so far, struck out:
My objective was simply to set background colors for the workspace plugin (wnck-pager?) to the panel application under XUbuntu 16.04. Based on another answer tip
I found elsewhere, I created the gtk.css from scratch (there was none there to begin with), as follows:
~/.config/gtk-3.0 cat gtk.css
wnck-pager { background-color: #0F0000; }
wnck-pager:selected { background-color: #00000F; }
wnck-pager:hover { background-color: #000FA0; }
This enables me to see which workspace I'm in, since the default background colors are so similar, its difficult to notice. However, while attempting to export this fix to adjacent Xubu 16.04 systems, I found a much more ornate gtk.css file, with references that looked like they might be relevant. However, I have yet to track down the relevant docs. I think this may be part of a project called 'mono'...but you see, this is a classic rathole situation, all I wanted to do was find a way to set the 'hover' and 'selected' background colors on the workspaces under the panel app.
Bottom-line: on the second system (the one with the much larger gtk.css file), I set that file aside, and installed the one listed above, just to see if a) anything was broken, and b) if I could get the workspace selected background color on the panel to change. Nothing obvious was broken (by removing the more involved gtk.css file). However, the very simple gtk.css file I put in its place did not work on the second Xubuntu 16.04 workstation. Same gtk.css file on both systems, both 16.04 Xubuntu, one works, one doesn't.
Not sure how much more time I can invest in resolving this, but whatever additional results I get, I'll post them here.
Note to moderators: I know this doesn't answer the question, however, I am sharing my research. (Thanks for StackExchange. An outstanding, invaluable resource.)
Comment: Why don't you ask a new question: **How to set background colors for the panel's workspace plugin in XUbuntu 16.04.**? Then you can post your answer (and further updates) there instead.
Comment: Okay... Does anyone know which program or process resolves multiple inputs which affect a given panel? In other words, if two different processes have a config file which requires them to respond to a 'select rectangle' event on the desktop window, which one is processed last? (Case in point: if you select a theme 'Ambiance' with a gtk-main.css file containing: '@define-color selected_bg_color #ffffff', and your ~/.config/gtk-3.0/gtk.css file contains: wnck-pager:selected { background-color: #ff0000 }'... how is that resolved?
Comment: @TbThomas That is a good candidate to ask a new AskUbuntu question.
Answer: The appearance of the Firefox scrollbars can be changed by creating a new gtk.css in the Firefox profile folder. For me this is located at ~snap/firefox/323/.config/gtk-3.0 , but it may have a different location if you don't have a snap version.
The gtk.css file should contain the following code to allow you to adjust the appearance of both the vertical and horizontal sliders:
scrollbar.vertical slider {
/* Slider dimensions */

min-width: 12px;
min-height: 70px;

/* Curvature top and bottom of the slider */

border-radius: 12px;

/* Padding around the slider */

border: 4px solid transparent;

/* Colour of the slider */

background-color: #666699;

}
scrollbar.horizontal slider {
/* Slider dimensions */

min-width: 70px;
min-height: 12px;

/* Curvature top and bottom of the slider */

border-radius: 12px;

/* Padding around the slider */

border: 4px solid transparent;

/* Colour of the slider */

background-color: #666699;

}
Just play around with the values until you find something you like. There are various colour finders online which will give you the hexadecimal values for a given colour.

Ubuntu 18.04 ignores my gtk.css file