CentOS NFS server session crashes

Question: I recently received some alerts that 2 of my backups failed to an NFS mount in my environment. After reviewing the logs I realized that the software was unable to establish a connection to the NFS mount in order to verify enough storage was availabe to run the job. I ssh'd into the box from the server that was experiencing the issue, thus verifying connectivity to the remote destination, and after reviewing df -h to find that there was plenty of storage, I then decided to "browse" that storage, and this is when my sessions continuously crash. Everytime I try to browse the /home/export/ path, the TTY session freezes and I have to establish a new session. Has anyone seen this? I'd tell you the version of CentOS that i'm running and some other versioning info, but I just rebooted the NFS mount and can't login at the moment.
Answer: Kill any NFS server daemons on the server, and any nfs-related processes on the client, and restart on both ends. In my years of working as a sysadmin, I've seen NFS freeze time and time again. It's one of the frustrating/unstable things about it.
Comment: This is a fix but does not prevent the problem, what errors do you get? The tty is freezing because it's waiting to change into a directory that does not exist. Do you have errors in your event logs? What are your mount options? Do you know that the mount target was available the entire time (is it a client, network or server problem)?  NFS does not "just crash", when configured properly on good hardware it's an extremely reliable protocol.
Comment: Keeping your system updated is the key to fixing these type of problems.
Comment: not with NFS it isn't :)  "reliable" and "NFS" don't go together. network file locking in general is problematic, right? NFS simply reflects that fact more readily, than, say AFS

CentOS NFS server session crashes


How do you sample from a half-normal distribution in Python?

Question: I would like to generate samples from a half normal distribution.
numpy's random number generator allows you to sample from many distributions. Here's an example for the normal distribution. However, it does not appear to support half-normal. I could take the absolute value of the samples, but this seems inelegant.
import numpy as np
import matplotlib.pyplot as plt

samples = np.random.normal(0, 1, size=1000)
plt.hist(samples)

scipy contains a half-normal distribution (halfnorm), but I can't figure out if you are able to sample from this.
from scipy.stats import halfnorm, norm

Comment: Why are you thinking $|X|$ for $X\sim N(0,\sigma^2)$ is inelegant ? You are just using the definition of the half-normal distribution unless you are thinking this definition is inelegant...
Comment: Use `halfnorm.rvs(loc = 0, scale = 1, size = 10000)` (the `rvs` method) for example to generate random variables. Found [here](https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.halfnorm.html).
Comment: @COOLSerdash this is exactly what I was looking for. Do you want to add this as an answer instead of a comment?
Comment: @utobi now that you mention it, it's not bad.
Answer: The documentation states the rvs method to calculate random variables from a half-normal distribution. For example:
from scipy.stats import halfnorm, norm
x = halfnorm.rvs(loc = 0, scale = 1, size=1000)

Here, loc specifies the location and scale the scale parameters.


Proof that $2^{ab} - 1$ is divisible by $2^a - 1$

Question: Could you please comment on the correctness and quality of the following proof?
I'm a bit suspicious of the line $n = ab, a = 1, r = 2^a$. Should it be $r = 2$? And are there any "off by one errors? E.g. $n = ab$ vs $n = ab -1$?
To prove:
For $a, b > 1$
$2^{ab} - 1$ is divisible by $2^a - 1$
Explanation:
$2^{ab} - 1$ can be expressed as $\sum_{i=0}^{ab-1}2^i$
Considering the formula for the sum of a geometric series
$S_n = a \frac{r^n-1}{r-1}$
with
$n = ab, a = 1, r = 2^{a}$
we have
$S_n = \frac{(2^a)^b-1}{2^a-1}$
From which it can be seen that $2^a - 1$ is indeed a factor of $2^{ab} - 1$.
$\square$
Comment: In $$n = ab, a = 1, r = 2^{a}$$     There are two **distinct** $a$ variables floating around.  The $a$ in $n=ab, r=2^a$ is the $a$ from the problem statement.  The $a$ in $a=1$ is the $a$ from $S_n = a \frac{r^n-1}{r-1}$.  Needless to say, this is bad practice, since it causes confusion.  (I see this more in programming than I do in mathematics, since then $=$ is assignment rather than equality)
Comment: That seems good.
Comment: Now, replace $2$ with $x$ and $1$ with $y$.
Comment: After some thought.  Are you *allowed* to use the geometric sum formula?  As the geometric sum formula is derived by demonstrating/proving that $(x-1)\sum x^k = x^n-1$ couldn't this proof be circular?  .... or we could simply make this a one line proof "this is simply one case of the geometric sum formula that claims $\sum_{k=0}^{b-1} 2^{ak}= \frac {2^{ab} -1}{2^a - 1}$"
Comment: The proof I know for the geometric sum formula uses $S − S·r$ and cancels out all but the first and last terms giving $S − S·r = a − ar^n$ and factorizing/rearranging.
Comment: Yes, but that proves  $(r-1)S = a(r^n -1)$.  So if $r$ is an integer and $a=1$, then $S$ is an integer and $r-1|r^n-1$ has been proven.
Answer: I'm going to be picky:
You state that $2^{ab}-1=\sum_{k=0}^{ab-1} 2^k$ but never actually use it. So leave it out; it just confuses things.
You should state explicitly that $S_n = \sum_{k=0}^{b-1} (2^a)^k$; as it is written I use confusing it with $\sum_{k=0}^{ab-1}=2^{ab}-1$ which is and entirely different completely irrelevant sum-- I was confused by the first line.
Then I'd like the, admittedly trivial but key, statement that: $S_n$ is an integer (as a finite sum of integers).

I.E. the proof should be:  $S_n= \sum_{k=0}^{b-1} (2^a)^k$ is integer. But $S_n = \frac {(2^a)^b -1}{2^a - 1}$.  So $2^a - 1| (2^a)^b - 1= 2^{ab}-1$.

Otherwise the proof is good.
======
Although......
For the purpose of a stronger proof.
If we can prove that $x-1$ always divides $x^n - 1$ we will be done by letting $x = 2^a$ and $n = b$.
And the formula for the geometric series states precisely that:  That $\sum_{k=0}^{n-1} x^k$ which is clearly an integer is equal to $ \frac{x^n-1}{x-1}$.  So $x-1|x^n -1$.
Of course, it could be that this exercise is expecting you to prove the formula for a geometric series.
Which you should be prepared to do.
Pf:  $(x- 1)(\sum_{k=0}^{n-1} x^k) = x\sum_{k=0}^{n-1}x^k - \sum_{k=0}^{n-1} x^k=$
$\sum_{k=0}^{n-1} x^{k+1} - \sum_{k=0}^{n-1} x^k=$
$\sum_{k=1}^n x^k - \sum_{k=0}^{n-1} x^k=$
$ ((\sum_{k=1}^{n-1} x^k) + x^n)- (x^0 + \sum_{k=1}^{n-1} x^k)=$
$x^n - 1$.
So $\sum_{k=0}^{n-1} x^k = \frac {x^n - 1}{x-1}$.
(Assuming, of course, $x \ne 1$... Obviously if $x = 1$ then $(1-1)\sum_{k=0}^{n-1} 1^k= 0*n = 0 =1^n-1$ which is fairly pointless)
====
More interesting is proving that if $2^m -1$ is not divisible by $2^a-1$ unless $m$ is divisible by $a$.
Answer: If we pick the common ratio to be $2^a$,
\begin{align}
\sum_{i=0}^{ab-1}2^i = \sum_{t=0}^{b-1}\sum_{i=0}^{a-1}2^{at+i} =\sum_{t=0}^{b-1}(2^a)^t \left(\sum_{i=0}^{a-1}2^i\right)
\end{align}
the first term is $\left(\sum_{i=0}^{a-1}2^i\right)$ and we have $b$ terms in total.
That is $$2^{ab}-1=\sum_{t=0}^{b-1}(2^a)^t \left(2^a-1\right)$$
$$\frac{2^{ab}-1}{2^a-1}=\sum_{t=0}^{b-1}(2^a)^t$$
Hence $2^a-1 | 2^{ab}-1$
I usually prove it in the following way:

$x^b-1$ is clearly divisible by $x-1$ since $1^b-1=0$.

Now, we just have to let $x=2^a$


Im trying to use prepared statements with a search bar php

Question: I have a search function on a page, but I need to use prepared statements. It keeps sending back 0 results when trying to use it.
Here is the page where the search bar is.
<form action="search.php" method="post">
    <input type="text" name="search" placeholder="Value To Search">
    <button type="submit" name="search">
    </button>
</form>

this is the search.php page
<?php

$db = mysqli_connect('localhost', 'root', '1234', 'users');

if (isset($_POST['search'])) {

    $search = $_POST['search'];

    $stmt = $db->prepare("SELECT * FROM users WHERE username = ?");
    $stmt->bind_param("s", $search);
    $stmt->execute();

    $result = $stmt->get_result();

    if ($result->num_rows > 0) {

        echo "

Name	id
";

        while ($row = $result->fetch_assoc()) {
            echo "
" . $row["username"] . "	" . $row["id"] . "
";
        }

        echo "
";

    } else {
        echo "0 results";
    }
}
?>

Comment: could you please add your table structure?
Answer: Both your button and your input has the name "search", therefore, your $_POST['search'] does not contain a relevant value. More specifically, it will always be the empty string "" as it will take the value of the last field with this name (e.g the button).
Try changing the name of the input, or the name of the submit button.


Buscar pessoas com nomes similares

Question: Estou desenvolvendo um código para buscar nomes de pessoas de forma inteligente usando o operador LIKE do SQL SERVER.
Em nomes como Souza e Sousa basta usar colchetes [] Ex.:
select * from pessoas where nome like 'joão sou[sz]a%';

O exemplo acima me retorna:
id | nome
-----------------
10 | joão souza araujo
56 | joão sousa dos santos

