How to assign custom colors to a map in Flutter without type mismatch errors?

Question: I'm developing a Flutter application in Android Studio and facing a challenge with customizing color assignments. My goal is to assign specific colors to different statuses in my app. For some statuses, using predefined Colors works fine, such as Colors.grey for PomodoroStatus.runningPomodoro. However, when I attempt to assign custom colors, I encounter type mismatch errors stating "The element type 'Color' can't be assigned to the map value type 'MaterialColor'".
Here's a bit of context: I'm implementing a feature that changes the UI color based on the current status of a Pomodoro timer. The timer has several statuses, like running, paused, and types of breaks. I've created a map to associate each status with a corresponding color.
Code:
import 'package:flutter/material.dart';
import '../model/pomodoro_status.dart';
import 'package:flutter/cupertino.dart';

const pomodoroTotalTime = 240 * 60;
const shortBreakTime = 20 * 60;
const lonBreakTime = 60 * 60;
const pomodoroPerSet = 4;

const Map<PomodoroStatus, String> statusDescription = {
  PomodoroStatus.runningPomodoro: 'Pomodoro is running, try to be focused',
  // Other status descriptions...
};

const Map<PomodoroStatus, MaterialColor> statusColor = {
  PomodoroStatus.runningPomodoro: Colors.grey, // Works fine
  // Custom color assignments below lead to errors
  PomodoroStatus.pausedPomodoro: const Color(0xFFC2C2C2),
  // Other status colors...
};

I've already tried consulting the Flutter documentation and searching for similar issues here, but couldn't find a scenario that matches mine exactly. Most solutions I found were related to using Colors directly, not custom Color values.
Questions:

How can I correctly assign custom Color values to my map without encountering type mismatch errors?
Is there a specific way to cast or convert Color objects to MaterialColor to fit the map's expected value type?

Any guidance or references to relevant documentation would be greatly appreciated.
Answer: Your statusColor map has MaterialColor as a value, so it will only accept colors within the Colors class.
Comment: Just change the `MaterialColor` value of your map to just `Color`
Comment: How can I change to customize colors, what should I write to do so?


Generating Function of a Recurrence Relation.

Question: Given a sequence a(n) = a(n -2) , a(0) = 2 , a(1) = -1
Find the generating function
What i have done so far:

The recurrence relation is going to be a(n) - a(n-2) = 0

A = the generating function

A = 2 - x + 2x^2 - x^3 + 2x^4.......

x^2 * A = 2x^2 - x^3 + 2x^4 ..........

- subtracting the two equations.

1-x^2 A = 2 -x
 divide both sides by 1-x^2

A = 2-x / 1-x^2
This is how i was taught to do it , but when u plug in numbers for x , it doesnt seem to satisfy the premise.
Comment: Why are you plugging in numbers for $x$? What are you expecting to get back?
Comment: when you plug numbers for x , shouldnt it equal the a number in the sequence
Comment: No, except that $A(0)=a_0$.
Comment: Think about it: why on earth should $\sum_{n\ge 0}a_nk^n$ be equal to $a_k$?
Comment: so if i plug in say x=2 , its not suppose to equal a(2)?
Comment: Absolutely not. The generating function is not a closed form for the sequence; it's a function whose power series has the terms of the sequence as coefficients.
Comment: Thank you , so did i solve for the correct generating function?
Comment: Yes, you did. I'll write up a quick answer showing how you can reverse the process to check.
Comment: The series is a sum of two simple geometric progressions, or of a single one if you gather terms as in $(2-x)+(2-x)x^2_\cdots$.
Answer: Your generating function is correct. What you have to realize is that a generating function is not a closed form for the sequence: it's a function whose power series has the terms of the sequence as coefficients.
Here you can actually work backwards to check that you have the right generating function. Split it into partial fractions:
$$A(x)=\frac{2-x}{1-x^2}=\frac{1/2}{1-x}+\frac{3/2}{1+x}\;.$$
You know that $$\frac1{1-x}=\sum_{n\ge 0}x^n\;,$$
so (substituting $-x$ for $x$) $$\frac1{1+x}=\sum_{n\ge 0}(-x)^n=\sum_{n\ge 0}(-1)^nx^n\;,$$
and therefore
$$\begin{align*}
A(x)&=\frac12\sum_{n\ge 0}x^n+\frac32\sum_{n\ge 0}(-1)^nx^n\\\\
&=\sum_{n\ge 0}\left(\frac{1+3(-1)^n}2\right)x^n\;.
\end{align*}$$
You can easily check that
$$\frac{1+3(-1)^n}2=\begin{cases}
2,&\text{if }n\text{ is even}\\
-1,&\text{if }n\text{ is odd}\;.
\end{cases}$$


Como fazer uma consulta que devolva o ultimo registro de cada dia?

Question: A duvida é simples, mas infelizmente acho que a resolução não. Tenho uma tabela com vários registros, e preciso realizar uma consulta que me devolva o ultimo registro de cada dia dos últimos 20 dias por exemplo.
Exemplo:
|------------ teste ---------------|
|id  | valor1 | data               |
|   1|     12 | 2016-01-01 00:41:00|
|   2|     31 | 2016-01-01 23:00:12|
|   3|     34 | 2016-01-02 00:41:00|
|   4|     63 | 2016-01-03 05:20:21|
|   5|     87 | 2016-01-03 13:51:00|
|   6|     95 | 2016-01-03 14:00:00|

A pesquisa deveria retornar o registro [2, 3, 6].
Answer: Tenta esta solução:
SELECT * FROM tabela INNER JOIN (SELECT MAX(data) AS ultimo_registo FROM tabela GROUP BY DATE(data)) as Lookup ON Lookup.ultimo_registo = tabela.data

Como podes ver, rodei aqui o teste e funcionou:

Retornando apenas os últimos 20 registos:
SELECT * FROM minha_tabela INNER JOIN (SELECT MAX(data1) AS ultimo_registo
FROM minha_tabela GROUP BY DATE(data1)) as Lookup
ON Lookup.ultimo_registo = minha_tabela.data1 ORDER BY data1 DESC LIMIT 20;

Comment: muito obrigado :)
Answer: Creio que você precisa formatar para data e, então, agrupar.
 SELECT * FROM tabela GROUP BY DATE(data) ORDER BY data DESC

Answer: Tente usar:
 SELECT max(valor1) FROM tabela GROUP BY DATE(data)

Comment: quase daria certo, mas sei que terá algumas ocasiões em que o ultimo registro do dia não terá o maior valor.
Comment: a resposta do @psantos te atende.
Answer: Acredito que você presisará procurar por dias distintos e ordenar pela data ficaria assim:
SELECT DISTINCT DAY(data) as dia, t.* FROM tabela t ORDER BY data DESC


Dividir arquivo do EXCEL

Question: Tenho uma base em um excel com 1 milhao de emails nela, e preciso dividir em 4 arquivos de  250 mil emails cada, alguém sabe como posso fazer isso com alguma função do excel ? obrigada
Comment: você provavelmente já resolveu o problema, uma vez que não respondeu os comentários, talvez possamos marcar sua pergunta como resolvido?
Answer: Se você ja sabe a quantidade total de células, basta fazer manualmente, vá direto até uma determinada linha (250.000) bastando escrever do lado superior esquerdo o numero da linha em questão e apertar enter.

Ou utilize filtros avançados.
Neste link tem um exemplo utilizando filtro avançado
Comment: @Math basta selecionar da linha 01até a linha 250.000 recortar os dados e colar em outra planilha, fara isso 04 vezes e gastara bem menos recursos do micro do que deixar esta tarefa para o Excel gerenciar gastando memória e processamento e travando, correndo o risco de corromper a planilha!
Comment: @Math a Luana não deixou claro se essa planilha ira crescer dinamicamente ou ela ja esta em seu limite máximo, se ja esta no limite máximo é simples, o Excel permite que você vá direto até uma determinada linha bastando escrever do lado superior esquerdo o numero da linha em questão e selecionar os dados e pronto. Mas se a planilha for crescer dinamicamente, ai é mais vantajoso utilizar o filtro avançado como proposto ou até mesmo um banco de dados simples como Access ou MySql.
Comment: @Math alterei a resposta, acho que agora esta mais didático, esta funcionalidade do excel é muito util.
Comment: @Math você pediu, ai esta.
Comment: Fazer manualmente, a quebra de 1 milhão de linhas não deve ser muito fácil, não é não?
Comment: Ok, mas como "Ir para" a linha 250.000? Essa é a minha dúvida. Scroll do mouse? Page downs infinitos? Por isso que digo não ser muito fácil.
Comment: "vá direto até uma determinada linha bastando escrever do lado superior esquerdo o numero da linha em questão" esse é o ponto que eu queria chegar!! Eu usei Excel a minha vida inteira e nunca tinha visto (prestado atenção) à essa caixa! E olha que eu procurei, antes de ver sua resposta. Se você puser isso como resposta eu voto a favor dela.
Comment: Se pusesse um print ficaria show, mas do jeito que está já me ensinou algo que eu não sabia. +1, já tá excelente
Comment: Para mim essa é a resposta correta. Parabéns, e bem vindo ao SOPT :)
Answer: Creio que uma solução em VBA seria bem mais prática do que uma manual e cansativa, então fiz isso aqui, caso não tenha experiencia com macro, eu deixei o código bastante explicado:
A ideia é pegar a coluna A e dividir ela de acordo com a variável divisor. As planilhas são salvas na pasta default Meus Documentos. A unica preocupação é que por rapidez usei o método de aproximação mais simples que arrendonda sempre pra mais: AsymArith, caso queira outro método, é só procurar nesse artigo do link.
Sub Dividir_em_arquivos()
Dim ultimalinha As Integer, divisor As Integer
Dim resultado As Double
Dim nomeaba As String, nomearquivo As String, nomeaba_loop As String, nomearquivo_loop As String

'pega o nome da sheet e do arquivo que voce esta executando a macro
nomearquivo = ActiveWorkbook.Name
nomeaba = ActiveSheet.Name

'seleciona a ultima linha da COLUNA "A"
ultimalinha = Range("A" & Rows.Count).End(xlUp).Row

'------------- > coloque aqui divisor
divisor = 4

'calculo (SOMENTE NUMEROS PARES, usando o SymArith: https://support.microsoft.com/en-us/kb/196652/pt-br)
resultado = ultimalinha / divisor
resultado_apro = Int(resultado * 1 + 0.5) / 1

'loop para criar as planilhas e selecionar as colunas para copia
For i = 0 To divisor - 1
    resultado_inicio = (resultado_apro * i) + 1
    resultado_fim = resultado_apro * (i + 1)

    'set nome na planilha do loop
    nomeaba_loop = "numero" & i

    'cria planilha
    Set NewBook = Workbooks.Add
    With NewBook
        .Title = nomeaba_loop
        .SaveAs Filename:=nomeaba_loop
    End With

    'adiciona aba para colar as informações
    nomearquivo_loop = ActiveWorkbook.Name
    Sheets.Add.Name = nomeaba_loop

    'seleciona a planilha fonte
    Windows(nomearquivo).Activate
    Sheets(nomeaba).Select

    'Copia as informações da planilha fonte
    Range("A" & resultado_inicio & ":A" & resultado_fim).Copy

    'seleciona a planilha do loop
    Windows(nomearquivo_loop).Activate
    Sheets(nomeaba_loop).Select

    'cola as informações
    Range("A1:A" & resultado_apro).PasteSpecial xlPasteAll
    Application.CutCopyMode = False
    ActiveWorkbook.Save

    'seleciona novamente a planilha fonte para começar o loop
    Windows(nomearquivo).Activate
    Sheets(nomeaba).Select

