HTML 501 error using Python Requests

Question: I'm writing a Python script to search for train tickets. So my first step was trying to make a ticket search at https://venta.renfe.com/vol/inicioCompra.do
I have tried mechanize, but it gets:
RuntimeError: maximum recursion depth exceeded while calling a Python object

as soon as I open the url, probably due to some bad format at that website.
So next attempt was using Python Requests library, and use the same request headers I can see at firebug. So my code looks like:
import requests

headers = {'Cache-Control': 'max-age=0',
           'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
           'Accept-Encoding': 'gzip,deflate,sdch',
           'Accept-Language': 'es,en-GB;q=0.8,en;q=0.6',
           'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.72 Safari/537.36',
           'Content-Length': '118',
           'Content-Type': 'application/x-www-form-urlencoded',
           'Connection': 'keep-alive',
           'Host': 'venta.renfe.com'}

cookies = {'target': '_self',
           'pagina': '/vol/index.do',
           'mensajeErrorSesion': 'null (null-U014)',
           'url_logout': '/vol/index.do',
           'tipoUsuario': 'N',
           'JSESSIONID': '0000W1mXLh9qNdE6l-qaEExFc9Y:15df38flv',
           'org.springframework.web.servlet.i18n.CookieLocaleResolver.LOCALE': 'es_ES',
           's_cc': 'true',
           's_fid': '5C053C8CEF00A17B-2B7E62472A63CF66',
           's_nr': '1377790666229-New',
           'gpv_p6': 'Venta%3APagina%20Principal',
           's_sq': 'renfeprod%3D%2526pid%253DVenta%25253APagina%252520Principal%2526pidt%253D1%2526oid%253Djavascript%25253AestacionesAccesibles%252528%252529%25253B%2526ot%253DA Host:venta.renfe.com Origin:https://venta.renfe.com Referer:https://venta.renfe.com/vol/inicioCompra.do'}

payload = {'IdOrigen': 'Madrid (*)',
           'IdDestino': 'Oviedo',
           'FechaIdaSel': '15/11/2013',
           'FechaVueltaSel': '17/11/2013'}

r = requests.post('https://venta.renfe.com/vol/inicioCompra.do', data=payload, cookies=cookies, headers=headers)
print r

But then I'm receiving 501 HTML code error: Not implemented. I guess I'm missing something, probably cookie information, but I don't know where to get that cookie info, or if I'm missing anything else.
Any idea?
Comment: You are probably trying to login to a site that needs authentication?
Comment: @PrahaladDeshpande it's not the case. You can browse manually the website without any authentication
Answer: I looked through the site and it appears that you are using a GET HTTP method to retrieve the data when what you actually need is a POST.
Typically an HTTP 501 is sent across as a response to the client, when the web server does not understand the HTTP verb sent across by the client within the request.
Try changing the code:
r = requests.get('https://venta.renfe.com/vol/inicioCompra.do', data=payload, cookies=cookies, headers=headers)

to something like
r = requests.post('https://venta.renfe.com/vol/inicioCompra.do', data=payload, cookies=cookies, headers=headers)

Note : I have not used Requests, hence you may want to double check the function call parameters. For a quick reference see this link.
Hope this helps - and here is a dump of my header as visible in Chrome. Observe that you are missing the Content-Type, Content-Length parameters within the header. Also note the contents of the cookie.
Accept:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Cache-Control:max-age=0
Connection:keep-alive Content-Length:118
Content-Type:application/x-www-form-urlencoded

Cookie:target=_self; pagina=/vol/index.do; mensajeErrorSesion=null (null-U014); url_logout=/vol/index.do; tipoUsuario=N; JSESSIONID=0000W1mXLh9qNdE6l-qaEExFc9Y:15df38flv; org.springframework.web.servlet.i18n.CookieLocaleResolver.LOCALE=es_ES; s_cc=true; s_fid=5C053C8CEF00A17B-2B7E62472A63CF66; s_nr=1377790666229-New; gpv_p6=Venta%3APagina%20Principal; s_sq=renfeprod%3D%2526pid%253DVenta%25253APagina%252520Principal%2526pidt%253D1%2526oid%253Djavascript%25253AestacionesAccesibles%252528%252529%25253B%2526ot%253DA Host:venta.renfe.com Origin:https://venta.renfe.com Referer:https://venta.renfe.com/vol/inicioCompra.do
    User-Agent:Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.95 Safari/537.36

Comment: It's true that it should be a post instead of a get: my bad. But anyway it's giving me the 501 error. I still think it has something to do with cookies or some missing header.
Comment: @RomanRdgz I updated the answer with my cookie dump and the Request headers. could you check if this is useful to you?
Comment: Edited code. Not working. Maybe I'm formating the cookie info in a bad way. Where does the chrome browser get all of this info anyway? I should be getting it from the same place
Comment: Use the Chrome developer tools and check out this information within the Network tab. click on a link and you will see all the request headers, cookies and the responses

HTML 501 error using Python Requests


Logical operation to fill new colum in dataframe with character values

Question: I have a data frame on broadband data for various countries (take AT_df for example). The columns "ofWithTV" and "ofWithFT" are of type character and indicate whether each case (broadband offer) comes with a bundled TV access or Fixed Telephony access, with (or without any) both of them.
ofWithTV    ofWithFT
no          no
no          no
no          no
yes         no
yes         no
no          no
no          yes
no          yes
no          yes
no          yes
yes         yes
yes         yes

I want to create a new column "ofProduct" where those cases shall be called "Singleplay" where both events are "no", "TV Doubleplay" where the events are "yes"; "no", "FT Doubleplay" where the events are "no"; "yes" and "Tripleplay" where both events are "yes". Something like this:
ofWithTV    ofWithFT   ofProduct
no          no         Singleplay
no          no         Singleplay
no          no         Singleplay
yes         no         TV Doubleplay
yes         no         TV Doubleplay
no          no         Singleplay
no          yes        FT Doubleplay
no          yes        FT Doubleplay
no          yes        FT Doubleplay
no          yes        FT Doubleplay
yes         yes        Tripleplay
yes         yes        Tripleplay

For this, I need a logical operation to assign the new values "Singelplay, Doubleplay,..." without deleting/overwriting existing data. I already searched for something similar but cannot find/understand how those operations actually work..
I am new to this community and also new to R (first post here). Hope somebody can help.
Answer: We can use case_when from the dplyr.
library(dplyr)

dat2 <- dat %>%
  mutate(ofProduct = case_when(
    ofWithTV %in% "no" & ofWithFT %in% "no"   ~ "Singleplay",
    ofWithTV %in% "yes" & ofWithFT %in% "no"  ~ "TV Doubleplay",
    ofWithTV %in% "no" & ofWithFT %in% "yes"  ~ "FT Doubleplay",
    ofWithTV %in% "yes" & ofWithFT %in% "yes" ~ "Tripleplay"
  ))
dat2
#    ofWithTV ofWithFT     ofProduct
# 1        no       no    Singleplay
# 2        no       no    Singleplay
# 3        no       no    Singleplay
# 4       yes       no TV Doubleplay
# 5       yes       no TV Doubleplay
# 6        no       no    Singleplay
# 7        no      yes FT Doubleplay
# 8        no      yes FT Doubleplay
# 9        no      yes FT Doubleplay
# 10       no      yes FT Doubleplay
# 11      yes      yes    Tripleplay
# 12      yes      yes    Tripleplay

Or we can create a look-up table first and then join the table to the original data frame.
library(dplyr)
library(tibble)

look_up <- tribble(
  ~ofWithTV, ~ofWithFT, ~ofProduct,
  "no"     , "no"     , "Singleplay",
  "yes"    , "no"     , "TV Doubleplay",
  "no"     , "yes"    , "FT Doubleplay",
  "yes"    , "yes"    , "Tripleplay"
)

dat3 <- dat %>%
  left_join(look_up, by = c('ofWithTV', "ofWithFT"))
dat3
#    ofWithTV ofWithFT     ofProduct
# 1        no       no    Singleplay
# 2        no       no    Singleplay
# 3        no       no    Singleplay
# 4       yes       no TV Doubleplay
# 5       yes       no TV Doubleplay
# 6        no       no    Singleplay
# 7        no      yes FT Doubleplay
# 8        no      yes FT Doubleplay
# 9        no      yes FT Doubleplay
# 10       no      yes FT Doubleplay
# 11      yes      yes    Tripleplay
# 12      yes      yes    Tripleplay

DATA
dat <- read.table(text = "ofWithTV    ofWithFT
no          no
no          no
no          no
yes         no
yes         no
no          no
no          yes
no          yes
no          yes
no          yes
yes         yes
yes         yes",
                  header = TRUE, stringsAsFactors = FALSE)

Comment: Thanks a lot! Worked perfectly


Arquivo de queries do Magento

Question: Boa tarde,gostaria de saber aonde fica o arquivo que faz as querys no Magento. uso a versão 1.9.
Answer: A classe que executa queries depende do driver que está configurado no Magento. Se estiver usando mysqli seria nessa classe: https://github.com/OpenMage/magento-mirror/blob/magento-1.9/lib/Zend/Db/Statement/Mysqli.php
As queries são geradas em diferentes partes do sistema, mas normalmente são representadas não com SQL diretamente, mas através de collections. A classe Mage_Catalog_Model_Resource_Product_Collection por exemplo pode ser usada para buscar produtos, e essa classe herda da collection genérica, que por sua vez usa a Zend_Db_Select para construir a query.

Arquivo de queries do Magento


Lebesgue's criterion for Riemann-integrability - a maximal function approach possible?

Question: Lebesgue's criterion for Riemann-integrablity:

A function $f\colon[a,b]\to\mathbb R$ is Riemann-integrable if and only if it is bounded and continuous almost everywhere.

There are several proofs. I know one using du Bois-Reymond's criterion: a bounded function is Riemann-integrable if and only if for each $\epsilon>0$, there exists a positive number $\delta>0$ and a partition such that the total length of intervals on which the oscillation $>\epsilon$ is less than $\delta$. However, I would like to see whether we have a proof using the idea of maximal functions.
Extend the function from $[a,b]$ to $\mathbb R$ by $0$, we can reformulate the continuity as $\lim_{h\to0}(f(x+h)-f(x))=0$ for a.e. $x\in\mathbb R$.
We have seen many examples of convergence a.e. of which the proof takes advantage of a maximal function. For example, Lebesgue differentiation theorem follows from the fact that the Hardy-Littlewood maximal function is a bounded sublinear operator from $L^1$ to $L^{1,\infty}$. Similarly, Carleson's theorem follows from, say, the boundedness of the maximal Carleson operator.
I wonder whether we can prove the Lebesgue's criterion in a similar fashion.
Answer: Of course even if the question were more precisely formulated it's hard to imagine how one might prove the answer is no. But offhand it's hard to see how a proof via a maximal function is going to work. Because, by analogy with the results you mention that are proved using maximal functions, it seems like the relevant maximal function here is just $$Mf(x)=\sup_h|f(x+h)|,$$but that makes $Mf$ constant.


How many players have been out on 99 run in their international cricket match debut?

Question: Many players have been out on 99 over the years in international cricket match but the question is how many of those player became out in their debut match?
This Link of crickinfo shows many batsman who were dismissed for 99 in test.
So what is total number of player who got out in 99 at their debut game combining test, ODI, t20i?
Answer: Asim Kamal (PAK) '03
AG Chipperfield (AUS) '34
RJ Christiani (WI) '48
EJG Morgan (IRE) '06
SP Patil* (UAE) '14
All were dismissed at 99 in their debut. SP Patil was not out. Hope this helps!
http://stats.espncricinfo.com/ci/engine/stats/index.html?class=11;debut_or_last=1;filter=advanced;orderby=runs;runsmax1=99;runsmin1=99;runsval1=runs;template=results;type=batting


Integrating Normal Distribution with $1$, $x$, and $x^2$

Question: I am taking an introductory Machine Learning class but it has been a while since I took calculus. I am having a difficulty in understanding the following equations.
So we are currently talking about the Gaussian Distribution:
$$\int_{-\infty}^{\infty} N(x|\mu,\sigma^2)dx = 1$$
This makes sense to me as I understand that the sum of the probability distribution adds up to one.
Where I start to struggle is the following:
$$\int_{-\infty}^{\infty} N(x|\mu,\sigma^2)xdx = \mu$$
I dont understand how adding all the x values from $-\infty$ to $\infty$ gives us the mean.
And this is the next step in the equations, which once again, I cant follow but I believe If I can get the earlier one, this one will be easy as well.
$$\int_{-\infty}^{\infty} N(x|\mu,\sigma^2)x^2dx = \mu^2 + \sigma^2$$
Sorry for the trivial looking question. If I can wrap around the intuitive meanings the rest should be easier I feel. The content is from Pattern Recognition and Machine Learning.
Thank you
Comment: If $\phi(x)$ is a probability density function for a random variable $X$, then the expectation of $f(X)$ is $\int_{-\infty}^\infty f(x)\phi(x)\,dx$.
Comment: Try replacing the integral and the probability distribution function with what it would be for a random variable with a finite number of choices (so there would be a sum instead of an integral and actual probabilities instead of a probability distribution function).
Comment: you need to write down the concrete formula of N(x), then it will be done
Comment: If you review integration this will become much easier. Or Im sure wikipedia has the computations written out as they are quite well known.
Comment: PRML is a great book, *but* I think you should seriously consider some sort of introductory probability text/lecture notes to study first to get the most from this book or any other text in machine learning
Comment: That really seems like a good idea! Any recomendations? I can also go for online courses/videos.
Answer: just write it out:
$$
\int_{-\infty}^{\infty} N(x|\mu,\sigma^2)dx = \int_{-\infty}^{\infty} \dfrac {1}{\sqrt {2\pi} \sigma} e^{- \frac {(x-\mu)^2}{2\sigma^2}}dx=1
$$
and
$$
\int_{-\infty}^{\infty} N(x|\mu,\sigma^2)xdx =\int_{-\infty}^{\infty} \dfrac {1}{\sqrt {2\pi} \sigma} e^{- \frac {(x-\mu)^2}{2\sigma^2}}xdx
$$
change variables $z=\dfrac {x-\mu}{\sigma}$, we get
$$
=\int_{-\infty}^{\infty} \dfrac {1}{\sqrt {2\pi}} e^{- \frac {z^2}{2}}(\sigma z + \mu )dz=\sigma\int_{-\infty}^{\infty} \dfrac {1}{\sqrt {2\pi}} e^{- \frac {z^2}{2}} zdz+\mu\int_{-\infty}^{\infty} \dfrac {1}{\sqrt {2\pi}} e^{- \frac {z^2}{2}} dz
$$
the first integral in the right hand side is zero since the integrand is odd; the second is $\mu\int_{-\infty}^{\infty} N(x|0,1)dx=\mu$. Then we are done.
You can do the next case on your own.
Answer: In you second equation it is important to notice that you are weighting $x$ by the probability of getting $x$, so the most likely values are going to contribute more to the sum, than the less likely values. That's why
$$
\int_{-\infty}^{+\infty}{\rm d}x~xN(x|\mu,\sigma^2) = \mu
$$
All this is saying is that average value of $x$ is $\mu$.
As for the last equation, you're ultimately calculating the integral
$$
\int_{-\infty}^{+\infty}{\rm d}x~(x-\mu)^2N(x|\mu,\sigma^2)
$$
which just represents the average (squared) distance from the all points to the mean value $\mu$


What are the steps required to solve this system of equations?

Question: The system that I need to solve is
$$
\begin{align}
&i_1 + i_2+ i_3 &=0\\
&i_1+i_4+i_6 &=0\\
&i_5+i_6&=i_2\\
&-v_{s1} + i_1r_1 + i_3r_3 - i_4r_4 + v_{s4} &= 0\\
&-i_2r_2 + v_{s2} - i_5r_5 - i_3r_3 &= 0\\
&-v_{s4} + i_4r_4 + i_5r_5 - i_6r_6 - v_{s6} &= 0\
\end{align}
$$
for the variables $i_k$.
For the asker: the question as it should appear

You can see the original question at: http://fourier.eng.hmc.edu/e84/lectures/ch2/node2.html :example 2. Please provide the steps. Thank U in advance.
Comment: Someone took the time to format your wretched question decently, and you rolled it back! Why would you do such a thing?
Comment: What have you already tried?  What do you know about systems of simultaneous equations?  Also, please take the time to learn how to format your questions properly: http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference
Comment: What are the variables ? One way is to compute a Groebner basis (i suppose the system is quadratic, and not linear).
Comment: We have to find i1,i2,i3,i4,i5,i6.
Comment: This is a system of 6 linear equations in 6 unknowns. You can find methods in any linear algebra textbook, or online by searching for "system of linear equations".
Comment: Then it is even linear, and you can solve it.
Comment: Sorry let me put it back.I did it because it did not make any sense to me.
Comment: I have not done this. It has been edited by Omnomnomnom.
Answer: For convenience, let's rewrite the system as
$$
\begin{align}
&i_1 &&+ i_2 &&+ \,\,\,\,i_3 &&&&&&&&=0\\
&i_1 &&&&&&+i_4&&&&+i_6 &&=0\\
&&&-i_2&&&&&&+i_5&&+i_6&&=0\\
&r_1i_1 &&&&+r_3i_3  &&-r_4i_4  &&&&&&= v_{s1}-v_{s4}\\
&&&-r_2i_2 &&- r_3i_3 &&&&-r_5i_5 &&&&= -v_{s2}\\
&&&&&&& +r_4i_4  &&+r_5i_5  &&-r_6i_6 &&= v_{s4}+v_{s6}\
\end{align}
$$
(the above should look like this):
$\hspace{14mm}$
From there, you should be able to use Gaussian elimination
Comment: What have you written.I cannot understand
Comment: I just rewrote the system of equations so that the variables we want to solve for are lined vertically lined up.
Comment: The phrase, "multiplication-addition", means nothing to me, and I've been teaching Linear Algebra for 35 years.
Comment: @GerryMyerson after googling, I realize that not everyone uses the same term for it. That's the term I heard for Gaussian elimination before I was told it was Gaussian elimination.
Comment: Why has anybody given me 2 vote downs?
Comment: I think there might be a communication issue going on here. Can you look at my answer again? I've added something
Comment: So i can find the values of the six i variables by using the 1st three equation by using guassian elimination method, Right?
Comment: You can find the values by using all of the equations and using the Gaussian elimination method.  The trick for those last 3 equations is to put the constants (like vs4 and vs6) on the right side of the equation.
Comment: It does not appear as you have shown. It begins with "\begin{align}..."
Comment: All right.  Apparently, the computer you're using doesn't render mathjax.  To most other people looking at this question, what I wrote looks like the picture that I have uploaded.
Comment: Thanks Omnomnomnom. I finaaly understood.
Comment: Please put back the image.
Comment: I've changed the question so that, in the mean time, you can read it as I wrote it.  I put the image of your question up in your question.


Guardar dados e inserir na CheckBox

