Prove that sum of the $k$ numbers in the $k$th group = ${\frac{1}{2}\left(k(k^2+1)\right)}$.

Question: Consider an arrangement of the positive integers, grouped as shown, so that the $k$th group has $k$ elements: $(1),(2,3),(4,5,6),(7,8,9,10), \ldots$.
The expression for the sum of the $k$ numbers in the $k$th group turns out to be ${\frac{1}{2}\left(k(k^2+1)\right)}$.
However, how would you prove this? I am assuming that you would have to proof by induction, but I can't seem to construct it as of now.
Comment: Each "group" is a finite AP, and its sum is half the number of terms times the "average" term.
Comment: How would you prove this theorem though using induction (or any other method)?
Comment: The induction lies in the formula for the sum of consecutive terms in an arithmetic progression.
Comment: @LordSharktheUnknown Actually, the sum an arithmetic progression is the number of terms times the "average" term, or alternately, half the number of terms times the sum of the first and last terms, as shown in [Arithmetic progression](https://en.wikipedia.org/wiki/Arithmetic_progression).
Answer: Let $a_{i,j}$ be the $j$'th term of the $i$'th group. The first element of the $k$'th group is the sum of the previous $1$ to $k - 1$ groups, plus $1$. Since each $i$'th group has $i$ elements, from Arithmetic progression, the first term of the $k$'th group is
$$a_{k,1} = 1 + \frac{(k-1)(1 + (k - 1))}{2} = 1 + \frac{k(k-1)}{2} \tag{1}\label{eq1}$$
Since the last term of the $k$'th group would be $1$ less than the first term of the $(k+1)$'th group, \eqref{eq1} gives it would be $\frac{k(k+1)}{2}$. Thus, the sum of the $k$'th group is
$$\begin{equation}\begin{aligned}
S_k & = \frac{k(a_{k,1} + a_{k,k})}{2} \\
& = \frac{1}{2}k\left(1 + \frac{k(k-1)}{2} + \frac{k(k+1)}{2}\right) \\
& = \frac{1}{4}k\left(2 + (k^2 - k) + (k^2 + k)\right) \\
& = \frac{1}{4}k\left(2 + 2k^2\right) \\
& = \frac{1}{2}(k(k^2 + 1))
\end{aligned}\end{equation}\tag{2}\label{eq2}$$
Answer: I noticed two patterns:

kth group has k numbers
last number of kth group is a triangular number = $\large {k(k+1) \over 2}$

First number of kth group = $\large {k(k+1) \over 2} \normalsize - k + 1$
Mean of kth group = $\large{k(k+1) - k + 1 \over 2} = {k^2+1 \over 2}$
Sum of kth group = $\large {k(k^2+1) \over 2}$


Fazendo ação em todos os dados

Question: Estou desenvolvendo um sistema de anúncios, onde é possível enviar ofertas ao dono do anúncio e depois realizar a aprovação ou rejeição da oferta, caso aprove e depois negociar com quem ofertou.
Me deparei em um problema: Quando tem apenas uma oferta eu consigo aprovar ou rejeitar, mas caso tenha mais do que uma oferta quando clico em alguma opção ele faz isso para todas as ofertas...
Dei uma procurada aqui pelo fórum, mas não encontrei nada parecido.
Segue o código (obs: quando joguei o código aqui ele bagunçou a identação):

Ofertas recebidas

                                <?php
                                $id_usuario = $_SESSION["id"];
                                $anuncio = $_GET["id"];

                                $sql = "SELECT * FROM ofertas = OF
                                INNER JOIN anuncios = AN
                                ON OF.id_anuncio = AN.ID
                                WHERE AN.id_usuario = '$id_usuario' AND OF.status = 'ANALISE'";

                                while($sql = mysql_fetch_array($query2))
                                { ?>

ID do usuário que enviou a oferta: <?php echo $sql['id_usuario_oferta']; ?>

ID da oferta: <?php echo $sql['ID_OF']; ?>

ID do anúncio: <?php echo $sql['ID']; ?>

Usuário que enviou a oferta: <?php echo $sql['nomeusuario_oferta']; ?>

Produto: <?php echo $sql['produto']; ?>

Valor oferta: <?php echo $sql['valoroferta']; ?>

Valor de recompensa que você informou: <?php echo $sql['valorrecompensa']; ?>

Viagem que ele irá fazer: <?php echo $sql['viagemcompra']; ?>

Comentário: <?php echo $sql['comentario']; ?>

Oferta enviada em: <?php echo $sql['dataoferta']; ?>

            <form method="post" action="">
         <button type="submit" name="aceitar" id="aceitar" value="NEGOCIACAO"class="btn btn-success btn-flat">Aceitar</button>
         <button type="submit" name="rejeitar" id="rejeitar" value="REJEITADO" class="btn btn-danger btn-flat">Rejeitar</button>
     </form>

                   <?php
                $IDoferta = $sql['ID_OF'];
                if(isset($_POST['aceitar'])) {
          $query = "UPDATE ofertas SET status = 'NEGOCIACAO' WHERE ID_OF = '$IDoferta'";
             mysql_query($query);
             echo "<meta http-equiv='refresh' content='0, url=index.php'";
       } ?>

   <?php
         $IDoferta = $sql['ID_OF'];
        if(isset($_POST['rejeitar'])) {
            $query = "UPDATE ofertas SET status = 'REJEITADO' WHERE ID_OF = '$IDoferta' LIMIT 1";
            mysql_query($query);
            echo "<meta http-equiv='refresh' content='0, url=index.php'";
      } ?>

    <?php

} ?>

Comment: Esse erro geralmente acontece quando tem um erro na cláusula `where` do sql, que em vez de fazer a alteração em uma linha do banco, pelo id por exemplo, faz isso a todas linhas. Acho que o erro está depois do where. Troque o `'$IDoferta'` por `" + $IDoferta + "`
Comment: Opa Guilherme, muito obrigado amigo! Consegui resolver com a resposta abaixo.
Answer: Como o if que verifica se existe $_POST['aceitar'] está dentro do laço while, independente da oferta escolhida ele é executado para todas as linhas do banco. Uma forma de evitar isso é tirar os ifs que checam por $_POST['aceitar'] e $_POST['rejeitar'] de dentro do laço while e colocar um input do tipo hidden dentro do form junto com os botões aceitar e rejeitar (serve para enviar o id da opção escolhida). Veja como fica:

Ofertas recebidas

                    <?php
                    $id_usuario = $_SESSION["id"];
                    $anuncio = $_GET["id"];

                    $sql = "SELECT * FROM ofertas = OF
                    INNER JOIN anuncios = AN
                    ON OF.id_anuncio = AN.ID
                    WHERE AN.id_usuario = '$id_usuario' AND OF.status = 'ANALISE'";

                    while($sql = mysql_fetch_array($query2))
                    { ?>

ID do usuário que enviou a oferta: <?php echo $sql['id_usuario_oferta']; ?>

ID da oferta: <?php echo $sql['ID_OF']; ?>

ID do anúncio: <?php echo $sql['ID']; ?>

Usuário que enviou a oferta: <?php echo $sql['nomeusuario_oferta']; ?>

Produto: <?php echo $sql['produto']; ?>

Valor oferta: <?php echo $sql['valoroferta']; ?>

Valor de recompensa que você informou: <?php echo $sql['valorrecompensa']; ?>

Viagem que ele irá fazer: <?php echo $sql['viagemcompra']; ?>

Comentário: <?php echo $sql['comentario']; ?>

Oferta enviada em: <?php echo $sql['dataoferta']; ?>

                        <form method="post" action="">

                            <input type="hidden" name="ID_OF" value="<?php echo $sql['ID_OF']; ?>">
                            <button type="submit" name="aceitar" id="aceitar" value="NEGOCIACAO"class="btn btn-success btn-flat">Aceitar</button>
                            <button type="submit" name="rejeitar" id="rejeitar" value="REJEITADO" class="btn btn-danger btn-flat">Rejeitar</button>
                        </form>

    <?php
    }
    ?>

<?php
/******************************************************************************************
Verifique a submissão do formulario fora do laço while
******************************************************************************************/
if(isset($_POST['ID_OF'])){
    $IDoferta = $_POST['ID_OF'];
    if(isset($_POST['aceitar'])) {
        $query = "UPDATE ofertas SET status = 'NEGOCIACAO' WHERE ID_OF = '$IDoferta'";
            mysql_query($query);
            echo "<meta http-equiv='refresh' content='0, url=index.php'";
    }
    if(isset($_POST['rejeitar'])) {
        $query = "UPDATE ofertas SET status = 'REJEITADO' WHERE ID_OF = '$IDoferta' LIMIT 1";
        mysql_query($query);
        echo "<meta http-equiv='refresh' content='0, url=index.php'";
    }
}
?>

Comment: Cara, era isso mesmo!!! Testei aqui e ficou perfeito! Muito obrigado meu amigo!

Fazendo ação em todos os dados


find pair of rows with largest value difference in pandas dataframe

Question: i have a large dataframe containing the x,y,z coordinates of a surface.
i am looking to find the pair of rows with the largest slope between them (dz/sqrt(dx^2+dy^2))
maxGrad = 0
currentGrad = 0
height = 0

for i in range(len(df)):
  for j in range(i+1,len(df)):
      height = abs(df.z.iloc[j]-df.z.iloc[i])
      distance = math.sqrt((df.x.iloc[j]-df.x.iloc[i])**2+(df.y.iloc[j]-df.y.iloc[i])**2)
      currentGrad = height/distance
      if currentGrad > maxGrad:
          maxGrad = currentGrad
          maxCoorPair = [df.x.iloc[i],df.y.iloc[i],df.x.iloc[j],df.y.iloc[j]]
print(maxGrad, maxCoorPair)

However this is not very elegant and the run time is very long due to the nested for loop.
How can i do it better?
Answer: As often it depends of the size of the problem.
Lets do some investigations
Conclusions:
Numpy arrays are faster than even if no Numpy function is used. .
The use of numpy functions still accelerates but at the expense of:

some initialization time
a loss of precision which leads to warnings

Investigations
init
from collections import namedtuple
import pandas as pd
import numpy as np
import math

Run = namedtuple('run', ['order', 'npa', 'df'])
def generate(maxorder):
    run_list = []
    for n in range(1, maxorder + 1):
        order = n
        npa = np.random.random(size=(10**n, 3))
        run_list.append(Run(order, npa, pd.DataFrame(npa, columns=list('xyz'))))

    return run_list

runs = generate(5)

tools
from functools import wraps
import time

def timeit(func):
    @wraps(func)
    def timed(*args, **kw):
        start_time = time.time()
        result = func(*args, **kw)
        end_time = time.time()
        print(f"{func.__name__}  {(end_time - start_time) * 1000} ms")
        return result
    return timed

def prints(f, data, max_order):
    for order,npa,df in runs[:max_order]:
        print()
        print("Order:", order)
        maxGrad, maxCoorPair = f(df if data == 'df' else npa)
        print("maxGrad:", maxGrad)
        print("Pair:")
        print(maxCoorPair)

Solutions
original solution
@timeit
def sol_original(df):
    maxGrad = 0
    currentGrad = 0
    height = 0

    for i in range(len(df)):
        for j in range(i+1,len(df)):
            height = abs(df.z.iloc[j]-df.z.iloc[i])
            distance = math.sqrt((df.x.iloc[j]-df.x.iloc[i])**2+(df.y.iloc[j]-df.y.iloc[i])**2)
            currentGrad = height/distance
            if currentGrad > maxGrad:
                maxGrad = currentGrad
                maxCoorPair = [(df.x.iloc[i],df.y.iloc[i]),(df.x.iloc[j],df.y.iloc[j])]
    return maxGrad, maxCoorPair

prints(sol_original, 'df', 3)

Order: 1
sol_original  2.979278564453125 ms
maxGrad: 4.274082602280762
Pair:
[(0.08217955028694601, 0.9160537098844143), (0.2396284679279188, 0.8196073645585937)]

Order: 2
sol_original  264.29247856140137 ms
maxGrad: 167.5282986999116
Pair:
[(0.09926115331767238, 0.7497707080285022), (0.09615387652529517, 0.7469231082687531)]

Order: 3
sol_original  24213.2625579834 ms
maxGrad: 1246.4073209631038
Pair:
[(0.8285207768494603, 0.016839864860434428), (0.8285102753052541, 0.016228726039262287)]

solution numpy1.0 : substitute np array to df
@timeit
def sol_numpy10(npa):
    maxGrad = 0
    currentGrad = 0
    height = 0

    for i in range(len(npa)):
        for j in range(i+1,len(npa)):
            height = abs(npa[j][2]-npa[i][2])
            distance = math.sqrt((npa[j][0]-npa[i][0])**2+(npa[j][1]-npa[i][1])**2)
            currentGrad = height/distance
            if currentGrad > maxGrad:
                maxGrad = currentGrad
                maxCoorPair = [(npa[i][0],npa[i][1]),(npa[j][0],npa[j][1])]
    return maxGrad, maxCoorPair

prints(sol_numpy10, 'np', 3)

Order: 1
sol_numpy10  0.0 ms
maxGrad: 4.274082602280762
Pair:
[(0.08217955028694601, 0.9160537098844143), (0.2396284679279188, 0.8196073645585937)]

Order: 2
sol_numpy10  13.963699340820312 ms
maxGrad: 167.5282986999116
Pair:
[(0.09926115331767238, 0.7497707080285022), (0.09615387652529517, 0.7469231082687531)]

Order: 3
sol_numpy10  998.3282089233398 ms
maxGrad: 1246.4073209631038
Pair:
[(0.8285207768494603, 0.016839864860434428), (0.8285102753052541, 0.016228726039262287)]

solution numpy1.1: idem numpy1.0 and optimize i coordinates
@timeit
def sol_numpy11(npa):
    maxGrad = 0
    currentGrad = 0
    height = 0

    for i in range(len(npa)):
        xi,yi,zi = npa[i]
        for j in range(i+1,len(npa)):
            height = abs(npa[j][2]-zi)
            distance = math.sqrt((npa[j][0]-xi)**2+(npa[j][1]-yi)**2)
            currentGrad = height/distance
            if currentGrad > maxGrad:
                maxGrad = currentGrad
                maxCoorPair = [(xi,yi),(npa[j][0],npa[j][1])]
    return(maxGrad, maxCoorPair)

prints(sol_numpy11, 'np', 3)

Order: 1
sol_numpy11  0.0 ms
maxGrad: 4.274082602280762
Pair:
[(0.08217955028694601, 0.9160537098844143), (0.2396284679279188, 0.8196073645585937)]

Order: 2
sol_numpy11  10.002613067626953 ms
maxGrad: 167.5282986999116
Pair:
[(0.09926115331767238, 0.7497707080285022), (0.09615387652529517, 0.7469231082687531)]

Order: 3
sol_numpy11  771.9049453735352 ms
maxGrad: 1246.4073209631038
Pair:
[(0.8285207768494603, 0.016839864860434428), (0.8285102753052541, 0.016228726039262287)]

solution numpy1.2; idem numpy1.1 and optimize j coordinates
@timeit
def sol_numpy12(npa):
    maxGrad = 0
    currentGrad = 0
    height = 0

    for i in range(len(npa)):
        xi,yi,zi = npa[i]
        for j in range(i+1,len(npa)):
            xj,yj,zj = npa[j]
            height = abs(zj-zi)
            distance = math.sqrt((xj-xi)**2+(yj-yi)**2)
            currentGrad = height/distance
            if currentGrad > maxGrad:
                maxGrad = currentGrad
                maxCoorPair = [(xi,yi),(xj,yj)]
    return(maxGrad, maxCoorPair)

prints(sol_numpy12, 'np', 3)

Order: 1
sol_numpy12  0.0 ms
maxGrad: 4.274082602280762
Pair:
[(0.08217955028694601, 0.9160537098844143), (0.2396284679279188, 0.8196073645585937)]

Order: 2
sol_numpy12  8.97526741027832 ms
maxGrad: 167.5282986999116
Pair:
[(0.09926115331767238, 0.7497707080285022), (0.09615387652529517, 0.7469231082687531)]

Order: 3
sol_numpy12  1075.1206874847412 ms
maxGrad: 1246.4073209631038
Pair:
[(0.8285207768494603, 0.016839864860434428), (0.8285102753052541, 0.016228726039262287)]

solution numpy2.0
Riley's answer
def d(vector):
    return vector.apply(lambda x: x-vector).values

@timeit
def sol_numpy20(df):
    slopes = np.abs(d(df["z"]))/np.sqrt(np.square(d(df["x"])) + np.square(d(df["y"])))
    maxGrad = np.nanmax(slopes)
    ind1, ind2 = np.where(slopes==maxGrad)
    maxCoorPair = [df.iloc[ind2]]
    return maxGrad, maxCoorPair

prints(sol_numpy20, 'df', 4)

Order: 1
10
sol_numpy20  6.981372833251953 ms
maxGrad: 4.274082602280762
Pair:
[          x         y         z
6  0.239628  0.819607  0.867972
5  0.082180  0.916054  0.078804]

Order: 2
100
sol_numpy20  42.88601875305176 ms
maxGrad: 167.5282986999116
Pair:
[           x         y         z
95  0.096154  0.746923  0.135159
45  0.099261  0.749771  0.841247]

Order: 3
1000

<ipython-input-201-ce6f8e091e1b>:7: RuntimeWarning: invalid value encountered in true_divide
  slopes = np.abs(d(df["z"]))/np.sqrt(np.square(d(df["x"])) + np.square(d(df["y"])))
<ipython-input-201-ce6f8e091e1b>:7: RuntimeWarning: invalid value encountered in true_divide
  slopes = np.abs(d(df["z"]))/np.sqrt(np.square(d(df["x"])) + np.square(d(df["y"])))
<ipython-input-201-ce6f8e091e1b>:7: RuntimeWarning: invalid value encountered in true_divide
  slopes = np.abs(d(df["z"]))/np.sqrt(np.square(d(df["x"])) + np.square(d(df["y"])))

sol_numpy20  625.3554821014404 ms
maxGrad: 1246.4073209631038
Pair:
[            x         y         z
991  0.828510  0.016229  0.893811
240  0.828521  0.016840  0.131971]

Order: 4
10000

<ipython-input-201-ce6f8e091e1b>:7: RuntimeWarning: invalid value encountered in true_divide
  slopes = np.abs(d(df["z"]))/np.sqrt(np.square(d(df["x"])) + np.square(d(df["y"])))

sol_numpy20  12746.904850006104 ms
maxGrad: 4346.72025021119
Pair:
[             x         y         z
3751  0.538723  0.168160  0.131924
1063  0.538800  0.168028  0.798256]

Answer: example data:
df = pd.DataFrame(
    {
        "x":[1,5,3],
        "y":[12,10,13],
        "z":[4,4,1],
    }
)

let's define a function which takes a vector of length n, and returns a n x n numpy array where the element in row i and column j is given by the difference of the ith and jth element in the vector
def d(vector):
    return vector.apply(lambda x: x-vector).values

For example
d(df["x"])

gives
array([[ 0, -4, -2],
       [ 4,  0,  2],
       [ 2, -2,  0]], dtype=int64)

Plug this method into your formula like so, to perform calcs for all pairs of coordinates at once
slopes = d(df["z"])/np.sqrt(np.square(d(df["x"])) + np.square(d(df["y"])))

slopes looks like this
array([[        nan,  0.        ,  1.34164079],
       [ 0.        ,         nan,  0.83205029],
       [-1.34164079, -0.83205029,         nan]])

Note that in the formula, the absolute value of dz is not used.  This is deliberate in order to not end up with answers of the form "(a,b) and (b,a)".
We can then use numpy.nanmax which calculates the maximum of an array, ignoring nan values, and use numpy.where to pull out the rows and columns which match the maximum found
cols, rows = np.where(slopes==np.nanmax(slopes))

We can then zip these up to get tuples of coordinates
list(zip(rows, cols))

which gives us [(0, 2)]
So the largest slope is between the coordinates in rows 0 and 2
Comment: works as advertised. awesome.


Como fazer uma galeria do tipo mosaico

Question: Bom pessoal, eu gostaria que alguém pudesse me indicar algum link ou me da uma luz de como fazer uma galeria tipo mosaico, como no link: http://todomundoodeiaochrisonline.blogspot.com.br/
Esse estilo ai é do blogspot e eu gostaria de algo parecido.
Answer: Você estaria querendo um plugin jquery como esses?

http://masonry.desandro.com/
http://sapegin.github.io/jquery.mosaicflow/
http://codecanyon.net/item/jquery-tiles-gallery/full_screen_preview/2281417
http://ed-lea.github.io/jquery-collagePlus/

acredito que são bons exemplos.
Comment: Por mais que a resposta esteja nos **links**, acredito que somente eles não fornecem uma resposta a questão .Aconselho fazer um tipo de resumo, colocar exemplos e o código na resposta.
Se acaso os links forem desativados a resposta não será mais útil para futuros usuários.

Como fazer uma galeria do tipo mosaico


Can you define an AJAX request without making the request in jQuery?

Question: With jQuery you can make an ajax request like this:
request=$.ajax({
  url: "test.html",
});

request.success(function(){
    alert('Yay!');
});

However, let's say I didn't want immediately make the ajax request.  I just wanted to define it and bind it to an event.  Is there a way to do that?
Comment: Why won't you write the ajax in that event?
Comment: Are you sure this success callback will be fired that way?!
Comment: @gdoron So I can use it a couple times and I think it is slightly neater to write it out first and then call it.

The answer to your second question is yes.
Answer: $("#but").click(function() {
  $.ajax({
    url: "test.html",
    success: function(){
      //...
    }
  });
});

Answer: Would this suit your need?
function callMeLater() {
    $.ajax({
        url: "test.html",
    });
}

//and later

$(selector).anyevent(function() {
    callMeLater();
});

Comment: i use this method allot you can even expand on it t put in different parameters by passing an object through the callMeLater function
Answer: Not really sure why you would do this but you could do something like this:
var ajaxParams = {
   cache: false,
   success: function(){...
}

$("something").click(function(){
    $.ajax(ajaxParams);
});

Answer: Yes, sure.
$(document).ready(function() {
  $('#somebutton').bind('click',function(){
    $.ajax({
      url: "test.html"
    });
  });
});


NHibernate Dynamic Columns Number

Question: In my C# project I need create in code one database with one table with dynamic columns number. Like this
------------------------------------------------------------------------------
| Time        ¦ Element #1       | Element#2        ¦ ... ¦ Element#N        ¦
------------------------------------------------------------------------------
¦ TimeValue#1 ¦ Element#1Value#1 ¦ Element#2Value#1 ¦ ... ¦ Element#NValue#1 ¦
¦ TimeValue#2 ¦ Element#1Value#2 ¦ Element#2Value#2 ¦ ... ¦ Element#NValue#2 ¦
                                      ...
¦ TimeValue#M ¦ Element#1Value#M ¦ Element#2Value#M ¦ ... ¦ Element#NValue#M ¦
------------------------------------------------------------------------------

I use simple SQL query 'SQL CREATE TABLE'
public void AddTable(string TableName, Dictionary<string,Type> columns)
{
    ...
    string query = @"CREATE TABLE " + TableName + "(";

    foreach (var c in columns)
    {
        SqlParameter temp = new SqlParameter();
        string t = SetSQLType(ref temp, c.Value).ToString();
        query += c.Key + " " + (t == SqlDbType.NVarChar.ToString() ? (t + "(200)") : (t)) + ",";
    }

    query = query.Substring(0, query.Length - 1);
    query += " )";
    ...
}

But I think, maybe, I can use more comfortable ORM for this, for example - NHibernate. Can i? I read about mapping-by-code and dynamic component, but I'm not sure, what exactly I need to do in my case.
I think, I need something like this:
public class Elements
{
    public virtual DateTime Timestamp { get; set; }
    public virtual IEnumerable<double> Values { get; set; }
}

Can I mapping this class?
Answer: This topic is interesting. And maybe not so clear at first look. Take my answer as an overview, a summary from all the sources listed below. And maybe it will give you the answer.
From the C# point of view, you can think about these dynamic properties this way
public virtual IDictionary<keyType, valueType> Additional { get; set; }
                 // (e.g. <string, object>

public virtual IDictionary Additional { get; set; }

Both of these are dynamic. There is no compile-time checking for handling IDictionary. Better situation is the generic arguments checking for IDictinary<,>. But because we are talking about dynamic mapping, the compile time check is what we can sacrifice...
To load data into one of these dictionaries we have to (in most cases) do different mapping and have different structure of tables. The Generic would be handy for transpostion of data contained in rows. The Non-Generic could be used for column mapping (as the example in the question). Let's discuss both
1) Generic IDictionary<,> - Dynamic rows
Let's start with more type safe scenario. Then touch solution close to the question
1a) Ternary Associations
For example, let's map a few Persons to some Entity (e.g. Contract) based on their roles/types. 1) Manager 2) Leader 3) Tester. If we know that there could be only one person per type/role (only one Tester or none), we can explain it as:
public virtual IDictionary<PersonType, Person> Persons { get; set; }

