Weaker version of Cauchy sequence criteria

Question:
Possible Duplicate:
Why doesn't $d(x_n,x_{n+1})\rightarrow 0$ as $n\rightarrow\infty$ imply ${x_n}$ is Cauchy?

my question is this:

The following definition is weaker than the definition of Cauchy sequences:
$\forall \; \epsilon > 0, \;\exists N \in \mathbb{N} \;s.t.\; \forall\; n \geq N, \; |a_{n+1}-a_n | < \epsilon.$
Show that this is not equivalent to $(a_n)$ being a Cauchy sequence.

The definition of Cauchy sequence is:
A sequence $(s_n)$ is Cauchy if (and only if) for each $\epsilon > 0$ there exists an integer $N$ with the property that $|s_n-s_m| < \epsilon$ whenever $n\geq N$ and $m \geq N$.
Note that a sequence (of real numbers) is convergent if and only if it is Cauchy.

So I see an (the?) obvious difference between these two in that the Cauchy criteria demands that all values in a sequence above a certain index ($N$) are within a prescribed tolerance of each other, whether adjacent or not. This is where the question is weaker, in that it only requires the immediately adjacent values of the sequence to be within a tolerance of $\epsilon$. This would then allow, by taking successive differences of adjacent values, to accumulate a difference greater than $\epsilon$. This is seen as,
$$\left| \sum_{i=1}^{n+1}\,a_i - \sum_{i=1}^{n}\,a_i\right| < \epsilon,\quad
\left|\sum_{i=1}^{n+2}\,a_i - \sum_{i=1}^{n+1}\,a_i\right| < \epsilon,\quad
\left| \sum_{i=1}^{n+3}\,a_i - \sum_{i=1}^{n+2}\,a_i\right| < \epsilon,$$
and summing each side of the inequalities gives (after reverting to sequence-notation and employing the triangle inequality),
$$
\left(|a_{n+1}-a_n| + |a_{n+2}-a_{n+1}| + |a_{n+3}-a_{n+2}| + \cdots + |a_{K} - a_{K-1}| \right) \leq \left( \epsilon_{1,2} + \epsilon_{2,3} + \epsilon_{3,4} + \cdots + \epsilon_{K-1,K} \right)
$$
which implies
$$\left( \epsilon_{1,2} + \epsilon_{2,3} + \epsilon_{3,4} + \cdots + \epsilon_{K-1,K} \right)_{\textrm{ by weaker criteria }}   \geq |a_n - a_{n+K}|_{\textrm{ by Cauchy criteria }}$$
If I understand these differences correctly, then my main problem is putting these into a formal mathematical proof. Unless this would qualify?
Thanks much for the help and the site!
Comment: Exact Duplicate: http://math.stackexchange.com/q/107336/21436
Answer: Your analysis is sound: though differences between neighbours may be ultimately small, these differences can build up. However, they do not need to build up: after all, there are Cauchy sequences.  So the analysis has to be used to generate specific situations in which the differences do build up, or at least to prove less directly that this can happen.
We exhibit a sequence that satisfies the "weaker" condition and is not Cauchy.   The following example is not mine, it was given on MathSE in the fairly recent past.
Look at the sequence
$$0, \tfrac{1}{2}, 1, \tfrac{2}{3}, \tfrac{1}{3}, 0, \tfrac{1}{4}, \tfrac{2}{4}, \tfrac{3}{4}, 1, \tfrac{4}{5}, \tfrac{3}{5}, \tfrac{2}{5}, \tfrac{1}{5}, 0, \tfrac{1}{6}, \tfrac{2}{6}, \tfrac{3}{6}, \tfrac{4}{6}, \tfrac{5}{6}, 1, \tfrac{6}{7} \dots$$
(we are travelling back and forth between $0$ and $1$, and each round uses smaller and smaller steps).
The above sequence satisfies your condition: After a while, any two consecutive terms are very close to each other.  But the sequence is clearly not Cauchy.  It is clear how in this example small differences do build up.
Comment: @nate: Giving a counterexample may not be the only way. Usually, one shows that $A$ is a *proper* subset of $B$ by exhibiting an object which is in $B$ but not in $A$.  But it is possible to imagine a highly indirect proof.  There are some famous such proofs, particularly in Graph Theory.  For simplicity, I will give an example that is actually phony, but may be familiar to you. Cantor proved that the reals have uncountable cardinality, and that the set of algebraic numbers is countable. So there exist transcendental numbers.
Comment: Hmmm... Nice example. I also knew of $1+1/1 + 1/2 + 1/3 + 1/n $ as a sequence of partial sums. I guess I do not understand why my reasoning does not prove they are not equivalent. Also, is providing a counter-example the _only_ way one would prove they are not equivalent?  Thanks and (Thanks also @Jasper)
Comment: I am very interested in this indirect proof - it is very interesting, but have no experience at all in graph theory. I do have some experience with Cantor sets though and will think about this some more. Thanks all and sorry for the duplicate - I missed the above previous question.
Comment: @nate: For genuine and important examples, I was thinking of the [Probabilistic Method] in graph theory. The link will supply some information.
Comment: Thank you for the reference to graph theory @Andre, I am taking it next semester!
Answer: Showing that the sum of the epsilons is possibly greater than the single epsilon in the supposedly stronger form does not prove the two forms are not equivalent. What you need is a counterexample.
The sequence $(1,1+\frac{1}{2},1+\frac{1}{2}+\frac{1}{3},\ldots)$ does not converge in $\mathbb R$ and so is not Cauchy. Yet it satisfies the weaker criterion.
Comment: That was the one I was thinking of. (+1)
Answer: Your intuition and argument are correct as far as they go, but note that you've only shown that the Cauchy condition is at least as strong, not strictly stronger. You can show "strictly stronger" by finding a counterexample, or by finding a property that all Cauchy sequences have and the weaker formulation doesn't have. A counterexample is probably easier to come by. Think about how this could happen. Can you think of a function $f$ defined for $x>0$ (hence, it is defined for each $n = 1, \; 2, \; 3,\;...$) that approaches $\infty$ as $x \rightarrow \infty$ (hence, $f(n) \rightarrow \infty$ as $n \rightarrow \infty$), but it does so in such a way that its everywhere positive slope approaches $0$ as $x \rightarrow \infty$ (thereby ensuring that $f(n+1) - f(n) \rightarrow 0$)? More specifically, think about how $f(x) = \log x$ or $f(x) = \sqrt x$ could help in light of what I've said.


O que é e como funciona o Bootstrap?

Question: Dei uma pesquisada, mas a maioria dos artigos que achei partem do pressuposto de que o leitor já tem alguma familiaridade com frameworks (o que não é meu caso), que ainda tenho só uma vaga ideia do que seja isso (é tipo um template né?).
Pelo que entendi, é um conjunto predeterminado de CSS e JavaScript, mas não existe nenhuma tela de configuração que pode ser aberta no navegador, nem nada assim né? É apenas uma reunião de modelos CSS e JavaScript?
Precisa instalar alguma coisa, ou é só descompactar a pasta no diretório do projeto e linkar com rel= "stylesheet" o arquivo bootstrap.css entre as tags head?
Já tenho um arquivo CSS em que estou colocando minhas formatações, isso é compatível com o Bootstrap? Tentei utilizar assim:
<link rel="stylesheet" href="bootstrap-3.3.4-dist/css/bootstrap.css"/>
<link rel="stylesheet" href="_css/form2.css"/> // meu aquivo de formatação

Mas ele só zoou o layout. Tirando o meu arquivo de css (form2.css) ele ficou sem formatação nenhuma, bem basicão mesmo (mas diferente do que se retirar o link pro bootstrap, o que indica que está funcionando né?), nada perto do exemplo que vi (e que não estou achando de novo, se achar posto aqui). Meu interesse é porque estou desenvolvendo um grande formulário, e vi um  desenvolvido com ele que achei muito legal, principalmente os estilos dos campos input etc.
Os campos do formulário são automaticamente modificados com o Bootstrap, ou precisarei editar todas as tags do HTML pra aplicar as formatações que quiser?
Eu estou utilizando JavaScript para algumas funções como exibir/ocultar campos do formulário. Isso é compatível com o bootstrap?
Bom, não sei se é amplo demais, ou se já pode existir uma pergunta assim por aqui (o que não achei), mas se alguém puder me ajudar a entender como funciona, e se é incompatível com outros scripts e arquivos CSS já está ótimo.
Comment: Impressionante, todas as respostas foram excelentes, e estão ajudando muito. Pra evitar poluir o tópico com muitos agradecimentos, vou estender aqui a todos os que responderam meu mais sincero agradecimento. Quando tiver acabado de implementar colocarei o sinal de resolvido na resposta que mais tiver me ajudado, ou se demorar demais pra eu acabar (provável), talvez coloque o sinal de solucionado na resposta que tiver recebido mais votos da comunidade depois de um tempinho (mas vou conferir ainda se isso é certo). Muito obrigado mesmo à todos!
Answer: Bootstrap é um framework front-end, explicando a grosso modo, ele te provê componentes front-end (css, sass, less e js) prontos pra você utilizar na sua aplicação.
O Bootstrap depende, basicamente, de 2 arquivos:

bootstrap.css.
bootstrap.js.

O bootstrap.js é baseado em jQuery, então pra ele funcionar você precisa ter o jQuery incluído no seu projeto também. Veja aqui, um exemplo do uso de um modal e de um alert simples.
Respondendo suas perguntas:
Possui alguma tela de configuração?
Por se tratar de um framework front-end (visualização) não há algo que você possa "editar"/"mudar a configuração", customizações devem ser feitas em outros arquivos que sobrescreverão os estilos padrão (você também, pode gerar seu estilo Bootstrap customizado no próprio site do Bootstrap, ou então, no Bootstrap Magic). Inclusive, você encontra diversos frameworks Bootstrap totalmente customizados, como o Flat UI, Get Sh*t Done e Bootflat.
Formulários
O Boostrap possui muitas classes css que tornam o desenvolvimento dum formulário (pequeno ou grande) muito mais rápido, por exemplo:
<form>

        Nome
        <input id="textinput" name="textinput" type="text" placeholder="Digite seu nome" class="form-control">

        <button id="button1id" name="button1id" class="btn btn-success">Enviar</button>
        <button id="button2id" name="button2id" class="btn btn-danger">Cancelar</button>

</form>

Exemplo no JSFiddle.
Neste código você pode notar algumas classes: form-group e form-control, elas são as classes, digamos que básicas de cada formulário, a form-control estiliza seu input (text, password, email, date, ...). Enfim, o Bootstrap tem MUITA COISA que vai te ajudar, você pode ver várias delas na página de exemplos do site.
Ok, mas as pessoas usam o Bootstrap só por isso?
NÃO! Eu costumo dizer que pra qualquer coisa que você precise fazer já existe um plugin ou biblioteca Bootstrap customizada que faz, duvida? Dá uma olhada nessa lista de recursos já prontos. E não é só isso:

Bootstrap é fácil de se começar a usar.
Um ótimo sistema de grids.
A já citada nas suas dúvidas, estilização de componentes HTML (botões, tipografia, formulários, ícones, tabelas, etc).
MUITOS componentes.
Já contém alguns plugins javascript (modal, dropdown, popover, etc).
Possui uma comunidade gigantesca.

