passing data from array of hash in ruby into javascript full calendar

Question: I am trying pass a value from data at index from ruby :
in user.rb file :
list = [{:date=>"07 Mar", :price => "1000,00", :fruit=>"Orange"},
 {:date=>"07 Mar", :price => "2000,00", :fruit=>"Apple"}]

to Js in full_calendar.js :
dayRender:function(date, cell){
  var array = <%= j @list.to_json %>;
  $(cell).html('' + array + '');
  },

in full calendar and I can't make it work. I have tried a lot of different options so far and can't find any solution to access at list one of the value at index 0, 1, or 2...
Any ideas?
Comment: your ruby code in wich file are? (also you have `list` not `@list`)
Comment: If your ruby code is outputting JSON, you need to parse it before you can access the properties. (`JSON.parse`)
Comment: Where is come from the variable(`@list`) and in which js file you're using it?
Comment: I have edited my question with answers to your questions. I have tried JSON.parse too
Comment: It's still unclear for me, where is come from that js file, is it in `app/assets/javascripts` folder? or `app/views/` ? What is `user.rb` ? is it a model file?
Comment: @Зелёный yes js is located inside `app/assets/javascripts folder` and `user.rb` is a model file
Comment: I suggest you to read some basic, how is javascript and Rails works. http://railscasts.com/episodes/324-passing-data-to-javascript?view=asciicast for example.
Answer: You need to split up the server and client part and test each.
First Ruby: You will need something like this, test it first in a separate Ruby script.
require 'json'
@list = [{:date=>"07 Mar", :price => "1000,00", :fruit=>"Orange"}, {:date=>"07 Mar", :price => "2000,00", :fruit=>"Apple"}]
@list.to_json
# [{"date":"07 Mar","price":"1000,00","fruit":"Orange"},{"date":"07 Mar","price":"2000,00","fruit":"Apple"}]

Then the client part: put yout Ruby code in a place where you can see the result in javascript. Make sure you get json required somewhere in the line.
dayRender:function(date, cell){
  var array = <%=
    require 'json'
    @list = [{:date=>"07 Mar", :price => "1000,00", :fruit=>"Orange"}, {:date=>"07 Mar", :price => "2000,00", :fruit=>"Apple"}]
    @list.to_json
  %>;
  console.log(array);
  $(cell).html('' + array + '');
  },

If that works, it's a matter of testing if your @list variable is known in the erb file. If not concentrate on passing this variable, is your erb file in the right path ? Is your route correct ? etc.
dayRender:function(date, cell){
  var array = <%=@list.to_json %>;
  $(cell).html('' + array + '');
  },

As an extra: make you some simple test script where you can extract your problem, test it without having to bother about other influences and above all can publish here in case you can't figure it out.
You ask this for rails but I use Sinatra most of the time, so you will have to do the same for Rails. In case you don't know Sinatra, put all of this in app.rb and run.
require 'sinatra' # gem install sinatra
require "sinatra/reloader" #so that you don't have restart the server after changes
require 'json'

get '/' do
  @list = [{:date=>"07 Mar", :price => "1000,00", :fruit=>"Orange"}, {:date=>"07 Mar", :price => "2000,00", :fruit=>"Apple"}]
  erb :index
end
__END__
@@ index

And yes, I get your json in the console..
Comment: thanks for your answer @peter it got me started. The following started me on the right path, I know have to iterate through the objects to catch by date each value I need to load in the corresponding cells.    `dayRender:function(date, cell){
      var json = <%=
        require 'json'
        (@list.to_json.html_safe
        %>;
      $(cell).html('' + (JSON.stringify(json, null, 4)) + '');
    },`


Como conectar com um banco de dados já existente em Rails?

Question: Gostaria de saber se há como me conectar ao PostgreSQL, de forma que eu só leia os dados das tabelas que já estão criadas.
Estou desenvolvendo uma API, que irá fazer a leitura num determinado banco de dados, e retornar um XML, por exemplo.
Answer: Sim, o Rails foi feito para suportar bases de dados legadas também, só que você vai ter que fazer configurações adicionais.
Primeiro, configure o arquivo config/database.yml com as configurações do seu banco.
Ao gerar models e scaffold, use a opção --no-migration para evitar a criação das tabelas (que já existem):
rails g model post title text:text --no-migration
rails g scaffold post title text:text --no-migration

Depois configure manualmente o nome da tabela e chave primária:
class Product < ActiveRecord::Base
  self.table_name = "PRODUCT"
  self.primary_key = "product_id"
end

Se for usar TDD, configure também o arquivo de fixtures no TestCase do model:
class FunnyJoke < ActiveSupport::TestCase
  set_fixture_class funny_jokes: Joke
  fixtures :funny_jokes
  ...
end

Lembre-se, o guia do Rails é seu amigo: http://guides.rubyonrails.org/
Fonte: http://guides.rubyonrails.org/active_record_basics.html#overriding-the-naming-conventions
Comment: Cara, muito obrigado pela sua ajuda. Foi de grande utilidade!


How do I open and type in another Tab Using only Javascript

Question: I need to open a URL, then type there, and I was wondering if you could do that in javaScript, how, and if not, are there any other languages I can do that in. Remember: No HTML Or CSS and I use Opera.
     Thanks, - Beginning Coder
Elaborating, I am trying to open my email or Gmail ( I can do that part) and then type in who it is to, etc. Please Help. + Thanks for the feedback and tips though
Comment: You can't directly write from one website to another in a new tab with Javascript. Perhaps you should explain what it is that you're trying to create? There are plenty of other solutions that _might_ do the job. Perhaps through some GET varialbles for example. Or maybe a browser addon like Greasemonkey that detects the new tab and injects the JS for you.
Comment: You should read about browser security. https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
Comment: Welcome to SO! I went ahead and answered your question b/c you're new, but please take some time to read our site standards (looks like you've attracted some downvotes). This is something you could easily have searched on your favorite search engine.
Answer: The first part of your question (opening a new tab) is a duplicate of this question:
StackOverflow
I'm not entirely sure what you mean by "write," but I answered what I think you're asking.
As for writing into a new window/tab with JS, you can do that 2 ways:

Open a url on your website in a new window/tab
Make a new window and use document.write()

Tutorial: W3 Schools
Now that I know what you want to do specifically, you can do this:
window.open("https://mail.google.com/mail/u/0/#inbox?compose=new");
to open gmail in a new window/tab. You cannot write into any elements in that window (the subject line, for example) with JS because the same-origin policy does not allow it (you do not own google.com). Thus, you cannot accomplish what you want to do unless you are writing into a new window on your own website or file directory.
This StackOverflow post tells you how to set up a mailto that can auto set the subject and body. It's not exactly what you want, but maybe you could adapt it.
Comment: Thanks, that really helped, but do you know any other languages I might be able to accomplish this in ?
Comment: You can use Ajax to `POST` data to gmail that will send your email to the intended recipient. https://www.xul.fr/en-xml-ajax.html But no, you cannot manipulate someone else's website with a script from another origin in any language. It is a web standard.
Comment: The gmail API may be a better option than Ajax, but it'll be difficult! https://developers.google.com/gmail/api/
Comment: Thanks again, but can I do that with a desktop application like e-mail?
Comment: I didn't think your question had anything to do with a desktop application. Gmail (and all other email services) runs on the web, a desktop application is a simple client. JavaScript is a language that runs in the web browser, it has no control over your desktop app.
Comment: Thank you so much, final question : Is there a language I could send an email to someone ?
Comment: I've already answered that in regards to using an existing mail client, such as Gmail. If you would like to set up your own server and email people with a PHP script, you can learn more about doing so here: https://stackoverflow.com/questions/5335273/how-to-send-an-email-using-php. good luck! :)
Answer: To open a new tab through JavaScript you can use window.open("link").
And to type in you could make a form in HTML and get the value from that form: document.getElementById("form id from html").value and store it in a variable so you can use it as link in windows.open;
Comment: I'm a sort of computer noob, but what is a form id from html ?
Comment: https://www.w3schools.com/tags/att_global_id.asp
Comment: When you make a form in HTML (https://www.w3schools.com/html/html_forms.asp) you can give it an Id(https://www.w3schools.com/Html/html_id.asp), and then in JavaScript where I wrote 'document.getElementById("form id from html").value', when I said "form id from html" I meant the Id that you gave to that form.


C# List<> - Inserir na base de dados

Question: Tenho uma app que pega em informação de uma TextBox, insere numa lista List<> e depois mostra numa CheckBoxList.
Exemplo:
List<string> quantidade = new List<string>();
for (int i = 0; i < CheckBoxListLinhas.Items.Count; i++)
{
   quantidade.Add(TextBoxQuantidade.Text.ToString());
}
List<string> artigo = new List<string>();
for (int i = 0; i < CheckBoxListLinhas.Items.Count; i++)
{
   artigo.Add(TextBoxArtigo.Text.ToString());
}
List<string> valor = new List<string>();
for (int i = 0; i < CheckBoxListLinhas.Items.Count; i++)
{
   valor.Add(TextBoxValor.Text.ToString());
}
/*List<string> artigo = new List<string>();
  for (int i = 0; i < CheckBoxListLinhas.Items.Count; i++)
  {
    artigo.Add(TextBoxArtigo.Text.ToString());
  }*/

CheckBoxListLinhas.Items.Add(new ListItem("Quantidade: " + TextBoxQuantidade.Text + " Artigo: " + TextBoxArtigo.Text + " Valor: " + TextBoxValor.Text) + " Anexo: " + FileUpload1.FileName.ToString());

E eu quero adicionar à base de dados todas as linhas inseridas no List<> e ja tenho este exemplo:
SqlCommand sqlInsertList = new SqlCommand("Insert into linhas (quantidade,descricao,valor) VALUES(@quantidade,@descricao,@valor)", sqlConn);
sqlInsertList.Parameters.AddWithValue("@quantidade", );
sqlInsertList.Parameters.AddWithValue("@descricao", TextBoxArtigo.Text);
sqlInsertList.Parameters.AddWithValue("@valor", float.Parse(TextBoxValor.Text, CultureInfo.InvariantCulture.NumberFormat));

sqlConn.Open();
sqlTran = sqlConn.BeginTransaction();
sqlInsert.Transaction = sqlTran;
sqlInsert.ExecuteNonQuery();
sqlTran.Commit();

Qual é a maneira mais fácil de fazer isso e adaptar o SQLInsert?
Comment: Você está tendo algum problema? Parece estar ok, falta só completar um linha.
Comment: Aconselho que em vez de usar três listas, crie somente uma lista tipada com a classe Linha. Será mais fácil percorrer somente um enumerável do que trabalhar com três deles sincronizados.
Answer: Pelo que vejo, o problema aqui é que está sendo criado três listas para se operar, em vez de usar somente uma, facilitando abstração da ideia de Linha. Primeiro você teria que ter uma classe que represente esse tipo de dado.
public class Linha
{
    public int Quantidade { get; set; }
    public string Descricao { get; set; }
    public float Valor { get; set }
}

Usando uma classe concreta você não precisa mais efetuar três loopings, um para cada propriedade da entidade Linha.
IList<Linha> linhas = new List<Linha>();

for (int i = 0; i < CheckBoxListLinhas.Items.Count; i++)
{
    linhas.Add(new Linha
    {
        Quantidade = int.Parse(TextBoxQuantidade.Text.ToString(), CultureInfo.InvariantCulture.NumberFormat),
        Descricao = TextBoxArtigo.Text.ToString(),
        Valor = float.Parse(TextBoxValor.Text, CultureInfo.InvariantCulture.NumberFormat)
    });
}

Então para inserir todas as linhas o processo fica muito mais simples, com somente um foreach.
foreach (Linha linha in linhas)
    this.InserirLinha(linha);
}