Question: Para começar vou já expor o meu problema: Depois da pessoa responsável por adicionar esse novo serviço como é que automaticamente irá aparecer no form onde está a lista de todos os serviços em forma de checkbox?
Neste momento estou a desenvolver um projeto de final de curso e a meio surgiu-me um problema que não sei como resolver.
Bem, é uma aplicação em Visual Basic que faz registos daquilo que um determinado aluno/professor faz na biblioteca escolar. Um dos botões que temos é inserção de um novo serviço que a biblioteca um dia mais tarde possa vir a adicionar à sua lista na base de dados. Num form à parte, iremos ter uma lista com esses dados todos da base de dados em checkbox para selecionar aquilo que o utilizador vai fazer na biblioteca para depois poder submeter.
Formulário do registo do novo serviço

A maneira como pensamos submeter os dados
(aqui aparecia uma nova checkbox, dependendo do que foi criado)
Comment: Seria interessante complementar sua pergunta com o código do seu formulário.
Comment: Ainda não existe código para isso é que pedi ajuda. Obrigado.
Comment: Você pode tentar usar um for e instanciar as checkbox manualmente ou usar um datagrid com binding.
Comment: O nosso objectivo era facilitar o trabalho da funcionária ou seja um código que automaticamente depois de inserido o serviço aparecesse nessa outra form como checkbox
Answer: Salve os serviços numa tabela do banco de dados. Para exibir todas as opções para o funcionário, o ideal é usar um ComboBox, pois o modo de apresentação independe da quantidade de serviços. Basta fazer um SELECT no banco e inserir os valores nas opções da ComboBox.
Comment: Muito obrigado peça sugestão, se calhar será a melhor opção. Mas imaginemos que a biblioteca terá um novo serviço por exemplo "jogos educativos" (apenas um exemplo) e aí este será inserido na base de dados, por sua vez não há esse registo do novo serviço na hora de a pessoa responsável pela biblioteca. Aí é que está a minha dúvida.
Comment: Você vai fazer o SELECT e colocar os resultados na tela na tela que o funcionário vai selecionar a atividade que o usuário vai fazer na biblioteca. Você vai obtê-las no banco de dados, entendeu? Na primeira tela você insere, na segunda você obtém.

Guardar dados e inserir na CheckBox


Please suggest the ( Interaction model of view model) MVVM design in the simple scenario discussed in the subject

Question: Data Layer
I have an Order class as an entity. This Order entity is my model object.
Order can be different types, let it be

A
B
C
D

Also Order class may have common properties like Name, Time of creation, etc.
Also based on the order type there are different fields that are not common.
View Layer
The view contains the following

Main Menu
ListView

The Main Menu contains the drop down menu button which is used to create the order based on the type selected from the drop down. The drop down contains the Order types ( A ,B , C and D).
There are different user control based on the order type. Like for example if user chooses to create an order of type A then different view with different inputs field is popped up.
Hence, there are four user control for each order type.
If user selects A option from the drop down then Order of type A is created and vica versa.
Now below is the List View that contains the List of orders so far created by the user.
To Edit any particular order user may double click the list view row. Based on the order type clicked by the user in the listview, the view of that order type opens in edit mode. For example if user selects an order type A from the list view then view for order type A open in edit mode.
Please suggest an interaction model for view models in the scenario discussed above.
Please excuse me if the query is very basic, since I am new new to MVVM and WPF.
Comment: where do you envisage the "edit mode" opening? So far you only describe a ListView...
Answer: Rather than give you a specific design, I'm going to suggest a different way of looking at the problem.
Make your xaml.  Now, if it could have the data organized in any way exposing any set of methods it wanted, what would that look like?  Don't even think about the real structure of the entities when imagining this.  More inheritance?  Less?  Up to you - whatever would be best for your View.
Okay, whatever you just described is your ViewModel.  Write the public API for that.  Then, hook it up to the actual underlying entities.
Answer: Is your main problem in how to create the correct View for the selected Order type? ie How does the drop down or the ListView trigger the correct Order view to be displayed.
If that's what you're getting at then you're going to want something like: When the user clicks on the list of Orders (for example) you'll need to change the some underlying ObservableCollection and send out some kind of notification or force it to do something on some kind of Workspace object. Probably the best way to understand that is to look at the MvvmDemoApp by Josh Smith as well as his article if you haven't already read it. From there zero in on the way he implements the WorkspaceViewModel as I think that might be the approach, or something like that, you are after for your Order view user controls. (if I've understood you correctly).


Create SVG text with javascript does not work as expected

Question: I'm having trouble making a SVG text element with javascript. The problem is that it is not scaling like it should when window resizes.
Look at this fiddle:
https://jsfiddle.net/cduL72mf/2/
Why is the javscript-generated "SVGtext 2" not behaving like "SVGtext 1", what I can see the output is exactly the same? What am I missing?

var xmlns = 'http://www.w3.org/2000/svg';
var svgelement = document.createElementNS(xmlns, 'svg');
svgelement.id='svg2';
svgelement.setAttribute('viewbox', '0 0 300 200');
document.body.appendChild(svgelement);

var svgtext = document.createElementNS(xmlns, 'text');
svgtext.id='text2';
svgtext.setAttribute('x', '56');
svgtext.setAttribute('y', '74');
svgtext.setAttribute('font-size', '33');
var textnode = document.createTextNode('SVGText 2');
svgtext.appendChild(textnode);
svgelement.appendChild(svgtext);
svg {
  width: 100%;
  height: 300px;
}
<svg id="svg1" viewbox="0 0 300 200">
  <text id="text1" x="56" y="74" font-size="33">SVGText 1</text>
</svg>
Answer: viewbox should be viewBox. It is case-sensitive.
The lower-case version in the other SVG ("svg1") is accepted because the HTML parser is more forgiving. It corrects that attribute name for you.

var xmlns = 'http://www.w3.org/2000/svg';
var svgelement = document.createElementNS(xmlns, 'svg');
svgelement.id='svg2';
svgelement.setAttribute('viewBox', '0 0 300 200');
document.body.appendChild(svgelement);

var svgtext = document.createElementNS(xmlns, 'text');
svgtext.id='text2';
svgtext.setAttribute('x', '56');
svgtext.setAttribute('y', '74');
svgtext.setAttribute('font-size', '33');
var textnode = document.createTextNode('SVGText 2');
svgtext.appendChild(textnode);
svgelement.appendChild(svgtext);
svg {
  width: 100%;
  height: 300px;
}
<svg id="svg1" viewbox="0 0 300 200">
  <text id="text1" x="56" y="74" font-size="33">SVGText 1</text>
</svg>


How to use fold to keep the values between function calls

Question: Consider having a list of 3 numbers where each number specify a shift in position and their value changes like this:
x starts off as zero and increases by one until 9 then y does the same and then z does the same. When they are all 9 they reset to zero.
I have written the following to that:
ShiftInX :: ShiftBy->ShiftBy
ShiftInX [z,y,9] = ShiftInY [z,y,0]
ShiftInX [z,y,x] = [z,y,x+1]

ShiftInY :: ShiftBy->ShiftBy
ShiftInY [z,9,0] = ShiftInZ [z,0,0]
ShiftInY [z,y,0] = [z,y+1,0]

ShiftInZ :: ShiftBy->ShiftBy
ShiftInZ [9,0,0] = [0,0,0]
ShiftInZ [z,0,0] = [z+1,0,0]

Also, there are 3 strings:
s1 = "ahsgtdfyu"
s2 = "kfhyrdncl"
s3 = "polsedrtd"

Given a string, I want to take each character of the given string, find it in s3, shift it by x, take that letter and find it in s2, shift it by y, take that letter and find it in s3 and shift it by z and retuen the character.
Do the same for each character of the given string. Before processing each character, the ShiftBy list changes as described at the begining.
I have written a function that gets a character and a shiftBy list as input and returns a character as output. It finds the output caharacter as described above.
    findChar :: String -> Char -> [Int] -> Char
Problem: I want to be able to call this function for each character of the given string but not loose the values of the shiftBy numbers so that the shiftBy number increase for each new character.
processString :: String -> [Int] -> String
I used map for this but the values are lost after each characetr is processed.
I am told i have to use Fold or explicit recursion for this. I understand what fold does but don't know how to use it here. Can anyone please help with this?
Many thanks
Answer: Your description is very confusing. If I understand correctly, you have a sort of encryption scheme, where s1, s2 and s3 are the key and the ShiftBy list is an encryption state that changes as you go through the string to be encrypted.
What I don't understand is what you mean by  "find it in s3, shift it by x". Do you mean a ROT encoding? Do you mean finding the index and then adding x to it to find the next character, rotating around the end? Do you mean actually modifying the key?
In any case, it sounds like the signature of your current character encryption function is
encryptChar :: Char -> ShiftBy -> Char

when it should be
encryptChar :: Char -> ShiftBy -> (Char, ShiftBy)

i.e. it needs to return the adjusted encryption state.
Or alternatively, don't pass out the altered encryption state and modify it outside, since it doesn't depend on the character.
So as for the fold, the key is to make the encryption state part of the fold state. Here's one way to do this:
-- Given:
encryptChar :: Char -> ShiftBy -> Char
adjustShiftState :: ShiftBy -> ShiftBy -- really just an alias of ShiftInX
-- You can fold thus:
encrypt :: String -> String
encrypt msg = fst $ foldr foldOne initialState msg
    where initialState = ("", [0, 0, 0])
          foldOne ch (encryptedString, shiftState) =
            (encryptChar ch shiftState : encryptedString, adjustShiftState shiftState)