Desculpa, me empolguei :).
Comment: Todas as respostas desta pergunta me ajudaram bastante, e o formulário está ficando outra coisa, mas coloquei o resolvido na sua porque além de ter falado sobre especificamente sobre formulários, foi quem mais me empolgou a mudar umas muitas e muitas de linhas de `tables` por `divs`. :-)
Answer: ...é tipo um template né?
É um pouco mais do que isso. É um template que te força a trabalhar num determinado nível de disciplina, de forma a exibir seu site em praticamente qualquer dispositivo com qualquer tamanho de tela.
Pelo que entendi, é um conjunto predeterminado de CSS e javascript, mas não existe nenhuma tela de configuração que pode ser aberta no navegador, nem nada assim né? É apenas uma reunião de modelos CSS e Javascript?
Pode ser definido assim, como "um conjunto predeterminado de CSS e JavaScript", mas que possui normas para uso. A configuração é feita utilizando um pré-processador chamado LESS.
Precisa instalar alguma coisa, ou é só descompactar a pasta no diretório do projeto e linkar com rel= "stylesheet" o arquivo bootstrap.css entre as tags head?
Não é apenas isso. O roteiro de instalação recomenda você usar uma ferramenta de pacotes que realiza essa configuração pra você. É possível fazer manualmente, mas envolve não apenas CSS como JavaScript e alguns arquivos auxiliares.
Os campos do formulário são automaticamente modificados com o bootstrap, ou precisarei editar todas as tags do HTML pra aplicar as formatações que quiser?
Não diria todos, mas diria que uma boa parte deles. Não é preciso editar tudo. É importante aprender como ele funciona pra depois partir pra customizações.
Eu estou utilizando javascript para algumas funções como exibir/ocultar campos do formulário. Isso é compatível com o bootstrap?
Sim.
Comment: Resposta escrita de maneira simples, mas completa e com certeza de fácil entendimento para quem está começando, só posso dizer, ótimo trabalho!
Answer: Bom, vamos por partes.

É apenas uma reunião de modelos CSS e Javascript?

Sim e não. Conforme descrição do site, o Bootstrap é voltado para prover a base para aplicações com design responsivo, mobile first. Ou seja, se você utilizar seus componentes e sistema de grids corretamente (aplicando as classes do Bootstrap e seguindo a estrutura de markup correta) sua aplicação estará pronta para funcionar em uma grande variedade de devices e navegadores (com telas dos mais diferentes tamanhos, nas mais diferentes resoluções). Além disso, como bem mencionado pelo colega Eduardo Silva, existe todo um ecossistema sendo construído em torno do Bootstrap (Temas, Templates, ferramentas para desenvolvedores, extensões de UI, plugins, etc).

Precisa instalar alguma coisa, ou é só descompactar a pasta no diretório do projeto e linkar com rel= "stylesheet" o arquivo bootstrap.css entre as tags head?

Existem várias maneiras de utilizar o Bootstrap (veja o Getting started guide). Você pode fazer o que está sugerindo ou até mesmo consumí-lo diretamente de uma CDN, e.g:
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">

Para a parte de JavaScript você também tem uma biblioteca (note que essa biblioteca depende do jQuery:

Já tenho um arquivo CSS em que estou colocando minhas formatações, isso é compatível com o bootsptrap?

É compatível, mas você deve tomar cuidado com seus estilos. Por exemplo, chumbar tamanhos pode tirar a flexibilidade de determinados componentes.

Os campos do formulário são automaticamente modificados com o bootstrap, ou precisarei editar todas as tags do HTML pra aplicar as formatações que quiser?

Você deve aplicar as classes. O site do Bootstrap tem um showcase com exemplos de todos os componentes.

Eu estou utilizando javascript para algumas funções como exibir/ocultar campos do formulário. Isso é compatível com o bootstrap?

Sim, JavaScript, jQuery, etc. Tudo é permitido. Valem, porém, as mesmas restrições do que para CSS. Esconder determinado componente ou mudar suas propriedades dinamicamente pode eventualmente bagunçar o layout sob determinadas condições. É sempre bom testar o resultado contra todas as combinações de devices e navegadores que sua aplicação deve suportar.
Answer: O bootstrap é uma coleção de arquivos js, css/less/sass entre outros, que tem como objetivo te dar um ponto de partida pro seu layout.
Não é um template, a ideia do bootstrap não é adicionar um visual único ao seu projeto, mas evitar que você tenha o trabalho de criar coisas que quase todo site precisa.
Um bom exemplo são as funcionalidades para auxiliar no desenvolvimento de um site responsivo, eu explico elas nessa resposta.
A maior parte das funcionalidades do bootstrap esta nas classes pré definidas, a ideia é você utilizar elas.
Para personalizar o bootstrap, existem diversos modos. O método mais simples é esse que você esta usando, incluir o css minificado e ter um arquivo css seu com seus estilos específicos. O método que eu prefiro é clonar o repositório do bootstrap e editar os arquivos Less, Less é uma linguagem que pré processa CSS, é bem parecido com css só que te deixa fazer mais coisas, por exemplo definir funções(se chamam de mixins no Less).
Eu pessoalmente não utilizo a parte javascript pois prefiro fazer essa parte eu mesmo e separado.
Pense no bootsrap como uma caixa de ferramentas, você pode pegar só as ferramentas que precisa, mas sempre vai ter de estudar um pouquinho pra entender como elas funcionam.
Quanto às outras perguntas:
Caso você utilize apenas o CSS compilado, não precisa instalar nada.
Para adicionar o estilo do bootstrap, você tem de usar as classes predefinidas dele, no caso de inputs, selects,textareas, etc a classe é .form-control .
Eu acho pouco provável que suas funções javascript pessoais deem conflito com as do bootstrap, mas é possível que aconteça.
Answer: O Bootstrap é, como qualquer framework de front-end, uma biblioteca que minimiza o trabalho de codificação na criação de páginas, com elementos estilizados e melhorados, assim como componentes reutilizáveis (ícones, alertas, navegação). É muito útil, pois começar do zero significa escrever muito código trivial, porém extenso e trabalhoso. Além disso, como o Bootstrap foi criado por uma empresa grande como o Twitter e é opensource, seus componentes, tanto na parte de programação quanto design serão muito superiores ao que qualquer um seria capaz de escrever sozinho.
Sugiro também dar uma olhada em outros frameworks, já que você vai começar agora: Semantic UI e Foundation.
A documentação do Bootstrap é muito completa e tem tudo o que você precisa pra implementá-lo. A coisa mais importante pra um desenvolvedor é saber se virar sozinho, e ter uma documentação completa como essa é uma benção.

Precisa instalar alguma coisa?
Existem várias formas de começar a usar o Bootstrap: referenciando os arquivos locais pré-compilados após baixá-los, compilando o código-fonte em Sass ou Less, usando o gerenciador de pacotes Bower ou npm... Essas formas estão todas descritas em Getting Started.
No entanto, a maneira mais fácil de fazê-lo é simplesmente referenciar os arquivos hospedados numa CDN, assim:

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

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

Bootstrap é compatível com meu CSS antigo?
Você precisará fazer mesmo algumas adaptações, pois o framework pré-define estilos para muitas tags. O trabalho necessário pra isso vai depender muito se os seus seletores conflitam com os dele. Pra alguém que está começando agora, sugiro reestruturá-lo com o poderoso Grid system. Suas estruturas de layout anteriores (sejam feitas usando
 ou flexbox) parecerão amadoras perto do que ele é capaz de fazer.
Nessa fase de transição, sugiro usar extensivamente o Web Inspector do seu navegador pra entender e resolver os conflitos do seu CSS com o Bootstrap.
Bootstrap é compatível com meu Javascript antigo?
Acredito que você não vá ter problemas com isso.
Os campos de formulário são automaticamente modificados?
Não. É necessário definir as classes de acordo com o layout de formulário desejado. A documentação cobre esse e qualquer outro assunto de maneira extensiva e precisa.
Answer: Pergunta 1:
O Bootstrap é um framework de CSS que utiliza HTML5, CSS3 e JavaScript.
O que deve estar acontecendo com o seu formulário é a sobreposição de CSS.
Utilize o Bootstrap.css como CSS principal e se precisar de customizar algo que já não esteja no Bootstrap vc faz no seu (form2.css). Veja se o seu CSS tem formatação para inputs, tire e deixe esta formatação para o Bootstrap.
Pergunta 2:
Sem problemas pode usar Javascript para qq coisa.
Você pode dar uma olha no Bootstrap da Globo.com.
Dica: use o obejct inspector (tecla [F12]) do seu browser para ver como o  tag Bootstrap foi construído.
Globo.com http://globocom.github.io/bootstrap/

O que é e como funciona o Bootstrap?


Converting Large Decimal Numbers to Octal and Binary

Question: I have large numbers that I need to convert to Octal and Binary systems. Examples of numbers that I am working with are $10^{10}$, $10^{20}$, $10^{30}$ ... (powers of 10) and numbers that are multiplied by $10^n$ for example $123.175*10^{31}$ and so on. Is there an efficient way (NOT Successive division) to do such a task?
Answer: It's not successive division that you have to do in this case, but successive multiplication, which is somewhat simpler. For example, to evaluate $123.175\times 10^{31}$ in binary, start with $123175$ and multiply it by $10$ $28$ times. Using a computer, so the answer will already be in binary :-)
You can make this faster if you want by multiplying by larger powers of $10$ at each step. The best power of $10$ to use depends on your machine architecture.
For numbers this small, this is the fastest solution. For much larger numbers, you will want to use Fast Fourier Transforms, but that is another chapter.
Answer: Once you have the octal representation of a number, it's easy to convert to binary, because each of the $8$ possible octal digits can be mapped to a string of $3$ binary digits. To convert the result of a calculation into the octal system, I instead suggest to convert the numbers before the calculation and calculate in the octal system. You will need some procedure to multiply (large) octal numbers, but you only need to convert small decimal numbers (like $123.175$ or $10$) to the octal system. To get the octal representation of $10^{31}$, convert $10$ to the octal system and note that
$$10^{31} = 10^{1+2+4+8+16} = 10^{1}\cdot10^{2}\cdot10^{4}\cdot10^{8}\cdot10^{16}$$
Also:
$$10^2 = 10 \cdot 10, \quad 10^4 = 10^2 \cdot 10^2, \quad 10^8 = 10^4 \cdot 10^4 \quad\text{and}\quad 10^{16} = 10^8 \cdot 10^8$$
Splitting the powers of $10$ this way, you can reduce the number of multiplications. Of course, you will need a method to calculate the binary representation of the exponent... :-)


Nonexistence of certain holomorphic function with periodicity

