Proof without words: $1+8\times\text{triangular number}$ is an odd perfect square

Question: A recent question asked how to show that $8T_n+1$ is a perfect square if $T_n$ is a triangular number. This follows immediately from $T_n=\frac12 n(n+1)\implies 8T_n+1=4n^2+4n+1=(2n+1)^2$.
Can this be proven without words?
Comment: I'm not very adept at art, so I'll just describe with words: have eight copies of right-triangular arrays of dots of height and length $n$.  Rotate and fit the triangles together along the hypotenuses to have now four $n\times (n+1)$ rectangular arrays.  Fit these together to form a square missing the center hole of side-length $2n+1$.
Comment: If this seems like a silly question...well, probably it is. But I'm fond of such visual proofs, so this is what sprang to mind when I saw the other question.
Comment: @JMoravitz I was just realizing that. Silly of me not to have spotted it sooner! In fact, that very image shows up on Mathworld's page for the triangular numbers: http://mathworld.wolfram.com/TriangularNumber.html.
Answer: The answer turns out to be quite simple, as @JMoravitz notes in his comment. In fact, Mathworld's page on triangular numbers includes precisely the right image:
Answer: $$
\begin{matrix}
\color{red}{\bullet} & \color{red}{\bullet} & \color{red}{\bullet} & \color{red}{\bullet} & \color{blue}{\bullet} & \color{blue}{\bullet} & \color{blue}{\bullet} & \color{blue}{\bullet} & \color{green}{\bullet} \\
\color{orange}{\bullet} & \color{red}{\bullet} & \color{red}{\bullet} & \color{red}{\bullet} & \color{blue}{\bullet} & \color{blue}{\bullet} & \color{blue}{\bullet} & \color{green}{\bullet} & \color{green}{\bullet} \\
\color{orange}{\bullet} & \color{orange}{\bullet} & \color{red}{\bullet} & \color{red}{\bullet} & \color{blue}{\bullet} & \color{blue}{\bullet} & \color{green}{\bullet} & \color{green}{\bullet} & \color{green}{\bullet} \\
\color{orange}{\bullet} & \color{orange}{\bullet} & \color{orange}{\bullet} & \color{red}{\bullet} & \color{blue}{\bullet} & \color{green}{\bullet} & \color{green}{\bullet} & \color{green}{\bullet} & \color{green}{\bullet} \\
\color{orange}{\bullet} & \color{orange}{\bullet} & \color{orange}{\bullet} & \color{orange}{\bullet} & \color{black}{\circ} & \color{purple}{\bullet} & \color{purple}{\bullet} & \color{purple}{\bullet} & \color{purple}{\bullet} \\
\color{cyan}{\bullet} & \color{cyan}{\bullet} & \color{cyan}{\bullet} & \color{cyan}{\bullet} & \color{magenta}{\bullet} & \color{yellow}{\bullet} & \color{purple}{\bullet} & \color{purple}{\bullet} & \color{purple}{\bullet} \\
\color{cyan}{\bullet} & \color{cyan}{\bullet} & \color{cyan}{\bullet} & \color{magenta}{\bullet} & \color{magenta}{\bullet} & \color{yellow}{\bullet} & \color{yellow}{\bullet} & \color{purple}{\bullet} & \color{purple}{\bullet} \\
\color{cyan}{\bullet} & \color{cyan}{\bullet} & \color{magenta}{\bullet} & \color{magenta}{\bullet} & \color{magenta}{\bullet} & \color{yellow}{\bullet} & \color{yellow}{\bullet} & \color{yellow}{\bullet} & \color{purple}{\bullet} \\
\color{cyan}{\bullet} & \color{magenta}{\bullet} & \color{magenta}{\bullet} & \color{magenta}{\bullet} & \color{magenta}{\bullet} & \color{yellow}{\bullet} & \color{yellow}{\bullet} & \color{yellow}{\bullet} & \color{yellow}{\bullet}
\end{matrix}
$$
Answer: And you can convert
the proof without words
back into algebra
(which has the advantage of
showing that
it is true
for any $n$):
$\begin{array}\\
8T_n
&=4(2T_n)\\
&=4(2(\frac{n(n+1}{2}))\\
&=4(n(n+1))\\
&=4n^2+4n\\
&=4n^2+4n+1-1\\
&=(2n+1)^2-1\\
\end{array}
$


How add/update a record conditionally based on existence of primary key?

Question: I have a table with structure:
Table
(
record_1 int,
record_2 int,
PRIMARY KEY (record_1)
);
I want to write/update a record based on its existence.
I was told to use drupal_write_record(), but for that I must know if the record already exists or not.
In my case I am not aware of its existence.
How can I do this?
Answer: No, you do not "must know if the record already exists or not". If you will look at drupal_write_record source code, you will see these lines:
 if (empty($primary_keys)) {
    // We are doing an insert.

On else, this function will update instead of insert. The only problem with this is that Drupal's record system expects you will leave key management to Drupal. No saving at arbitrary key, because it breaks autoincrement.
If you need to manage keys on your own, use lower level db_merge function instead.
Answer: You're looking for db_merge()

Returns a new MergeQuery object for the active database.

Example from the docs:
db_merge('example')
  ->insertFields(array(
      'field1' => $value1,
      'field2' => $value2,
  ))
  ->updateFields(array(
    'field1' => $alternate1,
  ))
  ->key(array('name' => $name))
  ->execute();

Comment: You beat me again ;)


Where can I find the source for the unix app 'free'?

Question: Free is a rather hard word to Google for, all my variations failed to bring up anything related to the unix app free (it's for viewing memory usage - free -m etc.).
If anyone has a link to the source so  I can have a try at compiling it that would be great.
Cheers
Comment: @cat Take a look at: http://googlesystem.blogspot.com/2011/06/google-discontinues-its-first.html
Comment: Using Googles Linux search engine at google.com/linux sometimes help cut through the false positives, but the word "free" is still very challenging.
Comment: @kmarsh 404 not found, I would have liked to know what that was
Answer: The free command installed by the Debian and Red Hat Linux distributions comes from procps.
The code for free is available in their cvs repository. Release versions are also available to download.
To build just the free command extract the source and run:
make SHARED=0 free

Comment: So you can't just install free? I was wanting to compile/install onto my OS X machine...
Comment: Oh sorry I hadn't looked at CVS..
Comment: @Adam The free command relies on the `/proc/meminfo` file that is available on Linux systems, so it won't work on OS X. I have however updated my answer with the make command you'll need to compile just the free command and a link to download releases.
Answer: Free is part of the Unix Coreutils, which is available here.
Comment: I can't see `free` in the latest version of Coreutils (version 8.4).
Answer: If your using Debian, just do this to get the source for any package:
mkdir work;
apt-get source procps

You'll have a working copy of the source used to build the binary .deb
Comment: You'll have to have the "deb-src" line configured in your /etc/apt/sources.list to fetch source packages.  Looks just like the "deb" line.


what kind of equalization is done for different music genres for your guitar tone?

Question: I have articles which say that if you are into classic rock and metal then you should have more of MIDS etc can some one please provide information that for different kind of genres what kind of EQ is desired in the guitar tone. Please elaborate on the following :

Classic rock / metal - More of MIDS
Death/Black metal- More of LOWS
Blues - less lows and MIDS and HIGH balanced

please explain in brief how eq the above stuff defines your tone and how should a novice approach eq and what other genres of music use what kind of specific eq.
Answer: Do you think B.B. King's guitar sound is anything like Stevie Ray Vaughan's? They're both labeled as "blues".
Do you think Jimmy Page's guitar sound is anything like Brian May's? They're both labeled as "classic rock".
Do you think Randy Rhoads's guitar sound is anything like Dimebag Darrell's? They're both labeled as "metal".
Forget about comparing different guitarists. How about Judas Priest's guitars in Rocka Rolla vs Judas Priest's guitars in Painkiller?
I guess you see where I'm going. Guitar sound is a HUGE subject. There are no hard and fast rules. Everything depends on what you want to hear.
Having said that, there are stereotypical guitar sounds for certain genres. I'll take the risk of sounding stupid and try to give my own recipes:
For blues, I prefer a gain level where you can distort when hitting hard and clean when touching softly. Try to get as much of your distortion as possible from your power amp (volume) instead of your preamp (gain). Set your bass so that it doesn't "boom" when you play the lowest strings. Set your trebles to a level where it doesn't scratch your ears and set your mids high enough to cut through the mix without being overly nasal. No one can say the exact levels like B:4,M:7,T:5 because it depends on your guitar, strings, amp, cab, mic and room.
For classic rock à la Led Zeppelin, add some more power amp gain and if it sounds too nasal cut some mids or add some bass and treble. Nothing drastic though, don't go very far from the blues sound, just make it a little more aggressive.
For classic metal à la Judas Priest, add some more bass and treble. Add some preamp gain but still try to get as much distortion from the power amp as you can.
For post-Metallica metal add some bass until it "booms" slightly and some treble without sounding fizzy. Cut some mids but don't overdo it, for most people scooped mids only sound good with palm muting and you won't be palm muting all the time. And get most of your distortion from the preamp instead of the power amp.
For extreme metal, add even more gain and bass. You can cut some more mids here but be sure that you still cut through the mix.
Answer: The eq settings on the amp are usually close to the same on Rock and other styles. Metal can go to extremes by cutting mids. The mids usually are more in control of the overall tone. I usually have Bass - 7, Mid - 6, Treble -7 for Classic Rock and Blues.
Play a chord and let it sustain while turning one knob up and down to hear the difference. If you were to increase the treble you would hear the high notes of that chord are more noticeable. Try other knobs and you will find a tone you like.
take a look here: https://answers.yahoo.com/question/index?qid=20080328155933AAvPBP1


Erro: Referência de objeto não definida para uma instância de um objeto, como resolver?

Question: Possuo o método ChamadaEfetuada(MAluno) : bool que verifica se a chamada foi efetuada para um determinado aluno, este método e utilizado em outro método ChamadaEfetuada() : bool que ao invés de verificar se a chamada foi efetuada a um único aluno, ele verifica todos alunos de uma vez, e ele só retorna true se a chamada tiver sido efetuada para todos os alunos.
Porem estou recebendo um erro no meu método ChamadaEfetuada() : bool com a seguinte mensagem:

Referência de objeto não definida para uma instância de um objeto.

O erro ocorre nesta linha:
alunos[i].IdAluno = Convert.ToInt32(registro["id_aluno"]);

O compilador diz que o problema esta no meu array alunos.
Código completo do método ChamadaEfetuada(MAluno) : bool:
public bool ChamadaEfetuada(MAluno aluno)
        {
            string query = "SELECT id_aluno FROM Lista_presenca WHERE id_aluno = " + aluno.IdAluno + " AND data = '" + this.Hoje() + "'";

            DadosConexao dados_conexao = new DadosConexao();

            SQLiteConnection conexao = this.conexao.Conexao;
            conexao.Open();

            SQLiteCommand command = conexao.CreateCommand();
            command.CommandText = query;

            SQLiteDataReader registro = command.ExecuteReader();

            bool existe_registro = registro.HasRows;

            conexao.Close();

            return existe_registro;
        }

Código completo do método ChamadaEfetuada() : bool:
public bool ChamadaEfetuada()
        {
            string query = "SELECT id_aluno FROM Alunos";

            int total_alunos = 0, alunos_chamada_efetuada = 0;

            DadosConexao dados_conexao = new DadosConexao();

            SQLiteConnection conexao = this.conexao.Conexao;
            conexao.Open();

            SQLiteCommand command = conexao.CreateCommand();
            command.CommandText = query;

            SQLiteDataReader registro = command.ExecuteReader(); //Obtem os IDs de todos os alunos

            MAluno[] alunos = new MAluno[registro.FieldCount];

            total_alunos = registro.FieldCount;

            int i = 0;

            while (registro.Read())
            {
                alunos[i].IdAluno = Convert.ToInt32(registro["id_aluno"]); //Popula o atributo IdAluno do objeto alunos com os IDs obtidos pela query. Porem aqui acontece o erro.
                i++;
            }

            conexao.Close();

            for (i = 0; i < registro.FieldCount; i++)
            {
                if (this.ChamadaEfetuada(alunos[i]))
                {
                    alunos_chamada_efetuada++;
                }
            }

            if (alunos_chamada_efetuada == total_alunos)
                return true;
            else
                return false;
        }

Os dois métodos acima faz parte da minha classe BLLListaPresenca.
Answer: Não sei se vou te ajudar porque essas mensagens de erro em português atrapalham e faltam informações que possam indicar o porquê do erro.
Eu vou chutar que você não quer o FieldCount afinal não interessa quantas colunas tem. Interessa quantas linhas tem, e esta informação não está disponível e aí você não pode usar um array (na verdade quase sempre que se usa um array, está cometendo um erro). Teria que usar uma lista para ir adicionando as linhas disponíveis nela. Até tem como usar o array, mas a gambiarra é tão grande que nem vou descrever.
Pra falar a verdade eu tenho minhas dúvidas se criar este array ou lista é realmente necessário. Até é neste código, mas ele está com vários problemas.
O código é muito confuso, usa técnicas erradas, códigos desnecessários, os métodos fazem mais do que deveriam, são repetitivos, inconfiáveis, inseguros, bastante ineficientes e nesta forma, um método chamar o outro deveria ser a última coisa a fazer. Precisaria de uma reestruturação completa.
Coloquei no GitHub para referência futura.
Comment: Comece eliminando todas variáveis que são usadas zero vezes, depois as que são usadas apenas uma vez (é raro uma variável que é usada uma vez ser útil, nenhum neste caso). Dê uma lida na classe [`SqlDataReader`](https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader(v=vs.110).aspx). Veja como usá-la, quais o métodos e propriedades existentes eo que elas fzem. Comece usar [`using`](https://msdn.microsoft.com/en-us/library/yh598w02.aspx), Use os [parâmetros do `SQLiteCommand `](http://stackoverflow.com/q/20017688/221800). Mude para `List. Tem mais. isto é só o começo.
Comment: Você esta certo o numero de colunas não e o que eu preciso, eu quero obter a quantidade de linhas que a query me retorna. Porem estou tendo dificuldades para implementar esta regra de negocio, que é verificar se a chamada do dia foi efetuada. Vc tem alguma dica de como eu posso restruturar este código?
Comment: Vou dar uma olhada aqui sobre os parâmetros do SQLiteCommand e também a classe SqlDataReader. O `List` o que seria, uma lista de objeto como array? Quero me aprofundar mais a respeito.
Comment: Vai fazendo perguntas específicas com cada dúvida que tenha.
Answer: Seguindo as recomendações do Maniero fiz as alterações no meu método ChamadaEfetuada() : bool e removi o método ChamadaEfetuada(MAluno) : bool. Substitui o array MAlunos[] alunos por uma lista List<T> e fiz a implementação da regra que é verificar se a chamada já foi efetuada a todos os alunos no meu método, também implementei corretamente os parâmetros do meu SQLiteCommand para efetuar as pesquisas.
Abaixo segue o método ChamadaEfetuada() : bool (reestruturado) que é a solução do problema acima:
public bool ChamadaEfetuada()
{
    /*Listas*/
    var alunos = new List<MAluno>();
    var alunos_chamada = new List<MAluno>();

    /*Prepara a conexão*/
    SQLiteConnection conexao = this.conexao.Conexao;
    conexao.Open();

    using (SQLiteCommand command = conexao.CreateCommand())
    {
        command.CommandText = "SELECT id_aluno FROM Alunos";

        SQLiteDataReader registro = command.ExecuteReader();

        if (registro.HasRows)
        {
            while (registro.Read())
            {
                alunos.Add(new MAluno
                {
                    IdAluno = Convert.ToInt32(registro.GetValue(0))
                });
            }
        }
        else
        {
            conexao.Close();
            return false;
        }

        conexao.Close();
    }

    conexao.Open();

    using (SQLiteCommand command = conexao.CreateCommand())
    {
        foreach (var aluno in alunos)
        {
            command.Parameters.Add("id_aluno", DbType.Int32).Value = aluno.IdAluno;
            command.Parameters.Add("data", DbType.String).Value = this.hoje;
            command.CommandText = "SELECT id_aluno FROM Lista_Presenca WHERE id_aluno = ? AND data = ?";

            SQLiteDataReader registro = command.ExecuteReader();

            if (registro.HasRows)
            {
                registro.Read();

                alunos_chamada.Add(new MAluno
                {
                    IdAluno = Convert.ToInt32(registro.GetValue(0))
                });
            }
            else
            {
                conexao.Close();
                return false;
            }

            registro.Close();
        }

        conexao.Close();
    }

    return (alunos.Count == alunos_chamada.Count);
}

Comment: Ainda pode ser melhorado, mas já é outra coisa. Bem melhor.
Comment: Se tiver mais sugestões pode me dizer que eu tento implementar aqui :)


Polyline refuses to show on IE8, works everywhere else

Question: I've got a custom .NET app using COM exposed objects to render GPS routes collected. It works brilliantly on every platform other than Windows XP running IE8 (wrapped via WebBrowser control in .NET).
To test it out, I've written a test map application, which uses the same object model but slimmed down, so I can debug, so far I'm being presented with IE Script Errors that state:
Line: 319 Char: 17 Error: String expected Code: 0 URL: about:blank
The line it's referring to is:
driverPathPoints[id] = [];
The code for rendering routes is as follows:
function ShowRoute(path, id, col) {

            try {
                clearRoutePaths(id);
            }
            catch (err) { }

            driverPathPoints[id] = [];
            driverDeliveryRouteMarkers[id] = [];

            var pointMarkers = [];
            var pointCounter = 0;
            for (var i = 0; i < path.Count(); i++) {
                driverPathPoints[id].push(new google.maps.LatLng(
                    path.item(i).lat, path.item(i).lng));

                if (pointCounter % 20 === 0) {
                    var marker = new google.maps.Marker({
                        position: new google.maps.LatLng(path.item(i).lat, path.item(i).lng),
                        title: path.item(i).deviceTime + " (" + Math.ceil(path.item(i).speed) + " MPH)",
                        infoParent: id,
                        infoIndex: i
                    });

                    pointMarkers.push(marker);
                }

                pointCounter++;
            }

            markerClusterer[id] = new MarkerClusterer(map, pointMarkers);

            var secondToLastLat = path.item(path.Count() - 2).lat;
            var secondToLastLng = path.item(path.Count() - 2).lng;

            var lastLat = path.item(path.Count() - 1).lat;
            var lastLng = path.item(path.Count() - 1).lng;

            var routeOptions = {
                path: driverPathPoints[id],
                strokeColor: col,
                strokeOpacity: 1.0,
                strokeWeight: 4,
                map: map,
                customIdent: id
            };

            var truckImage = 'http://ccgi.ablebox.plus.com/map_imgs/truck_' + calculateBearing(lastLat, lastLng, secondToLastLat, secondToLastLng) + '.png';

            var MarkerImage = new google.maps.MarkerImage(truckImage,
                new google.maps.Size(120, 120),
                new google.maps.Point(0, 0),
                new google.maps.Point(60, 60));

            var MarkerOption = {
                map: map,
                position: new google.maps.LatLng(path.item(path.Count() - 1).lat, path.item(path.Count() - 1).lng),
                icon: MarkerImage
            };

            var Marker = new google.maps.Marker(MarkerOption);
            driverDeliveryRouteMarkers[id].push(Marker);

            driverGPSDataLayer[id] = new google.maps.Polyline(routeOptions);

            driverGPSDataLayerCount++;
        }

Does anyone have any idea how I can fix this? Before, (while developing) I was able to debug scripts. But I'm running Windows 8 and only have an XP SP3 VM running, but can't debug on it. Was hoping some JS guru could point me in the right direction.
Many thanks.
Edit
I've just chucked my code through a jslint, and it has no 'problems'. I've tried creating a temporary array to fill, and assign that to the layer I'm working with. No change. I've tried the !DOCTYPE html 'fix' no change.
I have no idea why it thinks driverPathPoints[] should be a string. Will continue onward.
Comment: http://jsfiddle.net/. Nothing sinister at all. It allows you to post JS, CSS and HTML and share with other users. We can then see your code and the output
Comment: Can you create a jsFiddle? IE8 also has a developer console. Press F12. It's pretty limited but allows you to step through the code
Comment: I have no idea what a jsFiddle is, but it sounds REALLY sinister! Sorry, I should have said, I'm using WebBrowser control in my .Net app, which wraps IE. I shall update. So, no debug tools :(
Comment: Thats funky. I've done as you've asked, but it wont run as is. As I've stated it uses .NET COM exposed objects, but I guess it at least shows my (dodgy) JS complete: http://jsfiddle.net/Gbz9f/ - Cheers.
Answer: Sussed it. Was due to IE8 not knowing what a Long datatype was for id in: driverPathPoints[id] = [];  (being sent from .NET VB app). As soon as I converted it to a string and sent that as parameter of InvokeScript it was quite happy on XP and IE8.
Thanks :)


JQuery UI Dialog and OnClick event

Question: I have a JQuery UI Dialog which I have put an ASP.NET button on.  I need to be able to call a server side OnClick event from this, but it is never called.  Here is my Dialog, can somebody help?

                    Current Documents :

                                Upload Document :

                                <asp:FileUpload id="fileUploadControl" runat="server" Width="200px" />

                                <asp:Button  ID="btnUploadFile" runat="server" OnClick="btnUploadFile_Click" Text="Upload File" />

EDIT : Here is how the dialog is being created :
$(document).ready(function() {

    $('#<%=dialogWrapper.ClientID %>').dialog({
        autoOpen: false,
        height: 250,
        width: 600,
        modal: true,
        title: "Upload/Open Files",
        show: "drop"
    });

});

Comment: Can you show how you create the dialog? Have a look [here](http://stackoverflow.com/questions/568784/jquery-modal-form-dialog-postback-problems/608215#608215), there might be your answer.
Answer: jQueryUI puts the Dialog box outside of the ASP.NET Form tag and so your button won't register. Try appending the dialog to the Form tag like so:
    $('#divDialog').dialog({
     //your normal dialog settings...

      open: function(type,data) {
        $(this).parent().appendTo("form");
      }
    });

From this post.

JQuery UI Dialog and OnClick event


exclui uma pasta localmente mais nao consigo salvar a mudança remotamente no github "Everything up-to-date"

Question:
exclui a pasta, usei git add e commitei, ele detectou as mudanças no commit mas mesmo assim quando vou dar um push no master ele diz que está "Everything up-to-date"
o que to fazendo errado ?
Comment: Tentou forçar o push?
Comment: qual a diferença pra esse push forçado ? ele re-escreve todas as pastas ? tem alguma maneira de só apagar a pasta q eu quero que apague ?
Comment: usei push origin --force  e funcionou. obrigado
Comment: Sim, o repo vai ser recriado. De nada brother, mas não é normal precisar do --force. E parece que no commit diz "0 deletions". Se acontecer de novo manda aí que a gente investiga.
Answer: O Git não versiona pastas vazias, portanto só a ação de excluir o conteúdo da pasta já fará com que ela saia do versionamento.
Criei um repo com um arquivo na raiz e dois arquivos em uma pasta:

No Git não basta excluir os arquivos diretamente no sistema de arquivos ou no disco, é necessário fazer isso por um comando de exclusão:
git rm .\files\*.txt

O comando acima exclui todos os aquivos de extensão txt da pasta files. Repare que eu não fiz a exclusão da pasta, nem diretamente no dico.
Em seguida eu fiz o commit dessa alteração. A imagem abaixo mostra o commit e a listagem de arquivos no repositório, mostrando que a pasta não existe mais.

Para enviar as alterações para o Github é só utilizar o comando:
git push origin master

Assumindo que o seu remote é origin e a branch é a master.
Não é necessário utilizar o force, pois se não tem inconsistência entre o repositório remoto e o local, exclusão de arquivos ou pastas não necessitam de permissões especiais.


Can I use asyncio to read from and write to a multiprocessing.Pipe?

Question: I need to communicate between processes in Python and am using asyncio in each of the processes for concurrent network IO.
Currently I'm using multiprocessing.Pipe to send and recv significantly large amounts of data between the processes, however I do so outside of asyncio and I believe I'm spending a lot of cpu time in IO_WAIT because of it.
It seems like asyncio can and should be used to handle the Pipe IO between processes, however I can't find an example for anything but piping STDIN/STDOUT.
From what I read it seems like I should register the pipe with loop.connect_read_pipe(PROTOCOL_FACTORY, PIPE) and likewise for write. However I don't understand the purpose of protocol_factory as it would relate to a multiprocessing.Pipe. It's not even clear if I should be creating a multiprocessing.Pipe or whether I can create a pipe within asyncio.
Comment: How about https://github.com/kchmck/aiopipe
Comment: Just looking at the official documentation: https://docs.python.org/3/library/asyncio-eventloop.html#id12
Comment: can you post the code you have?
Comment: I'm trying to reproduce something akin to the asyncio UDP echo server in the docs (https://docs.python.org/3.6/library/asyncio-protocol.html#udp-echo-client-protocol), a simple ping back and forth between processes, over pipes rather than over the network stack. An explanation of how to architect that same example over pipes would be a very helpful answer.
Comment: @kmaork that looks like a good answer, if you post that as the answer I'll accept it.
Answer: multiprocessing.Pipe uses the high level multiprocessing.Connection module that pickles and unpickles Python objects and transmits additional bytes under the hood. If you wanted to read data from one of these pipes using loop.connect_read_pipe(), you would have to re-implement all of this yourself.
The easiest way to read from a multiprocessing.Pipe without blocking the event loop would be to use loop.add_reader(). Consider the following example:
import asyncio
import multiprocessing

def main():
    read, write = multiprocessing.Pipe(duplex=False)
    writer_process = multiprocessing.Process(target=writer, args=(write,))
    writer_process.start()
    asyncio.get_event_loop().run_until_complete(reader(read))

async def reader(read):
    data_available = asyncio.Event()
    asyncio.get_event_loop().add_reader(read.fileno(), data_available.set)

    while not read.poll():
        await data_available.wait()
        data_available.clear()

    print(read.recv())

def writer(write):
    write.send('Hello World')

if __name__ == '__main__':
    main()

Pipes created using the lower-level os.pipe don't add anything extra the way that pipes from multiprocessing.Pipe do. As a result, we can use os.pipe with loop.connect_read_pipe(), without re-implementing any sort of inner-workings. Here is an example:
import asyncio
import multiprocessing
import os

def main():
    read, write = os.pipe()
    writer_process = multiprocessing.Process(target=writer, args=(write,))
    writer_process.start()
    asyncio.get_event_loop().run_until_complete(reader(read))

async def reader(read):
    pipe = os.fdopen(read, mode='r')

    loop = asyncio.get_event_loop()
    stream_reader = asyncio.StreamReader()
    def protocol_factory():
        return asyncio.StreamReaderProtocol(stream_reader)

    transport, _ = await loop.connect_read_pipe(protocol_factory, pipe)
    print(await stream_reader.readline())
    transport.close()

def writer(write):
    os.write(write, b'Hello World\n')

if __name__ == '__main__':
    main()

This code helped me figure out how to use loop.connect_read_pipe.
Comment: doesn't the first code block break if there are multiple sends before a recv? or does the .poll() guard against that?
Comment: The .poll() guards against that. If there were earlier sends, the code will keep going to the .recv() call until all data in the pipe has been consumed.
Comment: Note that the `add_reader` strategy only works on Linux, and not on Windows
Answer: aiopipe seems to do what you want! It can be used with the builtin multiprocessing module, and provides a similar API to the regular blocking pipes.


How to set a button's background reveal brush in .cs code?

Question: currently I know how to use some system brushes like
xxx.Background = (SolidColorBrush)Application.Current.Resources["SystemControlForegroundAccentBrush"];

But how to use the reveal brush?
I use the same way,
xxx.Background = (SolidColorBrush)Application.Current.Resources["SystemControlBackgroundBaseLowRevealBackgroundBrush"];

It throw errors.
System.InvalidCastException:"Unable to cast object of type
    'Microsoft.UI.Xaml.Media.RevealBackgroundBrush' to type
    'Windows.UI.Xaml.Media.SolidColorBrush'."

Answer: We could not set reveal brush like general BackgroundBrush. RevealBackgroundBrush is a dynamic effect and does not exist independently. In other words, the RevealBackgroundBrush depends on the state. To enable Reveal on custom controls or re-templated controls, you modify the control's control template. Most control templates have a grid at the root; update the VisualState of that root grid to use Reveal. For example if your want to add RevealBackgroundBrush for button.

Usage
Btn.Style = (Style)App.Current.Resources["ButtonStyle1"];


Expectations from a violin teacher towards an adult learner

Question: I am an adult student learning the violin. I have have been playing for slightly more than a year. I can play most of the pieces in Suzuki book 1 now and have progressed up to book 2. I do not know if this is the norm; I feel like my teacher does not place too many expectations on me. Once she covers approximately 80% of a piece, we would move on. But I don't find that I'm playing the best that I can yet (e.g. when I listen to YouTube covers of the pieces, and then compare to my own recordings). One of my major weakness in playing is intonation because I have zero background in music and therefore still struggle to play in tune.
What would be better in this case? Continue with my teacher's teaching pedagogy, or request for her to fine tune and be critical on every piece. I understand the latter may make me lose my interest and joy in playing the violin more quickly. But I really want to be able to play pieces so perfect, to a level where they can be performed to an audience.
Comment: You should definitely bring this up with your teacher. I had exactly this kind of conversation with my clarinet teacher recently. In my case, my teacher doesn't want to take my money for telling me things I already know. Your teacher might be working on developing your ear and technique and leaving it to you to know where you need to focus on "finishing" pieces. That's one difference between children and adults, generally adults have more ability to objectively evaluate their own progress
Comment: By "covers approximately 80% of a piece", do you mean that you only get to play approx. 80% of the notes? Or do you end up skipping dynamics or notated articulation? Skipping anything on the score at the point you have to move on is a giant red flag.
Comment: A suggestion based on my teenage years of taking piano: get each piece to 80% competency and move on to a new piece. But put a star on every piece that you really like and are naturally good at. Once or twice a year have your teacher help you prepare one of the starred pieces as if you were doing it for a competition or recital or examination; that will help you get a sense of what it is like to take an 80% piece to performance-ready. It's a lot of work! Bonus points if you then actually do the recital. :)
Comment: I often think of the story of the two pottery classes. Class 1 is graded on quality of their pots, class 2 is graded on how many pots they produce to a minimal standard.  At the end of the term, class 2 is creating pots both faster *and better quality* than class 1. An apocryphal story probably, but relevant to music practice as well.
Comment: I have to point one thing out, for posterity: "I don't find that I'm playing the best that I can yet (e.g. when I listen to YouTube covers... and then compare to my own recordings)." That means actually not comparing your current playing to "the best you can," but to the best that the Youtuber can. It's not always a useful exercise.
Answer: As a beginner, you can't expect to get a piece sounding 'perfect' in any reasonable length of time, because you haven't yet built up all the skills - intonation, bow control, phrasing, your own style - that will make a piece sound like a well-played violin piece.
The best way to build up those general skills isn't to play the same piece over and over again, but to work through different pieces, building up your experience. This is because each piece challenges and develops your skills in different ways.
You can keep revisiting your old pieces as your skills improve, and you should find they sound better and better. How good is good enough is up to you - as mentioned in musicamante's answer, you may find 'perfection' an unattainable goal.
Comment: Its usually general advice for any skill to not bother grinding a single thing until its perfect over getting pretty good at a range of exercises and raising the quality level of everything gradually.
Comment: Additionally, while OP may want to grind and that's okay too, this is not something a teacher's time is best spent on. So I'd argue that the teacher is actually ensuring their presence (given their finite hours) is as optimal as possible.
Comment: @Qwertie yes - a couple of related ideas are that of [Overfitting](https://en.wikipedia.org/wiki/Overfitting), and [*What should they know of X, who only X know?*](http://www.kiplingsociety.co.uk/poems_englishflag.htm)...
Answer: As a teacher, and, most importantly, "former" pupil, I'd say this: you will probably never get to the 100%. Not even close.
Many professional and acclaimed musicians wouldn't say that they got their "one hundred percent" on anything. Ever.
A known quote by Pablo Casals, considered one of the greatest cellists of all time, was the answer to a question about why he was still doing 6-hours practice everyday, even at 80 (that was his age for the last verified quote, but some report the same even when he was 95).
His answer was, more or less: "Because I think I'm [still] making progress".
The fact is, your expectations are constantly increased by both your progress in specific skills and your experience in life.
I don't know your teacher and her/his method, but as a guess I'd say that your age might be an important aspect to be considered.
The learning curve of an adult is radically different than that of a child, teenager or young adult. The more you're younger, the faster you learn radically new skills (you're a blank slate, new things are much more evident and usually written in large characters), but this doesn't mean that your learning is slower at later age, as the experience acquired in adulthood can potentially make you learn new skills even faster.
Unfortunately, experience is also a big drawback: it tells you to avoid trying things because you "think" they're not worth it, or to believe that they won't do any good, and that's not always fine - especially for art related subjects.
Consider yourself lucky: you can still realize that you're not getting good as you wish (most adult people is not able to do that, for any new skill or knowledge: consider the current problem of disinformation and spreading of fake news on scientific facts).
I had experience with adult beginner students, and I have to say that's not easy: you have to continuously fight between giving satisfaction while keeping interest and providing useful knowledge, and, most importantly, you have to face that you're not teaching on a "blank slate". On the contrary: you got an already filled slate, with very few space left to write, and lots of (possibly incoherent) data, in which you have to find space to write things that consistently correlate to what is already there and that is probably impossible to clear out.
As others already told you, you should probably openly speak to your teacher, let her/him understand your doubts and ask about her/his method.
But, in any case, don't expect final results, even from "simple" books normally aimed for children. If you had the opportunity to actually listen to children having lessons with your books, you'd probably hear lots of awful noises. But those children would be normally "fine" with it, as their teachers would say.
That's what learning violin (and many instruments, not only stringed ones) means.
Be patient, tuning is one of the most important and hard aspects in violin. Professionals struggle with it even after decades of studying. For instance, you could see the latest posts from Hilary Hahn, a world's leading violinist, who is publicly struggling with tuning (amongst other things) while studying forced at home in these very days.
You can only get it "right" from experience: both from practice and listening; and that's the fact: you only get practice experience by playing, while you can have listening experience even if you never played in your life, and that's probably your case; beginning to play with an instrument at young age means creating a "parallel learning curve", so your expectations are not as "big" or "defined" as the limitations to those expectations and beliefs as an adult (professional or amateur whatsoever).
A child can truly believe to become an astronaut.
An adult usually thinks it's impossible, and hardly dreams about it - but maybe still can.
Answer: Let a professional play "Michael, row the boat ashore" in a beginners' arrangement (or even just the melody side) on something as simple to play as a piano.  You'll take years of practice before everything is just-right in articulation, phrasing, dynamics, development, tension like that.
And you'll not get there just playing "Michael, row the boat ashore".  In the long run, your teacher is there for teaching you, breaking new ground, opening new possibilities and insights for you and takes the material and supervision best suited for that.
But of course that should not keep you from revisiting previous material with those lessons in mind.  You'll not get anywhere by only letting your fingers touch teaching material under supervision of a teacher, and you'll not get anywhere by not actually giving the teacher's lessons and material a chance to seep into your play.
So try keeping working on what your teacher suggests, but don't close yourself off to other experiments, particularly older material.  And when you find that you enceounter problems you did not previously realise or have, don't be shy to consult the teacher about them, too: a good teacher should adapt to the student's needs, and those don't confine themselves to going through the assigned material.
Answer:
Once she covers approximately 80% of a piece, we would move on. But I
don't find that I'm playing the best that I can yet (eg when I listen
to youtube covers of the pieces, and then compare to my own
recordings)

I'm a year ahead of you (been learning for almost 2 years now) and my teacher is the same. Here's the thing. I love going back (particularly in lockdown when lessons are off) and playing pieces from a year or so ago. Not surprisingly I play them a lot better than I did at the time but, you know what?, still not perfect!

Continue with my teacher's teaching pedagogy or request for her to
fine tune and be critical on every piece. I understand the latter may
make me lose my interest and joy in playing the violin more quickly.
But I really want to be able to play pieces so perfect, like it can be
performed to an audience or something

I'm sure that if you stop and think critically about what you've just written then you'll realise the big flaw. If your teacher were to make you go on practising the same piece over and over and over again until everything was perfect you might end up playing only that piece for a year or two. Your improvement would get slower and slower as you had less and less incentive to practice.
Comment: This is exactly it. This is what my clarinet (which I've been playing about 4 months) teacher told me. Also my guitar (which I've been playing 27 years) teacher has recognized that I don't need to be told how to work on pieces. Instead he shows me how to refine techniques and help me get unstuck on pieces I've chosen to work on.
Answer: One thing that you might find if you asked your teacher this same question is that they tell you what our teacher tells my son.  (I'm learning along with, at his pace, with occasional lessons for me.)
She tells us that we learn the piece the first time for the purpose of learning the technique which the piece exists to teach.  Particularly in book 1, Suzuki pieces each exist primarily to teach a particular thing, often introducing a new skill or practicing a particular technique that will be needed heavily in future pieces.
Once we've learned that technique, it's okay to go on and learn the next song.  But, we still play the older pieces, always.  We play them both to remember them, and also to polish them - by the time we get to graduation, we should have polished most of the songs in the book (I gather it's less common to play Gavotte or Happy Farmer for graduation, as those are the last songs you usually learn, and so are less polished).  Hopefully by the time we get there, we've worked out the issues we had in earlier pieces.
Our instruction - somewhat earlier than you to be sure - is to play each piece at least once a week if possible, and usually we spend a little time working on one older piece in particular that week.
Answer: Every student is different so you can't really compare.  The violin is a very hard instrument to learn.  With any instrument you need to master the physical aspect of correct body movement and posture, proper technique, etc.  This takes years.  For kids that start young and move on to music conservatories in college, they've had a decade or more of practice before being at that level.  I have played violin (my first real instrument with an instructor) and classical bass (a violin like instrument) and I can tell you that intonation is tough.  Also, proper bow technique takes years to develop.
As for only getting through 80% of a piece?  If you spent 10 years on one song you would go mad.  You need to appreciate that the songs are supposed to be a fun and musical way to practice or apply technique.  A you get better you should go back to those pieces and see how they feel.  I would hope that you could get better at them than you thought you were at the time, and with less practice.  Variety is also important to make progress.  I don't think you instructor is cheating you by moving on to a new piece.  That real question is have you made progress in anything.  Are you better now than when you started.  I have the same issue with some of my guitar students, especially adult learners.  It is very hard to assess yourself, both positively and negatively.  Try recording yourself once a week and after 6 months try to objectively listen and see if your technique is better, intonation better.  I was on track to enter a music program or conservatory before changing my life path and after years of bass lessons, scoring very high in all state competitions, and even getting steady gigs, intonation was a constant effort to refine and perfect.  My teacher had me sight singing bass concertos before playing.  You are not at a level where that makes sense but my point is that for a fret-less instrument you need to be patient with yourself.
I think you should express your concerns about development to your teacher.  I'm sure she'd appreciate the feedback and your interest in your own development.  Communication is important.  But be prepared to hear that your expectations may be too high.  Maybe if you isolate one aspect of your playing (like intonation) she could give you more work in that area.
Answer: I echo the other answers that discuss how each new piece introduces a new skill or technique to be mastered. New notes, bowings, fingerings...
You mention one of your weakness is intonation:

One of my major weakness in playing is intonation because I have zero background in music and therefore still struggle to play in tune.

For this, I recommend

memorizing your music, and

using the Intonia app http://intonia.com/index.shtml

The app visualizes your intonation. This screenshot shows the Intonia app while I play two octave C major arpeggio. Blue tinted lines indicate the note is flat, red means sharp, and white is in tune.
Comment: You can actually fake quite a lot of this (up to a certain level, at least) through good muscle memory. Said as someone who has a really rubbish sense of pitch but really excellent muscle memory. It probably falls apart once you need to make more conscious adjustments to pitch, but as long as all you need is to get your finger down in the same spot every time...
Answer: I studied Suzuki violin as a child, and my oldest child is studying it now. Violin is one of the most difficult of all instruments on which to reach a basic level of proficiency. A beginner on piano or guitar can be very listenable. It takes most people multiple years of study to be even bearable on a violin, because minor mistakes with either the bow or the fingering can produce horrible sounds. Given that, you should expect to study for multiple years before you achieve a sound that even approaches the ones you are trying to emulate.
As other people have mentioned, each piece in the early Suzuki books is designed to impart a specific foundational skill. As you add each new skill, you go back and apply it to the old songs, and they get incrementally better. Child learners typically have to be forced to go back and review their old pieces --they are attracted to novelty. As an adult learner, it's probably expected that you will be conscientious about polishing your old pieces on your own accord.
Your teacher is entirely correct to instruct you to keep moving forward in your repertoire. In general, you won't have all the techniques you need to sound really good with a given Suzuki piece until you're a book or so beyond it. But you can still play Twinkle better each time you return to it.


SuiteScript - removeLine not removing last line

Question: I have created a pageInit SuiteScript that should remove line items on a Sales Order if they have a custom field filled out. The issue I am having is that it will not remove the line if it is the last line and no other line has a value for loss.
<code>function pageInit(context) {

    var objRec = context.currentRecord;

    var itemsLength = objRec.getLineCount({
        sublistId: 'item'
    });

    for (var i = itemsLength-1; i >= 0; i--){
        var loss = objRec.getSublistValue({
            sublistId: 'item',
            fieldId: 'custcol_linelossreason',
            line: i
        });

        if (loss) {
            objRec.removeLine({
                sublistId: 'item',
                line: i,
                ignoreRecalc: true
            });
            log.debug('removed', 'Line ' + i + ' has been removed.');
        } else {
            log.debug('no removal', 'Line ' + i + ' will remain.');
        }
    }
</code>
Answer: The only thing I can find is that maybe that line is missing the loss value...?  I tested with your code, minus the loss piece and it worked perfectly.  Below is what I tried with.
<code>**
 * @NApiVersion 2.x
 * @NScriptType ClientScript
 * @NModuleScope SameAccount
 *
 */
define(['N/record'],function(record){
  function pageInit(context){
    var objRec=context.currentRecord;
    var itemsLength=objRec.getLineCount({
      sublistId:'item'
    });
    log.debug('itemsLength',itemsLength);
    for(var i=itemsLength-1;i>=0;i--){
      log.debug('running line ',i+' of '+itemsLength);
      /*
      var loss=objRec.getSublistValue({
        sublistId:'item',
        fieldId:'custcol_linelossreason',
        line: i
      });
      */
      //if(loss){
      objRec.removeLine({
        sublistId:'item',
        line:i,
        ignoreRecalc:true
      });
      log.debug('removed','Line '+i+' has been removed.');
     /*
      }else{
        log.debug('no removal','Line '+i+' will remain.');
      }
      */
    }
  }

  return{
    pageInit:pageInit
  }
});
</code>
Comment: Thank you for your response! Your code did not work in my environment which made me dig deeper. Turns out I had two instances of this same script running so they were conflicting with one another.
Comment: Yep, that'll definitely do it. :)  Glad you found the issue!
FYI, if you have not already, make sure to check out the NetSuite Professionals Slack. :)


Blinking LED on MPLAB not Working ?

Question: am using MPLAB to program my new microchip board and programming it programming it using pickit3
code:
<code>// Include the necessary device header file
#include <p18f8722.h>

#pragma config OSC = HSPLL, //OSCS = OFF // HS-PLL Enabled, Internal External Osc. Switch Over OFF Disabled
#pragma config PWRT = OFF // Power Up Timer: OFF Disabled
//#pragma config BOR = OFF, BORV = 25 // Brown Out Reset: OFF, Brown Out Voltage: OFF Disabled
#pragma config WDT = OFF, WDTPS = 128 // Watchdog Timer: OFF Disabled, Watchdog Postscaler: 1:128
//#pragma config CCP2MUX = OFF // CCP2 Mux: OFF Disabled (RB3)
//#pragma config STVR = OFF // Stack Overflow Reset: OFF Disabled
#pragma config LVP = OFF // Low Voltage ICSP:OFF Disabled
#pragma config DEBUG = ON // Background Debugger Enable: OFF Disabled
#pragma config CP0 = OFF, CP1 = OFF, CP2 = OFF, CP3 = OFF // Code Protection Block 0-3: OFF Disabled
#pragma config CPB = OFF // Boot Block Code Protection: OFF Disabled
#pragma config CPD = OFF // Data EEPROM Code Protection: OFF Disabled
#pragma config WRT0 = OFF, WRT1 = OFF, WRT2 = OFF, WRT3 = OFF // Write Protection Block 0-3: OFF Disabled
#pragma config WRTB = OFF // Boot Block Write Protection: OFF Disabled
#pragma config WRTC = ON // Configuration Register Write Protection: OFF Disabled
#pragma config WRTD = OFF // Data EEPROM Write Protection: OFF Disabled
#pragma config EBTR0 = OFF, EBTR1 = OFF, EBTR2 = OFF, EBTR3 = OFF // Table Read Protection Block 0-3: OFF Disabled
#pragma config EBTRB = OFF // Boot Block Table Read Protection: OFF Disabled

// Function prototypes
void delay1(void);

// Main code section. Execution starts here.
void main(void){
 // First some setup code for the LED
 // The LED will be driven by port D, bit 0, driving the anode, cathode to ground

 // First we should clear the port D, bit 0 data latch
 LATDbits.LATD0=0;

 // We need to set port D, bit 0 as an output
 // Using TRISDbits instead of TRISD allows isolating a single bit leaving the other bits unchanged
 TRISDbits.TRISD1=0; // 0 = output, 1 = input

 // Set port D, bit 0 to off (driving the LED anode, cathode to ground)
 PORTDbits.RD1=0;

 // LED blinking loop that never ends since '1' never changes
 while(1){
 PORTDbits.RD1=1; // turn the LED on
 delay1(); // call the delay function
 PORTDbits.RD1=0; // turn the LED off
 delay1(); // call the delay function
 }
 // end of main, but we will never get this far (endless loop)
}

// Start of our functions
void delay1(void){
 /*
 It is important to note that all variable declarations need to be placed before any code in
 a function or the build will fail.
 */
 // declare a long integer and set it to zero
 long int loop1=0;

 // count from zero to 30,000 then continue on
 // Lower than 30000 for a faster blink, higher for a slower blink.
 for(loop1=0;loop1<=30000;loop1++){

 }
 // The loop is done and execution has moved past the loop
}
</code>
this code didn't do anything , it compiled perfectly on high tech C compiler but it didn't workout as it was expected ,
maybe the problem is in the configuration bit ? any idea how to solve this ?
Answer: Judging by the controller and port, I am guessing that you are using the PIC18 Explorer board.  If so, please verify that jumper JP1 is in place.  This must be in place when using the onboard LED's.
If it is not this board, then could you be using the wrong port?  For instance, the "low pin count" demo board I received with my pickit has the LED's on port C, not D.
Comment: I am using PIC18 Explorer board , JP1 is in place ! I tried bits from all the the ports yet no result !
Answer: Check if that pin also has an analog capability (ANx).
If it's the case, analog is the default setting and you cannot drive the pin. You should set it in digital mode first.

Blinking LED on MPLAB not Working ?


Borda não cobre tudo

Question: Minha borda não cobre tudo como gostaria, como podia fazer com que a borda vá ate antes de acabar o Limite ?

Meu css:

.conteudo
{
padding: 20px;
}

fieldset
{
border: 1px solid #000;
padding: 20px;
height: 200px;
}

       <fieldset>
         <legend>Limite</legend>
       </fieldset>

O que acontece:

Código todo:

@using SoftluxWebCore.ViewModels.Tabelas.Financeiro

<link href="~/css/Tabelas/Financeiro/FormaPagamento.css" rel="stylesheet" />

@using (Html.BeginForm())
{

using (Html.DevExtreme().ValidationGroup())
{
    @Html.AntiForgeryToken()

        @(Html.DevExtreme().Form<FormaPagamentoViewModel>()
                                                                .ID("formularioCadastro")
                                                                .ShowValidationSummary(false)
                                                                .Items(items =>
                                                                {
                                                                    items.AddGroup()
                                                                    .Items(groupItems =>
                                                                    {
                                                                        groupItems.AddSimpleFor(m => m.Fpg_descricao)
                                                                        .Editor(e => e.TextBox().Width("350px"));
                                                                        groupItems.AddSimpleFor(m => m.Fpg_quantidade)
                                                                        .Editor(e => e.NumberBox().Width("70px").OnKeyPress("key_press"));
                                                                        groupItems.AddSimpleFor(m => m.Fpg_LimiteDesconto)
                                                                        .Editor(e => e.NumberBox());
                                                                        groupItems.AddSimpleFor(m => m.Fpg_acrescimo)
                                                                        .Editor(e => e.NumberBox());
                                                                        groupItems.AddSimpleFor(m => m.Fpg_desconto)
                                                                        .Editor(e => e.NumberBox());
                                                                    });
                                                                    items.AddSimpleFor(m => m.Fpg_situacao)
                                                                        .Label(l => l.Visible(false))
                                                                        .Editor(editor => editor.CheckBox().ID("sit").Text("Ativo"));
                                                                    items.AddSimpleFor(m => m.Fpg_orcamento).CssClass("orc")
                                                                        .Label(l => l.Visible(false))
                                                                        .Editor(editor => editor.CheckBox().ID("orc").Text("Padrão para Orçamento"));
                                                                })
                                                                .FormData(Model)
        )

        <fieldset>
            <legend>Limite</legend>
        </fieldset>

    <button type="submit" class="btn btn-success btn-sucesso"> Gravar</button>
    <button type="reset" class="btn btn-danger btn-cancelar" onclick="parent.fecharJanela('CadastroFormaPagamento')"> Cancelar</button>

}
}

@section Scripts {
@{await Html.RenderPartialAsync("_ValidationScriptsPartial"); }
}

Código de criação do modal:
function geradorCodigo(idjanela, titulojanela, urljanela, largura, altura, aoFechar) {

    document.getElementById("geradorCodigos").innerHTML = "

";
    var janela = $("#" + idjanela).kendoWindow({
        width: largura,
        height: altura,
        title: titulojanela,
        iframe: true,
        modal: true,
        close: aoFechar,
        content: ".." + urljanela,
    }).data("kendoWindow").open();

    janela.center();

}

Comment: Não consegui reproduzir seu erro da imagem. Inclusive editei seu post add o snippet e o mesmo atendeu, qual browser esta testando? pode ser necessário adicionar algum webkit
Comment: Utilizo o google chrome, não sei o que é webkit
Comment: Mas trabalho com janelas, será que pode ser isso?
Comment: Eu reproduzi seu código, ele está correto, veja aqui https://jsfiddle.net/gferreiraa/pu2yos41/
Comment: é possível compartilhar este código da modal todo?
Comment: Vou editar a publicação
Comment: Vamos [continuar esta discussão no chat](https://chat.stackexchange.com/rooms/89679/discussion-between-getulio-rafael-ferreira-and-jeff-henrique).
Answer: Seu problema é que em algum lugar do seu CSS ou do Framework que vc está usando existem propriedades na legend que não deveriam!
Acredito que dentro da tag legend vc pode ter colocado alguma outra tag, ou alguma classe do Framework CSS que está usando. Ou colocou algum elemento de titulo tipo h3 ou dentro da legend e esse h3 já tinha alguma propriedade CSS nele.
Por algum motivo a sua legend deve estar com width de 100%
Veja que desse forma eu simulei exatamente o "erro" que o seu textfield apresentou...

Código da imagem acima:

.conteudo
{
padding: 20px;
}

fieldset
{
border: 1px solid #000;
padding: 20px;
height: 50px;
}

legend {
  width: 100%;
}

       <fieldset>
         <legend>Limite (legend com width de 100%)</legend>
       </fieldset>

       <fieldset>
         <legend style="width: initial;">Limite (legend com width de initial)</legend>
       </fieldset>

Comment: Ah sim, muito obrigado pela ajuda @hugocsl
Comment: Sim, o legend recebe width de 100%, já tive um problema com isso q cobria outro objeto, mas não sabia que era por causa disso que a borda n pegava, muito obrigado pela resposta
Comment: E não era css, ele já vem definido por padrão creio eu
Comment: A legend não eh 100% por padrão não ... Em algum lugar tem algum css colocando esse elemento com width de 100%... Tente inspecionar o elemento ai para ver de onde vem a propriedade
Comment: Não tem como enviar imagem aqui, mas creio eu que vem do bootstrap então, http://localhost:5000/lib/bootstrap/scss/_reboot.scss, isso que me aparece quando inspeciono e com width: 100%
Comment: @JeffHenrique era isso mesmo, teste aqui no BS3 e BS4 e nos dois o framwrok por padrão coloca a lagend com 100% de width...

Borda não cobre tudo


Como trabalhar com ui-mask em input angularjs

Question: <form name="myForm" ng-submit="addState(myForm.$valid)" novalidate >

        <input ng-model="data.cnpj" type="number" ui-mask="999.999.999-99" placeholder="CNPJ" required ng-minlength="6" ng-maxlength="12" ng-pattern="/^[0-9]{1,7}[-\.\/]?+$/">
 </form>

O que é preciso colocar no controller para o  ui-mask funcionar?
Eu tentei isso mas não deu certo.
mainAppControllers.controller('Ctrl', ['myservice','$rootScope','$scope', '$routeParams', '$location','$timeout',
function(myservice, $rootScope, $scope, $routeParams, $location,$timeout ){

Comment: já tentou importar o "ui-utils" ou "ui.mask"  ?
Comment: Já, não rolou :(
Comment: @ClaudiaMardegan Você carregou o `ui-utils.js` e importou o `ui-utils`? Aparece algum erro no console?
Comment: Não aparece erro, eu consegui fazer ele pegar, mas ele so funciona no 1 item no segundo não criou a mascara.

Comment: @AndréRibeiro qual seu linkedin?
Answer: Olhando pelo seu comentário, se a primeira tag
<input ng-model="data.cnpj" type="text" ui-mask="999.999.999-99" ng-pattern="/^[0-9]{1,7}[-\.\/]?+$/">

funcionou, altere a segunda para
<input ng-model="data.data" type="text" ui-mask="99/99/9999" ng-pattern="/^[0-9]{1,7}[-\.\/]?+$/">


React V16.7 TypeError: Object(...) is not a function

Question: <code>  import React, { useContext } from 'react';
  useContext is undefined.
</code>
error details:
<code>  Uncaught (in promise) TypeError: Object(...) is not a function
</code>
error when processing
<code>   const context = useContext(UserContext);
</code>
Current react versions:
<code>   "react": "^16.7",
  "react-dom": "^16.7",
</code>
Comment: Hooks are available only in the alpha version currently
Answer: To fix the issue downgrade react and react-dom to 16.7.0-alpha.2 as hooks are not available in v16.7
<code>    "react": "16.7.0-alpha.2",
    "react-dom": "16.7.0-alpha.2"
</code>
Comment: This is not working for me. Is there any other possible solution?
Comment: found this solution `"react": "next",
"react-dom": "next"`


Firefox and toFixed()

Question: When i do
$("#sum").html(parseFloat("2.2").toFixed(2));

In firefox i get:
"2.20"

in
 $("#sum").html()

I want to calculate (and display correct) with this div (#sum) what is not possible, because i get the float value with
sum = parseFloat($("#summe").html());

and it returns NaN.
This works with Chrome. Is there any way to get this to work with firefox?
Comment: Do you actually have an element with ID `summe`, or is that a typo?
Answer: Use .text() in both cases rather than .html(), since you are only setting text.
// Set
$("#sum").text(parseFloat("2.2").toFixed(2));

// Get (don't forget `var` if you're declaring here)
sum = parseFloat($("#summe").text());

Firefox and toFixed()


Como é identificado um bloco de escopo em uma linguagem como Python?

Question: Como uma linguagem identifica um bloco onde não usa chaves para abrir e fechar?
function exemplo(){
  // ...
}

Acredito que no exemplo acima o parser crie um bloco de escopo a partir das chaves, mas em uma linguagem como Python
def exemplo():
  // ...

Ele leva em consideração o nível de indentação como prioridade?
Como é feito a leitura? Como é gerado?
Comment: Primeiro, o que é uma linguagem *duck typing*? O que isto tem a ver com o escopo ou o bloco de comando? Você quer saber como o Python identifica o começo e fim do bloco de comando?
Comment: Isso mesmo, como é identificado o começo e o fim de um escopo. fiz a pergunta sem ler nada sobre Duck Typing apenas oque eu pensava que seria. Lendo esse artigo https://osantana.me/duck-typing/ vi que ta totalmente errado esse titulo.
Answer: Uma linguagem como Python, assim como diversas linguagens funcionais, só para citar algumas, a delimitação de um bloco de comandos (que pode gerar novo escopo ou não) é feita basicamente pela indentação (o deslocamento de espaços do início da linha).
Quando o parser identifica que há espaços adicionais no início da linha em relação a linha anterior ele considera que houve um indent. Quando ele identificar que uma nova linha voltou para a coluna anterior que estava antes no nível anterior (ele vai empilhando isto), então ele considera que houve um dedent. A marca de indent funciona como abre chave e a marca de dedent funciona como o fecha chave. Você pode não estar vendo nada mas o compilador sabe que tem uma marca ali que foi calculada.
Obviamente é preciso formatar bem o código para tudo dar certo e o parser "não se perder". Claro que algumas regras podem facilitar isto.
O Python ainda usa os dois pontos na linha anterior ao bloco para identificar que ela terá um bloco adiante o que até facilita o parser pelo menos entender melhor qual era a intenção e se antecipar (lookahead).


Diferença entre comandos para interromper execução

Question: Verifiquei que existem diversas formas de se interromper uma execução.
Basicamente qual é a diferença entre usar os comandos:

break;
sys.exit() ( Do módulo sys);
os._exit() ( Do módulo os);
exit();
quit();

Reparei que alguns são vinculados a execução de uma rotina (sys.exit() como exemplo), e outros ao kernel (exit() entre outros ).
Answer:
break

Sai apenas de um laço e não termina a aplicação, ele é menos que um return. Até um return pode encerrar a aplicação quando ele está na mesma função que é ponto de entrada.

sys.exit() ( Do módulo sys);

Encerra a aplicação lançando uma exceção (SystemExit) que pode ser tratada em algum ponto, e todo processo de encerramento, incluindo liberação de recursos é executada antes de terminar. Considera-se que seu uso não é ideal e só deve ser chamado em casos muito específicos onde você entende bem o que está fazendo e precisa exatamente dessa solução de término imediato. Particularmente não acho tão ruim assim se realmente não tem mais nada para realizar, pelo menos em arquiteturas bem feitas que não tem dependência de um encerramento específico. Use-a preferencialmente.

os._exit() (Do módulo os);

Encerra a execução imediatamente sem dar chance de executar mais nada, nem mesmo a liberação de recursos.

exit()

O mesmo que a sys.exit(), mas considera-se que não deve ser usado. Não sei bem o motivo, mas acredito que funções que não pertencem a módulos se tornam ambíguas. Use em códigos muitos simples ou no REPL quando importar um módulo pode ser pior. Esse é o problema da linguagem que começa para ser de script e depois muda para ser mais que isso.

quit()

Apenas um apelido para a função anterior. Clara violação do "só ter uma forma de realizar algo".
Não existe nada kernel aí, apenas que a os.exit() é uma chamada de encerramento que provavelmente pede ao OS para encerrar sem mais cerimônia. Não há vinculação à rotina alguma. Isso parece ser um entendimento errado. É uma função como outra qualquer que você chama em algum ponto do código e ela executa algo, no caso esse algo é o encerramento da aplicação.
Coloquei no GitHub para referência futura.
Comment: Obs.: as funções `exit()` e `quit()` são definidas no módulo `site`, que é importado ao contexto automaticamente pelo interpretador, exceto se utilizado a flag `-S` ao executar o código. Com a flag, as funções não estarão definidas, por isso não é muito indicado depender delas.
Comment: ótima resposta, obrigado!  No meu caso por exemplo, o ideal então é utilizar o (sys.exit()),  pois pretendo utilizar em situações em que não é necessário executar mais nada posteriormente. Realmente muitas opções acaba confundindo rs
Answer: Na verdade, só existem 3 jeitos de terminar a aplicação:

Normalmente, ou seja, o código rodar até o final do script principal;
Ocorrer uma exceção que não seja tratada com try/except, causando uma mensagem de erro (traceback);
os.exit_().

Os outros métodos que você passou não terminam o programa definitivamente - eles somente retornam de funções (return), saem de loops (break) ou sobem uma exceção SystemExit (demais métodos). O programa só vai terminar se isso fizer com que o código caia em uma das 3 situações citadas acima.
A exceção SystemExit faz o mesmo que qualquer outra exceção: As funcões e escopos são terminados e o fluxo de código vai voltando na pilha de chamadas até que a exceção seja tratada com o try/except ou volte para o escopo principal, onde, se até lá não foi tratada, causará a finalização do programa. A única diferença é que uma mensagem do tipo traceback não é impressa quando a exceção é a SystemExit.


Why does any function get thinner as $x$ is multiplied by a constant?

Question: Example:
$$\cos(x)$$

$$\cos(8x)$$

"Thinner" might not be the correct term. But I just want to know why does changing $x$ to $8x$ make it look like that?
Comment: It's simple, what the first function used to do in an interval from $0$ to $1$ the new function does in the interval from $0$ to $1/8$. In particular if cos rounds once from $-\pi/2$ to $\pi/2$ the new function will do that from $-\pi/16$ to $\pi/16$. So it will round 8 times in the interval to $-\pi/2$ to $\pi/2$. Which makes it look thinner.
Comment: indeed, this is like applying the function after a rescale in the x direction. I.e. consider the function $r: \mathbb{R} \to \mathbb{R},x \mapsto ax$ then your functions are just $f\circ r = f(r(x))$ and so just rescaled the whole grid.
Also, please observe that if the constant is smaller than 1 it actually gets "fatter" and if it is negative it gets mirrored
Comment: @Yanko Why are you answering in a comment?
Comment: @Arthur It's too "non-formal" for me to post it as an answer. I don't mind if someone else turns this into an answer.
Comment: @Yanko There is no requirement here that answers are formal and I see nothing wrong with yours. And while you may not care about the points, getting an actual answer post upvoted and / or accepted will take this question off the unanswered queue and you will have done a little part in tidying up this place. Comments do not help in that regard. Answers do.
Comment: @Arthur I understand, Thanks for posting it for me.
Answer: From the comment by Yanko above:
It's simple, what the first function used to do in an interval from $0$ to $1$ the new function does in the interval from $0$ to $1/8$. In particular if cos rounds once from $−π/2$ to $π/2$ the new function will do that from $−π/16$ to $π/16$. So it will round $8$ times in the interval to $−π/2$ to $π/2$. Which makes it look thinner.
Answer: Taking a stab at a non-mathematical answer (well, minimally mathematical I guess). It makes intuitive sense to me, but I can't quite explain it mathematically.
The first thing to notice is that this is unrelated to using goniometric functions. It applies to any function, even ones as simple as $y = x$. The only difference is that it's less clear at first sight that $y = 8.x$ is a squashed ("thinner") version of $y = x$.
Most people perceive the difference between the two graphs as a rotation instead of a horizontal squashing.
However, if you were to color-code the graph (e.g. red-green-blue-red-... for all integer values of $x$ (rounded down)), you will see that it is in fact squashed and not rotated.

Think of the x axis as measure of physical distance, let's say kilometers. From your starting point ($x=0$), the Eiffel tower is 10 kilometers ahead ($x=10$), and Big Ben is another 20 kilometers further ($x=30$). Try to visually imagine the monuments on the x axis.
<code>                                                                 ^
                       A                                        |o|
                      /-\                                       | |
-------------------------------------------------------------------------------------> (km)
  0 1 2 3 4 5 6 7 8 9 10 . . . . . . . . . 20 . . . . . . . . . 30 . . . . . . . .
</code>
I apologize for the mediocre artwork.
Now I'm going to introduce a new unit, the Flatermeter, which happens to be exactly equal to 10km. What would our graph now look like if the X axis expresses distance in Flatermeters?
From your starting point ($x=0$), the Eiffel tower is 10 kilometers ahead, which is 1 Flatermeter ($x=1$), and Big Ben is another 20 kilometers further, which is another 2 Flatermeters ($x=3$). Which would look like this:
<code>        ^
    A  |o|
   /-\ | |
-------------------------------------------------------------------------------------> (Fm)
  0 1 2 3 4 5 6 7 8 9 10 . . . . . . . . . 20 . . . . . . . . . 30 . . . . . . . .
</code>
Notice how everything bunched up together, and all the distances shrunk by a factor of 10. Also notice that you could replace $Fm$ by $10.km$ as they are equal values.
The original $y = f(km)$ was quite wide. But the $y = f(Fm)$, which is the same as $y = f(10km)$ has bunched everything up much closer (which is what you're calling "thinner" in your question).
When you take a graph (e.g. $y = x$), and then artificially inflate the "step size" (= value of x) by a factor $k$ (e.g. $y = k.x$), then the graph will run through its shape $k$ times faster. Depending on how you visualize the graph, this has one of two (visual) consequences:

The markings on the x axis move further apart (by a factor of $k$) and the graph has the exact same shape, visually speaking.
The markings on the x axis stay the same and the graph itself horizontally shrinks (by a factor of $k$), visually speaking.

Your example deals with the latter scenario.
Comment: Welcome to MSE!
Answer: Multiplying the argument of a trigonometric function by a constant changes its period, which precisely is the distance between two consecutive local maxima or local minima which in either case must be equal.
Consider the general sinusoidal wave $y=A\sin(ax+b)+C$. The period of this wave or trigonometric function is given by $2\pi/a$.
In your case, define $A_1:y=\cos x$ and $A_2:y=\cos 8x$. By merely inspecting the expressions one can observe that these two waves must have a difference of periods (because the coefficients of $x$ is different in both the cases). Period of $A_1$ is $2\pi$, however that of $A_2$ is $\pi/4$. That is why you observe such a change in graphs of these functions.
Answer: The plot of a graph is really just a set of points $S=\{(x,y)\mid y=f(x)\}$. Let's say you turned $x$ into $ax$ for a constant $a$. Then surely, $S$ will not in general remain the same. The new set will instead contain of $(x/a,y)$ for every $(x,y)$ that used to be in $S$, since now, $y=f(a(x/a))=f(x)$ which fufills the definition of a point being on the graph of a function. So the action of "making $f(x)$ become $f(ax)$" takes each point $(x,y)$ to $(x/a,y)$, hence "compressing" the $x$-axis.


Android throw DeadObjectException with LOG: Transaction failed on small parcel; remote process probably died

Question: 07-22 04:38:07.933  1579  3338 E JavaBinder: !!! FAILED BINDER TRANSACTION !!!  (parcel size = 352)
07-22 04:38:07.933  1579  3338 W BroadcastQueue: Can't deliver broadcast to com.android.systemui (pid 2160). Crashing it.
07-22 04:38:07.934  1579  3338 W BroadcastQueue: Failure sending broadcast Intent { act=android.intent.action.TIME_TICK flg=0x50000014 (has extras) }
07-22 04:38:07.934  1579  3338 W BroadcastQueue: android.os.DeadObjectException: Transaction failed on small parcel; remote process probably died
07-22 04:38:07.934  1579  3338 W BroadcastQueue:    at android.os.BinderProxy.transactNative(Native Method)
07-22 04:38:07.934  1579  3338 W BroadcastQueue:    at android.os.BinderProxy.transact(Binder.java:618)
07-22 04:38:07.934  1579  3338 W BroadcastQueue:    at android.app.ApplicationThreadProxy.scheduleRegisteredReceiver(ApplicationThreadNative.java:1211)
07-22 04:38:07.934  1579  3338 W BroadcastQueue:    at com.android.server.am.BroadcastQueue.performReceiveLocked(BroadcastQueue.java:489)
07-22 04:38:07.934  1579  3338 W BroadcastQueue:    at com.android.server.am.BroadcastQueue.deliverToRegisteredReceiverLocked(BroadcastQueue.java:702)
07-22 04:38:07.934  1579  3338 W BroadcastQueue:    at com.android.server.am.BroadcastQueue.processNextBroadcast(BroadcastQueue.java:1002)
07-22 04:38:07.934  1579  3338 W BroadcastQueue:    at com.android.server.am.BroadcastQueue.processNextBroadcast(BroadcastQueue.java:799)
07-22 04:38:07.934  1579  3338 W BroadcastQueue:    at com.android.server.am.ActivityManagerService.finishReceiver(ActivityManagerService.java:19153)
07-22 04:38:07.934  1579  3338 W BroadcastQueue:    at android.app.ActivityManagerNative.onTransact(ActivityManagerNative.java:528)
07-22 04:38:07.934  1579  3338 W BroadcastQueue:    at com.android.server.am.ActivityManagerService.onTransact(ActivityManagerService.java:2909)
07-22 04:38:07.934  1579  3338 W BroadcastQueue:    at android.os.Binder.execTransact(Binder.java:565)
07-22 04:38:07.937  2160  2160 D AndroidRuntime: Shutting down VM
07-22 04:38:07.953  2160  2625 E JavaBinder: !!! FAILED BINDER TRANSACTION !!!  (parcel size = 136)
--------- beginning of crash
07-22 04:38:07.972  2160  2160 E AndroidRuntime: FATAL EXCEPTION: main
07-22 04:38:07.972  2160  2160 E AndroidRuntime: Process: com.android.systemui, PID: 2160
07-22 04:38:07.972  2160  2160 E AndroidRuntime: android.app.RemoteServiceException: can't deliver broadcast
07-22 04:38:07.972  2160  2160 E AndroidRuntime:    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1690)
07-22 04:38:07.972  2160  2160 E AndroidRuntime:    at android.os.Handler.dispatchMessage(Handler.java:102)
07-22 04:38:07.972  2160  2160 E AndroidRuntime:    at android.os.Looper.loop(Looper.java:160)
07-22 04:38:07.972  2160  2160 E AndroidRuntime:    at android.app.ActivityThread.main(ActivityThread.java:6252)
07-22 04:38:07.972  2160  2160 E AndroidRuntime:    at java.lang.reflect.Method.invoke(Native Method)
07-22 04:38:07.972  2160  2160 E AndroidRuntime:    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:898)
07-22 04:38:07.972  2160  2160 E AndroidRuntime:    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:788)

The error happened in the BroadcastQueue class, when it called scheduleRegisteredReceiver through Binder, the DeadObjectException throw. Like the LOG said: Transaction failed on small parcel; remote process probably died, but why RuntimeException throw in the com.android.systemui process if it already dead?
Answer: I finally found the root cause, it happened in the binder kernel.
For now, I discovered two reasons for what can cause a DeadObjectException to be thrown in BroadcastQueue and therafter a RemoteServiceException in ActivityThread in the app:

There are no more asynchronous space to execute the binder transaction when AMS sends a one-way binder call to ActivityThread in order to trigger BroadcastReceiver.onReceive.

Related code shown below:
kernel/msm-4.4/drivers/android/binder_alloc.c
290     if (is_async &&
291            alloc->free_async_space < size + sizeof(struct binder_buffer)) {
292           binder_alloc_debug(BINDER_DEBUG_BUFFER_ALLOC,
293                         "%d: binder_alloc_buf size %zd failed, no async space left\n",
294                           alloc->pid, size);
295            eret = ERR_PTR(-ENOSPC);
296              goto error_unlock;
297    }

Therefore, this will not "end up destabilizing the system". It will only influences the application itself.

The user application had been force closed because BroadcastQueue send scheduleCrash binder call to ActivityThread. The root cause of this problem is that there are no binder buffer in the application side because some binder threads occupy most of it.

The bug can be triggered with the following steps:

Process1 sends large data (e.g. 980kB) to Process2, the Process2 need sleep for 30 seconds, and the large binder buffer will not be released.
Process1 sends a broadcast to Process2, consisting of e.g. 50kB data. That would go beyond the make the buffer capacity of 1016kB, since 980kB + 50kB is larger than the buffer capacity.
BroadcastQueue will throw a DeadObjectException and then pass scheduleCrash to ActivityThread in the application side.

Here is the code:
kernel/msm-4.4/drivers/android/binder_alloc.c
 315     if (best_fit == NULL) {
...
341         pr_err("%d: binder_alloc_buf size %zd failed, no address space\n",
342                   alloc->pid, size);
343         pr_err("allocated: %zd (num: %zd largest: %zd), free: %zd (num: %zd largest: %zd)\n",
344                       total_alloc_size, allocated_buffers, largest_alloc_size,
345                  total_free_size, free_buffers, largest_free_size);
346            eret = ERR_PTR(-ENOSPC);
347              goto error_unlock;
348    }

In conclusion, DeadObjectException can be thrown even if the application process haven't died.
The root cause is most likely because of full binder buffer for the application and does not influence the system.
So I think it is not necessary to make the application crash after catching a DeadObjectException in BroadcastQueue.
Comment: Hi I'm running into the same issues, do you have a fix for it?
Comment: @chopchop yep, as my answer shown, the buffer is temporary full, and make your app cannot use Binder IPC, i.e. whenever you call a Binder call method, it will throw DeadObjectException to you. To solve your question, you can transmit less data with Binder, so the Binder buffer will not full easily and this can avoid this problem too.
Answer: Basically everything Rick Ai's answer to their own question is correct but here is a a real world example:
If your app creates and registers a whole bunch of BroadcastReceiver instances all listening to the same action--perhaps due to a leak or bug in your app--then the ActivityManagerService in the system process will invoke android.app.IApplicationThread method scheduleRegisteredReceiver for each registered instance. Notice that the binder transaction for this particular method is oneway. Since it is oneway each invocation will return immediately and the calls to the binder driver will occur very rapidly before each transaction is complete thus effectively running them all in parallel.
Lets say you have 100 receivers in your app and the broadcast being received contains 20 KiB of data. Now you've got 2 MiB trying to pass through the binder driver and it will fail due to the limit of 1 MiB.
In kernel logs you will see:
binder: 1282:1298 transaction failed 29201/-28, size 28052-8 line 3072

So beware leaking BroadcastReceiver and beware oneway binder transactions. Note that apparently the AIDL file may not declare a method oneway but it may end up that way if the AIDL compiler decides it is possible.


CSV file to a web page in Joomla 2.5

Question: I have a 20Mb <code>.csv</code> file which I want to turn into a database, which is browsable and searchable through a public web page.
What would be the easiest way to do this?
I would prefer to use as much ready made components as possible and as little coding as possible...
How to do it using Joomla 2.5?
Answer: I'd import the data using phpMyAdmin or similar and then use ChronoForms to build a search form and display the results.
References:
https://www.interspire.com/support/kb/questions/851/Overcoming+file+size+limits+when+uploading+SQL+files+to+phpMyAdmin
Comment: Instead Chronoforms i ended up using JooDatabase which i a lot easier to configure to a usable state
Comment: phpMyAdmin manages to import only about 10000 lines of 300000 on the csv until it throws an error.

CSV file to a web page in Joomla 2.5


Help me understand how to apply a beta-binomial model in order to estimate a parameter when there are several Bernoulli trials?

Question: So, I have been presented with this question:
A sample of 100 people were asked how many days they drove their car during the last week (inc. the weekend). The resulting frequency of response is shown below:
Days, frequency
0, 1
1, 5
2, 3
3, 15
4, 20
5, 25
6, 31
7, 0
I need to use a beta-binomial model in order to estimate the average number of 'car driven' days a week for a uniform prior. There are a total of 7 Bernoulli trials, each with success probability p.
I'm incredibly confused at what the outcome will be. I know that for a uniform prior that alpha = 1, and beta = 1, but I don't know how to apply this all to get the average?
Thank you.
Answer: If you have the prior distribution $\mathsf{Beta}(\alpha_0, \beta_0)$ for Success
probability $\theta$ and binomial likelihood $\theta^x(1-\theta)^{n-x},$ corresponding to $x$ Successes in $n$ Bernoulli trials, then by Bayes' Theorem you have the posterior
distribution is $\mathsf{Beta}(\alpha_n = \alpha_0 + x,\; \beta_n = \beta_0 + n - x),$ which has posterior mean $E(\theta) = \frac{\alpha_n}{\alpha_n+\beta_n}.$
According to Bayes' Theorem, POSTERIOR = PRIOR $\times$ LIKELIHOOD:
$$h(\theta|x) = f(\theta) \times g(x|\theta)\propto\theta^{\alpha_n+1}(1-\theta)^{\beta_n+1}$$
$$\propto
\theta^{\alpha_0+1}(1-\theta)^{\beta_0+1} \times
\theta^x(1-\theta)^{n-x},$$
where $\propto$ (read as "proportional to") acknowledges that we have omitted
normalization constants to write 'kernels' of densities instead of densities.
We recognize $\theta^{\alpha_n+1}(1-\theta)^{\beta_n+1}$ as the kernel of
$\mathsf{Beta}(\alpha_n,\beta_n).$
If I understand your data correctly, you observed $x = 447$ days of use out of $n = 700.$ Also, it seems you are to assume that car use is equally likely on all days, that days of use are independent within any one
subject, and that subjects use cars independently of one another. These assumptions are required if we are to have 700 independent trials, each with the same Success probability $\theta.$
d = 0:7; f=c(1,5,3,15,20,25,31,0);  sum(d*f)
[1] 447

So if you begin with a flat prior $\mathsf{Unif}(0,1)\equiv\mathsf{Beta}(1,1),$
then your posterior distribution is $\mathsf{Beta}(448,554).$ Your posterior
mean is $E(\theta) = \frac{448}{1002}$ and a 95% Bayesian posterior probability
interval ('credible' interval) for $\theta$ is $(0.416, 0.478).$
qbeta(c(.025, .975), 448, 554)
[1] 0.4164427 0.4779689

Note: For various theoretical and technical reasons, some Bayesian statisticians
prefer to use the Jeffries prior $\mathsf{Beta}(.5,.5)$ as a non-informative prior
distribution, instead of the uniform prior $\mathsf{Beta}(1,1).$
Comment: there are only 7 trials here, each with their own success probability. i.e. trial 1 has a success probability of 5/100, trial 2 has a success probability of 3/100. From what you have done, I think I can see that we posterior distribution after applying the beta-binomial model with flat prior, and this posterior distribution is what we use to estimate the mean? It's extra confusing with all the independent trials too!
Comment: I think either your Question is what you want answered or your Comment is describing something entirely different. Please try to be clear about the data and the assumptions, then maybe someone can give you an answer.
Comment: what I'm telling you is what I've been told by my teacher. Where did you get x = 447?
Comment: `sum(d*f)` gives 447, as shown.
Comment: yes thank you, I have just worked through what you did after a good night's sleep and it's very helpful!! The posterior mean E(theta) is this simply the expected proportion of successes value? I'm just confused as to how this translates into the "average number of 'car driven' days"?
Comment: On any one day a person has probability $\theta$ of driving his/her car, and $E(\theta).$ is estimated. You have 100 people and 7 days so $n=700$ trials. And $x=447$ Successes. So in a non-Bayesian problem you'd have estimate $\hat\theta = 447/1000 = 0.447.$ In a Bayesian setting with non-informative prior, you'll get about the same point estimate. (Of course if you have prior data or good 'hunches' to express in Bayesian prior, your estimate would use _both_ prior dist'n and binomial likelihood based on 447 Successes in 1000 trials.)


Behaviour of the marginal in the limit for an infinite sequence of hierarchical priors

Question: Consider the following model:
$$y \sim \text{Exponential}(\lambda_0) \\
\lambda_i | \lambda_{i+1} \sim \text{Exponential}(\lambda_i+1) \\
\text{for } i=1,2,\dots,d\\
\lambda_{d+1} = k
$$
With an observed $y=c$.
How does the marginal likelihood given a fixed number $d$ of priors $P_d(y)$ behave as a function of $d$? How about $\lim_{d\to\infty} P_d(y)$
Can a general statement be made for arbitrary distributions?
Comment: https://projecteuclid.org/euclid.bj/1080004760 investigates these sorts of questions
Comment: @Cyan oh wow there's actually a paper on this exact question. I read the abstract, this is definitely going on my steadily growing reading list! Thanks so much for sharing!
Answer: The parameter of the Exponential distribution is an inverse scale parameter: $X\sim \mathcal E(\lambda)$ can be represented as$$X=\epsilon/\lambda\qquad\epsilon\sim\mathcal E(1)$$Therefore if
$$X \sim \mathcal E(\lambda_0) \\
\lambda_i | \lambda_{i+1} \sim \mathcal E(\lambda_{i+1}) \quad
i=0,1,\dots,d\\
\lambda_{d+1} = 1$$
we can write
\begin{align}X &= \epsilon_0 / \lambda_0 \qquad &\epsilon_0\sim\mathcal E(1)\\
&= \lambda_1 \epsilon_0 / \epsilon_1 \qquad &\epsilon_1\sim\mathcal E(1)\\
&= \epsilon_2 \epsilon_0 / \epsilon_1 \lambda_2 \qquad &\epsilon_2\sim\mathcal E(1)\\
&\quad \vdots\\
&= \frac{\epsilon_{2\lfloor d/2 \rfloor}\cdots \epsilon_0}{\epsilon_{2\lfloor (d-1)/2 \rfloor+1}\cdots \epsilon_1}\qquad &\epsilon_d\sim\mathcal E(1)
\end{align}
and hence
\begin{align*}X&=\frac{\exp\left\{\sum_{i=0}^{\lfloor d/2 \rfloor}\log\epsilon_{2i}\right\}}{\exp\left\{\sum_{i=0}^{\lfloor (d-1)/2 \rfloor}\log\epsilon_{2i+1}\right\}}\qquad \epsilon_i\sim\mathcal E(1)\\
&=\frac{\exp\left\{\sum_{i=0}^{\lfloor d/2 \rfloor}\log\{-\log\upsilon_{2i}\}\right\}}{\exp\left\{\sum_{i=0}^{\lfloor (d-1)/2 \rfloor}\log\{-\log\upsilon_{2i+1}\}\right\}}
\qquad \upsilon_i\sim\mathcal U(0,1)\end{align*}
appears as the ratio of two independent random variables both converging a.s. to zero with $d$, hence having no limiting distribution. (This property generalises to other scale distributions, obviously, provided $\mathbb E[\sqrt{\epsilon_i}]<1$.)
Considering the general case $\lambda_d\sim\mathcal E(k)$ simply means alternatively multiplying and dividing by $k$ the above, hence preventing any form of convergence.
Note [update]: Corey Yanovski pointed out to me that this problem is investigated in "Infinite hierarchies and prior distributions" by Gareth O. Roberts and Jeffrey S. Rosenthal (Bernoulli, 2001). The introduction reads as follows:

Suppose   that   we   had   independent   data   from   an $Exp(\theta_0)$   distribution.   In   a   Bayesian framework,   we  suppose  that   a  priori $\theta_0\sim Exp(\theta_1)$,  and  that  with  uncertainty  on  the hyperparameter $\theta_1$,  we  might  also  give  it  a  prior, $\theta_1\sim Exp(\theta_2)$  say.  In  fact  at  each  level  of  the hierarchy we can hedge our bets by imposing a further level of prior uncertainty. Suppose we impose $N$ levels  of  the  hierarchy  by  fixing  the  hyperparameter $\theta_N$ and  sequentially  setting
$$\theta_i\sim Exp(\theta_{i+1})\qquad i=N-1,N-2,..., 1, 0$$ In terms of the data, the only thing that matters is the marginal prior of $\theta_0$,  obtained  (if  it  were  possible)  by  integrating  out  the  hierarchical  parameters.In  such  a  situation,  it  is  natural  to  consider  the  prior  distribution  of $\theta$ as $N\uparrow\infty$. In this  case  and  many others,  no  proper  distributional  limit  exists,  but  the  limit  can  sometimes still  be  described  in  terms  of  an  improper  prior  distribution.
Comment: are there any general statements or results relating to larger and larger hierarchical models?
thanks for the answer, that was a clever way to go about it...


$P$ non-constant polynomial, then there is for each $a>0$ there is $b>0$

Question: $P$ non-constant polynomial, then there is for each $a>0$ there is $b>0$ such that
$$(z:\left |  z\right |>b)\subseteq (P(z):\left | z \right |>a)$$
I'm not sure where to start or how to prove this statement, any help would be great.
Edit:
I first wrote $b<0$, which is clearly false. And as corrected, $b>0$ is right one.
Comment: Do you really mean $b<0$?
Comment: My bad. It is $b>0$
Answer: The $z$'s in your two sets play different roles, so it might be better to write this as
$$ \{w: |w| > b\} \subseteq \{P(z): |z| > a \} $$
$\{P(z): |z| \le a\}$ is a compact set, so it is bounded.  Since the Fundamental Theorem of Calculus says $P$ is surjective, all you need to do is take $b$ so $\{P(z): |z| \le a\} \subseteq \{w: |w| \le b\}$, and then $ \{w: |w| > b\} \subseteq \{P(z): |z| > a \}$.
Comment: You mean Open mapping theorem or FTC?
Comment: I said FTC and I meant it.


BasicAF : Project: Tip Calculator

Question: these are the parameters of the project:
#If the bill was $150.00, split between 5 people, with 12% tip.
#Each person should pay (150.00 / 5) * 1.12 = 33.6
#Format the result to 2 decimal places = 33.60
***pleae keep in mind you may have a soulution that uses some advance code I many not be familiar with.
bill = input("What is the total bill?")

# bill is 150.00

tip = input("What percentage tip would you like to give? 10, 12, or 15?")

# tip will be 12%

max_tip = float(tip) / 100

# split between 5 people
people = input("How many people to split the bill?")

max_split = int(bill) / int(people)
max_cost = int(max_split) * float(max_tip)

print(f"Each person should pay:{max_cost}")

this is my current output:
What is the total bill?150
What percentage tip would you like to give? 10, 12, or 15?12
How many people to split the bill?5
Each person should pay:3.5999999999999996
I know from earlier lessons you can round(number, 2) and that should signify to python to round two place pass the decimal.
float(max_tip, 2) it was the only place that made sense to me. but then my out put was:
line 77, in
max_cost = int(max_split) * float(max_tip, 2)
TypeError: float expected at most 1 argument, got 2
Process finished with exit code 1
thank you for any tips and advice. I appreciate it.
I tired to figure this out on my own using just what I have learned so far. But I cannot figure out how to round up two places pass the decimal.
Also, how do I turn 0.12% into 1.12?
Answer: I'm not sure entirely what you are wanting from this question but here are some fixes to your code. First you wanted to know how to round, you would use the round() method with it's first parameter the number and the second parameter being how many places you would like to round to. You also asked about changing .12% into 1.12 all you would do it (tip / 100) + 1. I have added these changes to the code below:
bill = float(input("What is the total bill?"))
tip = int(input("What percentage tip would you like to give? 10, 12, or 15?"))
people = int(input("How many people to split the bill?"))

decimal_multiplier = tip / 100 + 1
max_split = bill / people
max_cost = round((max_split * decimal_multiplier), 2)

print(f"Each person should pay: {max_cost}")

Comment: so when I run your code I get. 33.6, however, I need it to say 33.60
Comment: You would need to use the `format` function so after `max_cost` variable you would add another line that says:
`
formatted_cost = "{:.2f}".format(maxcost)
`
Then change the print statement to print `formatted_cost`
Comment: that was perfect! thank you so much I've been trying for a few days now to get this correct. thank you all for the help tip and advise.

BasicAF : Project: Tip Calculator