No caso do exemplo do souza|souza era só substituir a letra, mas no Vitor|Victor em que a letra C é opcional não consegui informações sobre como montar a consulta. Esta é minha dúvida.
Comment: Possível duplicata de [Como fazer um algoritmo fonético para o português brasileiro?](https://pt.stackoverflow.com/questions/1828/como-fazer-um-algoritmo-fon%c3%a9tico-para-o-portugu%c3%aas-brasileiro)
Comment: No Oracle utilizo a UTL_MATCH EDIT_DISTANCE e JARO_WINKLER para sql server uma busca rápida retornou
https://stackoverflow.com/questions/33882620/jaro-winkler-in-sql-server
Comment: @Sorack não conhecia o algorítimo fonético. Vou pesquisar sobre
Comment: Tem uma resposta que tem o algoritmo para o `MySQL`. Eu tenho em algum lugar o mesmo exemplo pra `SQL Server`, mas tenho que procurar...
Answer: Você pode especificar o final do nome dentro do colchetes.
declare @pessoas table
(
  id int,
  nome varchar(100)
)

insert into @pessoas values
(57,'Victor Sousa dos Santos'),
(57,'Vitor Souza Santos')

select * from @pessoas where nome like 'Vi[ctor]%';
--ou
select * from @pessoas where nome like 'Vi[ctor]% Sou[sz]%a [dos Santos]%';

Result.
  57    Victor Sousa dos Santos
  57    Vitor Souza Santos

Buscar pessoas com nomes similares


jquery collapse using image as trigger

Question: I have a simple jQuery collapsible table, where the header row is the trigger to toggle the data i want to show/hide.
What I'm after is to have an image within the header row and use this as the trigger, rather than the row itself.
Here is an example: http://jsfiddle.net/RDybT/
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

        Header

        Data

        Data

I've done some searching but I'm not sure if this is possible or not?
Any ideas or tips would be great.
Thanks
Answer: Try this :
$(document).ready(function() {
    $('#trigger_1').click(function () {
      $('#toggle_1', $(this).parent()).toggle();
   });
$('#trigger_2').click(function () {
      $('#toggle_2').toggle();
   });
 });

Answer: Instead of unneccessary id's and such, I'd approach it as
$('#trigger_2').click(function () {
    $(this).closest('table').find('tr:not(:nth-child(1))').toggle();
});

$(this).closest('table') searches your clicked elements's parent, if it's not a table it searches this elements parents, and so on, until the parent is a table, than the find searches for every tr that is not the first child, and toggles it.
This allows for multiple lines of data that need to be toggled, without spamming id's and classes everywhere.
Answer: I have updated with some better practices like using thead / tbody and wrapping the image in an anchor.
But do you realise if the button is inside the header then you won't be able to click it again. Is that what you meant to do or am I misunderstanding?
http://jsfiddle.net/t4b7X/
$(document).ready(function() {
    $('.table-toggle').click(function(event) {
          $(this).closest('thead').toggle();
          event.preventDefault();
    });
});

jquery collapse using image as trigger


Como disponibilizar conteúdo para download em vez de exibir na página?

Question: Tenho uma aplicação em PHP e uma URL de um arquivo. Gostaria que, quando o usuário clicasse em um botão qualquer, fizesse com que o navegador disparasse a ação para download ou abertura da janela de opções de download desse arquivo (no caso do Firefox).
O arquivo pode ser DE QUALQUER EXTENSÃO, como um código-fonte, um arquivo compactado ou multimídia.
Obs: Download no sentido, servidor -> usuário.
Answer: Se você simplesmente quer fazer o download de um arquivo existente basta colocar o atributo download na tag a:
Clique aqui para fazer o download

Se você deseja que o download seja feito no momento que a página é carregada, basta fazer isso:
<?php

    // Define o tempo máximo de execução em 0 para as conexões lentas
    set_time_limit(0);
    // Arqui você faz as validações e/ou pega os dados do banco de dados
    $aquivoNome = 'imagem.jpg'; // nome do arquivo que será enviado p/ download
    $arquivoLocal = '/pasta/do/arquivo/'.$aquivoNome; // caminho absoluto do arquivo
    // Verifica se o arquivo não existe
    if (!file_exists($arquivoLocal)) {
    // Exiba uma mensagem de erro caso ele não exista
    exit;
    }
    // Aqui você pode aumentar o contador de downloads
    // Definimos o novo nome do arquivo
    $novoNome = 'imagem_nova.jpg';
    // Configuramos os headers que serão enviados para o browser
    header('Content-Description: File Transfer');
    header('Content-Disposition: attachment; filename="'.$novoNome.'"');
    header('Content-Type: application/octet-stream');
    header('Content-Transfer-Encoding: binary');
    header('Content-Length: ' . filesize($aquivoNome));
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Pragma: public');
    header('Expires: 0');
    // Envia o arquivo para o cliente
    readfile($aquivoNome);
?>

Fonte
Comment: Show @Adriano de Azevedo, me ajudou muito com essa dica, valeu


Filtro CLOB - Numero+texto

Question: Tenho um sistema cujo todos os campos de um documento são CLOBs, inclusive combo box com míseros "Sim" e "Não".
Estou construindo uma query, preciso filtrar um campo Clob e os valores são '0||Sim' e '1||Não'.
Eis o que já fiz:

Having campoclob like '0||Sim' Erro:ORA-22835: Buffer muito pequeno
  para conversão  de Clob em Char ou de BLOB em RAW
  (real:4300,Máximo:4.000)
CASE campoclob like '0||Sim' THEN 0 else 1 END Erro:ORA-22835: Buffer
  muito pequeno para conversão  de Clob em Char ou de BLOB em RAW
  (real:4300,Máximo:4.000)

Enfim, tudo o que eu mudo dá o mesmo erro, são 325 resultados que sem filtro mostra o campo com os valores corretos, até usando o case, mas não consigo filtrar que dá o erro. Analisei todos os documentos e não há problema com os campos, como são combobox não tem como o usuário digitar, nos outros meses a query roda sem problemas.
Comment: Ana, seria possível passar o restante da consulta ou montar um simples exemplo no SQLFiddle? CLOB com agrupamentos sempre é uma dor de cabeça ...
Answer: Não tenho como testar agora, mas tenta assim:
<code>Having dbms_lob.substr( campoclob, 4000, 1 ) like '0||Sim'
</code>
Comment: Também já havia tentado com esta função, joguei lá novamente e da o mesmo erro. o problema é no WHERE, quando jogo no where valor=1 ele da o erro de clob
Comment: tenta trim(valor) = '1'

Filtro CLOB - Numero+texto


How do I correctly use jQuery once()?

Question: Due to a module, the Drupal behavior I implemented is called five times instead of once.
(function ($) {
  Drupal.behaviors.myFunction = {
    attach: function (context, settings) {
      // …
    }
  };
})(jQuery);

How do I correctly use jQuery once()?
Comment: Are you using Drupal 7, or Drupal 8? The method is slightly different depending on the version.
Answer: You can use $.once(), which is available in both Drupal 7 and Drupal 8. The code called inside $.once() will only be executed a single time for the HTML element it is called on.
For Drupal 7, you can do this.
(function ($, Drupal) {

  function someElementWatcher(context) {
    // $.once acts like $.each, and loops through the found elements.
    // The code inside $.once() will act on each element in the jQuery object
    // a single time.
    $(context).find(".some_element").once("some-arbitrary-but-unique-key", function () {
      // $(this) refers to the current instance of $(".some_element")
      $(this).click(function () {
        // Do something clicky.
      });
    });
  }

  Drupal.behaviors.someUniqueKey = {
    attach:function (context) {
      someElementWatcher();
    }
  };
}(jQuery, Drupal));

In Drupal 8, the $.once() functionality has changed under the hood, and the method of setting it has changed on the front end. In Drupal 8, $.once() needs to be combined with $.each(). You need to change the following part.
$(context).find(".some_element").once("some-arbitrary-but-unique-key", function () {});

Instead, you need to use this.
$(context).find(".some_element").once("some-arbitrary-but-unique-key").each(function () {});

In Drupal 9, once() stopped to be a jQuery function. To use once() library, first add core/once as dependency of the relevant library in the .libraries.yml file.
some_library:
  css:
    ...
  js:
    ...
  dependencies:
    - core/once

You can now use once() to retrieve a list of elements and loop through them.
const elements = $(context).find(".some_element").once("some-arbitrary-but-unique-key");
elements.each(function () {
  // Do something with the current element.
});

Comment: You need to add *core/jquery.once* as dependency in the .libraries.yml file.
Answer: Drupal provides the jquery plugin once(), which allows you to ensure a function is run only once on any single element. You can use this within your behaviour.
See Drupal.behaviours here: https://www.drupal.org/docs/8/api/javascript-api/javascript-api-overview

How do I correctly use jQuery once()?


simple pigeonhole question

Question: Question from an exam.
In a university there are $40$ students. Every student prepares a list of $20$ other students he is willing to share his room with (Rooms are only able to hold 2 students.)
Show that there are at least $2$ students willing to live with each other.
I honestly can't think of what is the pigeon and what is the pigeonhole. How do you approach such a question?
Answer: If you were to consider a graph where each student is a vertex, and an edge from $a$ to $b$ means "a is willing to live with b", you're looking for two vertices $x,y$ with an edge going in each direction (one from $x$ to $y$ and one from $y$ to $x$).
There are $\binom{40}{2} < 40*20$ such pairs of vertices. Can you take it from there?
Comment: I think I understand you. there are $\binom{40}{2}$ ways to make pairs from the group of the students, and there are 40*20 requests...so there is a couple that has more than 1 request
Comment: Right, and I take it you've already understood what a couple with more than 1 request entails. :)
Answer: Let (i,j) denote that student i wishes to live with student j. There are 1,560 distinct ordered pairs of the form (i,j) with i not equal to j and 1 < i,j < 40. Since the students choose 800 ordered paris there must exist i,j such that (i,j) and (j,i) belong to this list of 800. If we discard (j,i) whenever we include (i,j) we end up with 1600 distinct ordered pairs, which is a contradiction.

simple pigeonhole question


Difference between np.max(x ,axis = 1) and x.max(axis = 1) for numpy array

Question: I am trying to get maximum value of each row of a numpy array matrix. I would like to achieve it efficiently and I came up with the following two idioms for doing this. My question is, is there any performance difference between the following two ways?
x = np.array([[1,2,3],[4,5,6],[7,8,9]])
#array([[1, 2, 3],
#       [4, 5, 6],
#       [7, 8, 9]])

np.max(x,axis = 1)
#array([3, 6, 9])

x.max(axis = 1)
#array([3, 6, 9])

Comment: Seems the real question here is whether these are two APIs to the same function, or are in fact two different functions, and how one might ever be able to tell.
Answer: I tested it out in a notebook and it seems your second method is slightly faster:
import numpy as np
x = np.array([[1,2,3],[4,5,6],[7,8,9]])

First method:
%%timeit
np.max(x,axis = 1)

The slowest run took 11.75 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 4.71 µs per loop

Second method:
%%timeit
x.max(axis = 1)

The slowest run took 12.81 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 3.71 µs per loop

Presumably, this is because for the first one you will have call the numpy module, whereas for the second one, it is already in the object.
However, I would recommend against trying to optimize such small things, and first look at if you did the rest already (did you use a compiler like Numba, did you use a profiler to see what part of your code is slowing you down, etc.)


How do I tell Lilypond to start hymns on new page

Question: I'm typesetting a hymn. For this particular project, it has the following requirements

Every hymn must start on a new page. (Not strethced/spaced out, short hymn scores to sit at the top normally).
If the hymn overflows to the following page (1 or 2 line of music), leave that line of music sits at the top of the page, and start a new hymn on a new page.
Cannot have 2 short hymns on 1 page.

How should I tell Lilypond to do this?
When I tried placing manual \pageBreak as such;
% Include songs from here ----------------------------------------------------------
\include "psalm1.ly"
\pageBreak

\include "psalm2.ly"
\pageBreak

\include "psalm3.ly"
\pageBreak

This gives me the following. Too spaced out.

For The second hymn, it has an overflow 1 music line. But it became too spaced out too! The requirement is to condense the score and leave the hanging 1 extra line music there, and start on a new page.

I feel \pageBreak is not what I am looking for here.
Can someone help me with my typesetting requirements?
Comment: If you want to keep the systems near the top of the page and not stretched over the page, you can add `\paper { ragged-bottom = ##t }`.
Answer: If you do not want stretching at all setting the variable
\paper {
  ragged-bottom = ##t
}

would do the trick. Else you can use \bookpart { ... } for this.
Comment: Thanks. `ragged-bottom = ##t` was exactly what I needed. This works well. As for `\bookPart`, I haven't figured out know how to use it yet. I tried `\bookPart { \include "psalm1.ly"}`, and whole psalm 1 dissapeared from the final output.


How to add 'not equal' condition in form #states

Question: In my form, there are 3 selection list  A, B and C.
I wanna show or hide C based on values of A and B selected.
C should be shown if A's value = 'all and B's value != 'all'
How to set the #state condition in this case?
<code> $form['C'] = array(
        '#type' => 'select',
        '#title' => t('C'),
        '#states' => array(
            'visible' => array(
                ':input[name="A"]' => array('value' => 'all'),
                ':input[name="B"]' => array('value' => 'all') //???how to set !='all' here?
            )
        )
)
</code>
Answer: This code should work:
<code>':input[name="B"]' => array('!value' => 'all')
</code>
Comment: Its working , Thanks
Answer: Although I don't think you can make negative condition with states in D7, you can make C invisible when B value equal all.
<code>$form['C'] = array(
    ...
    '#states' => array(
       'visible' => array(
          ':input[name="A"]' => array('value' => 'all'),
       ),
       'invisible' => array(  // you choose 'invisible' parameter
          ':input[name="B"]' => array('value' => 'all')
       )
    )
)
</code>


Difficulty and established result in the classification of Galois groups of quintic polynomials.

Question: This article provides a classification of Galois groups of cubic and quartic polynomials and criteria to determine it, then I try to find some paper about the same result in quintic equations. However, I find nothing similar.
So I am wondering if there is some fundamental difficulty abandoning people to approach to 5 degree, or it is just because it is less interested and no one wants to do it?
Answer: It is only more complex. The number of possible Galois groups is larger, and the degree of the resolvants needed to discriminate between candidate Galois groups also get larger.
The basic process to compute the Galois group of a polynomial is always the same :
You pick one expression $f(x_1,\ldots,x_5)$ where $x_i$ are the roots of $P$, and look at the subgroup $H_f$ of $S_5$ stabilizing it. You build the resolvant $\prod (X - \sigma(f(x_i)))$ for $\sigma \in S_5/H_f$. Don't be scared, the degree will only go up to $120$ in the worst case. Each coefficient is completely symmetric so can be expressed in terms of the coefficients of the initial polynomial.
Does the resolvant have a rational root ? If yes, great, you have learned that the Galois group of $P$ is included in some conjugate of $H_f$.
Does the resolvant split over $\Bbb Q$ ? If yes, great, you have learned that the Galois group of $P$ is included in the intersection of all the conjugates of $H_f$.
More precisely, the way the resolvant factors over $\Bbb Q$ tells you of the size of the $G$-orbits of $S_5/H_f$. You can still compute the Galois group without having to decide the factorisation over $\Bbb Q$, and only using the rational root test. You simply don't get as much information for each $H_f$, but that's all.

If you have two expressions corresponding to two groups $H_1 \subset H_2$, and if you get a rational root when doing a resolvant for $H_2$, you are lucky because when building your resolvant for $H_1$, you may restrict the product to range over $H_2/H_1$ and not over $S_5/H_1$. When doing that the coefficients obtained are invariant by $H_2$, so you will need to replace them with a rational root of their own resolvant (in a coherent way if the resolvants have several rational roots. In theory you only need one, and all the others are rational fuctions of the coefficients of $P$ and that one rational value. However the dependencies may be a bit long to compute) . This allows you to get a smaller polynomial

Now, all you have to do is carefully plan and choose which $H_f$ you want to use. To do that you will need a nice picture of all possible conjugacy classes of transitive subgroups $G$ of $S_5$, as well as what each possible choice for $H_f$ can tell you about each case once you have factored the resolvant.
For each transitive conjugacy class of $G$ and each $H$ you can compute the size of the $G$-orbits of $S_5/H$. Once you have this down, you can elaborate a strategy of choosing a sequence of $H$ that discriminates among all possible $G$ as fast as possible.
For example, first you will want to use the biggest possible $H$ so that $S_5/H$ is small. So start with $A_5$. If you pick $\prod_{i<j} (x_i-x_j)$, then its resolvant is $X^2 - D$ where $D$ is the discriminant of $P$. So the first question you have to ask is "is this discriminant a square ?"
Answer: The irreducible solvable (by radicals) quintic equations in $\mathbb{Z}[X]$ have been characterized by D.S. Dummit (1991) in Solving Solvable Quintics, his theorem being an irreducible quintic is solvable if and only if an explicit sextic integer polynomial has a rational root.
More recently Boswell and Glasser extended this approach to the irreducible sextic case, where solvability is equivalent to a certain tenth degree equation having a rational root.
Because it acts transitively on the roots, the Galois group of an irreducible quintic must be a transitive subgroup of $S_5$, so the only possibilities for an unsolvable quintic turn out to be Galois group $S_5$ or $A_5$.  For a solvable irreducible quintic the possibilities are the Frobenius group $F_{20}$ of order 20, the dihedral group $D_5$ of order 10, or the cyclic group $Z_5$ of order 5.
Following the discussion at MathOverflow, it seems that improved techniques for computing Galois groups are finding their way in to computer algebra software (CAS) packages.


Regression model for count data with "endogenously" right-censored data

Question: I have the following problem - I try to estimate a tolerance for negatives from a dataset of subjects. Notice negatives here is a count variable, i.e. it takes on values 0, 1, 2, 3...
The data I have reveals for a given dose of negatives how many negatives the subjects have consumed. The issue is that the data is what I would call "endogenously right-censored", i.e. I only observe their tolerance for the negative when they consume less negatives then the dose.
So

subject
time
dose
consumed
tolerance observed

1
sometimestamp
3
2
yes

1
sometimestamp
5
5
no

1
sometimestamp
2
0
yes

2
sometimestamp
3
3
no

3
sometimestamp
5
0
yes

4
sometimestamp
5
4
yes

I am wondering what would be a good regression model to estimate and predict this tolerance? Is there maybe a literature where these types of problems are discussed?
Comment: Why are there three rows for dose = 1?; does each row correspond to a subject? Also, what is the mechanism that determines the value of 'consumed'?; are they assigned a number to consume or something else?
Comment: Hey: sorry - the table was incorrect. Each row corresponds to a subject. But I can have multiple rows per subject (at different points in time). Regarding the mechanism: so they get dose and then they basically can decide what to consume up to the dose, i.e. if dose=5, they can consume 0,1, 2, 3, 4 or 5. Is that helpful?
Comment: the study design is unclear to me. subject 1 was assigned 3 doses and they decided to consume 2 of the 3 dose levels. And then later they were assigned 5 doses and consumed all 5? And later again they were given 2 doses and chose to consume 0? Who is in charge of determining the value of dose and how many times a subject will participate? what causes a subject to decide to consume 0 dose levels or consume all assigned dose levels? Also, it looks like the last column (tolerance observed) is equal to no if the dose column equals the consumed column. is that the definition of tolerance observed?
Comment: hey, thanks. maybe unclear - there is also context information available which explains why one person might have difference tolerance levels. Participation on the subject side lies entirely on the subject side. Regarding the dose: the dose is actually random. regarding what causes the subject to eat the doses: they get an reward and basically need to decide if the reward is worse the dose. last question: yes.
Answer: It seems that you are in a discrete failure time setting. Time is measured by number of doses taken by a subject (time 1 = first dose; time 2 = second dose, and so on), and you are interesting in the distribution of 'time to tolerance'. Formally, let $X$ be the number of doses consumed, and I think you are interested in estimating the survival function $Pr(X > k)$, $k=1,2,\ldots$. For subject $i$ for whom you observe a tolerance, your likelihood contribution would be $\Pr(X = x_i)$.
As you observe, some observations are censored, and you only know that $x_i > n_i$, where $n_i$ is the subject's assigned maximum dose. If you are willing to assume that the censoring process is not informative, then you can just use their likelihood contribution in estimating the model, which would be $\Pr(X > n_i)$.
There are a few things I would be concerned about, however, when it comes time to estimating the model. First, it's not clear to me that the censoring mechanism is non-informative. Do subjects know in advance what the value of dose is and, if so, is there a chance they will 'persevere' to finish all of their assigned dose levels? Second, I would want to know more about why subjects appear in the data more than once. You would want to account for the presumed correlation between observations from the same subject, to be sure, but, beyond that, why do these subjects appear in the data multiple times in the first place? Does that offer information about their tolerance?
Here are some other relevant questions on SE and external links that might be helpful as you start to fit the model.
Prediction: Discrete-Time Event History (Survival) Model in R
https://data.princeton.edu/wws509/notes/c7s6
https://link.springer.com/content/pdf/10.1007%2F0-387-34232-X.pdf
https://www.rensvandeschoot.com/tutorials/discrete-time-survival/
Comment: hey - thanks a bunch. This answer actually helped me enormously to make some progress.
Comment: I'm glad to hear!


Do some measures get no numbers, in an opera score?

Question: I'm counting measures and confirming measure numbers in an opera score, and I've come across a discrepancy.  I wonder what this means about conventions for numbering measures in opera scores in general. Do some measures not get numbers, or did I uncover a mistake?
The situation: it's a piano-vocal opera score. Page 67 has three systems. The first system is measure 620, and is one measure long. The second system is not labelled with a measure number. But it has four measures, then a double-bar-line, then a new key signature and time signature at the end of the system. The third system has its first measure labelled as measure 624.
Since system 1 starts with measure 620, and is one measure long, then system 2 should start with measure 621. However, it is not labelled. Since system 2 has 4 complete measures, system 3 should start at measure 621 + 4 = 625. But the score says 624.
It looks like the notation at the end of system 2, introducing a new key signature and time signature, gets no measure number. I'm can understand that.
What's going on musically? Systems one and 2 are the end of a duet between Violetta and Alfredo. The singers end on the second-last measure of System 2. The music plays out through the last full measure of system 2.  It is a 3/8 measure which ends a phrase. The first two pulses are a chord. The last pulse is a 1/8 rest with a fermata. This measure is a conclusion and a pause, before the music resumes with a new key and time signature and tempo too, as it turns out. In System 3, Gastone enters and starts a new bit of music.
Is there a convention that ending measures like this get no measure number? That would explain why the next measure is labelled 624 instead of 625. Or, is this likely an editorial mistake?
Similarly, if there is a pickup measure at the start of a piece, does that measure usually get a number?
The score, if you are wondering, is Verdi's La traviata, piano vocal score based on the critical edition, published by Ricordi and the University of Chicago Press, c2001. ISBN 8875926743. Since it's a critical edition, I think it's more likely that the numbering is as intended, and I don't understand the rules. But even Ricordi can make mistakes, I suppose.
It would be helpful if I could post a image. Unfortunately the score is under copyright, and I don't want to violate that. I could locate the corresponding measures in one of the public-domain editions at IMSLP. You can look in your own Traviata score: Act I, end of Violetta-Alfredo duet with, "ah! dimenticarmi allor" (system 2), followed by Gastone entering with, "Ebben? Che davo fate?" (system 3).
[Update 1: added more detail to "what's going on musically?" paragraph, and explanation for no image.]
[Update 2: on looking more closely at the end of system 1, I see there is no bar line at the end of the system. Instead there are pairs of turn symbols on each set of staff lines. Together with the absence of a measure number at the start of system 2, this support Pat Muchmore's interpretation that all of system 1 and the start of system 2 form a single measure, which has many more beats than the time signature calls for.]
Comment: I think copyright laws usually permit publishing small parts in cases like this (research, review, criticism, education, ...) so maybe you could re-consider posting an image?
Comment: Is this in any of this part of a recitative? Does the time signature change anywhere but at the beginning of system 3? Does system 1 end in a full measure? A photo of the passage could be very useful.
Final measures are definitely supposed to be numbered. Pickup measures are more debatable.
Comment: musical_coder, that sounds like an answer. Format it as such, and I can give you credit.
Comment: Just did- glad it could help!
Answer: OK, I think I've tracked this down. My college's library doesn't have the specific version of the score you're looking at, but I found the same passage in two different editions. Neither edition has measure numbers, and they deal with barlines very differently during this passage. In one edition, when Violetta starts the word "ah!" and sings the cascading 16th-note and 64th-note melisma all the way through "dimenticarmi al-" is a single measure and the next measure doesn't happen until "-lor" 3 bars before the double bar. Technically this bar has 19 eighth-notes in it, which exceeds the time signature substantially, but that's because it's a cadenza. This long measure actually is split across two systems, but there's no bar line at the end of the first system.
In the other edition, precisely the same music happens, but when the engraver hit the system split they added a barline that isn't in the other edition. However, this barline still doesn't turn either measure into a proper 3/8—this is still a cadenza measure.
Different publishing companies have different house rules about how to handle cadenza measures, but I think most would agree that it's only a single long cadenza measure in reality, and thus I think the decision not to give a new number to the "measure" created by the line break is the correct call. Personally, I wouldn't have put a barline at the end of the first system in order to make this situation clearer, and that's what I'd do if I were putting together a new edition.
Either way, I don't think this is an error, just a collision of two mildly contradictory editorial impulses; i.e. ends of systems should always have barlines vs. cadenzas count as a single mega-measure.
Comment: I think you have it! Based on your answer, I looked more closely at the score. I notice a notation, updated in the question above, which could mean "measure continues on to next system".  Conclusion 1: system 1 and the start of system 2 are one big long measure, not two measures as I incorrectly counted. Conclusion 2: nothing in this discussion points to a rule where some measures get no numbers. Conclusion 3: I have not yet found a mistake in the Ricordi critical edition. Conclusion 4: Pat Muchmore is awesome.
Comment: Ah yes, the edition I looked at that has no barline also uses the same symbol. I think you're right, that must be the meaning.
Answer: It sounds like a mistake in the score. Just like you occasionally see typos in published books, "errata" can pop-up every now and then in a score. I'd recommend using the nearest measure numbers before and after this one to confirm if it's just one fluke, or the entire score is mislabeled.
Comment: I gave more detail in my answer below, but I'm pretty sure this isn't an error in this particular case.


Two Proofs on a Simple Set Concerning Suprema and Maxima

Question: Suppose we have the set
$$\Gamma = \{\frac{n}{n+1} : n \in \mathbb{N}\}$$
We wish to determine what is $\sup \Gamma$ and $\max \Gamma$. We can clearly see that $\sup \Gamma = 1$ and that $\max \Gamma$ does not exist, but to prove this, I would like to know which of the following two proofs is better than the other and why, please.
Proof 1
We construct the following string of inequalities
$$0 < \frac{1}{n} \leq 1$$
$$1 < \frac{n+1}{n} \leq 2$$
$$\frac{1}{2} \leq \frac{n}{n+1} <1$$
Therefore, $\sup \Gamma = 1$ and $\max \Gamma$ does not exist.
Proof 2
Since $n \leq n+1$ for all $n \in \mathbb{N}$, we have
$$0 < n < n+1$$
implying
$$0 < \frac{n}{n+1} < 1$$
rendering the same results as the first proof.
I know that this is trivial, but verification and insight on demonstrating these simple results is what I value to learn more about and christen.
Answer: If you say $\dfrac n {n+1} <1 $, that doesn't prove that $\sup\Gamma=1$, but only that $1$ is an upper bound of $\Gamma$, so that $\sup\Gamma\le 1$.  The supremum is the smallest upper bound.  Here's one way.  Suppose there is some smaller upper bound than $1$, so that $\sup \Gamma<1$.  Notice that
$$
\frac n {n+1} = 1 - \frac 1 {n+1} <\sup\Gamma,
$$
so
$$
1-\sup\Gamma < \frac 1 {n+1}
$$
and thus
$$
\frac 1 {1-\sup\Gamma} > n+1.
$$
Thus $1/(1-\sup\Gamma)$ is an upper bound of all integers, so there is a least upper bound $\sup\mathbb N$ of all integers.  The number $-1+\sup\mathbb N$, being less that $\sup N$, is not an upper bound of $\mathbb N$. For any number $a$, some integer $N$ must be in $(-1+a,a)$.  So $N+1>a$.  Applied to $a=\sup N$ this says $N+1>\sup\mathbb N$.  But no integer can be greater than an upper bound of all integers.  Hence our assumption that there is a smaller upper bound than $1$ is false.
Answer:
I would not call this trivial.
I don't like any of those two since there's missing at least one crucial argument (the sequence is strictly increasing). Just listing true statements (here: inequalities) without arguments or connections is not a proof at all to me.
That said, I like the first one more since the inequality is stronger (and providing a lower bound which on the other hand is not mentioned) and otherwise they're pretty much identical.
Answer: $f(x)=\frac{x}{x+1}\Rightarrow f'(x)=\frac{1}{(x+1)^2}>0$ so it is increasing function, thus min in natural number happens when $n=1\Rightarrow \frac{n}{n+1}=\frac{1}{1+1}=\frac{1}{2}$ and increasing bounded sequence converges to their sup. Thus $\sup \frac{n}{n+1}=\lim \frac{n}{n+1}=1$
Answer: Note that the following are equivalent:
$$\begin{align}\frac{n}{n+1}&<\frac{n+1}{n+2}\\n(n+2)&<(n+1)^2\\n^2+2n&<n^2+2n+1\\0&<1\end{align}$$
Hence, the sequence $n\mapsto\frac{n}{n+1}$ is increasing.
As you've shown in both proof attempts, every element of $\Gamma$ is strictly less than $1.$ Hence, if we can show that $\sup\Gamma=1,$ it follows that $\max\Gamma$ does not exist.
Now, take any $\epsilon>0,$ and note that the following are equivalent: $$\begin{align}1-\epsilon&<\frac{n}{n+1}\\1-\frac{n}{n+1}&<\epsilon\\\frac1{n+1}&<\epsilon\end{align}$$ Readily, there is an $n$ that make these equivalent statements true, and so numbers less than $1$ are not upper bounds of $\Gamma.$ Thus, since $1$ is an upper bound of $\Gamma,$ then $\sup\Gamma=1,$ as desired.


How do you calculate a confidence interval for the difference between 2 dummy variables?

Question: I think I understand how to calculate the confidence interval for the difference in means of 2 groups when there's one dummy variable. You just add or substract 1.96 x (the standard error of the dummy coefficient) to the value of the dummy coefficient, eg b1 +- 1.96 x SE(b1) for a 95% confidence intercal. However as I understand it this only works when one of the groups you want to compare is a reference group (and doesn't have its own dummy variable). What if instead you want a confidence interval of the difference in means between 2 groups, both of which have a dummy? Say the regression is b0 + b1 x X1 + b2 x X2, with both X1 and X2 dummy variables. How do you find the confidence interval of the difference in means between X1 and X2?
Comment: Your regression example is not very clear. Say you have that regression, then you are estimating $b_0$, $b_1$ and $b_2$. Where does the difference in means of X1 and X2 suddenly come from?
Comment: They're different groups. X1 is for people with brown hair, X2 for people with blonde hair and the reference is for other colors. I then want to know confidence interval for the difference in means of the dependent variable (like height), for X1 and X2. If I'd want to know the 95% confidence interval of the difference in means between brown haired and other colours I'd just calculate it as b1+-1.96 x SE(b1), if I understood my handbook correctly. How do I make a similar confidence interval for the difference between blonde and brown haired people?
Answer:
If I'd want to know the 95% confidence interval of the difference in means between brown haired and other colours I'd just calculate it as b1+-1.96 x SE(b1), if I understood my handbook correctly. How do I make a similar confidence interval for the difference between blonde and brown haired people?

Solution 1
The difference between the height of people with brown coloured hair and blond coloured hair is $b_2-b_1$ and the standard error can be computed with the following rule for the variance of a sum of variables
$$Var(b_2-b_1) = Var(b_2) + Var(b_1) + 2 Cov(b_2, b_1)$$
So for this, you also need to know the covariance. Some software and packages for programming languages can give you this covariance. We can also compute it. The covariance is $\sigma^2 (X^TX)^{-1}$ and this $X$ contains an intercept and the dummy variables whether the hair is blue or brown so you get
$$X^TX = \begin{bmatrix}
n_{total} & n_{blue} & n_{brown} \\
n_{blue} & n_{blue} & 0  \\
n_{brown} & 0 & n_{brown} \\ \end{bmatrix}$$
with the inverse
$$(X^TX)^{-1} = \frac{1}{det(X^TX)} \begin{bmatrix}
n_{blue}n_{brown} & -n_{blue}n_{brown} & -n_{blue}n_{brown} \\
-n_{blue}n_{brown} & n_{brown} (n_{total}-n_{brown}) & -n_{blue}n_{brown}  \\
-n_{blue}n_{brown} & -n_{blue}n_{brown} & n_{blue} (n_{total}-n_{blue}) \\ \end{bmatrix} $$
The correlation will then be
$$\rho = \frac{Cov(b_1,b_2)}{\sqrt{Var(b_1)Var(b_2)}} = \frac{-\sqrt{n_{blue}n_{brown}}}{\sqrt{(n_{total}-n_{blue})(n_{total}-n_{brown})}}$$
or
$$Cov(b_1,b_2) = \rho \sqrt{Var(b_1)Var(b_2)}$$
and finally
$$\begin{array}{}
Var(b_2-b_1) &=& Var(b_2) + Var(b_1) + 2 Cov(b_1,b_2) \\ &=& Var(b_2) + Var(b_1) - \sqrt{{Var(b_1)Var(b_2)}}\sqrt{\frac{{n_{blue}n_{brown}}}{(n_{total}-n_{blue})(n_{total}-n_{brown})}}
\end{array}$$
Solution 2
Much easier is to estimate without the intercept. So you have a model like
$$Height = b_{other} X_{other} +  b_{blue} X_{blue} +  b_{brown} X_{brown} $$
and then there won't be a correlation between the estimates $b_{blue}$ and $b_{brown}$ and you can compute it as
$$\begin{array}{}
Var(b_{blue}-b_{brown}) &=& Var(b_{blue}) + Var(b_{brown}) + 2 \overbrace{Cov(b_{blue}, b_{brown}) }^{=0}\\&=& Var(b_{blue}) + Var(b_{brown})
\end{array}$$
Answer: Sextus Empiricus' answer is of course correct, but there is a simpler way to do it.
Consider the original equation:
$$y_i = \beta_0 + \beta_1 x_{1i} + \beta_2 x_{2i} + e_i$$
If $\beta_1 = \beta_2$. then this equation can be reduced to:
$$y_i = \beta_0 + \beta_1 (x_{1i} + x_{2i}) + e_i$$
Now we add another term $\gamma x_{2i}$ to the equation:
$$y_i = \beta_0 + \beta_1 (x_{1i} + x_{2i}) + \gamma x_{2i} + e_i$$
We can rearrange terms to get:
$$y_i = \beta_0 + \beta_1 x_{1i} + (\beta_1 + \gamma) x_{2i} + e_i$$
and by comparing with the original expression we see that $\beta_2 = \beta_1 + \gamma$, or, alternatively, $\gamma = \beta_2 - \beta_1$. This is what you want to estimate.
Consequently, estimating the parameters of:
$$y_i = \beta_0 + \beta_1 z_i + \gamma x_{2i} + e_i, \,\,z_i = x_{1i} + x_{2i} $$
allows us to test $\beta_2 - \beta_1 = 0$ by testing the equivalent $\gamma = 0$ using the standard results displayed by regression packages, and similarly for constructing confidence intervals.


Como fazer divisões no processo de desenvolvimento de software

Question: Temos um projeto todo arquitetado no papel, desenhos, esboços, o que cada parte do sistema vai fazer, mas como podemos gerenciar a equipe, definir por qual parte do código começar? Pelo feed de noticias ou pelo login? Nossa equipe, de 3 desenvolvedores está tendo dificuldade com isso já que somos todos leigos, e não consegui achar quase nada sobre isso na internet. Obrigado.
Mais informações sobre o projeto: Somos 2 programadores de android/java, e um de banco de dados, sem muita experiência claro. Temos que desenvolver um aplicativo em que será preciso login e senha, e um feed de noticias onde aparecerá os amigos que o usuário segue, e também terei de inserir informações do google maps, e tudo isso salvo dentro do banco de dados claro. O que a gente tem dificuldade, é por onde começar, programação? design? Qual parte da programação? Primeiro o maps, ou primeiro o login? Primeiro o feed? Não temos prazo, por isso ta mais tranquilo. Se alguém puder dar algum norte, ou material para ajudar.
Itens:
• Login
• Feed de Noticias
• Botão de gostei
• Google maps
• Compartilhar com facebook
Comment: Talvez seja melhor você delinear a arquitetura do projeto aqui. É só feed e login, não né?
Comment: Por favor edite sua questão explanando sobre o projeto? sem saber qual a realidade do projeto, itens a serem feitos, tempo fica meio complicado opinar ...
Answer: Acho que podem começar respondendo algumas perguntas:

Quais são todas as tarefas necessárias para o projeto (incluindo componentes do sistema, design, aquisição de software, hardware ou qualquer recurso)?
Quais destas tarefas dependem de outras?
Quanto tempo/esforço vai ser necessário para concluir cada tarefa?
Qual é o nível de complexidade de cada tarefa?
Quais tarefas possuem riscos de se tornarem mais custosas ao longo do projeto? Por exemplo, um software em promoção ficará mais caro se for comprado tarde demais, ou uma API que vocês não conhecem bem pode se revelar mais complexa do que o previsto e aumentar o tempo necessário para a tarefa.

As três primeiras questões podem ser dispostas em um diagrama de Gantt para facilitar a análise.
Uma vez que tiverem essas informações, acredito que ficará mais fácil decidir a prioridade de cada atividade. Tarefas que possuam mais dependentes e de maior risco em geral devem ser feitas primeiro, para não bloquear o andamento das demais, dar mais tempo de responder aos riscos antes que eles se tornem críticos e evitar surpresas no final, quando vocês estiverem com o prazo apertado.
Comment: Muito obrigado pela resposta, valeu!
Answer: Inicie pelo projeto, definam claramente cada uma das etapas e organize por ordem de valor, quanto mais agrega valor a aplicação maior a prioridade,Ex:(Base de dados, sistema de login, noticias etc), cada modulo deste tente quebrar mais em tarefas pequenas de 1 dia por exemplo.
da uma pesquisada em scrum que vai dar para vocês terem uma ideia melhor
Comment: Vou dar uma pesquisada sobre scrum. Valeuuu


How can I make this GIF appear correctly?

Question: I created a GIF and it is basically snow particles falling and has a transparent background. Therefore I can have just snow flowing over my other PNGs and images on the app. The problem is that the app loads and the GIF appears all white. Not sure why because I gave it transparency when making it. If I lower the alpha in Xcode I still don't see my old PNGs (usual background image).
This is in my ViewController.m
<code>- (void)viewDidLoad
{

  [super viewDidLoad];

  NSString *filePath = [[NSBundle mainBundle] pathForResource:@"snow" ofType:@"gif"];
  NSData *gif = [NSData dataWithContentsOfFile:filePath];

  UIWebView *webViewBG = [[UIWebView alloc] initWithFrame:self.view.frame];
  [webViewBG loadData:gif MIMEType:@"image/gif" textEncodingName:nil baseURL:nil];
  webViewBG.userInteractionEnabled = NO;
  [self.view addSubview:webViewBG];

  UIView *filter = [[UIView alloc] initWithFrame:self.view.frame];
  //filter.backgroundColor = [UIColor redColor];
  filter.alpha = 0.5;
  [self.view addSubview:filter];
</code>
Comment: set the webviews background to clear color? also not sure if the content of the webview will be transparent... you can make UIImageViews with animated images afaik, you have to give it an array of images though not a gif i think
Answer: You can set your view background Clear color And for animated image you can use UIImageView.
hope this will be work proper.
See Link:: - Click here to get code
Link2::- Click here for code


ASP.NET: How to remove the file name.aspx from URLs

Question: I'm trying to write a rewrite rule for web.config file so that the url will remove the file name from it, meaning:
http://www.example.com/admin/Index.aspx
http://www.example.com/admin/Product.aspx

will become:
http://www.example.com/admin/
http://www.example.com/admin/

AND:
http://www.example.com/Index.aspx
http://www.example.com/Product.aspx

to:
http://www.example.com/
http://www.example.com/Product/

tried a couple of codes found online, but all of them gave me internal error.
Thanks in advance!
Comment: Are you using IIS6 or IIS7? Can you provide an example of the code you've tried so far?
Answer: I have used the open source UrlRewriter to do that on a number of projects, it works very well
http://urlrewriter.net/
In order to make it work you must add it to your web.config file, like so:
<httpModules>
    <add type="Intelligencia.UrlRewriter.RewriterHttpModule, Intelligencia.UrlRewriter" name="UrlRewriter" />
</httpModules>

And add a routing section as well, they have good documentation, but basically you provide rewrite-rules, that could look something like this:
<rewriter>
    <rewrite url="~/([a-zA-Z0-9]+)$" to="~/$1.aspx" />
</rewriter>

Add the UrlRewriter dll-files to your bin, and set IIS to handle wildcards:

Find site in IIS Manager (inetmgr)
Open properties on your site
Go to tab "Home Directory"
Click "Configuration" under Application Settings
Click "Insert" under "Wildcard application maps"
Put path to .NET executable (same as the one used for handling .aspx files) in the "Executable" field
Uncheck "Verify file exists"
Press "OK"

And you are done :)
It's quite a good solution for WebForms projects, but make sure you test it well, and verify that GoogleBot can still access your site.
Comment: hey thanks alot for the info, but i wasn't able to figure out how to install it on Windows Server 2008 and IIS6.. is it possible? is there an easier way of doing this? I just want to remove the "Filename.aspx" from the url, only the filename and extension.
Comment: There might be simpler ways to it .. Step 5 "Insert wildcard application maps" could be used to it perhaps? If you add a wildcard that takes a file name without extension and handles it with .NET (step 5-6), and checks if the file exists, you might get away with just renaming the "file.aspx" to "file" without extension? I'm not sure it will work, and if it does it is quite hacky, but you could try it out :)
Answer: im not sure if you have it but with IIS7 there is a module that you can install that you can set up url rewriting rules. It will add the appropriate rules to the web.config of your site
a guide by Scott Guthrie of Microsoft may help - http://weblogs.asp.net/scottgu/archive/2010/04/20/tip-trick-fix-common-seo-problems-using-the-url-rewrite-extension.aspx
Comment: hey, thanks for your answer. but i have IIS6 running on windows server 2008. will I still be able to do this?


How to docreate a function to do if conditions dependign on content type name

Question: {% if logged_in == false %}

Heading

some text.

something here

    <buttonLearn
    more</button>

{% else %}

 {% endif %}

Hi Folks, in the code example above I have tried do doing some twig foo. It works greate if th user is looged out.
But what if I like to seperate contnet types by machine name?
So for example you have two names lets say article and block
How to make shure that the field is visible on block but not on artivle for logged out users? in short what is the required functioon to get false or true bi a string containing the content type machine name to do something like
 {% if logged_in == false || somefunction= 'content_type_machine_name' %}

Is that possible?
Answer: You can set a variable in hook_preprocess_Hook function which has the content type and then use that variable in twig file.

$node = \Drupal::routeMatch()->getParameter('node');
  $nids = $node->nid->value;
  if($nids){
    $variables['content_type'] = $node->bundle();
  }
Comment: thats $node='content_type' in the if statement?
Comment: {% if content_type == "etc" %}


Order type of well-orderings

Question: Wiki mentions the following for order type on even ordinals.

Consider the set of even ordinals less than ω·2+7, which is:
V = {0, 2, 4, 6, ...; ω, ω+2, ω+4, ...; ω·2, ω·2+2, ω·2+4, ω·2+6}.
Its order type is:
ord(V) = ω·2+4 = {0, 1, 2, 3, ...; ω, ω+1, ω+2, ...; ω·2, ω·2+1, ω·2+2, ω·2+3}.
Because there are 2 separate lists of counting and 4 in sequence at the end.

Unfortunately, I'm at a loss understanding why ord(V) = ω·2+4.  ω·2+4 appears to be a limit on ord(V), then I at least understand that part and that ord(V) = ω·2+4 = all ranks less then this limit, but that is all.
Does anyone have any insight into what Wiki is trying to show?  Also, why does the ordering on the set (total, partial, etc) relate to the infinite limit ordinal ω?
Thanks again!
Answer: The order-type of a well-ordered set is the unique ordinal it is order-isomorphic to.  In this case, you can read off the order-isomorphism from the way the two sets are listed:
$$V = \{0, 2, 4, 6, \dots; \omega, \omega+2, \omega+4, \dots; \omega\cdot2, \omega\cdot2+2, \omega\cdot2+4, \omega\cdot2+6\}$$
$$\omega\cdot2+4 = \{0, 1, 2, 3, \dots; \omega, \omega+1, \omega+2, ...; \omega\cdot2, \omega\cdot2+1, \omega\cdot2+2, \omega\cdot2+3\}.$$
Namely, the isomorphism $f:V\to \omega\cdot 2+4$ is given by $f(0)=0$, $f(2)=1$, $f(4)=2$, $f(6)=3$, and so on, and then $f(\omega)=\omega$, $f(\omega+2)=\omega+1$, $f(\omega+4)=\omega+2$, and so on, and then finally $f(\omega\cdot2)=\omega\cdot2$, $f(\omega\cdot2+2)=\omega\cdot2+1$, $f(\omega\cdot2+4)=\omega\cdot2+2$, and $f(\omega\cdot2+6)=\omega\cdot2+3$.  A bit more formally, we can say we define $f(n)=n/2$ and $f(\omega+n)=\omega+n/2$ for each $n<\omega$, and $f(\omega\cdot 2+n)=\omega\cdot 2+n/2$ for $n=0,2,4,6$.
The fact that this isomorphism $f$ exists proves that $ord(V)=\omega\cdot 2+4$, by definition of order-type.
Comment: That is, for $m\in \{0,1\}$ and $n\in \omega$ let $f(\omega\cdot m+n\cdot 2)=\omega\cdot m+n.$

Order type of well-orderings


Why can't I send a request to update the token through php?

Question: <code>$ret = file_get_contents('https://oauth2.googleapis.com/token', false, stream_context_create([
    'http' => [
        'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
        'method'  => 'POST',
        'protocol_version' => 1.1,
        'content' => http_build_query([
            'client_id' => $client_id,
            'client_secret' => $client_secret,
            'refresh_token' => $refresh_token,
            'grant_type' => $refresh_token
        ])
    ]
]));
</code>
After running the script, I see a 400 Bad Request error. What did I do wrong?
Comment: `\r\n` at the end of the header value definitively looks out of place. If you were passing _multiple_ headers in string form, then there should be a CR LF between each of them, but with just one, I am pretty sure that's wrong.
Comment: Yes, he still is not needed there
Answer: From: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/400

The HyperText Transfer Protocol (HTTP) 400 Bad Request response status
  code indicates that the server cannot or will not process the request
  due to something that is perceived to be a client error (e.g.,
  malformed request syntax, invalid request message framing, or
  deceptive request routing).

That means that most likely, something is wrong with the parameters you are sending in the request. That may not be it, but try removing the <code>\r\n</code> in your header parameter, they seem odd to me.
<code>$ret = file_get_contents('https://oauth2.googleapis.com/token', false, stream_context_create([
    'http' => [
        'header'  => "Content-type: application/x-www-form-urlencoded",
        'method'  => 'POST',
        'protocol_version' => 1.1,
        'content' => http_build_query([
            'client_id' => $client_id,
            'client_secret' => $client_secret,
            'refresh_token' => $refresh_token,
            'grant_type' => $refresh_token
        ])
    ]
]));
</code>
Comment: It turned out, but the following problem arose. After execution, I see a white screen and var_dump returns nothing
Comment: @jajaja var_dump does not ever return "nothing". If you mean you get no output at all from a script that should show at least some, then at this point this would probably a duplicate of https://stackoverflow.com/questions/1475297/phps-white-screen-of-death
Comment: If `file_get_contents` just returns `false`, then that's usually due to the request getting a response with a non-success status code, in that case file_get_contents will discard any response body, unless you explicitly instruct it to behave otherwise (parameter `ignore_errors` set to true in the HTTP context options.)
Comment: I accidentally forgot to remove the exit() line when testing. Now I checked and it gives me an error: HTTP/1.1 400 Bad Request
Comment: Maybe he sends the headers not like this? https://developers.google.com/youtube/v3/guides/auth/server-side-web-apps#offline What is the best way to check what it sends to the server?
Answer: The solution is very simple:
<code>'content' => http_build_query([
      client_id' => $client_id,
     'client_secret' => $client_secret,
     'refresh_token' => $refresh_token,
     'grant_type' => 'refresh_token'
 ])
</code>

Why can’t I send a request to update the token through php?


ReactJs - Why does calling onDelete() with parantheses without an arrow function not work?

Question: Currently learning React, and I am confused as to why this acts the way it does.
My App.JS:
import logo from './logo.svg';
import './App.css';
import Header from './components/Header'
import Tasks from './components/Tasks'
import {useState} from 'react'

function App() {
  let name = "Max";
  const [tasks, setTasks] = useState([
    {
        id: 1,
        text: 'Doctors Appointment',
        day: "Feb 5th at 2:30 pm",
        reminder: true,
    },
    {
        id: 2,
        text: "Meeting at School",
        day: "Feb 6th at 1:30pm",
        reminder: true,
    },
    {
        id: 3,
        text: "Food Shopping",
        day: "Feb 5th at 2:30pm",
        reminder: false,
    },
  ])
  const deleteTask = (id) => {
    alert("deleted " + id);
  }
  return (

      <Tasks tasks={tasks} onDelete = {deleteTask} />

  );
}

export default App;

Tasks.JS basically just displays Task.js as h3s
Task.js:
import {FaTimes} from 'react-icons/fa'

const Task = ({ task, onDelete }) => {
    return (

{task.text} <FaTimes style = {{color:'red', cursor:"pointer"}} onClick = {() => onDelete(task.id)}/>

{task.day}

    )
}

export default Task

So I saw the arrow function for onClick = () => onDelete(task.id) and wondered why I couldn't just do onClick = onDelete(task.id) So I tried that and got some unexpected behavior. Basically, upon the page creation i got the alert that each item had been deleted thrice, and then afterwards nothing happened when I clicked it.
Why does this happen? Like how do I explain this behavior? Why is this arrow function needed?
Answer: If you just use onClick = onDelete(task.id) it will call onDelete on every render of that component.  You're passing the return from that function to onClick.  By using the arrow function, you're passing the function itself, so that when a user clicks on your h3, it will then and only then call that function.
Note - not a great idea to put onClicks on elements like h3s for accessibility reasons.
Comment: So, the arrow function is also just a function right? So when passing it into onClick it's return value is given right? So that means it calls onDelete right? I guess my question is, why does the arrow fuction work differently than the non arrow function here? I don't fully get that. Like your are passing in the function itself but that function is just a call to another one right?
Comment: Correct.  The arrow function is just wrapping your `onDelete` with another function so it can be called on demand instead of being called inline.


Are Wysiwyg and CKEditor modules incompatible now?

Question: Apologies if this question has been raised elsewhere, but I couldn't find anything directly related to it.
I'm in the process of setting up my first Drupal site. I want to be able to include images in the body of posts but without turning on "full HTML". Chapter 4 of Using Drupal (2nd Edition) describes a way of doing that involves using both the Wysiwyg and CKEditor modules.
However, when I install the latest versions of both modules (Wysiwyg: 7.x-2.2; CKEditor: 7.x-1.13), I get the following message on the CKEditor configuration page:

"The WYSIWYG module was detected. Using both modules at the same time may cause problems. It is recommended to turn the WYSIWYG module off (click here to disable)."

If I ignore the message and try to configure Wysiwyg I get the following message:

"The version of CKEditor could not be detected.
  Extract the archive and copy its contents into a new folder in the following location:
  sites/all/libraries/ckeditor
So the actual library can be found at:
  sites/all/libraries/ckeditor/ckeditor.js"

But ckeditor.js is saved in the above directory.
I've tried installing other editors besides CKEditor (e.g., TinyMCE), but I get a similar result.
I've got CKEditor installed and working fine, but it only generates HTML code, not tags that the Media module can process. Consequently, images only appear in "Full HTML" mode, not in "filtered HTML" mode.
I'm really interested in finding out how can I include images in posts using filtered HTML mode (either by using CKEditor/Wysiwyg or by some other method). Very grateful for any suggestions.
Answer: Yes you use one or the other of the CKEditor & WYSIWYG modules.
They both provide the same sort of functionality.
As to which is better is up to your preference. You can try them both and see which one you prefer.


Why my function is being executed only once?

Question: I'm trying to make a program which finds out the longest strand of certain type of subsequence in the DNA, and then write it down into corresponing sub_sequences dictionary value.
The problem is that even though the loop executes 8 times (as much as i need), the function works only on the first execution. What's wrong here?
import sys
import csv

def main():

    # Check for command-line usage
    if len(sys.argv) != 3:
        exit()

    # Read database file into a variable
    database = open(sys.argv[1], "r")

    # Read DNA sequence file into a variable
    DNA_sequence = open(sys.argv[2], "r")

    # Makes a dictionary of kinds of sequences
    sub_sequences = {0: ["AGATC", 0], 1: ["TTTTTTCT", 0], 2: ["AATG", 0], 3: ["TCTAG", 0], 4: ["GATA", 0], 5: ["TATC", 0], 6: ["GAAA", 0], 7: ["TCTG", 0]}

    # Finds the longest match of each STR in DNA sequence

    sub_sequences_length = len(sub_sequences)

    for i in range(sub_sequences_length):
        sub_sequences[i][1] = longest_match(DNA_sequence.read(), sub_sequences[i][0])

    return

def longest_match(sequence, subsequence):
    """Returns length of longest run of subsequence in sequence."""

    # Initialize variables
    longest_run = 0
    subsequence_length = len(subsequence)
    sequence_length = len(sequence)

    # Check each character in sequence for most consecutive runs of subsequence
    for i in range(sequence_length):

        # Initialize count of consecutive runs
        count = 0

        # Check for a subsequence match in a "substring" (a subset of characters) within sequence
        # If a match, move substring to next potential match in sequence
        # Continue moving substring and checking for matches until out of consecutive matches
        while True:

            # Adjust substring start and end
            start = i + count * subsequence_length
            end = start + subsequence_length

            # If there is a match in the substring
            if sequence[start:end] == subsequence:
                count += 1

            # If there is no match in the substring
            else:
                break

        # Update most consecutive matches found
        longest_run = max(longest_run, count)

    # After checking for runs at each character in seqeuence, return longest run found
    return longest_run

main()

Answer: You call DNA_sequence.read() multiple times.
The documentation for TextIOBase::read says:

Read and return at most size characters from the stream as a single str. If size is negative or None, reads until EOF.

In other words, the first time you read the file, it reads the entire file, attemting to call read again, will result in reading nothing and you get an empty string back.

A simple fix is to store the contents of the file in a variable, and reuse that variable:
# Read DNA sequence file into a variable
with open(sys.argv[2], "r") as dna:
  DNA_sequence = dna.read()

Now you can use DNA_sequence variable which contains the contents of the file:
longest_match(DNA_sequence, sub_sequences[i][0])


Linear regression vs. Pearson's

Question: I understand that linear regression is finding the "best fitting line" and Pearson's r is measuring correlation between two variables, but I can't visualize this difference.
I had a project where I was finding if certain brain cancers were correlated to age, or sex for example, and I was advised to use linear regression for this, but from the definition above, in my head it sounds like Pearson's r was what I was looking for?
Can someone clarify this difference?
Answer: Check out this previous post to understand the differences/similarities between the two and how they are related.
I would assume the person advising you was implying that you should look at multiple predictors in the same model (e.g., regression) rather than look at each one separately (e.g., bivariate correlations).
Comment: In short, no. Multiple regression can rule out some competing hypotheses and is thus better than simple regression for inferring causality. Yet, regression tests association, not causation [(link)](https://bit.ly/2F4flKm). Absent controlled experiments, people do use some regression methods to infer causality (e.g. propensity matching, regression discontinuity designs). Yet, using regression in this manner also requires strong theoretical justifications. Multiple regression absent strong theoretical justifications would make a week argument for causality.
Comment: As the post is years old, I would like to ask if you or someone else can elaborate on this part of the highest voted comment:
"Neither simple linear regression nor correlation answer questions of causality directly. This point is important, because I've met people that think that simple regression can magically allow an inference that X causes Y."

Does he/she mean that a multiple regression is needed to infer causality?
Answer: The simple correlation can only be done between two variables. So, if you only wanted to look at age being associated with cancer, then a simple correlation would suffice. If you run a regression with just one variable, it will have the same outcome as the pearson correlation. Regression (or specifically, multiple regression), allows you to enter more than one variable into the model to explain the outcome variable (cancer). So with multiple regression, you could include not only age, but also sex, and even an interaction between age and sex.

Linear regression vs. Pearson's


Integrating with 3 products (Quantum Mechanics)

Question: $$
\int_{-\infty}^\infty\frac{1}{\alpha}(1-\cos\alpha\pi)e^{i\alpha x}\,\mathrm{d}\alpha
$$
Solving this integral is part of solving for a Fourier transformation problem and I am stuck on this integral. I tried treating this integral like another integration by parts but it wasn't doing much to simplify the integral any further.
I separated the integral into two by distributing the ($1/\alpha$)
Answer: I believe we can solve this by consulting a Fourier Transform table and using some basic properties of the Fourier Transform. We rewrite the integral as $$I(\omega) = \sqrt{2\pi}F(\omega) = \int_{-\infty}^{\infty}\frac{1}{t}(1-\cos\pi t)e^{i\omega t}dt.$$ Then we have $$F(\omega) = \mathcal{F}\left\{\frac{1}{t}(1-\cos\pi t)\right\}(\omega) = \mathcal{F}\{f(t)\}(\omega).$$
We can then use the property $$F'(\omega) = \mathcal{F}\{itf(t)\}(\omega)$$ for any Fourier transform pair $f,F$. We then have (From Wolfram Alpha)
$$I'(\omega) = \sqrt{2\pi}i\mathcal{F}\{1-\cos\pi t\}(\omega) = 2\pi i\delta(\omega)-\pi i\delta(\omega-\pi)-\pi i\delta(\omega+\pi).$$
Integrating this and requiring that our function goes to 0 at infinity, we have
$$I(\omega) = \pi i[2H(x)-H(x+\pi)-H(x-\pi)].$$
I'll be the first to admit that this is not my area of expertise so let me know if I messed up.


To which voice does this note belong? The one above or below? thanks

Question:
Which voice does this note belong to? The one above or below? thanks.
Answer: It belongs to both: a dotted quarter in the upper voice and an eighth-note in the lower one.
Comment: Supplement: this can be recognized by the two stems, one per voice.


Why are 32-bit registers divided into 4 parts?

Question: I'm learning about registers. It looks like 32-bit registers are divided up so that they can be accessed as 8-bit registers. This looks very inefficient. Performance would be improved if they didn't do this. So why do they do it?
Also, it costs extra money to design them like this. Why not make the CPU cheaper by not doing it?
Comment: You seem to think they can't be accessed simultaneously -- they can.
Comment: Even if they can, what for? It makes the CPU more expensive.
Comment: What about accessing just 16 bits? How would a 32-bit register be MORE efficient for that? Or accessing 8 bits? There are many times when all is needed is 8 bits. Then you need something in the middle to essentially "dump" those extra bits. THAT's expensive.
Comment: Then why not change it so that people don't need to access 8 or 16 bits. Just have them access 32 bits.
Comment: As I said, that's expensive (in the wasteful sense)
Answer: Because if you're only dealing with 8bit values, it'd be inefficient to have issue all the bitmasks to limit those 32/64bit register to just the 8bits you're working on.
So, x86 registers have
AH/AL = high/low 8bits of a 16bit register
AX = whole 16bit register
EAX = whole 32bit register

It's far more efficient, in terms of instruction size to have
mov ah, 0xXX   (2 bytes)

rather than forcing
mov ax, 0x00XX  (3 bytes)
mov eax, 0x000000XX  (7 bytes)

As for "designing the cpu to make it cheaper" - it's for backwards compatibility. All modern x86 processors are actually internally a RISC design, with a major chunk of silicon dedicated to taking the x86 instructions coming in and converting them into the CPU's own internal micro-ops (which is basically a RISC instruction set).
Comment: What if they didn't need backwards compatibility. Would there still be any good reason to do it?
Comment: Sure, not everyone has to work with only 32bit or 64bit values. And it's not like ah/al are completely seperate transistors from ax or eax. They're just shortcuts to access only certain portions of one single large register.
Comment: If backward compatibility was not taken into considerations, almost all previous programs would be un-usable. Such a small change would make an architecture become completely new, and maybe x86 won't be as success as nowadays.
Comment: @nodeninja 64bits + 32bits/16bit compatiblity of amd64/X86_64 won the case when competing to first 64bits only systems (aka IA-64 with itanium : http://en.wikipedia.org/wiki/Itanium) because all had to rewritten or at least adapted. When you disrupt technology too much, user field resists more...
Answer: The Intel 8080, which was the first "mainstream" microprocessor, had seven main 8-bit registers (A, B, C, D, E, H, and L).  Because memory addresses were 16 bits, instructions that needed to use a non-constant memory operand would use a pair of registers (most commonly H and L, but sometimes B and C, or D and E) to form the address.  Because the registers in the aforementioned pairs were often used together to represent 16-bit values, there were a few instructions which could operate upon the register pairs as 16-bit quantities.  An instruction to add BC to HL would perform the addition by adding C to L, and then by adding B to H (plus a carry if needed).  I'm not familiar enough with the 4004 or 8008 (the two predecessors of the 8080) to know if either of them did anything similar in its architecture.
When Intel produced the 8088, they included a full 16-bit arithmetic unit, but they wanted code which was written for the 8080 to be easily convertible to their new architecture.  On the 8080, a lot of code had been written to "manually" form addresses out of the 8-bit parts, since doing so was often much faster than using the 16-bit instructions to do the math.  For example, if one needed to access some specified table of 256 entries with an index stored in A, one could have done something like (Zilog notation show, but the 8080 had the same instructions):
ld   hl,(baseOfTable) ; 16-bit address
ld   c,a
ld   b,#0
add  hl,bc
ld   a,(hl)

but if one could make certain the table was aligned on a 256-byte boundary, one could simplify the code considerably:
ld   l,a
ld   a,(tableBaseMSB) ; Just load the MSB--assume the LSB is zero
ld   h,a
ld   a,(hl)

With the 8088 instruction set, it wouldn't terribly often be useful for code written "from scratch" to access the upper and lower parts of registers separately, but there was a lot of code written for the 8080 which used such techniques, and Intel wanted to make it easy for people to convert such code for use on the 8088.  Allowing registers to be built from 8-bit pieces was helpful in that regard.
Incidentally, there was another advantage to Intel's architecture: since it included four 16-bit only registers and four registers which could be used as either one 16-bit or two 8-bit parts, that made it possible for code to hold 12 values in registers if eight of them were 255 or less, or eleven values if six of them were 256 or less, etc.  When using architectures with more registers, eking out an extra register here and there isn't quite so important, but on the 8088 it was often very helpful.
Answer: The ability to address portions of the registers has no effect on their performance when used as 32-bit registers. In that case, this capability just isn't used.
CPUs, regardless of their native bit size, need to manipulate 8-bit values very, very often. Strings of text, for example, are frequently manipulated as consecutive 8-bit values. International character sets are often manipulated as sets of consecutive 16-bit values. So being able to operate rapidly on 8-bit and 16-bit values is of tremendous importance.
If you're asking as a practical matter for x86 CPUs, it's too late. The very first PC CPUs didn't even have 32-bit registers, and compatibility has been retained all the way through.
Comment: No, all that extra wiring doesn't make things more complex, expensive, and slow. Gates and wiring are cheap and nearly free. That's why we can make a CPU for $150 that has a billion of them on it. And making characters 32-bits would be a performance disaster because they would need four times as much space in memory, in cache, and on the bus when being transferred.
Comment: You can always fake it with bit operations. Many RISC CPUs do not have any way to address parts of their registers and requires you to fake it with bit operations. But you'd be surprised how many cases there are where you need to operate on small data objects. Pretty much every wire format (including IP and TCP) requires this. Almost every file and transfer format requires this (HTTP, XML, BER, and so on).
Comment: What if they didn't need to maintain compatibility? Wouldn't it be better to not do it?
Comment: No, because the cost is as close to zero as makes no difference and the benefits are enormous because have to manipulate strings of characters frequently.
Comment: All that extra wiring doesn't make things more complex, expensive, and slow? Why not make characters 32 bits instead?
Comment: But what about other CPUs, like for embedded systems? Do they do this too? Do they need to process characters?
Answer: Backwards compatibility. Processor manufacturers did not wanted to break compatibility with old software. This is the main reason why x86_64 processors still support 16bit software(virtual mode). If you look closely you'll see that majority of the features in x86 architecture are shaped by compatibility concerns. I'm no hating.


How to keep the last tab open in accordion after page refresh?

Question: I created a According store for my store with a link in the title that searches for products. However, is there an option to add a code to this that will open the last opened page before reloading the page? My website - https://www.styl-bruk.eu/
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>CSS Animated Accordion</title>
    <link rel="stylesheet" href="styles.css">

      Polbruk

     [elementor-template id="12389"]

      Bruk-Bet

     [elementor-template id="12389"]

I can't find any code that would work this way and I don't know that well.
Comment: Yes, there's an option to do that: write some code. What have you tried to resolve the problem? Where are you stuck? Is this a JS problem, a HTML problem, a PHP problem, or a WooCommerce problem?
Comment: You need to store the state somewhere, including the accordion which was open, and then reload that when the page refreshes. Options might include localstorage in the browser, Session on the server, etc.
Answer: You should use wp_options to save the selected tab in database.
The process could be as follows:
1- Send Ajax call on expanding the accordion tab.
2- Store the selected tab using add_option() function.(This could be element's id or attribute)
3- When page loads you will need a second Ajax call that will get option that you stored above using get_option() function.
4- Add the active class to that tab which you get from function.
Note: I suggested using ajax as I'm considering you are doing it via Elementor(Not using template file/backend)


PHP Funciona Local (XAMPP - PHP 5.5.33) mas não funciona no Servidor (PHP 5.5.31)

Question: Estou fazendo uma API, e localmente está perfeita. O problema é quando testo ela no servidor.
Criei ela em um subdomínio, exemplo: http://api.dominio.com
E estou testando em outro subdomínio: http://teste.api.dominio.com
Localmente os endereços estão assim:
API:   http://localhost/api/public_apiv1
Teste: http://localhost/api/public_apiteste
Obs.: A estrutura de pastas está igual no servidor. Quando eu faço uma requisição inválida localmente a API me retorna uma estrutura assim:
{
   "error": 401,
   "message": "Permissão negada."
}

Porém quando testo no servidor o AJAX não retorna nada, apenas é exibido o seguinte erro no console:

Antes eu estava redirecionando para o Controller e Action do erro:
self::$controller->request->redirect(Route::href('error/unauthorized'));

Então pensei que redirecionamentos não funcionava com requisições AJAX, então mudei a estrutura para imprimir o resultado do Controller e Action:
exit(self::$controller->controller('Error', 'unauthorized'));

Porém continuou da mesma forma.
Já coloquei pro servidor imprimir os erros:
ini_set('display_startup_errors',1);
ini_set('display_errors',1);
error_reporting(E_ALL);

E pra aceitar requisições CORS:
header('Access-Control-Allow-Origin: *');

Porém nada é retornado do servidor.
UPDATE
A minha aplicação roda o seguinte código:
public static function validateAccess() {

   if (!self::validateApplication()) {
      exit('Está entrando aqui');
      self::$controller->request->redirect(Route::href('error/unauthorized'));
   }

}

O exit acima é exibido, se eu remove-lo e coloca-lo no Controller do redirecionamento, não é exibido mais:
class ErrorController extends Controller {
   public function unauthorized(){
      exit('unauthorized');
      return self::returnError('Unauthorized');
   }
}

O método redirect possui o seguinte código:
public function redirect($params = NULL){

   if (empty($params))
      return $this->header('Location: ' . Route::href());

   if (is_string($params))
      return $this->header('Location: ' . $params);

   if (is_array($params)){

      $controller = empty($params['controller']) ? 'main' : $params['controller'];
      $action = empty($params['action']) ? 'index' : $params['action'];

      return $this->header('Location: ' . Route::href("{$controller}/{$action}"));
   } else
      return $this->header('Location: ' . Route::href());

   exit;
}

public function header($content) {
   header($content);
}

Comment: @rray é ai que está o problema, não vem nenhum erro. Sobre o _cors_ eu já adicionei o cabeçalho `header('Access-Control-Allow-Origin: *');`
Comment: @rray segundo a imagem anexada o problema é sim com cors: `Motivo: a pré-conexão CORS falhou`
Comment: Era bem isso que estava suspeitando, menos uma hipotese.
Comment: Por acaso o seu servidor é SoftLayer?
Comment: Não, é YCorn...
Comment: Há um tempo atrás, em uma simples aplicação, eu recebi um erro parecido com o teu. Não sei se aplica ao teu caso, mas o problema foi algumas diretrizes de segurança aplicados no firewall do servidor, não saberei te dizer exatamente o que foi.
Comment: O servidor não está rejeitando as requisições, mas está acontecendo o seguinte, quando eu tento redirecionar está abortando a requisição.
Comment: @rray atualizei a pergunta com alguns trechos de código...
Comment: @MarcelodeAndrade atualizei a pergunta com alguns trechos de código...
Comment: Fiz vários testes e o código está executando até o momento do redirecionamento, mas nada é executado após isso. Requisições AJAX não são redirecionadas?
Comment: Aonde exatamente adicionou `header('Access-Control-Allow-Origin: *');`? Quando ocorre o redirecionamento a página seguinte também precisará de CORS. Outra coisa, esta usando `ob_start` em algum lugar?
Comment: Guilherme, estou utilizando o Allow-Origin logo no início dos _script_, e como é um MVC, todas as requisições possui o Allow-Origin. Estou utilizando `ob_start`. apenas no carregamento da `view`. Conversei com um professor da faculdade e ele comentou que isso pode ser uma configuração padrão dos browsers, onde uma requisição _cross-domain_ não pode ser redirecionada por motivos de segurança.
Answer: Após vários testes constatei que redirecionamento não funciona com requisições Ajax, provavelmente por algum motivo de segurança, quando o browser recebe o código 301 de redirecionamento ele já interrompe a requisição.
A solução encontrada foi encerrar a execução do script com o Controller para o qual iria redirecionar:
exit(self::$controller->controller('Error', 'unauthorized'));

Answer: Já faz tempo seu post, mas fica para os que entrarem futuramente. Por padrão os navegadores bloqueia requisições cross domain, e é o que aconteceu com você.
Você requisitou em api.domain sendo que estava em teste.api.domain.
Uma alternativa para permitir requisições ajax cross domain é usar jsonp ao invés de json. o jsonp é muito semelhante com json com a diferença que é encapsulado em uma função e quando chega ao browser é executado para obter os dados. Este tipo de dados os browsers permitem fazer cross domain.
Geralmente quando se vai construir uma api que retorne jsonp é conveniente permitir que o client envie no corpo da requisição como parâmetro o nome padding
exemplo:
http://api.domain/users/3?jsonp=foo
o retorno será algo como:
foo({"Name": "Otto", "Id" : 3, "Age": 30});
Desta maneira o client pode determinar o que precisa para o correto parse.


Some commits are on two branches. Why?

Question: I have two branches: Voip and Elastic.
In some commits are showing "2 branches". Why this happens?
Comment: Is this only the case before you seperated your branches?
Answer: It means that 2 branches "have" this commit, or to rephrase it in git terms, that this commit is reachable through 2 branches.
Nothing unusual or problematic per se.
Example :
A---B---C <<< branch1
     \
      D---E <<< branch2

Here, both A and B would feature the same "2 branches" mention.
(You could, for the sake of the experiment, create a new branch at B, and then observe the mention "3 branches" on A and B.)
Comment: There is a way to rollback it? Or remove this commits from just only one branch?
Comment: I'm not sure about exactly *what* you want to rollback. If the situation is the result of an unwanted merge, it can be reverted, or if you're alone on the branch, its history can be rewritten, there are solutions, but we know far too few about your situation to safely advise anything. Could you describe the problem you're facing? (other than this "2 branches" mention which unsettled you)
Answer: This happens typically when changes have been merged from a branch into another.
The commits will appear on both the branches,So if you had ever:

merged voip into elastic
Created voip from elastic

Or similar situations.
And like RomainValeri has mentioned it is nothing to worry about. In fact it gives  a way to trace back commit, via the path.

Some commits are on two branches. Why?


Function with linearly decreasing difference between subsequent outputs

Question: How can we find a function for a conversion table with the following properties? The range of both inputs and outputs is $[0..100]$; inputs are integers.
$$f(0) = 0$$
$$f(100) = 100$$
$$f(1) - f(0) = 2(f(100) - f(99))$$
So, $f(1)$ should be $1.\bar3$ and $f(99)$ should be $99.\bar3$. The difference between subsequent outputs is linearly decreasing, so $f(50)-f(49)\approx 1$.
Answer: Let $a_n=f(n)-f(n-1)$. Then $a_1=\frac{4}{3}$ and $a_{100}=\frac{2}{3}$. Since the differences are linearly decreasing, we have $a_n=\frac{4}{3}-\frac{n-1}{99}\frac{2}{3}$.
Hence $f(n)=a_n+...+a_1+f(0)=\frac{4n}{3}-\frac{2}{297}(1+...+(n-1))=\frac{4n}{3}-\frac{n(n-1)}{297}=\frac{n(397-n)}{297}$.
Comment: Thanks for the question edit, although outputs obviously aren't integers. I fixed that.
Comment: Thank you very much. Now I can use the same logic to verify for different ratios (where ratio in my example was 2, between $f(1)-f(0)$ and $f(100)-f(99)$).


observer event for the customer delete action in Magento

Question: i want observer event for the customer delete action in magento.
There is any observer is there for that or i create custom observer.
I Search a lot but not find the observer for the customer delete action in admin grid area
Comment: are you want which observer is trigger when customer is creating or else?
Answer: The customer model extends Mage_Core_Model_Abstract which has a _beforeDelete() and _afterDelete() methods. Each delete method fires 2 dispatch events:
_beforeDelete():
Mage::dispatchEvent('model_delete_before', array('object'=>$this));
Mage::dispatchEvent($this->_eventPrefix.'_delete_before', $this->_getEventData());

_afterDelete():
Mage::dispatchEvent('model_delete_after', array('object'=>$this));
Mage::dispatchEvent($this->_eventPrefix.'_delete_after', $this->_getEventData());

Too hook into these events, just set the config.xml of your module to fire methods when the customer model is in the process of being deleted. The customer model's $_eventPrefix value is 'customer', so the following should fire MyModule_Model_Observer:: onCustomerDeleteDoThis() right before the customer object is deleted:
<events>
    <customer_delete_before>
       <observers>
          <my_module_delete_customer>
            <class>mymodule/observer</class>
            <method>onCustomerDeleteDoThis</method>
          </my_module_delete_customer >
        </observers>
     </customer_delete_before>
</events>

Answer: I Done Is Works for me..there is observer event is there for magento customer delete after
<customer_delete_commit_after>`

</customer_delete_commit_after>

Use the Observer to the customer delete after event


Return statement in python 3

Question: How is if else working fine in this code snippet without any syntactical errors.
def even_or_odd(number):
    return 'Odd' if number % 2 else 'Even'

In Python3 if and else introduce code blocks and should be terminated by ":" (a colon), but in the code snippet above inside return statements there is no ":" after if and else.Why is python not showing syntax error
Answer: if and else only require colons when used in statements. But here they are used in an expression. No colons are allowed in the expression. The Python grammar has the rule:
test: or_test ['if' or_test 'else' test] | lambdef

No need to be surprised here, it is very common for languages to use the same words or symbols for completely different things in different contexts. For example, in Python, the * is used both for multiplication and for packing and unpacking list elements.

Return statement in python 3


How to wrap line by command line option

Question: In most case, I don't want the vim to wrap line, is there command line options could I set to let vim launch with wrap line?
I've tested the following command, but failed
vim --cmd "set wrap" -do origin.txt new.txt

Answer: see vim -h there is a -c flag to execute a command after the initialization so vim -c "set wrap" should do it
Answer: if you used --cmd, your command will be executed before the vimrc settings. That is, the settings could be overwritten by vimrc.
Try -c, this will be executed after the file was read.

How to wrap line by command line option


Specify missing image icon

Question:
Possible Duplicate:
jQuery/Javascript to replace broken images

This should be easy I just don't know the terminology to be googling for.  I think this is HTML/CSS, if an image link is broken it often shows a missing image icon showing a page with red, green, blue shapes.  In HTML is it possible to configure "use this image if an image link is broken?"
Comment: Note that, despite jQuery in the title of above link, the answer is purely based on standard Javascript
Comment: @Icarus: only the accepted answer. A jQuery answer is available below.
Comment: Voting to reopen because while the questions are similar, I don't think a question asking for a CSS solution can be a duplicate of a question asking for a JavaScript solution. Even if the only possible solution is to *use* JavaScript regardless.
Comment: Wasn't sure where client side this should be happening but js is a pretty reasonable place it would be handled.  This works for me.
Comment: [Duplicates should NOT be deleted.](http://meta.stackexchange.com/questions/32311/do-not-delete-duplicates)
Answer: An 'onerror' example:

http://jsfiddle.net/u4hQd/
Answer: I think the heart of this is how to add dynamic functionality to CSS. I don't know of an if/else check in CSS apart from detecting browsers, however, this is what I would do if I ever need to do something like this.
If you are using php you can do this:
$imagename = "image.png";
if (file_exists($imagename)){
   echo '
';
} else {
   echo '
';
}

Then in the css you can have
.exists{background:url("../img/git-sprite.png") no-repeat 0px -32px;}
.dne{background:url("../img/git-sprite2.png") no-repeat 0px -32px;}

This way you can add an if/else functionality for this in the CSS itself. You don't have to use PHP, I'm sure a javascript would work as well
Answer: Are you using php?
You could check before sending the file with something like this:
$filename = "whatever.png";
if (file_exists($filename)){
   $html = "";
} else {
   $html = "";
}
echo $html;

Comment: Just because it is tagged as html/css doesn't mean that he isn't using php.  This is a perfectly valid solution, offering another viewpoint.
Comment: This is not what's wanted, the OP wants this client side.
Comment: No it's not, for example he could be writing a userscript or a template. I can't imagine this solution being useful in any situation.
Comment: fwiw this isn't useful to me personally as yes, we do have a business reason (like, charged per harddrive access) not to do it server-side in this manner.
Comment: This is another solution, by the way, @nightcracker, server side validation idea, as proposed by ajon, is way better over client-side. By many reasons.
Comment: interesting another person posted a nearly identical solution.  Maybe you should step out of your box and realize there are inumerable ways to solve problems using an inumerable number of languages.  Even if this solution doesn't help this person, it could help someone else viewing the post.  Stop abusing the down arrow.
Answer: Your question is understandable without any additional terminology.
Unfortunately there are no means in HTML for what you want.
What you can do is use JS (jQuery will help), to cycle through all img tags in your document, and check which of them have images (check against null). For those, who miss their images, you can load some other image (some default).
But remember to run this script after the page has completely loaded (with all assets: JS, CSS, images), because if you run it before page loading is done, you may mistakenly put default image to some img tag, which had no time to load it's real image.
Comment: The proposed solution is bad, the event `"onerror"` was specifically made for this problem.
Comment: @nightcracker, I did not say his terminology was unclear, but since he mentioned, he "just don't know the terminology", I wrote it is understandable without any additional terms.
Comment: Sorry I misread, which is why I edited it out :)
Comment: So, please, read the posts next time before being rude.

Specify missing image icon


Available IDE's for Oracle iStore jsp.

Question: I am working with Oracle Apps, customizing jsp pages for oracle iStore applications.Now, we are using Dreamweaver for viewing and editing jsp pages.The page may be coded with html,scriptlets and styles. I am new to iStore applications and can we use Eclipse as IDE for this jsp pages. Or any other better IDE available for this?
Answer: You can use eclipse IDE for editing the jsp file.
Jdeveloper is the IDE specified by oracle for use in oracle applications.

Available IDE's for Oracle iStore jsp.