Question: Sorry lads, but my analysis is long in the past...
Given a lattice $\Gamma$ in the complex plane (or more generally: in a complex vector space $V$), why does there not exist a holomorphic function $f$ on the whole plane (or $V$) which satisfies:
$f(z+\gamma)=f(z)-\bar{\gamma}$
for all $z \in \mathbb C$ (or $V$) and $\gamma \in \Gamma$ ?
(here $\bar{\gamma}$ denotes the complex conjugate).
Comment: How about $f(z) = \sin z - z$, with $\gamma=2\pi$?
Comment: Oh..... "lattice" must have meant having two periods that are linearly independent over $\mathbb{R}$.
Comment: Yes, that's a lattice.
Comment: What do you take a lattice in a general complex vector space to mean here? Would $\{(2\pi a, 2\pi b)\mid a,b\in\mathbb Z\}\subseteq \mathbb C^2$ qualify?
Comment: A subgroup generated by a real basis of $V$. Just look at a complex tours e.g.
Answer: Assume there exists such a function $f.$
Recall that any entire function $g:\mathbb{C} \rightarrow \mathbb{C}$ satisfying the equation $g(z + \omega) = g(z)$ for all $\omega \in \Gamma$ is constant. And observe that the derivative of $f$ is of this form. It follows $f(z) = az +b \text{ for }a,b \in \mathbb{C}.$
But then
$$a(z + \gamma) + b = az + b - \overline{\gamma}$$ for all $\gamma \in \Gamma.$
Hence, $-a\gamma = \overline{\gamma}$ for all $\gamma \in \Gamma.$ As the $\mathbb{R}$-span of $\Gamma$ is equal to $\mathbb{C}$ and complex conjugation and complex multiplication are both $\mathbb{R}$-linear, it follows that multiplication by $-a$ and complex conjugation are equal as automorphisms of $\mathbb{C}.$ But the former is holomorphic and the latter is not. This is a contradiction. It follows no such function $f$ exists.
Answer: Assume without loss of generality that $1\in\Gamma$. (Otherwise just replace $f$ with $g(z)=f(\gamma z)/\bar\gamma$ for some nonzero $\gamma\in\Gamma$).
Let $\gamma$ be any lattice point, and integrate $f$ around the parallelogram $0\to\gamma\to1+\gamma\to1\to0$. The terms that involve $f$ cancel due to the periodicity, and the result ends up being just $\gamma-\bar\gamma$. This is twice the imaginary part of $\gamma$, which is nonzero for at least some lattice points -- but if the integral around a closed curve is nonzero, then $f$ cannot be entire.


Can't find apache error logs

Question: It seems my server doesn't have error logs . i can't find them anywhere . in info.php file there is no mention about any error log.
 I tried commands like pico /usr/local/apache/logs/error_log ,but of course,no results.
  How can i find the apache error logs and view them ?
thanks for the help
Comment: On CentOS it should be /var/log/httpd/error_log and /var/log/httpd/access_log
Comment: this is a perfect question for Google I think :-)
Comment: ok, to help you a little bit: http://www.cyberciti.biz/faq/apache-logs/ ;-)
Comment: thanks,but i already tried that. nothing happens. maybe i do something wrong..i am a newbie ..
Comment: find your httpd.conf and try: grep 'ErrorLog\|CustomLog' httpd.conf
Comment: and if you don't know where it is, try: find / -name httpd.conf -exec grep 'ErrorLog\|CustomLog' {} \;
Comment: also you can tell what's your OS/distro and what type of Apache you use (from distribution/tarball/xampp etc.)
Comment: when running the command i get ' No such file or directory'
Comment: try the second one...
Comment: id did  .after i login as root,i typed that command,the second one,but i still get no such file or directory i have  CentOS 5.5-64
Comment: Or maybe your server really doesn't have logs... You can try: grep 'ErrorLog' /etc/httpd/conf/httpd.conf to see if it's set there or not
Comment: hmm not working,i get no such file or directory. and that command gives no results..nothing happens .do i have to do anything else ? i just typed what you gave me
Comment: Do you really have Apache installed on the machine?
If yes, there should be httpd.conf somewhere. You can find it with: find / -name httpd.conf , preferably executed with root privileges (i.e. sudo)
Comment: ok,i see DEFAULT_ERRORLOG="logs/error_log" when i run httpd -V i run pico(or nano) /var/logs/error_log ,it opens it,but with nothing in it thanks for the help,really amazing help :)
Answer: Default apache error log location, by distro's:
RHEL / Red Hat / CentOS / Fedora - /var/log/httpd/error_log
Debian / Ubuntu - /var/log/apache2/error.log
FreeBSD - /var/log/httpd-error.log
To find exact apache error log file location, you can use grep command:
<code># grep ErrorLog /usr/local/etc/apache22/httpd.conf
# grep ErrorLog /etc/apache2/apache2.conf
# grep ErrorLog /etc/httpd/conf/httpd.conf
</code>
Sample output:
<code># ErrorLog: The location of the error log file.
# If you do not specify an ErrorLog directive within a
ErrorLog "/var/log/httpd-error.log"
</code>
Source.
Answer: To add what is already given, you can try this (if you are not sure what distro you are running):
<code>[root@centos ~]# httpd -V
Server version: Apache/2.2.3
Server built:   May  4 2011 06:51:15
Server's Module Magic Number: 20051115:3
Server loaded:  APR 1.2.7, APR-Util 1.2.7
Compiled using: APR 1.2.7, APR-Util 1.2.7
Architecture:   32-bit
Server MPM:     Prefork
  threaded:     no
    forked:     yes (variable process count)
Server compiled with....
 -D APACHE_MPM_DIR="server/mpm/prefork"
 -D APR_HAS_SENDFILE
 -D APR_HAS_MMAP
 -D APR_HAVE_IPV6 (IPv4-mapped addresses enabled)
 -D APR_USE_SYSVSEM_SERIALIZE
 -D APR_USE_PTHREAD_SERIALIZE
 -D SINGLE_LISTEN_UNSERIALIZED_ACCEPT
 -D APR_HAS_OTHER_CHILD
 -D AP_HAVE_RELIABLE_PIPED_LOGS
 -D DYNAMIC_MODULE_LIMIT=128
 -D HTTPD_ROOT="/etc/httpd"
 -D SUEXEC_BIN="/usr/sbin/suexec"
 -D DEFAULT_PIDLOG="run/httpd.pid"
 -D DEFAULT_SCOREBOARD="logs/apache_runtime_status"
 -D DEFAULT_LOCKFILE="logs/accept.lock"
 -D DEFAULT_ERRORLOG="logs/error_log"
 -D AP_TYPES_CONFIG_FILE="conf/mime.types"
 -D SERVER_CONFIG_FILE="conf/httpd.conf"
</code>
Note DEFAULT_ERRORLOG line.

Can't find apache error logs


ownCloud WebDAV interface seems to be broken

Question: I've been trying to host ownCloud on my server but everytime I try to it tells me this :
Your web server is not yet properly setup to allow files synchronization because the WebDAV interface seems to be broken.

Please double check the installation guides.

This is my setup :
Windows Server 2012 R2
IIS 8.5
PHP 5.5.11
ownCloud 6.0.3
MySQL 5.6.17