Next i

End Sub

Dividir arquivo do EXCEL


Tracing and debugging in OCaml

Question: What do you use for tracing and debugging in OCaml?
For debugging I tried ocamldebug and the Emacs plugin.
For tracing I want to be able to print the data constructor of every variable.
An example using Camlp4 is shown here: http://caml.inria.fr/pub/docs/tutorial-camlp4/tutorial007.html#toc52
   type colour = Red | Green | Blue
   let print_colour =
     function
       Red -> print_string "Red"
     | Green -> print_string "Green"
     | Blue -> print_string "Blue"

Comment: There's no built-in way to print values of a user defined type, but there are some external projects that solve the problem in various ways.  See this previous SO question page: http://stackoverflow.com/questions/7518752/is-there-a-way-to-print-user-defined-datatypes-in-ocaml
Comment: For tracing, the toplevel is the easiest way, if you can do your experiments in it (works well for data structure debugging, not so well for I/O).
Answer: ocamldebug works fine when you can use bytecode.
If you want to debug a native code application, there is a patch by Thomas gazagnaire on Mantis that allows to step line by line in the OCaml program using gdb. Parts of this patch should be integrated in the next version of OCaml (3.13 or 4.00).
Currently, however, there is no way to print OCaml values, but another patch is coming, using GADT's to define a generic printer function for any type.
Comment: Hi, what is the state of gdb/lldb support, as of 2015?
Comment: What's a bytecode file? I tried everything and `ocamldebug` says "not a bytecode file".

Tracing and debugging in OCaml


Algebra Ages Question GCSE

Question: I need help to work out this algebra question.
Question:
Ram's Daughter's Age in 3 years will be the square of her age 3 years ago.
How old is she now?
What I did:
algebraically:
x+3 is daughters age in 3 years
x-3 age years ago
x+3 = (x-3)(x-3)
<code>   x-3 = 0
   x=3
</code>
x = 3 so her age now is 3 years old?
On the mark scheme it said the answer was 6 but it didn't show the working so please can someone try this question and tell me what I did wrong.
Thank You and Help is Appreciated
Comment: Check your work.  Does $x=3$ satisfy the equation you posed? (No, since $3\neq 0^2$.)
Answer: Your setup of
$$x + 3 = (x - 3)(x - 3)$$
is correct, but I have no idea how you concluded that $x - 3 = 0$ from this. I guess that you tried setting the factors on the right equal to zero, but there is no reason to here... their product is $x + 3$, not zero. Rather, expand and collect terms:
$$x^2 - 6x + 9 = x + 3 \iff x^2 - 7x + 6 = 0 \iff (x - 6)(x - 1) = 0.$$
So now it is valid to set each of the factors to zero, and so either $x = 6$ or $x = 1$. The latter solution doesn't make sense, so $x = 6$.
Comment: oh thank you for helping me=-)

Algebra Ages Question GCSE


A question to show that the integral operator is a bounded operator

Question: This question was asked in my assignment of Functional analysis and I was not able to solve this particular problem.

Question:(a) Show that the formula $Af(x) = \frac{1} {x} \int_{0}^x f(y) dy$ defines a bounded operator $A: L^2 (( 0,\infty)) \to L^2 ((0,\infty))$ with $||A||\leq 2$.

(b)Show that in fact $||A||=2.$
(c) Determine the adjoint operator of A.
(d) Show that $A^*A= A+A^* =AA^* .$  Deduce that the operator $U= I-A $ is unitary.
Attempt: (a) $ ||A|| \leq || \frac{1} {X} \int^x_0 f(y) dy ||\leq \frac{1} {X} \int_{0}^{x}||f(y)|| dy$ but I am not able to show that $||A||\leq 2$ because I don't understand how to find the minimum value of  integral of $f(y)$.
(b)  Due to this I am also not able to show how ||A||=2.
(c) Using the definition , I got that $A^* =  {x} ({\int^{x}_{0} f(y) dy})^{-1}$ but using this definition I am not able to show that $AA^* = A+ A^*$.
Can you please tell is my $A^*$ wrong and how to rightly calculate it?
Comment: First rework your answer to (a) but before that, write down the definitions of the norm of an operator and of the $L^2$-norm of an $f.$
Comment: @3ibfwcbi: you already got an answer. But note that the expression you wrote for $A^*$ is not even linear.
Answer: The bound of the Hardy operator $Hf(x)=\frac1x\int^x_0f(t)\,dt$ has been discussed in several posting in MSE, for example posting 1 and posting 2
As for the adjoint: for $f,g\in L_2(0,\infty)$, an application of Fubini's theorem yields
\begin{align}
\int^\infty_0\Big(\frac1x\int^x_0f(y)\,dy\Big)\overline{g}(x)\,dx&=\int^\infty_0\Big(\frac1x\int^\infty_0\mathbb{1}_{(0,x]}(y)f(y)\,dy\Big)\overline{g}(x)\,dx\\
&=\int^\infty_0f(y)\int^\infty_0\mathbb{1}_{[y,\infty)}(x)\frac{\overline{g}(x)}{x}\,dx\Big)\,dy\\
&=\int^\infty_0f(y)\Big(\int^\infty_y\frac{\overline{g}(x)}{x}\,dx\Big)\,dy
\end{align}
Hence,
$$A^*g(x)=\int^\infty_x\frac{g(y)}{y}\,dy$$

For part (c), another application of Funibi's theorem yields
\begin{align}
AA^*f(x)&=\frac1x\int^x_0A^*f(y)\,dy=\frac1x\int^x_0\Big(\int^\infty_y\frac{f(t)}{t}\,dt\Big)\,dy\\
&=\frac1x\left(\int^x_0\frac{f(t)}{t}\Big(\int^t_0\, dy\Big)\, dt +\int^\infty_x\frac{f(t)}{t}\Big(\int^x_0\, dy\Big)\,dt\right)\\
&=Af(x) + A^*f(x)
\end{align}
Hr=er th region of integration $R:=\{(y, t):0<y\leq x, y\leq t\}$ is expressed as $R:=\{(y, t): 0<t\leq y, 0<y\leq t\}\cup\{(y, t): x<t,0<y\leq x\}$.
Similarly
\begin{align}
A^*Af(x)&=\int^\infty_x\frac{Af(y)}{y}\,dy=\int^\infty_x\frac1{y^2}\Big(\int^y_0 f(t)\,dt\Big)\,dy\\
&=\int^x_0f(t)\Big(\int^\infty_x \frac{dy}{y^2}\big)\,dt+\int^\infty_xf(t)\Big(\int^\infty_t\frac{dt}{y^2}\Big)\,dt\\
&=Af(x)+A^*f(x)
\end{align}
Here, the region of integration $Q:=\{(y, t): x<y, 0<t\leq y\}$ is split into $\{(y, t): x<y, 0<t\leq x\}\cup\{(y, t): x<t, t<y\}$.