Considere que InserirLinha é o seu método atual que serve para tratar somente uma unidade. Modifique o seu código nesse método para que ele trabalhe da seguinte maneira:
SqlCommand sqlInsert = new SqlCommand("Insert into linhas (quantidade,descricao,valor) VALUES(@quantidade,@descricao,@valor)", sqlConn);

sqlInsert.Parameters.AddWithValue("@quantidade", linha.Quantidade);
sqlInsert.Parameters.AddWithValue("@descricao", linha.Descricao);
sqlInsert.Parameters.AddWithValue("@valor", linha.Valor);

sqlConn.Open();
sqlTran = sqlConn.BeginTransaction();
sqlInsert.Transaction = sqlTran;
sqlInsert.ExecuteNonQuery();
sqlTran.Commit();

OBSERVAÇÕES:

Apesar de estar sendo feito um looping, está sempre acessando os mesmos três campos. Não sei se era esse o comportamento que você realmente queria. Se existe várias linhas ou você quer duplicar essa informação.
Eu usei o tipo float para a propriedade Valor, mas se for para tratar de um valor monetário o tipo mais adequado para essas operações é o decimal.
Não sei como está o seu método por completo na inserção de uma Linha, mas no exemplo que foi passado o sqlConn não está sendo fechado. Sempre feche as conexões com operações relacionadas a banco (IO, stream, etc) quando você finalizar a sua ação. Se não quiser usar o método Close, geralmente essas classes implementam a interface IDisposable, permitindo que dessa maneira você a Instrução Using, que já faz esse trabalho por você.
Comment: Peço desculpa pela demora na resposta, mas fiquei com uma pequena dúvida. Esse primeiro ciclo for eu insiro dentro de um método?
Comment: Sim. Nesses casos é sempre bom separar os comportamentos em uma ação coletiva e uma ação única. Se a ação que você vai efetuar pode ser feita para somente uma unidade, separe isso em um método e crie um método que seja um coletivo para sair chamando o método de única unidade.

C# List<> - Inserir na base de dados


Rank of the Homomorphic image of a finitely generated abelian group

Question: I have been trying to find a relatively simple proof of the following result:

let $f$ be a group homomorphism such that $f: G \to K$ where $G$ and $K$ are groups. Then, $rank(f(G))\leq rank(G)$.

Could somebody please provide me with one?
Thank you.
Comment: How are you defining rank? If it's the minimum number of generators of $G$, then I can give a fairly straightforward proof.
Comment: But a finitely generated abelian group is not necessarily free: it has a free part and a torsion part.
Comment: Can you use tensor products?
Comment: @Bernard, no. Jgon, as the # of elements in a basis for a finitely generated abelian group.
Answer: I know two definitions of rank, one is the one for all groups, $\newcommand{\rank}{\operatorname{rank}}\rank(G)=\min \{|X| : X\subset G\text{ generates $G$.}\}$. The other is for abelian groups, and is defined by $\rank(G)=\max\{|X| : \not\exists_{a_i\in\mathbb{Z},x_i\in X} \sum_{i=0}^r a_i x_i =0\text{ unless all the $a_i=0$}\}$.
In the first case, if $X$ generates $G$, then $f(X)$ generates $f(G)$ since if $f(g)\in f(G)$, $g=\prod_{i=1}^n x_i$ for $x_i\in X$ since $X$ generates $G$. Thus $f(g)=\prod_{i=1}^n f(x_i)$, and $f(X)$ generates $f(G)$. $|f(X)|\le |X|$, so $\rank(f(G))\le \rank(G)$.
Otherwise, if $X$ is a set of linearly independent elements in $f(G)$, then for each element of $X$, choose a preimage in $G$, call this set $Y$.
Then if for some $a_i,y_i$ we had $$\sum_{i=0}^r a_iy_i=0,$$ we can take $f$ of both sides to get $$ f\left(\sum_{i=0}^r a_i y_i\right)=
\sum_{i=0}^ra_if(y_i) = f(0)=0.$$ However, this is a linear dependence among the elements of $X$, so all the $a_i$ must be 0. Thus $Y$ is linearly independent, with the same cardinality as $X$, so $\rank(G)\ge \rank(f(G))$.
Note that we need AC to choose the set $Y$ here, and possibly to show $|f(X)|\le |X|$ although I'm not sure about that part.


If $f:\mathbb{R}\to \mathbb{R}$ is a continuous function with $|f|$ uniformly continuous, is $f$ necessarily uniformly continuous?

Question: I don't think so. But, I can't find the counterexample.
The singularity shall be at infinity because $f$ is uniformly continuous over any bounded and closed intervals $[a,b]$. Also, $f$ must oscillate at infinity. Otherwise, the uniform continuity of $f$ is identical to $|f|$.
Comment: I can't imagine a counter-example. +1 for the question
Answer: Yes. Let $\epsilon>0$ be arbitrary. For some $\delta>0$ uniform continuity tells us that $$|x-y|<\delta\implies \left|\left(|f(x)|-|f(y)|\right)\right|<\frac{\epsilon}{2}$$ Take $x<y$ arbitrary with $|x-y|<\delta$. If $f(x)$ and $f(y)$ have the same sign, $$|f(x)-f(y)|=\left|\left(|f(x)|-|f(y)|\right)\right|<\frac{\epsilon}{2}<\epsilon$$ and we are done. Otherwise, by continuity of $f$, for some $z\in (x,y)$, $f(z)=0$. Then since $|x-z|<\delta$ and $|z-y|<\delta$, $|f(x)|$ and $|f(y)|$ are bounded by $\frac{\epsilon}{2}$, so that $$|f(x)-f(y)| \le |f(x)|+|f(y)|<\epsilon$$


Get row number of current element in table structure

Question: I have a HTML structure like below:

I need jQuery for booking_end click event which tells which row it is in, and which td booking_start is in, booking_start and booking_end are linked by an attribute booking.
So on click in above case I need output 2,3. where 2 is the tr number in which booking_end exists and 3 is the td number in which its booking_start exists.
Comment: Do you mean `event_start` instead of `booking_start`?
Comment: http://stackoverflow.com/questions/11026738/jquery-selector-to-find-content-of-td             Try this
Comment: Like [this](https://jsfiddle.net/j8e6cnh0/2/)?
Comment: @RoryMcCrossan: Yes event_start
Comment: @Dense: http://ttcube.co.in/booking/make_booking.php
Comment: @Gladiator9: its not of help
Answer: You can get the element index with its siblings.  Use the index function that returns the zero-based index.
You will need to use the function on the row itself, e.g.
$('a').click(function()
{
     var self = $(this),
         row = self.closest('tr'),
         rowIndex = row.index();

     // do something with rowIndex
});


PAReview.sh error, Expected "switch (...) {\n"; found "switch(...) {\n"

Question: In my theme's template.php file, I have a custom function as:
function _MYTHEME_content_grid($columns = 1) {

  $class = FALSE;
  switch($columns) {

    // No sidebars, just content.
    case 1:{
      $class = 'grid-100';
      break;
      }

// etc...

When I run the code through http://ventral.org/, I get this message in regard to the switch statement line: switch($columns) {
ERROR | Expected "switch (...) {\n"; found "switch(...) {\n"

I googled around but I can't really find anything on this error. My function works perfectly fine though. I'm guessing it's a syntax error but it would seem weird to insert a ; after the curly brace...
Comment: RajeevK is right, there is no need for curly braces wrapping the case block. Nonetheless, my guess is that the PAReview error is about the need for a white space in front of the term "switch". Well, it is not exactly a need, but a code convention.
Comment: @FranciscoLuz - yes without the curly braces around the `case` block, that too throws an error with PAReview.sh so I added those based on its suggestion... I may end up ignoring this as I got the function from the bootstrap theme and that's already a fully promoted project and I have full commit rights so I could just ignore it but obviously I'm trying to follow best practices.
Answer: Put simple switch, why put curly braces.
    function _MYTHEME_content_grid($columns = 1) {

      $class = FALSE;
      switch($columns) {

        // No sidebars, just content.
        case 1:
          $class = 'grid-100';
          break;
        case 2:
          //something
          break;

       // etc...
     }
   }

Comment: Ironically, without the curly braces around `case`, that too throws an error with PAReview.sh so I added those because of that issue.
Answer: The error says it all.
Put switch ($columns) instead of switch($columns)

Control statements should have one space between the control keyword
  and opening parenthesis, to distinguish them from function calls.

For more info refer Drupal coding standards


$(0,1]$ is not homeomorphic to $(a,b)$ - Carothers Example 5.6(g)

Question: I'm reading Carothers' Real Analysis, and I'm currently looking at homeomorphisms. The author says "two intervals that look different, are different" - i.e. they are not homeomorphic. The proof is done for the case $(0,1]$ and $(a,b)$, where the first interval is semi-open so we expect that the two are not homeomorphic.
I have some difficulty following the book's argument which I paraphrase here (for convenience) with inline questions.

Proof by contradiction. Suppose $(0,1]$ and $(a,b)$ are homeomorphic. Then by removing $1$ from $(0,1]$ we get $(0,1)$, and by removing its image $f(1) = c$ from $(a,b)$ we have that $(0,1)$ is homeomorphic to $(a,c)\cup (c,b)$.

Wait, why is that? I understand that we are deleting an element each from the domain and codomain, so the bijection remains a bijection. What about the continuity of $f$ and $f^{-1}$ though? We literally threw away an element, how do we know that continuity still holds?

But $(0,1)$ is homeomorphic to $\Bbb R$, so $\Bbb R$ would have to be homeomorphic to $(a,c)\cup (c,b)$ too. So $\Bbb R$ can be written as the disjoint union of two non-trivial open sets, which is impossible.

Two questions:

Why is $(0,1)$ homeomorphic to $\Bbb R$? We really need to produce a homeomorphism, that's all I'm asking.
How to prove that $\Bbb R$ cannot be written as the disjoint union of two non-trivial open sets? The idea that comes to my mind is - we already know that any open subset of $\Bbb R$ can be written as the disjoint union of unique open maximal intervals. Since $\Bbb R$ is open in $\Bbb R$, we can obviously do the same for it as well, and clearly, our choice of intervals would not be maximal in the event that we could write $\Bbb R$ as the union of two disjoint open intervals. Does this make sense?

Thank you!
Comment: I do not have access to Carother's book, but via a preview in the internet I have seen that there is a whole chapter about "connectedness". I would be surprised if that would not contain a proof that real intervals are connected.
Comment: Okay, then you should read chapter 6. I think it does not make much sense to write an answer here - it will contain nothing else than the book. But you can also look at https://math.stackexchange.com/q/3943095 .
Comment: This example is from the chapter preceding Connectedness, I haven't gotten there yet.
Answer:
Continuity still holds when you remove a point, because the restriction of a continuous map is still continuous.

A homeomorphism between $(0,1)$ and $\mathbb{R}$ is given by
$$x \mapsto \tan \left(-\frac{\pi}{2}+t\pi \right)$$

$\mathbb{R}$ is connected, so cannot be written as the disjoint union of two non-trivial open sets.
Answer: In $\Bbb R^2$ let $C$ be the circle centered at $(0,2)$ with radius $1.$ Let $D=\{(x,y)\in C: y<2\}$...Now $D$ is a semi-circle without its end-points, and $D$ is homeomorphic to $(0,1).$
For $p\in D$ let $l_p$ be the line thru $p$ and $(0,2)$ and let $l_p$ intersect the $x$-axis at $(f(p),0)$... (Draw a diagram of this.)
$f: D\to \Bbb R$ is a homeomorphism. A composition of homeomorphisms is a homeomorphism, so if $g: (0,1)\to D$ is a homeomorphism, then so is $(fg):(0,1)\to\Bbb R.$


Step-wise walking bass for tritone substitution

Question: I'm unsure how to handle a step-wise walking bass under a tritone substitution progression.
I'm working on piano and using what I understand to be basic "Evans" voicings in the right hand where the tritone sub. is an altered dominant when in major, but a un-altered dominant when in minor.
Not notating actual rhythms, just the changes and bass tones, I have...

Would those be the right (typical) step-wise tones?

EDIT
Posting a revision after answers...
Comment: the bass for `Dm7b5` should have been `A` _flat_
Answer: I'd first like to offer a few comments about walking bass in general:
Sometimes walking bass lines are written out note for note by arrangers but for the most part they are created by the bassist (or other instrumentalist playing a bass line) based on his knowledge of harmony, experience and also his personal preferences, what sounds good and right to him. I have sometimes heard other pro bassists' use note choices that are not what I would have used. My point is that there are some universally used conventions like avoiding awkward intervals or repeated notes from beat 4 to beat 1 there are similar approaches to lines that are slightly different but that both work. Use and trust your ear and listen to bass players you admire for ideas and techniques.
My other point is that walking bass lines in general and also specific to this question of stepwise motion are very dependent on context. The tempo of the song, the speed of the harmonic motion and the interval from one chord root to the next all play a factor in creating good walking bass lines.
The rest of my answer will be based on your examples of 8 notes starting and ending on the original note.
What you have written here will work just fine. Actually the fact that they are tritone substitutions is not really relevant to the shapes of the lines. One choice I would make is on the last 4 notes of say the Db7 I would use Ab-Gb-F-Db because I like to hear the F chord tone on beat 3 (assuming quarter note notation) instead of beat 2 because that way the chord tone falls on a stronger beat. Also note the Gb instead of G which I also prefer despite the ascending #11 because the descending Gb leads to the 3rd better but the G works fine too.
Walking up and down to the 5th works well because of the number of notes from the root to the 5 but if you were descending to the 5th and back up an adjustment is required, an extra chromatic note must be added, either between the root and 7 or between the 6 and 5.
Altered chords and scales present a different challenge because of the dissonance, the lack of a P5 and also the fact that the scale from a jazz perspective has two 2nds (b9 and #9) and either no 4th or no 5th depending on your point of view (is it a #11 or b5?). With this scale and chord the best approach is to create a line that has a good shape and incorporates the root and 3rd effectively.
My last comment is regarding your choice of chord quality for the tritone subs. A Db7alt in a 2-5 to a major chord is sonically the same as a G13#11 except for the root. A Db13#11 would give you a more noticeable sonic contrast to the regular 2-5. The same applies to the minor 2-5 in reverse.
Comment: I've been studying some transcriptions from Ray Brown and others, which has been very helpful. But sometimes I want a really plain vanilla reference as a starting point.
Comment: Looks good, for what it's worth that's what I would play!
Comment: "...on the last 4 notes of say the Db7 I would use Ab-Gb-F-Db because I like to hear the F chord tone on beat 4." Would you generally prefer `5431` versus `5321` to get the chord tone on the downbeat of 4? So, even on the `Dm7b5`, I should do `D Eb F G, Ab G F D`?
Comment: In a similar vein, maybe for the `Dbalt7` I should try `Db E F G, A G F Db`?
Comment: Actually @MichaelCurtis, if these are quarter notes the third (F) would fall on beat 3 and the root on beat  4, my mistake, I will edit my answer. I would and do play a Dm7b5 the way you mentioned.
Comment: I edited my answer, clarified I'm talking about quarter notes and offered a brief explanation as to why I prefer that choice. As for altered chords,  I'm a member of the "G is the b5" camp (as opposed to the #11) so I like G as the top note and that's also in line with it being stepwise since Db E skips a note. I like Db D E F G F E Db but I think your original solution works well too. If you think about it, E (Fb) is actually the 3rd of a altered scale even though we approach it as a #9 in jazz.
Comment: I posted a revision to capture your suggestions, how does that look now? Don't mean to belabor the point, I just want a basic reference doc, sort like in this https://www.scribd.com/doc/51760071/walkingbasslines, but for tritone subs. and especially alt7.
Comment: I understand. I would also practice walking down to the 5th and back up which requires adding a chromatic note descending like I mentioned in the answer so you land on the 5th on a downbeat.
Comment: Definitely will, on the downward walk. Your comments about the extra chromatic step either at the top or bottom is helpful. Thanks.
Answer: Yes, that's pretty much what I'd play for a stepwise walking bass line coming up from the root in each chord, essentially outlining altered and lydian-dominant scales respectively. It's not necessarily what I would play as a bass player doing a walking line as we tend to try and keep the whole bassline stepwise and not reset on a new chord but yes, coming up from the root that would work for me!


Several text files to csv with filename

Question: I have several text files in a folder and I would like to transpose them to csv. In each line, I would like to have in a column the name of my file, and in another column the content, for example:
file1.txt, All the text included in this file
file2.txt, More text here
...
I am using the following code:
from glob import glob
import pandas as pd
files=os.listdir("where the text files are saved")
content=[]
for file in files:
    with open(file, 'r', newline='') as source_file:
        for line in csv.reader(source_file):
            content.append(line[0])
with open('output.csv', 'w') as target_file:
    for line in content:
        target_file.write(out_filename + "," + line + '\n')

However, with this code I am only able to obtain in my csv the content of the text files. Could anyone explain how can I add the filename in a column?
Answer: import csv
import pandas as pd
filelocation = "FILELOCATION"
files= [k for k in next(os.walk(f"{filelocation}"))][2]
filenames = []
content=[]
for file in files:
    with open(f"{filelocation}\\{file}", 'r', newline='') as source_file:
        filenames.append(file)
        lines = source_file.read()
        content.append(lines)

data = {'Filename':filenames,
        'Content':content}

df = pd.DataFrame(data)
print (df)

df.to_csv(r'Path where you want to store the exported CSV file\File Name.csv', index = False)

Comment: You might prefer [`os.path.join`](https://docs.python.org/3/library/os.path.html#os.path.join) over `f"{filelocation}\\{file}"`
Comment: Thank you. The code permits me to obtain one column with the filename and another with the content, as I wanted. However my text is in french, so for some reason words like "élections" are replaced by "élections" or "françois" by "françois". Is there a way to avoid this? This did not happen with the previous code.
Comment: Not sure about the language. But you can reusue and merge the code you used if that works. Just append your line[0] to a list. And after going through each line at the end of that loop for that file, append that list to content
Comment: As I said I'm not sure about the language, it could be the pandas implementation, in which case either way of reading the file wouldn't work. Then it would be a matter of writing to csv differently
Comment: Sorry for the late answer. It seems to me that the problem is in the pandas. Maybe if I use: with open('output.csv', 'w') as out_file, I do not obtain these errors. But I do not know how to finish this code.
Comment: in the code provided, does it alter the characters when you do print(df)?
Comment: No, it doesn't. It only alters the characters in the csv file
Comment: try df.to_csv(r'Path where you want to store the exported CSV file\File Name.csv', index = False, encoding="utf-8")
Comment: also if you are opening in excel, have a look and see what it looks like in a text editor?

Several text files to csv with filename


Método save() do eloquent não funciona

Question: Quando tento utilizar o método save() do eloquent-laravel 5.1, da maneira que pede a documentação, a atualização não é feita no banco.
Esse é como pede a documentação:
$flight = App\Flight::find(1);
$flight->name = 'New Flight Name';
$flight->save();

Esse é o meu:
public function adotado($id) {
        $animal = Animal::find($id);
        if (Auth::user()->id == $animal->user_id) {
            $animal->ativo = 0;
            $animal->save();
            return redirect()->action('UserController@index');
        } else {
            return view('errors.restrito');
        }
    }

Verifiquei com dd($animal) que os dados estão sendo puxados normalmente do banco após o find(), inclusive o atributo 'ativo' é igual a 1. Dentro do if, dd($animal->ativo) retorna 0, ou seja, até ali o código está ok. O dd($animal->save()) também retorna true e é redirecionado normalmente para o index, porém, a atualização não aparece no db.
Alguma dica? Salve-me quem puder. Grato.
Comment: Tente comentar o redirect e verifique se acontece algum erro
Comment: Nenhum erro. =\
Comment: Verifica o retorno do `save`, pode estar retornando `false`. Seria o método `push` útil nesse caso?
Comment: @VirgilioNovic a alteração está sendo feita no $animal->ativo que está 1 no db. Depois que setei ativo = 0 dentro do if, o retorno de dd($animal->ativo) era 0, logo teve alteração.
Comment: @AndersonCarlosWoss o retorno do save() é 1. Tentei push também e continuou na mesma.
Answer: Na view, ao marcar o animal como "adotado", um modal era exibido pedindo confirmação. Após retirar o modal da view, o save() funcionou normalmente.
A pergunta que me ficou é: por quê?
O 'confirmar' do modal exibia o caminho 'animal/adotado/6' onde 6 é o id do animal. Exatamente da mesma maneira feito sem modal. Na action, confirmei que recebia o $id das duas maneiras, com ou sem modal. A diferença é que de um jeito não fazia alteração e do outro sim. Sou iniciante e não sei por que isso aconteceu, e talvez nem seja uma resposta adequada, mas tirando o modal da view resolveu.
Answer: Não use redirect()->action() amigo. Crie rotas para seus métodos, ficará muito mais simples.
Alguns passos para solucionar:

Use try/catch nos teus métodos, e coloque um dump() na exception.
Todos os erros são armazenados no arquivo laravel.log, que fica no
diretório storage/logs/laravel.log. Você pode verificar por ali o
porque não está salvando.
Comment: Obrigado pela dica. Irei utilizá-la.

Método save() do eloquent não funciona


Python testing if whitespace(\s) symbol is in string

Question: I have a problem testing if "\s" symbols are present in a string. For example is '\sgoogle\s.com' must show that there is.
Comment: Are you trying to match actual whitespace, or a backslash followed by an s?
Answer: # use raw strings to ignore escapes:
s = r'\sgoogle\s'
print s, s.find(r'\s') != -1

# and with regex:
import re
print re.search(r'\\s', s)

Gives:
\sgoogle\s True
<_sre.SRE_Match object at 0x7f2d696fc850>

Answer: You have to escape your \ as follows:
s = '\sgoogle\s.com'
re.search(r'(\\s)', s)

Demo: http://regex101.com/r/tF9oW6


Map from 2 different nodes to duplicated target node

Question: I have this source and target :

I need that my map would produce a target with 2 nodes of "T".
The first one is with "A" source content, and the second is with "B" source content.
For example:
Input:
<Root>

   <FieldA>FA</FieldA>
   <FieldB>FB</FieldB>

   <FieldC>FC</FieldC>
   <FieldD>FD</FieldD>

</Root>

Requested Output:
<Root>
    <T>
      <F1>FA</F1>
      <F2>FB</F1>
    </T>
    <T>
      <F1>FC</F1>
      <F2>FD</F2>
    </T>
</Root>

*** There is also a condition regarding the map from "B" to "T"
Answer: The following does what you want to achieve:
<?xml version="1.0" encoding="utf-8"?>

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">

<xsl:output method="xml" indent="yes"/>

 <xsl:template match="/">
  <xsl:apply-templates/>
 </xsl:template>

 <xsl:template match="Root">
  <xsl:copy>
   <xsl:apply-templates/>
  </xsl:copy>
 </xsl:template>

 <xsl:template match="A|B">
  <xsl:element name="T">
    <xsl:apply-templates/>
  </xsl:element>
 </xsl:template>

 <xsl:template match="*[parent::A or parent::B]">
  <xsl:choose>
     <xsl:when test="./name() = 'FieldA' or ./name() = 'FieldC'">
        <xsl:element name="F1">
           <xsl:value-of select="."/>
        </xsl:element>
     </xsl:when>
     <xsl:otherwise>
        <xsl:element name="F2">
           <xsl:value-of select="."/>
        </xsl:element>
     </xsl:otherwise>
  </xsl:choose>
 </xsl:template>

</xsl:stylesheet>

Besides, please take the time to report on what you have tried so far. SO is not there to do your homework. So, show your effort in your future questions.
Answer: Place looping functoid
A --> Looping Functoid --> T
B --> Looping Functoid --> T

FieldA --> F1
FieldB --> F2
FieldC --> F1
FieldD --> F2

Comment: Great solution, but I have another small problem.
A is unbounded, so the looping functoid creates an unnecessary T node.. how can I get over it ?
Comment: @ohadinho What do you mean 'unnecessary'. This map will create T nodes for each A and for each B.
Comment: because A is unbounded, it creates 3 nodes instead of 2.
2 are good, and another one that's empty
Comment: @ohadinho It isn't because A is unbounded. Something else is happening here. Try to validate your map (RightMouse --> Validate Map) and you'll see generated xsl.
Answer: Just link A and B to T through a Looping Functoid.
Comment: Great solution, but I have another small problem.
A is unbounded, so the looping functoid creates an unnecessary T node.. how can I get over it ?
Comment: Can you follup up with a sample?  T would only get created for each A & B so if an A is unnecesary, you'd need to add a filter to suppress the one you don't want.


AngularFire storage task observable never completes

Question: I am uploading a camera gallery image to firebase successfully, however I am unable to getDownloadURL() as the AngularFire storage task observable never completes.
I have consulted the documentation  following the 'Monitoring upload percentage' - Example Usage here
Please can you kindly advise what I am doing wrong or recommend an alternative approach. Thanks.
async onCamera(){
      try{
          const options: CameraOptions = {
          quality: 100,
          targetHeight:500,
          targetWidth:500,
          allowEdit: true,
          correctOrientation: true,
          sourceType: this.camera.PictureSourceType.PHOTOLIBRARY,
          destinationType: this.camera.DestinationType.DATA_URL,
          encodingType: this.camera.EncodingType.JPEG,
          mediaType: this.camera.MediaType.PICTURE
        }
        const imageData = await this.camera.getPicture(options);
        const image = 'data:image/jpeg;base64,' + imageData;
        const id = Math.random().toString(36).substring(2);
        const user = this.authenticatorService.getUser();
        const fileRef = this.afStorage.ref(user.uid + '/images/categories/'+id);
        const task = fileRef.putString(image, 'data_url');
        console.log('Done! - I can see this comment successfully logged to the terminal');
        //---------------------------------
        // But this Observable never completes?....
        //---------------------------------
        task.snapshotChanges().pipe(
          finalize(() => {
            console.log('Sequence complete'); // Execute when the observable completes: never logged
            this.downloadURL = fileRef.getDownloadURL();
            this.downloadURL.subscribe(url=> this.imageUrl=url);
            console.log('My ImageUrl' + this.imageUrl); // Never logged to terminal?
          }));

        console.log('Finished! - I can see this comment successfully logged to the terminal');
      } catch(e) {
        console.error(e);
        this.errorMessage = JSON.stringify(e);
        console.log(this.errorMessage);
      }
    }

Relevant Imports
import { AngularFireStorage, AngularFireStorageReference, AngularFireUploadTask } from '@angular/fire/storage';
    import { Observable } from 'rxjs/Observable';
    import { Camera, CameraOptions} from '@ionic-native/camera/ngx';
    import { finalize } from 'rxjs/operators';

Ionic Native 5 Reference:
https://blog.ionicframework.com/help-test-ionic-native-5/
Relevant Dependencies
"dependencies": {
    "@angular/animations": "6.1.0",
    "@angular/common": "6.1.0",
    "@angular/compiler": "6.1.0",
    "@angular/compiler-cli": "6.1.0",
    "@angular/core": "6.1.0",
    "@angular/fire": "^5.1.0",
    ....
    "@ionic-native/camera": "^5.0.0-beta.22",
    "@ionic-native/core": "^5.0.0-beta.22",
    ...
    "cordova-plugin-camera": "~4.0.3",
    ...
    "firebase": "^5.5.9",
    "ionic-angular": "3.9.2",
    "promise-polyfill": "^8.1.0",
    "rxjs": "^6.3.3",
    "rxjs-compat": "^6.3.3",
    "cordova-android": "~7.1.4"
  },

Comment: Are you sure console.log('My ImageUrl' + this.imageUrl); // Never logged to terminal? is not at all executing or imageUrl is empty?
Comment: Yes I am sure as console.log('Sequence complete') inside the finalize block doesn't get logged either.
Answer: You look like you're 99.9% of the way there, nice job on this one! And thanks for providing the links to the docs. I think the reason that the finalize() is never firing is because you aren't subscribing to the .snapshotChanges(). Without .subscribe() your code won't actually listen to the changes fired off by task.snapshotChanges().
In the example you found, notice that there is a .subscribe() stuck on after the .pipe():
// get notified when the download URL is available
task.snapshotChanges().pipe(
    finalize(() => this.downloadURL = fileRef.getDownloadURL() )
)
.subscribe()

So your code should be:
//---------------------------------
// But this Observable never completes?....
//---------------------------------
task.snapshotChanges().pipe(
    finalize(() => {
        this.downloadURL = fileRef.getDownloadURL();
        console.log('My ImageUrl' + this.downloadURL);
    })
).subscribe();


file upload string or binary data would be truncated

Question: Hi Guys I have been struggling with this issue for days now. I have a website that uploads different file types, creates thumbs from the files and saves the file and thumbs to their respective folders. every so often it throws an exception  string or binary data would be truncated, Ive never encountered this locally. I have a problem pinning down  the circumstances that it happens, I thought it was documents with spaces in the name but that works sometimes as well. This is really bugging me and I need to fix this. The db table fields are long enough, trust me . Has anyone else ever encountered this issue?
Comment: Do you save files in DB or locally ?
Comment: The thing is it works for me normally, then after tests, a tester reports the bug, the tester uses mac/safari, I have also tested this myself and it works
Comment: But it also seems to break randomly sometimes which makes no sense
Comment: That error message typically comes from the database, not the file system.  Have you been able to reproduce it?  If so, I would double-check the data being saved to the database and make sure it doesn't exceed your column sizes.
Answer: Hi I know all this, this is  a db error etc, but the fields are long enough. I have not been able to reproduce this, my log files are empty. This is very weird


Let $\{x_n\}$ be a bounded sequence and $s=\sup\{x_n|n\in\mathbb N\}.$ Show that if $s\notin \{x_n|n\in\mathbb N\}, $then there exists a subsequence .

Question:
Let $\{x_n\}$ be a bounded sequence and $s=\sup\{x_n|n\in\mathbb N\}.$
  Show that if $s\notin \{x_n|n\in\mathbb N\}, $then there exists a
  subsequence convereges to $s$.

$s-1$ cannot be the upperbound and $s\notin \{x_n|n\in\mathbb N\}, \exists n_1\in \mathbb N:n_1\ge1:s-1<x_{n_1}<s.$
$s-\frac{1}{2}$ cannot be the upperbound and $s\notin \{x_n|n\in\mathbb N\}, \exists n_2\in \mathbb N:n_2\ge1:s-\frac{1}{2}<x_{n_2}<s.$
$\dots$
$s-\frac{1}{k}$ cannot be the upperbound and $s\notin \{x_n|n\in\mathbb N\}, \exists n_k\in \mathbb N:n_k\ge1:s-\frac{1}{2}<x_{n_k}<s.$
$\dots$
My doubt
I can create a sequence of a number like this. How do we guarantee that we can choose $n_2>n_1$ such that $s-\frac{1}{2}<x_{n_2}<s$ hold? similarly for other cases. If we can show this then required subsequence would be $\{x_{n_k}\}$.
Answer: Using the definition of supremum and the assumption that $s\notin \{x_n\}$, show that for any $\epsilon > 0$, there are infinitely many $n$ such that $s-\epsilon < x_n < s$. Having done so, find an increasing sequence $n_1 < n_2 < n_3 < \dots,$ such that $s-1/n_i < x_{n_i} <s$.
Comment: How can one show this?
Answer: One can do it like looking for $n_{k+1}\geq 1$ such that $\max\left\{s-\dfrac{1}{k+1},x_{1},...,x_{n_{k}}\right\}<x_{n_{k+1}}<s$.
Comment: $n_{k+1}$ can be less than $x_{n_r}:rn_{k}$, I am excluding from $1$ to $n_{k}$.
Comment: It is only important to consider the indices such that $n_{k+1}>n_{k}$ to fit the definition of subsequence.
Comment: okay. Now, I got the point.


.Xib creates error when running the project with Xcode 4.6.1

Question: Please someone help me out.
MY Mac OS(10.8.5) is updated and me also using the Xcode 5, but i have my previous Xcode 4.6.1 also installed in my mac. When i run my project through Xcode 5 then it's OK but when i run my project through Xcode 4.6.1 then it show that error which you seen in the image.and can't run the project.
Answer: This has a very simple answer.
Open the Project file on Xcode 5, And then
1.Open file inspector

2.On Interface Builder Documents section change Open with to Xcode 4.6 (if it's 5.x).

3.Click Revert, Close the project and open that with old Xcode.

you can do the same thing on Xcode 4.6 to work with older version.
Happy coding.. :)
Answer: 1)Goto your xcode5 see your StoryBoardFile go to Assistant Editor preview option.
2)Then Goto  file inspector see first tab
3)Select your interface Builder Documents 4.6
4) One Alert popup they ask you Revert to Xcode 4.6 format? select Revert
Follow this step and open your project in your old xcode project.


Tuning Linux IP routing parameters -- secret_interval and tcp_mem

Question: We had a little failover problem with one of our HAProxy VMs today. When we dug into it, we found this:

Jan 26 07:41:45 haproxy2 kernel: [226818.070059] __ratelimit: 10 callbacks suppressed
Jan 26 07:41:45 haproxy2 kernel: [226818.070064] Out of socket memory
Jan 26 07:41:47 haproxy2 kernel: [226819.560048] Out of socket memory
Jan 26 07:41:49 haproxy2 kernel: [226822.030044] Out of socket memory

Which, per this link, apparently has to do with low default settings for net.ipv4.tcp_mem. So we increased them by 4x from their defaults (this is Ubuntu Server, not sure if the Linux flavor matters):

current values are:    45984   61312   91968
new values are:       183936  245248  367872

After that, we started seeing a bizarre error message:

Jan 26 08:18:49 haproxy1 kernel: [ 2291.579726] Route hash chain too long!
Jan 26 08:18:49 haproxy1 kernel: [ 2291.579732] Adjust your secret_interval!

Shh.. it's a secret!!
This apparently has to do with /proc/sys/net/ipv4/route/secret_interval which defaults to 600 and controls periodic flushing of the route cache

The secret_interval instructs the kernel how often to blow away ALL route
  hash entries regardless of how new/old they are.  In our environment this is
  generally bad.  The CPU will be busy rebuilding thousands of entries per
  second every time the cache is cleared.  However we set this to run once a
  day to keep memory leaks at bay (though we've never had one).

While we are happy to reduce this, it seems odd to recommend dropping the entire route cache at regular intervals, rather than simply pushing old values out of the route cache faster.
After some investigation, we found /proc/sys/net/ipv4/route/gc_elasticity which seems to be a better option for keeping the route table size in check:

gc_elasticity can best be described as the average bucket depth the kernel
  will accept before it starts expiring route hash entries.  This will help
  maintain the upper limit of active routes.

We adjusted elasticity from 8 to 4, in the hopes of the route cache pruning itself more aggressively. The secret_interval does not feel correct to us. But there are a bunch of settings and it's unclear which are really the right way to go here.

/proc/sys/net/ipv4/route/gc_elasticity (8)
/proc/sys/net/ipv4/route/gc_interval  (60)
/proc/sys/net/ipv4/route/gc_min_interval (0)
/proc/sys/net/ipv4/route/gc_timeout (300)
/proc/sys/net/ipv4/route/secret_interval (600)
/proc/sys/net/ipv4/route/gc_thresh (?)
rhash_entries (kernel parameter, default unknown?)

We don't want to make the Linux routing worse, so we're kind of afraid to mess with some of these settings.
Can anyone advise which routing parameters are best to tune, for a high traffic HAProxy instance?
Answer: I never ever encountered this issue. However, you should probably increase your hash table width in order to reduce its depth. Using "dmesg", you'll see how many entries you currently have:
$ dmesg | grep '^IP route'
IP route cache hash table entries: 32768 (order: 5, 131072 bytes)

You can change this value with the kernel boot command line parameter rhash_entries. First try it by hand then add it to your lilo.conf or grub.conf.
For example: kernel vmlinux rhash_entries=131072
It is possible that you have a very limited hash table because you have assigned little memory to your HAProxy VM (the route hash size is adjusted depending on total RAM).
Concerning tcp_mem, be careful. Your initial settings make me think you were running with 1 GB of RAM, 1/3 of which could be allocated to TCP sockets. Now you've allocated 367872 * 4096 bytes = 1.5 GB of RAM to TCP sockets. You should be very careful not to run out of memory. A rule of thumb is to allocate 1/3 of the memory to HAProxy and another 1/3 to the TCP stack and the last 1/3 to the rest of the system.
I suspect that your "out of socket memory" message comes from default settings in tcp_rmem and tcp_wmem. By default you have 64 kB allocated on output for each socket and 87 kB on input. This means a total of 300 kB for a proxied connection, just for socket buffers. Add to that 16 or 32 kB for HAProxy, and you see that with 1 GB of RAM you'll only support 3000 connections.
By changing the default settings of tcp_rmem and tcp_wmem (middle param), you can get a lot lower on memory. I get good results with values as low as 4096 for the write buffer, and 7300 or 16060 in tcp_rmem (5 or 11 TCP segments). You can change those settings without restarting, however they will only apply to new connections.
If you prefer not to touch your sysctls too much, the latest HAProxy, 1.4-dev8, allows you to tweak those parameters from the global configuration, and per side (client or server).
I am hoping this helps!
Answer: The Out of socket memory error is often misleading.  Most of the time, on Internet facing servers, it does not indicate any problem related to running out of memory.  As I explained in far greater details in a blog post, the most common reason is the number of orphan sockets.  An orphan socket is a socket that isn't associated to a file descriptor.  In certain circumstances, the kernel will issue the Out of socket memory error even though you're 2x or 4x away from the limit (/proc/sys/net/ipv4/tcp_max_orphans).  This happens frequently in Internet-facing services and is perfectly normal.  The right course of action in this case is to tune up tcp_max_orphans to be at least 4x the number of orphans you normally see with your peak traffic.
Do not listen to any advice that recommends tuning tcp_mem or tcp_rmem or tcp_wmem unless you really know what you're doing.  Those giving out these advices typically don't.  Their voodoo is often wrong or inappropriate for your environment and will not solve your problem.  It might even make it worse.
Comment: When this happens, the message is different in dmesg, you see "too many of orphaned sockets". However I agree with you that orphans can consume a huge amount of memory.
Comment: When you exceed the number of `/proc/sys/net/ipv4/tcp_max_orphans` you will experience a different error.  The entire Stack Exchange stack for instance has `/proc/sys/net/ipv4/tcp_max_orphans` at 65536 and `/proc/net/sockstat` results in TCP: inuse 2996 orphan 171 tw 15972 alloc 2998 mem 1621 - a difference that cannot be ignored.
Answer: We tune some of these parameters regularly.  Our standard for high throughput, low latency trading platforms is:

net.ipv4.tcp_rmem = 4096 16777216 33554432
net.ipv4.tcp_wmem = 4096 16777216 33554432
net.ipv4.tcp_mem = 4096 16777216 33554432
net.core.rmem_default = 16777216
net.core.wmem_default = 16777216
net.core.rmem_max=16777216
net.core.wmem_max=16777216
net.core.netdev_max_backlog = 30000
net.core.netdev_max_backlog = 30000
Comment: These tunables are wrong and are very frequently found in bench environments then blindly copy-pasted. They will not have any problem with just a few concurrent sessions, but even with 100 TCP sockets, you'll allocate 3.2 GB of RAM. As long as the latency is low, you won't notice anything suspect. You just have to unplug a remote machine during a transfer to see the output buffers fill, or freeze a local task and see the input buffer fill. This is insane...
Comment: Jeff, this is not times three. tcp_mem is in pages and defines the global size. tcp_rmem and tcp_wmem are in bytes and define the per-socket size.
Comment: per Willy's math that means your standard memory pressure # (middle number) is 68 GB?! Times three (rmem, wmem, mem)??
Comment: Those tuneables look wrong, for concurrent servers with small data you don't want to reserve so much socket buffers and tcp_mem is totally different from r/wmem, using the same numbers does not really make sense, (one is bytes per Connections the other pages per system)


Find a basis B of R2 such that the matrix of the linear transformation T(x, y) = (y, x) is diagonal with respect to B, and give the diagonal matrix.

Question: Find a basis $B$ of $R^2$ such that the matrix of the linear transformation $T(x, y) = (y, x)$ is diagonal with respect to $B$, and give the diagonal matrix.
This is the question. I'm not really sure how to begin with this one. Anything would help thanks.
Answer: We're looking for a basis $\{(x_1,y_1),(x_2,y_2)\}$ of $\mathbb{R}^2$ such that:
$T(x_1,y_1)=(y_1,x_1) = \alpha(x_1,y_1) +0(x_2,y_2)$
$T(x_2,y_2)=(y_2,x_2) = 0(x_1,y_1)+\beta(x_2,y_2)$
We get:
$y_1=\alpha x_1$ and $x_1=\alpha y_1 \Rightarrow y_1=\alpha^2y_1$
Since $\alpha \neq0$ (why?), we get $\alpha=\pm1$. In the same way we get $\beta=\pm1$.
In order to get two linear independent vectors in $\mathbb{R}^2$, we will choose $\alpha=1$ and $\beta=-1$.
So let's look at $B=\{(1,1),(1,-1)\}$. That's a basis of $\mathbb{R}^2$ (why?).
Can you continue from here?


nagios core v4, please help me add more service checks for a single host

Question: I am having difficulties understanding the documentation and would appreciate clarification.
I have NRPE and nagios plugins installed from source on both the nagios server and its clients.
Can somebody provide additional service checks that I can add to this 'database' servers, such as check_disk check_users check_load etc....
I am having difficulty with the syntax:
define host {

        use                          linux-server

        host_name                    database

        alias                        database

        address                      database

        register                     1

}

define service{

      host_name                       database

      service_description             PING

      check_command                   check_ping!100.0,20%!500.0,60%

      max_check_attempts              2

      check_interval                  2

      retry_interval                  2

      check_period                    24x7

      check_freshness                 1

      contact_groups                  admins

      notification_interval           2

      notification_period             24x7

      notifications_enabled           1

      register                        1

}

Answer: To add a new check like check_disk for your host database you have to define a new service and use check_nrpe as command and the name of your check as option (could be in advanced_services.cfg)
example:
define service {
                service_description                   Diskspace
                max_check_attempts                    4
                check_interval                        10
                retry_interval                        5
                first_notification_delay              2
                notification_interval                 45
                active_checks_enabled                 1
                passive_checks_enabled                1
                notifications_enabled                 1
                check_command                         check_nrpe!check_disk
                check_period                          24x7
                notification_period                   24x7
                host_name                             database
                contact_groups                        admins
                use                                   generic-service
}
You must ensure that "check_disk" is defined in your NRPE-client config (don't forget to reload/restart NRPE on your client after editing your conf).
Comment: You can omit anything that's already defined in the generic-service template (probably everything except `service_description`, `host_name`, `check_command`, and `use`)


Solve $12Q-20- 144/Q^2 = 0$

Question: I don't know how to find $Q$:
$$12Q-20- \frac{144}{Q^2} = 0$$
Comment: Try a few numbers.  Start with factors of 144.
Comment: Multiply on both sides by $Q^2$ to get $120Q^3- 20Q^2- 144= 0$, a cubic polynomial equation.  Divide through by 4 to simplify: $30Q^3- 5Q^2- 36= 0$.  Use the "cubic formula".  Or you could check to see if there are rational roots- if there is a rational root, Q= m/n, then the numerator, m, must evenly divide 36 and the denominator, n, must evenly divide 30.
Answer: \begin{align}&12Q-20-\frac{144}{Q^2}=0 &\times Q^2\\
&12Q^3-20Q^2-144=0 &:4\\
&3Q^3-5Q^2-36=0 \end{align}
Use rational root theorem which leads you to find $p=\frac{m}{n}$ where $m$ must divide $36$ and $n$ must divide $3$ and $p$ must be integer
$p=3$
then divide whole equation by $(Q-p)$
$$(Q-3)(3Q^2+4Q+12)=0$$
equation $3q^2+4q+12=0$ has ${4^2}-{4*3*12}=-128<0$ so that the only real solution is
$$Q=3$$
Comment: Welcome to Math.SE! Your answer would be better if you stated you used Rational Root theorem, and for the $12-144<0$, stating that you used the discriminant $b^2-4ac$ would help increase the clarity of the solution.
Comment: Amazingly polite comment.
Comment: In addition, $Q=3$, is the 'only Real solution' not just the 'only solution'.
Answer: \begin{align}0=12Q-20-\frac{144}{Q^2}=\frac{12Q^3-20Q^2-144}{Q^2}\iff 3Q^3-5Q^2-36=0\end{align} or $Q^2(3Q-5)=36$. Now, you can write $36$ as $$36=2^2\cdot3^2$$ so since $Q^2$ (could) divide $36$, two reasonable numbers to test first are $Q=2$ and $Q=3$. Indeed $Q=3$ is a solution and the only real one.

Solve $12Q-20- 144/Q^2 = 0$


Custom Template for Comment links

Question: I would like to have a custom template for links (edit, reply, deleted) for my custom Comment Type. (Drupal 9)
Twig Debugging of course enable. I have tried to use hook_theme_suggestions_link_alter and hook_theme_suggestions_link, and I see my suggestion, but it doesn't apply my custom twig for links.
I spent a lot of time looking for a solution and did not find.
Please, could you help me?
function answer_theme_suggestions_links_alter(array &$suggestions, array $variables)
    {
      if (isset($variables['links']['comment-custom-action'])) {
        array_splice($suggestions, 1, 0, 'links__comment__answer');

      }
    }

function answer_theme()
{
  return [
    'links__comment__answer' => [
      'template' => 'links--comment--answer',
      'base hook' => 'links'
    ]
  ];
}

Comment: I edited my question one more time, maybe now it is clearer
Comment: First: [Enable Twig debuggin](https://www.drupal.org/docs/theming-drupal/twig-in-drupal/debugging-twig-templates#s-enable-debugging) to see the template that's currently used as HTML comments when inspecting the page. Next, copy that template to your custom theme's template folder and adjust the markup to your needs. Flush cache.
Comment: Sorry, it is not the answer for my question
Comment: Yes, it's a comment after which you added crucial information to your question. So you tried `hook_theme_suggestions_comment_alter` and could not retrieve the comment type to add a template suggestion based on the comment type? Can you please post the current code that's not working?
Comment: The  question is improved however I do not understand it fully.
Answer: It happens because Drupal first collect all the theme suggestions following this order.

The suggestions returned by hook_theme_suggestions_HOOK() implementations done by modules, the base themes for the active theme, and the active theme (in that order)
The suggestions returned by hook_theme_suggestions_alter() implementations done by modules, the base themes for the active theme, and the active theme (in that order)
The suggestions returned by hook_theme_suggestions_HOOK_alter() implementations done by modules, the base themes for the active theme, and the active theme (in that order)

Inside the group of modules (or base themes) that implement the same hook,  the invocation order is determined by system weight, then by module (or theme) name.
Once Drupal collects all the theme suggestions in an array, it reverts the order of those suggestions, which means the last suggestion becomes the first one.
This is done by ThemeManager::render(), for example, which uses the following code. (Notice the code following the "// >>> * <<<" comment I added.)
  // Invoke hook_theme_suggestions_HOOK().
  $suggestions = $this->moduleHandler->invokeAll('theme_suggestions_' . $base_theme_hook, [
    $variables,
  ]);

  // If the theme implementation was invoked with a direct theme suggestion
  // like '#theme' => 'node__article', add it to the suggestions array before
  // invoking suggestion alter hooks.
  if (isset($info['base hook'])) {
    $suggestions[] = $hook;
  }

  // Invoke hook_theme_suggestions_alter() and
  // hook_theme_suggestions_HOOK_alter().
  $hooks = [
    'theme_suggestions',
    'theme_suggestions_' . $base_theme_hook,
  ];
  $this->moduleHandler->alter($hooks, $suggestions, $variables, $base_theme_hook);
  $this->alter($hooks, $suggestions, $variables, $base_theme_hook);

  // Check if each suggestion exists in the theme registry, and if so,
  // use it instead of the base hook. For example, a function may use
  // '#theme' => 'node', but a module can add 'node__article' as a suggestion
  // via hook_theme_suggestions_HOOK_alter(), enabling a theme to have
  // an alternate template file for article nodes.
  // >>> * <<<
  foreach (array_reverse($suggestions) as $suggestion) {
    if ($theme_registry->has($suggestion)) {
      $info = $theme_registry->get($suggestion);
      break;
    }
  }

It then search for the first existing template file that matches the suggestions and uses that template file.
In your case, the suggested template files have been checked following this order. (This is shown in the debugging output shown in the screenshot.

links--comment.twig.html
links--inline.twig.html
links--comment--answer.twig.html

If links--inline.twig.html has been suggested by the active theme, or one of its base themes, and the code shown in the question is implemented by a module, there isn't anything you can do, as a theme suggestion always take precedence over a module suggestion.
If links--comment.html.twig suggestion was done by module, and the code shown in the question is implemented by a module too, you need to increment your module's weight, for example calling module_set_weight() inside hook_install() or hook_update_N().
This is doesn't seem your case, but notice that if you implement answer_theme_suggestions_links_alter() and answer_theme_suggestions_alter() (or answer_theme_suggestions_links_alter() and answer_theme_suggestions_links()) the suggestions given by answer_theme_suggestions_links_alter() takes the precedence.

Custom Template for Comment links


Drush make Distribution throwing errors: exec() unable to fork bootstrap.inc:636

Question: I'm using DrupalPro VM and trying to do a drush make on the distribution One Page CV.
I build the distribution:
sudo drush make onepagecv.make -y

But I'm getting the following errors during the make and crashes my terminal. I logged the install process and it seems to stop at the following.
Here is the log:
Answer: This is probably related to some resources limit or temporary glitch. So first try to restart your Apache.
If this won't help, make sure that you've necessary requirements to run drush (which is either curl or wget).
Otherwise it could be some resource limitation on your environment. E.g. check for ulimit -a or kern.maxprocs.
If there is still problem, please add -v for verbose mode or -d for debug messages for drush, you could more easily track the issue.
Comment: This fixed it for me. Classic turn it off and on again solution :)


OPNsense move interface to other hardware port

Question: I have an OPNsense with interfaces directy configured to the hardware ports. The corresponding switch port is also an access port.
We plan to change the switch port to a trunk port to transport multiple VLANs via this port. Is there a way to move the already configured OPNsense interface (IPs, rules, etc.) to the new corresponding vlan port?
Answer: I have figured it out.

Add the VLAN interface to the hardware port via "Other Types"
Change the FW interface assignment to the VLAN interface at "Assignments"
Reboot to flush and recreate the state table
In case of a cluster, start with the passive host and do a CARP Switch Over.


Every Presheaf Is Colimit of Representables

Question: I am working on the proof that each presheaf $F\in \mathbf{Set}^{\mathcal C^{op}}$ is the colimit of $\mathbf{y}\circ \pi\colon \int_{\mathcal{C}}F\to \mathbf{Set}^{\mathcal C^{op}}$ where $\int_{\mathcal{C}}F$ is the category of elements of $F$, $\pi\colon (x,C)\mapsto C$ is the natural projection and $\mathbf{y}$ is the Yoneda embedding. In the course of the proof, I showed there was an embedding of $\int_{\mathcal C}F$ into the slice category $\mathbf{Set}^{\mathcal C^{op}}/F$ to obtain a cocone with vertex $F$. Then using the Yoneda lemma, for any other cocone $(p_x\colon \mathbf{y}C\to P)_{(x,C)}$ under $\mathbf{y}\circ \pi$, I constructed the natural transformation $\alpha$ componentwise, using the Yoneda lemma. However, I cannot for the life of me see where I needed the arrows of $\int_{\mathcal{C}}F$ in the proof. I see how the cocone is compatible with the arrows, but can't see how they are not extraneous to the proof.
So my question boils down to: Can someone provide a counterexample of a presheaf $F$ that is not a colimit of the functor $\mathbf{y}\circ\pi$ where the domain is the discretization of the category of elements of $F$, i.e., forgetting the nontrivial arrows?
Comment: If your claim is true, then every presheaf is the _coproduct_ of representables. Try finding one that isn't. (Hint: coproducts of representables are projective...)
Comment: @ZhenLin That's a good hint. Nonprojective presheaves are not hard to come by. And going over the proof today, I noticed that the naturality condition for the unique natural transformation $F\to P$ depends on the arrows of $\int_{\mathcal C}F$ being there.
Answer: There is a conceptual proof which goes along these lines:

The Yoneda Lemma entails that for any presheaf $F\colon \mathcal C^\text{op}\to \bf Set$, there is a canonical isomorphism $F\cong \int^X\hom(-,X)\times FX$ (see here);
You can interpret the former result as "any presheaf is canonically a weighted colimit";
$\bf Set$-weighted colimits correspond to colimits over the category of elements of the weight:
$$
\text{lim}^{W} F\cong \text{lim}_{(c,x)\in \text{el}(W)}(F \pi)
$$ The proof goes by nonsense (allow me to be sloppy but evocative, it's up to you to fill the details):
$$
\begin{align*}
\int^{c\in \bf C}Fc\times {Wc} &\cong {\rm coeq}\Big(\coprod_{c\to c'}Fc'\times {Wc} \rightrightarrows \coprod_{c\in \bf C}Fc\times {Wc}\Big)\\
&\cong {\rm coeq}\Big( \coprod_{c\to c'}\coprod_{x\in Wc}Fc'\rightrightarrows \coprod_{c\in\bf C}\coprod_{x\in Wc} Fc \Big)\\
&\cong {\rm coeq}\Big( \coprod_{c\to c'\in \text{el}(W)} Fc'\rightrightarrows \coprod_{(c,x)\in \text{el}(W)} Fc \Big)\\
&\cong \varinjlim_{(c,x)\in\text{el}(W)}(F\circ\pi)
\end{align*}
$$
Points 1+3 reads now as $F\cong \text{lim}^F\textbf{y}$, so by point 3 you get the result.
Comment: Not the answer I was looking for, but the answer I needed...
Comment: (too long for a comment, and not what you are asking for, but I like this proof too much)
Answer: Here is a version using weighted limits.
Given a presheaf $P$, and considering $Y:C \to \hat{C}$ we have the PU :
$$
\begin{align*}
\hat{C}({colim}_P Y, X) &\cong Set^{C^{op}}(P,\hat{C}(Y-, X))\\
&\cong \hat{C}(P,X)\\
\end{align*}
$$
naturally in $X$, so that *
$${colim}_P Y  \colon= colim_{\int P} (Y \circ \pi)  \cong P$$
The arrows $f : (x \in Pc) \to (y \in Pd)$ in $\int P$, which verify $x = Pf \circ y $, translate to commutation requirement for components of the cocones of $y \circ \pi$ namely that we should have $\tilde{x} =\tilde{y} \circ f_*$ meaning we can derive all the components "below" from the "highest" component.

Presheaves are upward closed sets, relative to positions in $C$ (A telling picture made of nested convex sets, whose apex are labeled with objects of $C$ helps a lot to visualize). Exploding sets and viewing them from an element-wise point of view, you get the many arrows in the category of elements along with the many commutations. Every  $Q$ positioned "above" $P$ (by means of a natural transformation from $P$ to $Q$) has to commute with all of those those arrows among the category of elements in order to properly be "above" the presheaf $P$, once all elements are packed again into sets.
The smallest such $Q$ is $P$ itself, with components at $(x\in Pc)$ the natural transformation $\tilde{x} : yc \to P $
Going back to this idea of phreshaves as upward closed sets, we can think of a point $y\in Pb$ as a proof of membership at $b$ for $P$.
Taking some $f : a \to b$ in $B$, functoriality says that $Pf(y)$ is a proof of membership at $a$ for $P$ deduced from $f$ in $C$. Those proofs have to respect some transitivity built into $C$.
A diagram in $Set$ describing the category of elements as arrows from $1$, say $Pf(y) : 1 \to Pa $, $y : 1 \to Pb $ and $Pf : Pb \to Pa$ with commutation $Pf(y) = Pf . y $ gets translated by Yoneda to a diagram in $\hat{C}$ with commutation $\hat{Pf(y)} = \hat{y} . f_*$
TLDR : functoriality of a presheaf $P$, after "exploding" each sets $Pa$ to its ingredients, creates arrow in the category of elements. After their translation by Yoneda to $\hat{C}$, this creates commutation requirements for the cocones considered.


Como importar uma função de um módulo no Python?

Question: Estou com problemas ao importar a função de um módulo e fazer uso da mesma.
Já me certifiquei de colocar o arquivo __init__.py na pasta. Mas não consigo fazer uso das funções.
O programa fará download do conteúdo HTML de uma página web, e faz um recorte de substrings (busca subs inicial e final) e recorta o entre elas. Também faz um acompanhamento offser da posição inicial e final de cada tag.
Meu programa (já com as funções do módulo, mas preciso retirá-las). Deixei para testarem a funcionalidade.
# -*- coding: utf-8 -*-
import requests

Texto = requests.get('https://www.panvel.com/panvel/concor-hct-5mg125mg-30-comprimidos/p-622540')

#print("Status Code :", Texto.status_code)
#print(Texto.headers)

def PosEx(Substring,Texto,Offset):# Retorna resultado de corte em textos com offset e upper ignore
    return Texto.find(Substring,Offset)

Offset = 0

def CortaFora(Offset,Texto,Inicio,Fim): # Da o que está entre o inicio e o fim em determinado texto, respeitando offset e retornando offset inclusive.
    Inicial = Final = ''
    Inicial = PosEx(Inicio,Texto,Offset)+len(Inicio)
    # print('Pos Inicial:'+str(Inicial))
    Offset = Inicial
    Final = PosEx(Fim,Texto,Offset)
    # print('Pos Final:'+str(Final))
    Offset = Final
    return Texto[Inicial:Final].strip(' '), Offset

a = Texto.text
b = PosEx('
',a, Offset)
print('Posição antes do corta Fora do Offset:' +str(b))
print('')
d,Offset = CortaFora(Offset, a,'
','
')
print(d)
print('')
print('Posicao Após Corta Fora do Offset:'+str(Offset))

Módulo que quero importar as funções PosEx e CortaFora:
# -*- coding: utf-8 -*-

def PosEx(Substring,Texto,Offset):# Retorna resultado de corte em textos com offset e upper ignore
   # return Texto.find(Substring,Offset)

Offset = 0

def CortaFora(Offset,Texto,Inicio,Fim): # Da o que está entre o inicio e o fim em determinado texto, respeitando offset e retornando offset inclusive.
    Inicial = Final = ''
    Inicial = PosEx(Inicio,Texto,Offset)+len(Inicio)
    # print('Pos Inicial:'+str(Inicial))
    Offset = Inicial
    Final = PosEx(Fim,Texto,Offset)
    # print('Pos Final:'+str(Final))
    Offset = Final
    return Texto[Inicial:Final].strip(' '), Offset

Answer: É do mesmo modo que você faz os import de outros módulos, como você fez no seu próprio código com a lib request.
Vamos supor que os seus programas estão na mesma pasta.
Chamemos function.py (sugestão) o código com as funções:
# -*- coding: utf-8 -*-
def PosEx(Substring,Texto,Offset):
    """
    Retorna resultado de corte em textos com offset e upper ignore
    """
    return Texto.find(Substring,Offset)

def CortaFora(Offset,Texto,Inicio,Fim):
    """
    Da o que está entre o inicio e o fim em determinado texto, respeitando offset
    e retornando offset inclusive.
    """
    Inicial = Final = ''
    Inicial = PosEx(Inicio,Texto,Offset)+len(Inicio)

    Offset = Inicial
    Final = PosEx(Fim,Texto,Offset)

    Offset = Final
    return Texto[Inicial:Final].strip(' '), Offset

Daí seu código principal ficaria assim:
# -*- coding: utf-8 -*-
import requests

from function import PosEx, CortaFora

Texto = requests.get('https://www.panvel.com/panvel/concor-hct-5mg125mg-30-comprimidos/p-622540')

a = Texto.text
b = PosEx('
',a, Offset)
print('Posição antes do corta Fora do Offset:' +str(b))
print('')
d,Offset = CortaFora(Offset, a,'
','
')
print(d)
print('')
print('Posicao Após Corta Fora do Offset:'+str(Offset))

Comment: Valeu Octávio!, deu certo, falta de atenção e experiencia, achei que fosse necessário chamar a função!!


How can I save what filters a user wants when viewing a view?

Question: I don't know if this is possible but, I would like to allow my users to be able to filter out what content they would like to show up in a view so that every time they return to that view, their preferences are saved.
I no how to allow my users to filter content in a view but I'm having trouble saving it. I'm trying to allow my users to control their own news feeds.
I've tried looking around for a module to do this and I've been playing around with views for a while but I can't seem to hack something thing that does what I outlined. Any help would be appreciated. Thanks.
Answer: If your view is using exposed filters, there is a "Remember search" option in the View configuration. This stores the search parameters in the session, and should give you the expected effect. Admittedly, I'm thinking of Views 2, and I just assume the setting is available in Views 3 as well.
Comment: If this stores it in the session, what if the user logs out? Will this require them to rest their settings?
Comment: In my case that is not an issue, so I had never even noticed, but I just tried, and the answer is yes. Logging out removed the Views settings.
Answer: Since my initial answer doesn't persist the search between user-login/logout, here's a solution that will require significantly more work, but is permanent.
Create a module, with a two column table. One for uid, and one for serialized search parameters.
Implement hook_views_query_alter().
In this hook, you can add the SQL needed to both fetch old data, and update with new. You should be aware however that such a solution can quickly become a heavy DB-burden, as you potentially add a lot of writing to the DB.
Comment: This is a little to complicated for me to do
Answer: The Views Saved Searches module will save the filters used even if they log out. Here is a quote about it (from the module's project page):

... allows you to save your current configuration of exposed filters for later use. This can be especially useful for Views with a lot of exposed filters.
Whenever a View is changed, all saved searches for that View are deleted, to prevent corruption. If the user has JavaScript enabled, the saving and deleting process happens through AHAH, and the new section is displayed below the exposed filters section. When JavaScript is disabled, the new section is displayed above the exposed filters section.


Error installing Vips

Question: I am trying to install Vips, I've downloaded the latest files:
wget http://www.vips.ecs.soton.ac.uk/supported/current/vips-7.30.0.tar.gz
wget http://www.vips.ecs.soton.ac.uk/supported/current/nip2-7.30.1.tar.gz
And on ./configure I get:
configure: error: Package requirements (glib-2.0 >= 2.6 gmodule-2.0 >= 2.4 libxml-2.0 gobject-2.0) were not met:

No package 'glib-2.0' found
No package 'gmodule-2.0' found
No package 'gobject-2.0' found

However I have tried yum install glib2 and rerun ./configure but get the same error.
Am I doing something wrong?
Answer: sudo yum install glib2-devel and try again.

Error installing Vips


Correct way to render a modules output through a template?

Question: I usually do exclusively functionality on a site, and as such I'm familiar with php and Drupals APIs, but I'm mostly lost in the theming layers.
I find myself with these pieces of code, that "work", but doesn't look quite right to me.
// ------ Actual USE of #theme -------
$block->content = array(
  '#theme' => 'MODULE_more_information',
  'dataA' => $dataA,
  'dataB' => $dataB,
  'dataC' => $dataC,
);
return $block;

// ------ hook_theme to attach the #theme to a template -------
function HOOK_theme($existing, $type, $theme, $path) {
  $base = array(
    'render element' => 'element',
    'path' => drupal_get_path('module', 'HOOK') . '/templates',
  );
  $theme = array(
    'MODULE_more_information' => array(
      'template' => 'MODULE-more-information',
    ) + $base,
  );
  return $theme;
}

// ------ Actual template -------
<?php
extract($element);
?>

<?php print $dataA ?>

<?php print $dataB ?>

<?php print $dataC ?>

What gives me the idea that something is amiss is that the author manually runs extract(), which I've never seen a template do before.
Canonical examples of how to do this "right"?
Answer: To be honest, aside from the use of extract() (which is obviously bad in and of itself), I think the code is perfectly valid, and respectful of Drupal's processes/conventions.
There are two different ways to pass variables to theme functions in Drupal 7, both provided as an argument to a theme definition in hook_theme(). They are variables and render element.
I can't possibly explain the difference between these two better than the hook_theme() docs:

Use 'render element' if you are theming a single element or element tree composed of elements, such as a form array, a page array, or a single checkbox element.
Use 'variables' if your theme implementation is intended to be called directly through theme() and has multiple arguments for the data and style; in this case, the variables not supplied by the calling function will be given default values and passed to the template or theme function.

In your case you're theming a render array, rather than calling theme() directly, so render element is the one to use.
When you use a #theme property on a render array, the entire element (in your case $block['content']) is passed through to the theme function/template file. The name of the variable that you have access to in the template file is the name you have given to render element in the hook_theme() definition.
So if your hook_theme() defines 'render element' => 'my_lovely_var', you'll have access to the render array as $my_lovely_var in the template file.
I suspect that the author of your code was just taking a small shortcut so he/she didn't have to access the $element array directly with code. Without the use of extract() the template file would/should have looked like this:

<?php print $element['dataA'] ?>

<?php print $element['dataB'] ?>

<?php print $element['dataC'] ?>

Just for posterity, this is the same code re-written to make use of variables instead:
The same code using variables would look like this:
// ------ Actual USE of #theme -------
$args = array('dataA' => $dataA, 'dataB' => $dataB, 'dataC' => $dataC);
$block->content = array(
  '#markup' => theme('MODULE_more_information', $args)
);
return $block;

// ------ hook_theme to attach the #theme to a template -------
function HOOK_theme($existing, $type, $theme, $path) {
  return array(
    'MODULE_more_information' => array(
      'template' => 'MODULE-more-information',
      'variables' => array('dataA' => '', 'dataB' => '', 'dataC' => ''),
      'path' => drupal_get_path('module', 'HOOK') . '/templates'
    )
  );
}

// ------ Actual template -------

<?php print $dataA ?>

<?php print $dataB ?>

<?php print $dataC ?>

You could even use the following, slightly different, method to build up the block content when using variables:
$block->content = array(
  '#theme' => 'MODULE_more_information',
  '#dataA' => $dataA,
  '#dataB' => $dataB,
  '#dataC' => $dataC,
);
return $block;

This second method makes the block more re-usable as the theme function hasn't already been called, and other parts of the system can still alter the individual elements of the block.
Comment: Cool, thanks :) When _would_ it be appropriate to use a `render element`? What is it?


Comparing differences across conditions

Question: I measured a variable during pre- and post-sessions and my research question is whether the change from pre to post is different across various conditions (e.g. (c=1,a=1), (c=2,a=1), (c=1,a=2), (c=2,a=2) etc) and if so, across which.
How can I test whether the differences between pre- and post are significantly different across conditions?
This may sound easy, however, the pre- and post-session measurements are not paired in any meaningful way. Hence, using an arbitrary pairing to compute the differences and then performing an ANOVA for the differences across conditions does not make full use of the dataset.
Alternatively, I think a multi-way ANOVA could be applied with factors (pre/post), c and a (for the above example). In that case, however, it is unclear to me how to figure out across which of the conditions the change from pre to post is significantly different. Posthoc pairwise comparisons would not directly provide such information.
Thank you very much in advance for any help!
Comment: I'm really unclear on your setup. Most critically, if you have a single variable measured pre- and post-treatment, how is it that your data are not paired in a manner appropriate for a paired t-test?
Comment: Thanks for the reply. The variable is measured during 20 trials pre and 20 trials post but there is no relation between note first trial pre and the first trial post etc. Hope its clearer now.
Comment: Your data seems like it must be at least theoretically paired, but that the pre- and post-treatment measurements that correspond to a particular subject are unmatched. Is that right?
Comment: For each subject there are 20 measurements pre (within a short time) and 20 measurements post (again within a short time). The question is whether the difference pre-post varies significantly across different factors.
There are two factors: a and c; both of which are binary. For each subject there are always measurements for a=0 and a=1 but not necessarily for c=0 AND c=1. For some subjects only c=0 and for others only c=1 was measured. In addition there are relatively few subjects and therefore I would like to make use of the 20 pre and 20 post measurements.
Thanks for the help!
Comment: And are these 20 measurements per subject time-independent (so that it might make sense to average them and you are taking 20 measurements to measure one "thing"), or time-dependent?
Comment: Yes, it makes perfect sense to average them however then I have only one value per subject (for pre and post) and the dataset doesn't contain many subjects. Therefore, I'd like to make use of the 20 measurements.
Answer: Based on your statement, I think paired t test can be done to assess the pre and post session measurements as the values belong to the same sample.
Comment: Thanks for the response but I am interested in testing whether post minus pre changes significantly across conditions.
Comment: If you want to check whether there is significant difference between the Pre treatment values and Post treatment values then paired t test is the solution.
Comment: Yes but I want to check whether the difference between pre and post varies with conditions in a situation where there is no meaningful pairing between the pre and post samples.
Comment: Do you mean to say that pre and post samples are independent? i.e. A in pre sample is independent of A in post sample. If yes, then use manova on 2 inputs(pre and post, A and B and C...) and one output.
Answer: Someone more experienced than me can probably weigh in more usefully, but to me this sounds like a difficult data set to work with. That your data are unpaired, despite a research question that seems based in within-subject differences, could do a lot to mask the actual effect of each treatment. I agree that arbitrarily pairing data is not desirable in this case.
Assuming that I understand the data you have correctly, I think that your best bet would be to do unpaired, two-tailed t-tests on the pre- and post-treatment measurements of your variable for each condition. This covers a "did the treatments have any effect?"-style question in a fairly typical way.
Comparing between conditions seems a lot iffier to me given what you have described. I'm not clear on how subjects were assigned to different conditions, but when only some subjects have measures for condition c, and without being able to take within-subject variation into account, it's hard to conclude that differences are truly due to the conditions themselves.
If comparison across conditions is necessary, I would probably do the t-tests described above and then a naïve comparison of the measured pre/post differences for those conditions which met your significance threshold (something like: a1 saw an average difference of 5 measured units from pre to post while c1 saw an average difference of 3 measured units, both significant at alpha=0.05).
This may not be the answer you are hoping for, but the quality and nature of data always puts a ceiling on how much that data can tell you. I could easily be making a wrong assumption (or assumptions) about your data and your study design, but with stats it pays to be conservative when in doubt.

Comparing differences across conditions


Double and Triple Tonguing Syllables?

Question: Brass and Woodwind players use specific syllables like ta-ka-ta for triple tonguing...
I would like to know:

What are the most common used syllables for double and triple tonguing?
Are they different for Woodwinds and Brass instruments?
Do they use different syllables depending on the tempo of the piece, or do they work equally with any tempo?
...or are there even "common" syllables that "everyone" uses?
Comment: a) Ithink takata is the most commonI use for triplets
I use tkt, tgd or  tgr depending of the situation  (Bariton and Euphonium)
Comment: Even Bach used it, in his famous   Takata and Fugue  (sorrynotsorry)
Answer: I can only speak for the brass side of things, but the standard double-tonguing syllables are either "ta-ka" or some variant thereof. Variants include "ta-ga" or "da-ga," depending on the musical context. For instance, sometimes the "ka" syllable is too accented, so players conceptualize "ga" instead. Similarly, the "ta" may be much stronger than the "ka/ga," leading some players to conceptualize this as "da."
As for triple tonguing, I've always used "ta-ka-ta" (with the same variant caveats as above), but some players swear by "ta-ta-ka."
In my experience, the only reason tempo would change this is if the tempo is so slow that I don't even need to double/triple tongue. In such cases, I just stick with single tonguing.

Double and Triple Tonguing Syllables?


Upper bound for largest eigenvalue of non-negative matrix

Question: a) Show that the largest eigenvalue of a non-negative matrix is upper bounded by its largest row sum.
b) For a non-negative matrix $M$, show that the largest eigenvalue of $M$ is upper bounded by the largest row sum of $DMD^{-1}$, for any positive diagonal matrix $D$.
I've tried multiplying by one of the eigenvalues and making comparisons, but i couldn't find any that is true only for the largest row sum. Also, i've tried multiplying the matrix by the only 1's vector, since that would result on the vector with the row sums, but i didn't find any useful inequalities. The matrix may not be symmetric, so we can't assume it has a basis of eigenvectors.
Answer: (a) Let $\lambda$ be an eigen value of the non-negative matrix $A.$ Then $Ax=\lambda x \implies \lambda |x_i|= |\sum_{j=1}^n a_{ij}x_j|\leq (\sum_{j=1}^n a_{ij})\max_j|x_j|\implies \lambda \max_i |x_i|\leq \max_i (\sum_{j=1}^n a_{ij})\max_j|x_j|\implies \lambda\leq\max_i (\sum_{j=1}^n a_{ij})$
(b) Again $\lambda$ be an eigen value of the non-negative matrix $A.$ Then $Ax=\lambda x \implies AD^{-1}Dx=\lambda D^{-1}Dx\implies DAD^{-1}Dx=\lambda DD^{-1}Dx\implies DAD^{-1}y=\lambda y$ for $y=Dx.$ Same proof as (a) follows because $DAD^{-1}$ is non-negative for $D$ positive diagonal.