Como transformar Y-m-d para Unix timestamp à meia noite em PHP?

Question: Boa tarde,
Estou precisando converter os dados de um formulário que vem no formato ex: 2018-02-13 para UNIX à meia-noite.
Se eu converto normalmente usando o strtotime ele vem certo mas com o horário as 6:00AM.
Alguem pode dar uma luz?
Obrigado =)
Comment: $unixMeiaNoite = strtotime($dataFormulario." 00:00:00");
Comment: Esse meia-noite é confuso. Meia-noite do dia `2018-02-13` é o próximo segundo  depois de `2018-02-13 23:59:59`, ou seja `2018-02-14 00:00:00`
Answer: Resolvido,
$check_in = strtotime('-6 hour' , strtotime($arrival));


Erro em posicionamento de divs

Question: Tenho uma página, que possui três divs. A primeira contém um banner gerenciável a segunda tem uma imagem de fundo e a terceira é uma cor chapada.
Como mostra a imagem abaixo:

Minha dúvida é: o banner um, tem tipo um corte e o dois também, no caso irei usar um JPG. porém, como as divs são quadrada por padrão, terei de usar position e z-index.
Meu código atual está assim http://jsfiddle.net/felipestoker/87L7r2nx/
O que acontece, é que quando eu chego na div três, colocando position e z-index, só que não aparece.
O que está errado?
Comment: O código no JSFiddle tem muita coisa, está difícil identificar o elemento `1`, `2` e `3` para ajudar a resolver o problema. Dá para referenciar quem é quem?
Comment: atualizei agora, veja se está melhor
Answer: Analise
Já estive a olhar para o código no teu JSFiddle. O problema parece ser a organização do elementos para que a stack funcione da maneira que pretendes.
O que sugiro é utilizares uma estrutura simples e após isso ires formatando consoante a necessidade:

No elemento #wrapper dás um position:relative; e aos elementos filhos um position:absolute;. Desta forma podes manipular a posição dos três elementos para chegares à composição pretendida.
De igual forma também consegues ajustar a posição do elemento #wrapper e se necessário dar-lhe posição absoluta e chegar o mesmo para baixo.
Da forma que tens atualmente, os elementos posicionados de forma absoluta estão relativos à tab body. Como tens dois elementos no topo (topoBarra e topoMenu) já a ocuparem determinado espaço, as coordenadas de posicionamento absoluto começam após o espaço ocupado pelos referidos elementos, isto porque tens o posicionamento absoluto a ser dados a elementos filhos que por si são elementos filhos da tag body. (é confuso, eu sei...).
Solução
Exemplo no JSFiddle
HTML

1

2

3

CSS
html, body{
    width:100%;
    height:100%;
    background-color:yellow;
}

/* Elemento chave para criar a área de manipulação */
#wrapper{
    position:relative;
    background-color:green;
}

/* definições comuns aos três elementos a manipular
 */
.indawo{
    position:absolute;
    background:none no-repeat scroll left top transparent;
    color:red;
    text-align:center;
    line-height:200px;
    font-weight:bold;
}

/* primeiro elemento posicionado absolutamente, com coordenada de topo
 * a 0 (zero) para ficar colado ao topo do elemento #wrapper
 */
.eyodwa{
    top:0px;
    background-image:url(https://i.stack.imgur.com/4WwA2.png);
    overflow: hidden;
    width:592px;
    height:242px;
}

/* segundo elemento posicionado absolutamente, com coordenada de topo
 * para o "chegar para baixo" o suficiente para alinhar as imagens
 */
.ezimbili{
    top:105px;
    background-image:url(https://i.stack.imgur.com/sFCc9.png);
    overflow: hidden;
    width:592px;
    height:213px;
}

/* terceiro elemento posicionado absolutamente, com coordenada de topo
 * para o "chegar para baixo" o suficiente para ter as imagens do primeiro
 * e segundo elemento visiveis por completo.
 */
.amathathu{
    top:318px;
    background-color:blue;
    overflow: hidden;
    width:592px;
    height:200px;
}

Pré-visualização
Na pré-visualização estou a selecionar os elementos usando o inspetor do navegador para os destacar. Podes ver que os dois elementos onde ficam as duas imagens estão sobrepostos. O terceiro elemento fica por baixo deles.

Cada frame dura 2 segundos.
Comment: Entendi, eu estava tendo problemas com o posicionamento, como eu havia suspeitado. No caso, todos irão se basear pelo `#wrapper`, e o que devo mudar mesmo é o `top`.

Erro em posicionamento de divs


how to solve this trigonometric equation involving one parameter?

Question: I was trying to solve this question:

Let $x$ be defined from $0$ to $\pi$, in this equation $\sin x$ must be equal to "$2-k$". It has at least one solution if $k$ is in the range

(1) from 1 to 2 (both included),
(2) from 2 (included) to positive infinity,
(3) from 1 to 3 (both included),
(4) from negative infinity to 1 (included).

Here's my attempt to solve it:
Since x must be in the interval from 0 to pi,
if I plug 3 in the equation I'd get a negative value, so 2 and 3 are both incorrect.
the other options could be both correct,
but if I plug 0, I get "2-0 = 2", 2 it's not in the interval, and if I plug a negative value I got a value that is greater than 2, so it is still not correct.
The first option is correct for each value inside the interval. To prove that, I plug 1.5 (half) and it is acceptable (according to the equation), therefore my solution is (1).

is it correct?
Let me know, and if you know a different method (not trial and error) let me know.
Answer: If $x \in [0, \pi],$ then $0 \le \sin x \le 1.$
Hence:
$$0 \le 2-k \le 1 \iff -2 \le -k \le -1 \iff  1 \le k \le 2.$$


How precise and how accurate is perfect/absolute pitch?

Question: For those that need a reminder of the  difference between accuracy and precision

I don't have perfect pitch. For those who do, how accurately and precisely can you recognise, say 440Hz for an A.
(1) You can hear a note, and say that it is nearer to an A than to some other nearby note
(2) You could tune a piano to perfect concert pitch without any reference to any outside measure of frequency whatsoever.
(3) You can distinguish perfectly between different keyboard temperaments and say from hearing a single scale, the temperament the instrument is tuned in.
(4) Someone could play you a pure frequency on an oscillator, tell you the precise frequency in Hz and you would be able to identify and reproduce that precise frequency to within 1Hz for the rest of your life.

I realise that abilities differ but I'm trying to get a general understanding of what is possible and how finely the ability can be honed.
Comment: I daresay that like any capability or ability that some may possess, its depth and perfection will vary between individuals. As in, there cannot be anything but a sliding scale (no pun intended), so if one person actually has *perfect* absolute pitch, and another has it to some degree, where does that leave us?
Comment: This smacks of a poll, but I do feel like entertaining you with my entry.
Answer: In terms of my level of absolute pitch, I'd say I definitely fit #1, I can kinda fit #2, I only vaguely sorta fit #3, and I cannot pull off #4 at all.
I can definitely hear notes and give you their closest note in the usual 12-note scale (with more effort, also their octave, although orchestral music can make me skew the loudest octave wrong) assuming A440 12TET. If they sound like quarter tones, I'll give you their two closest notes instead and declare the actual note a quarter tone or something close enough to it. If they distinctly sound out of tune, I'll say whether they're sharp or flat.
I'm not sure whether I have the manual dexterity to pull off a satisfactory piano tuning, and I may end up tuning to A444 or A438 instead, but I can definitely tune your ukulele to standard tuning with no auditory references. I generally prioritize making open strings sound good when played with each other (e.g. the C and G open strings sound like a great perfect 5th together) over tuning to exactly A440.
Termperament-wise, all I can say is if you're reasonably within equal temperament or you're clearly deviating (e.g. just intonation, out-of-tune singer, meantone temperaments). I can't say which precise temperament system you're using if it's not equal temperament. The main way I detect this is the presence of consistent out-of-tune notes and a lack of consistency in how notes are (or aren't) out of tune.
...So I can't tell you the precise Hz of heard frequencies and need to deduce Hz differences between similar notes by checking for beating like everyone else, including people without absolute pitch. And then I'll probably be unable to distinguish between A432 and A430 the next day despite (re-)learning A432 yesterday. Sorry.
Answer: (1) You can hear a note, and say that it is nearer to an A than to some other nearby note
Yes.
(2) You could tune a piano to perfect concert pitch without any reference to any outside measure of frequency whatsoever.
Yes in principle, but just so you know, that would be a lousy way to tune a piano.
The proper way to tune a piano is to start with one note, then one octave, then go up and down by octaves, then try various intervals and other tricks and adjust all around until it sounds good.
(3) You can distinguish perfectly between different keyboard temperaments and say from hearing a single scale, the temperament the instrument is tuned in.
Not by perfect pitch, but possibly via relative pitch.
(4) Someone could play you a pure frequency on an oscillator, tell you the precise frequency in Hz and you would be able to identify and reproduce that precise frequency to within 1Hz for the rest of your life.
1 Hz is a very big interval in low octaves, and an almost insignificant interval in high octaves.
You should instead ask by how many cents one's perfect pitch is precise. (A cent is a hundredth of a semitone).
I'd say that an average PP can be as precise as 20 cent, and a really good one, 10 cent or so.
Also keep in mind and with advancement of age, the sense of perfect pitch tend to slide down. That is, the same note that sounded like a concert C in your head when you're young, after middle age will start to sound like a B, then a Bb, then an A... (the latter is the case of a friend of mine in his 80s).


Sending system e-mails do not work in spite system says it sends e-mail

Question: So, my Drupal 7 does not dispatch those messages (notify user on registration and such) in spite the system says it sended e-mail. Other scripts (like send the web page by email) work well, though!
I am on dedicated unmanaged (i manage it ;) ) Debian server with LAMP, and for e-mail I installed Postfix.
If someone got clues i would be grateful!
Comment: What are the postfix logs telling you. Are they handling the emails?
Answer: If the system log reports it is sent, mostly likely it was sent. Perhaps those mail went to SPAM box? If that is the case, check if you have Reverse DNS set up for your domain.
Besides, you can utilize 3rd party email service (such as Gmail) as your Drupal mail system.
Check out SMTP module.
Comment: This may break the Gmail ToS.  Be aware of the daily send/receive caps as well.  This could be an easy setup to hit with a DoS.


How do I characterise a distribution, when each measurement comes paired with an erroneous measurement whose identity is ambiguous?

Question: I have a set of measurements $x_1 ... x_n$, which I believe are normally distributed, $x\sim N(\mu, \sigma^2)$. I would like to estimate their mean and variance.
Here's the catch: Due to the nature of how the measurements were made, each measurement $x_i$ actually comes as a pair $(x_{i_{lower}}, x_{i_{higher}})$. One member of each of these pairs is the true measurement, the other is the true measurement +/- some error $E_i = x_{i_{higher}} - x_{i_{lower}}$. The identity of the members of the pairs is ambiguous (I don't know a priori which measurement is real and which contains the error).
The probability distribution of the size of the errors can obviously be empirically measured. Probably best not to assume the errors have any particular distribution if possible.
Is there a way I can get meaningful summary statistics from these data? Bonus points for a method of estimating the respective probabilities of $x_{i_{lower}}$ or $x_{i_{higher}}$ being the real measurement, for each $i$.
Answer: If the errors are independent of the $x_i$ and symmetric, so that errors of $y$ and $-y$ are equally likely, then:
Let $A$ be the average and let $D$ be the difference of the higher and lower observations. If the error is $Y$, then $D=|Y|$ and $$Var[Y]=E[Y^2]-E[Y]^2=E[D^2]-0.$$
Similarly, since $A=X+\frac12Y$,
\begin{align}
\mu &= E[A],\\
\sigma &= Var[A]-\frac14E[D^2].
\end{align}
Answer:
Probably best not to assume the errors have any particular
distribution if possible.