I tried google the error but I can't seem to find anything usefull.
Some say I should try if this works :
https://cloud.mcsoftworks.net/remote.php/webdav/
and yes I can navigate to this folder and I can open files from there.
The calendar works and I can also just upload files from here https://cloud.mcsoftworks.net/ the only thing that doesn't seem to work is the sync client.
The sync client doesn't say anything it just doesn't connect (Screenshot : http://prntscr.com/3p2apz)
This is the error log :
Warning     core    isWebDAVWorking: NO - Reason: [CURL] Error while making request: Could not resolve host: cloud.mcsoftworks.net (error code: 6) (Sabre_DAV_Exception)    2014-06-02T19:56:00+00:00
Warning     core    isWebDAVWorking: NO - Reason: [CURL] Error while making request: Could not resolve host: cloud.mcsoftworks.net (error code: 6) (Sabre_DAV_Exception)    2014-06-02T19:55:47+00:00
Warning     core    isWebDAVWorking: NO - Reason: [CURL] Error while making request: Could not resolve host: cloud.mcsoftworks.net (error code: 6) (Sabre_DAV_Exception)    2014-06-02T19:55:34+00:00
Warning core    isWebDAVWorking: NO - Reason: [CURL] Error while making request: Could not resolve host: cloud.mcsoftworks.net (error code: 6) (Sabre_DAV_Exception)    2014-06-02T19:55:34+00:00
Fatal   webdav  Sabre_DAV_Exception_Forbidden: Path does not exist, or escaping from the base path was detected 2014-06-02T19:54:37+00:00
Fatal   webdav  Sabre_DAV_Exception_Forbidden: Path does not exist, or escaping from the base path was detected 2014-06-02T19:54:36+00:00
Fatal   webdav  Sabre_DAV_Exception_Forbidden: Path does not exist, or escaping from the base path was detected 2014-06-02T19:54:36+00:00
Fatal   webdav  Sabre_DAV_Exception_Forbidden: Path does not exist, or escaping from the base path was detected 2014-06-02T19:54:36+00:00
Warning core    isWebDAVWorking: NO - Reason: [CURL] Error while making request: Could not resolve host: cloud.mcsoftworks.net (error code: 6) (Sabre_DAV_Exception)    2014-06-02T19:51:24+00:00

This is my php.ini : http://pastebin.com/es3MB8Uh
Does anyone have any idea on how I should get this to work?
I've been trying to get this to work for about 14 days now and it starts to annoy me =P
UPDATE :
Okay so today I installed the newest version of the client on my PC and this client returned an error I think the other client just didn't show this error but the error is :
Error downloading [hostname]/remote.php/webdav/- server replied : Method Not Allowed
http://prntscr.com/3p9dx1
LOG FILE UPDATE:
Fatal   webdav  Sabre_DAV_Exception_Forbidden: Path does not exist, or escaping from the base path was detected 2014-06-03T13:40:17+00:00
Fatal   webdav  Sabre_DAV_Exception_Forbidden: Path does not exist, or escaping from the base path was detected 2014-06-03T13:40:17+00:00
Fatal   webdav  Sabre_DAV_Exception_Forbidden: Path does not exist, or escaping from the base path was detected 2014-06-03T13:40:16+00:00
Fatal   webdav  Sabre_DAV_Exception_Forbidden: Path does not exist, or escaping from the base path was detected 2014-06-03T13:40:15+00:00
Fatal   webdav  Sabre_DAV_Exception_Forbidden: Path does not exist, or escaping from the base path was detected 2014-06-03T13:39:28+00:00
Fatal   webdav  Sabre_DAV_Exception_Forbidden: Path does not exist, or escaping from the base path was detected 2014-06-03T13:39:24+00:00
Fatal   webdav  Sabre_DAV_Exception_Forbidden: Path does not exist, or escaping from the base path was detected 2014-06-03T13:30:32+00:00
Fatal   webdav  Sabre_DAV_Exception_Forbidden: Path does not exist, or escaping from the base path was detected 2014-06-03T13:30:31+00:00
Fatal   webdav  Sabre_DAV_Exception_Forbidden: Path does not exist, or escaping from the base path was detected 2014-06-03T13:30:31+00:00
Warning core    isWebDAVWorking: NO - Reason: [CURL] Error while making request: Could not resolve host: cloud.mcsoftworks.net (error code: 6) (Sabre_DAV_Exception)    2014-06-02T20:09:05+00:00
Error   PHP Undefined index: accessclass at D:\Websites\MCS-oCloud\apps\calendar\lib\object.php#889 2014-06-02T20:02:16+00:00
Warning core    isWebDAVWorking: NO - Reason: [CURL] Error while making request: Could not resolve host: cloud.mcsoftworks.net (error code: 6) (Sabre_DAV_Exception)    2014-06-02T19:56:07+00:00
Warning core    isWebDAVWorking: NO - Reason: [CURL] Error while making request: Could not resolve host: cloud.mcsoftworks.net (error code: 6) (Sabre_DAV_Exception)    2014-06-02T19:56:00+00:00
Warning core    isWebDAVWorking: NO - Reason: [CURL] Error while making request: Could not resolve host: cloud.mcsoftworks.net (error code: 6) (Sabre_DAV_Exception)    2014-06-02T19:55:47+00:00

Comment: Don't forget to check the handlers for WebDAV and delete it, I still had problems until I did that.
Answer: The most likely reason for this error is that your server cannot communicate with itself.  This could be because your router does not have NAT reflection so your server cannot communicate with itself on its public IP.  Try adding a cloud.mcsoftworks.net pointing to 127.0.0.1 in your hosts file (or your internal DNS if you have) so that the server knows to contact itself instead of going out on the Internet.
Alternatively, this could be because your server is not allowing the WebDAV HTTP Verbs through to PHP.  See the OwnCloud setup guide for instructions on making sure these settings are set up properly.

As discussed in the OwnCloud forum, the OwnCloud sync client also does not necessarily work with self-signed certificates.  Try switching to HTTP temporarily and see if that works.  (However, others have gotten self-signed certififcates to work with no problem, and the error you are receiving does not say that this is the issue despite the fact that the symptoms are the same.)
You may also just be having an issue where WebDAV is working properly but the tests are failing, thus preventing WebDAV from working.  You can bypass the WebDAV tests in the admin site by adding check_for_working_webdav=false to the config.php file.
Comment: Okay I just added cloud.mcsoftworks.net to my hosts file and the server is now rebooting. I already changed the HTTP Verb to all quite some days ago. I will comment if it worked soon.
Comment: :( It didn't work I also tried without SSL and this also didn't work.
Just before I changed it to http it did came up with an error 405 method not allowed.
Comment: @Nobleleader13245 the only way I know of to get a 405 is if the verbs are set wrong.
Comment: I did enable these verbs this is what I did : http://prntscr.com/3p320c
Comment: @Moshe_Katz It still doesn't seem to work :(
Answer: Okay, I found out what the problem was.
in the IIS 8.5 manager there is a tab called modules if you open that it displays tons of modules search for WebDavModule and delete it.
@Moshe_Katz Thanks for the help.. it pointed me in the right direction.


SQLAlchemy how to group_by relation?

Question: Here are the models:
class User(Base):
    __tablename__ = 'users'

    id = Column(CHAR, primary_key=True)
    first_name = Column(CHAR)
    last_name = Column(CHAR)
    email = Column(CHAR)
    receive_reports = Column(Boolean)

class MailPiece(Base):
    __tablename__ = 'mail_pieces'

    id = Column(CHAR, primary_key=True)
    created_at = Column(DateTime)
    template_id = Column(CHAR, ForeignKey('templates.id'))

class Template(Base):
    __tablename__ = 'templates'

    id = Column(CHAR, primary_key=True)
    name = Column(CHAR)
    created_by_id = Column(CHAR, ForeignKey('users.id'))
    user = relationship(User, backref='templates')

I want to send to users reports with: which templates they are sent and how many mail pieces was sent for each template.
I wrote the code:
        stmt = self.session.query(MailPiece.template_id, func.count('*')
                               .label('mail_pieces_count')).filter(
            MailPiece.created_at > day_ago,
            MailPiece.created_at < now,
            ).group_by(MailPiece.template_id).subquery()

        query = self.session.query(Template, stmt.c.mail_pieces_count).\
            filter(Template.user.has(receive_reports=True)).\
            join(stmt, Template.id == stmt.c.template_id)

But this is slightly not what I wanted. I got result grouped by templates but need list grouped by users where each user will have templates. So in that way I can iterate through users list and send report to each user with summary.
Current result:
[<Template(id='123', name='Test', mail_pieces_count='123', user=<User(id=1212, first_name='Some name', last_name='Some lastname')>)>, <Template(id='456', name='Test2', mail_pieces_count='456', user=<User(id=1212, first_name='Some name', last_name='Some lastname')>)>]
Expected result:
[<User(id=1212, first_name='Some name', last_name='Some lastname, templates=[<Template(id='123', name='Test', mail_pieces_count='123')>, <Template(id='456', name='Test2', mail_pieces_count='456')>,])>]
In other words, now it can be represented like:
Current:
templates = [
    {
        "id": 123,
        "name": "Test",
        "mail_pieces_count": 123,
        "user": {
            "id": 1212,
            "first_name": "Some name",
            "last_name": "Some lastname"
        }
    },
    {
        "id": 456,
        "name": "Test2",
        "mail_pieces_count": 456,
        "user": {
            "id": 1212,
            "first_name": "Some name",
            "last_name": "Some lastname"
        }
    }
]

Expected:
users = [
    {
        "id": 1212,
        "first_name": "Some name",
        "last_name": "Some lastname",
        "templates": [
        {
            "id": 123,
            "name": "Test",
            "mail_pieces_count": 123
        },
        {
            "id": 456,
            "name": "Test2",
            "mail_pieces_count": 456
        },]
    },
]

Comment: can you add a few data records and expected result?
Comment: @Danila Ganchar question updated.
Comment: I think you might need something like [Correlated Subquery Relationship Hybrid](https://docs.sqlalchemy.org/en/latest/orm/extensions/hybrid.html) if you want `mail_pieces_count` to appear as a property of `Template`.
Answer: The reason of current output:
You build a query using Template class:
self.session.query(Template, stmt.c.mail_pieces_count)

This is the main reason why you got Template instances instead of User. Below just an example how to get expected result.

Note! I just try to explain how it works. My answer isn't related to optimization, performance etc.

# I skipped filters...
stmt = (session.query(MailPiece.template_id, func.count('*')
        .label('mail_pieces_count'))
        .group_by(MailPiece.template_id).subquery())
# to tie templates with upper subquery
stmt2 = (session.query(Template.created_by_id, stmt.c.mail_pieces_count)
         .join(stmt, Template.id == stmt.c.template_id)
         .subquery())
# User query - to tie template id with user id
query = session.query(User, stmt2.c.mail_pieces_count).join(
    stmt2,
    # you can add additional conditions into JOIN ON...
    and_(User.id == stmt2.c.created_by_id, User.receive_reports.is_(True))
)

for result in query:
    print("count: %s" % result.mail_pieces_count)
    print("user: %s" % result.User)
    print("templates: %s" % result.User.templates)

JFYI. If we look at console you will find that alchemy will do 1 query per iteration:
### one more select when you use result.User.templates
2019-02-11 13:02:24,702 INFO sqlalchemy.engine.base.Engine SELECT templates.id AS templates_id, templates.name AS templates_name, templates.created_by_id AS templates_created_by_id
FROM templates
WHERE %(param_1)s = templates.created_by_id

You can add Template into query to avoid this, but in this case you will get the number of records equal to the number of templates (not users):
stmt2 = (session.query(Template, stmt.c.mail_pieces_count)
         .join(stmt, Template.id == stmt.c.template_id)
         .subquery())
# select User and Template
query = session.query(User, Template, stmt2.c.mail_pieces_count).join(
    stmt2,
    and_(User.id == stmt2.c.created_by_id)
)

for result in query.all():
    print("user: %s" % result.User)
    print("template: %s" % result.Template)

So summarize, you need to use a specific class if you need to get instances of the class as a result:
session.query(ExpectedClass).other_methods()...

Hope this helps.
Comment: Thank you for answer. That's actually does not solve the problem described above (I wanted to get data in this way so that I can just iterate through list with `users` and be able to get templates which was sent in some time range and `mail_pieces_count` for each template) but I realized that this is not the smartest way to do what I want :D

SQLAlchemy how to group_by relation?


Travelling with electric violin under revised airport security rules

Question: In light of suspected terrorist threat airport security has been tightened to include new restrictions on "electronic devices". For example, on Heathrow Airport's site they say:

Make sure your electronic devices are charged before you travel. If your device doesn't switch on when requested, you won't be allowed to bring it onto the aircraft.

I travel with an electric violin, not so that I can rock-out during business trips but so that my practise does not disturb people in neighbouring hotel rooms since the electric violin is near-silent without an amplifier.
Will my electric violin fall foul of new airport security restrictions? If so how does one prove that an electric violin (or any other active electronic instrument) is "turned on" without an amplifier to hand?
Comment: Rather annoyingly no-one at security asked me to turn anything on: not my phone and not my laptop; so I probably could have taken my electric violin through (at least from the UK) without issue. The thing that did cause them to ask me to open up my violin case was the [metal practise mute](http://www.caswells-strings.co.uk/shop/269-tonwolf-violin.html), which looked odd on the x-ray.
Comment: My corporate travel folk (which I think Amex provides) phoned British Airways who said that as it is battery operated it falls within the new guidelines, and that if I am unable to demonstrate that it has power I will be asked to leave it behind. My current plan is to leave it at home and take my normal non-electric violin with a practice mute and save up for a non-electric 'silent' violin for next time.
Comment: Is it a possibility for a miniature amplifier to work? Such as this: http://www.musiciansfriend.com/amplifiers-effects/danelectro-honeytone-n-10-guitar-mini-amp
Answer: I doubt this will be an issue, but there are plenty of ways to connect your guitar to an mobile phone. I'm guessing the electric violin outputs the same signal, so it can be used in a guitar amplifier. If so, you could use one of those together with your smartphone, and some sort of sound will be produced. Or even simpler, use one of those portable practice devices, which are just a 1/4" plug and a small box you can connect headphones too.
Comment: Good answer but I'd rather not have to carry another thing in hand luggage purely to keep security happy.
Comment: I missed this on my first reading but I think your point about headphones holds the key. I don't even need a portable practise device, headphones will plug directly into the preamp built into my electric violin.
Comment: Plus current advice from BA is that it will be an issue :-(
Comment: @dumbledad: How is it with checked in luggage? An electric violin should be able to be safely packed and checked in. I doubt they can screen checked in luggage to that extent. Since it's a business trip you only have carry on luggage...
Comment: @dumbledad: Well, since the violin itself isn't capable of proving it is working, I don't see how it's possible to show how it works without extra paraphernalia...
Comment: Indeed.
I think checked in luggage is fine (in theory) but in practise they seem very very reluctant to check in instruments as I guess the potential for costly damage appears too high.
Answer: This security change in Airport exists because they fear that the batteries might have been replaced by explosives or that the device might be a fake one, so they ask you to switch on your electronic device in order to check that it's a real battery and a "real" working device.
Moreover, the targeted devices are mostly phones, tablets and laptops (I even read that they especially look for Samsung & Apple devices).
I guess an electric violin is quite similar to an (passive) electric guitar, so there is probably no battery on your device and not much electronics.
So you're probably okay with your instrument (regarding this specific safety rule change).
Comment: I totally agree that this should be the answer, but current advice from BA is that it will be an issue. Mad.
Comment: This is why I added "regarding this specific safety rule change", there might be A LOT of other security rules that would prevent you from doing that (I should probably add that to my answer...) but I don't really know all the rules, I never travelled to the US so I don't know how hard it is to get on those planes with any hand luggage :).
Comment: No, BA advised that regarding this specific rule change it would be an issue (though I agree with your reading of the ruling and not theirs).
Answer: I asked my friends on Facebook too and got several recommendations for miniature amplifiers like the Roland Micro Cube

the irig (though I don't use an iPhone)

or the Amplug

but then one friend pointed out that headphones suffice to demonstrate the difference between the electric violin turned off and the electric violin turned on and many of us travel with headphones in our hand luggage anyway.
Next time I'll take the electric violin again and keep some simple headphones to-hand when going through airport security.


How do I disable model validation on a single field in C# MVC?

Question: I have a view model that looks vaguely like:
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }

I have a custom ModelBinder to parse the fields in the form, and assign the values to them. Which works.
However, when an error occurs, my ModelState ends up with two errors in it. The first from my ModelBinder, and the second from (I guess) the default validation rules:
- Invalid start date selected                    <-- My custom error message.
- The value 'fgfdg' is not valid for Start Date. <-- I want this to go away

How do I turn the default validation off for a specific field, on the server side?
Edit: Before you ask, yes my ModelBinder is extending DefaultModelBinder, but obviously I need the other default model binding behaviour; it's just these fields I want a custom behavior for.
(Why don't I just use standard validation rules? Because this is a search form, and depending on if the 'custom date range' is selected, we either ignore the StartDate and EndDate, or parse and perform various checks on them. Specifically, it is an absolute requirement that if the date ranges are invalid (eg. 'fdafsfsf' for start date, but 'search by XXX' instead of 'search by date range' is selected, the form must submit successfully without error)
Code fragment:
[ModelBinderType(typeof(MyViewModel))]
public class MyViewModelBinder : DefaultModelBinder {
    public override object BindModel(ControllerContext cc, ModelBindingContext bc) {
        var model = new MyViewModel();
        var searchType = cc.HttpContext.Request["SearchType"];
        if (searchType == "CustomDateRange") {
          // Do checks here, etc.
          // ONLY if searchType == "CustomDateRange" should there be ANY validation on StartDate
          bc.ModelState.AddModelError("StartDate", "Invalid start date; outside of invoice range");
        }
        // bc.ModelState["StartDate"].Errors.Clear(); <--- Clears my error, not the default one.
        bc.ModelMetadata.Model = model;
        return base.BindModel(cc, bc);
    }
}

Comment: check here in case you want to do **[unobtrusive validation](http://forums.asp.net/t/1698991.aspx/1)**
Comment: That's already easily done, you just turn it off for those fields. I'm only interested in how to make the *server side* part of this work.
Comment: `ModelState["StartDate"].Errors.Clear(); ModelState["EndDate"].Errors.Clear();`
Answer: You should be able to call ModelState.Errors.Clear on the specific property. E.g:
if (someCondition) {
    bindingContext.ModelState["StartDate"].Errors.Clear();
    return base.BindModel(......
}

Clear the ModelState then call the DefaultModelBinder implementation..
Comment: This doesn't the opposite of what I want. I want *my* error message, and *not* the default error message. Specifically in my case, this means the StartDate fields is *still always checked* and generates a validation error.
Comment: Wait.. what's stopping you from clearing the defaults on entry into your custom `BindModel` and adding them yourself during the rest of the method?
Comment: oh, you mean call base.BindModel() and then clear and *then* do my own validation? I see~
Comment: I think a custom model binder is overkill. You can get the functionality you require via nullable `DateTime` properties on your view model.
Comment: They'll still be invalid if the content is invalid though. Specific acceptance criteria, see the actual Q.
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/31745/discussion-between-simon-whitehead-and-doug)
Comment: Can you please tell how to access `bindingContext` ?
Comment: @PankajGarg The `bindingContext` is passed into the `BindModel` method you override in a custom model binder.


Place element at the bottom of the wrapper with height 100%

Question: This is my code:

body,
html {
  height: 100%;
  color: white;
}

.wrapper {
  height: 100%;
}

.wrap-content1 {
  background-image: url(https://source.unsplash.com/random/600x600);
  min-height: 100%;
}

.wrap-content2 {
  min-height: 100px;
  background-color: green;
}

.footer {
  background-color: blue;
  text-align: right;
}

    Wrapper Content 1

    Wrapper Content 2

  This is a footer

I want to display the footer div at the bottom of the wrapper div which has a height of 100%.
I know this can be achieved by placing the footer div inside of the wrapper div, but it doesn't meet my requirements.
Comment: But the footer IS displaying below the wrapper. The problem in the plunkr is that the wrapper's contents overflow out of it, being higher than the wrapper itself. You should fix that first.
Comment: You want the text of the footer to appear inside the wrapper, but without the footer being inside the wrapper?
Comment: or padding-bottom to wrapper, negative margin to footer
Comment: @Mr Lister: No i want the footer to appear below the wrapper
Comment: Do you want it to always display at the very bottom or ONLY in the wrapper div? Will your page never have vertical scrolling?
Comment: @Nihal please pay attention while editing .. why did you add extra  CSS ? don't understand why your edit got approved ...
Comment: sry that was mistake on my part i was trying to change that but my internet was not working so my edit wasn't changed.
Comment: @Nihal and since you placed the code inside snippet remove unecessary text like `here is my CSS` which has no more meaning  .. so please don't make his question irrelevant and create confusion.
Answer: I suppose you want the wrap-content1 to be full height so use vh unit and you will avoid all the height:100% and thus no more overflow issue:

body,
html {
  color: white;
  margin: 0;
}

.wrap-content1 {
  background-image: url(https://source.unsplash.com/random/600x600);
  min-height: 100vh;
}

.wrap-content2 {
  min-height: 100px;
  background-color: green;
}

.footer {
  background-color: blue;
  text-align: right;
}

    Wrapper Content 1

    Wrapper Content 2

  This is a footer

Answer: I think your calculation is not right for .wrap-content1 and it makes the footer does not place at the bottom of .wrapper. You set height of .wrapper = 100%, but .wrap-content1 and .wrap-content2 are more than 100% of parent, this makes the .wrapper cannot wrap 2 children. When I set
.wrap-content1 {
    background-image: url(https://source.unsplash.com/random/600x600);
    min-height: 87%;
}

I can put the footer at the bottom of wrapper.
Comment: how come the value `87%` ?
Comment: yes, but as more contents are added to the wrapper div this will fail.
Comment: this value is just example. the explanation is above.
Comment: @khoi: yes your explanation is absolutely correct, sorry somebody else downvoted


How can I attribute a midnight value (dd/mm/yyyy 00:00) to the previous day?

Question: I have data which accumulate and log each half hour. Therefore, the data logged at midnight (e.g. 27/01/2019 00:00) is actually relevant to the previous day (26/01/2019). This causes problems when totalling daily values
I understand it might be possible to recode the 00:00 as 23:59 to make sure it sits within 26/01/2019, but is there a cleaner/more pythonic way to approach?
Many thanks!
Answer: If your issue is that your logs record at midnight when they actually correspond to the half hour prior to midnight, why not just apply this to all of your records. Something like:
import pandas as pd

# ...

df['Log Period Start'] = df['Log Time'] - pd.Timedelta(minute=30)

Then apply your calculations to 'Log Period Start' rather than 'Log Time'.
Comment: @MohitMotwani That way you would mess up all the other times. The answer is valid for the whole dataframe.
Comment: Why not pd.Timedelta(day=1)?
Comment: You're right. This is only relevant to the data logged at midnight. I misunderstood the question.
Comment: Great idea - a good work around to document that 2330 is the data from 2330-0000, perhaps the most straight forward way.


Exponential least squares biased to small y?

Question: I'm working on fitting an exponential decay curve to a data set.  While searching for techniques I found Wolfram's page describing how to easily accomplish it by taking the natural log of the predictor equation.  http://mathworld.wolfram.com/LeastSquaresFittingExponential.html
I'm confused by equations (5) and beyond, as there is no justification to the claim that the prediction gives greater weight to small y values.  In order to test the claim, I generated a sample data set (took an exponential decay function and added random noise) and compared the predictive model generated by the standard linear regression vs. the one suggested by equations (5) and beyond.  I found that the sum of the residuals squared was significantly smaller (6 million vs. 11 million) for the predictive model generated by using the parameters calculated from (9) and (10).
Can someone give me a reason for this bias?  Is multiplying by the response (y) just a convenient choice, or can it be shown that it is the optimal correction?
Also, if this is indeed a known bias, why doesn't software designed to generate exponential fits take it into account?  I generated the fit using Oracle (REGR_SLOPE, REGR_INTERCEPT) and Excel (Trendline) and both gave me the same fit, which wasn't as good as the one I generated by equations (9) and (10) on Wolfram's site, based on my analysis of the residuals.
Comment: This is just a trick ("to weight the points equally", as they say). What you should do is just linearize the model, get the parameters from linear regression and start a nonlinear regression using these parameters. You cannot compare SSQ for two different objective functions.
Comment: That does get me to a better fit than either of the fits I generated previously.  I'm not sure what you mean when you say I can't compare the SSQ.  I'm comparing the gross sum of squares calculated by taking the square of the difference between my predicting function and the existing data for every point.  Are you saying that this comparison is invalid?
Comment: Could you send me exactly your data points at firstname.lastname@example.com [as a .txt file - one pair of (x,y) per line] and I shall show you things. Cheers :-)
Answer: First of all, parameters of unweighted linear regression are very strongly influenced by the largest values of $y$, the dependent variable. When you linearize an exponential model and you have very small values, then the $\log(y)$ can be very large (negative) and strongly influence the results.
I made an example fo your problem.
I generated $20$ equally spaced $x$'s $(x_i=1,2,3,\cdots,20)$ and generated the corresponding $y$ using $$y=e^{5.678-0.456 x}$$ to which I added a random noise for a maximum relative error of $\pm10$%.
For the first run, I just linearized the system and used the classical linear regression. The resulting parameters are $5.710$ and $-0.460$. For these values was computed $$SSQ=\sum_{i=1}^{20} \Big(y_i^{calc}-y_i^{exp}\Big)^2$$ which is equal to $87.07$.
In a second step, I used the weighting as suggested in the link you give. The resulting parameters are $5.655$ and $-0.443$ and $SSQ=26.64$.
In a third step, starting with the parameters obtained by the first step, I performed a nonlinear regression. The resulting parameters are $5.656$ and $-0.444$ and $SSQ=26.54$.
As you can see, what is proposed leads to results which are quite close to the nonlinear regression.
I must confess that I always perform a nonlinear regression even if the model can be linearized and even if errors are small. Remember that what is measued is $y$ and not $\log(y)$ and when you compare sum of squares they must be consistent.
By the way, you could demonstrate easily that, if the errors are not too large, minimizing the sum of the squares of logarithms is almost identical to minimizing the sum of squares of relative errors. For illustration purposes, I also made that. The resulting parameters are $5.706$ and $-0.460$ and $SSQ=74.74$. Compare these results to those from the first step.
Comment: Your results are very similar to mine.  I got only minor improvements beyond Wolfram's suggestion, but it can still be improved upon, so obviously it's not a closed form of the best fit.  I do wonder why Excel doesn't iterate to generate a better fit, but maybe they prefer to present a result that can be derived by hand.
Comment: How did you find the correct weights?


Integration Factor in terms of $x$ and $y$ used to reduce an ODE to an exact form

Question: If your ODE is non exact you need an integrating factor to make it exact I'am asking for a general expression for finding this integrating factor
Let the Integration factor be  $T(x,y)$
$$T(x,y)M(x,y)dx +  T(x,y)N(x,y)dy  =0$$
Apply the  condition for exactness
$$ T_yM + M_yT = T_xN + N_xT   $$
Question is much easier if your T depends on x or y only
I want to ask how do solve the above PDE for the function T if it depends on both x and y
Comment: @TaimoorAli Yes, for bivariate Pfaffian form there's no general form of integrating factor. But if you impose some constraint, there it is. For example, if M and N are both homogeneous, then the integrating factor is $\frac1{Mx+Ny}$.
Comment: I'm not sure what are you asking
Comment: if your ODE is non exact you need an integrating factor to make it exact  . After some inspection  your IF does not depend on x , it does not depend on y rather it depends on both x and y . I'am asking for a general expression for finding this integrating factor
Comment: There is no general method.
Comment: My lecturer ranked  3rd or 4th in Asia  says there is
Comment: if u have a question to solve  ho do you approach that
Comment: @TaimoorAli There should be some misunderstanding here on your side. There is a theorem that says that the integrating factor always exists (locally). And it is completely different matter to present a formula for it -- that does not happen often.
Comment: Then can u give any example .. how to solve one if IF depends on both x and y
Comment: @TaimoorAli See my answer. It also halps if you use @ name.
Comment: @ShuchangZhang  what do mean by   Bivariate Pfaffian form
Comment: @TaimoorAli I mean for $M(x,y)dx+N(x,y)dy=0$, there's no general integrating factor. You can refer to applications of Lie group in ODE to find integrating factor for different types of ODE.
Answer: Here is an example of an integrating factor that depends both on $x$ and $y$. Since you have such a highly ranked lecturer, I will give this example by stating a problem:

Let
  $$
M(x,y)dx+N(x,y)dy=0.\tag{1}
$$
  Show that if the expression
  $$
\frac{N'_x-M'_y}{xM-yN}
$$
  is a function of $xy$ only, then $(1)$ admits an integrating factor and find it.
Comment: Thank God this was the expression  i was looking for . Know after evaluating this expression ( and it comes out to be a function of x and y ) how do you use it to find the IF ...
Comment: let Integration Factor be F(x,y) then  F(x,y) = exp ( Integral of above Expression  ) . my question is   " with respect to what should I integrate your expression " e.g with dx dy or both .. Example can be helpful


How to re create a section of my code with new variables through javascript

Question: I'm trying to create a comment feature for my page so when a user comments some text, the comment will appear above the comment section as a new comment. I'm having issues with adding the new comment into the html from the javascript right now, what i want is the format of the comment of the new one same as my the first comment shown there, how can I go about this? Sorry if i'm unable to phrase my question properly :/

var post= document.getElementById("post");
post.addEventListener("click",function(e){
    e.preventDefault();
    console.log('coment button pressed');

    var userComment=document.getElementById("comment-box").value;
    console.log(userComment)

    var text= document.createTextNode(userComment);
    console.log(text)

    var newComment = document.getElementById("new-comment");
    console.log(newComment)

    newComment.appendChild(userComment)

})
  .comment-box,
  .post-comment .list{
    background-color: white;
    border-radius: 5px;
    box-shadow: 0 2px 2px black;
  }

.comment-section{
  width: 100%;
  height: auto;
  margin: 0 auto;
}

.post-comment .list{
  width: 100%;
  margin-bottom: 12px;
}

.post-comment .list .user{
  display: flex;
  padding: 8px;
  overflow: hidden;
}

.post-comment .list .user img{
  height: 38px;
  width: 38px;
  margin-right: 10px;
  border-radius: 50%;
}

.comment-section .name{
  text-transform: uppercase;
}

.post-comment .list .day{
  font-size: 12px;
}

.post-comment{
  padding: 0 0 15px 58px
}

#comment-box{
  border:none;
  border-radius: 5px;
}

.comment-box .user{
  display: flex;
  width: min-content;
}

.comment-box .image img{
  width:24px;
  height: 24px;
  margin-right: 10px;
  border-radius: 50%;
}

.comment-box textarea{
  height: 50px;
  width: 1 ;
  background-color: white;
  margin: 10px 0;
  padding: 10px;
  border-radius: 5px;
  box-shadow: 0 0 0 1px black;
}

TOM

100 days ago

LOREM IPSUN DABUN VUB

              <form>
              <textarea name="comment" placeholder="YOUR MESSAGE" id="comment-box"></textarea>
              <button id="post">Comment</button>
            </form>

Comment: Look into the
Comment: You can have comment markup within your template element and then clone it with JavaScript
Comment: https://www.youtube.com/watch?v=y17RuWkWdn8
Answer: You are almost there. Basically you need to passing a node when using appendChild() method.
Create a div node,
// create an element node
// var text = document.createTextNode(userComment);
var text = document.createElement('div');
text.innerText = userComment;

And pass it to the new comment section,
// note: you need to pass a node to appendChild() method
// newComment.appendChild(userComment);
newComment.appendChild(text);

Hope it helps!

var post= document.getElementById("post");
post.addEventListener("click",function(e){
    e.preventDefault();
    console.log('coment button pressed');

    var userComment = document.getElementById("comment-box").value;
    console.log(userComment)

    // create an element node
    // var text = document.createTextNode(userComment);
    var text = document.createElement('div');
    text.innerText = userComment;
    console.log(text)

    var newComment = document.getElementById("new-comment");
    console.log(newComment)

    // note: you need to pass a node to appendChild() method
    // newComment.appendChild(userComment);
    newComment.appendChild(text);
})
.comment-box,
.post-comment .list{
  background-color: white;
  border-radius: 5px;
  box-shadow: 0 2px 2px black;
}

.comment-section{
  width: 100%;
  height: auto;
  margin: 0 auto;
}

.post-comment .list{
  width: 100%;
  margin-bottom: 12px;
}

.post-comment .list .user{
  display: flex;
  padding: 8px;
  overflow: hidden;
}

.post-comment .list .user img{
  height: 38px;
  width: 38px;
  margin-right: 10px;
  border-radius: 50%;
}

.comment-section .name{
  text-transform: uppercase;
}

.post-comment .list .day{
  font-size: 12px;
}

.post-comment{
  padding: 0 0 15px 58px
}

#comment-box{
  border:none;
  border-radius: 5px;
}

.comment-box .user{
  display: flex;
  width: min-content;
}

.comment-box .image img{
  width:24px;
  height: 24px;
  margin-right: 10px;
  border-radius: 50%;
}

.comment-box textarea{
  height: 50px;
  width: 1 ;
  background-color: white;
  margin: 10px 0;
  padding: 10px;
  border-radius: 5px;
  box-shadow: 0 0 0 1px black;
}

TOM

100 days ago

LOREM IPSUN DABUN VUB

        <form>
        <textarea name="comment" placeholder="YOUR MESSAGE" id="comment-box"></textarea>
        <button id="post">Comment</button>
      </form>

Answer: You should change newComment.appendChild(userComment) by newComment.appendChild(text); And here you are, I added some small updates like clearing the text area after sending a comment, and adding the comment into a paragraph to prevent showing different sent comments in the same line:

var post= document.getElementById("post");
post.addEventListener("click",function(e){
    e.preventDefault();

    var userComment=document.getElementById("comment-box").value;

    var text= document.createElement('p');;
    text.innerHTML = userComment;

    var newComment = document.getElementById("new-comment");

    newComment.appendChild(text);
    document.getElementById("comment-box").value = "";

})
  .comment-box,
  .post-comment .list{
    background-color: white;
    border-radius: 5px;
    box-shadow: 0 2px 2px black;
  }

.comment-section{
  width: 100%;
  height: auto;
  margin: 0 auto;
}

.post-comment .list{
  width: 100%;
  margin-bottom: 12px;
}

.post-comment .list .user{
  display: flex;
  padding: 8px;
  overflow: hidden;
}

.post-comment .list .user img{
  height: 38px;
  width: 38px;
  margin-right: 10px;
  border-radius: 50%;
}

.comment-section .name{
  text-transform: uppercase;
}

.post-comment .list .day{
  font-size: 12px;
}

.post-comment{
  padding: 0 0 15px 58px
}

#comment-box{
  border:none;
  border-radius: 5px;
}

.comment-box .user{
  display: flex;
  width: min-content;
}

.comment-box .image img{
  width:24px;
  height: 24px;
  margin-right: 10px;
  border-radius: 50%;
}

.comment-box textarea{
  height: 50px;
  width: 1 ;
  background-color: white;
  margin: 10px 0;
  padding: 10px;
  border-radius: 5px;
  box-shadow: 0 0 0 1px black;
}

TOM

100 days ago

LOREM IPSUN DABUN VUB

              <form>
              <textarea name="comment" placeholder="YOUR MESSAGE" id="comment-box"></textarea>
              <button id="post">Comment</button>
            </form>


Apache2 falling over

Question: On my dev server.  Evey so often apache2 just falls over. Its no longer running as a process.
Server details:
Linux Debian etch
Apache2
<code># ps aux | grep apache
www-data  6782 99.9  0.2   4792  2912 ?        R    Oct12 8592:53 /usr/sbin/apache/log
root     22418  0.0  0.0   2852   704 pts/2    S+   13:31   0:00 grep apache

# apache2ctl restart
httpd not running, trying to start
(98)Address already in use: make_sock: could not bind to address [::]:80
(98)Address already in use: make_sock: could not bind to address 0.0.0.0:80
no listening sockets available, shutting down
Unable to open logs
</code>
When I check the /var/log/apach2/error.log  There is nothing in there.
I guess I want to do two things.

Figure out why apache is falling over. Fix it
Congifure where nessacary so it doesn't happen again and maybe set up log files better?

If i restart the machine I can get apache up and running again.  can anyone explain what is going on here?
Thanks,
Derek
Answer: I'm afraid you may have been hacked. I would run a tool that checks for a root kit and look for any rogue php scripts. Check out /tmp for any weird files or scripts. I think debian has rkhunter in the apt repos. Good luck.
Comment: hsperfdata should be nothing to worry about. I found this link while trying to figure out what /usr/sbin/apache/log could be.

http://www.interworx.com/forums/showthread.php?p=16421
Comment: really!? thats not good. right well a quick look in /tmp and there is one folder there i don't know understand why it is there or what it is for.
     /tmp/hsperfdata_root

there seems to be two files in there. not sure what they are.. maybe java files but they are just name by numbers with no file extensions. I don't use java on this server.
Comment: crap! found some sneaky ".txt" files that are actually scripts in /var/tmp. I'll update here on what I find. thanks for the link.
Comment: I think I found the problem and the fix using APT-GET ..
http://lists.debian.org/debian-security-announce/2008/msg00056.html
Answer: It appears that pid 6782 is an apache process, so why do you think it's not running?  That process is probably holding port 80 open, which is why you can't start a new one.
I'm willing to bet that what's killing it is the "restart" that happens when it rotates log files.  But you won't know until it happens again and you can get both a real "ps" output and maybe an "strace" or "truss" on the stuck process.
Comment: It may be a rootkit.
Comment: sorry.. there seems to be a bit missing there on the text..

/usr/sbin/apace/log is the process..  Not sure how that is the case.
Comment: That's very unlikely.  There is no such file as /usr/sbin/apache/log on Debian.  Try doing a "ps auwwx" and paste the real results.
Comment: crap.. I can't do that now as I had to get apache running again so I rebooted to get apache up and running again. I agree there is no file /usr/sbin/apache/log... that's what confused me. but that is what it said.
Answer: First thing I would do is go look for a /usr/sbin/apache/log file, and see what the hell that is.  It looks very strange.  Even if it looks like a valid binary, try "strings /usr/sbin/apache/log | less", to look for anything suspicious.
ps should be displaying the executed command there, afaik, and no command like /usr/sbin/*/log should exist.  On my system (ubuntu), ps lists /usr/sbin/apache2 there.  I use debian regularly too, and as far as I recall, the setup is identical on Debian.  Also, check the output of "pgrep -l apache".
IF you find out that something normal is going on (i.e., your server hasn't been hacked) then you might try making sure that you're not running a multithreaded mpm that's incompatible with some module (especially php).  Also, check things like disk space, permissions, etc.  Apache does like to give up and crash if its log files are inaccessible, but usually that happens on startup.  Something similar might be happening with files that aren't opened until later (although I can't think what those files would be --- htaccess and password files should fail gracefully).
Answer: The only time I saw something like this was when the network interface was not configured and apache kinda started but just hung itself.  If your system is configured to assign IP by DHCP, this could be a weakness.  Of course if you are ssh'ed into same interface apache listens on, then this isn't the issue!
Perhaps find out what is listening on port 80 this way:
<code>lsof -Pni | grep ":80 "
</code>

Apache2 falling over


Complex integral and contour

Question: I'm trying to compute the integral $\int\limits_0^\infty \frac{dx}{2+x^n}$
So my attempt is finding the roots of $2+x^n$ that are $e^{\pi i}$$e^{\frac{2  \pi m}n} $ for $m=1,2...,n-1$ and then define the contour of the integral.
After that apply Residue Theorem.
Please tell me if I'm doing this right.
Comment: Here's your answer... just to check your final solution:  $\frac{\pi  2^{\frac{1}{n}-1} \csc \left(\frac{\pi }{n}\right)}{n}$
Comment: You still have a typo in the formula in your last comment (and there are $n$ roots, not $n - 1$). Since you know what contour to take, determine which of the roots lie inside the contour. Then parametrize the ray $\arg x = 2 \pi/n$ and write out the integral along the ray.
Comment: That's the right approach.  How far have you gotten?
Comment: I'm not sure if those are the roots of the denominator, but the contour is like a piece of cake with angle $\frac{2 \pi}{n} $
Comment: I don't know how you obtain $csc(\frac{\pi}{n})$
Comment: First:  simplify your $e^{i \pi}$ using Euler's famous equation.
Comment: Are the roots of the form $2^{1/n}$$e^{\frac{i2k \pi + \pi}{n}}$
Answer: Not a full solution (so please don't downvote).
Here are your poles:
Comment: Surely that's not what a regular polygon with $n$ vertices looks like. (What you have is apparently $(-2)^{1/n}$ for successive values of $n$.)

Complex integral and contour


How is the inequality reversed in this limit proof?

Question:
In the above proof, how did they go from $|g(x)-B|<|B|/2$ to |g(x)|>|B|/2? Wouldn't that only work if $B$ is positive?
Answer: Intuitively, if $g(x)$ is closer to $B$ than $0$, then thinking about distances from $0$, $g(x)$ must be farther than $B/2$ from $0$. This then implies that $|g(x)| > |B|/2$.
You can prove this formally using the reverse triangle inequality, i.e. ($||a| - |b|| \leq |a - b|$). Observe that
$$|g(x)| = |B - (g(x) - B)| \geq ||B| - |g(x) - B|| \geq |B| - |g(x) - B| > \frac{|B|}{2}.$$


Spark structured streaming: java.lang.NoClassDefFoundError for GroupStateTimeout

Question: I'm trying to use mapGroupsWithState in spark structured streaming as defined in https://spark.apache.org/docs/2.2.0/api/scala/index.html#org.apache.spark.sql.streaming.GroupState
However I get the error:
<code>Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/spark/sql/streaming/GroupStateTimeout
</code>
Seems like the GroupStateTimeout class definition was not found in the package
I'm using the JAR for spark-sql_2.11_2.2.0 from:
https://mvnrepository.com/artifact/org.apache.spark/spark-sql_2.11/2.2.0
When I open up the JAR, there is no class definition of GroupStateTimeout. I'm not sure if it's something that I'm missing here, because the mapGroupsWithState seem to be a pretty well documented feature. How is a class definition missing in the package?
Answer: GroupStateTimeOut is the part of spark-catalyst module. Please have a look here: https://github.com/apache/spark/blob/master/sql/catalyst/src/main/java/org/apache/spark/sql/streaming/GroupStateTimeout.java
So you need to add spark-catalyst dependency https://mvnrepository.com/artifact/org.apache.spark/spark-catalyst_2.11/2.2.0 in your project. Hope it will solve your problem


Let's Encrypt error with Amazon Linux with virtualenv

Question: I download certbot-auto and ran
./certbot-auto certonly --standalone -d domain.com -m firstname.lastname@example.com --agree-tos -n --debug

I get below error that it is looking for virtualenv==15.1.0 but installed version is 16.0.0. Is it possible to let certbot-auto use version 16.0.0? What can I do to resolve this error.
Traceback (most recent call last):
  File "/usr/bin/virtualenv", line 6, in <module>
    from pkg_resources import load_entry_point
  File "/usr/lib/python2.7/dist-packages/pkg_resources/__init__.py", line 3049, in <module>
    @_call_aside
  File "/usr/lib/python2.7/dist-packages/pkg_resources/__init__.py", line 3033, in _call_aside
    f(*args, **kwargs)
  File "/usr/lib/python2.7/dist-packages/pkg_resources/__init__.py", line 3062, in _initialize_master_working_set
    working_set = WorkingSet._build_master()
  File "/usr/lib/python2.7/dist-packages/pkg_resources/__init__.py", line 660, in _build_master
    return cls._build_from_requirements(__requires__)
  File "/usr/lib/python2.7/dist-packages/pkg_resources/__init__.py", line 673, in _build_from_requirements
    dists = ws.resolve(reqs, Environment())
  File "/usr/lib/python2.7/dist-packages/pkg_resources/__init__.py", line 858, in resolve
    raise DistributionNotFound(req, requirers)
pkg_resources.DistributionNotFound: The 'virtualenv==15.1.0' distribution was not found and is required by the application

   $ virtualenv --version
    16.0.0

Answer: I've been search for this exact issue. I finally found the answer. First, you go into /usr/bin and delete the files called virtualenv*.
Then, install virtual with this command:
sudo /usr/bin/easy_install virtualenv

From there certbot works perfectly.
Answer: Just uninstall and install virtualenv again, worked for me.
pip uninstall virtualenv
pip install virtualenv


Play piece using a custom waveform?

Question: As part of a music festival, I have been asked to convert one of my piano compositions, titled "Fractal", into an electronic piece by playing around with timbres using MIDI data. Though I have a few ideas I would like to implement, I don't have experience with digital audio workstations nor electronic music in general.
In particular, the main idea I had in mind was to create a separate timbre -- constructed from a custom fractal-shaped waveform -- for each section of the piece. I did stumble upon this question, though I don't know how one could apply this to sections of MIDI data. Is this a viable idea?
EDIT: in response to the comments, I suppose that I really have two separate tasks I want to figure out how to do:
a) I need a way to generate the waveforms for each pitch, and
b) I need a way to play the MIDI data using these waveforms.
Comment: If you don't have waveforms and you don't know how to generate them, what do you mean by "fractal-shaped waveforms"? Perhaps all you need is to experiment with various software synthesizers, and e.g. effects as @Bennyboy1973 suggests, until you find the sounds you like?
Comment: I'm not sure I'm understanding what you're asking. Do you mean that the sound should also be generated based on the midi data, not only (like standard sampling) its pitch?
Comment: Are you looking for a way to generate the waveforms, or are you looking for a way to play midi data using waveforms you've already generated?
Comment: The problem is that for true Weierstrass waveform you'd need an infinite number of oscillators. Of course, physical sound reproduction equipment couldn't play it either and a human certainly wouldn't be able to tell it from approximation with frequencies above ~20KHz removed
Comment: Without electronic music experience your best approach might be to collaborate and find a music tech to get you all set up with the custom fractal waveform patch and necessary controller and software so you can focus on performing
Comment: If you want to play back "custom waveforms" isn't a sampler-kind of software exactly what you need? Do you already have wave files with the waveforms you have in mind?
Comment: To those voting to close the question: I don't think OP needs specific product recommendation, what they _seem_ to need (if only they can clarify they question) is a product _type_.
Comment: @musicamante if I'm understanding your question correctly, the sound should be generated with the MIDI data, but using a non-piano timbre. It would be something like "play the MIDI but use a square-wave timbre", except "square-wave" is replaced by a different, custom waveform.
Comment: @Edward I'm looking for both, actually. Let me edit the question to make that clear.
Comment: @user1079505 I don't have wave files with the waveforms I have in mind yet. (nor do I know how to generate them yet). And yes you are right, I'm essentially looking for a product type — a tool that can do what I want.
Comment: I could probably be talked into collaborating on something like this.  I once wrote a mensural fugue, with the idea that a simple sine wave could carry pretty much a whole universe of compositions.
Comment: @user1079505 I was thinking of a waveform similar to a Weierstrass function, or perhaps something similar like sin(n)+sin(2n)/2 + sin(4n)/4 + sin(8n)/8 ... I'm not exactly sure, since I'll have to play around for a bit before I get something that I want.
Comment: If n represents time in your formula, that's something many synthesizers could do easily. You tune the first oscillator to the base octave, second an octave higher, another two octaves above the base, and so on.
Answer: As you already figured out, MIDI has nothing to do with timbres or waveforms. MIDI is an interface and a command language for musical instruments to talk to each other, saying things like "Note On, C-5, velocity 100". How the recipient device reacts to that Note-On message could be literally anything. It could cause a stage light to move to a different position, or it could cause a MIDI-controlled tape deck to start playing, or it could cause a synthesizer to start making sound, or it could cause a MIDI-controlled garage door to open. I don't know if there are MIDI controlled garage doors, but if there is, the garage door will probably have an electric motor, which will produce an electrical waveform of some sort. If the waveform has a frequency between around 20Hz and 20kHz, and if it causes air vibrations at those frequencies, then the garage door motor makes a sound and the sound can be heard by a human. Whether a MIDI sequence playd on the garage door counts as electronic music, is a matter of opinion.
Notation applications can produce MIDI messages, working as sequencers. There are free notation applications such as MuseScore, which you could use for sending out the MIDI commands just fine, no "digital audio workstation" needed at all.
The device receiving the MIDI messages and producing the audio waveforms can be a piece of software or it can be an outboard MIDI synth, i.e. external hardware box or keyboard-type instrument that you connect to your computer via a MIDI interface and a MIDI cable. If it's a virtual synth or sampler or other sound-producing program, you connect it to the sequencer (for example MuseScore) via a virtual MIDI cable, which is a piece of software that routes MIDI messages from application A to application B. Or you could save out ("export") a MIDI file from the notation application and load it into a combined sequencer/synth application for playback, bypassing the need for a virtual MIDI cable.
I think this much you could have found out yourself by reading an introductory text or watching a tutorial about what MIDI is.
But then the more interesting question. How to create a waveform that you could legitimately call "fractal shaped"? Fractals are supposed to have "infinite detail", detail inside detail inside detail, reproducing variations of the same pattern or formula at many resolutions and scales, right? How do you do that, because audio only has finite resolution - how do you demonstrate fractal properties in an audio waveform? Is it enough if it just sounds weird and is accompanied by an explanation "something something fractal something", creating a science-mystic layer? Or do you have to be able to justify and defend the fractal claims?
This is just mumbling out my ad-hoc ideas, but to believe something is a fractal, I'd want to see repetitions of characteristics of a pattern occurring at many different scales of magnification. Our display screens have finite resolution just like audio, and fractal properties in images are demonstrated by zooming, i.e. changing the horizontal and/or vertical magnification scale of the display. So the demonstration cannot be just one static image, you have to provide several images or an animation with different scales. If we extend this thinking to audio, you'd have to show some kind of a display, something happening either in the time dimension (time domain) or frequency spectrum (frequency domain). Maybe if the visual shape of the waveform in time domain at some scale has a shape, and then, when looked at closer, similar shapes or characteristics could be found? Or what if the waveform itself morphed, creating a zooming in/out image, while keeping the oscilloscope zoom level the same? This would also cause changes in the sound itself, creating a morphing timbre! Or what if the spectrogram in frequency domain looked like a fractal?
One way to do this properly, in my opinion, would be by programming the audio-generating (virtual) device yourself. See topo's answer for ideas.
You had a requirement of the fractal-like properties being found in waveforms, and that suits the idea of playing an existing composition, but fractal-like properties have been claimed to be found in the rhythmic patterns/timings of Jeff Porcaro's drumming. https://phys.org/news/2015-08-fractals-patterns-drummer-music.html Fascinating? Nonsense? You decide.
Comment: Thank you for your response! Regarding your question "how to create a waveform that you could legitimately call 'fractal shaped'?" I was actually planning on making a waveform that looks similar to, say, the Weierstrass function or some (not totally non-differentiable) variants thereof. So I suppose, yes, this would justify the fractal claims. I doubt one could actually "hear" the fractal nature of the waveform, but it would make for an interesting experiment.

The frequency domain fractal idea also seems interesting, but it wasn't what I was going for.
Comment: The Weierstrass function could at least be an interesting experiment. I wonder what happens if you zoom into the function or make the a/b/c parameters adjustable? So that it would generate a single cycle of the wave, or a wavetable entry. Zooming in would take a narrower window between 0..1. This would require a bit of programming.
Answer: There are quite a few ways you could go about this, depending on how much 'conventional'  music technology you are happy to use.
One straightforward way to play a custom waveform using MIDI data is to load that waveform (as an audio file) into a sampler, or any other synthesizer that can load samples.
These days, pretty much any 'DAW' (Digital Audio Workstation) software will be able to load a sampler 'plug-in', and control that with MIDI data.
From your other SE accounts, it looks like you're a coder, so you should be able to write a function that generates the fractal as a 'function'.
So as a first, very simple approach, you could

Write some code to sample the fractal function, and (possibly using an audio library of some kind), write this to an audio file (sucn as a .wav or .aiff file). You might want to find a section of the function's domain that has the same values at the start and end, so that you get a 'smooth' waveform when that section is copied end-to-end to play a note at a certain frequency.
Use your sampler plug in in your DAW to load in the waveform and control it with MIDI.

There will be a few refinements that you could make to the process - you might want to write your function-sampling code in a way that uses filtering to avoid aliasing, and you will want to experiment with finding a satisfying sections of fractal 'shape' to use as your samples.
Comment: Thank you for your response! Your answer (along with piiperi's) seem to be the most promising so far. It seems like what I want to go for is what you outlined: somehow use a DAW to load a sampler 'plug-in', and use this to generate the final audio file.

I suppose that once I generate the waveform for a specific frequency, the DAW can handle the rest and generate the waveforms for all other frequencies -- is this correct?
Comment: @TheTurtle yes, that's correct. One think you could perhaps consider to incorporate some of piiperii's ideas would be using a granular synth, rather than a straight 'sampler' - the granular synth would allow you to change your grain size and potentially move along and look at different parts of your waveform....
Answer: MIDI's the wrong tree to bark up, I think.  What you need is a DAW and a few good VST plugins.
I recommend taking a look at a few sample of "ring modulation" on Youtube.  I like this one, from about 13:00 to 15:00 or so.  My suggestion is to have a series of ring mods, so you resolve ONE to a new sound, then use the NEXT one to morph that into a new waveform:

This video is not the most musical application, but it is a pretty good explanation of how ring mods work.

Play piece using a custom waveform?


How can I call a layout after clicking a button?

Question: I am having a difficulty displaying a layout. Here is my intention:
1. User clicks Button
2. A message pops up and user selects between Yes or No
3. When yes is clicked a layout named "dialpad" will be displayed.
But when I click "yes" it says "Unfortunately,  has stopped." Can anyone help me ?
I do know there's a problem on this line...
ViewStub stub = (ViewStub)findViewById(R.id.dialpad);
stub.setVisibility(View.VISIBLE);

Thank you for your help !
Here's the code:

package com.example;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewStub;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class ExampleGUIDialogActivity extends Activity {

    final Context context = this;
    private Button button;

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        button = (Button) findViewById(R.id.buttonAlert);

        // add button listener
        button.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {

                AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                        context);

                // set title
                alertDialogBuilder.setTitle("Your Title");

                // set dialog message
                alertDialogBuilder
                .setMessage("Click yes to exit!")
                .setCancelable(false)
                .setPositiveButton("Yes",new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,int id) {
                        // if this button is clicked, close
                        // current activity
                        // launch dialer
                        ViewStub stub = (ViewStub)findViewById(R.id.dialpad);
                        stub.setVisibility(View.VISIBLE);

                        //stub.inflate();
                        //View mDialerView = (View)findViewById(R.id.dtmf_twelve_key_dialer_view);
                        //mDialerView.bringToFront();

                        ExampleGUIDialogActivity.this.finish();
                    }
                })
                .setNegativeButton("No",new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,int id) {
                        // if this button is clicked, just close
                        // the dialog box and do nothing
                        dialog.cancel();
                    }
                });

                // create alert dialog
                AlertDialog alertDialog = alertDialogBuilder.create();

                // show it
                alertDialog.show();
            }
        });
    }

}

Comment: Can you please post some code? What is the error specifically?
Comment: It will be very difficult to help you without seeing any code. Don't you think so?
Comment: remove this line `ExampleGUIDialogActivity.this.finish();`
Answer: Try this
ViewStub stub = (ViewStub)findViewById(R.id.dialpad);
if (stub != null){
    stub.setVisibility(View.VISIBLE);
}

Can you provide any logcat info???
Answer: Well, one problem is that you're inflating the ViewStub and then immediately exiting your Activity, which will cause all kinds of problems; first among them, your user will never see the new layout!
I think you may want to launch a new Activity which has as its content view the layout you're trying to inflate, and allow the user to perform some action based on it... or perhaps you want to call dialog.dismiss() instead?
Comment: I removed the ExampleGuiDialogActivity.this.finish() and tried try catch around setVisibility and the application didn't crash, but didn't show the layout.


Hibernate find by criteria get single result

Question: i am experimenting using Hibernate.
I am trying to get a User by id this is what i do
<code>public User get(DetachedCriteria dc){
    List<User> users = getHibernateTemplate().findByCriteria(dc);
    if(users != null)
    {
        return users.get(0);
    }
    else return null;
}
</code>
but it fails when the user is not in the database. Could you help me to understand how to achieve this?
Thanks
Comment: Start by enabling SQL tracing to see what Hibernate is sending to the database. In your hibernate config (or applicationContext.xml, depending...) add: true
Answer: If you want to load something by ID you should really be using either Load or Get.  Ayende has a good post on the difference between The difference between Get, Load and querying by id.
As far as why your query is failing when the user isn't in the database.  It's because the query will return an empty list, which is different from null.  So when you try to access the 0th element of a list that has nothing in it, you're probably getting an index out of bounds exception.


How to discover the currently active twig template

Question: I need to find out the currently active Twig template from within my module preprocess function.
function mymodule_preprocess_field(&$variables, $hook) {
    // How do i retrieve the currently active Twig template?
}

I need to know whether it is field.html.twig, field--field-example.html.twig or some other template suggestion.
Is that possible?
Comment: What is the purpose?
Comment: Oh ok, you can get most of what you need from `ThemeManager::render()`.
Comment: I'm creating a helper module for TailwindCSS theme.  I want to provide the themer with the ability to inject classes into fields without having to override every single template.  The idea is that the themer can create a YAML file containing a structured list of classes that I will load in the preprocess and inject.
Comment: Why would you need the template file name to decide which classes to inject? Wouldn't it make more sense to base it on criteria, like the field name, formatter being used, and so on?
Comment: I want to allow the themer to create a YAML file like this: https://ibb.co/6rJmwRF  Then in my module preprocess, I want to load the YAML file, check whether there is an entry matching the current Twig template and inject the classes.
Comment: I'm thinking that there must be somewhere in Drupal that determines the currently active (highest priority) twig template for a given field but I can't seem to find it.
Comment: I thought that `theme_get_registry()` might help but it shows all template suggestions with no indication of the highest priority template.
Comment: Awesome, thanks.  I'll check it out and post an answer here.
Answer: With the help of Clive's comment, I managed to identify the active theme suggestion.  Code below.
function mymodule_preprocess_field(&$variables, $hook) {
  $theme_suggestions = mymodule_get_theme_suggestions($hook, $variables);

  $active_suggestion = mymodule_get_active_theme_suggestion($theme_suggestions);
}

function mymodule_get_theme_suggestions(String $base_hook, array $variables) {
  // Invoke hook_theme_suggestions_HOOK().
  $suggestions = \Drupal::moduleHandler()->invokeAll('theme_suggestions_' . $base_hook, [$variables]);

  // Invoke hook_theme_suggestions_alter().
  $hooks = [
    'theme_suggestions',
    'theme_suggestions_' . $base_hook,
  ];
  \Drupal::moduleHandler()->alter($hooks, $suggestions, $variables, $base_hook);

  array_unshift($suggestions, $base_hook);

  return $suggestions;
}

function mymodule_get_active_theme_suggestion($suggestions) {

  $theme_registry = theme_get_registry(FALSE);

  // Order by most specific first.
  $suggestions = array_reverse($suggestions);

  foreach ($suggestions as $candidate) {
    if ($theme_registry
      ->has($candidate)) {
      return $candidate;
    }
  }
}


Why should we avoid theming forms with template files?

Question: The issue was raised in this question. Why not exploit the advantages that template files offer in the case of forms?
Comment: We should **not** avoid this! If you care about the presentation of any particular form, create a tpl for it.
Answer: I can see no good reason for not using a template file to theme a form. As I stated in that question, the simple #prefix and #suffix tricks might not be enough, say if you wanted the entire form to be a table rather than div based. I've used drupal_render with a form element parameter in a template to draw the individual fields in the form, but make sure you call drupal_render without an argument at the end of the template to populate the rest of the form, such as the form hash etc. as it won't validate.