In other words, as you fold, you always keep a pair of the encrypted string so far and the current shift state. At the very end of the encryption, you take the result string and throw the shift state away.
The above is efficient; however, it doesn't do quite what you want, since it goes through the string in reverse. You need a left fold, which (because the way : works) is a bit more complicated, and probably less efficient. (Judicious application of strict left fold and strictness markers could probably be used after profiling reveals issues.)
Here's the left fold version:
encrypt msg = fst $ foldl foldOne msg initialState
    where initialState = ("", [0, 0, 0])
          foldOne (encryptedString, shiftState) ch =
            (encryptedString ++ [encryptChar ch shiftState],
             adjustShiftState shiftState)

Note the use of list concatenation instead of simple cons.


is there an easy way to determine who my ubuntu server is talking to?

Question: I am running Ubuntu Server and using putty to check on it from time to time.  There shouldn't be any traffic at all on this machine unless I initiate it.  About once/twice per month when I run 'vnstat -l' to check the traffic, I notice that it's transmitting and receiving more than usual.
I want to know exactly what it's doing.  I have been a Windows admin for years and know my way around Microsoft like the back of my hand.  I can look at the services/processes running on any Windows machine and easily identify them.  I can't do this with linux yet.  I want to be just as comfortable with Ubuntu (as I am with Windows), which is why I have set up this machine.
I would like to be pointed in the right direction here.  I know a handful of basic commands and have some Linux cheatsheets with some vague suggestions, which usually suffice, but I am still not satisfied that my machine is safe.
I am running ufw with one open port, 22, for putty.  When I use the machine for other things I usually open up other ports, such as 80, but immediately close it when finished.
Comment: There are several services that may initiate outgoing connections from an Ubuntu machine.  Checking for update packages and network time synchronization come to mind.
Answer: You could use netstat -a for this task. It shows every connection the system currently has.
If you want to monitor every single packet you should have a look at tcpdump or tshark.
Comment: tcpdump sounds like the best option to me.  You probably want to use the `-w file` flag to it so you can save the dump for future analysis.  You can then load this file into Wireshark and that application will make it a little easier to analyze.
Comment: `netstat -a` shows all connections; `netstat -l` shows only shows listening connections.
Answer: apt-get install ntop
ntop is a service that will monitor and report on all network traffic.  You can access it on port 3000 with a web browser.
** Edit to include some command line utilities I use (ntop remains more valid to this question for it's ability to store and view historical data)**
As Wienczny points out below, iptraf is an excellent curses based monitor
pktstat performs a similar function to iptraf but also displays a real-time list of active connections seen on a network interface, and how much bandwidth is being used by what. Partially decodes HTTP and FTP protocols to show what filename is being transferred. X11 application names are also shown. Entries hang around on the screen for a few seconds so you can see what just happened. Also accepts filter expressions á la tcpdump.
iftop displays bandwidth usage on an interface. iftop does for network usage what top does for CPU usage. It listens to network traffic on a named interface and displays a table of current bandwidth usage by pairs of hosts.
tcptrack is a sniffer which displays information about TCP connections it sees on a network interface. It passively watches for connections on the network interface, keeps track of their state and displays a list of connections in a manner similar to the unix 'top' command. It displays source and destination addresses and ports, connection state, idle time, and bandwidth usage.
Comment: installed..and I like it.  Thanks for the suggestion.
Comment: an alternative to ntop with more settings is iptraf


Evaluate the integral $\int \frac{dx}{x^3 + 2x^2 + 2x}$ of a rational function

Question:
Evaluate $$\int \frac{dx}{x^3 + 2x^2 + 2x}.$$

I have no idea how to approach this. I know how to solve rational functions with numerator as highest degree polynomial using division and remainder.
How do I go about this type of question?
I am more interested in the approach and general procedure rather than the answer itself, so that I can answer questions like these in the future.
Comment: You forgot $dx$. Sorry for being annoying, but I'd rather be annoying now than seeing you getting point off on your test...
Answer: Hint Using the factorization of the denominator, we can rewrite the integrand as
$$\frac{1}{x^3 + 2x^2 + 2x} = \frac{A x + B}{x^2 + 2 x + 2} + \frac{C}{x}$$ for some unique constants $A, B, C$. To find those constants, cross-multiply to clear denominators, distribute, and then compare like terms in $x$. This is the so-called partial fractions decomposition of the given rational function.

 Additional hint When integrating the first summand above, substitute $u = x + 1$ so that the denominator becomes a sum $u^2 + 1$ of squares.
Answer: Hint:
First, you must re-write the integrand using partial fractions decomposition:
$\begin{align*}
\frac{1}{x^3+2x^2+2x}&=\frac{\frac{1}{2}}{x}+\frac{-\frac{1}{2}x-1}{x^2+2x+2}\\
&=\frac{1}{2}\frac{1}{x}-\frac{1}{2}\frac{(x+1)+1}{(x+1)^2+1}
\end{align*}$
Answer: Extract $x$ out of denominator and you can have
$$\frac{1}{x^3+2x^2+2x} = \frac{1}{2}\left(\frac{1}{x} - \frac{x+2}{x^2+2x+2}\right)$$
Now you can integrate. If you still have problem on the second term, the hint is use substitution.


How do i do some search feature like this

Question: I have a requirement like this show in image

Like left hand side i need to show some fields data and when i click on the links i should filter out the data in content area. and its should be like a AND operation ? I need to use VIEWS and what else modules are needed for this thing to be completed?
Comment: Should items on the left hand side be taxonomy terms ?
Comment: It will be some node reference texts in one section and some taxonomy terms. If it can be done using taxonomy completely i can change it.
Comment: Most probably the keyword here is "faceted search". Are you looking for such a solution ? (http://en.wikipedia.org/wiki/Faceted_search)
Answer: This is related to the issue on D7 Faceted Search module here.
Using specialized search systems (Solr, Sphinx, Xapian, or others) is the way to go.
You can get results with Solr, the Apache Solr Search Integration module, and customizations.
Comment: can i make this work without using Solr i.e. just by using drupal DB ?
Comment: Try http://drupal.org/project/faceted_search on D6. This is not for D7.
Comment: For Solr you need access via ssh and to be able to install java and solr packages. You don't need a separate mysql database. If you prefer, you can use Solr search offered as a service http://www.acquia.com/products-services/acquia-search.
Comment: you mean to say that with out solr on D7 faceted wont work?
Comment: I mean drupal.org/project/faceted_search project doesn't work on D7.
Comment: @ refineo - yup saw that and they have no idea of porting it to D7 also


Ajax JavaScript Post Authentication Failed

Question: Eu tenho uma LP que submete um formulário. Estou fazendo um teste para chamar um POST quando clicar no Botao enviar um JSON para minha API.
O JSON é convertido.
Mas quando chama o post do $.ajax dá ERR_CONNECTION_TIMED_OUT.

Segue o javascript utilizado:


Determine whether this set of vectors is linearly independent

Question: For $n \geq 1$ determine if the set $S$ is linearly independent.
The set $S$ is these vectors:
$$
v_1 \equiv(\,1,2,\ldots,n\,)\,,\quad
v_2 \equiv(\,1,2^2,3^2,\ldots,n^2\,)\,,\ldots\,
v_n \equiv(\,1,2^n,3^n,\ldots,n^n\,)
$$
I know for vectors to be linearly independent we usually multiply by a scalar  to each vector and see if it equals the zero vector
(i.e. $av_1 + bv_2 + cv_3=0$ ), but I've attempted it that way but am having trouble solving it when its a series involving $n$'s.
All help would be appreciated
Answer: It is very similar to Vandermonde matrix , except that your matrix does not have the all 1 column. If the determinant is not zero, then the matrix is a full rank matrix and the columns are independent.
Answer: Consider the matrix consisting of those vectors of columns, call it $M_n$. Then by induction it can be shown that
$$\det M_n = 1!\cdot2!\cdot3!\cdots n!$$
Prove this and you're home. (I wish I could say it's a one line proof. Nice result though.)
Comment: Any chance you could give me a little help with the induction proof? What assumption did you make
Answer: If $n=3$ it is
$$\left|\begin{array}{rrr} 1 & 1 & 1 \\ 2 & 2^2 & 2^3 \\ 3 & 3^2 &  3^3 \end{array}\right|=\left|\begin{array}{rrr} 1 & 1 & 1 \\ 0 & 2 & 2^2 \\ 0 & 2\cdot 3 &  2\cdot 3^2 \end{array}\right|=\left|\begin{array}{rr}   2 & 2^2 \\  2\cdot 3 &  2\cdot 3^2 \end{array}\right|=2^2\cdot 3 \left|\begin{array}{rr}   1 & 2 \\  1 &  3 \end{array}\right|\ne 0.$$
If $n=4$ it is
$$\left|\begin{array}{rrrr}1 & 1 & 1 & 1 \\ 2 & 2^2 & 2^3 & 2^4 \\ 3 & 3^2 & 3^3 & 3^4 \\4 & 4^2 & 4^3 & 4^4 \end{array}\right|=\left|\begin{array}{rrrr}1 & 1 & 1 & 1 \\ 0 & 2 & 2^2 & 2^3 \\ 0 & 2\cdot 3 & 2\cdot 3^2 & 2\cdot 3^3 \\ 0& 3\cdot 4 & 3\cdot 4^2 & 3\cdot 4^3 \end{array}\right|=\left|\begin{array}{rrr} 2 & 2^2 & 2^3 \\ 2\cdot 3 & 2\cdot 3^2 & 2\cdot 3^3 \\ 3\cdot 4 & 3\cdot 4^2 & 3\cdot 4^3 \end{array}\right| \\=2^2\cdot 3^2 \cdot 4\left|\begin{array}{rrr} 1 & 2 & 2^2 \\ 1 & \cdot 3 & 3^2 \\ 1 & 4 &  4^2 \end{array}\right|\ne 0.$$
You can get the solution for arbitrary $n$ using induction.


thread malfunction II

Question: Another question:
Now is posible to start the thread, the problem is this: click button1 and thread start, click button2 and set running to false so thread finish. The problem is if I click button1 again then error and aplication stop.
Please, where is the problem??? Thank in advance.
activity_main.xml
<Button
   android:id="@+id/button1"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:onClick="gestionbotones"
   android:text="Thread ON" />
<Button
   android:id="@+id/button2"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:onClick="gestionbotones"
   android:text="Thread OFF" />

MainActivity.java
public class MainActivity extends Activity {
.......
private HiloJuego hj = new HiloJuego();
.......
public void gestionbotones (View v){
    int id = v.getId();
    switch(id){
    case R.id.button1 :
        Log.d(TAG, "Thread activado");
        hj.setRunning(true);
        hj.setTurno(true);
        hj.start();
        break;
    case R.id.button2:        //    Desactivar
        hj.setRunning(false);
        Log.d(TAG, "Thread destruído");
        break;
    default:
        break;
    }
}

HiloJuego.java
package com.example.tocatoca1;
import android.util.Log;
public class HiloJuego extends Thread {
    private static final String TAG = HiloJuego.class.getSimpleName();

    private boolean running;
    private boolean turno;
    public void setRunning(boolean running) {
        this.running = running;
    }
    public void setTurno(boolean turno){
        this.turno=turno;
    }
    public HiloJuego() {
        super();
    }
    @Override
    public void run() {
    Log.d(TAG, "Starting game loop");
    while (running) {
        if (turno){
            Log.d(TAG, "Turno Ordenador");
        } else{
            Log.d(TAG, "Turno Jugador");
        }
    }   // end finally
}
}

Comment: No Gray, is another question over the almost the same code (hj.start()). Is another question. Thanks.
Comment: @josemfr Generally, you should show your stack trace for your error.
Comment: http://stackoverflow.com/questions/1881714/how-to-start-stop-restart-a-thread-in-java
Answer: You can't restart threads in Java. You have to create a new one. You are trying to reuse the same one that you stopped previously.
Answer: You are trying to start an already started thread when clicking next time.
if(!hj.isAlive()) {
    hj.setRunning(true);
    hj.setTurno(true);
    hj.start();
}

Comment: The same error. Thanks.

thread malfunction II


Gerar um Partial Model a partir de um Model completo

Question: Tenho uma Model chamado: Cliente_man que representa o cadastro de clientes.
Porém este Model, tem muitas informações, e para a tela que estou desenvolvendo não ah necessidade de todas, então gostaria de passar para a View um Partial Model somente com os dados que eu preciso usar.
Segue abaixo parte do código recebendo o Model completo(Cliente_Man)
Controller:
    [ValidateInput(false)]
    public ActionResult DetailTabControl()
    {
        if (Session["cod_cli"] != null)
        {
            int codCliente = Convert.ToInt32(TempData["codCliente"]);

            Cliente_man model = db.Cliente_man.Find(codCliente);

            return PartialView("~/Views/Cliente_man/_DetailTabControl.cshtml", model);
        }
        else
        {
            return RedirectToAction("Login", "Account");
        }
    }

View:
@model OneeWeb_v3.Models.Crm.Cliente_man

    @Html.DisplayFor(model => model.razao_social).ToHtmlString()

Então, criei um novo Model chamado: Cliente_manDetalhes, que contem somente os dados que eu preciso.
Alterei na View:
@model OneeWeb_v3.Models.Crm.Cliente_manDetalhes

    @Html.DisplayFor(model => model.razao_social).ToHtmlString()

E no Controller:
 [ValidateInput(false)]
    public ActionResult DetailTabControl()
    {
        if (Session["cod_cli"] != null)
        {
            int codCliente = Convert.ToInt32(TempData["codCliente"]);

            //Cliente_man model = db.Cliente_man.Find(codCliente);

            Cliente_manDetalhes mode = from s in db.Cliente_man
                                       where s.id_cliente == codCliente
                                       select new
                                       {
                                           id_cliente = s.id_cliente,
                                           nome_fantasia = s.nome_fantasia,
                                           Perfil = s.Perfil,
                                           n_doc = s.n_doc,
                                           cidade = s.cidade,
                                           siglaEstado = s.siglaEstado
                                       });

            return PartialView("~/Views/Cliente_man/_DetailTabControl.cshtml", model);
        }
        else
        {
            return RedirectToAction("Login", "Account");
        }
    }

Porém como faço para recuperar as informações do Model Cliente_Man? Ao o código acima retorna o erro:
Cannot implicity convert type 'System.Linq.IQueryable<<anonymous type:int id_cliente, string nome_fantasia, string Perfil, string n_doc, string cidade, string siglaEstado>>' to 'OneeWeb_v3.Models.Crm.Cliente_manDetalhes'. An explicit conversion exists
Comment: Thomas, por favor, sempre adicione as mensagens de erro como texto e não como imagens. Além de facilitar a leitura e a melhorar a indexação da pergunta, evita de que pessoas com bloqueios a domínios externos não consigam ler toda a publicação.
Comment: esse Cliente_manDetalhes  'e o mesmo que Cliente_man ? a sua query retorna os valores para esse modulo de forma correta? se sim apenas coloque (esse Cliente_manDetalhes) na frente da query
Answer: Tem vários erros aí.
Pra começar. Esta consulta
from s in db.Cliente_man
where s.id_cliente == codCliente
select new
{
    id_cliente = s.id_cliente,
    nome_fantasia = s.nome_fantasia,
    Perfil = s.Perfil,
    n_doc = s.n_doc,
    cidade = s.cidade,
    siglaEstado = s.siglaEstado
});