With no prior information about the distribution of $x$ or $E$ other than a belief that the $x$ are independent draws from a normal distribution with unknown parameters, the only criterion we can use to assess whether a candidate set of points, $\hat x$, is the "real measurement" is how well it fits a normal distribution.
A reasonable approach may be to find the $\hat x$ that minimizes the statistic of a goodness of fit test. This can be done by nested optimization. The inner optimization uses the Hungarian algorithm to find the $\hat x$ that minimizes the test statistic for a given $\mu$ and $\sigma$. The outer optimization uses a general-purpose optimizer to find the $\mu$ and $\sigma$ that minimize the test statistic returned by the inner optimizer.

Simulation
The following R code demonstrates this approach with simulated data and the Cramér–von Mises test statistic. The process is repeated 15 times.
A function to perform the simulations:
library(RcppHungarian)

f0 <- function(...) {
  (seed <- sample(.Machine$integer.max, 1))
  set.seed(seed)

  # simulate data
  n <- 500
  # Sample E from a distribution with an erratic PDF between -1 and 1
  f <- splinefun(seq(-1, 1, length.out = 20), runif(20) + (1:20)/40)
  E <- runif(n*10, -1, 1)
  E <- E[f(E) > runif(length(E), 0, 2*max(E))][1:n]
  # the "real" data is in the first column, and the error-shifted data is in the
  # second
  x <- cbind(x <- rnorm(n), x + E)

  # get rough upper and lower bounds on the parameters of x
  i <- seq(1/n/2, 1 - 1/n/2, 1/n)
  xx <- sort(x)
  rsd <- range(TTR::runSD(c(x), n, 0)[n:length(xx)])
  lower <- c(mean(xx[1:n]), log(rsd[1]))
  upper <- c(mean(xx[(n + 1):(2*n)]), log(rsd[2]))

  # function to be optimized--uses the Hungarian algorithm to find the optimum
  # set of values that minimizes the Cramer-von Mises test statistic for a given
  # mean and standard deviation
  f <- function(params) {
    y <- pnorm(x, params[1], exp(params[2]))
    HungarianSolver(
      pmin(
        outer(i, y[,1], "-")^2,
        outer(i, y[,2], "-")^2
      )
    )$cost
  }

  # function to perform the Gaussian parameter optimization and return the
  # candidate set that globally minimizes the Cramer-von Mises test statistic
  normOptim <- function(x) {
    # method "L-BFGS-B" with bounds does well at finding a global minimum in the
    # presence of multiple local minima
    params <- optim(c(mean(x), log(sd(x))), f, lower = lower, upper = upper,
                    method = "L-BFGS-B")$par
    # retrieve the candidate set
    y <- pnorm(x, params[1], exp(params[2]))
    A <- A1 <- outer(i, y[,1], "-")^2
    A2 <- outer(i, y[,2], "-")^2
    bln <- A1 < A2
    A[bln] <- A1[bln]
    A[!bln] <- A2[!bln]
    pairs <- HungarianSolver(A)$pairs
    out <- integer(n)
    out[pairs[,2]] <- 2L - bln[pairs]
    out
  }

  # for each row, identify the column of x that contains x-hat
  idx <- normOptim(x)
  xhat <- x[cbind(1:n, idx)]
  y <- pnorm(sort(x[,1]), mean(x[,1]), sd(x[,1]))
  yhat <- pnorm(sort(xhat), mean(xhat), sd(xhat))

  list(
    seed = seed,
    p = mean(idx == 1L),
    # Cramer-von Mises test statistic for x and x-hat
    T1 = sum((i - y)^2) + 1/12/n,
    T2 = sum((i - yhat)^2) + 1/12/n
  )
}

Perform the simulation 15 times in parallel and summarize the results.
library(parallel)

cl <- makeCluster(15, type = "PSOCK")
clusterEvalQ(cl, library(RcppHungarian))
data.table::rbindlist(parLapply(cl, 1:15, f0))

#>          seed     p         T1           T2
#> 1   382014738 0.502 0.05428307 0.0006133394
#> 2   908878520 0.506 0.05151929 0.0008763339
#> 3  1583518653 0.482 0.11607714 0.0007895081
#> 4  2066117082 0.472 0.07424786 0.0007267635
#> 5  1626352239 0.500 0.03307783 0.0005275291
#> 6  2119421263 0.486 0.02932221 0.0005932570
#> 7   626401422 0.496 0.04912518 0.0010036447
#> 8    66718651 0.492 0.10045322 0.0006823435
#> 9  1107913526 0.502 0.02884935 0.0007366666
#> 10 1990492963 0.514 0.02569923 0.0010301989
#> 11   50074952 0.534 0.02930599 0.0006010961
#> 12  165422105 0.550 0.02351056 0.0008490050
#> 13  621963233 0.478 0.08712079 0.0011667846
#> 14  129867844 0.484 0.07650852 0.0008400564
#> 15  843946982 0.520 0.03574757 0.0012544344

Conclusion
In each of the 15 repetitions, $\hat x$ results in a much smaller test statistic (column T2) than the test statistic computed on $x$ (column T1). However, notice from column p that, in aggregate, $\hat x_i$ is no more likely to be $x_i$ than $x_i + E_i$. With $2^n$ possible sets to form $\hat x$, it is unsurprising that a large portion the values in $\hat x$ are from $x_i + E_i$.
There is insufficient information about the distribution of $x$ or $E$ in order to reliably distinguish $x_i$ from $x_i + E_i$.


Is there a way to run top as a daemon to gather historical process data?

Question: I am aware that I can write a cron job that will run top in batch mode and write the output to a file but I am looking for something more elegant than that. Also I am aware of sysstat (sar) but I am looking for more detailed process data.
Does something like this exist?
Comment: What about running periodically `ps`? This command seems to be much more suitable for what you plan.
Comment: Not sure what you mean - can you expand a little more
Comment: If a snapshot of running processes once in a while is what you're looking for, you could run `ps -ef >> logfile` from cron.
Answer: Look into atop, which runs a daemon and keeps historical data for every process. You made need to do some tweaking to keep an archive, but that's my other tool of choice besides sar.


Is there a way to define Variadic template macro?

Question: Is there a way to define variadic template macro just like variadic macro?
For example, if define variadic macro like:
#define PRINT_STRING(fmtId, ...) { \
    CString fmt; \
    fmt.FormatString(fmt, ##__VA_ARGS__); \
    cout << fmt << endl; }

Could we define something like:
#define PARSE_FUNCTION(functionName, typename...) \
    std::function<int(typename...)> m_##functionName(){ \
        return (std::function<int(typename...)>) functionName; }

Comment: Macros and templates aren't the same thing. This looks like an XY problem. Explain what it is that you're trying to *achieve*, rather than how you're trying to do it.
Comment: What? can you explain what you want in more detail, i didn't get it...
Comment: Thanks, yes, I think it is a stupid question too :)
Comment: @Nicol: I can't understand your comment! Why should someone not write a macro which holds an template? It is not the question that macros are the bad side of c/c++, but there are still reasons to use them. Indeed: I could also not understand the code sample :-)
Comment: @Klaus: It's not whether someone can put a template inside a macro. It's that there's no such thing as a "macro template". They do different stuff.
Answer: __VA_ARGS__ can be used multiple times, so you could write:
#define PARSE_FUNCTION(functionName, ...) \
    std::function<int(__VA_ARGS__)> m_##functionName() { \
        return std::function<int(__VA_ARGS__)>(functionName); \
    }

What is happening is just simple text substitution, whether the arguments is for a template or not won't be checked by the preprocessor.
Actually any function objects can be implicitly converted to a std::function, so the cast can be omitted. Furthermore, if functionName refers to function pointers, the exact type can be easily inferred, that you don't need the variadic macro at all:
#define PARSE_FUNCTION(functionName) \
    auto m_##functionName() \
        -> std::function<std::remove_pointer<decltype(functionName)>::type> \
    { \
        return functionName; \
    }


DAO is responsible only for CRUD operations?

Question: Is DAO class responsible for handling all following methods? Or it's better to exclude some methods into service layer?
I found this interface here . And I think about repeating this interface in my code..
public interface GeneralDAO {

        public <T> T find(Class<T> type, Serializable id);

        public <T> T[] find(Class<T> type, Serializable... ids);

        public <T> T getReference(Class<T> type, Serializable id);

        public <T> T[] getReferences(Class<T> type, Serializable... ids);

        public boolean save(Object entity);

        public boolean[] save(Object... entities);

        public boolean remove(Object entity);

        public void remove(Object... entities);

        public boolean removeById(Class<?> type, Serializable id);

        public void removeByIds(Class<?> type, Serializable... ids);

        public <T> List<T> findAll(Class<T> type);

        public List search(ISearch search);

        public Object searchUnique(ISearch search);

        public int count(ISearch search);

        public SearchResult searchAndCount(ISearch search);

        public boolean isAttached(Object entity);

        public void refresh(Object... entities);

        public void flush();

        public Filter getFilterFromExample(Object example);

        public Filter getFilterFromExample(Object example, ExampleOptions options);
}