Part (d) of the OP follows from (c).
Comment: Diaz  Solutions of (c) and (d)  I completely understood. Can you please give solution of (a) and (b) also? I am not able to understand them using the links mentioned . I am very new in this topic.
Comment: @3ibfwcbi: The first one is not complicated if one uses the generalized Minkowski inequality. On of the postings does that. The other part is more delicate. The second posting I refer to has several good solutions which are very interesting on their own. I suggest you take a look at them.
Comment: I looked at them but I couldn't understand. Kindly help if you have some time to spare.
Comment: Are you familiar with the generalized Minkowski inequality? If not, here is a different proof of the Hardy inequality (boundedness of $A$) that is based on (a) showing the statement for continuous functions of compact support then, and then by density arguments to extend result for all $f\in L_p$ (in your case $p=2$. That $p/(p-1)=2$ is the best constant, is more involved and I don't have the energy to rewrite my previous solution. The idea is to get a sequence of functions $f_n$  with $\|f_n\|_2=1$ and such that $\|Af_n\|_2\xrightarrow{n\rightarrow\infty}\frac{p}{p-1}=2$ (for your case $p=2$)
Comment: See [this solution](https://math.stackexchange.com/q/4163455/121671) that does not use Minkowski's inequality
Comment: @OlivierDiaz How should I prove the equality of part (b)? I have done (a), thanks to your references!
Comment: @3ibfwcbi: part b is requires a little finesse. In my previous message I told you what the idea was, [posting 2](https://math.stackexchange.com/q/126889/121671) in my answer has a couple of solutions.


ErrorSummary for multiform model

Question: I am using a multi form model. A $model array is passed to the view and for each model object I am trying to have an errorsummary. See the code below.
<code>foreach ($model as $f=>$edu):
echo $form->errorSummary($edu,'');
echo $form->textField($edu,"[$f]schoolname",array('size'=>30,'maxlength'=>128));
endforeach;
</code>
When I submit the form an error summary for only one form is displayed. Any ideas.
Comment: I think that, since you are only posting a single form at a time, there is only one validation done? No validation means no errors. As I don't see more of the code this is just a guess.
Comment: what about your controller code?
Answer: Maybe you need to rethink your form structure, for example - put all into one form, then inside controller make validation of every model you use and then show error messages.

ErrorSummary for multiform model


How to transform a nonlinear constraint to linear constraint using big M?

Question: Given a nonlinear constraint
$$xy=0$$
where $x$ is a continuous variable and $y$ is a binary variable.
Question: Using the Big-M method, how do I get to change the constraint above to a linear constraint below:
$$x \leq M(1-y)?$$
Probably by showing a theorem.
What I know: I know that $M$ is probably a variable to bound the continuous variable $x$ so that it applies $0 \leq x \leq M$.
Thank you for the help.
Comment: Big-M method = ? Big-Monster ?
Answer: Because $y$ is a binary variable, you just need to check the two cases.

If $y=0$, then $xy=0$, as desired, and the linear constraint reduces to $x \le M$, which is redundant.
If $y=1$, you want to enforce $x=0$ so that $xy=0$.  Because $x \ge 0$, it is enough to enforce $y = 1 \implies x \le 0$.  The big-M constraint $x \le M(1-y)$ does exactly that.

More generally, to enforce $y=1 \implies f(x) \le b$, impose $f(x) - b \le M(1-y)$, where $M$ is an upper bound on $f(x) - b$ when $y=0$.


Which tests can I use to analyze dependent likert-type data?

Question: In a survey, where students were presented various stimuli, after each stimulus they were asked to rate the following:

Quality, on a five-point scale from "Excellent" to "Bad", let's say $Q$
Confidence in their quality ratings, on a four-point scale from "Very Confident" to "Not confident", i.e. $C$

Here are my assumptions:

Obviously these samples are dependent, since they belong to exactly one stimulus and student pair (am I right assuming so?)
Also, the questions are very similar to the Likert scale, therefore I'm unsure of whether to classify them as ordinal or interval-based (and others seem too). I'd say they're ordinal, but many researchers in my field seem to ignore that and treat them as interval-based.

Basically, what I'd like to find out is whether these ratings are dependent on each other. So, my questions are:

Would that data be considered interval-based or ordinal?
Which tests can I apply here? $\chi^2$? Wilcoxon signed rank test?

I've already come up with three dimensional plots that show the counts for each pair, e.g. to say "In ten cases, users chose Bad and were Not Confident about it". Or, $count(Q_1,C_4) = 10$ … But there's nothing I can statistically prove from that alone.
Comment: I believe you will be receiving   answers  suggesting accurate tetrachoric and related alternatives for ordinal DV. Just want to comment that often researchers avoid the nominal scale as their association measures may be missunderstood and/or because they may yield different alternative measures. Going into interval scales allows standard association estimations at the price of the akward implications of an interval scale (consecutive categories are equally spaced).
Answer: I think there are several challenges to consider.
In terms of how to visualize, the most accurate would be to use a mosaic plot, or a stacked barplot (which are practically the same in this case, but it might be easier to find a stacked barplot in excel or SPSS than the mosaic plot).
It might also be helpful to change the likert scale to a numerical (1-5) scale, and have a boxplot of each of the 4 categories of your second question.  Since boxplots are based on percentiles, the meaning of the boxplot can be somewhat consistent (depending on how the quantiles are calculated when dealing with mid points) with the type of data you present.
In terms of how to analyse, there are different questions you can ask.  The simplest will be "is there a correlation between the two?", that can easily be answered using the pearson correlation on the ranking of the numerical values of your scales.  This correlation will actually give you the Spearman correlation measure (the correlation of the ranks).  The ranking is important for cases where you will have ties (for example, the vector:  1,2,2,4  should actually become:  1,2.5,2.5,3).
The wilcoxon test is relevant if you want to answer the question if the ranks of one measure is different than the other measure.  But from your question, it doesn't sound like an interesting question.  You can also use the Chi-square test for a similar question, but it's power will probably be smaller.
Answer: In my opinion, this question has been done to death but surfaces again and again due to slightly different nomenclature. First off, it depends on what your scientific question is: are you interested in trend (averaged differential response comparing groups) or heterogeneity (piecewise comparisons of responses among all categories)? What are the outcomes of the study? What are your stimuli? Are the stimuli categorical or ordered somehow or continuous in nature? These are details that statisticians need to know.
Ordinal regression is the family of methods around coding ordinal responses by their numeric categories. The physical quantities you estimate are uselessly intepreted as "expected differences in ordinal response levels" (this is verbatim how you would report regression coefficients) which are often non-integral, however the statistics around those quantities do test for association in the response levels. So coding, "very poor" as 0 and "excellent" as 5 in the case of Likert data is sensible.
You are using the word dependent ambiguously here. Does your experimental design have repeated measures within individuals? Is one individual exposed to many stimuli and recorded for different responses at different times? This would be repeated measures. Otherwise, I think you are confused about dependence and each stimulus/outcome observation is pairwise independent from other observations.
Comment: To answer your initial questions: I just want to know how confident people feel depending on various factors, e.g. the quality. The stimuli are visually degraded video clips in this case, and they are impaired in different ways, i.e. with different "treatments" if you want. One individual is exposed to *n* stimuli, one after another, a total of *n* times. The observations are independent, then, but of course "quality" and "confidence" are sort of dependent (although I agree I might have used the wrong wording here).
Comment: If you are interested in the effect of your stimuli on the ordinal response levels as you've stated, then this is a standard "full factorial" design. For an example of a different approach, look at latin squares. Both are examples of repeated measures analyses and you're correct in assuming you need to take the correlated nature of the data into account. Repeated measures ANOVA would be the knee jerk reflex analysis for this type of data. No need for a Wilcoxon since there's no censored data.
Comment: In our field, we can use latin square designs, but they're not that common for these types of experiments. As for the repeated measures ANOVA, could you maybe elaborate a little on what exactly to do in my specific case? Which would be the independent and dependent variable here?
Comment: Your indep and dep variable are determined by design: I don't know that, but you do. Repeated measures ANOVA lets you specify a cluster ID for values drawn repeatedly within the same individual. It lets your statistical technique know, "Hey, observations 14, 73, and 132 are all from the same individual, so consider them slightly more correlated". You specify independent and dependent variables much the same way as regular ANOVA.
Answer: A summary test statistic for multidimensional, non-metric (input and output) data is a tough pitch and likely of limited interpretable value.
You could run a proportional odds logistic regression model of one variable (input) on the other (target) - if you are willing to do the analysis as comparing the target's probability distribution over the input levels. It would show if the input variable has significantly different dependence over the input levels and target classes. It won't really matter for predictive probabilities which contrast scheme you use, however, for interpretation of the weights, you might like to use orthogonal polynomials. You will need to interpret with examples test cases and their predictive distributions on barplots. This is because along with the logit probability scale that the weights work on, there are cut-offs identified by the regression process - which makes it rather difficult to interpret logit scale quantities.
For example with R, your code would be
<code>#input data
#quality <- scan()
#confidence <- scan()
Q <- length(unique(quality))
C <- length(unique(confidence))

require(MASS)
# tell R that the data is ordinal
quality <- factor(quality, levels = paste(1:Q), ordered = TRUE)
confidence <- factor(confidence, levels = paste(1:C), ordered = TRUE)

# train model, R will use orthogonal polynomials by default
polr.model <- polr(confidence ~ quality)

#plot probability predictions as pdf for each input level
lapply(
  unique(quality),
  function(z) {
    pdf(paste('Quality_predictive_probabilities-Confidence_',z,'.pdf',sep=''))
    probs <- predict(polr.model,newdata=list(quality=z), type='probs')
    barplot(probs,xlab=paste('Quality',z),ylab='Confidence')
    dev.off()
  }
)
</code>
which will save the probability predictions into your current working directory. You may want to be careful about calling your variables confidence and quality if the audience is statistically aware as these words mean something quite specific to the community.
Comment: I ran your script but swapped `confidence ~ quality` since I'm rather interested in the effect of experienced quality on user confidence (is that the correct notation?). Running your script I get `newdata' had 1 rows but variable(s) found have 4938 rows` four times, and four times the exact same plots output as PDF (note the missing `.pdf` extension in your script). The only thing differing in the plots is the `xlab`, the numbers and histogram (?) are the same.
Comment: Oops, try newdata=list(quality=z).Did you also replace unique(confidence) with unique(quality)?
Comment: Yes, I updated the code and it produces graphics I can probably use. Thank you! However, I'm not sure how exactly interpret the numerical results (or the regression results specifically). The graphics are obvious, but what in `polr.model` is interesting for me?
Comment: The signs and magnitude of the regression coefficients for the different quality levels indicates their tendency to move the distribution around the 'confidence' classes. You could look at the t-statistics for the quality variable, but it would need you to throw out the only variable if they are not significant.


php-ffmpeg installation on apache2

Question: Trying to run PHP-FFMPEG and after install via composer I'm currently getting this.

PHP Fatal error:  Uncaught
  Alchemy\BinaryDriver\Exception\ExecutableNotFoundException:
  Executable not found, proposed : avprobe, ffprobe in
  /var/www/html/vendor/alchemy/binary-driver/src/Alchemy/BinaryDriver/AbstractBinary.php:159\nStack
  trace:\n#0
  /var/www/html/vendor/php-ffmpeg/php-ffmpeg/src/FFMpeg/Driver/FFProbeDriver.php(48):
  Alchemy\BinaryDriver\AbstractBinary::load(Array, NULL,
  Object(Alchemy\BinaryDriver\Configuration))\n#1
  /var/www/html/vendor/php-ffmpeg/php-ffmpeg/src/FFMpeg/FFProbe.php(226):
  FFMpeg\Driver\FFProbeDriver::create(Object(Alchemy\BinaryDriver\Configuration),
  NULL)\n#2
  /var/www/html/vendor/php-ffmpeg/php-ffmpeg/src/FFMpeg/FFMpeg.php(117):
  FFMpeg\FFProbe::create(Array, NULL,
  Object(Doctrine\Common\Cache\ArrayCache))\n#3
  /var/www/html/starapp/test.php(4): FFMpeg\FFMpeg::create()\n#4
  {main}\n\nNext FFMpeg\Exception\ExecutableNotFoundException: Unable
  to load FFProbe in
  /var/www/html/vendor/php-ffmpeg/php-ffmpeg/src/FFMpeg/Driver/FFProbeDriver.php:50\nStack
  trace:\n#0 /var/www/html/vendor/php-ffmpeg/php-ffmpeg/src/FFMp in
  /var/www/html/vendor/php-ffmpeg/php-ffmpeg/src/FFMpeg/Driver/FFProbeDriver.php
  on line 50

Some people have suggested running the following:
<code>$ffmpeg = FFMpeg\FFMpeg::create([
    'ffmpeg.binaries' => 'usr/bin/ffmpeg',
    'ffprobe.binaries' => 'usr/bin/ffprobe',
    'timeout' => 3600, 'ffmpeg.threads' => 12
]);
</code>
However I have no ffmpeg/ffprobe files in usr/bin and can't seem to find them anywhere.
EDIT:
FFMpeg is installed. I rebooted the server and restarted apache2 and now the files are visible. Getting this now:

PHP Fatal error:  Uncaught
  Alchemy\BinaryDriver\Exception\ExecutableNotFoundException:
  Executable not found, proposed : usr/bin/ffprobe in
  /var/www/html/vendor/alchemy/binary-driver/src/Alchemy/BinaryDriver/AbstractBinary.php:159\nStack
  trace:\n#0
  /var/www/html/vendor/php-ffmpeg/php-ffmpeg/src/FFMpeg/Driver/FFProbeDriver.php(48):
  Alchemy\BinaryDriver\AbstractBinary::load(Array, NULL,
  Object(Alchemy\BinaryDriver\Configuration))\n#1
  /var/www/html/vendor/php-ffmpeg/php-ffmpeg/src/FFMpeg/FFProbe.php(226):
  FFMpeg\Driver\FFProbeDriver::create(Object(Alchemy\BinaryDriver\Configuration),
  NULL)\n#2
  /var/www/html/vendor/php-ffmpeg/php-ffmpeg/src/FFMpeg/FFMpeg.php(117):
  FFMpeg\FFProbe::create(Array, NULL,
  Object(Doctrine\Common\Cache\ArrayCache))\n#3
  /var/www/html/starapp/test.php(11): FFMpeg\FFMpeg::create(Array,
  NULL)\n#4 {main}\n\nNext
  FFMpeg\Exception\ExecutableNotFoundException: Unable to load FFProbe
  in
  /var/www/html/vendor/php-ffmpeg/php-ffmpeg/src/FFMpeg/Driver/FFProbeDriver.php:50\nStack
  trace:\n#0 /var/www/html/vendor/php-ffmpeg/php-ffmp in
  /var/www/html/vendor/php-ffmpeg/php-ffmpeg/src/FFMpeg/Driver/FFProbeDriver.php
  on line 50
Comment: As it says on that github page **This library requires a working FFMpeg install. You will need both FFMpeg and FFProbe binaries to use it**
Comment: How did you install php-ffmpg and ffmpg
Comment: `composer require php-ffmpeg/php-ffmpeg` as on here https://github.com/PHP-FFMpeg/PHP-FFMpeg
Comment: THats the library that links PHP to FFMPEG.... Did you also install FFMPEG itself?
Comment: FFMpeg is installed. I rebooted the server and restarted apache2 and now the files are visible. Getting another error now.
Answer: Issue was the paths
<code>'ffmpeg.binaries' => 'usr/bin/ffmpeg',
'ffprobe.binaries' => 'usr/bin/ffprobe'
</code>
Whereas:
<code>'ffmpeg.binaries' => '/usr/bin/ffmpeg',
'ffprobe.binaries' => '/usr/bin/ffprobe'
</code>
Is working.

php-ffmpeg installation on apache2


How to insert text from a file into another in bash

Question: The content in fileA is:
Here's the ip list.

ip: 22.214.171.124
ip: 220.127.116.11
ip: 184.108.40.206
ip: 184.108.40.206

The content is fileB is
ip: 220.127.116.11
ip: 126.96.36.199
ip: 220.127.116.11
ip: 188.8.131.52

How to use sed command or other commands in a bash script to produce a list below?
Here's the ip list.

ip: 22.214.171.124
ip: 18.104.22.168
ip: 220.127.116.11
ip: 188.8.131.52

ip: 18.104.22.168
ip: 184.108.40.206
ip: 18.104.22.168
ip: 22.214.171.124

'cat fileA fileB' would only append fileB to fileA.
If I insert a keyword into fileA first and then replace the keyword with fileB's text, all lines from fileB's text would combine into one line when being assigned to a variable.
t=$(cat fileB)
sed '/[keyword]/c\$t' fileA

Comment: Re your edit: No one "abused his power". Your question is hard to understand, so two users (which might be entirely different from those who close-voted it) downvoted it. Write better questions that are clearly topical and this won't happen. See the [help] and [How to ask better questions on Serverfault](http://meta.serverfault.com/questions/3608/how-can-i-ask-better-questions-on-server-fault)
Answer: Unless I misunderstand, how about you append
cat filea >> fileb

You can do a sort afterwards, if that's what you're after.
Comment: There are lines that need to keep at the top in fileA. It could be more than one line that need to be at the top.
Comment: So... cat fileb >> filea


windows remote desktop vs tightvnc server

Question: Is there any comparation of the bandwidth usage, it seems that vnc take much more bandwitdh, but I am not sure.
Is there any way I can make vnc use less bandwidth.
Answer: You're absolutely right in your observation that, typically, VNC requires more bandwidth than RDP.
VNC is a "bandwidth hog" because it's oriented at duplicating the pixels of the remote display. Conversely, RDP is based on drawing primitives (boxes, lines, etc) rather than sending pixel updates. Think of it like this: In VNC, the pixels on the display that change get sent over the wire (simplified somewhat). If lots of pixels get modified-- say in drawing a large box in the middle of the screen, a potentially large number of pixels are modified and need to be sent over the wire. In RDP, the instruction "draw a box in the middle of the screen" gets sent over the wire (which is much more concise than a list of pixels to change) and the client "draws the box". (I'm radically simplifying this and not considering VNC compression at all, but this gives you a general idea of how it works.)
You can use various "flavors" of VNC that have different compression options, but at the end of the day the RDP protocol (and protocols like it-- ICA, X, etc) are very difficult to "beat" because, fundamentally, they need to move less data to accomplish the same effect.
Comment: You're really good at describing things in layman's terms.
Comment: @phuzion: Thanks. Comes from teaching classes for 8+ years... >smile<
Comment: @osij2is: Starting back in 1998 I taught academic courses at a community college in their Microsoft Certification program. I had a whole laundry list of classes (dating back to IIS 4.0). I ended up leaving in 2006 when my classes were transitioned to "online delivery". I've never had the enthusiasm to take an online class, and as such I wasn't about to try teaching one. It was a fun ride, and I met a lot of people with varied career backgrounds and interests. I got asked a *lot* of "what if" questions and spent hours in labs trying to break Microsoft products in new and fun ways.
Comment: @Evan - You're a braver man than most. Dare I ask what you taught? :)
Answer: Like Evan says, sending the instructions to the remote display is better than sending the picture detail.
However, I think that some advantage comes from TightVNC and UltraVNC techniques when you
consider that the resolution you want to use at the other end may not be really very high.
The VNC tools allow JPEG compression and even 8-bit pixel communication that will 'corrode' the picture to some extent but give you lower bandwidth utilization and effectively speed.
You have to remember that JPEG compression is fast on computers today.
And, You can compress a lot for a typical monitor resolution (I use 1920 horizontal pixels, WUXGA)
An 2005 post by Jeff -- VNC vs. Remote Desktop.
Since then, VNC has made some more progress.
Answer: TightVNC has three connection profiles, try the Low Bandwidth option.

Low Bandwidth
Normal
Highspeed

Also change the theme on the remote PC to be as simple as possible, no backgrounds, no gradients, etc.  VNC does compress the data, and solid screen areas compress much better than pictures and/or gradients.


What's the probability a rabbit will return to a (certain) forest?

Question: Let's assume we have a forest.
And there is a breed of rabbits that is visiting that forest all the time.
It is possible to distinguish every individual rabbit.
There are devices in that forest that count the visits of every individual rabbit on a daily basis; so there are not two or more visits for a specific rabbit on one day; a rabbit stay the whole day so to say.
The information I have is e.g.:

rabbit #343 visited the forest on May 5th 2012 for the 12th time.
rabbit #793 visited the forest on June 2nd 2012 for the 1st time.

now the CEO of the forest wants to measure if there is a tendency of rabbits not coming back.
and I am the CEO's data guy and have to figure that out.
My question is if this "problem type" is known under a specific label - I guess it is - and if there is something like an established formula to indicate the "back out rate" or the "loyalty rate" / "probability of another visit extrapolated for all rabbits".
What I will do is to chart for multi-day-time-periods (e.g. a week)

the number of rabbits that visited for the first time
and the number of rabbits that visited for the last time (e.g. hindsight knowledge for six month)

but I doubt that is the most efficient way to go about this question.
Comment: In a business-analytic context, this is often referred to as *churn modeling* or *churn prediction*. It employs a wide variety of statistical ideas and methodologies including survival analysis, Markov-chain and stochastic-process theory, hierarchical Bayes models, etc.
Comment: Can you give some more examples of how you would want to use the data? Decisions it might be applied to, etc. "Measure if there is a tendency of rabbits not coming back" is very broad. A more specific example could be "Evaluate the success of an email followup campaign by dividing new rabbits into two experimental groups with and without the campaign and calculating the % that return at least once after their first visit."
Comment: my stochastic knowlege got through time a tad rusty ... what would be a solid yet simple algorithmic approach. but thanks for the labelling. if you put it more verbose with a useful link for further reading, I could accept it as an answer.
Comment: Although, if all you need is the name I guess that's not necessary.
Answer:
In a business-analytic context, this is often referred to as churn
  modeling or churn prediction. It employs a wide variety of statistical
  ideas and methodologies including survival analysis, Markov-chain and
  stochastic-process theory, hierarchical Bayes models, etc.
Comment: I've copied this comment by @cardinal as a community wiki answer because the comment is, more or less, an answer to this question. We have a dramatic gap between answers and questions. At least part of the problem is that some questions are answered in comments: if comments which answered the question were answers instead, we would have fewer unanswered questions.


To which (logical) language belongs $\{p\} \Rightarrow q$?

Question: According to my book, the essential difference between a logical implication $\{p\} \Rightarrow q$ and the statement $p \to q$ is  that $p \to q$ is part of the propositional language, and $\{p\} \Rightarrow q$ is not. My question is, to which language does the logical implication $\{p\} \Rightarrow q$ belong?
Comment: Which book are you using? Other people may be able to look it up.
Comment: @CarlMummert I'm using this book: http://www.ou.nl/Docs/Spinoza/Benthem/LIA_eBook.pdf , page 32. But it is written in dutch.
Answer: The authors clarify the matter in the next sentence:

Schrijven we $\varphi\Rightarrow\psi$, dan stelt dit dat $\psi$ inderdaad volgt uit $\varphi$, terwijl als we $\varphi\to\psi$ opschrijven, deze formule best onwaar kan zijn.

In other words, $\varphi\Rightarrow\psi$ is the assertion that $\psi$ really is a logical consequence of $\varphi$, while $\varphi\to\psi$ is a proposition that may be true or false.
The connective $\to$ is part of the language in which we build propositions; $\Rightarrow$ is part of the language in which we talk about these propositions. Thus, if $A$ is a set of propositions, $A\Rightarrow\varphi$ is the assertion that if every proposition in the set $A$ has the truth value TRUE, then so must $\varphi$: $\varphi$ is a logical consequence of the propositions in $A$. In particular, $\{\varphi\}\Rightarrow\psi$ is synonymous with $\varphi\Rightarrow\psi$: it's the assertion that if $\varphi$ has the truth value TRUE, then so must $\psi$.
In contrast, $\varphi\to\psi$ is just a proposition that may be true or false; the formula does not in itself make any assertion about the truth or falsity of any proposition.
Answer: The way that this book appears to be using the notation, if $A$ is a set of formulas and $\phi$ is a formula, the relation $A \Rightarrow \phi$ means that in the appropriate truth table, every row that makes all formulas in $A$ true also makes $\phi$ true.
So, for example, $p \land q \Rightarrow q$ holds because every row that makes $p \land q$ true also makes $q$ true. This is different than $p \land q \to q$, which is not true or false on its own, but only true or false for each row in the truth table. The logical implication arrow $\Rightarrow$ has the effect of quantifying over all the rows. So $p \land q \to q$ has "4 separate truth values", one for each row of a 2 variable truth table, while $p \land q \Rightarrow q$ is simply true.
Similarly, $\{p, p \to q\} \Rightarrow q$ holds, but this is not even of the right syntactic form to be true or false in each row.
The language of formulas is called the object language; the language of $\Rightarrow$ is called the metalanguage, which is another language used to study the object language. The need to keep these distinct is not obvious at first, but the distinction turns out to be vital for many aspects of logic.
Comment: Great answer, really appreciate it :)


Windows Server 2008 as Bridge in virtualbox: make another Virtual Machine enter his Domain

Question: I have installed a Windows Server 2008 in Virtualbox(bridge) this one work fantastic! i want to make a virtual machine(virtualbox) which can enter the Domain and access my Server 2008(Datacenter).

Which network connection should i choose? bridge, nat, host-only?
How should i configure Server 2008 to accepts the new machine in his Domain?

Thank you a lot!
Edit : When i mean enter the Domain it is like this explicitly  :

I just want to build into VirtualBox a LAN Environment -> with One Server and One another OS.
On the Server(win2k8) i will install a Webservice( with Windows Authentication )
On the OS a client which should consumes the Webservice.

This is why the client should be a part of the win2k8 Domain 'cause the authentication.
I hope that was clear enough.
Comment: Yes it is a domain controller!
Comment: So is the current WIn2k8 guest a domain controller?
Answer: If you want the second host to only access the guest DC, I suggest you create a Host-only network in VBox, add a second NIC to the DC and attach it to the new network.  Then connect the NIC of the new guest to host-only network.
If you don't care if both hosts have access to the bridged network, then add the second guest to the bridged network but point it to the DC for DNS.
Having the server and the guest point to an AD DNS will be crucial to make this work
Comment: well! thank you a lot uSlackr! my Win2k8 is the DataCenter Edition! so i think he is a domain controller isnt? I tried Host-Only but i occur some problems that is why i made a bridge for my Server! do u mean that i must installed a new VirtualBox into Win2k8 and then installed Win 7 into it?
Comment: It is not a domain controller unless you install the bits and run dcpromo.  but it doesn't sound like you need it.  I just wasn't sure.  And no, there is no reason to change your current setup.  Perhaps you could clarify what you mean when you say you want a second host to "enter the domain"


Get stable range in google spreadsheets (after adding/deleting rows in that range)

Question: Having a problem with a range of cells.
On the list first 2 rows are headers and rows 3-82 (80 total) are for data.
I have to delete/add rows from this data sometimes and my condition formating rules and formulas are changing.
E.x. =COUNTIF(WIN!B3:B78; "<>") had range B3:B82, but after deleting of rows it became as B3:B78.
Any way to hardcode this 82 value?
Answer: You can use INDEX function:
=COUNTIF(B3:INDEX(B:B,82), "<>")

Comment: Thank you!
Working with `=COUNTIF(WIN!B3:INDEX(WIN!B:B;82); "<>")` for my case with other page


A little guidance setting up FTP server authentication on Windows Server 2008 R2 standard?

Question: I have a (clean) server running Windows Server 2008 R2 standard. I would just like to use it for serving a website and a FTP server through IIS. IIS is installed and serves my website propery. I have now added a FTP site but when I try to logon using my user/pass i get the following error:

530 User cannot login

From this article (http://support.microsoft.com/kb/200475) I understand that these four causes can be pointed out:

The Allow only anonymous connections security setting has been turned on in the Microsoft Management Console (MMC). Not the case
The username does not have the Log on locally permission in User Manager. The user is in the Users group, however I'm not able to logon through RDP. I tried configuring this by following this article through GPMC however this only works when I'm logged in as a domain user on a domain controller which I'm not: I'm logged in as administrator
The username does not have the Access this computer from the network permission in User Manager. Not sure what this implies...?
The Domain Name was not specified together with the username (in the form of DOMAIN\username). Tried adding the server name: server\username, not working...

I am an absolute server noob and I'd just like to be able to connect through FTP... Any guidance is highly appreciated!
Answer: You need to go into the FTP settings in IIS and change it from Anonymous to Authenticated. Then you need to give the user NTFS permissions to the folder(s) that you want them to have access to via FTP. Access control in IIS FTP server is controlled with NTFS ACLs.


Deleted term shown in exposed filter

Question: I'm using exposed simple hierarchal select module for a taxonomy in my exposed filter, i have deleted some terms from the taxonomy but the filter  still showing the deleted terms.
I tried clearing caches and cron and even waited one day with no luck!
Any ideas what is the problem??
❤
Answer: I think it may be revisions or taxonomy revisions issue
module documentation  says
This module enables revisions for the taxonomy terms.
The users will have an option to create new revision for a taxonomy term as for
nodes. This means when a taxonomy term is edited in the default form, a new
checkbox is displayed for revision creation. If clicked a textarea will appear
to fill a revision log message.
Also on the taxonomy term edit page a new menu tab appears after the module
installation which will list all of the taxonomy term's revisions and provides
Comment: I don't have taxonomy revisions module installed. And when i deleted the term it disappeared from the taxonomy menu but still in the exposed filter.
Answer: disabling the 'JavaScript callback handler' module solved the problem.

Deleted term shown in exposed filter


A closed formula for $\prod_{n=1}^{N}(an-b)\;$?

Question: Is there a way to express a closed formula for the finite product:
$$\prod_{n=1}^{N}(an-b)$$
Maybe it can be done through the Pochhammer symbol?
Answer: We can start by taking out a factor of $a^N$, leaving us with $a^N \prod_{n=1}^{N} (n-\frac{b}{a})$, and now we can just use the Pochhammer symbol(I'll assume you know what this is as you mention it in your question) to get $a^N(1-\frac{b}{a})_{N}$
It is known that $(x)_{N} = \frac{\Gamma(x+n)}{\Gamma(x)}$(this should be intuitively obvious from the definition), so our closed form is $\boxed{a^N \frac{\Gamma(1-\frac{b}{a}+N)}{\Gamma(1-\frac{b}{a})}}$
I'm not a hundred percent sure that a nicer form doesn't exist, but this is the best that I could come up with.


Let $a, b$ integers such that $ab+2a+3b=93$. Find all solutions integers.

Question: Let $a, b$ integers such that $ab+2a+3b=93$. Find all solutions integers.
What I tried is
$ab+2a+3b=b(a+3)+2a$ but i don't see how to proceed to related $a$ and $b$ such that see it multiplying and play with combinations of  $93=3*13$.
Comment: Hint: If $ab+2a+3b=93$, then $(a+3)(b+2)=?$
Comment: There are 12 integer solutions : https://www.wolframalpha.com/input/?i=ab+%2B2a+%2B+3b+%3D+93   :)              ( 93 = 3 * 31 ;) )
Comment: Thank you so much
Comment: $$93 = 3 . 31 $$ not $$93 =3 . 13$$ as you said.
Answer: $(a+3)(b+2)=99$
then you can decompose 99 and get integer solutions.


What does it mean to "renormalize" the density of a kernel distribution?

Question: I'm a marine spatial ecologist looking to remove land from some kernel density estimations of tagged sharks. I've seen numerous methods for this approach, with one such method described succinctly in Barry & McIntyre (2011):

A typical approach to remedying this [kernel density estimator boundary] problem is first to compute the
  estimator as if there were no boundaries, then to clip off inaccessible regions after the fact, and finally renormalize the density.

What does it mean to "renormalize" the density? Are they essentially saying that once you calculate the kernel density, you set your boundary areas (in my case, land) to zero, and then make every cell in your kernel range in value from 0 to 1?
Comment: This is answered at https://gis.stackexchange.com/questions/13925 and https://gis.stackexchange.com/questions/42354 (on another SE site).
Answer: Renormalizing here means that you are forcing the integral of your distribution to be equal to 1. This is a required property of any probability distribution.
Of course, any density estimation method, kernel one included, is made in a way that the result will be valid, which means that its integral will be 1. If you clipp off some regions from the domain of that fuction, its integral won't be 1 anymore. To fix this, you have to divide the function by its integral, so that the resulting function will have unit integral and therefore will be a valid probability density. This is the "normalization".
Comment: +1.  But note that it's likely that in this case the KDE does not estimate a probability: it will estimate the number of sharks per unit surface area of ocean.  Your argument applies, *mutatis mutandis:* normalization means the total number of estimated sharks equals the total number of observed sharks.  spops: there's no bell curve imposed.  Normalization will not change a colored contour map of your density at all, for instance--it leaves the spatial pattern (within the water areas) unchanged. Normalization is a poor idea when many of the sharks are close to land: it downweights them.
Comment: I don't know any package for doing that, but if it is a raster I think it would be very easy to do by hand (I mean by coding it, the integral would be evaluated as a sum over rester points). I never did it though, so I don't really know your workflow, sorry.
Comment: So essentially this is forcing a normal distribution ("bell curve") on all points in both dimensions of a 2D kernel? (This is the struggle of ecology grad students only knowing rudimentary statistics)
Comment: @spops I didn't really understand your comment. What do you mean?
Comment: Thanks whuber & carlo for the clear explanations. I've been looking for the best method to estimate home ranges/density and have gotten the impression that cutting the land out is a bad idea - but I think I will post a separate question on this topic in the GIS forum!
Comment: Let's say I or another future poster wanted to actually go about actually doing this - is renormalizing the kernel raster something typically done by stats packages (e.g. in R)? I'm assuming dividing by the integral isn't something done longhand anymore?


Modify Active Directory Client OU from Client Machine

Question: I am trying to create a powershell startup script for my domain controlled computers that will place the computer into the the specified OU. I would like for the variables to be taken on the local computer and then passed to the remote server. Once there I would like to execute the last two lines on the server.
The script below does work if it is ran on the server however as stated above I would like to be able to execute this from a client machine. How can I make this happen?
$computername = $env:ComputerName
$new_ou = "OU=TestOU,DC=Test,DC=Controller,DC=com"
Import-Module ActiveDirectory
Get-ADComputer $computername | Move-ADObject -TargetPath $new_ou

Note: Before anyone asks...my goal is to have the OU be determined by the client IP address. I understand that there are scripts that will do the discribed above but they run strictly on the server and query the DNS. I would rather have this run as a startup script on the local computer so I an better control which computers are being moved. At this point I am not interested in tackling this issue. Only the issue of how to execute the above lines on a local machine.
Comment: Did you try running the script from a client (while logged on the client)? I guess you will need the AD module from RSAT enabled. You could also have the machine run a script to drop a file on the server with its IP address (and more if needed) and run a script on the server to do the AD work as a scheduled task. You could also link IP subnets to Active Directory sites iirc.
Answer: I assume you want to run the last 2 lines on the server because you expect that most of your domain computers won't have the RSAT tools or AD cmdlets installed.
The way to run it on a server is to have PowerShell Remoting enabled on the server and then use Invoke-Command.
That authentication is typically done with kerberos, though you could change the method, and you can supply credentials manually (though I doubt you want to be embedding credentials in the script).
You need to consider that the user making the AD changes needs permission to do so. Usually that's a domain admin, although permission could be delegated.
If you're running this as a startup script, it's running as SYSTEM. That account authenticates on the domain as the computer account (COMPUTERNAME$). This means that the computer account needs permission to move itself, which may mean it needs the ability to write objects into all possible OUs (I don't recall offhand which permissions are needed).
So you would either need to grant this ability to all computers (any computer in Domain Computers would have the ability to move any other computer to any OU), or somehow give each computer only the ability to move itself into the correct OU (which might still be too much in the way of permissions).
Another option is to make a customized session configuration on the server with a RunAs user. You could limit the users allowed to connect to the session (to Domain Computers), and limit the allowed commands so that the connecting computers can only run a limited set of functions/cmdlets. Even better, you can write your own function to do the change and only let them run that one. With the RunAs user being a privileged user in AD, the changes will work without the connecting user having the ability to make the changes directly, and without giving the connecting user the ability to use the privileged user or elevate their own permission. Remember that the connecting user in this case is the computer account.
This last method is, I think, the best/most secure way to do what you want, if you insist that it must be initiated from the client machine.
Reconsider doing this as a server-side process. Get-ADComputer can return an IPv4 address for the object, so you could use that instead of DNS. Centralizing it would make it easier to manage and troubleshoot the process.
Comment: So I did a bit more thinking about what you said and I believe you are right. It is easlier and more secure to organize via the server. I did a bit of research and I am basing my script off of the floowing: http://blogs.technet.com/b/heyscriptingguy/archive/2011/12/03/use-powershell-to-move-computers-based-on-ip-addresses.aspx
Comment: I think the concept seemed simple but as I got into building it out I began to see something that I was a bit uneasy with. For me the particularly difficult and concerning thing was what you mentioned in the 5th paragraph.
Comment: @thebradnet nice! The only thing I might mention is that the article you linked to is a bit long in the tooth. It uses the Quest AD cmdlets but by now you could just use Microsoft's `ActiveDirectory` module.
Comment: @thebradnet yeah that was the crux of it for me too. Even if you could lock down the AD permissions in such a way, it seems like something that would need to be exceptionally well-documented, and might need constant work (every new computer added separately, every decommissioned computer removed separately). Constrained endpoints really offer some nice options, it just seems like this particular task can be done centrally with less effort and better results.
Comment: you are right, I did link to one that uses Quest. The same fellow who wrote that article has a version of the same script that used the ActiveDirectory module. I believe it is linked on the same page.


Python datetime.time and arithmetic operations

Question: How to get sum and difference of two datetime.time variables in Python? For example:
import datetime
now = datetime.datetime.now()
act_time = datetime.time(now.hour, now.minute, now.second)
diff = act_time - finish_time

Comment: http://docs.python.org/2/library/datetime.html#timedelta-objects or http://stackoverflow.com/questions/13685201/how-to-add-hours-to-current-time-in-python/13685221#13685221
Comment: @hafron this solution should fit to your question http://stackoverflow.com/a/51042/461493
Comment: What do you mean by sum?
Comment: What are you trying to do? Just difference of two times?
Comment: Yes, it's what I'm searching for, maybe it doesn't help my code to be simple and clear but it works. Thank you @tony
Comment: It's easier to get a `datetime.time` instance from a `datetime.datetime` instance by calling the latter's `.time()` method.
Answer: Try this for difference:
#-----------------------------
# Dates produce timedeltas when subtracted.

diff = date2 - date1
diff = datetime.date(year1, month1, day1) - datetime.date(year2, month2, day2)
#-----------------------------

bree = datetime.datetime(1981, 6, 16, 4, 35, 25)
nat  = datetime.datetime(1973, 1, 18, 3, 45, 50)

difference = bree - nat
print "There were", difference, "minutes between Nat and Bree"
#=> There were 3071 days, 0:49:35 between Nat and Bree

weeks, days = divmod(difference.days, 7)

minutes, seconds = divmod(difference.seconds, 60)
hours, minutes = divmod(minutes, 60)

print "%d weeks, %d days, %d:%d:%d" % (weeks, days, hours, minutes, seconds)
#=> 438 weeks, 5 days, 0:49:35

#-----------------------------
print "There were", difference.days, "days between Bree and Nat."
#=> There were 3071 days between bree and nat

Operations:
#-----------------------------
# Adding to or Subtracting from a Date
# Use the rather nice datetime.timedelta objects

now = datetime.date(2003, 8, 6)
difference1 = datetime.timedelta(days=1)
difference2 = datetime.timedelta(weeks=-2)

print "One day in the future is:", now + difference1
#=> One day in the future is: 2003-08-07

print "Two weeks in the past is:", now + difference2
#=> Two weeks in the past is: 2003-07-23

print datetime.date(2003, 8, 6) - datetime.date(2000, 8, 6)
#=> 1095 days, 0:00:00

#-----------------------------
birthtime = datetime.datetime(1973, 01, 18, 3, 45, 50)   # 1973-01-18 03:45:50

interval = datetime.timedelta(seconds=5, minutes=17, hours=2, days=55)
then = birthtime + interval

print "Then is", then.ctime()
#=> Then is Wed Mar 14 06:02:55 1973

print "Then is", then.strftime("%A %B %d %I:%M:%S %p %Y")
#=> Then is Wednesday March 14 06:02:55 AM 1973

#-----------------------------
when = datetime.datetime(1973, 1, 18) + datetime.timedelta(days=55)
print "Nat was 55 days old on:", when.strftime("%m/%d/%Y").lstrip("0")
#=> Nat was 55 days old on: 3/14/1973

#-----------------------------
# Adding to or Subtracting from a Date
# Use the rather nice datetime.timedelta objects

now = datetime.date(2003, 8, 6)
difference1 = datetime.timedelta(days=1)
difference2 = datetime.timedelta(weeks=-2)

print "One day in the future is:", now + difference1
#=> One day in the future is: 2003-08-07

print "Two weeks in the past is:", now + difference2
#=> Two weeks in the past is: 2003-07-23

print datetime.date(2003, 8, 6) - datetime.date(2000, 8, 6)
#=> 1095 days, 0:00:00

#-----------------------------
birthtime = datetime.datetime(1973, 01, 18, 3, 45, 50)   # 1973-01-18 03:45:50

interval = datetime.timedelta(seconds=5, minutes=17, hours=2, days=55)
then = birthtime + interval

print "Then is", then.ctime()
#=> Then is Wed Mar 14 06:02:55 1973

print "Then is", then.strftime("%A %B %d %I:%M:%S %p %Y")
#=> Then is Wednesday March 14 06:02:55 AM 1973

#-----------------------------
when = datetime.datetime(1973, 1, 18) + datetime.timedelta(days=55)
print "Nat was 55 days old on:", when.strftime("%m/%d/%Y").lstrip("0")
#=> Nat was 55 days old on: 3/14/1973

Source: http://pleac.sourceforge.net/pleac_python/datesandtimes.html
Comment: information overflow.


Django Admin: How to select Groups roles to display based on active user role?

Question: I have a Django app with multiple levels of admin role and users defined by the django-role-permissions package.  I want to apply permissions to users only through groups, defining the permissions for the group roles and assigning the user to the correct group.
I want to "hide" the higher level admin roles in Groups when lower level admins create users. A lower level admin should not be able assign a created user to a higher level admin role in Groups.
I can do this with Users (lower level admins cannot view / change higher level admins) by overriding get_queryset with code shown below. I want to be able to do something equivalent with the roles in Groups.  I would prefer to do this in my admin.py rather than in templates. It would have been nice if the Groups members were also gathered by get_queryset, but that does not seem to be the case.  I have searched around without finding anything definitive. I set up django-debug-toolbar to see the context passed into the forms, but I don't see the Groups elements passed in that way to change_form. It's tempting to try overriding FilteredSelectMultiple inside of django.contrib.admin.widgets, but I don't yet see exactly where the Groups elements are actually gathered, so that feels like too much guesswork to try that yet.
What would be the best way for me to proceed?
from django.contrib.auth.models import User
from django.contrib import admin
from django.utils.translation import ugettext, ugettext_lazy as _
from rolepermissions.checkers import has_role
from myapp.roles import SuperAdmin, Admin   # can't import TrustedUser and User because already have User above LOL
import logging

logger = logging.getLogger(__name__)

class MyUserAdmin(UserAdmin):
    def get_queryset(self, request):
        qs = super(MyUserAdmin, self).get_queryset(request)
        logger.debug(f'get_queryset logged in user is {request.user}, queryset is {qs}')
        if request.user.is_superuser:               # see all users
            return qs
        elif has_role(request.user, SuperAdmin):    # see all but superusers
            return qs.filter(is_superuser=False)
        elif has_role(request.user, Admin):         # see all but superusers & SuperAdmins
            excludes = [x.username for x in qs if has_role(x, SuperAdmin)] # has_role will be true for superuser
            return qs.exclude(username__in=excludes)
        else:
            logger.debug(f'get_queryset should never get here {request.user}, acting on qs {qs}')
            return q.none()

#Unregister current Django Admin
admin.site.unregister(User)

#Register current Django Admin
admin.site.register(User, MyUserAdmin)

By looking at the admin feature with the web developer tools, the objects I care about a the RelatedFieldWidgetWrapper which contains the FilteredSelectMultiple class.  Going through all the inheritance, eventually I got to forms/widget, and within forms/widget there is a method optgroups that appears to provide the group lookup that I am looking for.
So I do want to override FilteredSelectMultiple.  How can I do that or  how can I override django.contrib.admin.widgets?
Answer: I ended up doing something that looked a lot like this:
from django.contrib.auth.admin import UserAdmin, GroupAdmin
from django.contrib.auth.models import User, Group
from django.contrib import admin
from django.utils.translation import ugettext, ugettext_lazy as _
from rolepermissions.checkers import has_role
from myproj.roles import SuperAdmin, Admin

class MyUserAdmin(UserAdmin):

def get_form(self, request, obj=None, **kwargs): # filters groups in the change_form, prevents creation of higher privledge user when adding user
    # Get form from original UserAdmin.
    form = super(MyUserAdmin, self).get_form(request, obj, **kwargs)
    if 'groups' in form.base_fields and has_role(request.user, Admin) and not request.user.is_superuser:
        groups_filtered = form.base_fields['groups']
        excludes = ["super_admin", "admin"]       # Admin role cannot modify krakbot_admin or admin
        groups_filtered.queryset = groups_filtered.queryset.exclude(name__in=excludes)  # updates groups_filtered queryset
    return form

with an unregister of the original User model, and registering the new User with the MyUserAdmin class. There was additional functionality in the MyUserAdmin class, which I have left off.
The key information was someone else on SO mentioning that the base_fields had the group data that I was looking for, and also that the data I wanted to filter was present the second time the from was presented, so I needed a conditional ('groups' in form.base_fields) to detect when we were going through the form for the second time.


Is it possible to show callout views for 3 different annotations at once?

Question: I need to show calloutView for all 3 annotations I presently have on the map, and let the user decide which he will interact with based on the info written on those callouts.
I tried calling:
<code>[[SKRoutingService sharedInstance].mapView showCalloutForAnnotation:annotation1 withOffset:CGPointMake(0, 52.0f) animated:YES];
[[SKRoutingService sharedInstance].mapView showCalloutForAnnotation:annotation2 withOffset:CGPointMake(0, 52.0f) animated:YES];
[[SKRoutingService sharedInstance].mapView showCalloutForAnnotation:annotation3 withOffset:CGPointMake(0, 52.0f) animated:YES];
</code>
But it results in showing a CalloutView only for the last annotation.
Any solution to this?
Comment: It's covered here: http://stackoverflow.com/questions/2417952/multiple-annotation-callouts-displaying-in-mkmapview
Answer: Actually, I solved this with making a custom UIView for annotation, adding the Map pin and the UIView that was supposed to be a Callout View. In there, i added a label that will hold the value I need to show to the user
Comment: no problem i got the answer https://stackoverflow.com/questions/47887717/how-to-add-a-customview-xib-as-annotation-in-ios
Comment: Unfortunately no, I don't have a hold of that code any more as I did it long time ago. But the main idea is this: instead of just showing the map pin and then showing the callout view once you click on the pin, make the annotation to look like a combination of the map pin and the callout view above it as a default. That way you can customize it to look whatever you want it. You can put your labels and buttons on that callout view and connect them with the appropriate IBActions of your choosing


Ajuda para escrever código

Question: Como devo fazer para utilizar o Dev-c++ com este código.
Como traduzi-lo para C?
Comecei há pouco tempo com programação, estou meio enrolado para entender algumas coisas.
Programa CalculoMedia
Var
 N1, N2, MEDIA: Real
Início
Leia N1
Leia N2
MEDIA ← (N1+N2)/2
Se MEDIA >=6 Então
 Escreva "Aluno aprovado com média: ", MEDIA
 Senão
 Escreva "Aluno reprovado com média: ", MEDIA
Fim Se
Fim.

Comment: Matheus, retornei a pergunta ao seu estado original mais compreensível, para que a resposta aceita não fique fora de contexto. Se você tem **novas** dúvidas, mesmo que sejam à respeito do mesmo programa, crie uma nova pergunta, explicando seu problema.
Comment: Mas este problema só necessita dos comandos básicos da linguagem C. 15 minutos de estudo e você estará apto a solucionar seu dever de casa.
Answer: Para transcrever esse programa para linguagem c, primeiro é necessario um metodo main que é equivalente a instruçao programa <nome>
as instruções leia e escreva devem ser substiuidas por printf e scanf, se por if e fimse por {
segue um exemplo de como deve a sintaxe:
#include <stdio.h> // declara printf e scanf, usados abaixo

int main(int argc, char *argv[]) {// equivalente ao programa
    int numero; //equivalente ao var
    printf("digite um numero: "); // serve para imprimir caracteres na tela
    scanf("%d", &numero); // leitura de um valor

    if(numero > 10){ // se
        printf("numero maior que 10");
    }else{// se não
        printf("numero menor que 10");
    }// fimse
    return 0;
}// fim do programa

Comment: Faltou o `return 0;`
Comment: estou tentando mais esta dando um erro:[Warning] incompatible implicit declaration of built-in function 'scanf' [enabled by default]
Comment: @matheusferreira adicione o `#include ` no topo.
Comment: @GuilhermeBernal, obrigado por acertar o `#include`.
Answer: O IF está errado faltou as chaves tente assim:
if(MEDIA >=6){
    printf ("Alunos aprovados com media: ", MEDIA);
}
    else{
    printf ("Alunos reprovados com media: ", MEDIA);
}

Ajuda para escrever código


Why is CompositeCollection not Freezable?

Question: I am writing an application using the MVVM pattern.  I am providing data to my view by setting my view's DataContext property to an instance of my ViewModel.  Generally I just use Binding from there and go about my way.
Recently, I tried to implement a ComboBox with an "extra" element beyond the collection my ViewModel provides that says "Select Item".
<ComboBox>
    <ComboBox.ItemsSource>
        <CompositeCollection>
           <ComboBoxItem IsEnabled="False">Select Item</ComboBoxItem>
           <CollectionContainer Collection="{Binding MyItemsCollection}" />
        </CompositeCollection>
    </ComboBox.ItemsSource>
</ComboBox>

The problem is, CompositeCollection is not a Freezable: Freezable Objects Overview.  This causes only the static ComboBoxItem to appear and none of the results from my binding expression.
My initial reaction to the problem was to just implement my own version of CompositeCollection that was Freezable.  This, though, begs the following question:
Why isn't CompositeCollection a Freezable in the first place?
My concern is that generally these decisions are made for a reason and I don't feel I know enough about Freezable to say why they didn't inherit from it.  I know I can implement this collection, but I'm concerned there will be a measurable difference in performance if I do.
Any help would be appreciated.  Thanks!
Also: please note that I realize I can insert a Null or some other special value and provide and template or valueconverter to do what I want.  This is not the question I'm interested in... only the question in bold above.
Update:
After some further research brought on by ArsenMkrt's comment, I'm led to believe this was actually an oversight.  The evidence is this:

There is a collection that is freezable called FreezableCollection<T>.  It does not produce CollectionViews, which makes it inappropriate for my needs directly.
Sam Bent of MSFT says as much in the above link.  I cannot find contact information for him yet, but I plan on discussing this with him if I get the chance.

My current plan to get around this problem is to create a new collection with the properties of CompositeCollection and FreezableCollection<T>.  I don't know if it'll work yet, but I'm thinking about something like this:
public class BindableCompositeCollection : FreezableCollection<object>, ICollectionViewFactory

If anyone has a better option, I'd like to hear it!
Comment: may be this will help?http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/b15cbd9d-95aa-47c6-8068-7ae9f7dca88a
Comment: It's the same basic problem as outlined here, with the same workarounds applicable: http://www.codeproject.com/KB/WPF/ArtificialInheritanceCxt.aspx. Personally, I prefer the "spy" trick.
Comment: Maybe... it seems to contain a MSFT employee saying that it's a bug.  Interesting.  Makes me feel a little better about doing this.  I'd like to see if anyone has any concerns about performance, though.

Log this as an answer so I can give you credit if it turns out that this is all just because someone overlooked this scenario for CompositeCollection.
Answer: I just tried this tonight:
public class State
{
    public string Code { get; set; }
    public string Name { get; set; }
}

public class MyWindowViewModel
{
    ObservableCollection<State> _states = new ObservableCollection<State>
    {
        new State { Code = "FL", Name = "Florida" },
        new State { Code = "CA", Name = "California" },
    };

    public ObservableCollection<State> States
    {
        get
        {
            return _states;
        }
    }
}

<Window x:Class="WpfApplication1.MyWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:app="clr-namespace:WpfApplication1"
        Title="Window1"
        Height="300"
        Width="300">

  <Window.Resources>
    <app:ServiceLocator x:Key="Locator" />
  </Window.Resources>

  <StackPanel>
    <ComboBox x:Name="TestCombo" SelectedIndex="0" DisplayMemberPath="Name" SelectedValuePath="Code">
      <ComboBox.ItemsSource>
        <CompositeCollection>
          <app:State Code="" Name="Select a state..." />
          <app:State Code="TX" Name="Texas" />
          <CollectionContainer Collection="{Binding Source={StaticResource Locator}, Path=MyWindowViewModel.States}" />
        </CompositeCollection>
      </ComboBox.ItemsSource>
    </ComboBox>
  </StackPanel>
</Window>

The key here is to create an instance of your service locator as a static resource then go through it to get to your viewmodel. The service locator can wire up to instances of the ViewModel using Unity or whatever DI you want.
Edit:
Actually in my silverlight app I create the service locator as a static resoure in the App.xaml and then bind my other UserControls/Windows/Pages DataContext to a ViewModel property of the service locator. It should still work the same way for the combo boxes though even if the service locator is instantiated in the App.xaml's resources. I wish there was a silverlight version of CompositeCollection that I could use. This would work great for the app I'm working on. :(
Comment: We have been meaning to go this route based on some recent suggestions on Marlon Grech's blog.  I'll try this in the morning!


PHP + AJAX not yielding results when querying database

Question: I'm taking my first steps in PHP and now I'm trying to create a simple login form and trying to validate the information using AJAX and PHP by querying a database.
I used Ajax because I needed to change a few elements on my page in case the login information wasn't valid and later I found out that you can't actually call a php function directly from jquery, you need to use ajax instead.
I have this form in a php file:

      <form>

        <input type="text" required id="username" name="user" placeholder="Username">

        <input type="password" required id="password" name="pass" placeholder="Password">

      <input type="button" name="submit" id="loginButton" value="login" onclick="post();" class="btn-login">
      </form>

      Forgot password?

And I've created this ajax script to send my variables to the php file that is supposed to test the login information, this is the ajax script:

I get the value of the password and username by accessing the elements via their ID and then I send it to the php file entitled "testLogin.php" that contains the script to test the login information
this is the content of that file:
<?php
session_start();
include_once('connect.php');
if(isset($_POST['username']))
{
  $username = $_POST['username'];
  $password = $_POST['password'];
  $sql = "SELECT * FROM users WHERE Username = '".$username."' AND password ='".$password."' LIMIT 1";
  $result = mysql_query($sql) or die(mysql_error());
  if(mysql_num_rows($result) == 1)
  {
      $row = mysql_fetch_assoc($result);
      echo "true";
      exit();
  }
}
  else
  {
    echo "false";
    exit();
}
?>

Im the ajax scrip previously shown I'm "listening" for a echo of true if the information is correct and an echo of false if the information is not valid.
When I change the code in the test script to this:
if($_POST['username'] == 'Joao' && $_POST['password'] == "meu")
echo "true";
else echo "false";

it works perfectly, because of this I have in mind that maybe there is an error with either ajax calling the php file or something to do with php querying the database, and I can't tell because I feel powerless testing this.
I would appreciate if anyone could give me a help to figure out if it's the connection to the database or something to due with ajax or php.
Thank you
EDIT: This is the content of the connection file
<?php
$host = "localhost";
$username = "root";
$password = "";
$db = "forum";
mysql_connect($host,$username,$password) or die(mysql_error());
mysql_select_db($db);
 ?>

I've now changed all the deprecated mysql functions to mysqli as suggested:

<?php
session_start();
include_once("config.php")
if(isset($_POST['username']) && isset($_POST['password']))
{

$status = "";
$username = $_POST['username'];
$password = $_POST['password'];
  if($bd = mysqli_connect('localhost','root','','forum'))
  {
     if($command = mysqli_prepare($bd,"SELECT *  FROM users WHERE Username = ? AND password = ? "))
     {
       mysqli_stmt_bind_param($command,"ss",$username,$password);
       mysqli_stmt_execute($command);
       mysqli_stmt_bind_result($command,$testUser,$testPass);
       mysqli_stmt_fetch($command);
       if($username == $testUser && $password == $testPass)
       $status = "true";
       else $status = "false";
       mysqli_stmt_close($command);
     }
    mysqli_close($bd);

  }

}
else $status = "false";

echo $status;
exit();

But I still get the same result
Comment: A lot of the mysql methods are deprecated and you should either look into mysqli or PDO for database access.
Comment: Ps, don't be afraid to read the [manual](http://php.net/docs.php). It's confusing at first but it gets easier!
Comment: @Terminus after hours upon hours of youtube videos and checking all of your answers I finally got it to work. I will post my answer it may help other fellow coders in the same situation
Comment: @NigelRen could that be the cause of the issue I'm facing?
Comment: @NigelRen the `mysql_` methods* Also, all of them are deprecated and removed entirely from php7. @Newbies, what version of php are you using?
Comment: @Terminus I'm currently using php version 7.1.1, and I will try to change the commands to mysqli
Comment: @KingOFNewbies Glad to hear! That should solve your problem. While your application is in development  (ie, not able to be visited by anyone but you) you should enable [error reporting](https://stackoverflow.com/questions/1053424/how-do-i-get-php-errors-to-display). You may want to make a `config.php` file and include that file everywhere. Within the config file, you can `include_once 'connect.php';` and the code from the answer I linked. It'll keep your code clean and make it easier to read and change later. Good luck!
Comment: @Terminus thank you for all the help, I'm changed the entire code to mysqli but I still get the same results :\ could you please check my edit on the post?
Comment: Check your php my giving dummy data in username &password variable. Are they echo correctly.
Comment: I see your edit, looks good to me... could you try turning error reporting as that other link shows?
Answer: Well after many hours of research and reading through documents and all of that, and with the precious help of your questions I got to this code that actually works.
I've changed the ajax call to:

which, in my opinion, is far more readable than what I had and I think it's far more easier to understand as well.
After I understood how the ajax call actually works I went to change the php file that fetches data from the database and actually tests it to this:
<?php
if(isset($_POST['username']) && isset($_POST['password']))
{
$username = $_POST['username'];
$password = $_POST['password'];
if($username == "" || $password == "")
{
  //server response if the info or the test wasnt valid
  echo "notok";
  exit();
}
}
else
{
  echo "notok";
  exit();
}
if($bd = mysqli_connect("localhost", "root", "", "forum"))
{
  if($stmt = mysqli_prepare($bd,
  "SELECT User_ID, username, password, email from users WHERE Username = '".$username."'")) {
    mysqli_stmt_execute($stmt);
    mysqli_stmt_bind_result($stmt, $idUser, $name, $pass, $email);
    mysqli_stmt_fetch($stmt);
    if($name == $username && $password == $pass) echo "ok";
    else echo "notok";
    mysqli_stmt_close($stmt);
  }
  mysqli_close($bd);
  }
 ?>

this actually produces the result I was after.
I only have 3 questions/problems atm.
The first is that in the jquery function that calls the ajax I think this is the best place to test if the username and the password fields are empty. I've done so by adding this lines of code:
   if(password == "" || username ||)
   {
     alert("please fill out the information required for the login");
     return;
   }

but after adding that code the ajax call no longer works...
The second thing is that I've found something to do with form serialization for the ajax calls that I think is far more proficient than getting the values by element ID, I havent got this to work tho.
Comment: i have edited my answer check it . Hope it will clarify you more.
Answer: Your tons of code could be simplified by using jquery ajax call. For example:
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});

For details refer jquery ajax manual it's very simple.
In the php script:

Please use PDO in php for code security.
What is the need for mysql_fetch_assoc () when you don't want to see any data.
Besides, selecting rows only to count them simply makes no sense. A count(*) query have to be run instead, with only one row returned.
the if statement is returning true and what if it is false. So a else statement is also required. Your else is returning false only when username is not set.
Also session_start() has no use in your script.

Hope it helps you understand.
Update:
Problem1: How to validate the form?
Solution: See this example:
    $(document).ready(function(){
     $('#form_id').on('submit',function(e){
        var username = $('#username').val();
        var password = $('#password').val();

       if(username == '' || password == '')
      {
      alert('required fields!!');
      e.preventDefault(); //stop submitting the form.
      }else{

     //here your ajax call

     }
   });

});

Problem2: How to use serialize in form submit?
Solution: in jquery do it like this
   $('#form').serialize(); //use in your ajax call

Comment: I'm now trying to use that ajax post and I've taken out the fetch and used count (*) instead.
Comment: after you're answer and searching I finally got something working with your ajax example, check my answer and please tell me if there's something wrong or I can change


How to hook drupal commerce line item create

Question: I want to process something when a new commerce line item create, is there any hook can do this?
Or is there another methods can do this?
Thanks at first!
Answer: Yes, you can use

hook_entity_insert()

Act on entities when inserted.

hook_entity_presave()

Act on an entity before it is about to be created or updated.
Comment: Thank you also, though I don't test, but I think this hook should also can fix my problem. But the hook_commerce_line_item_insert will be more suitable to me this time.
Answer: Look at this (hook_hook_info()) hook implementation in commerce_line_item.module, it exposes commerce_line_item_insert which gives you a chance to process some operations on insert operation..
You can use it like this:
function MYMODULE_commerce_line_item_insert($line_tem)
{
  // dpm($line_item);
}


SQL Azure server in different region to web server

Question: I've just taken over a web project hosted on Windows Azure.
We've been having performance problems, and I noticed today that our SQL Azure server is in the West Europe region, while the instances hosting our site are in the North Europe region.

How big a problem is this?
Assuming it's a problem (and I assume it is at least a problem from a bandwidth billing point of view!) how do I fix it?

Is there an easier way to migrate than purchasing a second SQL Azure server in the correct region, taking the site offline, exporting from the current server, importing to the new server, modifying the site config so it points at the new server? If it can be done without downtime, that would make me very happy.
Answer: Q: How big a problem is this?
A: It's a potentially significant problem, due to:

Latency - You are looking at double-digit millisecond ping times between your web server and its backend database. This is silly and can only make your site less responsive than it should be.
Cost - Data transfer between subregions is billable, whereas data transfer within a subregion is free.

Q: How do I fix it with minimal downtime?
A: It is difficult for us to make a specific recommendation without knowing anything about the size or complexity of your database. Microsoft offers many options for moving data from one SQL server to another:

Copying entire databases
Copying data only
SQL Azure Data Sync Service

Generally speaking, if you have enough data that a simple backup and restore won't be quick enough to satisfy your requirement to minimize downtime, Data Sync Service is probably your best bet.
Answer: The ideal case is to have your database in the same data center as your compute instances, as @Miles mentioned. I wanted to address the topic of "buying" another database server.
When you configure a SQL Azure server, there's no cost for the server itself, only for the database. And that database cost is amortized daily, based on the database size for each day.
For a migration from one data center to another, let's just say you were able to successfully back up your database and store the backup in a blob. You could then restore this database to your new server. Once you know your two databases are in sync (maybe by setting up sync service), you can then modify your app's connection string to point to the newly-created database. Assuming your database connection is stored in your app's web config, you would likely need to deploy a new version of your app. You can deploy to staging, making sure everything works right, and then do a VIP swap to roll out your new app to production.
Once you migrate to your new database and ensure all the data is up-to-date, you can safely delete the database in the original data center. Assuming this all took place in, say, 3 days, you'd only incur double-database cost for those 3 days.


Como evitar que a borda afete elementos filhos

Question: como faco para adicionar borda a uma img de modo correto pois estou adicionando a borda na img e a mesma parece ficar maior que as outras.
estou adicionando por click usando o jquery quando clico na img marco ela com uma borda verde de 2px como faco para isso não acontecer adicionar a borda e a img não aumentar?

$('input[type=checkbox]').on('change', function () {
    var total = $('input[type=checkbox]:checked').length;
    $("#count").text("Fotos selecionadas: " + total);
    $(this).closest('.hovereffect').toggleClass('clic');
});
.hovereffect {
    width:100%;
    height:100%;
    float:left;
    overflow:hidden;
    position:relative;
    margin-bottom: 25px;
    text-align:center;
    cursor:default;
    box-shadow: 0px 0px 5px 1px rgba(0,0,0,.2);
}

.hovereffect .overlay {
    width:100%;
    height:100%;
    position:absolute;
    overflow:hidden;
    top:0;
    padding: 15px;
    left:0;
    opacity:0;
    background-color:rgba(0,0,0,0.5);
    -webkit-transition:all .4s ease-in-out;
    transition:all .4s ease-in-out
}

.hovereffect img {
    display:block;
    position:relative;
    -webkit-transition:all .4s linear;
    transition:all .4s linear;
}

.hovereffect h2 {
    /*text-transform:uppercase;*/
    color:#fff;
    text-align:center;
    position:relative;
    font-size:22px;
    /*background:rgba(0,0,0,0.6);*/
    -webkit-transform:translatey(-100px);
    -ms-transform:translatey(-100px);
    transform:translatey(-100px);
    -webkit-transition:all .2s ease-in-out;
    transition:all .2s ease-in-out;
    padding:10px;
}

.hovereffect a.info {
    text-decoration:none;
    display:inline-block;
    text-transform:uppercase;
    color:#fff;
    /*border:1px solid #fff;*/
    background-color:transparent;
    opacity:0;
    filter:alpha(opacity=0);
    -webkit-transition:all .2s ease-in-out;
    transition:all .2s ease-in-out;
    margin:0 0 0;
    padding:7px 14px;
}

.hovereffect a.info:hover {
/*box-shadow:0 0 5px #fff;*/
}

.hovereffect:hover img {
    -ms-transform:scale(1.2);
    -webkit-transform:scale(1.2);
    transform:scale(1.2);
}

.hovereffect:hover .overlay {
    opacity:1;
    filter:alpha(opacity=100);
}

.hovereffect:hover h2,.hovereffect:hover a.info {
    opacity:1;
    filter:alpha(opacity=100);
    -ms-transform:translatey(0);
    -webkit-transform:translatey(0);
    transform:translatey(0);
}

.hovereffect:hover a.info {
    -webkit-transition-delay:.2s;
    transition-delay:.2s;
}

.col-lg-3{
    width: 30%;
}

.bloco{
    background-color: rgba(0,0,0,0.67);
    width: 100%;
    height: 100%;
    opacity: 0;
    position: absolute;
    padding: 17px;
    top: 0;
    -webkit-transition: all .4s ease-out;
}

h2{
    font-family: 'Courgette', cursive;
}

.corr{
    background-color: #2ecc71;
    width: 40px;
    height: 40px;
    border-radius: 30px;
    position: absolute;
    padding: 10px;
    margin-top: -10px;
    /* margin: 0 auto; */
    left: 0;
    /* top: 50%; */
}

.btn-group, .btn-group-vertical{
    position: absolute;
    top: 50px;
    left: 50%;
    margin-left: -43px;
}

.clic{
    border: 3px solid #1abc9c;
}
#count{
    font-family: 'Courgette', cursive;
}
.sweet-alert{
    border-radius: 0px;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>

                                <input type="checkbox" name="ck[]">Selecionar

https://jsfiddle.net/tob0b5ak/3/
Comment: opa vo subi as img so 1 min
Comment: cara o codigo e isso so isso so o border o codigo ja esta na perg postei a img pra exemplificar
Comment: Você não colocou o seletor e nem o HTML, fica meio dificil deduzir. Mas ok, teste as respostas abaixo, se nada der certo poste o html e CSS de maneira que possamos reproduzir o problema, conforme dita as boas praticas de se criar uma pergunta: http://pt.stackoverflow.com/help/mcve - Por favor entenda como uma critica construtiva ;)
Comment: nossa e vdd perai so coloquei uma coisa vo arruma mals
Comment: arrumei minha pergunta
Comment: sim ele se repete para cada img que tiver no banco
Comment: vo faze aqui  daqui a pouco atualizo
Comment: atualizei a resposta com o link do jsfiddle
Comment: tipo essa descida da img quando seleciono e normal isso?
Comment: intendi obg pela resposta
Comment: nao funciono tipo quando vc clica na img parece que ela da um padding de 3px na img
Answer: Use box-sizing com a propriedade border-box
Assim a borda ficará pra dentro e não pra fora.

div {
        box-sizing: border-box;
        -moz-box-sizing: border-box;
        -webkit-box-sizing: border-box;
        width: 100px;
        height: 100px;
        border: 20px solid #f00;
        background: #00f;
        margin: 10px;
    }

div + div {
border: 10px solid red;
}

Olá

Olá

Answer: Isso ocorre porque a borda é adicionada para fora, por padrão.
Para resolver, defina o atributo box-sizing
Isso fará com que a borda fique para dentro do elemento.

.out, .in {

    width: 200px;
    height: 200px;
    border: 10px solid #ff0000;
    margin: 0px;
    padding: 0px;
}
.in {
    box-sizing: border-box;
    -moz-box-sizing: border-box;
    -webkit-box-sizing: border-box;
}

border in

border out

Comment: +1. Mas [não é mais preciso usar prefixos](http://caniuse.com/#feat=css3-boxsizing) (a menos que esteja suportando algum IE < 8).
Comment: @renan usuários de android 2.3 e 3... iOS e outros mobiles não precisam. `-moz-box-sizing` não vi nenhum caso de necessidade. Ainda existem muitos usuários de Android2.3 e 3 ;)
Answer: O efeito é exatamente este mesmo, tanto com box-sizing: border-box; ou não, pois não é a imagem que recebeu a borda e sim um elemento parent e isto afeta a imagem.
A solução é não usar borda, talvez usar box-shadow resolva (no caso a imagem ficou por cima no teste, vou atualizar a resposta depois e colocar um exemplo com box-shadow) ou então você pode criar um elemento a mais colocar position:absolute nele também, remove isto:
E depois adicione isto:
.border-overlay {
    position: absolute;
    z-index: 9999;
    border: 3px solid #1abc9c;
    opacity: 0;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    transition: opacity .4s ease-out;
}
.clic .border-overlay {
  opacity: 1;
  display: block;
}

E o html deve ficar assim:

                                <input type="checkbox" name="ck[]">Selecionar

NOTA: troque todos -webkit-transition: por transition: apenas, pois assim irá funcionar em navegadores como Firefox (se quiser compatibilidade para navegadores antigos mantenha os dois -webkit-transition e transition)
Comment: Eita um downvote injusto, por favor justifique... Se não notou sr. Downvoter a solução com `box-sizing` não funciona porque o problema é um elemento interno, seu voto negativo demonstra que não entendeu o problema do autor da pergunta... isso demostra que é apenas um ignorante.


Center pivot Instantied GameObject

Question: I have a GameObject and his child. When we view the parent, the pivot is the center between the gameobject and his child. When I cloned the gameobject, the child was destroyed but the pivot is still in same place and not replaced to the cloned active gameobject. How can I fix that ? Thanks
Answer: Unity generally doesn't do the kind of "pivot child averaging" you're describing here. Is this object imported from a 3D program? If so, it's much more likely the pivot is just not correct in the model. If it's not a model and just a primitive, post a screenshot!
Comment: Yes the object is imported from a 3D program (obj) but his child is a button that is a object from Unity. When I cloned and scaled both of them, the pivot is the average of both of them. And then When I destroyed the child and kept the object (parent), the pivot stay in same position and not around the object.

Center pivot Instantied GameObject