We are dynamic right now. There could 0, 1 or 1+ Persons related to the Contract. Each of them has to be unique by the PersonType. And we can also introduce new PersonTypes in a runtime, and extend any Contract's related Person set...
The mapping should be like this
<map name="Persons" table="ContractPerson" >
    <key column="ContractId"/>
     <index-many-to-many column="PersonTypeId" class="PersonType"/>
     <one-to-many class="Person"/>
</map>

This is an example of 6.9. Ternary Associations. There are three entities involved, and we still do have flexibility in the runtime. As already said, we can insert new PersonTypes and amend these Contract-Person relations.
This scenario (in comparison with IDictiniary<string, object>) still provides lot of compile-time checking.
1b) Closer to the Question
In the scenario described above, if we would like to use <map> and be dynamic from a rows perspective - we need a table like this:
ElemntId| TheKey       | TheValue (e.g. nvarchar)
1       | "name"       | "Element A"
1       | "time"       | "20:02"
1       | "date"       | "2013-05-22"
1       | "value"      | "11.22"

C# would look like this
public class Elements
{
    ...
    public virtual IDictionary<string, string> Values { get; set; }
}

mapping:
<map name="Values" table="DynamicElementValues" >
   <key column="ElementId"/>
    <index column="TheKey" type="string"/>
    <element column="TheValue" type="string"/>