retorna uma lista de objetos de um tipo anônimo, uma vez que você usou a keyword new e não especificou o tipo a ser criado.
Você está tentado atribuir o resultado da consulta a uma variável do tipo Cliente_manDetalhes.
Seria possível adaptar a consulta para retornar uma lista de Cliente_manDetalhes, alterando a instrução select para
select new Cliente_manDetalhes { ... }

A atribuição continuaria errada porque o retorno disso será uma coleção de Cliente_manDetalhes e, além disso, o EF não conseguiria criar instâncias de
Cliente_manDetalhes.
Bem, a solução é simples, você precisa materializar os dados antes de tentar fazer o mapeamento para Cliente_manDetalhes.
Como você precisa de um item e não de uma coleção, pode facilitar a sua consulta usando First/FirstOrDefault, mas precisaria fazer este mapeamento de outra forma que não usando o método Select.
var item = db.Cliente_man.FirstOrDefault(s => s.id_cliente == codCliente);
var mode = new Cliente_manDetalhes
{
    id_cliente = item.id_cliente,
    nome_fantasia = item.nome_fantasia,
    Perfil = item.Perfil,
    n_doc = item.n_doc,
    cidade = item.cidade,
    siglaEstado = item.siglaEstado
};

Se você fizer questão de usar o método Select para isso, vai precisar adaptar sua consulta. Seria algo como:
(from s in db.Cliente_man
where s.id_cliente == codCliente
select s)  // #1 Consulta LINQ To Entities - Retorna uma lista de Cliente_man
.ToArray() // #2 Materialização da consulta em memória
.Select(s => new Cliente_manDetalhes
{
    ... // #3 Mapeamento da lista de Cliente_man para Cliente_manDetalhes
})
.FirstOrDefault(); #4 // Seleção do primeiro item


Mount an only FTPS reachable storage?

Question: I recently purchased a domain that comes with 10 GByte storage. I could be only reachable with FTP over TLS.
Are there any methods to "mount" this storage like when e.g.: using SSHFS?
Comment: I found it!! - CurlFtpFS
Answer: In most cases; yes.   However this is achieved through software (usually run in userspace) and sometimes can cost money.
Since you didn't nail down what client-operating system, here's the broad ones.
Windows / OSX : http://www.expandrive.com/   Expandrive can "mount" a FTP(SSL) & sFTP drive just like a USB storage device.
Linux: CurlFtpFS should be able to mount it with FUSE.

Mount an only FTPS reachable storage?


Hierarchical Select reset when I click add another item

Question: I have a custom content type that has an unlimited field. This field is from field collection type and it contains a field that is from taxonomy type and with a hierarchical select widget. When I want add a node of that type and choose a value for hierarchical select field and then click add another item the value of the hierarchical select will reset. What is the problem?
Answer: Temporarily I fixed it by rearranging the hierarchical select field at top and add another item field(image field) at the bottom of that field.
You can rearrange the field under Mange Fields.
Comment: Do you mean that I rearrange the field collection fields? I did it and change the order of fields in field collection and the taxonomy term field is the first field and there are 5 other fields next to that but when I click _add another item_ the selected value for the previous item's taxonomy term will remove.
Comment: @SaeedRajabi I done this without field collection, I think you have to submit a bug to hierarchical select issue queue.


How do I interact with the virtual machine from Hyper-V host?