Answer: All of the methods listed on your GeneralDao are compatible with the DAO pattern.
Also, its possible to have methods specific to the entity your working with, as long as they relate to persisting/retrieving from storage. . For example a CustomerDao: besides having the methods on your GeneralDao might have methods to find by criteria relating to a customer. . . If you can present this in a specific way that leads to more descriptive-code, then so much the better. There's nothing wrong with specifics and focusing in on an entity.
(CustomerDao, OrderDao, ProductDao, . . PilotDao, BookDao, etc. All of these could have unique methods relating to storage and retrieval of that type of entity)
You'll know that you're still honoring the DAO pattern if you could swap the underlying persistent store for something else, and the DAO still makes sense.
Answer: DAOs (Data access objects as they're called) are primarily meant to provide an abstraction to the underlying data store and isolate the other modules from worries of underlying DBMS and schema. As long as you're not using DAOs to keep business logic or anything else that's not relevant to data access, I think you're good.


Select com quantidade indefinidos de condições

Question: É o seguinte, eu tenho um campo de pesquisa, e quero pesquisar em locais distintos do que está cadastrados, tipo assim: tenis nike shox preto.
Eu coloco na pesquisa: tenis preto. Se eu usar um descrição like '%tenis preto%' ele não me retornara nada.
Eu teria que colocar descrição like '%tenis%' or descricao like '%preto%'.
Até ai tudo bem, eu coloco no SQL lá duas condições, porem e se ele quiser pesquisar com 3 ou mais palavras, vai variar a quantidade de where que eu preciso usar, tem como fazer isso?
Estou usando:

PHP
PostgreSQL
Comment: Algumas soluções apresentadas utilizam queries dinâmicas. Sugiro que quem for utiliza-las pelo menos estude os prós e contras de utilizar esse tipo de técnica
Comment: Sugeriria inclusive ler o conceito de query dinâmica, pois olhando as respostas dadas, nenhuma delas aplica esse conceito quanto ao ponto de vista do _engine_ de SQL.
Answer: Não é necessário montar strings, o que aliás é má prática. Basta passar os parâmetros na forma de array com qualquer das duas sintaxes:
select *
from t
where descricao ilike any ('{"%tenis%", "%nike%", "%shox%", "%preto%"}')

select *
from t
where descricao ilike any (array['%tenis%', '%nike%', '%shox%', '%preto%'])

ilike é insensível à caixa. A lógica acima é de or. Se for necessário fazer and troca-se o any por all
Comment: O papo de má prática eu estou desconsiderando, pq não tem o mínimo embasamento, mas de qq forma recebeu meu +1 por ser uma solução técnica adequada usando um recurso do SGBD.
Answer: Uma possibilidade com um resultado mais completo é usar o PHP para dividir a sua pesquisa em palavras separadas, e gerar a clausula WHERE pra você:
<?php

   $pesquisa = 'carro verde amassado ';

   // Aqui você pode juntar vários campos no concat.
   $campo = 'CONCAT( title, " ", description, " ", author)';
   // Ou usar um só, mas nesse caso talvez compense um LIKE tradicional
   // $campo = 'title';

   $palavras = explode( ' ', $pesquisa ); // dividindo as palavras pelo espaço
   $palavras = $array_filter($palavras); // eliminando ítens vazios

   $where = '';
   $cola = 'WHERE ';

   foreach ($palavras as $palavra) {
      $palavra = trim($palavra); //Removendo espaços em branco
      $palavra = mysql_real_escape_string($palavra); // Aqui você sanitiza de acordo com o DB
      $where .= $cola.campo.' LIKE "%'.$palavra.'%" ';
      $cola = 'AND ';
   }

   echo htmlentities( $where );
?>

E o resultado será:
WHERE
   CONCAT( title, " ", description, " ", author) LIKE "%carro%" AND
   CONCAT( title, " ", description, " ", author) LIKE "%verde%" AND
   CONCAT( title, " ", description, " ", author) LIKE "%amassado%"

(quebras de linha adicionadas para facilitar a leitura)
Desta forma a pesquisa encontrará todos esses resultados:
O carro amassado era verde
A carroceria foi atingida por abacates verdes amassados
Verde e amassado carro

Note que apesar de algumas linhas não terem resultados exatos, é melhor ter coisas a mais do que o usuário não encontrar o que precisa. Tenha em mente, no entanto, que o preço que se paga pela complexidade é uma pesquisa mais lenta. LIKE e índices não trabalham bem juntos.
Comment: Não tem como usar um ataque de injeção, sendo que já está sanitizado. Li o artigo, principalmente no parágrafo que inicia a questão das condições dinâmicas de pesquisa, e ele não se aplica em nada ao nosso caso, tem certeza que leu direito? Inclusive, pelo jeito você não entendeu que condição dinâmica não é nada disso que eu fiz na resposta. Quando a query chega no engine SQL, ela está montada já. Para o _engine_, é uma query igual qualquer outra. Sugeriria começar pelo básico, e depois tentar se aprofundar nestes conceitos.
Comment: Uma solução simples mas que infelizmente usa queries dinâmicas que não são recomendadas. Se for utilizar esta solução sugiro pelo menos sanitizar o input e se puder parametrizar a query (possivelmente usando Stored Procedure)
Comment: Tem todo proveito: Primeiro e mais importante barrar ataques de SQL Inject, segundo performance. Sugiro ler este artigo sobre como criar condições dinâmicas. http://www.sommarskog.se/dyn-search-2005.html#casestudy
Comment: Discordo, no artigo tem técnicas ensinando como montar queries e quais são os pró e contra dessa abordagem além de outras idéias que podem ser exploradas como queries dinâmicas parametrizáveis. Sempre que você montar queries você está correndo o risco de SQL inject, sanitizar não é 100% seguro, existem técnicas para burlar a sanitização como mandar os códigos dos caracteres e corrigindo você: as queries chegam montadas à engine porém um SP já está compilada. Queries dinâmicas não paramétricas precisam ser recompiladas e não fazem bom uso de cache e estatísticas. Leia +
Comment: Sanitização foi feita já, leia melhor a resposta `$palavra = mysql_real_escape_string($palavra);`. Stored procedure não tem o mínimo proveito num caso desses.
Answer: Depende da complexidade da funcionalidade que você quer implementar e do tamanho da sua aplicação. Para uma aplicação pequena e simples você pode fixar até três campos, exigir que pelo menos o primeiro esteja preenchido e fazer três likes sendo que os likes dos campos não preenchidos seriam algo como LIKE "%".
Agora se você precisa de mais complexidade e uma aplicação maior sugiro você implementar uma tabela de tags e uma tabela de relacionamento entre tags e registros que você quer retornar.
Ao fazer uma busca tipo google o array de strings é enviado para a função que vai procurar registros que estejam relacionados àquelas tags.
Com um pouco mais de complexidade você pode implementar ranks de tags; ignorar as tags com menor ranks caso elas façam com que não haja um retorno mínimo; ignorar flexões de género, número e verbais; automatizar a extração de tags dos registros; etc
Implementei algo assim uma vez mas para MS-SQL e .Net pois apesar do SGBD ter ferramentas nativas para esse tipo de SELECT a hospedagem não permitia ativa-las (a menos que o servidor fosse dedicado, o que era caro).
Answer: Amigo. Existe uma solução simples para seu problema.
Estou utilizando o MySql, mas é de fácil alteração para seu caso.
Primeiramente, defina as colunas na qual você quer buscar o valor, imaginando que seja mais de uma.(Funciona para 1 ou N colunas).
/* Colunas da Tabela */
$aColumns = array (
        'ID',
        'PRODUTO',
        'DESCRICAO'
);

Em seguida monte o WHERE:
/* Filtros.. */
$sWhere = "";
if ($_GET ['sSearch'] != "") {
    $sWhere = "WHERE (";
    for($i = 0; $i < count ( $aColumns ); $i ++) {
        $sWhere .= $aColumns [$i] . " LIKE '%" . strtoupper ( mysql_real_escape_string ( $_GET ['sSearch'] ) ) . "%' OR ";
    }
    $sWhere = substr_replace ( $sWhere, "", - 3 );
    $sWhere .= ')';
}

Porém continuará o problema em questão, para a busca, caso seja procurado: Tenis Preto, só irá retornar os valores que contenham o intervalo total.
Como solução, pode-se utilizar o IMPLODE e o EXPLODE:
$busca  = "Tenis Nike Preto"; //Set GET ou POST..
$busca_explode =  explode(' ', $busca); //Desmonta String..
print_r($busca_explode) ; // Visualização como fica..
$busca_total = implode('%', $busca_explode); // Tenis%Nike%Preto
echo '
'.$busca_total;

Basta passar este valor para o WHERE acima em vez de buscar direto pelo $_GET ['sSearch'].


Cello double stops fingered thirds?

Question: On violin there are (at least) two ways to play double stop octaves.
The 'regular' way:
using fingers 1+4 1+4 1+4 etc.
or 'fingered':
using fingers 1+3 2+4 1+3 2+4 etc.
I remember seeing somewhere something similar for the cello.
Fingered thirds.
I can't remember where, and I can't find anything on google. So was that my imagination?
or is 'fingered thirds' referring to playing thirds using fingers
3+1 4+1 3+1 4+2 etc. as in thumb position?
vs the 'regular' way, using fingers
4+1 4+1 4+1 4+1 etc.
Also if 'fingered thirds' isn't the right name, then what is it?
Comment: Unless you have extremely large hands, any fingering but **4+1** is impractical for thirds in neck positions; at least it's basically impossible for minor thirds. I do occasionally play major thirds with **3+1**, but only in the context of a larger strummed chord – I doubt this has any name cellists would be familiar with.
Comment: just curious what is the notation being used here? what does the 1+4 mean? is that a finger and string or a string and position marking?
Comment: I'm referring to the fingers here. so 1+4 would mean first finger and 4th finger. I edited the question to reflect that.
Comment: one more question, sorry, i am not sure if your question is not clear or if this is just that is just too different from guitar for me to get what you mean. What are you trying to play, two notes a 3rd apart from each other at the same time, a series of notes like c, e, then d, f, then e, g...going up the scale with jumps of thirds, or something else all together?
Comment: It's fine, I'll be able to clear up my question if things are unclear. When we say double stops on the violin and cello (guitar too I think) we mean playing two pitches on two different strings at once. So C+E, D+F, E+G etc. would be double stop thirds. Double stop octaves would be C+C, D+D, E+E etc. When you say, jumps of thirds it sounds like you are describing scales in thirds which is a different thing. The notes would be separate and would generally have different fingerings.
Comment: ok, that is what i thought. guitar is the same, but since each pair of adjacent strings are not tuned the same the fingering changes as you go from thick string to thin string. also wouldn't the fingering change depending on the key?
Comment: Oh, well yeah this fingering won't work on guitar. The fingerings mentioned there don't really change depending on the key. The spacing between the fingers are different but the same fingers are pretty much always used.
Answer: for octave doublestops
Obviously above 4th or 5th position you can do whatever's comfortable (or better, whatever pairing lets you get into and outof the double-stops to the remainder of the notes in the passage) .   In the lower positions, folks like me with big hands have no difficulty playing thumb + 3 or even a fully extended  1+4 .  Smaller hands probably require thumb+3 (and some stretching exercises :-) ) .
for thirds doublestops
lower positions:  1+3 followed by 2+4 or vice versa.  Upper positions:  same if you're comfortable, but preferable, usually is  thumb+2 followed by 1+3 .
That said, there's no reason not to use thumb+2; 1+3 in lower positions if you wish, especially if the passage moves, with double stops, into higher positions.

Cello double stops fingered thirds?


Show the following continuous function has a solution $f(c) = 0$

Question: Let $S = [0,1] \times [0,1]$, and let $f: S \rightarrow \mathbb{R}$ be continuous. Assume for each $a \in S$, there exists a $b \in S$ such that $|f(b)| \leq \frac{1}{2}|f(a)|$. Show that there exists a point $c \in S$ such that $f(c) = 0$.
My idea is to use the intermediate value theorem. So let $a \in S$. Then, there exists $b \in S$ such that $|f(b)| \leq \frac{1}{2}|f(a)|$.
If $f(a) = 0$ or $f(b) = 0$, then we're done. So assume $f(a) \neq 0$ and $f(b) \neq 0$.
Then, from $|f(b)| \leq \frac{1}{2}|f(a)|$, we have $-\frac{1}{2}|f(a)| \leq f(b) \leq \frac{1}{2}|f(a)|$.
But I don't see how I can apply IVT from here since we are not guaranteed that $\pm \frac{1}{2}|f(a)|$ is in the range of $f$. Perhaps $f$ maps $S$ to only positive reals.
Comment: Does this answer your question? [Let $f \in C [a,b]$ such that $\forall x\exists y$ such that $|f(y)| \leq \frac{1}{2}|f(x)|$. Prove that $\exists c\in [a,b]$ such that $f(c) = 0$.](https://math.stackexchange.com/questions/1643681/let-f-in-c-a-b-such-that-forall-x-exists-y-such-that-fy-leq-frac) – that is about a function on an (one dimensional) interval, but the proof is the same.
Comment: Note that you cannot use the intermediate value theorem here, because $f$ is defined on a subset of $\Bbb R^2$,
Comment: Also: https://math.stackexchange.com/q/3881742/42969, https://math.stackexchange.com/q/347911/42969.
Comment: Yeah I see my approach isn't very useful. But I planned on using the generalized intermediate value theorem involving connectedness
Answer: Hint
Consider $a_1\in S.$ (If $f(a_1)=0$ we are done. So assume $f(a_1)\ne 0.$) There exists $a_2\in S$ such that $|f(a_2)|\le \dfrac {|f(a_1)|}{2}.$ And there exists $a_3\in S$ such that $|f(a_3)|\le \dfrac {|f(a_2)|}{2}=\dfrac {|f(a_1)|}{2^2}.$
Use that $S$ is compact and $f$ is continuous.
Answer: Fix ANY $a_0\in S$.
If $f(a_0)=0$, you are done.
Assume $|f(a_0)|>0$. for $a_0\in S$, there exists $a_1\in S$ such that $|f(a_1)|\le \frac{1}{2}|a_0|$.
For $a_1\in S$, there exissts $a_2\in S$ such that $|f(a_2)|\le \frac{1}{2}|f(a_1)|\le \frac{1}{2^2}|f(a_0)$.
So, by induction, you construct a sequence $(a_n)_{n\ge 0}$ such that $|f(a_n)|\le\frac{1}{2^n}|f(a_0)|$. In particular, $f(a_n)\to 0$.
Since $S$ is compact, there is a subsequence $(a_{n_k})_k$ of $(a_n)$ converging to some point $a\in S$.
Now, since $f$ is continuous, $f(a)=\lim_k f(a_{n_k})=0$.


gRPC-Gateway: Is there a way to return responses in form of JSON arrays?

Question: I'm making an implementation of https://todobackend.com/ using gRPC-Gateway. https://todobackend.com/'s spec requires some responses to be in form of JSON arrays, like:
GET /todos
=> [{ "title": "...", ... }, { ... }]

But AFAIK by using gRPC-Gateway I must return objects, like { "todos": [{ ... }, { ... }] }. Can I return arrays instead of objects?
Answer: I found this thread and got it working with response_body option along with allow_repeated_fields_in_body CLI argument.
  rpc Add(Todo) returns (Todo) {
    option (google.api.http) = {
      post: "/v1/todos",
      body: "*"
    };
  };

protoc -I proto/ -I googleapis \
  --go_out ./proto --go_opt paths=source_relative \
  --go-grpc_out ./proto --go-grpc_opt paths=source_relative \
  --grpc-gateway_out=allow_repeated_fields_in_body=true:./proto --grpc-gateway_opt paths=source_relative \
  ./proto/todo/todo.proto
# note "allow_repeated_fields_in_body=true"


Selecting 3 distinct elements from $\{2^1, 2^2,\ldots, 2^{2000}\}$ such that they form a GP.

Question: Compute the number of sets of three distinct elements that can be chosen from the set $\{2^1, 2^2,\ldots, 2^{2000}\}$ such that the three elements form an increasing geometric progression.
This is a problem from ARML 2001. I was thinking of classifying the set into subsets of odd and even power of $2$ but that does not work very effectively. I would prefer a conceptually elegant way over a rigorous computation. Thank you.
Comment: Perhaps the powers can form an arithmetic progression
Comment: We wish to calculate the number of 3 term arithmetic progressions in $\{1,2,...2000\}$. Now given a triple $\{a,b,c\}$ this forms an arithmetic progression provided $b=\frac{a+c}{2}$ so you could count pairs $a$ and $c$ whose average is an integer.
Answer: As David said, this is the same as selecting three exponents in arithmetic progression. Clearly the first and last exponent determine the middle exponent, and they (the first and last) must have the same parity. Therefore it amounts to choosing a pair either from $\{1,3,\ldots,1999\}$ or from $\{2,4,\ldots,2000\}$, for a total of
$$
 2\times\binom{1000}2 = 1000\times 999 = 999000
$$
possibilities.
Comment: Yes, thank you, I was trying to see this by odd-even subset classification, but couldn't. Thanks for helping.
Answer: This is the same as selecting three elements of $\{1,2,\ldots,2000\}$ to form an arithmetic progression.  First we choose the middle element $b$ to be anything from $2$ to $1000$; then choose the smallest element $a$ to be anything from $1$ to $b-1$.  This uniquely determines the largest element $c$.  The number of possibilities is
$$\sum_{b=2}^{1000}(b-1)=\frac{999\times1000}{2}\ .$$
Similarly, if we choose $b$ from $1001$ to $1999$ we then proceed to choose $c$, and this uniquely determines $a$.  This gives the same number of possibilities as the first case, so the grand total is $999000$.
Comment: There's a $2000$ in the problem statement.
Comment: @MarcvanLeeuwen thanks, fixed.  Don't know how I misread that... maybe it was all the $2$s in the question.
Comment: Thank you, I developed a very nice concept while trying to understand your question.
Answer: Number of GPs in which the difference-factor is $2^1$ is 1998.
$(2^1\to 2^2\to 2^3)\cdots (2^{1998}\to 2^{1999}\to 2^{2000})$
Number of GPs in which the difference-factor is $2^2$ is 1996.
$(2^1\to 2^3\to 2^5)\cdots (2^{1996}\to 2^{1998}\to 2^{2000})$
$\cdots$
Number of GPs in which the difference-factor is $2^{998}$ is 4.
$(2^1\to 2^{999}\to 2^{1997})\cdots (2^4\to 2^{1002}\to 2^{2000})$
Number of GPs in which the difference-factor is $2^{999}$ is 2.
$(2^1\to 2^{1000}\to 2^{1999})\cdots (2^2\to 2^{1001}\to 2^{2000})$
Do you see a pattern?
Comment: Interesting....


Twitter Bootstrap - full width navbar

Question: Following the example of TB, I have a navbar that is marked up as follows:

I'd like this to span the full width of the screen and not have any rounded corners -- similar to static top styling of the navbar.
I can't seem to find how to do this in TB. If there isn't a way, what CSS would I need to override TB and not break responsiveness?
Comment: I realized late last night that there was a bad typo in the solution I provided you. It is now fixed in [my answer below](http://stackoverflow.com/a/14736713/61654).
Answer: Just change the class container to container-fullwidth like this :

Comment: This isn't a bootstrap class?
Answer: Not sure if the navbar-static-top class was available prior to version 2.2.2 but I think you can accomplish your goal with the following:

Test1

Test2

Test3

Test4

Test5

    ...

I put together a jsFiddle as an example.
Answer: Put the navbar out of your container:

EDIT:
Here is one that I did with responsive navbar. The code fits the document body:

          Project name

Home

Link

Link

Log out

Comment: It doesn't work well: 1.) still has rounded corners, 2.) horizontal scroll bar appears as I resize the browser, 3.) at small screen width, it no longer spans the full width of the browser.
Comment: Updated my answer with some snippet which I used. Did you include the responsive CSS and viewport meta tag? The docs show how to implement a responsive navbar http://twitter.github.com/bootstrap/components.html#navs
Comment: Sorry - I think I meant "fluid", not responsive. I actually don't want it to turn into that UI with the button on the right. I'll style it differently than the default TB look. How to get rid of rounded corners? Why do I get horizontal scroll bars? Why does it not span full width at small screens?
Comment: How do you want the navbar to be exactly? links getting to the following lines?
Comment: I'm only concerned with the navbar's container. I want it to span the width of the screen always.
Comment: you shouldn't be having a `.container` within a navbar. `.container` is for multiple rows, so you only really need it once right after the `body` tag or so. You should be using rows for other elements like navbar, header, body, etc.
Comment: Wow thank you so much. Exactly what I needed, and it seems so obvious now.
Answer: I'm very late to the party but this answer pulls up top in Google search results.
Bootstrap 3 has an answer for this built in, set your container div in your navbar to container-fluid and it'll fall to screen width.
Like so:

More Stuff

Answer: Put your element out from the
.
Ex :-

 ......nav content goes here

   ........ other content goes here

Answer: You need to push the container down the navbar.
Please find my working fiddle here http://jsfiddle.net/meetravi/aXCMW/1/

Test

Test1

Test2

Test3

Test4

Test5

Comment: Same comment to rrikesh: It doesn't work well: 1.) still has rounded corners, 2.) horizontal scroll bar appears as I resize the browser, 3.) at small screen width, it no longer spans the full width of the browser.
Comment: Try this fiddle this might solve your problem. http://jsfiddle.net/meetravi/aXCMW/2/

1. Border radius problem is solved now

2. Try overflow:hidden

3. I am not sure my solution will solve it.so let me know the results.
For minor bootstrap tweaks I use !important to override it. I am not sure is there any better way to override it.
Comment: #3 is not solved. You can see it in the jsFiddle. Is there no "native" way to do this in TB?
Comment: #3 issue is solved now. See the updated fiddle http://jsfiddle.net/meetravi/aXCMW/4/.

Accept my ans if it solves your problem or +1 if it is of any little help to you.
Answer: Just replace
 with
, which is the container with no margins on both sides.
I think this is the best solution because it avoids some useless overriding and makes use of built-in classes, it's clean.
Comment: This doesn't fix it.  It does expand further but not completely.
Answer: You can override some css
body {
    padding-left: 0px !important;
    padding-right: 0px !important;
}

.navbar-inner {
    border-radius: 0px !important;
}

The !important is needed just in case you link the bootstrap.css after your custom css.
And add your nav html out of a .container
Comment: The `body` styles will affect the rest of the site, right? I just really want to affect just the navbar. I already like the padding/margins of everything else.
Comment: yes, but you can make a way to do this.. everything else should be unser a `div.container`, right? So you can apply the `body` styles that you override in the `div.containe`, e.g.: `.container {
    padding-left: 10px !important;
    padding-right: 10px !important;
}`
Answer: To remove the border-radius on the corners add this style to your custom.css file
    .navbar-inner{
       -webkit-border-radius: 0; -moz-border-radius: 0; border-radius: 0;
    }

Answer: I know I'm a bit late to the party, but I got around the issue by tweaking the CSS to have the   width span 100%, and setting l/r margins to 0px;
#div_id
{
    margin-left: 0px;
    margin-right: 0px;
    width: 100%;
}

Answer: You have to add col-md-12 to your inner-navbar. md is for desktop .you can choose other options from bootstrap's list of options . 12 in col-md-12 is for full width .If you want half-width you can use 6 instead of 12 .for e.g. col-md-6.

Here is the solution to your question

Twitter Bootstrap - full width navbar


Is it true that $H_n(X,\mathbb{Z})=Hom(H^n(X,\mathbb{Z}),\mathbb{Z})?$

Question: I assume that $H_n(X,\mathbb{Z})$ are finitely generated free ablelian groups. Then from the universal coefficients theorem I have $H^n(X,\mathbb{Z})=Hom(H_n(X,\mathbb{Z})).$
Then, since $H_n(X,\mathbb{Z})$ is just $\mathbb{Z}^m$, we have $Hom(H_n(X,\mathbb{Z}),\mathbb{Z})=H_n(X,\mathbb{Z})$ through dual basis. Thus, taking $Hom$ from both sides, we get $Hom(H^n(X,\mathbb{Z}),\mathbb{Z})=H_n(X,\mathbb{Z})$. Is it a legit argument?
However, if I start with no information on homologies, and all information on cohomologies (for example, let's assume that $\forall n~$ $H^n(X,\mathbb{Z})$ is finitely generated free abelian group), can I somehow deduce what $H_n(X,\mathbb{Z})$ looks like?
Answer: Suppose your $X$ has finitely many cells in each dimension. Then by the universal coefficient theorem, $H^{n}(X)=\operatorname{Hom}(H_{n}(X),\mathbb{Z}) \oplus \operatorname{Ext}(H_{n-1}(X), \mathbb{Z})$. Since we are finitely generated, we have a spitting into a free part and a torsion part. Since $\operatorname{Ext}(\mathbb{Z}/p^n,\mathbb{Z})=\mathbb{Z}/p^n$, and since any nontrivial homomorphism into $\mathbb{Z}$ has infinite order, we deduce that the rank of $H_{n}(X)$ is the rank of $H^{n}(X)$ and the torsion part of $H_{n}(X)$ is the torsion part of $H^{n+1}(X)$.
In general you cannot solve the problem because I believe you have groups with isomorphic sets of homomorphisms into the integers and ext groups with the integers. Then you get an example by the Moore spaces for these groups.
Comment: I should link this https://math.stackexchange.com/questions/1268593/is-homology-determined-by-cohomology which gives the exact same answer as me, but actually gives an example of such a group.
Comment: Yes, your reasoning is correct. It is the same as this proof but you remove all torsion
Comment: Thanks. But is what I wrote about the case when we know homologies true? I mean, that $H_n(X,\mathbb{Z})=Hom(H^n(X,\mathbb{Z}),\mathbb{Z})$


Pandas expanding a dataframe length but populate each row incrementally based on column

Question: I'm working with a dataframe that looks like this:
    frame   requests
0   0   214388438.0
1   1   194980303.0
2   2   179475934.0
3   3   165196540.0
4   4   154815540.0
5   5   123650671.0
6   6   119089045.0

The thing is I want to add each of the value found on the requests column incrementally.
Say frame 0 should have the first value, frame 1 should have the previous value and the one that comes after followed by 0. I want the dataframe to look something like this:
        frame   requests
    0   0   214388438.0
    1   0             0
    2   0             0
    3   0             0
   ....................
   48   1   214388438.0
   49   1   194980303.0
   50   1             0
   ....................
   ..   2   214388438.0
   ..   2   194980303.0
   ..   2   179475934.0
   ..   2             0

Eventually, on the last value for column frame all rows would be populated by the value on the requests, no more 0s.
   ....................
   ..   47   214388438.0
   ..   47   194980303.0
   ..   47   179475934.0
   ..   47   165196540.0
   ..   47   154815540.0
   ..   47   123650671.0
   .....................

Answer: Assuming df as input, you can use numpy to reshape and create a new DataFrame:
import numpy as np

a = df['requests'].to_numpy()

df2 = (pd
 .DataFrame(np.tril(np.tile(a, (len(a), 1))), index=df['frame'])
 .stack()
 .droplevel(1)
 .reset_index(name='requests')
)

NB. You can also use df['requests'] directly instead of a, the conversion to array will be done automatically.
output:
    frame     requests
0       0  214388438.0
1       0          0.0
2       0          0.0
3       0          0.0
4       0          0.0
5       0          0.0
6       0          0.0
7       1  214388438.0
8       1  194980303.0
9       1          0.0
10      1          0.0
11      1          0.0
12      1          0.0
13      1          0.0
14      2  214388438.0
15      2  194980303.0
16      2  179475934.0
17      2          0.0
18      2          0.0
19      2          0.0
20      2          0.0
21      3  214388438.0
22      3  194980303.0
23      3  179475934.0
24      3  165196540.0
25      3          0.0
26      3          0.0
27      3          0.0
28      4  214388438.0
29      4  194980303.0
30      4  179475934.0
31      4  165196540.0
32      4  154815540.0
33      4          0.0
34      4          0.0
35      5  214388438.0
36      5  194980303.0
37      5  179475934.0
38      5  165196540.0
39      5  154815540.0
40      5  123650671.0
41      5          0.0
42      6  214388438.0
43      6  194980303.0
44      6  179475934.0
45      6  165196540.0
46      6  154815540.0
47      6  123650671.0
48      6  119089045.0


Can the existance of IIS be queried through Active Directory database?

Question: I'm looking for a way to query Active Directory to return a list of IIS servers. I'm running Windows Server 2008 domain. Is there some sort of Active Directory property or attribute that gets set when IIS is installed on a server?
I know that I could query services on the servers to see if it's installed, but I'm curious if there is a way to do it strictly through Active Directory. I've looked through the database using ADSI edit (no changes made!) just to examine properties of the IIS boxes and didn't see anything jump out at me.
Anyone solved something like this before?
Answer: No, there's nothing that does this. IIS doesn't put stuff in Active Directory, so there's nothing to query for.
Interrogating the machines directly is the only way to be sure.
Answer:
You can scan your internal IP ranges to see which IPs respond on port 80 (you may miss computers configured to respond on different ports). This will give you a list of web servers (IIS, Apache etc). You can improve results by requesting a page and analysing returned results (e.g. a 404 page would usually be different on different web servers). Or you can analyse HTTP headers (e.g. Server)
You can use SMS or SCCM to see which computers in your organisation have IIS installed.
You can use WMI to query computers from your AD (or a given IP range) to see if IIS is installed. E.g. http://www.vistax64.com/powershell/175977-iis-installed.html


jQuery toggle menu not working

Question: If I Click on the current item it should toggle on and off and close all other
item if it is open. When I click on menu1 it just keeps open.. i want to features like when it is open it should close, when it it closed it should open. Please see the url

Menu 1

Menu 1 content

Menu2

Menu2 content

Menu3

Menu3 content

Comment: What exactly is your question?
Answer: I'm not sure what your question is, but I do see an extra comma at the end of the third line of your code (...slideToggle("slow,")). That should probably not be there.
EDIT: After checking the provided url I now see what the problem is. First you should add a new style for the .toggle_container class:
li.toggle_container { display: none; }

This prevents initial display of the sub menus. Next you should take into account inside your jQuery script if you click on an active or inactive link:
$(document).ready(function() {
    $("li.trigger").click(function() {
        $(this).next(".toggle_container").slideToggle("slow");
        if (!$(this).hasClass("active")) {
            $(".toggle_container").hide();
            $(".active").toggleClass("active");
            $(this).toggleClass("active");
        }
        return false;
    });
});

And that's it.
Comment: Look at the url - http://18.104.22.168/~paglaso/jquery/toggle.php

what I want is when I click on menu it should open and close. At the moment it just open. Initially it used to open and close.... i had to close all other opened menu by adding $(".toggle_container").hide(); in onclick list item.
Comment: I updated my answer based on the code behind the provided url. This should work.
Answer: Try these on your code,
$("selector").addClass("class").siblings().removeClass("class");
or
$("selector").slideToggle("slow").siblings().hide("slow");

Answer: You can just extend jQuery with a toggleClass as shown below:
//extend jquery
(function($) {
    $.fn.toggleClass = function(check, replace) {
        return this.each(function() {
            if ($(this).hasClass(check)) {
                $(this).removeClass(check);
                $(this).addClass(replace);
            } else {
                if ($(this).hasClass(replace))
                    $(this).removeClass(replace);
                $(this).addClass(check);
            }
        });
    };
})(jQuery);

So you can do stuff like this:
<input type="button" value="Toggle"
onclick="$('#myDiv').toggleClass('expanded','collapsed')"/>

Answer: Here's a bit simpler solution overall:
$(function(){
  $(".toggle_container").hide();
  $("li.trigger").click(function(){
     $(".toggle_container").not($(this).next()).hide();
     $(this).addClass("active").next(".toggle_container").slideToggle("slow")
            .end().siblings().removeClass("active");
  });
});

Note though, the only thing needed to fix your original code, is to exclude the element you want from being hidden so the toggle works correctly (it was being hidden always before toggle, so toggle was always "show"), you do this by adding .not() like this:
$(".toggle_container").hide();
$(".toggle_container").not($(this).next()).hide();

jQuery toggle menu not working


Função void com Spring retornando null no Angular 6

Question: Tenho o seguinte código para apenas excluir um registro no banco e que deveria devolver um resultado com o status 204-OK.
Utilizo Spring Rest no back e um método como void com uma anotação @ResponseStatus(HttpStatus.NO_CONTENT). Testei no Postman e ele retorna normal o resultado, e no navegador também aparece o resultado esperado. Porém, no código só retorna null.
O registro é excluído nessa função, está funcionando corretamente, porém o retorno 204 do backend não retorna para o Angular apenas. Não tenho a mínima ideia do que pode ser.
<code>import { Injectable } from '@angular/core';
import { MasterHttp } from './../seguranca/master-http';
import { HttpParams } from '@angular/common/http';
import { Tipo } from './../model/Tipo';

import 'rxjs/add/operator/toPromise';
import { environment } from './../../environments/environment';

export class TipoFilter {
  tipo: string;
  pagina = 0;
  itensPorPagina = 2;
}

@Injectable({
  providedIn: 'root'
})
export class TipoService {

  tiposUrl: string;

  constructor(private http: MasterHttp) {
    this.tiposUrl = `${environment.apiUrl}/tipos`;
  }

  excluir(id: number, posicaoDaPagina: number, itensPorPagina: number): Promise<any> {
    const dadosPagina = posicaoDaPagina + itensPorPagina - 1;

    const params = new HttpParams({
       fromObject: {
          page: `${dadosPagina}`,
          size: '1'
       }
    });

    return this.http.delete<any>(`${this.tiposUrl}/${id}`)
      .toPromise()
      .then(response => {
        console.log(response);
        let proximoObjeto;
        if (response.ok) {
           proximoObjeto = this.buscarProximo(params, dadosPagina);
        } else {
           return null;
        }
        return proximoObjeto;
      });

 }

  buscarProximo(params, dadosPagina): Promise<any> {
    return this.http.get<any>(`${this.tiposUrl}`, { params })
    .toPromise()
    .then(resp => {
      const resultado = {
          lancamentos: resp.content,
          total: resp.totalElements
      };
      return (resultado.total + 1) < dadosPagina ? null : resultado;
    });
  }
}
</code>
No backend está assim:
<code>@RestController
@RequestMapping("/tipos")
public class TipoResource {

    @Autowired
    private TipoRepository tipoRepository;

    @DeleteMapping("/{id}")
    @PreAuthorize("hasAuthority('ROLE_CADASTRAR_TIPO')")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public void remover(@PathVariable Long id) {
        tipoRepository.deleteById(id);
    }
}
</code>
EDIT 1
Todas as funções que eu tenho funcionam no backend normalmente, inclusive essa de remover. Eu tenho essa exata função em outro projeto que funciona perfeitamente.
Comment: Tente mudar o retorno de void para Object, se funcionar, eu publico a resposta
Comment: Tentei porém sem sucesso. Coloquei também retorno como ResponseEntity e uma String como body e mesmo assim continuou retornando null. Talvez o problema possa ser no backend, porém não consigo identificar.
Comment: Outros metodos sem ser delete estão funcionando?
Comment: Sim. Está tudo normal. O backend funciona corretamente, só o Angular que não está pegando essa resposta "OK 204" mesmo retornando ela.
Answer: Já tentou retornar ResponseEntity ?
<code>    @DeleteMapping("/{id}")
    @PreAuthorize("hasAuthority('ROLE_CADASTRAR_TIPO')")
    public ResponseEntity<Void> remover(@PathVariable Long id) {
        tipoRepository.deleteById(id);
        return ResponseEntity.noContent().build();
    }
</code>
https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/http/ResponseEntity.html
Comment: Tentei, porém sem sucesso também.


Determine if the polynomial $X^4+2X^2+1 \in \Bbb Z_3[X]$ is non divisible.

Question:
Determine if the polynomial $X^4+2X^2+1 \in \Bbb Z_3[X]$ is non divisible.

I couldn't find any theorems on "non divisiblity" so I assume that this isn't divisible since it doesn't have any roots in $\Bbb Z_3$? We have that $0+0+1=1, 1+2+1=4=1$ and $2^4+8+1=25=1$. Wouldn't this imply that the polynomial doesn't factor and thus doesn't have any divisor?
Comment: If by "non-divisible" you mean irreducible, then it is not sufficient to show there are no roots in $\Bbb Z_3$ since it might factorise as two quadratic polynomials.
Comment: $u^2 + 2u+ 1 = (u+1)^2$. Put $u = x^2$ to see that the given polynomial is redicible.
Comment: The polynomial is obviously a square in $\Bbb Z_3[X]$, hence reducible. More precisely, it is $(x^2+1)^2$.
Answer: Over any field you have $X^4+2X^2+1=(X^2+1)^2$, and therefore $X^4+2X^2+1$ is reducible, even when it has no roots. It's only when the degree of polynomial is $2$ or $3$ that the non-existence of roots implies that the polynomial is irreducible.


How to prove that there is no positive integer solution to this two variables inequalities system?

Question: I would like to know if it is possible to prove that there are no integer solutions to:
$$
\begin{cases}
77n &- 154m &\leq -1\\
154m &- 77n &\leq 76
\end{cases}
$$
I have no idea how to start, so any comments are welcome.
Thank you and regards, Tony.
Comment: Use that $154$ is divisible by $77$.
Comment: yes, i need to prove that there are no integer solutions for n and m.
Comment: What is a number of natural numbers on $[1,76]$, which are divisible by $77$?
Comment: how about 154y - 154x <= -1 and 154m - 154m <=76? how to find x and integers?
Answer: The given inequalities can be written as $$1\le 154m-77n\le 76\;\;,where\,m,n\in N$$
$$0\lt\frac{1}{77}\le 2m-n\le \frac{76}{77}\lt 1$$
$$\forall m,n \in N \;\;,2m-n\in I $$
For any positive integer $m,n\;\;, 2m-n\notin (0,1)$ $$. $$
Hence therefore there doesnot exist any positive integer $m,n$ that satisfy both inequality.
Comment: Where can I learn about the theorem or proof that you gave me, Rajan?
Comment: These all are part of school level mathematics for which one more site which I follow is. https://www.mathsdiscussion.com/. You can find some and also learn there.
Answer: The first inequality gives $n-2m \le -\frac{1}{77}.$ Since $n-2m$ is an integer, we get
$(1) \quad n-2m \le -1.$
The second inequality gives $2m-n \le \frac{76}{77}.$ Since $2m-n$ is an integer, we get
$(2) \quad 2m-n \le 0.$
But from $(1)$ it follows that $2m-n \ge 1.$ This is a contradiction to $(2)$.
Comment: Thank you so much, Fred. Are there any references for the theorem that I can read to prove the contradiction?


Cannot get the original colored bitmap after tesseract processing - android

Question: I use tesseract library for android to capture certain text from an image. I know that the captured image is not saved anywhere, it gets recycled. I need to find the original colored bitmap. I have been trying to locate the original colored bitmap, but all I could find was a grayscaled bitmap:
Bitmap bitmap = activity.getCameraManager().buildLuminanceSource(data, width, height).renderCroppedGreyscaleBitmap();

When I save this bitmap to the sdcard, I get a gray scaled image. renderCroppedGreyscaleBitmap() method is as follows:
public Bitmap renderCroppedGreyscaleBitmap() {
    int width = getWidth();
    int height = getHeight();
    int[] pixels = new int[width * height];
    byte[] yuv = yuvData;
    int inputOffset = top * dataWidth + left;

    for (int y = 0; y < height; y++) {
      int outputOffset = y * width;
      for (int x = 0; x < width; x++) {
        int grey = yuv[inputOffset + x] & 0xff;
        pixels[outputOffset + x] = 0xFF000000 | (grey * 0x00010101);
      }
      inputOffset += dataWidth;
    }

    Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
    return bitmap;
  }

I would greatly appreciate if someone can tell me to get the original colored image captured. Do I have to change this method to get the colored image(RGB)?
Comment: do you get any solution for this problem?
Comment: YuvImage yuvImage = new YuvImage(data, ImageFormat.NV21, width,
     height, null);
   ByteArrayOutputStream baos = new ByteArrayOutputStream();
   yuvImage.compressToJpeg(new Rect(0, 0, width, height), 80, baos);
   byte[] byteArray = baos.toByteArray();
   Bitmap bitmaptest = BitmapFactory.decodeByteArray(byteArray, 0,
     byteArray.length);
Answer:     /**
     * YUV to bitmap
     * @param data   The YUV preview frame.
     * @param width  The width of the preview frame.
     * @param height The height of the preview frame.
     * @return
     */
    public static Bitmap byteArray2Bitmap(byte[] data, int width, int height) {
        YuvImage yuvimage = new YuvImage(data, ImageFormat.NV21, width, height, null);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        yuvimage.compressToJpeg(new Rect(0, 0, width, height), 100, baos);
        byte[] rawImage = baos.toByteArray();

        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inPreferredConfig = Bitmap.Config.RGB_565;
        Bitmap bitmap = BitmapFactory.decodeByteArray(rawImage, 0, rawImage.length, options);

        Matrix matrix = new Matrix();
        matrix.postRotate(90);
        return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
    }

Comment: You need to write a question. First I recommend you read tutorial for asking!


How to access the existing field value in a custom field?

Question: I have a content type which shows video in iframe from youtube. There is a field which I can enter the youtube link and it will render the iframe using the link.
I have created a custom field which will take the youtube link as input and get the youtube statistics using youtube api. The field will display a div in the page with view count and number of likes of the video.
I wanted to access the already existing field value (youtube link which shows iframe), to show my stats information, as both are same. In my custom field module, I am taking an input field which is the youtube url.
For a user, it will be repetitive, if he types the url twice. Also I already have so many contents added to my content types, so it will be a burden to the content creators to go and add values to my newly created field.
Is there any way, I can access the existing fields value of my same content type ?
Here is my code :
YoutubeStat.php
<?php

namespace Drupal\youtube_stat\Plugin\Field\FieldType;

use Drupal\Core\Field\FieldItemBase;
use Drupal\Core\TypedData\DataDefinition;
use Drupal\Core\Field\FieldStorageDefinitionInterface as StorageDefinition;

/**
 * Plugin implementation of the 'player_info' field type.
 *
 * @FieldType(
 *   id = "Youtube_stat",
 *   label = @Translation("Youtube statistics"),
 *   description = @Translation("To Display Youtube statistics"),
 *   category = @Translation("Custom"),
 *   default_widget = "Youtube_statDefaultWidget",
 *   default_formatter = "Youtube_statDefaultFormatter"
 * )
 */
class Youtube_stat extends FieldItemBase {

  /**
   * Field type properties definition.
   *
   * Inside this method we defines all the fields (properties) that our
   * custom field type will have.
   *
   * Here there is a list of allowed property types: https://goo.gl/sIBBgO
   */
  public static function propertyDefinitions(StorageDefinition $storage) {

    $properties = [];

    $properties['videoId'] = DataDefinition::create('string')
      ->setLabel(t('Video Id'));

    return $properties;
  }

  /**
   * Field type schema definition.
   *
   * Inside this method we defines the database schema used to store data for
   * our field type.
   *
   * Here there is a list of allowed column types: https://goo.gl/YY3G7s
   */
  public static function schema(StorageDefinition $storage) {

    $columns = [];

    $columns['videoId'] = [
      'type' => 'char',
      'length' => 255,
    ];

    return [
      'columns' => $columns,
      'indexes' => [],
    ];
  }

  /**
   * Define when the field type is empty.
   *
   * This method is important and used internally by Drupal. Take a moment
   * to define when the field fype must be considered empty.
   */
  public function isEmpty() {

    $isEmpty =
      empty($this->get('videoId')->getValue());

    return $isEmpty;
  }

}

YoutubeStatDefaultFormatter.php
    <?php

namespace Drupal\youtube_stat\Plugin\Field\FieldFormatter;

use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\FormatterBase;
use Drupal;

/**
 * Plugin implementation of the 'Youtube_statDefaultFormatter' formatter.
 *
 * @FieldFormatter(
 *   id = "Youtube_statDefaultFormatter",
 *   label = @Translation("Youtube statisctics"),
 *   field_types = {
 *     "Youtube_stat"
 *   }
 * )
 */
class Youtube_statDefaultFormatter extends FormatterBase {

  /**
   * Define how the field type is showed.
   *
   * Inside this method we can customize how the field is displayed inside
   * pages.
   */
  public function viewElements(FieldItemListInterface $items, $langcode) {

    \Drupal::service('page_cache_kill_switch')->trigger();
    //$memory = (string)ini_get("memory_limit");
      //ini_set('memory_limit', '-1');
    $elements = [];
    foreach ($items as $delta => $item) {

      $JSON = file_get_contents("https://www.googleapis.com/youtube/v3/videos?key=*_API_KEY_*&part=statistics&id={$item->videoId}");
      $JSON_Data = json_decode($JSON);
      $viewCount = $JSON_Data->items[0]->statistics->viewCount;
      $likeCount = $JSON_Data->items[0]->statistics->likeCount;
      //$dump_data = '
'.json_encode($item).'
';
      $stat_div = "
Views : ".$viewCount." Likes : ".$likeCount."
";
      //$result = $query->fetchAll();
      $elements[$delta] = [
        '#type' => 'markup',
        '#markup' => $stat_div,
        '#cache' => ['max-age' => 0]
      ];
    }
    //ini_set('memory_limit', $memory);
    return $elements;
  }

}

Is there any way to achieve this ?
Answer: I don't think this warrants a custom field but could be handled many other ways. A couple options here
1.) You can preprocess the node and provide your value as a variable to use in the node.tpl.php template.
2.) Create a new Drupal field and use hook_form_alter and on your submit take the value from the youtube field and place it into your new field. Then hide the field from the end user when they edit the node. Then run a one time function to loop through existing content types and update it with the youtube value.


Replit Database. How would I embed the curl commands of the Replit Database into my php web server code?

Question: I am creating a sign up page on my PHP web server on replit that involves the replit default database. I know that there are language clients for python, node, and go. How do I embed the curl commands into the PHP code. Currently, I am using the shell exec command to execute curls on the online shell. The curl commands I am using from repl.it are
curl $REPLIT_DB_URL -d 'key=value'

curl $REPLIT_DB_URL/key

curl -XDELETE $REPLIT_DB_URL/key

curl "$REPLIT_DB_URL?prefix=key"

They are used for setting keys to values, getting a key's value, deleting a key, and listing all keys respectively.
When I copy these commands and paste them into a PHP file like this,
<?php

$email = $_POST["email"];
$password = $_POST["password"];
curl $REPLIT_DB_URL -d '$email=$password';
curl $REPLIT_DB_URL/$email;

?>

I get this error:
syntax error, unexpected '$REPLIT_DB_URL' (T_VARIABLE)

Thank you in advance.
Comment: Is there any other info I need to provide because I am getting downvoted for no known reason without any feedback?
Comment: You are getting downvoted because you haven't shown any attempt at research or provided an attempt at a solution that you need help with. PS: a simple web search for 'php curl' should lead you to the inbuilt PHP curl library. https://www.php.net/manual/en/curl.examples-basic.php
Comment: I couldn't really find anything there. The one Im looking for involves key-value databases. I will edit my question to show this.
Comment: A curl is a curl. You want to call a database via curl from PHP. Use the PHP curl library. Anything specific to your database is just URL, headers and body. I have quite successfully written trash-grade 'drivers' to call GraphQL and Elasticsearch services from PHP applications using only PHP's curl library. It works fine. Heck, go deep enough into any real driver library in PHP that calls a HTTP service and you'll find the curl commands.
Answer: You can't just paste console commands into PHP code and expect them to work. The error you are getting is that it doesn't understand what $REPLIT_DB_URL is.
You are going to have to convert your console commands into PHP code.
$ch = curl_init('http://url-to-your-database-server');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
curl_setopt($ch, CURLOPT_POSTFIELDS, "{$email}={$password}");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
if ($result === false) {
    // handle the error here
}
curl_close($ch);

Whether you need to json_encode the body (email and password pair) or not is up to how your database accepts the body. Your raw curl lines suggest maybe not. You may also need to json_decode the $result, maybe not.
Note that I have kept the $ch handler open for the error handling, you can get the code and response for an error with
curl_error($ch)
curl_errno($ch)

Answer: <?php
$email = $_POST["email"];
$password = $_POST["password"];

$retval = null;

//adds key and the data
exec('curl $REPLIT_DB_URL -d \''.$email.'='.$password.'\'');

//gets the key
exec('curl $REPLIT_DB_URL/'.$email, $retval);
echo $retval[0] . "
";  //prints data the

$retval=null;

//gets all keys that have the $email (like @gmail.com and all emails with Gmail domain come up) in it, as a list
exec('curl "$REPLIT_DB_URL?prefix='.$email.'"', $retval);

foreach ($retval as $keyname) {
  $retval=null;
  exec('curl $REPLIT_DB_URL/'.$keyname, $retval);
  echo $keyname .": ". $retval[0]."
";  //prints data the

}

//deletes the key
exec('curl -XDELETE $REPLIT_DB_URL/'.$email);

?>

Answer: I have faced the same problem and I finally solved it. Here is the steps:

open Replit's terminal (shell) and execute this command: echo $REPLIT_DB_URL to get the database URL.
copy ReplitDB.php from Replit Database for PHP.
include or require it to your code, here is the code:

require __DIR__ .'/ReplitDB.php';

use \Dannsbass\ReplitDB;

$db = new ReplitDB(REPLIT_DB_URL); // get from terminal: echo $REPLIT_DB_URL

// set your data
$db->set_data('email', $your_email);
$db->set_data('password', $your_password);

// get all data keys
echo $db->get_keys();

// retrieve a specified data by its key
echo $db->get_data('email');

Please check Replit Database for PHP for documentation.


Adicionar header em http request ionic 3

Question: estou com problema para enviar headers, quando eu coloco os headers não funciona no APK, somente no navegador, mas se eu tirar as linhas e não enviar nenhum header ele funciona normalmente.
No navegador funciona os 2 exemplos, no celular só funciona a segunda imagem, não sei se é CORS pq eu não consigo dar uma alert na requisição...
O código: https://pastebin.com/nQY7Gz8e
Answer: É normal desenvolvedores cairem nesse problema, isso acontece porque seu aplicativo tenta acessar algo externo uma "a url da api" e para proteger você de um acesso externo ele bloqueia essa requisição.
mas porque no navegador funciona? Aposto que a api e o navegador estão rodando no mesmo PC então a requisição não é bloqueada.
Para entender mais sobre o CORS : Controle de Acesso HTTP
Algumas soluções possiveis pode ser:

Enviar Parametros pelo Headers durante a requisição =>  { Access-Control-Allow-Origin: * }
Adicionar um proxy para consumir a api.
Usar a Lib CORS na api

Espero ter ajudado :)


Intuition on the Topological definition of continuity, considering the special case of the step function.

Question: I'm trying to get an intuition for open sets and topological reasoning in general. One example I want to understand is the step function, and specifically why it would be considered discontinuous under the topological definition of continuity. For instance, suppose I define the step function as:
f(x) = the smallest integer larger than x.
The simple example here implies that f is a map from R->R (which is implicitly thought of as having the open ball topology? Could we think of the step function as continuous under some other topology?), then it seems trivially true that the step function is continuous because both spaces have the same open sets.
In contrast to the last statement, I do understand that it's not just about having the same open sets, but about the preimage of the open sets in the output space being open in the input space.
However, I get extremely confused here because there is no open set under the open ball topology which is covered by the mapping. That is to say that f(x) always outputs an integer, and a single integer in R does not constitute an open set given the open ball topology.
My initial thought was that perhaps this fact is the reason the function is called discontinuous, but then a constant function, for instance f(x) = 3, would also be considered discontinuous under identical reasoning as there is no open ball which contains only 3 in R.
I believe that my confusion is somehow related to nuances of the distinction between the image set and range of a mapping. As a follow up question, I could imagine adding further complications. Suppose I chose to think of my step function as a map from R->C where the image set is simply the integers with nonzero imaginary part. How could I show that the mapping is discontinuous in this case?
Answer: Take the left-continuous unit step function with the jump at zero. Consider the inverse image of $(-1/2,1/2)$. It is $(-\infty,0]$. Intuitively this means that you can't go any distance to the right of $0$ and still have values within $1/2$ of $f(0)=0$.
For the right continuous one, the inverse image of $(1/2,3/2)$ is $[0,\infty)$. Intuitively this means that you can't go any distance to the left of $0$ and still have values within $1/2$ of $f(0)=1$.
For ones which are neither left nor right-continuous, you can choose $\epsilon$ small enough that the inverse image of $(f(0)-\epsilon,f(0)+\epsilon)$ is $\{ 0 \}$. Intuitively this means that you can't go any distance in either direction from $0$ and have values within $\epsilon$ of $f(0)$.
In all three cases they are not open.


Minute Hand will be as much ahead of the hour Hand as it is Behind it

Question: The time is past 2 o'clock in 10 minutes. The minute hand will be as much as ahead of the hour hand as it is behind it. What time is it?
The Answer is 2:05.91
I am having trouble interpreting " Minute Hand will be as much ahead of the hour Hand as it is Behind it ". Does it mean the hour hand somehow bisects the two times of the minute hand? I am more of a visual learner... but i dont know why clock problems for me are so hard to visualize. maybe there is an easier way?
Comment: Is this the exact wording of the problem?
Comment: @OnceUponACrinoid yes
Answer: Here is how I would interpret the question: "The time is past 2 o'clock. In 10 minutes, the minute hand will be as much ahead of the hour hand as it is behind it [right now]." It's not quite right to say that the hour hand bisects the two positions of the minute hand, since the hour hand is also moving, but you're on the right track. Here is what we can infer:

Right now the minute hand is behind the hour hand (in particular, it is probably between 2:00 and 2:10).
In ten minutes the minute hand will be in front of the hour hand.
The distance right now between the minute hand and the hour hand is the same as the distance between them will be in ten minutes.

These points make 2:05.91 seem like a reasonable answer, although I'll admit that I'm getting a slightly different answer when I work the problem myself.
Answer: I would suggest that the interpretation given by Annie Carter is correct, and would solve the problem as follows.  Suppose that the time now is $m$ minutes past $2$.  For convenience we measure angles in units of full circles.  Then the angles between "12" on the clock, the centre of the clock, and the minute and hour hands are
$$\angle TOM=\frac{m}{60}\ ,\quad \angle TOH=\frac{2+\frac{m}{60}}{12}\ .$$
In ten minutes time it will be
$$\angle TOM=\frac{m+10}{60}\ ,\quad \angle TOH=\frac{2+\frac{m+10}{60}}{12}
  \ .$$
So we have
$$\frac{m+10}{60}-\frac{2+\frac{m+10}{60}}{12}
  =\frac{2+\frac{m}{60}}{12}-\frac{m}{60}\ .$$
Probably the best way to solve this is to write it as
$$\frac{2m+10}{60}=\frac{4+\frac{2m+10}{60}}{12}\ ;$$
you then easily get $2m+10=\frac{240}{11}$ and so $m=\frac{65}{11}=5.91$.
Answer: It's a problem from H.S. Hall's Elementary Algebra revised & enlarged for use in American schools by F.L. Sevenoak (Macmillan Company, 1896), Chapter XXV, Problem 11.

It is between 2 and 3 o'clock, and in 10 minutes the minute-hand will be as much before the hour-hand as it is now behind it: what is the time?

Adopting the method described in the book, the solution looks something like this:
Let x denote the current number of minutes after 2 o'clock (i.e., effectively, time now), and y the number of minute-divisions the minute-hand is before the hour-hand. Then, as the minute-hand travels twelve times as fast as the hour-hand, the hour-hand has already moved over $\frac{1}{12}*x$ minute-divisions.
At 2 o'clock the minute-hand was 10 divisions behind the hour-hand, and now is y divisions behind, therefore, the minute-hand has moved over 10 - y divisions more than the hour-hand. Hence, $$x = \frac{1}{12}*x + 10 - y \tag 1$$
In ten minutes the minute-hand will be y divisions in advance of the hour-hand which would travel $\frac{1}{12}*(x+10)$ by that time. Thus, the minute-hand will move over 10 + y divisions more than the hour-hand (10 minutes since 2 o'clock, and y more minutes). Hence, $$x + 10 = \frac{1}{12}*(x + 10) + 10 + y \tag 2$$
Subtracting (1) from (2), $$y = \frac{55}{12}$$ Therefore, $$x = \frac{65}{11} = 5\frac{10}{11} \simeq 5.91$$ as required.


Deny Access to AWS Console if not in IP

Question: I'd like to deny access to AWS console if a user is outside of our network or VPN. I found this policy but I'm running into random issues where a user gets an explicit deny even though they are in the network and have AdministratorAccess attached. It should be noted that I am using role based access through Okta.
<code>{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "DenyOutOfOffice",
            "Effect": "Deny",
            "Action": "*",
            "Resource": "*",
            "Condition": {
                "NotIpAddress": {
                    "aws:SourceIp": [
                        "<insert IP>"
                    ]
                }
            }
        }
    ]
}
</code>
Comment: You might be able to use **AWS CloudTrail** to diagnose the rejection issues.
Comment: Have you tried adding the Okta IP address?
Comment: Okta IP address? Okta has many IP addresses that are used. The request is coming from one public IP not multiple.
Answer: I've resolved the issue. This is related to AWS making internal calls using their internal IP and systems which naturally will cause an error due to my policy. The only work around at this time is to whitelist the specific services that use AWS's internal servers..
Comment: As of Jun 2022, there is a AWS global condition context key of [aws:ViaAWSService](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-viaawsservice) which can accommodate the check for AWS internal calls.