</map>

Because we've used IDictionary<string, string> all values are strings. We would need some MetaData to correctly interpret its value
We gained:

dynamic collection of many values of many types

We lost:

ability to put any value into SELECT or ORDER BY clause
have to convert data types (from a string into any other)

1c) Key as a string

In fact, dictionary with a string key is dynamic, but too much. As
  shown in the 1a) it is always better idea, to somehow manage the set
  of values to be used as a key. That's why we've discussed Ternary
  associations. Because we sooner or later have to interpret the data in
  this dictionary - with some MetaData, it could be handy to use them
  also as a key...

2) Non-Generic IDictionary - Dynamic columns
This time we will really try to do dynamic solution over columns.
The NHibernate features, we can use here are:

4.4. Dynamic models,
5.1.13. component, dynamic-component,
5.1.18. join

This kind of mapping is very close to the Question, to our requirement. We will have this C# representation
public class Elements
{
    ...
    public virtual IDictionary DynamicValues { get; set; }
}

And this could be the mapping:
<join table="ElemntValues" >

  <key column="ElementId" />
  <dynamic-component name="DynamicValues"   >

    <property name="Time"        type="TimeSpan" />
    <property name="Date"        type="DateTime" />
    <property name="Salary"      type="decimal" />
    <property name="Color"       type="string" />
    <property name="WorkingDays" type="integer"  />
    <many-to one....
    ...

  </dynamic-component>
</join>

In this case, we do have separted table ElementValues, joined to our Parent entity (as a part of its <class> mapping).
This is not the only mapping. There could be other mapping types e.g. with 4.4. Dynamic models
<class entity-name="DynamicValues"...

These could require some more special handling (insert, udpate, delete)
Join would simplify lot of stuff, but will be used in a SQL statment always (even if only Parent core properties are required)
Is it dynamic?
Well we gained:

On a C# we have only property IDictionary ElementValues
NHibernate does for us runtime checks. Only correct types of value could be inserted to the keys (Salary must be decimal)
with some MetaData model we can really be dynamic to the user
Any of the Mapped properties could be used in SELECT (projections) and ORDER BY (user will love it)

We lost:

some performance, because all data (e.g. session.Get<>(id)) will be loaded
we are not dynamic, in case of adding or removing columns. All the mapping is part of the application distribution, and cannot be change in runtime. Well, we can always re-deploy just new mapping...

2b) IDictionary and MetaData

While the IDictinary is from a C# perspective very dynamic (it could
  contain any key/pair value), due to NHibernate mapping, the content is
  managed. Only integer values could be added to the properties mapped as
  integer. But how would we in a runtime know: what keys we do have? what
  values could be placed there and retrieved from there? Again, we need
  some MetaData... not acting the role of a key, but they will be
  crucial in the runtime. NHibernate checks are last line of defense.

3) How to change mapping in the runtime (new column added)?
Well, what is stated in the documentation? 7.5. Dynamic components:

The advantage of this kind of mapping is the ability to determine the
  actual properties of the component at deployment time, just by editing
  the mapping document. (Runtime manipulation of the mapping document is
  also possible, using a DOM parser.)

...using a DOM parser. To be honest, I do not know what that mean, how to implement that.
And also Adam Bar in Mapping-by-Code - dynamic component stated (see comments)

I think that dynamic component can't be really dynamic at both object
  and database level. Note that the component parts are stored as
  ordinary columns, so we need to know its list...

But there is a nice idea from Firo - NHibernate dynamic mapping (take a look, too complex for some extract). If really needed, this could be solution to a real dynamic world... new columns in runtime ... new keys mapping in IDictionary
Summary
With a <map> mapping we can be very dynamic. Different keys and values in runtime. No need to redeploy. But we cannot use these dynamic properties in a select or order by. It is hard to filter by these values
With a <dynamic-component> we are (out of the box) dependent on the mapping. But we do have our data in columns and therefore we can use joins to retrieve them. Easy to filter, sort. And/but there must be some metadata to guide us what we do have and what we can do.
Other Sources:

Ayende Dynamic component
Adam Bar, Mapping-by-Code - dynamic component
Firo and runtime mapping replacement
4.4. Dynamic models
7.5. Dynamic components
Comment: Thanks for your answer. Very helpfull. Now I can dynamic generate columns, and its wonderfull. But I got another question. Is it posible in NHibernate creating one class and many maps for it.
Comment: If, for example, I need 10 tables from class 'Elements', it is possible realize in NHibernate?
Comment: The amount of tables, columns ... is not a limitation for NHibernate.
Comment: But what about 'Duplicate class/entity mapping Error'? For One Class only One Table?
Comment: Ok, Now I understand how I can do this, Just need create many configuration, one configuration for one table. Thanks alot for your help.

NHibernate Dynamic Columns Number


pushbuttonfield with double byte character

Question: Searched around on Google as well as stackoverflow but didn't see this come up anywhere. I need a pushbuttonfield with double byte characters as the text. Does anybody know if this is possible?
Currently if I set the button text as any double byte text, the text won't show up. It shows up fine if it's just in the body of the PDF.
Edit#1: Double byte character set (DBCS) like Japanese, Russian, Dutch, etc.
Edit#2:
PushbuttonField myButton = new PushbuttonField(writer, rect, "myJapaneseButton");
myButton.setText("japanese text here");

Comment: What do you mean by double byte? Are you referring to wide character strings?
Comment: Ideally, please give a short but complete program demonstrating the problem. It's very unclear at the moment.
Answer: Please take a look at the CreateJapaneseButton example. It creates a PDF with a button that looks like this:

Your code snippet is very short, but you probably have all the code you need, except the line that sets the font:
public static final String JAPANESE = "\u3042\u304d\u3089";
public static final String FONT = "resources/fonts/FreeSans.ttf";

public void createPdf(String dest) throws IOException, DocumentException {
    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(dest));
    document.open();
    PushbuttonField button = new PushbuttonField(writer, new Rectangle(36, 780, 144, 806), "japanese");
    BaseFont bf = BaseFont.createFont(FONT, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
    button.setFont(bf);
    button.setText(JAPANESE);
    writer.addAnnotation(button.getField());
    document.close();
}

If you don't set the font, the default font is used. The default font is the Standard Type 1 font Helvetica. This font doesn't know how to write Japanese. I used the font freesans.ttf. If you don't have that font, you can try arialuni.ttf or any other font that supports Japanese.


objective-C syntax beginner question

Question: what is the syntax to use an object (NSString) that declared in another class?
object workId in class works, i want to use it's value in class jobs.
thanks.
Answer: Go here:
http://www.cocoadevcentral.com/d/learn_objectivec/
And scroll down to the "Properties" section.
Answer: if you declared workId as a property and synthesized it, you should be able to access it using works.workId or [works workId]
http://developer.apple.com/mac/library/documentation/cocoa/Conceptual/ObjectiveC/Articles/ocProperties.html
Comment: i need to declare it also in jobs class ?
Comment: You'll need to import the header for your works class into your jobs class' implementation, so jobs knows about works and what it can do.
Answer: If you'd like to hold a pointer to the same object you can declare a second property in the Jobs class using 'assign' or 'retain', if you'd just like a copy you could declare the property using 'copy'.
@property(nonatomic, copy) NSString* theString;

If Jobs has a pointer to Works like so:
@interface Jobs
{
    Works* works;
}
@property (nonatomic, retain) Works* works;
@end

You could just use self.works.workId to access the work id from within an instance of the Jobs class.
Could you let us know a little more about your particular use case, it would help to determine what you should be doing.
Answer: in Person.h:
#import <Foundation/Foundation.h>

@interface Person : NSObject {
    NSString * name;
}
@end

in Person.m:
@implementation Person

- (NSString*) name {
    return name;
}

- (void)setName:(NSString *)aName {
    [name autorelease];
    name = [aName copy];
}

@end

objective-C syntax beginner question


Como mudar a tipagem em Haskell

Question: Quero que a função sorteie um número e, se este for maior que 7, mande uma mensagem de aprovação e chame essa função adicionar. Entretanto, minha função só cai no 'else'. Aparecendo a mensagem "reprovado". Acredito que seja a tipagem de IO Float com Float. Como resolver?
sortear :: Float -> Int
sortear x = ceiling(10 * x)