Question: I'm running a hypervisor Hyper-V on server hardware. I exported two virtual machines from elsewhere and I want to start them here while disconnected from the LAN. I'm on a terminal session on the Hyper-V with Task Manager, command line and Powershell; I don't have a GUI interface. So I started them just fine using Start-VM from Powershell.
How do I interact with the virtual machine? Normally while on the LAN I remote into the VM. But now I'm disconnected from the LAN. How do I start a terminal session (or remote into) the VM?
Answer: I believe what you are looking for is the Hyper-V Virtual Machine Connection tool. The tool can be installed easily on other servers and it uses the host to provide the connection to the guest, which gets around your no guest networking issue.
Comment: Your Hyper-V server should be on the network and nothing should be keeping you from putting it on the network. If you don't want your migrated guests to have any networking then just remove/disable the virtual NIC in the guest's machine config. This allows you to have the Hyper-V host on the network, the guests off the network, and then you to be able to use a tool like VMConnect to have remote console access.
Comment: I don't have VMConnect.exe and I don't have a start button: I don't have Windows Server etc. I can't find the Connection Tool for download. I'm not sure if it can be installed.
Comment: I'm thinking maybe not possible to do what I want to do.
Comment: @D_Bester That doesn't make sense. You don't install this on your Hyper-V server, you install it on your local workstation, laptop, etc. It then connects from your computer to the Hyper-V server. That tutorial is extremely out of date though and doesn't really explain how to install the Hyper-V management tools on modern Windows. Try something like [this](https://petri.com/workaround-finding-missing-hyper-v-tools-windows-10).
Comment: @MichaelHampton Well I guess you're agreeing with me then that it can't be done on the Hyper-V Server. Thanks for that confirmation. Remember, I don't have it on the network.


Installing MongoDB on CentOS 5.5 32bits

Question: I'm trying to install mongoDB on my CentOS 5.5 32bits VPS server which is going without any trouble until I try to install the PHP driver.
Logged in as root i do
$ pecl install mongo

Resulting in the error

Cannot find autoconf. Please check your autoconf installation and the
  $PHP_AUTOCONF environment variable. Then, rerun this script.

I tried to manually download it from github but when executing a phpize on that one I get the same error.
Hopefully someone can help me with installing the driver.
Comment: Thanks for the awnsers, @Phil: your comment did the trick.
Thanks again!
Comment: @Phil, can you post your comment as an answer so that sandermangel can accept it?
Comment: Voting to move to ServerFault. In the meantime, try installing `autoconf`, `make` and `gcc` via yum
Comment: I agree that you'll surely have better luck on serverfault. you could also install mongo via yum. maybe [this](http://www.easyflip.co.uk/farnell_2010PT/ebook.html) helps.
Answer:
Make sure you have the correct permissions to install mongodb
Install the development tools (quite a lot of packages to install, you may want to install only some if you have a low bandwidth or not enough disk space): yum groupinstall "Development Tools"
Comment: Thanks for the awnser, i managed to do it by installing try installing autoconf, make and gcc via yum and then $sudo pecl install mongo
Answer: Try installing autoconf, make and gcc via yum, then sudo pecl install mongo

Installing MongoDB on CentOS 5.5 32bits


No 'Access-Control-Allow-Origin' - Node / react / socket.io

Question: I have try to use socket.io in my project to do real-time notifications, but I got a console error, here's my example backend (nodejs):
const express = require('express');
const app = express();
const Server = app.listen(1337);

const io = require('socket.io')(Server, {
    origins: ["http://localhost:3000"],
    handlePreflightRequest: (req, res) => {
        res.writeHead(200, {
          "Access-Control-Allow-Origin": "http://localhost:3000",
          "Access-Control-Allow-Methods": "GET,POST",
          "Access-Control-Allow-Headers": "my-custom-header",
          "Access-Control-Allow-Credentials": true
        });
        res.end();
    }
});

io.on('connection', (socket) => {
    console.log('connected');
    socket.on('message', (message) => {
        console.log('message');
    })
    socket.emit('message', 'toto');
});

frontend (Reactjs) :
import './App.css';
import React, {useState, useEffect} from 'react';
import io from 'socket.io-client'

const socket = io('http://localhost:1337',{
  withCredentials: true
})

function App() {
  return (

    {/*  */}

  );
}

export default App;

and here's the error is shown on my navigator  console :
Access to XMLHttpRequest at 'http://localhost:1337/socket.io/?EIO=4&transport=polling&t=NVYt_fH' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

polling-xhr.js:202 GET http://localhost:1337/socket.io/?EIO=4&transport=polling&t=NVYuaDS net::ERR_FAILED

I can't figure out my error, I have tried with too many solutions but no thing was helping/
Comment: I'm not familiar with your stack, but in my handling of CORS I've found it to be a right pain until you find the one thing that it was looking for.

Did you try with "Access-Control-Allow-Methods": "GET, POST, OPTIONS" as OPTIONS is the pre-flight call
Answer: Thank you @Beerswiller for your interest, I found what I miss is :
instead of using :
const io = require('socket.io')(Server, {
    origins: ["http://localhost:3000"],
    handlePreflightRequest: (req, res) => {
        res.writeHead(200, {
          "Access-Control-Allow-Origin": "http://localhost:3000",
          "Access-Control-Allow-Methods": "GET,POST",
          "Access-Control-Allow-Headers": "my-custom-header",
          "Access-Control-Allow-Credentials": true
        });
        res.end();
    }
});

i changed to :
const io = require('socket.io')(Server, {
    cors: {
        origin : "http://localhost:3000"
    }
});

and on the front section i do :
const socket = io('http://localhost:1337')

instead of :
const socket = io('http://localhost:1337',{
  withCredentials: true
})


Scala - foreach is not a member of Int

Question: I'm fairly new to Scala and have to write a program which calculates the average of given List of Integers.
However, I always get the error:

foreach is not a member of Int.

Does anybody of you know how to solve this? Here is my code:
 var measureResults = List(100, 36, 54, 4, 22, 37, 86, 20, 3000)

 var averageResult = getAverage(measureResults)

 println(averageResult)

 def getAverage(measureResults: List[Int]): Double = {
    var entryList = listOfValidElements(measureResults)
    var average = entryList(0)
    for (element <- average){
      average =+ 1
      var trueAverage = average/length(entryList)
      return trueAverage
   }
 }

Comment: Any reason why you're calculating average using Java-like code with mutable variables and `for` loops instead of just writing `list.sum / list.size`?
Comment: 1) Please indent you code. 2) Please include the error in your question. 3) `average` is probably an `Int` on wich `<-` makes no sense. 4) Calculating the average of `L` is done by `sum(L)/len(L)`.
Comment: In case you want to calculate avg. you must add all elements to each other and divide them by their count.
Comment: Please replace your code with a minimal example that exhibits the error. As it stands, this question has little lasting value and should probable be closed -- for someone who runs into the same error, the code sample is overly convoluted. For someone looking to compute an average in Scala, a simpler, more direct question would be better.
Answer: A more Scala-ish approach,
def average(list: List[Int]): Double = {
  list.sum.toDouble / list.size
}

Note there is no return statement, the last expression is returned; and no mutability is involved. Casting the sum to Double ensures a floating-point division and result. The method name omits get prefix for conciseness and eventually to convey with a non-getter class method.
From these notes, var measureResults = List(1,2,3) may become immutable, val measureResults = List(1,2,3).
Comment: A more scalish approach: `def average(list: List[Int]): Double = list.sum.toDouble / list.size` :-)
Comment: It's unfortunate that this is marked as the answer, since it doesn't even attempt to answer the question (and it answers another question that should be asked more directly/succinctly).
Answer: To actually answer the question as asked

However I always get the error: foreach is not a member of Int.
Does anybody of you know how to solve this?