Deny Access to AWS Console if not in IP


Is it possible to get the node ID of the node that will be created?

Question: Trying to pass some information to third party API, every time a new node is created.
So far I have managed to identify the node insert/create when a node is created in hook_node_presave(). Done it by using empty($node->id()).
Now I want to anticipate what the node ID will be once the node is saved. Is it possible to get the node ID  before the node is created?
Comment: I needed hook insert for passing new node field values along with its id. Used presave because, for some reason I was convinced that node_insert from Drupal 7 is deprecated and no more used in D8 .  Jdrupal 's pointer to use hook_ENTITY_TYPE_insert helped me sort my query. Thanks !
Comment: Does this answer your question? [Get node ID in a form submit](https://drupal.stackexchange.com/questions/96634/get-node-id-in-a-form-submit)
Answer: You can use hook_ENTITY_TYPE_insert which is called after the node has been saved.
Function description:

This hook runs once the entity has been stored. Note that hook implementations may not alter the stored entity data.


Piecewise function in $L^p$ spaces

Question: Consider the space $C[0,3]$ for piecewise function such that
$$f_a(x)= \begin{cases}a^3(2-a^3x),&      0\le x \le \frac2{a^3}\quad\text{and} \\[1ex]
            0  ,   &                  \frac2{a^3}\le x \le 3\end{cases} $$
Set $\;B=\{f_a(x) : a\ge 1 \}$. Show that

$B$ is not bounded in $(L([0,3]) ,\| \cdot\|_\infty)$
$B$ is bounded in  $(L([0,3]) ,\| \cdot\|_1)$
B is not bounded in  $(L([0,3]) ,\| \cdot\|_2)$

I think about the question, but I didn't understand it. I get $\sup ( {f_1, f_2, ...} )= 2$ in the $\|\cdot\|_\infty$. Naturally, there is only one answer and it is not bounded this is ok. But what about the others? How bounded can we say in $\||\cdot\|_1$? The value of the integral proceeds independently of the value $a$, and the result is $2$. So $B ({f_1 + f_2 ...}) = B ({2 + 2 ....}$ ) continues. I think the result goes to infinity. I don't know how it is bounded . I checked its graph. As $x$ approaches $0$, the function goes to infinity. I'm really confused. I need your help.
Answer: $B$ is NOT the sum of the integrals, its just the collection of functions $f_a$.
Remember that a set is bounded if there is a ball of finite radius that contains the whole set, since each integral in $B$ integrates to $$4 - 2/a^3$$ and $2/a^3 \leq 2$ for $a \geq 1$ just pick any $f_a$ and the ball of radius $8$ at this point covers $B$, since for any $f_k$ in $B$
$$ \lvert\lvert f_k - f_a \rvert\rvert_1 \leq \lvert\lvert f_k \rvert\rvert_1 + \lvert\lvert f_a \rvert\rvert_1 \leq (4 - 2/a^3) + (4 - 2/a^3) \leq 8$$
Comment: How did you get 4- (2/a^3) ? I obtained result just 2.   2xa^3-(a^6x^2)/2 if we write x=2/a^3 then result is 2. Where is my mistake?
Comment: @Dore $a$ is constant, the integral is $2a^3 x - \dfrac{a^3x^2}{2}$ the exponent on your $a^6$ is wrong.

Piecewise function in $L^p$ spaces


$Var(\min\{X,Y\}) \leq Var(X)$?

Question: I have this problem, and the only thing that tells me is that X and Y are random variables that have finite variance, when $\min\{X,Y\} = X$, it is true, since $Var (X) = Var (X)$, I have the problem when I take the case $Var(\min\{X,Y\}) = Y$, clearly $Y <X$, but how do I prove that then $Var(Y)<Var (X)$?
I know that $Var(\min\{X,Y\}) = Var(\max\{X,Y\})$ when they have the same distribution or are symmetric, and I also read that $Var(\min\{X,Y\}) \leq Var(X) + Var(Y)$ but the latter I do not know how to prove it or how are the restrictions of such a statement, I would appreciate your help.
Comment: You should not look at the variance of X or Y bur rather the variance of them conditional on being lower. In any case, I guess it is simpler to just evaluate the integral and compute the variance analitically.
Comment: It's not correct to write "If $\min\{X,Y\} = X$ then is true, since $Var (X) = Var (X)$", because is this case you imply conditional variance but write just variance. Example: by this logic: "Bern(p) takes values 0 and 1, if it's equal to 0, then Var0=0, in other case Var1=0, hence Var(Bern(p))=0", that is false, of course.
Comment: https://math.stackexchange.com/q/4129387/321264
Answer: The claim is not true. Put $X=0$ and $Y = U[-1,0]$,.i.e. uniform distribution on $[-1, 0]$.

$Var(\min\{X,Y\}) \leq Var(X)$?


Supervised classifier for events with missing data

Question: I'm working on an experiment in which we try to sort events into three categories based on roughly 20 inputs using a feed-forward neural network (trained via backpropagation). Unfortunately, many variables which offer good discrimination become meaningless in some situations. So far, the procedure has been to set meaningless variables to some placeholder value which lies outside the normal range for that variable.
But that's roughly half the inputs in something like half the events. The classification isn't as strong as we'd like, so the options I've come up with are:

Split the events based on whether the unreliable variables are present, train several neural nets on the sub-samples. The classified samples would then be merged.
Switch to some other classifier (boosted decision trees are very popular in my field) which handles missing information more naturally.

Is one of these approaches obviously superior? Is there some other obvious option I'm missing?
Comment: I would add a feature for each value which might be missing indicating whether that value is missing, and clone the training point with several values for the missing data drawn from the normal ranges (using a lower learning rate to avoid overemphasizing that point).
Comment: @DouglasZare, can you elaborate more on that? (maybe an example will be good). I'm really interested in this question, but I'm not sure I really got you suggestion.
Answer: As requested, I'll elaborate on my comment, although I don't have experience using it. I work with neural networks for regression problems and often construct new features, but I don't have to deal with missing data so I'm not sure whether this will work.
Let's suppose the features of your data look like
$(0,1)$
$(0.5,0.5)$
$(*,0.2)$
$(*,0.7)$
$(0.8,*)$
where $*$ means the value is missing or unreliable. Rather than replacing $*$ with a very large or very small value outside the typical range, or breaking up your data so that you have a separate net for each subset of the data which might be missing, I suggest making two features for each input which might be missing. If the value is present, the two features become $(0,value)$. If the value is missing, then the features become $(1,random)$ where you randomly sample value from the range. So, the above data set would become
$(0,0,0,1)$
$(0,0.5,0,0.5)$
$(1,rand,0,0.2)$
$(1,rand,0,0.7)$
$(0,0.8,1,rand)$
Each point with a random coordinate can be cloned to give several inputs which you can train with a lower learning rate.
$(0,0,0,1), \alpha = \alpha_0 $
$(0,0.5,0,0.5), \alpha = \alpha_0$
$(1,0,0,0.2), \alpha = \alpha_0/3$
$(1,0.5,0,0.2), \alpha = \alpha_0/3$
$(1,0.8,0,0.2), \alpha = \alpha_0/3$
$(1,0,0,0.7), \alpha = \alpha_0/3$
$(1,0.5,0,0.7), \alpha = \alpha_0/3$
$(1,0.8,0,0.7), \alpha = \alpha_0/3$
$(0,0.8,1,1), \alpha = \alpha_0/4$
$(0,0.8,1,0.5), \alpha = \alpha_0/4$
$(0,0.8,1,0.2), \alpha = \alpha_0/4$
$(0,0.8,1,0.7), \alpha = \alpha_0/4$
One idea is that this should encourage the neural network to learn that when the indicator that the value is missing is $1$, then the value doesn't matter. You can test whether this is true for the neural network, and perhaps use a regularizer which encourages this.
Comment: this is an interesting idea. I'm not sure about using a flat random distribution, though: probably better to pick the value from a distribution that approximates the data, no?
Comment: Yes, that's what I did in the example.
Answer: Doug Zare's suggestion is a little like a missing data technique called multiple imputation.  The data point gets repeated many times with plausible values for the missing variable being input.  I think that would allow the classifier to gain the information from the correct coordinate and in a way learn the uncertainty from the missing one.  The tree classifiers can handle missing data with surrogate variables (i.e. using a replacement variable that is known to be highly correlated with the one that is missing).


How to get a route param

Question: This is how my router looks like:
export default new VueRouter({
    mode: 'history',
    routes: [

        /**
         * Authentication
         */

        {   name: 'login',
            path: '/',
            component: Login,
            guest: true
        },

        {   name: 'registration',
            path: '/registreer',
            component: Registration,
            guest: true
        },

        /**
         * Forum
         */

        {   name: 'forum',
            path: '/forum',
            component: Forum,
            auth: true
        },
    ]
});

Now I would like to get the auth value when I go to /forum. How do I get that value? I can't find anything in the docs.
Already tried this:
router.beforeEach((to, from, next) => {
    console.log(to.auth);
    next()
});

But nothing show up, only undefined.
Any ideas?
Comment: You'll need to iterate over [matched routes](https://router.vuejs.org/en/advanced/meta.html).
Comment: you cannot set keys like you want .. use meta : {auth:true}
Answer:
This is a good use case for Vuex - https://vuex.vuejs.org/en/intro.html
Vuex allows you to maintain the state of the application, and also store various API responses so that you do not have to reload the same data in other components.
In your specific case, your forum component can check the Vuex state if auth is available (this can be done in created or mounted handler). If auth is not available, then you should immediately re-route to auth page using this.$router.replace("/login")
In your auth component or login component, you can do the authentication normally. Once the user login is successful, you can store the server response in this.$store.state["auth"] - the Vuex state that is available globally for all components. This can be done as follows (as a mutation in Vuex store):
Vue.set(state, "auth", currentUserDetailsObject)

Afterwards, you may redirect to forum component, where auth is available in this.$store.state and therefore forum may proceed to display the component normally.
You may need some ramp-up time to get used to the concepts of actions and mutations, but you will find it very helpful for the rest of your app, once you get used to it.
Answer:
I think you could find what you want here.
And you probably want to know about Vuex.
Then you can write code like this.
if (!store.getters.auth) {
    next({
        path: '/login',
        query: {redirect: to.fullPath}
    })
}

How to get a route param


R find key influencers

Question: In Excel's data mining tools there is a "Key Influencers" tool which will look at a dataset which is perhaps customers and whether or not they converted to a given goal (e.g. a flag that equals 1). It then tells you the most influential factors in reaching that goal,( e.g. Gender=Male and Age=30-45). What would be equivalent algorithm in R to achieve a similar outcome.
Comment: What approach does the excel command use? That might be useful to know.
Comment: My guess is it's really something pretty ad hoc, like finding those variables having a correlation with the outcome variable greater than some threshold such as 0.5. It seems like trying to duplicate something Excel does in R is kind of an empty cause: it's so easy to do something much better.
Answer: The algorithm used in the "Analyse Key Influencers" tool in excel is a variation on the Naive Bayesian algorithm for classification.  The explanation from Microsoft may be found here:
http://msdn.microsoft.com/en-us/library/dn282341.aspx
The naive Bayes algorithm has been implemented in several packages, though most notably the e1071 package by David Meyer.  It can be found on CRAN and a decent tutorial on implementing the algorithm may be found here:
http://en.wikibooks.org/wiki/Data_Mining_Algorithms_In_R/Classification/Na%C3%AFve_Bayes
I would caution you to ensure that your predictor variables are independent and to avoid multicollinearity in your models, as the algorithm ignores dependencies and is thus "naive" or "stupid".
Comment: If Naive Bayes was an option then logistic regression is a better one, with weaker requirements and no pesky conditional independence assumption.
Comment: Multicollinearity is still a problem with logistic regression!

R find key influencers


SmartGWT Live Grid (with iBATIS)

Question: I didn't find any docs about how to convert a SmartGWT ListGrid in a Live Grid. How can I do it? Is the ListGrid a Live Grid by default? If so, how can I disable this feature?
Finally: I have to provide a DataSource for the Grid. My app uses iBATIS in the server-side, using GWT-RPC. How can I provide the data to the Live Grid and let it manage the data to be fetched?
Answer: You don't have to change anything on your ListGrid, your DataSource which is bound to your ListGrid has to send the startrow and endrow parameter and then your backend has to return the appropriate data.
You can the see if the parameters are send in firebug, if they aren't send, just call setSendMetaData(true) on your DataSource
I don't have any knowledge with iBatis so I can't answers that part of the questions

SmartGWT Live Grid (with iBATIS)