numeroSorteado :: IO ()
numeroSorteado = do
    num <- randomIO :: IO Float
    print $ sortear num
    if(num >= 7) then
        do
            putStrLn ("Aprovado!" ++ "\n") >> adicionar
        else
        do
            putStrLn "Reprovado!"

adicionar = do
    putStrLn "Nome:"
    nome <- getLine
    putStrLn "Sobrenome:"
    sobrenome <- getLine
    putStrLn "CPF:"
    cpf <- getLine
    putStrLn "Idade:"
    idade <- getLine
    putStrLn "Salario:"
    salario <- getLine
    putStrLn "Cargo (Estagiario, Analista, Gerente, Diretor, VicePresidente ou Presidente) :"
    cargo <- getLine
    let new =  (nome ++ " "++ sobrenome ++ " " ++ cpf ++ " " ++ idade ++ " " ++ salario ++ " " ++ cargo ++ "\n")
    appendFile "funcionarios.txt" new
    putStrLn "Funcionario Salvo!"

Comment: A função ``adicionar`` não parece ser importante para reproduzirmos seu problem. É recomendável que você só coloque o código daquilo que interessa, e apague o restante para evitar distrações. Isso se chama exemplo mínimo: https://pt.stackoverflow.com/help/mcve
Answer: O problema no seu código deve-se à linha que contém a seguinte informação:

num <- randomIO :: IO Float

Este num nunca será maior que 1, visto que randomIO :: IO Float gerá unicamente números de virgula flutuante que sejam menores que 1.
Uma solução para este problema passará pela implementação da função randomRIO de tipo randomRIO :: Random a => (a, a) -> IO a que gerá um número, limitado a um certo intervalo.
Uma possível resolução:
numeroSorteado :: IO ()
numeroSorteado = do
       num <- randomRIO (1::Float,20::Float)
       print $ sortear num
       if(num >= 7) then
           do
               putStrLn ("Aprovado!" ++ "\n") >> adicionar
           else
           do
               putStrLn "Reprovado!"

Como mudar a tipagem em Haskell


Converter string em XML

Question: Considerem a tabela:

No code behind, eu não consigo converter uma string em um xml
  modCamadaOperacao objModCamada = new modCamadaOperacao();
  objModCamada.idCamadaOperacao = idCamada;
  objModCamada.xmlCamadaOperacao = serializer.Xml; // XML_CAMADA_OPERACAO

No caso a string é o serializer.Xml
o erro que retorna é:

Cannot implicity convert type string to system.Xml.XmlDocument
Comment: Quem ta negativando por favor se manifeste, pois nao vejo motivos para isso.
Answer: Tente usar esta conversão.
public static class Serializa
{
    public static string SerializaParaString<T>(this T valor)
    {
        XmlSerializer xml = new XmlSerializer(valor.GetType());
        StringWriter retorno = new StringWriter();
        xml.Serialize(retorno, valor);
        return retorno.ToString();
    }

    public static object DeserializaParaObjeto(string valor, Type tipo)
    {
        XmlSerializer xml = new XmlSerializer(tipo);
        var valorSerealizado = new StringReader(valor);
        return xml.Deserialize(valorSerealizado);
    }
}

Chamada dos métodos de conversão:
class Program
{
    static void Main(string[] args)
    {
        var stringParaSerializar = "Frase Qualquer";

        var valor = Serializa.SerializaParaString(stringParaSerializar);

        Console.WriteLine(valor);

        Console.ReadKey();
    }
}

Resultado:
<?xml version="1.0" encoding="utf-16"?>
<string>Frase Qualquer</string>

Mais informações sobre serializar e deserializar objetos XML para string: C# -  Serializando Objetos para String e vice-versa

Converter string em XML


Why user_save overrides user picture?

Question: I have a user profile form. If a user selects a picture, it's uploaded and shows on user profile but If user just updates other details and leaves the picture the same the user_save overrides the user picture and then there is no user picture.
My code is like this.
<code>if(!empty($_FILES['files']['name']['profile_image']) && isset($_FILES['files']['name']['profile_image']) && ($_FILES['files']['size']['profile_image'] != 0)) {

        $filepath = 'public://pictures/';
        $file = file_save_upload('profile_image', $validators, $filepath);
        $file->status = 1;
        file_save($file);
        if(isset($file) && !empty($file) && !is_null($file)) {
            $loaded_user->picture = $file;
        }

    }
user_save
</code>
Comment: Can you post your whole form code, not just this part? Without seeing the rest of the code I would assume you are not setting the previously saved value as the default value for the picture field.
Comment: Thank you rooby for your comment. This is the section where I add the file.                                                                        $form['profile']['profile-share']['upload-photo']['upload-pic']['upload'] = array(
     '#name' => 'files[profile_image]',
        '#type' => 'file',
        '#title' => 'profilbild',
        '#title_display' => 'invisible',
        '#size' => 30,
        '#attributes' => array(
            'id'=> 'upload',
        ),

    );
Comment: You're right, I'm not setting the previously set value as a default value. Where can I set it because the #default_value property is not used by file?
Comment: Can you post the whole code for your form in your original post by editing it, then it will be easier to give a correct answer. - You can change field names etc. if they are sensitive information.
Comment: The whole form is too big to be posted here but If you could tell me how to set a default value for the file then may be I'll fix it.
Comment: Even just the part where you define the file field in question would help, but I will make some assumptions.
Answer: I assume you are not setting you default_value for the file field and that you are using a managed_file field.
The default value should be the fid of the file that has been uploaded before.
Something like this:
<code>$form['profile_image'] = array(
  '#title' => t('Profile picture'),
  '#type' => 'managed_file',
  '#description' => t('Upload a photo for your profile.'),
  '#default_value' => $previously_uploaded_file->fid,
);
</code>
In your case I'm not exactly sure where the $previously_uploaded_file->fid will come from, but I assume it will be in your form or form state or else you will have to get it from the database or something.
If you are using a regular file field instead of a managed_file file field I don't believe you can set a default value.
In that case you have to make sure that when you do the user save that you are not overwriting the file with an empty value.
Comment: Thank again rooby, it's type is file. I can get the fid from DB.
Comment: In that case I don't believe that you can use default value. I have added some more info to the answer.
Comment: +1 for your time. I had already checked the default value for type file. I couldn't solve it, will ask some senior developer in my company to help me. Thank you again.
Comment: Your use case may be different but I would have thought a user picture would be better as a managed_file?

Why user_save overrides user picture?


In Drupal 7 how could I change style.css conditionally

Question: Where in drupal themes files I could apply the following blueprint code:
if ($language->language == 'ar'){
// Do something to change the included style.css to be style_rtl.css
}

Does it template.php or html.tpl.php? and How to implement the comment in the code above?
I use Drupal 7
Answer: You want to put it in template.php and probably want something like this:
function hook_css_alter(&$css) {
  global $language, $theme_path;
  if ($language->language == 'ar'){
    unset($css[$theme_path . '/css/style.css']);
    drupal_add_css($theme_path . '/css/style_rtl.css', array('group' => CSS_THEME, 'every_page' => TRUE));
  }
}

I think there is something in the Domain Access project regarding theme settings, if you are using that suite of modules.
Comment: Because you create a hook implementation in Drupal by replacing `hook` with your module or theme name. I've edited the answer to reflect this.
Comment: Your solution as it is, does not work. However, I had to replace the `hook` with the theme name to make it run. i.e `my_theme_css_alter()` Could you please tell me why does not it work with hook?
Answer: Another way to do this would be using prefixing your CSS classes/id's with .i18n-en and .i18n-es (for English and Spanish respectively). Here's an example:
.i18n-en .myclass {
    color: #ff0000;
}

.i18n-es .myclass {
    color: #336699;
}

You'll see this in the  tag.
You can also make use of hook_css_alter. Check this page for the official documentation and some examples.
Comment: Your solution is good but in the end will lead to very big CSS file that affect website performance (downloading time)


Are P-bass pickups noise cancelling?

Question: I'm getting conflicting information as to whether the two halves of a P-bass pickup are configured so that they are noise cancelling, so
Are the pickups in  standard P-basses (say a Fender American Standard if we need a specific model) designed to reduce/eliminate external noise?
Answer: Yes. The "split coil" pickup (actually two separate pickups placed close together under the strings) is a humbucking, noise-cancelling design. These have been standard on the Fender Precision Bass since the early 1960s.

Split-coil noise-canceling design
However, the original "vintage" Fender Precision Bass pickup is a single pickup with a single coil, and it is not noise-cancelling -- it is subject to 60-cycle hum electrical interference.

Original 1950s P-Bass single-coil pickup (not noise-cancelling)
The original single-coil design is less popular, but it is favored by some traditionalists, notably Sting. Occasionally Fender will re-issue basses with this "vintage"-design pickup.
Comment: However, keep in mind that originally styled single-coil pickups for guitars (and therefore, basses) are available in noise-cancelling and humbucking flavors.  For Fender, they're often referred to as noiseless.  These pickups will vary slightly from their traditional counterparts, but share a similar, less noisy sound quality.
Answer: Will's answer is precise, however keep in mind that this transformation of the Precision Bass really has lead to a few types of pickups common for P-Bass installation.
Different off-the-shelf P-Bass models could use traditional, 60-year old single coils, a split single coil that may or may not be hum-cancelling through reverse-would reverse-polarity wiring, straight beefy humbuckers (sometimes using two Jazz Bass pickups stacked together, also reverse-wound from each other) or even a jazz bass pickup that may be noiseless or not.

Are P-bass pickups noise cancelling?


File uploads: Warning: session_start(): Cannot send session cookie - headers already sent

Question: When I check watchdog, I have lots of PHP warnings like this:

Warning: session_start(): Cannot send session cookie - headers already
  sent by (output started at
  /srv/bindings/9c42927e5316467d82a6fb1be50ed34e/code/includes/file.inc:1972)
  in drupal_session_start() (line 287 of
  /srv/bindings/9c42927e5316467d82a6fb1be50ed34e/code/includes/session.inc).

There are a lot of reports of errors like this, apparently most of which are caused by having spaces at the beginning or ends of PHP files.  But in this case, I think the problem is related to file uploads for the following reason.  The Location of these warnings are paths like this:

https://example.com/sites/default/files/styles/profile_pic/public/pics/41207/image.jpg?itok=cdQrU8Rv

The Referrer is my "manage pictures" page, which allows users to add a Picture content type which includes an Image field.
So, it looks like session_start() is having trouble during uploads.  Is there a standard fix fox this kind of problem?
Comment: Those are image style paths, not related to uploads as such. What's happening is that when an image style is requested, a header is being sent before the request has completed, when Drupal sends the headers it's supposed to. It's often caused by a warning/error being written out to the buffer, so try making sure you have all error reporting disabled. The real error should be I your server logs if you're logging then
Comment: Those look like Pantheon paths?  Are the derivatives being made properly?  We have run into memory limits there w/ some large images.
Comment: Stabdard fix? Well I'd start with scanning all files that end with PHP close tag `?>`.
Comment: @MPD Yes, this is on Pantheon.  Based on your suggestion, I tried uploading larger images than I usually do, and I was immediately able to reproduce the error.  It appears this error appears right after the image is uploaded, on the image page-- the image derivative hasn't been created yet, and then eventually it gets generated, and somehow in that process this error results.
Answer: I'm also getting the exact same issue on a Pantheon hosted site. This is on a more complex content type (number of fields) with the image field using the multiupload_imagefield_widget module so we can upload multiple images. The error can also appear on removing an image, where the image field is updated via AJAX. Occasionally, a WSOD will occur.
Location or Path always relates to files/styles/....
Tried to duplicate this on a basic content type but it was not occurring. The issue appears on the main content type 80% of the time.