in you code here:
var average = entryList(0)
for (element <- average){

you take the first entry in entryList, which is an Int. You then try to iterate over it, which doesn't make any sense, and causes the error you get
You probably meant something like
var average  = 0
for (element <- entryList) {

(and average += element not average += 1)
but as others have pointed out, there are much better ways of calculating this in Scala

Scala - foreach is not a member of Int


YII framework, is SSH required to run protected/yiic.php migrate

Question: We have a company doing several websites for us using the YII framework. The developers tell us that in order to run protected/yiic.php migrate that they must have SSH access to our server.
We are reluctant to provide SSH as there are many clients on our server. Is SSH really required as they say or can this migration script run via other means via the web browser?
Answer: You can write php-script, that will execute migrates, use CConsoleCommand for base, but it is not simple issue.
Answer: The fastest way run the migration only SSH, but approach proposed by Alex also nice.


Sticky Header and Table Combination breaks flow

Question: Does anybody know how to combine a Table (in my example one with fixed Header) with a Sticky Header without breaking the flow.
I tried to add the padding but it ignores the values.
The table goes over the the Header.

This is  my code :
https://codepen.io/danielde/pen/mKKgZg
and this is my css :
table {
 position: relative;
 width: 700px;
 background-color: #aaa;
 overflow: hidden;
 border-collapse: collapse;
 padding-top: 100px;
}

Answer: you just have to add z-index:1 to your .menu like this:

body {
   margin: 0;
}

.header {
    height: 100px;
    background-color: #ddcbaf;
    text-align: center;
}

.header h1 {
    margin-top: 0;
    padding-top: 20px;
}

.menu {
    margin: 0;
    padding: 0;
    width: 100%;
    background-color: #BFFFF3;
    top: 0;
    position: -webkit-sticky;
    position: sticky;
    z-index: 1;
}

.menu li {
    display: inline-block;
    text-align: center;
    width: 25%;
}

.menu li:hover,
.menu li:focus {
    background-color: #66FFE3;
}

.menu a {
    display: block;
    padding: 10px 0;
    text-decoration: none;
}

.sticky {
    top: 0;
    position: fixed;
}

.container {
  padding: 0 20px;
  color: #989898;
}

/*Table*/
table {
  position: relative;
  width: 700px;
  background-color: #aaa;
  overflow: hidden;
  border-collapse: collapse;
  padding-top: 100px;
}

/*thead*/
thead {
  position: relative;
  display: block; /*seperates the header from the body allowing it to be positioned*/
  width: 700px;
  overflow: visible;
}

thead th {
  background-color: #99a;
  min-width: 120px;
  height: 32px;
  border: 1px solid #222;
}

thead th:nth-child(1) {/*first cell in the header*/
  position: relative;
  display: block; /*seperates the first cell in the header from the header*/
  background-color: #88b;
}

/*tbody*/
tbody {
  position: relative;
  display: block; /*seperates the tbody from the header*/
  width: 700px;
  height: 239px;
  overflow: scroll;
}

tbody td {
  background-color: #bbc;
  min-width: 120px;
  border: 1px solid #222;
}

tbody tr td:nth-child(1) {  /*the first cell in each tr*/
  position: relative;
  display: block; /*seperates the first column from the tbody*/
  height: 40px;
  background-color: #99a;
}
<!DOCTYPE html>

    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" type="text/css" href="./resources/css/style.css">
    <title>ScrollIssue</title>
    <meta charset="utf-8">
    <title></title>

Testpage

Home

        Services

        Portfolio

        About

          ectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
          asljasödsljasdkljsd Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
          asljasödsljasdkljsd Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
          asljasödsljasdkljsd Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
          asljasödsljasdkljsd Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
          asljasödsljasdkljsd Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
          pisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

              Name
              Town
              County
              Age
              Profession
              Anual Income
              Matital Status
              Children

              John Smith
              Macelsfield
              Cheshire
              52
              Brewer
              £47,000
              Married
              2

              Jenny Jones
              Threlkeld
              Cumbria
              34
              Shepherdess
              £28,000
              Single
              0

              Peter Frampton
              Avebury
              Wiltshire
              57
              Musician
              £124,000
              Married
              4

              Simon King
              Malvern
              Worchestershire
              48
              Naturalist
              £65,000
              Married
              2

              Lucy Diamond
              St Albans
              Hertfordshire
              67
              Pharmasist
              Retired
              Married
              3

              Austin Stevenson
              Edinburgh
              Lothian
              36
              Vigilante
              £86,000
              Single
              Unknown

              Wilma Rubble
              Bedford
              Bedfordshire
              43
              Housewife
              N/A
              Married
              1

              Kat Dibble
              Manhattan
              New York
              55
              Policewoman
              $36,000
              Single
              1

              Henry Bolingbroke
              Bolingbroke
              Lincolnshire
              45
              Landowner
              Lots
              Married
              6

              Alan Brisingamen
              Alderley
              Cheshire
              352
              Arcanist
              A pile of gems
              Single
              0

            asljasödsljasdkljsd Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
            asljasödsljasdkljsd Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
            asljasödsljasdkljsd Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
            asljasödsljasdkljsd Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
            asljasödsljasdkljsd Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
            asljasödsljasdkljsd Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
            asljasödsljasdkljsd Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
            asljasödsljasdkljsd Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
            asljasödsljasdkljsd Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
            asljasödsljasdkljsd Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
            asljasödsljasdkljsd Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
            asljasödsljasdkljsd Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
            asljasödsljasdkljsd Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
            asljasödsljasdkljsd Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
            asljasödsljasdkljsd Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
            asljasödsljasdkljsd Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
            asljasödsljasdkljsd Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
            asljasödsljasdkljsd Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
            asljasödsljasdkljsd Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
            asljasödsljasdkljsd Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
            asljasödsljasdkljsd Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
            asljasödsljasdkljsd Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
            asljasödsljasdkljsd Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
            asljasödsljasdkljsd Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
            asljasödsljasdkljsd Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
            asljasödsljasdkljsd Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
            asljasödsljasdkljsd Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
            asljasödsljasdkljsd Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
            asljasödsljasdkljsd Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
            asljasödsljasdkljsd Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
            asljasödsljasdkljsd Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
            asljasödsljasdkljsd Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
            asljasödsljasdkljsd Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
            asljasödsljasdkljsd Lorem ipsum dolor sit amet, consectetur adi

Hope this will help you.


Como sobrepor e centralizar uma imagem a outra?

Question: Gostaria de saber como faço para sobrepor uma imagem sobre outra e centraliza-la, sendo que, estou usando divs diferentes para o filter:blur(25px); não se estenda para a logo também (drunkerslogo.png), porém estou com dificuldade para centralizar o drunkerslogo.png dentro do fundobackground.png (sobreposto)
segue o arquivo css
    body {
    background: black;
}

#site {
    width: auto;
    border: 1px solid red;
    background: black;

}

#background {
    width: 100%;
    height: 1080px;
    border: 1px solid red;
    background: url(imagens/fundobackground.png) no-repeat;
    background-size: cover;
    filter: blur(25px);

}

#logo {
    width: 540px;
    height: 540px;
    border: 1px solid red;

}

e o html

        Drunkers

"border" é para minha melhor visualização dos itens
Answer: Para alcançar a sobreposição como pretende, deve posicionar absolutamente o logo sobre a imagem, tendo como elemento relativo o seu parent. Adicionei o css em falta. Por favor verifique.

body {
  background: black;
}

#site {
  width: auto;
  border: 1px solid red;
  background: black;
}

#background {
  width: 100%;
  height: 1080px;
  border: 1px solid red;
  background: url(imagens/fundobackground.png) no-repeat;
  background-size: cover;
  filter: blur(25px);
}

#logo {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  margin: auto;
  width: 540px;
  height: 540px;
  border: 1px solid red;
}

#primeira-parte {
  position: relative;
}

Comment: Muito obrigado :D, estava um pouco confuso em relação ao uso do position:, mas agora deu para entender


Use of geometric series for Laurent series and domain of convergence for $\frac{1}{\sin (z)}$

Question: There has been a lot of explanation concerning the Laurent expansion of, for exemple,$\frac1{\sin(z)}$. The most common derivation I have encountered is: $$
\begin{align}
\frac1{\sin(z)}
&=\frac1z\frac{z}{\sin(z)}\\
&=\frac1z\left(1-\frac{z^2}{3!}+\frac{z^4}{5!}-\frac{z^6}{7!}+\cdots\right)^{-1}\\
&=\frac1z\left(1+\frac{z^2}{6}+\frac{7z^4}{360}+\frac{31z^6}{15120}+\cdots\right)\\
&=\frac1z+\frac{z}{6}+\frac{7z^3}{360}+\frac{31z^5}{15120}+\cdots
\end{align}
$$
However I find strange that it is not specified wether or not the term $-\frac{z^2}{3!}+\frac{z^4}{5!}-\frac{z^6}{7!}+\cdots$ is of modulus $\leq1$, in order to make proper use of the geometric series. I understand that in a neighbourhood of $0$, this term will satisfy the condition as it is holomorphic. However, I do not see how it can be used beyond a certain radius, yet I have often seen use of this derivation for similar problems, is there something I am missing?
Comment: The Laurent series for $\frac1{\sin(z)}$ centered at $z=0$ only converges for $|z|\lt\pi$. That is, the radius of convergence goes out only as far as the first singularity in $\frac{z}{\sin(z)}$.
Comment: Would this guarantee that the modulus of the term that I mentioned is less than 1?
Comment: The term you mention is $\frac{z-\sin(z)}{z}\lt1$ for $|z|\lt\pi$.
Comment: @robjohn $\bigl\lvert \frac{\sin (\pi i)}{\pi i} - 1 \bigr\rvert > 2$.
Comment: @DanielFischer: ah, yes. I was blindly looking at $\mathbb{R}$. How silly.
Comment: @MatthieuLeCauchois: As Daniel Fischer points out, the series you cite is not less than $1$ for all $|z|\lt\pi$. However, you can compute the series for small enough $|z|$ and use analytic continuation to show that it converges to $\frac{z}{\sin(z)}$ for $|z|\lt\pi$.
Answer: You are right, for the geometric series we need that $\bigl\lvert \frac{\sin z}{z} - 1\bigr\rvert < 1$. And for the reordering and regrouping of $\sum_k (z^2/6 - z^4/120 + \dotsc)^k$, it is convenient to require
$$\sum_{n = 1}^{\infty} \frac{\lvert z\rvert^{2n}}{(2n+1)!} < 1$$
so that everything is clearly absolutely convergent and the manipulations legitimate.
As you say, in a small enough neighbourhood of $0$ that is the case, say for $\lvert z\rvert < r_0$.
Thus we have an expansion of $\frac{1}{\sin z}$ into a Laurent series that we know is valid in the annulus $0 < \lvert z\rvert < r_0$. Now we use the uniqueness of Laurent series. From the general theory, we know that $\frac{1}{\sin z}$ has a Laurent expansion
$$\frac{1}{\sin z} = \sum_{n = -\infty}^{+\infty} a_n z^n$$
that is valid in the annulus $0 < \lvert z\rvert < \pi$. In the annulus $0 < \lvert z\rvert < r_0$ (since $r_0 < \sqrt{6} < \pi$), we have two Laurent series representing the same function, hence by the uniqueness, these series are the same (have the same coefficients). Therefore, although the calculations were a priori only justified for $\lvert z\rvert < r_0$, it follows a posteriori that the series we obtained represents the function in the whole annulus $0 < \lvert z\rvert < \pi$.


Finite geometric series of matrices

Question: Suppose $A$ is a $m \times m$ matrix. Under what condition(s) does the following finite geometric series hold? Note that $I$ is a $m \times m$ identity matrix.
$$\sum_{i=0}^n A(I - A)^i = I - (I - A)^{n+1}$$
I'm referring to https://mast.queensu.ca/~math211/m211oh/m211oh96.pdf, and it seems that the above would hold if $(I - A)$ is invertible, i.e. $|\lambda_i| < 1$ for each eigenvalue of $A$? Does that imply that $A$ also has to be invertible?
Comment: I'm guessing the left side should read $\sum_{i = 0}^n (I - A)^i$?
Comment: "if $(I - A)$ is invertible, **i.e.** $|\lambda_i| < 1$ for each eigenvalue of $A$" really? For $A=\operatorname{diag}(3,5)$ with eigenvalues $\lambda_1=3,\,\lambda_2=5$ $\quad I-A=\operatorname{diag}(-2,-4)$ is invertible and $(I-A)^{-1}=\operatorname{diag}(-\frac12,-\frac14)$... Btw, recall how the usual geometric progression sum is derived, like $qS_n=S_n+bq^n-b$, the same argument applies here if $Q=(I-A)$...
Comment: @AlexeyBurdin I see, thanks. For the equality to hold, do we only need $A$ to be invertible?
Answer: Let $S_n=\sum\limits_{k=0}^n Q^k$ where $Q=(I-A)$. Then
$$QS_n=\sum\limits_{k=1}^{n+1} Q^k=-I+S_n+Q^{n+1}$$
Bring $S_n$ to the left part:
$$(Q-I)S_n=-I+Q^{n+1}$$
now recalling $Q=I-A$ and multiplying by $(-1)$ we get the desired result.
P.S. No assumptions taken.
Comment: Thank you. On a related note, if we take $S_n = \sum_{k=0}^n BQ^k,$ where $Q = (I-A)$, then we would have $S_n = \sum_{k=0}^n BQ^k = BA^{-1}(I-(I-A)^{n+1})$? In this case, we would need to assume that $A$ is invertible, correct?
Comment: I hope so, if we write $A^{-1}$. For non-invertable $A$ it doesn't make sense otherwise) Alternatively we may leave $A$ in the LHS, as done in the question. However, I'm not sure whether it's OK that $A^{-1}$ is between $B$ and $(I-(I-A)^{n+1})$. How did it get there?)
Comment: Hmm, I thought since $S_n = \sum_{k=0}^n BQ^k = B\sum_{k=0}^n Q^k = BA^{-1}(I-(I-A)^{n+1})$, then the $A^{-1}$ is between $B$ and $(I - (I-A)^{n+1})$? Is it incorrect that I pulled out $B$ in front of the sum in the second equality?
Comment: $\sum\limits_{k=0}^n BQ^k=B\sum\limits_{k=0}^n Q^k$ is perfectly correct, it's distributivity. Another thing that now we maybe should write $S_nQ=-B+S_n+BQ^{n+1}$ and thus $S_n(-A)=B(-I+Q^{n+1})$. Anyway, $A^{-1}$ (if exists) and $(I-(I-A^{n+1}))$ appears to commute, so that's fine having $A^{-1}$ in between (after some thinking). Thanks for reading)

Finite geometric series of matrices


Prove that $\neg 0 = 1$ in every boolean algebra.

Question: I am trying to prove that $\neg 0 = 1$ in every boolean algebra by using the laws of boolean algebra.
The assistant told us to start by using the identity law and form $\neg 0 = 1$ to $\neg 0 = \neg 0 \cdot 1$. However I don't know how to proceed from there.
Comment: Not sure how the assistant expects you to use the identity law for mutiplication but the indentity law for addition give you $\lnot 0 = \lnot 0 + 0$.  And what does $\lnot x + x$ equal?
Comment: For $\neg 0 = \neg 0 + 0 = 1$ to be true, then it must be $\neg x + x = 1$. Is that right?
Answer: Identity Law: $\lnot 0 = \lnot0\circ 1$
Double Negation: $\lnot 0 \circ 1 = \lnot 0 \circ \lnot \lnot 1$
De Morgan:  $\lnot 0 \circ\lnot \lnot 1 = \lnot(0 + \lnot 1)$
Indentity:  $\lnot (0 + \lnot 1) = \lnot \lnot 1$
Double Negation: $\lnot\lnot 1 = 1$.
....
Oh this is better:  $\lnot 0 + 0 = 1$ by the complement law.
But $\lnot 0 + 0 = \lnot 0$ by the identity law.
Answer: Well, think about the defining property of $\neg$ in a Boolean algebra: $$(\neg x)\vee x=1.$$ Taking $x=0$, this gives $(\neg 0)\vee 0=1$.
Now, you know a rule for simplifying expressions of the form $a\vee 0$. Can you see how to use it here to get what you want?
Comment: I know that $a \vee 0 = a$, so in this case it means that $\neg 0 \vee 0 = \neg 0$
Comment: @exhausend Exactly. So you know $(\neg 0)\vee 0=\neg 0$ as you've just pointed out. But we also already know $(\neg 0)\vee 0=1$ (we got that earlier, from the behavior of "$\neg$"). Putting these together ...
Comment: Ahh yes of course, we get to $\neg 0 = 1$. Thank you.


a problem with coprime numbers

Question: I thought that numbers were coprime if the only positive integer that evenly divides all of them is 1.
However Wolfram Alpha say that 6, 10 and 15 are not coprime. But the only number that divides all of these is 1?
Are a list of numbers coprime if ALL pairs of numbers are coprime?
Comment: http://en.wikipedia.org/wiki/Pairwise_relatively_prime
Comment: @user26069, [CoprimeQ](http://reference.wolfram.com/mathematica/ref/CoprimeQ.html) checks for *pairwise* coprimality.
Comment: http://www.wolframalpha.com/input/?i=are+6%2C+10+and+15+coprime%3F
Answer: I can't speak for wolfram, but the standard convention is the one you give: a coprime list of numbers is one in which there is no non-unit that divides all of them. That makes 6, 10, 15 a coprime list.
The stronger concept, where one insists that each pair be coprime, is referred to as "pairwise coprime." The numbers 6, 10, 15 are not pairwise coprime.
Comment: Oh so wolfram should have said; 'not pairwise coprime'. How confusing..

a problem with coprime numbers


Visual Studio 2017 nenhum template

Question: Instalado o VS2017 porém não aparece os templates apenas 'Blank Solution'.
Tentei desinstalar e reinstalar sem sucesso.
Alguém já passou por essa situação?
Imagem:
Comment: Escolheste algum tipo de projecto no instalador?
Comment: Sim Escolhi '.NET desktop development', entre outros. porém não apareceu nenhum template.
Comment: Após diversos testes, consegui fazer aparecer Instalei o VS2015 e copiei a pasta _'ProjectTemplates'_ e colei no VS2017, porém não me parece correto, como se estivesse faltando alguma coisa.
Answer: Você precisa instalar pelo instalador do Visual Studio.

Clique na aba "Workload" no canto superior esquerdo, então marque no canto direito ".NET-Desktop Development" e clique em instalar. Note que isso pode modificar o tamanho de sua instalação (Canto inferior direito), e você pode instalar outros Workloads, mas você deve instalar pelo menos o ".NET-Desktop Development".

Se feito isso você ainda não conseguir ver os templates, então o Visual Studio provavelmente está pegando os templates dos seus "Custom Templates" e não instalados. Para resolver isso, copie a pasta dos templates instalados
para os custom.
Pasta de instalados: "C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\ProjectTemplates"
Pasta dos custom: "C:\Users\Documents\Visual Studio 2017\Templates\ProjectTemplates"
Fonte: Stack
Comment: Obrigado pela resposta. Porém infelizmente já fiz isso esta marcado o ".NET-Desktop Development"., já desinstalei e reinstalei instalando apenas ele e continua igual.
Comment: Copiando o ProjectTemplates funciona. Porém não sei se seria o correto, visto que instalei outras opções no 'worload' e não está aparecendo..
Comment: Alguma ideia?.. pois a pasta que mencionou em cima é da do vs2015, embora funcione, o vs2017 deveria instalar corretamente.
Comment: Apesar da versão, a pasta é a do VS17 mesmo. Mas infelizmente é difícil apontar a causa exata do porque o VS não instala corretamente, seria necessários vários testes em vários ambientes pra tentar chegar numa resposta, e ainda sim, ela pode não ser unica. A questão é que se alguns dos procedimentos citados solucionou o problema, já é alguma resposta válida e que pode ser útil pra alguém.
Comment: Perfeito. Apenas para finalizar.. quando adiciona uma nova classe Shift + Alt + C,  tbm não aparece a classe. Saberia  como acertar?
Answer: Obrigado pelas respostas. Ajudaram bastante como paliativo porém não solucionaram definitivamente.
Após eu abrir um bug na microsoft eles não conseguiram resolver, porém depois atualizei para a ultima versão liberada recentemente ele voltou a funcionar.

Visual Studio 2017 nenhum template


How to change the style class of a certain div

Question: I'm a novice trying to learn basics for fun.
I've set up a 7.24 drupal website. I've installed the bootstrap theme. I managed to create a subtheme and activated it. I use the bootstrap-cdn method.
Now, I'm not happy with the style of certain elements. Bootstrap already has great css definitions but they are not used in the basic starter kit of the theme.
So here's my problem:
I want the tag fields of my articles to be styled with the style class label label-info of bootstrap - displayed here:

I've read an article about the usage of template.php but I'm stuck for hours to find the right method name. Something like <mythemename>_field_X_X_X(). How do I find out which method name I have to use?
If there is an easier way to change/add the style of a certain div class I'm open for suggestions.
Thank you for reading this! Your help is appreciated.
Comment: So basically, you want to add a css class on a tag (term) that you can define in the CMS ?
Comment: Yes. That's what I want!
Answer: The module Semantic fields did the job.