Como mostrar todo o conteúdo de uma variável utilizando var_dump?

Question: Estou debugando um objeto (vamos assim dizer), mas, quando utilizo var_dump, não aparece todo o conteúdo desse objeto.
var_dump($obj[0]->link);

Resultado:
string '...atebypass%3Dyes%26dur%3D236.263%26lmt%3D1575166829736796%26c%3DWEB%22'... (length=751)

Existe alguma coisa que eu possa fazer para conseguir visualizar o resto dessa string?
Comment: Tenta [`var_export()`](https://www.php.net/manual/pt_BR/function.var-export.php) ou [`print_r()`](https://www.php.net/manual/pt_BR/function.print-r.php), veja alguma dessas funções são adequadas para o que precisa.
Comment: @AugustoVasques A resposta abaixo me ajudou
Answer:
Existe alguma coisa que eu possa fazer para conseguir visualizar o resto dessa string?

Sim, existe.
Você pode configurar isso no seu php.ini adicionando/alterando essa linha:
xdebug.var_display_max_depth=-1
Ou adicione isto ao topo do seu código PHP:
<?php

ini_set("xdebug.var_display_max_children", -1);
ini_set("xdebug.var_display_max_data", -1);
ini_set("xdebug.var_display_max_depth", -1);

Aqui está uma resposta no Stack Overflow em inglês.
Comment: Ótimo, a segunda opção funcionou.
Comment: Se funcionou, marque a resposta.
Comment: @ShutUpMagda, está pedindo para esperar 5 minutos.


What do you call a note that stays throughout the whole song?

Question: I am searching for songs that have a constant note throughout the whole song. For example "The Beatles - Tomorrow Never Knows" has has a C in the background through the whole track.
My plan is to put together a playlist of popular songs with at least one song for each note to train your perfect pitch.
But it would also be beneficial, if the standing-note is only found in every background chord, for example on a guitar, you often find those when one finger is kept in one position through the whole song.
Comment: It's called a *pedal* or a *drone*, however the terms are also used to mean other things so are not likely to be easily searchable.
Comment: It's a given in Indian classical music. See [tanpura](https://music.stackexchange.com/a/80347/13649).
Comment: For some examples, see https://en.wikipedia.org/wiki/Drone_(music)#Use_in_musical_compositions
Comment: In byzantine chant specifically it is called an [Ison](https://en.wikipedia.org/wiki/Ison_(music)) (literally, that which stays the same), and the person who sings it (and by extension the vocal part in a byzantine score) the "Isokrates" (literally, "he who holds the Ison")
Comment: You might check out [this list of songs](https://music.stackexchange.com/questions/203/what-are-some-useful-and-effective-exercises-for-training-absolute-pitch/235#235) from a previous question about developing perfect pitch.
Answer: This is called "Drone". There is a special minimalistic style for this:

Wikipedia: https://en.wikipedia.org/wiki/Drone_music
see also https://www.reddit.com/r/LetsTalkMusic/comments/5tpt81/what_are_your_favorite_pop_songs_that_incorporate/

A drone is defined as: "A harmonic or monophonic effect or accompaniment where a note or chord is continuously sounded throughout most or all of a piece."

also interesting: https://playguitar.com/chord-progression-drone-notes/
Comment: If you search for "drone music" you find a lot of music that fits for drone-flights but search for the german word "Bordunmusik" and you find something like this: https://www.youtube.com/watch?v=-uFdnWQhEHs&list=PL1C339F52ED0F4C08
Comment: Sure… if you search for another term in another language you might well get different results. As this is an English language site, we're really not expected to know what 'drone' may translate to in other languages, nor what those words may return in google searches.
Comment: As I noted in my comment above, that's not going to be easy to search. No-one, I mean no-one, is going to include that information in any song info. Also, a pedal is not quite the same as a drone. A drone in the traditional sense is like bagpipes; continuous & unrelenting, related only vaguely to the other harmonic content of a piece. A pedal, on the other hand, is a definite 'statement of intent' that a single note or phrase is repeated throughout a piece or significant sections of it. Again… no-one is ever going to include that in the piece's info section.
Comment: I note (ha!) that "drone music" is listed as originating in the 1960s. That would therefore be a very narrow definition, as the continual note has been around since essentially the invention of polyphony
Answer:
I search for songs, that have a note, that stays through the whole song?
My plan is to put together a playlist with popular songs with at least one song for each note to train your perfect pitch.

In Western music there are many examples with a note that is kept for a long time but usually a change happens sooner or later. On a piano or giutar it is a repeated note since you can not sustain a note on those instruments. It is usually referred to as a pedal ponit.
You want popular songs, so I am not sure what you think of the following pieces. At least for some people they are popular.
Chopin's Rain Drop Prelude for piano. It has a constant repeated A♭, sometimes notated as G♯. There are a few bars where the repeated note changes to another one, but only for a short while, after which the music goes back to the repeated A♭/G♯. Here is an image from the piece:
Stravinsky's Augurs of Spring (from the The Rite of Spring) has one chord that is repeated during the entire movement. Here it is on YouTube: Augurs of Spring
Comment: I looked up the Chopin piece on Spotify. There it had the term *Sostenuto* in the name, which sounds like a plausible version of the term in classical music.
Comment: @JAD Sostenuto refers to the overall feel of the music, which could mean a bit withheld or sustained in the melodic line here and there, somewhat rubato and the overall tempo fairly calm. You can listen to different YouTube videos and hear how different pelple play it. Here is an example: https://www.youtube.com/watch?v=dPQMPu3vLjg Lang Lang stops frequently and explains his way of interpreting the music.
Answer: "Immovable", as in The Immovable Do by Percy Grainger?
A comment on the video says:

Legend has it that this piece originated when Grainger was at home, practicing on a harmonium (a form of reed-organ), when a note (a high "C") began to cipher (malfunction where the note sounds continuously, even after the key is released). Being a composer, and a curious man, Grainger began to improvise around the note, turning the idea of a "pedal-point" in the bass upside-down, and this piece was the result. When originally published, Grainger included the sub-title: "The Ciphering C".
Comment: It's a believable story. Where did you get it? Nice to see Grainger mentioned. His Shallow Brown is hardly ever off my turntable. (Adobe have another name for this turntable but I can't remember it.) The idea of an inverted pedal-point wasn't new, btw.
Comment: @OldBrixtonian: As I said, it's one of the comments on the video itself. Actually, the way I first heard it, the stuck key happened during a live performance, and he improvised the whole thing, but the story above is a bit more believable.
Comment: Oh sorry! I thought that was a link simply to a piece of music and thought I'd listen to it later. Yes - more believable!
Answer: A drone perhaps?   But, apart from bagpipe music - where it's a feature of the instrument rather than of the song - you're not going to find many in Western music.   'Tomorrow Never Knows' borrows elements of Indian music including the sitar drone.  It's a bit of a one-off!
Comment: Drones are very common in some western music genres and styles! One example is electronic music, where entire genres are based on drones.
Comment: A huge amount of world music makes frequent use of drones in songs.  (Probably most commonly known is Indian music, but a lot of South Asian, African, aboriginal Australian, etc. music uses them.)  I doubt that's what OP is looking for, but it's not just bagpipe music.
Comment: Drones are ubiquitous in five-string banjo, where the fifth string is seldom fretted but often sounded.
Comment: Drones are an intrinsic part of the hurdy-gurdy / vielle, so feature heavily in French and also Eastern European traditional musics.


Recurrence relation with summation of previous terms

Question: I am stuck while trying to solve a recurrence relation. I just need the characteristic function to know the dependence of $Y_n$.
My recurrence relation is of the following form where $a$ and $b$ are constant,
$Y_n = a + b \frac{\sum_{j=1}^{n-1}Y_j}{n-1}$
I am unable to figure out the characteristic equation or even the asymptotic nature of the series.
Comment: @Peter $x^n$ seems to work but the $n$ in the denominator doesn't add up. It seems to me that there is something missing.
Comment: I suppose, that $n$ is unknown, but fixed. So, we will get a polynomial with coefficients depending on the degree.
Comment: $n$ is known, the second term of the recurrence relation just means taking a mean over the previous terms.
Comment: For any concrete $n$, we have concrete coefficients and can determine the characteristic equation as usual.
Comment: $n$ is the sequence index. It is not fixed. This is not a simple linear recurrence, so it does not have a characteristic equation. Characteristic equations occur for recurrences of the form $y_n = f(y_{n-1}, ..., y_{n-k})$ for some fixed $f$. You do not have that here. Your recurrence involves all previous elements of the sequence, not a fixed number of them. The standard linear methods do not apply. I suggest looking that the sequence $X_n = \sum_{j=1}^{n} Y_j$ instead. Once you have it, finding $Y_n$ from it is easy.
Comment: @PaulSinclair I tried replacing $X_n=\sum_{j=1}^{n} Y_j$, but I am not able to eliminate the sequence index still, the equation becomes of the form,
$X_n = c + d X_{n-1}/n$ which is still unsolvable. Is there some way to show there does not exist any closed form expression ?
Comment: I get $X_n = a + \frac{n-1 +b}{n-1}X_{n-1}$. But you are right that this still doesn't count as a simple linear recurrence. Alas, I don't have a better suggestion yet.
Answer: Using the definition of $X_n$ in the comments by @Paul Sinclair, I ran out the first couple of cases, and then used the Online Encyclopedia of Integer Sequences to formulate the following conjecture:
$$X_n = \frac{1}{(n-1)!}\left[\displaystyle\sum_{i=0}^{n-2} \left(ab^i\sum_{j=i+2}^{n} s(n,j)\right)+X_1\prod_{i=1}^{n-1}(b+i)\right]$$
where $s(n,k)$ is the unsigned Stirling number of the first kind.
Using the recurrence relation $X_{n+1}=a+\frac{n+b}{n}X_n$ given by Paul Sinclair, it is an interesting exercise to prove the formula using induction.


How to extract Euler angles from a a point in a plane?

Question: Given a certain coordinate frame, I can compute a new one by applying a set of rotations in a given order (what I call Euler $Z-Y-X$). So I yaw, then pitch then roll.
Now imagine that I want to do exactly the opposite: given two coordinate frames (same origin to simplify), how do I find out roll, pitch and yaw angles that were used to transform from one to the other?
Comment: Writing the new unit vectors in terms of the old gives you the rotation matrix. The conversion between the rotation matrix and Euler angles is covered here: http://en.wikipedia.org/wiki/Rotation_representation_%28mathematics%29#Conversion_formulae_between_representations
Comment: How do you write the new unit vectors in terms of the old ones? Is it just arcsines? Does order matter?
BTW: Why you didn't reply as an answer? It does sound like one to me.
Comment: I took your "given two coordinate frames" to mean that you could write down new coordinates in terms of old ones. What did you mean? Knowing how only one point is transformed is not enough to recover the rotation.
Comment: Oh, ok. Yes, I only know the new system in terms of the old one. Thanks!
Comment: Cmon, go to wikipedia and lookup rotation matrices. There is a link to extract euler angles from a 3x3 rot. matrix. What is your rot. matrix? $E = {\hat{i},\hat{j},\hat{k}}$ where i,j,k are the unit vectors of one coordinate system expressed on the other system.
Answer: The details will vary according to what you mean exactly by yaw, pitch, roll. But here is a general way of transforming the axes. It may not be the best theoretical way to do it, but it works fine computationally.
Let rotations about the $X$-axis by an angle $\theta$ be denoted by $R_{X,\theta}$, and similarly for the other axes. A frame is then obtained by $$T_{\theta,\phi,\psi}:=R_{X,\phi}R_{Y,\theta}R_{Z,\psi}$$
If I understand your question correctly, you want the three angles that would give $T_1T_2^{-1}$ given two frames $T_1$, $T_2$.

Calculate the matrix $S:=T_1T_2^{-1}$
Calculate $\phi=\arctan_2(S_{3,3},-S_{2,3})$, $\theta=\arctan_2(\sqrt{S_{1,1}^2+S_{1,2}^2},S_{1,3})$, $\psi=\arctan_2(S_{1,1},-S_{1,2})$.

Then $\theta$, $\phi$, and $\psi$ are the required angles. Here $\arctan_2(x,y)$ is the modified arctan function that gives the angle in the correct quadrant.
Note that there may be different values of $\phi$, $\theta$, $\psi$ that give the same transformation $S$.


What happens if two players of opposite teams hold the ball over the net?

Question: Let's say that the ball is right over the net, and one player of each team is trying to push it to the other side. What is the rule if they just happen to hold the ball between each others hands for a really long time?
Answer: What you describe is called a "joust" (in American terminology), and it is legal.  From Team USA's "Guide to Volleyball Basics":

Joust - when two players on opposing sides attempt to block the ball at the same time pushing it onto each other's side of the net.

Apparently jousting used to be illegal, but this page says it was made legal in 1999:

14.2.4 is a new Rule concerning the Joust, which is a ball held between opponents over the net. This will no longer be considered a double fault (caught ball). The new Rule is the same as played in Beach Volleyball. This eliminates a referee's decision in this play. Play will continue, and the side on which the ball falls after the contact over the net will have three additional contacts. As with any other ball simultaneously contacted by both sides over the net and if it goes out after the contact, it will be considered the fault of the team on the opposite side. If during the Joust a net fault occurs that infraction will be whistled and play stopped. If there is a simultaneous net fault, then a replay will be indicated.

The term "joust" may not be used internationally, but the FIVB rules still say that extended contact with the ball over the net by two opponents is legal:

126.96.36.199 When two opponents touch the ball simultaneously over the net and
  the ball remains in play, the team receiving the ball is entitled to another
  three hits. If such a ball goes "out", it is the fault of the team on the
  opposite side.
220.127.116.11 If simultaneous hits by two opponents over the net lead to an extended contact with the ball, play continues.
Comment: I tried finding rule 14.2.4 in the FIVB rules from Philip Kendall's answer, but it doesn't exist (anymore?). The word "Joust" also doesn't exist in those rules. Is it possible to unify this answer with the current FIVB rulebook?
Comment: It looks to me that 220.127.116.11/184.108.40.206 have almost exactly the same text as the 14.2.4 quoted above - it probably was moved to a more logical section of the rulebook at some point.


Tips and tricks for proofs involving algebraic / equation manipulation

Question: I recently completed a solid chunk of my first truly formal math book on Set Theory and decided to move on to Michael Spivak's Calculus (as I heard it was a good place to begin one's journey into Analysis). For the purpose of self-studying, I purchased the solution manual, as well.
After completing the first two chapters and going through all practice problems, I am now painfully aware that I am not particularly great at proofs involving clever equation manipulations. As I progressed through my aforementioned set theory book, I felt like the number of "proof flavors" (different strategies one could invoke to tackle the claim) were quite manageable. Figuring out which path to pursue  seemed to be categorically recognizable.
However, when it comes to proofs involving equation manipulation, I literally feel like I am staring into a sea of hundreds of possible permutations (in the English sense) that one might use to arrive at the desired conclusion. From what I have seen so far, the strategies largely seem to involve the invocation of Field Axioms (e.g. creative usages of $0$ and $1$ through the existence of additive inverses and  multiplicative inverses, respectively) and factoring (that often times feels quite contrived).
I was wondering if there were any general tips and tricks as to how one might improve his/her ability in recognizing the type of equation manipulation that a given proof is suggesting (yelling) to carry out. I am assuming the seasoned mathsters have some sort of pattern recognition that goes off in their heads that allows for efficient determination of starting points.
I apologize if this question is a little too broad. I recognize that every proof may necessarily be "special", so in the absence of a specific example, perhaps this question is unanswerable. But here's hoping. Book recommendations are also greatly appreciated! Cheers~
Comment: The way one finds "clever" proofs is to immerse yourself deeply into the problem and *live* in it for so long that you have explored all the ins and outs and eventually stumble into the clever solution. Then you write it up nicely and pass it around and everyone is amazed how you so easily found this neat proof. They don't see all the blood, sweat and tears, and mostly time, you put into it. You've only begun to put that effort in. Don't get discouraged because you cannot yet match those who have invested far more effort.
Comment: You have to crawl before you can walk.  The reason that you are having trouble is probably nothing more than lack of experience.  Instead of jumping into Spivak, find an intermediate book with **lots** of problems, and get good at that intermediate book.  Then move on to Spivak.
Comment: Typical proofs in analysis do not involve much algebraic manipulation. Instead they deal with basic inequalities (ok mostly triangle inequality).
Comment: In general algebraic manipulation is mostly a thing of practice. If you have seen/done many examples you will be able to do more.
Comment: Can you provide some specific examples from Spivak where you think algebraic manipulation part of some proof is tricky?
Comment: @ParamanandSingh certainly. The one that actually prompted me to write this was the following: prove that $\sqrt(6) - \sqrt(2) - \sqrt(3)$ is irrational, but there are certainly several others.
Comment: Thanks for feedback. That's not exactly the analysis/calculus part (limits, continuity, derivative, integral). It's more related to basic number theory and Spivak perhaps uses those exercises to give a feel of variety of real numbers.
Comment: Also a large part of high school math education (say for students till 15 years of age) is designed to teach mostly algebraic manipulation. Later on these tricks are combined with new functions (exponential, logarithm, etc).
Comment: I'll just say it: I hate all of Spivak's books. It's a weird mix of touchy-feely and very formal. Some love it, some hate it, I hate it. I never learned anything from them. I took many classes taught from them. Find other books. Stewart's Calculus is very commercial but not bad! At a higher level, Walter Rudin isn't trying to be your friend, but try to be his friend instead of letting Mike Spivak live rent-free in your mind.
Answer: I'm about halfway through Spivak's Calculus myself.
The specific problem you mention (Prove $\sqrt 6-\sqrt 2 - \sqrt3$ is irrational) is a tricky one. I certainly wasn't able to do it myself. I ended up having to look at the published solution. Coming back to it today, several months later though, I managed it.
(Note: the next part of that problem ("prove that $\sqrt2$ + $\sqrt[3]{2}$ is irrational") is marred by a hint ("start by working out the first 6 powers of this number") that's meant to push you towards the published solution, which relies on linear algebra and is certainly outside the scope the book. Usually Spivak is loath to rely on things without justification. This is an unusual lapse, made more baffling by the existence of a much more appropriate solution.  Compounding things, I think there's also a typo in the table in his solution. There are mistakes in the text, ranging from typos to more serious problems. When you think there might be a mistake, MSE can be very helpful.)
More generally, many of the problems in the book are challenging. Often, I have to look up the solution, at least for a hint.
The difficulty is also somewhat front-loaded. The first 4 Chapters which in 3rd edition are "Basic Properties of Numbers", "Numbers of Various Sorts", "Functions", and "Graphs" (with 3 appendices), were in some ways more challenging for me than anything that's come since.
Once you hit the first chapter on "Limits", things settle into a groove.
Not that it's "easy" from that point on; the problems remain challenging throughout. Just that, I think you'll find from limits on, it gets really fun.
Don't be discouraged if you aren't able to "ace" the problems. Many of the early problems are introducing you to concepts and techniques you will use later on. The full import of some things doesn't become clear until many chapters later.
You can learn most of Spivak's clever tricks in Spivak, as opposed to trying to learn them elsewhere ahead of time just in case they are in Spivak.
Certainly look outside of Spivak if you need to brush up on something specific, but I don't know if it's worth it trying to just generally get better at clever arithematic tricks before moving on with the text.
Remain diligent about doing the problems. If you make sure you understand them, even the ones you need help with, you will get a lot out of it.
Go back periodically and try re-working problems that initially gave you a hard time.
The book is a tough, glorious, frustrating, edifying beast. Stick with it at least until the end of the "Limits" chapter. I think at that point you'll be happy you did.


How do I dynamically change an SVG output in a loop in Jupyter Notebook?

Question: I am trying to make a chess simulation of two random bot players in Jupyter notebooks. To display an SVG image of the chess board, I can perform the following line:
chess.svg.board(board = board, size = 300)
This works if I display it in a standalone cell. However, if I try to display this board inside of a loop (so the players can have a display after each time they move), nothing happens. Could someone help me with this? Example below.
Answer: What luck! I was trying to visualize the board's dynamic state as well!
from IPython.display import display, Image

## Setup board here
display(board)


Serializar lista de objetos para JSON: A circular reference was detected while serializing an object of type

Question: Estou tentando Serializar uma lista de objetos para Json e tenho recebi o seguinte erro:
An exception of type

'System.InvalidOperationException' occurred in
  Microsoft.Web.Extensions.dll but was not handled in user code
  Additional information: A circular reference was detected while
  serializing an object of type
  'System.Data.Entity.DynamicProxies.Pais_FE2360F9C3DD9892003FC5DC33EF9BD07698CFF62033EE442867F74C88F09AC7'.

Tenho usado:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public void GetListaPais(string prefixText, string contextKey)
{
    var serializer = new JavaScriptSerializer();
    var json = serializer.Serialize(AuxiliarControler.ListaPais(prefixText,contextKey));
    Context.Response.Clear();
    Context.Response.ContentType = "application/json";
    Context.Response.Flush();
    Context.Response.Write(json);
}

Método que obtêm a lista de Pais:
public static List<Pais> ListaPais(string nomePais, int IDIdioma)
{
    using (entidadesIUS entidades = new entidadesIUS())
    {
        return entidades.Pais.Where(p => p.IDIdioma == IDIdioma &&
            p.Pais1.Contains(nomePais)).ToList();
    }
}

Entidade Pais
public partial class Pais
{
    public Pais()
    {
        this.CAL = new HashSet<CAL>();
        this.Clientes = new HashSet<Clientes>();
    }

    public int IDPais { get; set; }
    public string Pais1 { get; set; }
    public int IDIdioma { get; set; }

    public virtual ICollection<CAL> CAL {get; set; }
    public virtual Idiomas Idiomas {get; set; }
    public virtual ICollection<Clientes> Clientes {get; set; }
}

Comment: "Dá pau" é o comentário mais subjetivo possível. Qual o erro? O que você já tentou fazer para sana-lo?
Comment: Qual é a IDE que você está usando?
Answer: Isto acontece porque possivelmente você tem uma entidade A que referencia uma entidade B e que em algum lugar volta a referenciar A.
Para resolver, anote o seguinte nas entidades dependentes:
[JsonIgnore]
public virtual Idioma Idioma { get; set; }

Ou, numa abordagem global, dá um pouco mais de trabalho. Esta abordagem vale para o pacote JSON.NET.
1. Implemente um JsonResult que use a configuração desejada
O meu ficou assim:
public class CustomJsonResult : JsonResult
{
    private static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
    {
        Formatting = Newtonsoft.Json.Formatting.Indented,
        ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
    };

    public override void ExecuteResult(ControllerContext context)
    {
        if (this.JsonRequestBehavior == JsonRequestBehavior.DenyGet &&
            string.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
        {
            throw new InvalidOperationException("GET request not allowed");
        }

        var response = context.HttpContext.Response;

        response.ContentType = !string.IsNullOrEmpty(this.ContentType) ? this.ContentType : "application/json";

        if (this.ContentEncoding != null)
        {
            response.ContentEncoding = this.ContentEncoding;
        }

        if (this.Data == null)
        {
            return;
        }

        response.Write(JsonConvert.SerializeObject(this.Data, Settings));
    }
}

2. Derive a classe básica Controller e implemente um override para o método Json
public abstract class Controller : System.Web.Mvc.Controller
{
    protected override JsonResult Json(object data, string contentType, System.Text.Encoding contentEncoding, JsonRequestBehavior behavior)
    {
        return new CustomJsonResult
        {
            Data = data,
            ContentType = contentType,
            ContentEncoding = contentEncoding,
            JsonRequestBehavior = behavior
        };
    }
}

3. Teste
Fiz um teste para pegar 10 cidades no meu sistema que ficou assim:
public async Task<JsonResult> SelecionarDez()
{
    var cidades = await db.Cidades.Take(10).ToListAsync();
    return Json(cidades, JsonRequestBehavior.AllowGet);
}

Comment: Bela ampliação da resposta, muito bom.
Comment: @MaurícioJúnior Essa resposta do Cigano é sensacional. Bom que ela pode te ajudar :)
Comment: Ok!, Depois que eu salvei as  `classes` dentro da pasta `Controller` e funcionou, perfeito!
Comment: Verdade @Marconi ! Implementei em um projeto e rodou perfeitamente!
Comment: Estou com dificuldades para implementar esta solução, imagino que no `Controller` devo substituir: `public class ColaboradorController : Controller`  por `public class ColaboradorController : CustomJsonResult` , é isso ?
Comment: Não. `CustomJsonResult` é uma classe. `Controller` derivado de `System.Web.Controller` é outra.
Comment: Entendi, mas como eu implemento o uso dessa classe em meu `Controller`? O `Controller` contém alguns `ActionResult` e `JsonResult`, exemplo:  `public JsonResult MontarGridColaborador()` que retornar dados do BD (retorno com referência circular) e quero implementar essa solução para exibir os dados na `View`.
Comment: Não, a classe é em separado do `Controller`. O `Controller` que implementa `public JsonResult MontarGridColaborador()` herdará de `Controller` e o problema de referência circular acaba porque este `Controller` ancestral reimplementa `JsonResult`.
Comment: No meu caso fica dando a seguinte Mensagem: 'Controller' is an ambiguos reference between 'ERP4.Helpers.Controller' and 'System.Web.Mvc.Controller' como faço para Declarar essa controller nova sem dar conflito com a padrão do Mvc?
Comment: @EdenilsonBila `public abstract class Controller: System.Web.Mvc.Controller { ... }`
Answer: Recomendo a utilização desta biblioteca. Ela é altamente difundida na comunidade .net.
No meu caso eu utilizo o recurso abaixo para evitar referências cíclicas e ignorar valores nulos no json no momento da serialização.
 GlobalConfiguration.Configuration.Formatters.JsonFormatter
    .SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;

 GlobalConfiguration.Configuration.Formatters.JsonFormatter
    .SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;

Está configuração é feita no arquivo Global.asax de uma aplicação WebApi. Você teria que ver no seu caso onde colocá-la.
Comment: Ele já está usando a JSON.NET. Possivelmente na época que tive que resolver isso essa configuração nem existia. +1.


The simplest service worker for a Web App Manifest

Question: I must confess that I have no idea what a service worker is (TL;DR), but after reading around in the internet and SO, it seems that to have a Web App Manifest properly working, you need one.
Do I really need this extra script (service worker) to have the homescreen option on Android with Web App Manifest?
This is my /manifest.webmanifest:
{
  "short_name": "autocustos",
  "name": "Calculadora dos Custos do Automóvel",
  "icons": [
    {
      "src": "/favicon32x32.png",
      "type": "image/png",
      "sizes": "32x32"
    },
    {
      "src": "/favicon72x72.png",
      "type": "image/png",
      "sizes": "72x72"
    },
    {
      "src": "/favicon114x114.png",
      "type": "image/png",
      "sizes": "114x114"
    },
    {
      "src": "/favicon144x144.png",
      "type": "image/png",
      "sizes": "144x144"
    },
    {
      "src": "/favicon192x192.png",
      "type": "image/png",
      "sizes": "192x192"
    }
  ],
  "start_url": "/PT",
  "scope": "/",
  "background_color": "#F4F6FE",
  "display": "fullscreen",
  "theme_color": "#F4F6FE"
}

I have this in the head section
<link rel="manifest" href="/manifest.webmanifest" crossorigin="use-credentials">

And to serve my /manifest.webmanifest I set the content header to application/manifest+json
But Google Dev Tools on Application -> Manifest, tells me:
Comment: Here is a simple example I wrote before, hope it will be helpful to you, https://github.com/januwA/web-app-manifest
Comment: 1. Have a web application manifest file manifest.json
2. Have a service worker registered on your website
3. Provided over HTTPS (this is a requirement to use service workers)
4. Be visited at least twice, with at least five minutes between visits
Comment: @januwa great `:)` Therefore you just need [this](https://github.com/januwA/web-app-manifest/blob/master/sw.js) as service worker? Really? Please add your example as an answer such that I can make it the solution.
Comment: @januwa oh, I see, you also have some extra scripts on `index.html`. Could you kindly just tell me what is really essential?
Comment: @januwa I did 1. and it's working. I have 3. working properly. 4. it's easy. I don't know how to implement 2. That was my OP
Comment: @januwa do you need [this script](https://github.com/januwA/web-app-manifest/blob/master/index.html#L43-L53) on your repo?
Comment: Yes, I found the URL I studied previously https://web.dev/customize-install/
Answer: Following the instruction on the comments I did the following:
Add a very simple /serviceWorker.js file at the url root, like this:
self.addEventListener("fetch", function(event) {
  console.log(`start server worker`)
});

Load the following piece of code either by embedding it on html head tag or loading it within a JS file after the event onload is triggered
if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('./serviceWorker.js')
    .then(function(registration) {
      // Registration was successful
      console.log('ServiceWorker registration successful with scope: ', registration.scope);
    }).catch(function(err) {
      // registration failed :(
      console.log('ServiceWorker registration failed: ', err);
    });
}

Then the manifest.json as stated in the original post will work as expected
Based on this example: https://github.com/januwA/web-app-manifest
Answer: To get clarity about how all this fits together, head to https://developer.mozilla.org/en-US/docs/Web/Progressive_web_apps
Comment: I read it and on the [requirements](https://developer.mozilla.org/en-US/docs/Web/Progressive_web_apps/Installable_PWAs) it says I need a service worker. How do I get one?
Comment: Service worker is javaScript code to cache the assets of a website. You need to create a service worker file and then register it in your main file. The code is explained in the 'Making PWAs work offline with Service workers' section.


Swift 3 - Como instanciar uma View Controller?

Question: Preciso trabalhar com um método com atributos que estão em outra ViewController mas não consigo o fazer.
O que estou tentando:
let notasViewController: NotasViewController()

E também:
let notasViewController: NotasViewController = UIStoryboard.init(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "NotasViewController") as! NotasViewController

Sempre retorna EXC_BAD_ACESS ou um erro dizendo que meu Storyboard não contém esse View Controller
Alguma ajuda? Grato!
Answer: Serão basicamente 2 etapas a serem feitas no Storyboard:

No seu Main.storyboard, selecione o ViewController desejado e modifique a classe do mesmo para NotasViewController.
Modifique o campo Storyboard ID, com o nome do identificador que você utilizará no código, no caso do seu código, você está utilizando: "NotasViewController"

As configurações ficariam dessa forma:

A caixinha "Use Storyboard ID" não é obrigatória de estar marcada, ela serve caso você queira deixar o "Restoration ID" com o mesmo ID do identificador na Storyboard.
Feito isso, vá até a classe do View Controller que você deseja ter uma instância da classe NotasViewController e utilize o mesmo código que você utilizou:
let notasViewController: NotasViewController = UIStoryboard.init(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "NotasViewController") as! NotasViewController

Sendo assim você terá acesso aos métodos da classe NotasViewController através da constante notasViewController.
Answer: Pode fazer dessa forma para criar uma nova instância do ViewController:
let notasViewController = NotasViewController()


How do I get Loopback to prefer short ids when doing id injection?

Question: I have a loopback app which gives ids like "56dbfa7089223aca7946ca14" when creating models. I would prefer ids like "0" or "73". Is there a way to adjust id-injection practices to have ids start at 0 and increment as base-10 integers?
The data store is MongoDB v2.6.10)
running loopback v2.22 on node v5.7.1 on Ubuntu 15.10
Here's the relevant model.json
<code>{
  "name": "Term",
  "base": "PersistedModel",
  "idInjection": true,
  "options": {
    "validateUpsert": true
  },
  "properties": {
    "name": {
      "type": "string",
      "required": true
    },
    "beginDate": {
      "type": "date",
      "required": true
    },
    "endDate": {
      "type": "date",
      "required": true
    }
  },
  "validations": [],
  "relations": {
    "lessons": {
      "type": "hasMany",
      "model": "Lesson",
      "foreignKey": ""
    },
    "classes": {
      "type": "hasMany",
      "model": "Class",
      "foreignKey": ""
    },
    "weeklySchedules": {
      "type": "hasMany",
      "model": "WeeklySchedule",
      "foreignKey": ""
    }
  },
  "acls": [],
  "methods": {}
}
</code>
Comment: I think you are using MongoDB as your data store.
The generated ID is default ObjectID of MongoDB, you can't avoid that unless setting your own ID and removing idInjection in your model configuration.
Comment: Why not post this as answer?
Comment: Not 100% sure about this
Comment: Please show the model .json file.
Answer: there are several ways to do it, you can read about them in official documentation
It is stated by mongo developers, that is completely ok, to use your own id, if you really need it, so go for it.
However if you do it only because you "dont want ObjectId, because it does not look good", I suggest you, to get used to it.
Comment: I don't care how it looks. There isn't a strong reason why these long ids should be considered a problem.  I prefer them for the purposes easily testing by hand as I go through the initial set up. As such, the most useful solution is to get used to it. Thanks.


Exp. Stability of perturbed system with temporally vanishing perturbation

Question: I have a perturbation problem for which I can't find a fitting theorem in Khalil's Nonlinear Systems. Maybe someone can point me in the right direction:
Given a nominal system
$\dot x(t) = A(t)x(t)$
which is exponentially stable and a perturbed system
$\dot x(t) = A(t)x(t)+g(t)$
where $g(t)$ is bounded and as $t\rightarrow \infty$ converges exponentially to zero.
I imagine that the perturbed system is exponentially stable as well.
Any pointers appreciated.
Comment: I have exactly the same problem. Have you found any solutions?
Answer: Ok, it is not true.
Consider $\dot x = -x +e^{-3t}$.
The solution is $x=c_1e^{-t}-0.5e^{-3t}$ with $c_1=x_0+0.5$.
So $\|x\|$ has a part that is independent from $x_0$, which means that for arbitrarily small $\|x_0\|$, the exponential stability condition breaks.
Comment: why does it break? Exp. stability basically says that you can fit an exponent from above and below such that your solution never exits created tunnel. I can think of such an exponential for any $|x_0|$.


Storing SQL queries in Table in sql server

Question: We have multiple jobs in our system.  These jobs are listed in a grid.  We have 3 different user types (usertypeid 1,2,3). For each user listing is different and he can filter listing by selecting view from a dropdown.  ViewName in the below table is the view which needs to be displayed.  To achieve this functionality, a fellow developer has created the following table structure and stored sql fragments in SQLExpression in the below table.  According to me the query should not be stored in database. What are the pros and cons of this approach and what are the available alternatives?
JobListingViewID         ViewName        SQLExpression            UserTypeID
 3                     All Jobs            1 = 1                       3
 4                     Error Jobs   JobStatusID IN ( 2 )               1
 5                     Error Jobs   JobStatusID IN ( 2 )               2
 6                     Error Jobs   JobStatusID IN ( 2 )               3
 7                     Speech       JobStatusID IN ( 1, 3, 8 )         1

Comment: Why aren't you using the built-in SQL Agent Jobs functionality? Why reinvent the wheel??
Comment: Not sure that its anything to do with SQL Agent? Might be a work scheduling system. (jobs for client)
Comment: We get dictation file from physicians and create a job out of it.
Answer: You just need to have a Matrix table of ViewName UserTypeID JobStatusID combinations and then join onto that in your query. You don't need dynamic SQL and an additional DB lookup.
NB: For the "All Jobs" View you should just have a different query that forgoes the JOIN. This will save a bit of unnecessary processing and mean when you add a new job you don't have to set up the permissions. For the rest use a matrix like the below.

ViewName        JobStatusID        UserTypeID
Error Jobs             2                1
Error Jobs             2                2
Error Jobs             2                3
Speech                 1                1
Speech                 3                1
Speech                 8                1
Answer: Disadvantages:
1. Pain to maintain.
2. No optimisation (caching etc).
3. Changing object names means you'll have to change the data in that table. It's ok for the few records, but once the table grows, you'll spend more time maintaining that table.
Comment: +1 Agree on points 1 and 3. It would cache the query plan for dynamic SQL as  well though. @Rohit to turn things around what does your coworker say the advantages of their approach are?
Comment: He says that its predefined data.So i have stored it this way. There are predefined status for a job in system.These wont change, so whynot store these IDs and use them as where clause.
Comment: Right so basically sounds like there is no good reason for doing it at all. In terms of why not. Performance, maintenance, adding unneeded complexity all spring to mind immediately. Additionally if you have them stored in the database in the traditional way then knocking up an admin screen to configure the permissions or using them in any other queries is much simpler.
Answer: I guess that fellow developer is right, and that approach, if it works for him (and for the rest of the system) is just as good as any.  Rework it later if it will make a problem - performance, maintenance, something...
Comment: Strongly disagree. There is a standard way of doing this in SQL if you depart from it then I would suggest that the onus is on you to have a good reason why.


How do you add type-property schemas from Schema.org into 8 sites?

Question: Some SEOers have reported good experience with enriching their websites with the formal schema vocabulary Schema.org.
Is there any way to implement such schemas on Drupal 8 webpages?
Update - July 9 2016:
Is it true to say to most of the functionality of this module got into the Drupal 8 core via the module Aggregator 8.x.x ? I read now in the modules' page (for Drupal 7 as linked in the answer) and that's what I understood; But if it did, then when why creating a new module is on the quine? It is written there the module has not yet been ported and that's why I'm confused.
Answer: Yes, there's a Drupal 7 module of the same name, schema.org.

This project is a drop-in solution to enable the collections of
  schemas available at schema.org on your Drupal 7 site. The major
  search engines including Bing, Google and Yahoo! have agreed to
  recognized these in order to improve the display of search results.

Along with the core module, there's a UI that makes it pretty easy to setup; you specify the schema.org type on the content type settings page & then you specify the schema.org property names on the field settings page. It also has support for address field & fivestar fields.
In Drupal 8, the project has deferred to the RDFUI project, to provide the UI component, now that other parts of the module have been ported to core.

The default RDF mappings of Drupal core have been updated to include
  schema.org in Drupal 8. Also, a lot of the backend code of this module
  was ported into Drupal 8 core. The User Interface allowing to set the
  mappings lives in the RDF UI, which is based on Sachini's Google
  Summer of Code project.
Comment: Hi there Sahwn Conn. Is it true to say to most of the functionality of this module got into the Drupal 8 core via the module Aggregator 8.x.x ? I read now in the modules page (for Drupal 7 as linked above) and that's what I understood.
Comment: But if it did, then when why creating a new module is on the quine? It is written there the module has not yet been ported and that's why I'm confused.
Comment: Will reward for updated answer well.
Comment: It has been updated accordingly
Comment: Shawn, could you add just a small note in the end of the answer if there should be a dedicated module to Drupal 7 that will give more Schema.org options (I know that RDF isn't the only option) or someone should better work with the RDF way and there is no serious need for anyone to wait for a port of the D7 module?
Comment: I am just not sure if so much cover is the ultimate cover.
Comment: Like with many things Drupal, there's rarely a solution that covers all possible use cases. If there's any alternative that covers a different scenarios, I'll let someone cover that with a different answer. As for the port, it's already covered in the answer ("the projects has deferred"); there's not going to be one.
Comment: I admit I didn't quite knew the word "Deffered" in English... IIANW, I never used it before in English and don't find its interpretation with the Morfix dictionary. I thus assume it means "Changed".


How can I "spy" on an Apache web server's response to server-side code like PHP or JavaScript?

Question: I'm trying to debug a problem with a file upload strategy and don't know whether there's an issue with directory permissions / ownership or the scripts. ... I've tried both PHP and JavaScript and can't seem to get enough information to track down what's happening, despite tail -f on both the error and access logs for the domain.
NOTE:
I've tried to increase the LogLevel on the php module - I'm running 7 - but I can't seem to find the module name.
This is on Fedora 31 /32 and there's a file /etc/httpd/conf.d/php.conf that says it's looking for mod_php7, and a comment that there's no mod_php in the default configuration. However, I KNOW php is running. . . NEITHER mod_php nor mod_php7 are acceptable in LogLevel - perhaps it's not loaded until / when needed?!
So, I enabled debug LogLevel on the directory instead. Lots of data, no idea why it's not working. ...Trying to increase the LogLevel, but this seems to be headed the wrong way - too much noise! And I don't ever see the data passed.
Update on Logging
I increased the LogLevel only for the directory that kicks off the upload to trace5. I got a lot more data and still nothing on either file access or why the upload fails.
...Do browser side things like Web Consoles (Firefox is what I'm using) have anything to share here? I would think not, but I'm a novice at this!
Configuration Data
**# rpm -qa | grep php**
php-fpm-7.4.8-2.fc32.x86_64
php-json-7.4.8-2.fc32.x86_64
php-xml-7.4.8-2.fc32.x86_64
php-mbstring-7.4.8-2.fc32.x86_64
php-opcache-7.4.8-2.fc32.x86_64
php-pgsql-7.4.8-2.fc32.x86_64
php-ldap-7.4.8-2.fc32.x86_64
php-cli-7.4.8-2.fc32.x86_64
php-pdo-7.4.8-2.fc32.x86_64
php-mysqlnd-7.4.8-2.fc32.x86_64
php-sodium-7.4.8-2.fc32.x86_64
php-7.4.8-2.fc32.x86_64
php-common-7.4.8-2.fc32.x86_64
**# rpm -qa | grep apache**
apache-commons-collections-3.2.2-16.fc32.noarch
apache-commons-daemon-1.2.2-2.fc32.x86_64
apache-commons-pool-1.6-22.fc32.noarch
apache-commons-dbcp-1.4-29.fc32.noarch
python3-certbot-apache-1.6.0-1.fc32.noarch
**# rpm -qa | grep httpd**
httpd-tools-2.4.43-5.fc32.x86_64
httpd-manual-2.4.43-5.fc32.noarch
httpd-filesystem-2.4.43-5.fc32.noarch
fedora-logos-httpd-30.0.2-4.fc32.noarch
httpd-2.4.43-5.fc32.x86_64

Advice, please!
Comment: Start with installing a php script with nothing but "phpinfo();".  It'll show you (when you browse to that page) a lot of information concerning your configuration.
Comment: How did you install PHP?
Comment: @MichaelHampton I installed it the usual way on Fedora Server - by installing Fedora Server. It comes with. I know it's being called because of the browser's Web Console contents... What I can't see are when it tries to touch disk space.... I'm about to update the comment to include more about my trace efforts...
Comment: I just installed Fedora Server. It doesn't install either Apache or PHP. How did you manage to get them?
Comment: @MichaelHampton Hmmm... That confuses me! Well, I can tell you that I use all the standard Fedora tools like DNF and sometimes yum, and, more rarely these days, rpm. I know for sure I didn't explicitly install these this time, which, well, IDK what to say about that but I'll be glad to share the installed package list above! ... Right now, family member with issues, so it'll take another hour or so to do.
Comment: @MichaelHampton Sorry for the delay - a friend had a home invasion robbery and they tied him up, the police had to free him! Anyway, got the data up. ... As for how I got these packages, I've since remembered: THIS system, unlike several recent installs, wasn't from scratch but was an "upgrade" because the version wasn't so old. IE # dnf upgrade...
Answer: A few ideas.
Turn up the debug logging in apache.
Run strace against the process.
Comment: I've used strace many times but don't have a clue how I run it against an image apache starts during the server / web browser exchange..


Is a compact subset of a topological group G/N closed if G is hausdorff?

Question: I just used this hypothesis when I was proving a theorem.But I was not sure if this hypothesis is correct.
Comment: Note that the statement is definitely false for *monoids*: homeomorphically embed $(\mathbb{R}, +)$ into $(\mathbb{R}, \times)$ as the interval $(0, \infty)$.
Comment: Yes.If G is hausdorff,and if K is a compact subset of G/N,is K closed?@NoahSchweber
Answer: Edit: This is a response to the original question:

If $G$ is a Hausdorff topological group and $N$ is a normal subgroup is the quotient map $G\to G/N$ always a closed map?

Assuming $G$ is Hausdorff, one necessary condition for the quotient map $q\colon G \to G/N$ to be closed is that $N$ is closed in $G$. Otherwise $q^{-1}(q(\{1\})) = N$ isn't a closed set, which means that $q(\{1\})$ isn't closed in $G/N$.
For example, the quotient map $q\colon \mathbb{R}\to \mathbb{R}/\mathbb{Q}$ isn't closed since $q^{-1}(q(\{0\})) = \mathbb{Q}$ isn't a closed set in $\mathbb{R}$.
However, there are lots of examples where $N$ is closed in $G$ but the quotient map is not closed.  For example, if $G = \mathbb{R}^2$ and $N=\{0\}\times\mathbb{R}$, then the quotient map $G\to G/N$ is essentially the projection of $\mathbb{R}^2$ onto its first factor.  This is not a closed map since, for example, the set
$$
\{(x,\tan x) \mid -\pi/2<x<\pi/2\}
$$
is closed in $\mathbb{R}^2$, but its projection onto the first factor is not.
The quotient map is always closed if $G$ is compact and $G/N$ is Hausdorff, since every map from a compact space to a Hausdorff space is a closed map.  It follows that the quotient map is closed whenever $G$ is compact Hausdorff and $N$ is closed, since then it follows that $G/N$ is Hausdorff (see here).
Comment: @Meelod For future reference, it's usually not considered polite on this site to change your question after it's been answered.  It's better to leave the original as it is and then start a new question.
Comment: I just changed my question,you may edit your answer if you wish@JimBelk
Comment: I am new in here,but I won`t change my question again...
Comment: @Meelod The answer to your new question is no, by the way.  For example, one-point sets are compact but not closed in $\mathbb{R}/\mathbb{Q}$.
Comment: @Meelod Isn't $A=\{0\}$, $G = \mathbb{R}$, and $N=\mathbb{Q}$ a counterexample?
Comment: yes.now I have no question...thanks for helping me.In fact I had an exam and I was trying to justify my wrong hypothesis.thanks @JimBelk