Put a wrapper div around every second row in drupal view

Question: Hi there I am trying to use a views template override to put a wrapper div around every group of two rows. If the last group only has 1 row ( say if there were 5 rows total ) I want to end the wrapper div.
I found some code for this but it's not working I am getting zero output from this I can see my comment tag but that it.

<?php
$group_nr = 1;                  // first group number
$last_row = count($rows) -1;    // last row
$wrapper  = 2;                  // put a wrapper around every 2 rows
?>
<?php foreach ($rows as $id => $row): ?>
<?php if ($id % $wrapper == 0) {print '
'; $i = 0; $group_nr++; } ?>
<?php print $row; ?>
<?php $i++; if ($i == $wrapper || $id == $last_row) print '
'; ?>
<?php endforeach; ?>

Any idea what I am doing wrong
My template is called views-view--homepage-awards--block-2.tpl.php
I want my output to look like this

row1

row2

row3

row4

row5

Any help would be greatly appreciated.
Comment: I am not saying this is not possible, but I am curious, what is your end goal? What are you trying to accomplish by wrapping the rows this way?
Answer: This should accomplish it:
<?php
  $last=count($rows) - 1;
?>
<?php foreach ($rows as $id => $row): ?>
  <?php if (!($id & 1)): // if this an even row id, open the
 ?>

  <?php endif; ?>
  <div<?php if ($classes_array[$id]) { print ' class="' . $classes_array[$id] .'"';  } ?>>
    <?php print $row; ?>

  <?php if ($id==$last || ($id & 1)): // if this the last or an odd row id, close the
 ?>

  <?php endif; ?>
<?php endforeach; ?>

It'll wrap each group of two rows with a div with a class of row and make sure if it's an odd number that the final div is closed.
Now, if you want to remove all the classes from those inner rows that Views inserts, then you just need to clean them up or out of that obvious if in the middle.
CAVEAT:  If you have done anything with Views pre_render()ing or other similar hooks that have deleted any of the rows out of the results and not reset the ids to be consecutive, this logic will most probably fail.


Reconhecer apenas a primeira letra da palavra PYTHON

Question: Estou fazendo um programa conversor de temperaturas para um trabalho, e estou com uma dúvida
tipo_temperatura = input('Qual tipo de temperatura deseja escolher?\nCELSIUS [C]\nFAHRENHEIT [F]\nKELVIN [K]\nESCOLHA: ').strip().upper()
    if tipo_temperatura not in ['C', 'F', 'K']:
        raise ValueError('Tipo de temperatura inválido')

Eu queria saber qual comando terei que usar para caso o usuário digite por exemplo "Celsius", o programa reconheca que a primeira letra foi "C", e então ele não irá reconhecer como um ValueError, e sim como resposta "C", continuando o programa
Comment: Use o `startswith`, sempre retorna True se a string começa com o prefixo que definiu nesse caso mesmo que digite por extenso **FAHRENHEIT** vai pegar apenas a primeira letra. `if not tipo_temperatura.startswith(['C', 'F', 'K']):`
Comment: Se o usuário digitar `Cachorro` deve reconhecer como Celsius? Se digitar `Falcão` ser `F`? Com startswith palavras que comecem com C, F e K serão aceitas, pra resolver cheque ambos, abreviação e palavra inteira, `while True: tipo_temperatura = input('Qual tipo de temperatura?').strip().upper()
 if tipo_temperatura not in ('C', 'F', 'K', 'CELSIUS', 'FAHRENHEIT', 'KELVIN'): print('Temperatura invalida') else: ` e depois use o [***slice da string***](/a/536620/3635) nativo do Python para usar em comparações posteriores: `tipo_temperatura[0]`. Exemplo: https://ideone.com/67ECXC
Answer: Uma maneira de resolver o problema é pegando o índice zero da variável tipo_temperatura. Um exemplo de como fazer isso seria:
print(tipo_temperatura[0])

Uma outra maneira é utilizando a função str.startswith(prefix[, start[, end]]) da seguinte forma:
tipo_temperatura.startswith(('C','F','K'))

Segundo a documentação

prefixo também pode ser uma tupla de prefixos a serem procurados

Repare que neste caso o argumento prefix da função startswith é o valor ('C','F','K') [que é a declaração de nossa tupla].
Para mais informações consulte a documentação.
Answer: Acredito que uma solução elegante pra esse problema possa ser:
UNIDADES_VALIDAS = ['C', 'F', 'K']

TEXTO_DE_INPUT = '''
Qual tipo de temperatura deseja escolher?

CELSIUS [C]
FAHRENHEIT [F]
KELVIN [K]

ESCOLHA: '''

input_temperatura = input(TEXTO_DE_INPUT).strip().upper()
unidade_escolhida = input_temperatura

if len(input_temperatura) > 1:
    unidade_escolhida = input_temperatura[0]

if unidade_escolhida not in UNIDADES_VALIDAS:
    raise ValueError('Tipo de temperatura inválido')

# Agora, faça o que precisa com a variável `unidade_escolhida`
...


How to use function - CAST(datetime as date) of SQL Server in sqlalchemy?

Question: I have a table which has columns - id(int), date(DateTime), value(float). I wanted to output daily average group by date of all rows which has id=2.
I wrote following sql query for that and query was working fine:
select cast(date as date), avg(value) from table where id=2 group by cast(date as date)

For the same problem, if I wanted to execute in sqlalchemy, I was using following expression :
>> from sqlalchemy import sql, types
>> x = sql.cast(Table.date, types.Date)

But when I tried executing x, I got following error :
>> x.execute()
ArgumentError: Not an executable clause: CAST(Table.date AS DATETIME)

which means that SQL Server is considering that types.Date as DateTime.
Please ignore the ArgumentError. What I am trying to focus on is that internal sql query is using CAST(Table.date AS DATETIME) rather than CAST(Table.date AS DATE)
Is there any way so that I can convert DateTime to Date in sqlalchemy?
Comment: You should use `sqlalchemy.func.cast` instead of `sqlalchemy.sql.cast`.
Comment: I tried using it. I got this error :-

`ProgrammingError: (ProgrammingError) ('Invalid parameter type.  param-index=0 param-type=Date') 'SELECT cast(Table.date, ?) AS cast_1, avg(Table.value) AS avg_1 FROM Table AS Table_1 WHERE Table_1.id = ? GROUP BY cast(Table_1.date, ?)' [Date(), 2, Date()]`
Answer: Following is wrong with you code:

you cannot execute a clause. You need to have a statement or a query (see below). This is the reason for the error that you get originally.
indeed, if you cast to sa.Date, mssql engine will cast to DATETIME. I am not entirely sure why this is, but i suspect it is because older versions of MSSQL did not have a separate DATE-only datatype. To solve this, simple cast it to the DATE datatype found in mssql dialect.

The code below should work. I do not have mssql right now, but I do show the compilation of the SQL statement for mssql instead:
from sqlalchemy import create_engine, Column, Integer, Float, Date, DateTime, func
from sqlalchemy.dialects.mssql import DATE
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base

# @TODO: replace with your connection string
engine = create_engine('sqlite:///:memory:', echo=True)
Session = sessionmaker(bind=engine)
session = Session()

Base = declarative_base()

class MyTable(Base):
    __tablename__ = 'my_table'
    id = Column(Integer, primary_key=True)
    date = Column(DateTime())
    value = Column(Float())

Base.metadata.create_all(engine)

def get_mssql_sql(qry):
    from sqlalchemy.dialects import mssql
    dialect = mssql.dialect()
    return str(qry.compile(dialect=dialect))

# DATE = Date  # @note: this will not work in MSSQL (shows problem-2)
q = (session
     .query(func.cast(MyTable.date, DATE), func.avg(MyTable.value))
     .filter(MyTable.id == 2)
     .group_by(func.cast(MyTable.date, DATE))
     )
print(get_mssql_sql(q.statement))

# in your code, just run below to execute:
rows = q.all()


JavaScript exibir data do dia anterior ao atual

Question: Tenho seguinte script que funciona certinho, porém na virada do mês ele não "monta" corretamente a data, por exemplo hoje, ele está mostrando a data 20181000

var today = new Date();
var dd = today.getDate()-1;

var mm = today.getMonth()+1;
var yyyy = today.getFullYear();
if(dd<10)
{
    dd='0'+dd;
}

if(mm<10)
{
    mm='0'+mm;
}
var data_ok = today = yyyy+''+mm+''+dd;

var filename = 'ldrel_'+data_ok+'.txt'
Answer:

var hoje = new Date();

var ontem = new Date(hoje.getTime());
ontem.setDate(hoje.getDate() - 1);

var dd = ontem.getDate();
var mm = ontem.getMonth()+1;
var yyyy = ontem.getFullYear();

if(dd<10)
{
dd='0'+dd;
}

if(mm<10)
{
mm='0'+mm;
}

var data_ok = yyyy+''+mm+''+dd;

var filename = 'LDREL_'+data_ok+'.txt'

console.log(filename);

A tarefa da instrução new Date() é criar um local na memória para todos os dados que uma data precisa armazenar. O que falta dessa tarefa são os dados - que data e hora são colocadas nesse ponto da memória. É aí que entram os parâmetros.
Se deixar os parâmetros vazios, o JavaScript considera que você deseja a data e hora atuais para esse novo objeto date.
Para criar um objeto date para uma data e hora especifica, você tem cinco maneiras de enviar valores como um parâmetro à função construtora new Date():

new Date("mês dd, aaaa hh:mm:ss")
new Date("mês dd, aaaaa")
new Date("aa,mês,dd,hh,mm,ss")
new Date("aa,mês,dd")
new Date(milissegundos)

A maior parte dos métodos de um objeto date serve para leitura de partes da informaç]ão de data e hora e para a mudança da data e hora armazenadas no objeto. Essas duas categorias de métodos são facilmente identificáveis, pois começam com a palavra-chave get ou set
objDate.getTime() - milissegundos desde 1/1/70 00:00:00 GMT
objDate.setDate(val) - dia dentro do mês (1-31)
objDate.getDate() - data dentro do mês
Date
Comment: Legal, realmente seu script está capturando a data correta, como eu faço para o resultado final apareça somente LDREL_20180930.txt  ?
Comment: @EdvaldoLucena Do mesmo jeito que vc fez no seu script, veja resposta editada. Não esqueça de marcar como aceita se resolveu seu problema!
Answer: Tem uma forma bem mais simples de se fazer isso usando o setTime().
Esse comando arruma as horas do objeto data a sua escolha, aceitando parametros de -1 a 24. De 0 a 23, ele arrumaas horas corretamente, entretanto, com o 24 ele passa para o dia seguinte, e com o -1 para a ultima hora do dia anterior. Ou seja.
var hoje = new Date();
var ontem = new Date().setHours(-1);
ontem = new Date(ontem) // o comando setHours devolve a data em milisegundos

var dataformatada = ontem.toLocaleDateString('pt-BR'); // '30/09/2018'
dataformatada = dataformatada.split('/').reverse().join('') // '20180930'
var filename = 'LDREL_'+dataformatada+'.txt'

console.log(filename); // LDREL_20180930.txt

Comment: O retorno de `toLocaleDateString` varia conforme o locale do browser, seria melhor especificar o locale para garantir que sempre usará o formato brasileiro: `toLocaleDateString('pt-BR')`. O meu browser, por exemplo, está setado com `en-US` (sei lá pq está em inglês, nem lembrava disso) e `toLocaleDateString()` retorna no formato M/D/YYYY (9/30/2018)
Comment: Obrigado pelo apontamento, vou ajustar.


FireFox gets ns_error_net_interrupt when clicking on loaded page

Question: FireFox is connecting to my website, but accessing already visited pages would randomly  not connect resulting in a

Secure Connection Failed

Chrome and Microsoft Edge are not having that problem.
What is strange is that reloading the page is also not working. I need to force reload the page by way of using Shift and reload - and then I get the page back, and will always load when using shift and reload.
How can I prevent this from happening?
The html pages are pre-compresses Brotli files served by an Apache 2.4.57 server.
<IfModule mod_expires.c>
    ExpiresActive On
    ExpiresDefault                  "access plus 1 day"
    ExpiresByType text/asp          "now"
    ExpiresByType text/html         "now"
    ExpiresByType text/css          "access plus 1 day"
    ExpiresByType video/x-m4v       "access plus 15 days"
    ExpiresByType image/jpg         "access plus 5 days"
    ExpiresByType image/jpeg        "access plus 5 days"
    ExpiresByType image/gif         "access plus 5 days"
    ExpiresByType image/png         "access plus 5 days"
    ExpiresByType application/pdf   "access plus 1 month"
    ExpiresByType text/x-javascript "access plus 1 month"
    ExpiresByType application/x-shockwave-flash "access plus 1 month"
    ExpiresByType image/x-icon      "access plus 1 month"
</IfModule>
<FilesMatch "\.(html)$">
    FileETag None
    <IfModule mod_headers.c>
        Header unset ETag
        Header set Cache-Control "max-age=0, no-cache, no-store, must-revalidate"
        Header set Pragma "no-cache"
        Header set Expires "access plus 3 hours"
    </IfModule>
</FilesMatch>

I am using these default Connection Settings in FireFox:

SSL info when the connection is not made and I get a ns_error_net_interrupt error:

SSL info after reloading that same page (using Shift and reload) -- it works again:
Answer: It seemed like FireFox did not like to reconnect onto pages that expired.
    ExpiresByType text/asp          "now"
    ExpiresByType text/html         "now"

When changing it to
    ExpiresByType text/asp          "access plus 3 seconds"
    ExpiresByType text/html         "access plus 3 hours"

things started working.


Como efetuar o @Override de uma function em AngularJs?

Question: Eu tenho um controller abstrato com o angularjs.
 Nele tenho dentre outras coisas, uma toolbar de pesquisa.
 Gostaria de usar esse input de pesquisa em todos os controllers que herdem do controller pai. sendo acionados através de um "ng-change".
function IndexCtrl() {
  var vm = this;
  //Objects
  vm.searchText = '';

  //Methods
  vm.search = search;

  function search(search) {

  }
}

function TesteCtrl() {
    var vm = this;

    //Methods
    vm.search = search;

    function search(search) {
      console.log(search);
    }
}

Quais alternativas de implementação eu tenho, quando ng-change do controller pai for disparado, o método do controller filho for acionado(quando estiver em uso)?
Answer: Uma alternativa para resolver seu problema seria a utilização de sobrecarga.
Ex: Sobrecarga – Número de parâmetros
Mais uma vez vou utilizar o método "apply" do Js para resolver essa questão, como a linguagem mexe muito com prototipos e construtores, nada mais inteligente do que usar esse método de escopo. A idéia que tive foi usar uma função como uma função e ao mesmo tempo como um objeto que segura suas próprias propriedades.
var Person = {
Class: function(){
    //Private
    var name = ''

    //Public
    this.name = function(){
        return this.name[ arguments.length ].apply( this, arguments )
    }

    this.name[0] = function(){ return name }
    this.name[1] = function(n){ name = n }
    this.name[2] = function(a, b){ name = a + " " + b }
    }
}

Aqui eu crio uma função ( método ) com nome "name" e crio mais 3 propriedades dela que são: 0, 1 e 2. São números, mas ainda sim são propriedades do método name. O que a função principal vai fazer é ver quantos parâmetros ela tem e vai chamar a sua propriedade correspondente, que nada mais é que outro método que vai ser executado no mesmo contexto que a name e terá os mesmos parâmetros que a name.
Logo:
var Edu  = new Person.Class

Edu .name() //  ''
Edu .name('Eduardo')
Edu . name() // "Eduardo"
Edu . name('Eduardo', 'Ottaviani')
Edu . name() // "Eduardo Ottaviani"

Não é porque eu tive essa idéia não, mas eu considero esta a forma mais elegante de sobrecarga de operadores até agora. Talvez não seja a mais eficiente, não testei sua velocidade em relação as outras técnicas. Se for mais lenta, creio que não seja perceptível.
Fonte.: https://javiani.wordpress.com/2010/04/17/overload-em-javascript/


Relative primes

Question: What is the number of integers between 1 and 60 that are relatively prime to 60? I know that the answer is 16, but how do I go about finding the relative primes using a quick process?
Comment: If your using a computer, a quick recursion using the Euclidean algorithm will answer this question.
Answer: You can use the Euler's totient, see http://en.wikipedia.org/wiki/Euler%27s_totient_function for how it works.
By the way, the answer is 16, not 15 (if you include 1).
If moreover you want to know who are those numbers, I guess you should list all the primes between 1 and 60 that does not appear in the factorisation of 60 ; then all the numbers you are looking for are made from those primes.
Comment: An upvote from me if it weren't for the Wikipedia link. Someone could vandalize the Wikipedia article for the sole purpose of making you look foolish.
Comment: In @Bernard 's answer, the 16 relative primes include 49. So, starting with a list of primes between 1 and 60 less those in the factorization of 60 would *miss* 49.
Answer: Erastothenes's sieve. The number of integers relatively prime to $60$ is equal to $\varphi(60)=\varphi(2^2)\,\varphi(3)\,\varphi(5)=16$. Here is the list:
$$\bigl\{1,7,11,13,17,19,23,29,31,37,41,43,47,49,53,59\bigr\}.$$
Comment: I'm not sure the Eratosthenes sieve is the most relevant thing here. Still, thumbs up from me.
Comment: For a small value of the modulus  like that, it's the simplest way to get the list of units modulo $60$, and it's easy to program.
Answer: Possibly the principle of inclusion-exclusion (PIE) is asked for here as this usually shows up when the Euler totient is computed. For $n$ having three prime divisors $p,q,r$ the corresponding Hasse diagram consists of nodes for all subsets $Q\subseteq \{p,q,r\}$ representing multiples of $\prod_{m\in Q} m$ less than or equal to $n$ with the empty product having value one and inclusion of the node $P$ in $Q$ if $Q\subseteq P$. Assigning weight one to the top node that corresponds to $\{\}$ and for the other nodes $Q$ the weight that makes the weights of the subset spanned by the $Q$ and the top node sum to zero yields
$$n-n\sum_{\{p'\}\subseteq \{p,q,r\}}\frac{1}{p'}+n\sum_{\{p',q'\}\subseteq \{p,q,r\}}\frac{1}{p'q'}-n\sum_{\{p',q',r'\}\subseteq \{p,q,r\}}\frac{1}{p'q'r'}$$
which is
$$n\left(1-\frac{1}{p}\right)\left(1-\frac{1}{q}\right)\left(1-\frac{1}{r}\right).$$
With $n=60$ this gives $$60\times\frac{1}{2}\times\frac{2}{3}\times\frac{4}{5}
= 16.$$
Answer: You can just use Euler's totient function. Given a prime $p$, $\phi(p^\alpha) = (p - 1)p^{\alpha - 1}$. The function is multiplicative, so $\phi(p^\alpha q^\beta) = \phi(p^\alpha) \phi(q^\beta)$.
Since $60 = 2^2 \times 3 \times 5$, you calculate $$\phi(60) = \phi(4) \phi(3) \phi(5) = 2 \times 2 \times 4 = 16.$$
To verify this answer, let's count up the primes from 7 to 59, and throw in there the odd composite numbers not divisible by 3 or 5, to get: 1, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 49, 53, 59; this is a list of 16 integers.
I suppose either way is a quick enough process for small numbers. But if the numbers get just a little bit bigger, Euler's totient function is much faster: try for example to count up the integers between 1 and 5168743489 that are relatively prime to 5168743489.

Relative primes


Making Sense of Blues Soloing; differentiating major/minor pentatonics

Question: Quarantine has allowed ample time for musical exploration. I'm a classically trained pianist studying music in college, and I'm using this extra time to be immersed in and learn how to play the blues.
I've transcribed a handful of pieces and I can play them in full, but I fail to understand certain theoretical aspects of each. I expect this post to be quite long...
The first song I transcribed was "Marie" by Otis Spann.

The most confusing aspect of this song is its mixing of major/minor blues scales. Even in the opening riffs, the song seems to switch between the two. The first little lick uses notes G, A, and C, going into a C7. The A puts it in the C major pentatonic/major blues scale category. Another 2 licks incorporates notes all from the C major blues scale, then he uses a lick that uses Bb instead of A (0:07). At what point is this just minor blues with an added sixth, and at what point is it switching between the major and minor blues scale. And, if it is all minor blues scale with an added 6th, how does one explain the constant use of sliding from Eb to E almost every time that note is hit (since E is not in the C minor blues scale). Is this merely a blue note leading into a chord tone?
Another point in this song that perfectly showcases this mixture is at 0:24. As the first 12 bar blues sequence goes into the V, Otis uses a lick that goes up chromatically (hitting each note in conjunction with a high C). The notes hit are C, D, Eb, E, F, F#/Gb, G. It's almost as if both the major/minor blues scales are combined into one, composite, chromatic scale. How can this be explained?
I understand that blues is essentially a study in mixing major and minor simultaneously, but I'm confused about the how and the when; how do I know when to mix these two ideas, when does it get away from one or the other and turn into one seamless mixture?
Another song that mixes the major and minor blues scales is "Same Old Blues" by Freddie King. I worked this out on piano first and then on guitar when the bends proved... kind of impossible on piano. lol

I'm specifically interested in the solo section starting at 1:56
The chord progression of this one is a little more nuanced. The solo section is as follows: D, F#7, Bm /, D, F#7, Bm, Am7, D7, G, G#dim, D, D/C, B7, E7, A7, D
The solo is all in the D major blues scale until the second D chord hits, the one before the D/C (at 2:24). At this point, it switches quite abruptly to D minor pentatonic, incorporating the 7th (C) instead of the 6th (B), and making heavy use of the minor blue note Ab. The remainder of the solo is in this minor blues scale.
Why does this work, and how can it be understood in a way that can be applied to my own playing? I understand it was most likely just intuition on Freddie's part, but because I don't have that intuition, that doesn't help me learn and progress from the example.
One last example that I'd like to add is the piano solo in Jeff Beck's "Blues Deluxe" performed by the great Nicky Hopkins.

The solo runs from 2:37 to 4:47, and it's a banger. It constantly seems to switch between the major and minor blues scales, incorporating the 6th and lowered 7th left and right. I've found that it's common to switch from the major blues scale on the I to the minor blues scale on the IV, and that happens here; Nicky also uses the bVII chord on the IV, something widely used in almost every bluesy Elton John track. That said, there seems to be some other forms of blues-based trickery going on here, and I can't make sense of the seemingly mixed scales and how to synthesize that into an understandable and usable format.
I hope this all makes sense. I guess some smaller-scale questions would be:
- Can the blues idiom of hitting the minor third and major third in quick succession be be interpreted as a blue note in the minor blues scale or is it a switch to the major blues scale, since the major blues scale contains the major third (as well as the minor third)?
- Does adding the 6th and 9th (or 2nd) scale degrees in a minor blues scale make it major, or is it simply a means of changing color/tone?
And these lead to the larger question of:
- How do I understand the mixture of the major and minor blues scales in an applicable way?
It could just come down to more transcription and familiarization with the blues in the pursuit of this major/minor intuition. It could also be that the major and minor blues scales are completely interchangeable over a major blues harmony and can thus be used and switched at any point, whether separately (like "Same Old Blues") or in conjunction (the other two). Or maybe there is a more concrete explanation.
If you made it this far, thank you so much for your time and I look forward to your answer!
~Carson
Comment: @piiperiReinstateMonica In questions of music theory it's generally safe to take "Why does X work?" as shorthand for "What is the theoretical justification for this musical choice, and how can I incorporate that concept into my own compositions and improvisations?" The OP has clearly done their homework, including noting the harmonic context (`I've found that it's common to switch from the major blues scale on the I to the minor blues scale on the IV`) and the emotional effect of the phrases in question.
Comment: Frankly, I'm not sure what you mean by a "harmonic potential field" or the distinction between "what it does" and "why it works" (which to me are both synonyms for "its musical function"). I find OP's question perfectly legible; if you can see a way to make it clearer, propose an edit.
Comment: If you find yourself asking "why does X work", you don't know enough about the domain. "Why does scratching my back work?" What do you mean "work"? You should be asking "what does it _do_ to _something_". And when you get that question answered, then you might be closer to figuring out _how_ it does what it does to that something. What is the thing that's being manipulated here? It's the harmonic context. Do you have practical musical ways to test and feel what the harmonic context is in your mind at each point in time? The context is in your mind, so how do you test your feelings?
Comment: @Max The question should be, what does "switching from the major blues scale on the I to the minor blues scale on the IV" do (if that's the main musical device in question here). Not why it "works". If you can explain what its effects are to the "harmonic potential field" around a tonic, and you can reproduce those effects at will in any key you want, what more is there to understand? "What does it do" is the real question. Switching between scales doesn't feel like a description of that. A scale is not harmony. Think about all the harmonic turns that can be done with a single major scale.
Answer:
How do I understand the mixture of the major and minor blues scales in an applicable way?

The short answer is that the mixing of major and minor tonalities is the essence of blues.
Many people draw a distinction between "major" and "minor" blues scales, where in C the major blues scale is A C D E♭ E G and the minor blues scale is C E♭ F G♭ G B♭. Generally speaking, both of these scales are available when playing a blues (or even a bluesy song) in C.
Another way of thinking about this is that there is only one blues scale, namely the "minor" blues scale 1 ♭3 4 ♭5 5 ♭7. Notice that A minor is the relative key to C, so the two blues scales available in C are really just the (minor) blues scale from the parallel minor and the (minor) blues scale from the tonic. I will refer to these as the vi blues scale and the i blues scale, respectively, but try to include both names to be helpful.
Now, as you note, there is a 12(ish)-bar song form called the blues. Both the A and C blues scales are available when playing a blues in the key of C, but there are certain points in the form where one or the other may be more appropriate. A common newbie mistake is to play an E♮ on bar 5, where we have the incompatible chord F7. This comes from misapplying the A (C major) blues scale.
In general, as you have observed in the Jeff Beck example, we favor the i (minor) blues scale over the IV7 chord. The vi (major) blues scale works nicely over the I7 chord, particularly at the resolution point in bar 11, whereas the i blues scale confers a tenser sound when played over the I7 chord.
Finally, there's no rule requiring us to use exclusively blues scales when playing the blues. Notice that neither of the blues scales in C contains the note B, but that's the leading tone and sounds quite lovely when played over the G7 chord on bar 10; it's also used in plenty of classic blues guitar licks. You can use mixolydian scales, triad pairs, or any other jazz techniques you know about to lend variety to your blues playing, bearing in mind that the more you deviate from the blues scale, the more your sound moves from a "classic" blues sound to a modern, "jazz" idiom.

Can the blues idiom of hitting the minor third and major third in quick succession be be interpreted as a blue note in the minor blues scale or is it a switch to the major blues scale, since the major blues scale contains the major third (as well as the minor third)?

I would say it's the latter: It's a lick drawn from the parallel minor's blues scale. If you write the chord changes into your transcription, you'll notice that this pair of notes rarely appears over the IV7 chord since the major third becomes the major seventh of this chord, as above.
But another interpretation comes from noticing that when singers or horn players approach the blues, they will often bend the pitch to play a note that sits just between scale degrees ♭3  3, or ♭5 and 5. This sounds quite melancholy and beautiful. A textbook example occurs at about 1:26 here:

(King Oliver is one of the earliest recorded blues cornet players, and most know him primarily as the mentor to Louis Armstrong.)
Freddie King also uses this move a bit in your example, which will certainly confound your piano execution. To emulate that sound, pianists often play both notes (e.g. ♭3 and 3) together, then release the lower note. Theolonius Monk was famous for this. You can also play a more conventional grace note.

Does adding the 6th and 9th (or 2nd) scale degrees in a minor blues scale make it major, or is it simply a means of changing color/tone?

It could. Depending on the context and idiom, you could argue that such notes are drawn from the iv blues scale, or if it's a more modern example you might argue instead that the player is using something called a "bebop scale."
In general, jazz theory aims to describe rather than prescribe, and sometimes there are multiple theoretically correct descriptions of what's going on.

The notes hit are C, D, Eb, E, F, F#/Gb, G. It's almost as if both the major/minor blues scales are combined into one, composite, chromatic scale. How can this be explained?

You explained it right there :) Notice that this line is phrased in triplets, so the accent falls on the notes C, E, and G, outlining the tonic.

Overall, I would say your approach to understanding the blues is the correct one: Favor transcription by ear over sheet music, and learn to recognize the character of the major and minor blues scales as they fit with each chord in the blues form.
Comment: @Tim, here's an example: In bar 2 of the guitar solo (starts at about 1:10), we have Db bent to D over a Bbm7 chord. https://www.youtube.com/watch?v=bZ2EEepqzMM
Comment: This is immensely helpful! Thank you so much! It's interesting to think about the major blues scale in the context of the relative minor, it makes sense and simplifies it. I never really thought about it that way. One follow-up question is that, while the b3 to 3 is derived from the major blues (or vi blues), I find that, in my limited guitar experience, it's "curled" up within a purely minor pentatonic/blues context. In this case, it would simply be a bent note in minor, not a one-note digression into major, correct? Thanks so much! ~Carson
Comment: Yes, I've noticed that too, where the guitarist will bend into what seems like the major 3rd over a minor chord. They usually stop just shy of the major 3rd itself, so I would be inclined to analyze this as the "blue note" between b3 and 3 rather than a digression into major. But in some contexts, the other reading might make more sense. For example, if we have Cm7 moving to Fm7, then an E natural over the Cm7 would be the leading tone of the Fm and could be analyzed as tonicizing that subsequent chord.
Comment: 5th para. - blues in C - playing an Enat. in bar 4 is absolutely fine! You probably meant bar 5, which is where the F chord comes in. There is also the 12 bar blues that has F on bar 2, so Enat. doesn't work there either.
Comment: Your last comment: it's far more usual to bend a m3 towards M3 over a *major or seventh* chord. Doing it over a minor chord sounds more like they really don't know what they're doing!
Answer: I think the source of your confusion is the notion of "switching" between major and minor, and the resulting question of when to switch. I would suggest to view things differently, i.e., not to think in terms of "switching" between major and minor.
If we consider a blues based on dominant chords - so we're not talking about the minor blues here, which doesn't have that problem anyway - we need to realize that the basic scale over a dominant chord is the mixolydian scale. In the blues, we like to add blue notes, and these notes are the b3 and the b5. So the melodic material in the blues is drawn from the mixolydian scale to which we add those two blue notes. It is important to see, however, that in that concept we can't use a single scale for the whole blues progression, because over the IV7 and V7 chords we need to use their respective mixolydian scales, possibly with added blue notes.
In that concept, we don't need to think of switching between major or minor. We just use the melodic material in whatever way we like. We can stick more to the basic chord sound by emphasizing the chord tones and using the mixolydian scale, and we can give it a more bluesy touch by mixing in the blue notes (b3 and b5). When moving from I7 to IV7 we switch scales, which in practice just means that we replace the 3 of the I chord with the b3, which becomes the b7 of the IV chord, and that we put more emphasis on the 6 of the I chord (which is now the 3 of the IV).
The "traditional" blues scale (minor pentatonic with added b5) simply fits in with the above concept as a certain subset of the mixolydian scale with added blue notes. Played over the I7 chord, the notes that are skipped are the 2, 3, and 6 (while adding all blues notes). For this reason, very long solos based exclusively on the blues scale can sound a bit one-dimensional to some listeners.
But apart from all theoretical considerations, it's of course important to understand that music develops before we come up with a theoretical framework for it, and that we have to learn how blues works from recordings of blues artists, just like you've done. Then we note, for instance, that the major third can sound a bit too sweet in a blues context, so it is more often than not approached from below using the b3, which gives it a much more bluesy sound. One can also notice that blues improvisation is approached differently with different instruments. As an example, it's interesting to compare guitar players with horn players. One can learn a lot from listening to other instruments and from figuring out which lines they tend to play.
Comment: After more reflection, I actually do prefer this mixolydian + blue notes approach to things (opposed to major/minor blues scales or the I and vi minor blues scales as explained above). I think it makes more sense and will make more progressive sense as my blues exploration inevitably leads down a jazzier road. Thank you!
Comment: I agree that it's less a matter of "switching" between major and minor and more a matter of blending them, for the same reason that apple pie doesn't "switch" between sweet and sour, but combines them. That said, the mixolydian-based (modal) understanding of the blues applies better and better the further forward we move in history. In early blues, we can observe the melody really *is* confined to the two blues scales; the leading tone seldom appears, and the b7 (when sung) is usually "extra" flat to conform to the natural harmonic. **cont.**
Comment: **cont.** I also think that blues scales can explain certain blues cliches, like alternating between the 5, 6, and 1 (a segment of the major blues scale), more directly. But a modern blues musician should be familiar with both approaches/justifications, since they can each guide you to new possibilities. Anyway, I hate to risk my +25, but @eubio, if you like this answer better, you're free to accept it instead of mine :)
Comment: @max I agree that both should coexist in a modern blues toolkit, and I also see how the blues scales explanation can address many "pure" blues situations more directly. I decided to accept your answer because it addresses my other smaller questions and gives that freedom of interpretation (par. 6) to enable both (or even more) understandings to coexist. Thanks again!!
Answer: The (sort of) generally known major blues scale in key C consists of C, D, E♭,E, G, A, and minor blues scale in key Cm consists of C, E♭, F, G&flat, G, B♭. So, put another way, the notes NOT included are:C♯, G♯ and B! So, if you like, there are three avoid notes involved in blues on C.
Given that the other two main chords used frequently in blues in C are F and G, and those missing notes can come out to play at times.As in - when on the F chord, the F blues scale notes are brought out (or in!) to play, both maj. and min., and exactly the same thing happens on the G. So, put another way, there's very little that you could play that will be 'wrong'. Obviously, as with all music, where you play particular notes in each bar is of paramount importance to it sounding good.
Thing is, with blues, it's that the 'rules' get broken - often. And maj. and min. blues tend to get mixed and used side by side all the time. And that's without considering the 'bent' notes that guitarists and sax players in particular use all the time. They're the ones 'in the cracks'. Piano players tend to get some emulation of them by crushing in the notes that are one semitone lower.
As I tell my students - you can use any of the twelve notes from the chromatic scale, in any key, at any time, once you know the basics of how they interact and work. And blues (and jazz) tend to do just that. It's not breaking the 'rules' (there are few!), but working alongside them.
One caveat - maj. and min. blues both work over major (or seventh) chords, but maj. blues doesn't do so well over minor blues sequences.
Answer: As per my answer here, I feel that the essence of melodic blues playing is to move beyond the idea of a fixed set of notes, and embrace the fact that in certain parts of the octave, ranges of pitch, rather than only certain fixed pitches, are available.
I also think a lot of the writing in educational resources about "major blues" and "minor blues" is potentially confusing, and sometimes maybe even confused. Conceptually, I find it easier to think of a single, flexible blues scale when playing in an archetypal blues style. It may be that "major blues" and "minor blues" are each good descriptions of the tonality of some pieces, but it would definitely be incorrect to say that blues tonality divides neatly into "major" and "minor"; a strong characteristic of blues is that it bridges the gap between the two.
Yes, when you're playing a fixed-pitch instrument like the piano, you're restricted to fixed pitches - but you rightly mention the idiom of e.g. hitting the minor third and major third in quick succession, which is the piano's way of putting in a bit of that 'bendiness'.
In the blues, these bends aren't just incidental inflections - they're central to how the tonality works, and to ignore their importance is to misunderstand the genre.

The notes hit are C, D, Eb, E, F, F#/Gb, G. It's almost as if both the major/minor blues scales are combined into one, composite, chromatic scale. How can this be explained?

Let's compare that with my impression of the 'C' blues scale from my linked answer:

C
a 'window' around Eb, covering the range down to D and up to E.
F, bending up a little (maybe not as far as Gb)
G
Bb, with scope to bend up a little (but maybe more like a quarter tone - not as far as B)

Apart from the fact your particular lick doesn't hit a Bb, I'd say we pretty much agree :)
Answer:
Making Sense of Blues Soloing; differentiating major/minor pentatonics

A. Major:
The major blues-melody contains major 3rds but also minor 3rds (and diminished
    5ths, minor 7ths: the  blue notes, which fit quite well with the tones of
    the parallel key)
    The bass and the chords are major chords (the blue notes are chromatic approaches or bent 3rds and 5ths.
B. Minor:
The minor blues melody, chords and bass line don't contain major 3rd (except in V7 and sometimes when the subdominant   is a major IV  like in Dorian.)
"It ain't necessarily so",  "A woman is a sometime thing" (Porgy and Bess / Gershwin) and"Yer blues" (Beatles)
We probably shouldn't try to describe the blue notes by traditional western theory. My own concept is to understand the blues as a sad song expressing misery, desperation, crying, as if you someone is soaring and desperately singing, not able to reach the perfect pitch. In German baroque we have the "Seufzer motif" - the motif of sighing. In my opinion the blue notes are like a sighing (bent tones, chromatic approaches leading up to the major 3rd or major 5th, down leading ("Seufzer") b3->2->1 and b5->4-1
Comment: Interesting idea in the last para.
Comment: yes, Tim, I don't remember that I've ever heard about this parallel or analogy.;) Here's a link: https://de.wikipedia.org/wiki/Seufzermotiv
Comment: But I was sure I'm not the first who found this connection! Just googled "blue note and Seufzermotiv" and here is the first result: (s. page 67).  https://books.google.com/books/about/Begegnung_im_Niemandsland.html?hl=de&id=J8nBDwAAQBAJ
Answer: Considering your situation, I suspect you're pretty good on theory.  So regarding your problem of thinking of "switching" major and minor, I suggest you start thinking more in terms of modes.  In historical terms, pretend you're playing baroque or even earlier.
We have a perfect example of this in the English folk tradition.  Greensleeves switches seamlessly between its relative majors and minors.  Its author (allegedly Henry VIII, although evidence of this is lacking!) would have been entirely familiar with how blues players move around the scale.
And of course remember that musical theory is just a way to represent what the piece or player is doing, after the piece is written or the player has improvised.  It's not a rulebook of what is and isn't permitted! :)
Answer:
I've found that it's common to switch from the major blues scale on the I to the minor blues scale on the IV, and that happens here; Nicky also uses the bVII chord on the IV

I think some of your questions can be addressed as general harmony issues and in many cases those blues harmony characteristics are not hard to understand from a "classical" harmony perspective.
First take note of the importance of the <code>IV</code> chord in blues. In the opening of 12 bar blues you get <code>I IV I</code> and then in the turnaround ending you get <code>IV I</code>. There is a very noticeable emphasis on the subdominant.
In classical style you can have <code>I IV6/4 I</code> where the <code>IV</code> chord is considered a kind a embellishment of <code>I</code>. If you want to treat <code>IV</code> not as a mere embellishment, it can be tonicized to emphatically make it a goal by lowering the seventh scale degree. <code>I V7/IV IV</code> or with chord names in <code>C</code> it's <code>C C7 F</code>.
Both of those happen in blues harmony.
In 12 bar blues the basic beginning harmony is <code>| I | I | I | I7 | IV...</code>. The <code>I7</code> essentially tonicizes <code>IV</code>. If you really wrote the symbols correctly it would be like `| I | I | I | V7/IV | IV...'
On the <code>IV</code> chord of bars 5 & 6 you can have something like <code>IV IV64/IV IV</code> in <code>C</code> it's <code>F Bb/F F</code>. The subdominant of the subdominant. It's a lot easier to write and think about it you treat <code>F</code> as momentarily tonicized and just label it <code>I IV64 I</code>. This is the embellishing use of <code>IV</code>. In your question you called the chord <code>bVII</code>. <code>C: bVII</code> is sort of synonymous with <code>F: IV</code>, but it misses the subdominant quality.
Lot's of jazz and blues method put this all together with a general reference to the Mixolydian mode. Each of the 12 bar blues chords - <code>I7 IV7 V7</code> - can be seen as a Mixolydian flavored chord. The Mixolydian mode provides both the <code>7</code> for each chord and an embellishing <code>IV6/4</code>.
Now go back to switch from the major blues scale on the I to the minor blues scale on the IV and you will see the minor blues scale in <code>C</code> gives you a <code>Bb</code> and <code>Eb</code> and those are exactly the tones needed to get <code>F</code> Mixolydian for the <code>IV</code> chord. In classical harmony terms <code>Bb</code> first provides the seventh for <code>C7</code> to <code>F</code> then it becomes the subdominant of <code>F</code> and the <code>Eb</code> which seems like a minor third relative to <code>C</code> also provides a minor seventh for <code>F7</code>.
So, if you are trying to make sense of why and when to switch between blues major and minor, and you bring to the question a "classical" perspective, you can say switch from blues major to minor tonicizes the subdominant.
I don't see a problem with intellectually satisfying the question with a bit over overwrought music theory ...and then setting the theory aside to approach improvisation more intuitively.
Answer: There is no blues scale, any more than there is a jazz or a pop scale. Much African music is based on a pentatonic scale having notes that fall in between western temperances, explaining the blues guitarist's use of bending strings and/or a slide, and the pianist's use of adjacent keys. The harmonic content and use of scale is sometimes better viewed as being based from the V chord even when you are on the I chord, and much African music displays this context. Possibly this could be seen as a cultural difference in what is perceived as the root. As far as "mixing minor and major", the real answer is neither. Its pentatonic.
 Furthurmore, if you listen to blues from the 1930s through the 1960s you will hear musicians intentionally blurring the "rules", contrasting the harmonic major tone of a song's vocal part by playing a guitar part based completely in minor. This is an element of blues evolution, in which western harmonic mentality has been somewhat assimilated.
 Another thing you may discover if you start to understand the pentatonic scale is that everything you play or sing sounds "sad", but that is a reflection of our contextual experience; the lyrics of many blues songs can be interpreted differently if one is not hearing "that melancholy strain" accompanying them.
 You are most correct in thinking that further study will help learn this mysterious musical language, and startong with very early blues and working your way thru the decades. Many idioms and elements became meme-atic over the years, you no longer have to play a turnaround because everyone knows there's a turnaround there.
  Or, to put simply: "Blues ain't nothin but a good man feelin bad"
      St. Louis Slim
"Nobody leaves without singin the blues".
Answer: I have been playing the blues since the late 1960's (lead guitar) by ear and imitation, but only during 2020 (pandemic time on my hands) started thinking about why I use at least 10 out of 12 notes but only use some of them at certain times.
I think everyone agrees that the basic blues scale is pentatonic (1, 3, 4, 5 and b7). But what about that 3rd? Is it major or minor? I say it is a minor 3rd. The motif of the minor 3rd to 1 is fundamental to the blues sound. It's almost like the V to I chord motion in establishing the tonic. A repeated minor 3rd to one announces, "This is a blues song." It occurs in hundreds of tunes. It is not in my opinion an "accidental" or "color" note. It is definitional. So rather than thinking of blues as a Myxolydian mode that sometimes uses a minor third, I think of the major 3rd as an alteration to a minor scale. The skeleton of a blues scale is 1, m3, 4, 5 and b7 - a minor pentatonic scale.
While the minor pentatonic scale is a starting point, it's a pretty restricted tonal palette. So what notes to add? Thinking in terms of modes, Aeolian, Dorian and Phrygian contain the minor pentatonic scale. I normally include the major 2nd (major 9th) which rules out the Phrygian mode. I don't normally use the flat 6 which rules out Aeolian. It is perfectly acceptable to avoid the 6th scale degree when improvising over the 1 chord.
How does the major 3rd function? I noticed that I always use the major third in anticipation of the IV chord. So in anticipation of A moving to D, the major third of A (C#) leads chromatically to D.
What about the flat 5/#4?
Similarly when improvising over the tonic chord (in this case A), the fifth scale degree of A (E) is flattened (Eb) to lead chromatically to D. The flat 5 or #4 can also be used as a passing tone to get from the IV chord to the V chord and vice versa. This happens constantly in the bass lines. Obviously, the flat 5 adds a lot of spice to the scale but it also creates strong tension towards the subdominant chord.
So far we have A, B, C, C#, D, D#, E, G.
I also use the natural 6th scale degree borrowed from Dorian, I use that over the 1 chord in anticipation of moving to the IV chord as it is the major 3rd of the IV chord. In my example using A as the tonal center, F# is the major 6 of A and the major 3rd of D. It is also consonant with the V chord (E).
The IV chord is a dominant chord, so the F# (major 3rd of the subdominant) is an important note to highlight over the IV chord. By the way, it also works to use the minor third (F) as a grace note over the IV chord.
Similarly the V chord is also a dominant chord so we must add G# to our collection (major 3rd of E) so now our list of acceptable notes is;
A, B, C, C#, D, D#, E, F#, G, G#.
That's 10 notes but G# is only used over the E chord.
The flat 5 is only used over the tonic chord or as a passing tone between the IV and V chords.
The major third is only used over the tonic and dominant (A and E) chords, not the IV chord. Those are the proper uses of those notes according to my ear.
Of course the remaining two notes can also be used but more sparingly and now we're getting into jazz.
I hope that helps.
Answer: Thinking in terms of scales may not be very useful here.  Just let a Blues in C be in C major, with lots of 'blue' notes freely added - the ♭7, ♭5, the E♮/E♭ slide which is the nearest a keyboard can manage to the 'blue' 3rd degree, and any other chromatics that seem like a good idea at the time!   'Chord=scale' has its uses, but it's not the only way of looking at things.


LACP Trunk from Cisco to Fortinet

Question: I am setting up a 2 ethernet trunk between a Cisco switch and Fortinet 100E firewall. So far the below is working (i can ping from Cisco 192.168.1.2 and get replies from the Fortinet 192.168.1.1):
interface Port-channel1
 switchport trunk native vlan 1
 switchport trunk encapsulation dot1q
 switchport trunk allowed vlan 255
 switchport mode trunk
!
interface FastEthernet0/1
 switchport trunk native vlan 1
 switchport trunk encapsulation dot1q
 switchport trunk allowed vlan 255
 switchport mode trunk
 channel-group 1 mode active
!
interface FastEthernet0/2
 switchport trunk native vlan 1
 switchport trunk encapsulation dot1q
 switchport trunk allowed vlan 255
 switchport mode trunk
 channel-group 1 mode active
!
interface vlan255
 ip address 192.168.1.2 255.255.255.0

And as per https://forum.fortinet.com/tm.aspx?m=106460  the above is not a LACP trunk (although it does work), and instead should be:
int range gi 1/0/1-2
no shut
switchport
channel-group 1 mode active
channel-protocol lacp
load-interval 30
logging event link-status
logging event bundle-status
!

I have a couple of questions please:

If the way i have done is not true LACP, how come it is working with the Fortinet (which is set for 802.3ad Aggregate)? Seems setting channel-protocol lacp on my ports makes no difference (is it LACP by default)?
If i want to move my native vlan from 1 to 10, would this stop the trunk from working (as i cant see where to define native vlan on Fortinet, as i understand LACP negotiation goes over native vlan)?
I see on the Fortinet there is the default network upon which VLANs are added - i have currently set this to no ip 0.0.0.0/0 but is there any way to remove this entirely and just have the VLANs? Or should one instead put the management IP on this default network? What is best practice?
Comment: You are not even allowing the native VLAN on the trunk. The only VLAN allowed on the Cisco trunk is VLAN 255, which is not defined as the native VLAN. Some devices (perhaps Fortigate?) only allow VLAN 1 as the default and native VLAN.
Answer:
If the way i have done is not true LACP, how come it is working with the Fortinet (which is set for 802.3ad Aggregate)? Seems setting channel-protocol lacp on my ports makes no difference (is it LACP by default)?

By using channel-group 1 mode active you have defined the etherchannel to use LACP unconditionally.
Depending on platform you have additional keywords to use in place of active, but no matter the platform, they have the same meaning on Cisco platforms. For example:

on : statically configures the port as part of the etherchannel
active : use LACP
passive : use LACP only if connected to a device with LACP is detected
auto : use PAgP (Cisco proprietary link aggregation) if connected to a device that initiates PAgP (doesn't initiate negotiations itself)
desirable : use PAgP and attempt to initiate negotiation of PAgP

The reason the Fortinet post may be correct is that the configuration it is referencing only lists a port channel configuration, but doesn't list any port configuration that includes a channel-group command.
The channel-protocol lacp command is only relevant on a platfrom that by default only does PAgP and needs to be switched to LACP mode (this may be a port level or module level configuration). AFAIK, this is unnecessary configuration on the 3750G as listed in the post.

If i want to move my native vlan from 1 to 10, would this stop the trunk from working (as i cant see where to define native vlan on Fortinet, as i understand LACP negotiation goes over native vlan)?

I would recommend against changing the native VLAN as doing otherwise can hit a number of Cisco LACP bugs that result in LACP PDUs being tagged (which they shouldn't be according to the standard). Examples of such bugs are CSCsh97848 or CSCse14774 (may need Cisco TAC login to view).
While most of these bugs have been addressed by Cisco, you don't mention the platform or code version, so this is generally the safest approach when connecting Cisco devices to other vendor's equipment.

I see on the Fortinet there is the default network upon which VLANs are added - i have currently set this to no ip 0.0.0.0/0 but is there any way to remove this entirely and just have the VLANs? Or should one instead put the management IP on this default network? What is best practice?

Your screenshot shows the link aggregation interface with the physical interfaces that are part of it, as well as the subinterfaces. There is no way to remove the main interface from the configuration (i.e. you need to have the main interface to base the subinterfaces on) and having no IP address assigned isn't a problem if you aren't using it.
As for best practices, it is the best practice to keep the management interface on a secure subnet/VLAN. Other than that, it is what is best in your network configuration so what you have may be fine.
However I will point out that you are only allowing one VLAN on the Cisco side of your configuration, namely VLAN 255. So odds are good that while it appears you have two VLAN subinterfaces configured on the link aggregated interface, only one of them is actually usable.
Answer:
If the way i have done is not true LACP, how come it is working with
  the Fortinet (which is set for 802.3ad Aggregate)? Seems setting
  channel-protocol lacp on my ports makes no difference (is it LACP by
  default)?

What you have done is configured a trunk. A trunk deals with sending and receiving packets for particular Virtual Local Area Networks (VLANs). LACP is about aggregating links. These are different technologies for different purposes. You have also configured a Cisco Port Channel. Port channels allow you to have some of the functionality of LACP but Port channels do not pass protocol packets. The consequence of this is all of the individual links are in the "on" mode for the channel. https://www.cisco.com/c/en/us/td/docs/switches/datacenter/nexus5000/sw/configuration/guide/cli/CLIConfigurationGuide/EtherChannel.html#47157

If i want to move my native vlan from 1 to 10, would this stop the
  trunk from working (as i cant see where to define native vlan on
  Fortinet, as i understand LACP negotiation goes over native vlan)?

A native VLAN is the network untagged traffic sent to a trunk port will be assigned. If the native VLAN on the trunk port is VLAN 20 and untagged traffic is sent to the trunk port then it will be assigned to VLAN 20. To setup a native VLAN on the Fortinet firewall you need to create a trunk and put switch port members in it. Then edit the trunk and configure a native VLAN. https://networkengineering.stackexchange.com/questions/19377/is-the-default-vlan-simply-the-default-native-untagged-vlan-on-all-interface

I see on the Fortinet there is the default network upon which VLANs
  are added - i have currently set this to no ip 0.0.0.0/0 but is there
  any way to remove this entirely and just have the VLANs? Or should one
  instead put the management IP on this default network? What is best
  practice?

When you create a VLAN on the Fortinet firewall you need to select what interface you are creating the VLAN on. This is because VLAN tags are assigned on port interfaces. You cannot remove the physical interface (what you have set with 0.0.0.0/0) and still have the VLAN on the physical interface. Other vendors handle this differently, but this is how Fortinet does it. http://help.fortinet.com/fweb/580/Content/FortiWeb/fortiweb-admin/network_settings.htm#network_settings_2363754841_1026461
I would also suggest taking a look at http://kb.fortinet.com/kb/documentLink.do?externalID=FD30542.

LACP Trunk from Cisco to Fortinet


For the function $Y = e^{-x}$ where $X$ is $N (0,1)$

Question: For the function $Y = e^{-X}$ where $X \sim N (0,1)$ show that the variance of $Y = e(e−1)$
Comment: What is the question?
Comment: to show the variance is
\begin{equation}
Y = e(e - 1)
\end{equation}
Sorry for the formatting earlier. quite new to mathJax
Comment: The variance should be given by
$$
\mathbf{Var}(Y)=\mathbf{E}(Y^2)-\mathbf{E}(Y)^2
$$
I am not sure how to get ${E}(Y^2)$
Answer: Hint:
$$
\Bbb E\exp(aX) = \int_{-\infty}^\infty \exp(ay-y^2/2)
\frac{dy}{\sqrt{2\pi}}
= \int_{-\infty}^\infty \exp (-(a-y)^2/2)\exp(a^2/2)
\frac{dy}{\sqrt{2\pi}} = \exp(a^2/2)
$$because the integral is the normalization of a variable $N(a,1)$.
details:
The variance you look for is then
$$
\exp(2^2/2) - \exp(1/2)^2 = e^2-e
$$
Answer: Hint: Use change of variables technique and find the distribution of $Y$, then you'll be able to identify the distribution, and we'll be able to calculate the variance: Take a look at this: https://onlinecourses.science.psu.edu/stat414/node/157


How to create custom hAxis labels in Google Charts?

Question: I am using Google Charts for a simple Area Chart. I have many points to draw, i would like to set the interval between them. At the moment there is a list 1,2,3,4,5,6,7 etc
I would like to show all points but with custom hAxis labels, like: 0 5 10 15 20 etc
The code is:

And the result is:

The horizontal labels represent all points, I need all of them, but showing specific horizontal labels. How can i set specific interval?
Thanks
Answer: This will be much easier to achieve if you enter your axis values as numbers instead of strings:
var data = google.visualization.arrayToDataTable([
    ['Day', 'Visit', 'Applic.'],
    [1, 19, 1],
    [2, 100, 9],
    [3, 103, 18],
    [4, 42, 8],
    [5, 34, 2],
    [6, 63, 9],
    [7, 35, 7],
    [8, 427, 51],
    [9, 314, 38],
    [10, 71, 4],
    [11, 27, 0],
    [12, 25, 0],
    [13, 78, 0],
    [14, 54, 0],
    [15, 60, 0],
    [16, 47, 0],
    [17, 29, 0],
    [18, 16, 0],
    [19, 10, 0],
    [20, 26, 0],
    [21, 200, 0],
    [22, 255, 0],
    [23, 160, 0],
    [24, 30, 0],
    [25, 35, 0],
    [26, 9, 0]
]);

You can then specify the hAxis.ticks option to tell the chart which values should be labeled on the axis:
hAxis: {
    title: 'Days',
    ticks: [0, 5, 10, 15, 25]
}

Comment: Also you can use the viewWindow to specify the min and max of the values.
hAxis: {
                    viewWindow:
                        {
                            min: 0,
                            max: 7
                        },
                    ticks: [0, 1, 2, 3, 4, 5, 6]
                }


How can you add custom buttons and text to an android navigation? (Logged in as X)

Question: I'm creating an android app and making a custom top navbar for it. I am using a res/menu xml file to do this.
Ideally, I'd like to be able to add a button with text on it that says "Log In" when the user is not logged in and "You are logged in as X" when they are logged in. I have not been able to find a way to have text buttons however.
After searching online I have, surprisingly, been unable to find many guides or discussion on the topic. The only options I ahve found are "Group", "Menu", "Switch" and "Search" which all seem to have pre-defined pictures.
Is there a way I can add custom text buttons to an android nav bar?
Answer: <code>Please try below code :

     <android.support.v4.widget.DrawerLayout
            android:id="@+id/drawer_layout"
            android:layout_width="match_parent"
            android:layout_height="match_parent"

            android:fitsSystemWindows="true">

            <android.support.design.widget.CoordinatorLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent">

                <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:background="@color/white"
                    app:layout_behavior="@string/appbar_scrolling_view_behavior">

                    <FrameLayout
                        android:id="@+id/content_frame"
                        android:layout_width="match_parent"
                        android:layout_height="match_parent" />

                </RelativeLayout>

            </android.support.design.widget.CoordinatorLayout>

            <LinearLayout
                android:id="@+id/ll_drawer"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_gravity="start"
                android:layout_marginRight="50dp"
                android:background="@color/white"
                android:orientation="vertical">

                <ListView
                    android:id="@+id/list_menu"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_gravity="start"
                    android:layout_weight="1"
                    android:background="@color/white"
                    android:divider="@android:color/transparent"
                    android:dividerHeight="0dp"
                    android:fitsSystemWindows="true"
                    android:scrollbars="vertical" />

                <TextView

                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_alignParentBottom="true"
                    android:gravity="center"
                    android:text="@string/Logout"

                    />
            </LinearLayout>

        </android.support.v4.widget.DrawerLayout>
</code>
Answer: You have to use Toolbar instead of default Action bar
<code>  <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" >

             <RelativeLayout
              .
              .
              .
             </RelativeLayout>
</android.support.v7.widget.Toolbar>
</code>


Como ter acesso ao css do bootstrap?

Question: Estou utilizando uma barra de navegação do bootstrap e gostaria de aumentar o espaço entre os botões e mudar suas cores, editando attravés de um arquivo externo, mas não sei onde consigo o código css dele (é minha primeira vez utilizando o bootstrap)...
 o HTML está assim:
<!DOCTYPE html>

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">

      titulo
      <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

      </button>

            Home (current)

        <form class="form-inline my-2 my-lg-0">

          <button class="btn btn-outline-success my-2 my- sm-0" type="submit">BOTAOA</button>

          <button class="btn btn-outline-success my-2 my-sm-0" type="submit">BOTAOB</button>
        </form>

Comment: Geralmente fica dentro da pasta do bootstrap, mas precisamente na pasta css e no arquivo bootstrap.min.css ou bootstrap.css. Depende de qual dos dois arquivos vc está chamando.
Comment: é que eu não baixei nada pra usar, eu só utilizei o link de referencia... vou tentar baixar os arquivos e ver se funciona
Comment: Mas eu não entendi direito. Todas essas mudanças que vc citou, tu pode fazer utilizando classes do bootstrap.
Answer: Crie uma

em volta do código que você deseja alterar as propriedades do css presente no bootstrap.
.unique-section-name .bootstrap-class { css here }

Assim você altera as propriedades do css do bootstrap em um trexo do seu sistema(unique-section-name) sem alterar em outros.
EDIT1: Para saber qual classe você deve alterar, na teoria, você deveria consultar a documentação oficial do bootstrap, mas, provavelmente será mais fácil pelo inspect do seu browser.
Obs: O bootstrap era útil, assim como o jQuery, em momentos da humanidade nos quais grande parte de nós ainda nem éramos vivos. Caso esteja aprendendo e não dando manutenção para um sistema mais antigo, não utilize nenhum deles, atualmente as versões de CSS e JS te dão ferramentas para lidar com páginas web de formas extremamente efetivas.
Obs2: esse padrão de isolar uma classe em uma 'seção' do seu sistema utilizando uma classe única para essa seção, é a base do css local(componente isolado) em frameworks como angular, Vue e bibliotecas como React.
Answer: É mais fácil você "criar" sua própria classe do que alterar a classe do Bootstrap, e se você já tem conhecimento pra alterar, você consegue criar a sua. Pra você alterar, você precisaria ter os arquivos baixados dentro da pasta do seu projeto, o que deixaria ele mais lento, é melhor deixar por cdn mesmo.
Pra criar sua classe, basta você criar um arquivos css (eu normalmente chamo de custom.css), procura a classe que você desejaria alterar dentro do arquivo bootstrap.css (é mais difícil de achar no arquivo bootstrap.min.css), copia ela inteira, joga na custom.css e faça as alterações, muda de nome, cores, padding, assim como fiz aqui.

Aí no caso eu peguei o btn-primary que é azul, e criei um btn-caixa que é laranja. Valeu, espero ter ajudado, qualquer dúvida comenta aqui

Como ter acesso ao css do bootstrap?


Multivariable Calculus Books

Question: I am an undergraduate student currently taking a course in Multivariable Calculus. Long story short, I took a hiatus from doing any sort of serious mathematics for a couple of years, and now that I am back I am finding it difficult to pick up where I left off.
The "textbook" that we are using is more of a collection of notes, lacking any sort of practice problems, other than in-text, usually trivial proofs, and I find that the practice problems posted (usually about 5-10 per week) are insufficient practice for me.
I am posting to see if any of you have suggestions for a good multivariable calculus textbook that has clear and detailed explanations, and lots of practice problems.
Any suggestions are greatly appreciated.
Comment: Stewart Multivariable Calculus is one of my favourite  books
Comment: I used to recommend "How to Ace the REST of Calculus."  Adams, et al.   It's a sequel to "How to Ace Calculus".  But while I didn't like the first book, the second was stable and helpful.
Answer: Try

A Course in Multivariable Calculus and Analysis by Ghorpade, Sudhir R., Limaye, Balmohan V. [Springer link]
Calculus. Vol 2 ., Multi Variable Calculus and Linear
Algebra, with Applications to
Differential Equations and Probability by Tom M Apostol (Pdf !)
Answer: See Calculus with Analytic Geometry by George Finlay Simmons.  A student friendly book with many relevant exercises.

Multivariable Calculus Books


Direct limits of injective modules

Question: Is it true that the direct limit of injective modules is injective?
Comment: See page 81 Theorem 3.46 Lectures on Modules and Rings by Lam. This has exactly the theorem refered to in the comment below and is a nice textbook.
Answer: Over what ring?
In particular, the answer to your question is "yes" iff the ring is Noetherian.
Comment: To be clearer: the answer is yes for all direct limits of injective module if and only if the ring is noetherian.

Direct limits of injective modules


Month Displaying Earlier Than Expected

Question: I have the following code to print last month once a new month starts.
$prevmonth = date('F Y', strtotime("last month"));
print $prevmonth;
The problem I encountered recently was that last month was printed before this month (August) begins.  E.g. July was showing although it was still July 31.
Any help on this issue is greatly appreciated.
Answer: What about the timezone settings ? This could be a lead.
http://php.net/manual/en/function.strtotime.php
Answer: Your time zone settings may not be set correctly so I would check that.  If those are correct I would suggest a better way then to rely on strtotime:
<code>$date1 = new DateTime();
$month_ago = new DateInterval( "P1M" );
$month_ago->invert = 1; //Make it negative.
$date1->add( $month_ago );

$prevmonth = date('F Y', $date1);
</code>
Answer: Thank you, chadpeppers.  I tried your code but it didn't do anything for me.  My co-worker was able to help. The following code fix the problem:
<code>$prevmonth = date('F Y', strtotime("first day of last month"));
print $prevmonth;
</code>

Month Displaying Earlier Than Expected


Help! Light voice with non-existent high notes

Question: I have been really frustrated for the characteristics of my voice. I have a very light, metallic timbre in it that gets a little warm the higher I sing, but I cannot reach even a Eb4 without straining A LOT.
While the lower register is there (it's consistent) when I get lower than A2 I lose all the resonance and it becomes very airy and weak.
After doing research and reading a lot I conclude that for the color and weight of my voice I must be some kind of tenor, but the passagio (I know there is two of them) does not fit with the extremes of my range.
I have never heard of a tenor that strains in Eb4 like I do, it is just impossible to me sing that without strain and change to head. I personally think that it may be the strain in my neck that does not let me go higher, because all muscles just get harder and it feels so uncomfortable.
I was in a choir in November/December last year, and the teacher seems to be so confused about me like I did (and still do). After checking my range and make me sing scales he says: "Yes, you are a tenor". And then he press the E4 key and make sing it, it sounded horrible obviously, and he says: "You should be able to sing there"... But I can't. He never answered my questions, and I was worried about making him get angry.
Answer: Okay, there are a few things to unpack here:
Your age.
The voice doesn't really mature until people are in their 30's, and will continue to mature as they age. One of the biggest issues with young vocalists is that they see and hear so much garbage out there and attempt to sing far beyond their vocal maturity. If you are younger than your 30's then your voice has much growing up to do. Be nice to your voice and don't try and make it do things it's not ready to do.
Your vocal fache.
Tenors I know do not have a problem with Eb4. If you're straining to reach it then you shouldn't be counting it in your range. Trained vocalists only count notes that resonate and respond comfortably. Ergo, your range is likely smaller than A2-Eb4. Trained vocalists have at minimum a two-octave range at their disposal. Your described range suggests to me that your voice is not trained, and more specifically, you seem like an untrained baritone, which is the most common voice type for men.
There are multiple types of each vocal fache; a friend of mine is a lighter baritone and because of that, he specializes in Baroque / early music, which needs a lighter voice.
Last, it's important to remember that vocal ranges aren't set in stone. Not all baritones, tenors, etc are the same. Do not worry if you don't fit into a specific box. Things change over time. A friend of mine started as a mezzo soprano, but after years of training she now sings as a coloratura soprano. It is likely that your voice will change as you mature as well.
Your vocabulary.
This is a small but important one. "Tessitura" is not the overall range of notes you are capable of producing, but the most-often used region of pitches along a variable continuum (which in this case is the voice).
The "passagio" typically lies toward the upper-center of the voice; though it's different for everyone.
Your technique.
The straining you describe is most definitely affecting your ability to resonate and therefore vocalize. Singers spend a significant amount of time learning about the various vocal mechanisms and how to relax them in order to increase resonance. Singing should be a big, effortless thing; if you're straining, you're working too hard.
Good luck.
Answer: My advice, and I know that it's not quite proper to answer your question, since you never technically asked one;
Listen to David Bowie.
His voice was similarly thin, and oddly stuck between this range or that.
He affected a low, affable speaking voice, and there was no small amount of cigarette smoke in his plumbing.
Bowie was a fan of several techniques.
One, he would double-track his own voice with one track in the lower register, and the other at the exact higher octave.
Two, when he went low, he was overly-emotive and tremulous.
Oh, and he was also an impressionist.
He was an actor.
He emoted something that sounded like something or somebody that pleased him, and he BECAME that.
Listen to the man, and see if there is wisdom in there for you.
Maybe it's best that you don't fall into any comfortable category of voice type.
You may well just forge your own way.


How to get value of PartyList field using Javascript and oData in CRM 2011

Question: due to CRM 2011 online problems with IE10, we have decided to convert all front-end JavaScript from Soap to oData. Everything was going fine, I installed the oData designer, centralized the queries in functions, but i ran into a problem when i tried to retrieve the partylist field Resources for ServiceActivity.
The oData query I got using the oData Query designer is the following (the guid is a sample)
ServiceAppointmentSet?$select=Resources&$filter=ActivityId eq guid'83CA6B11-6C0A-E311-8BB5-B499BAFE71A5'
but in the response i get an error that the Resources field was not found.
I tried without the select, and debugged the returned oData object, but noticed that it doesn't show both Resources and Customers partylist fields that are in ServiceActivity.
ServiceAppointmentSet?$filter=ActivityId eq guid'83CA6B11-6C0A-E311-8BB5-B499BAFE71A5'
Does anyone have any ideas?
Answer: I believe you can get the Resources and Customers by using $expand to allow the query to include the serviceappointment_activity_parties relationship. Like so:
<code>ServiceAppointmentSet(guid'83CA6B11-6C0A-E311-8BB5-B499BAFE71A5')?
  $select=
    serviceappointment_activity_parties/ParticipationTypeMask,
    serviceappointment_activity_parties/PartyId
  &$expand=serviceappointment_activity_parties
</code>
The GUID of the activityparty is found in PartyId, and the ParticipationTypeMask integer allows you to figure out what kind of activity party it is, for example Customer is 11 and Resource is 10. The full list of ParticipationTypeMask mappings can be found here.
Comment: You sir have saved the day and significant time that would have been spent investigating the relationships to the activity parties and service appointment. Thanks you very much for the short and precise answer!
Comment: Glad that you find it useful!
Comment: @adner1 Thanks this was very useful info. I have a follow up question. Is it possible to filter your results against what is in the PartyList?
Comment: No, I don't believe it is possible. As far as I know, filtering criteria can only be applied to the ServiceAppointmentSet, not to related related using $expand. See [here](http://stackoverflow.com/questions/9171310/odata-filter-with-items-in-a-expand) for more info. But as comments in the linked post suggest, the OData specification seems to support  using filters on related entitites using a different notation than $expand, however I don't think that the CRM 2011 implementation supports this...
Answer: Issues with capitalization tend to cause alot of OData errors.  Also, have you tried creating your query in LinqPad (Assuming it is not CRM-Online)?  I've found it quicker in generating my OData URLs.
Comment: Yes @KonradViltersten, I have used it like that.  I believe it only works with the Guid, its just not what LinqPad spits out so I don't think I normally use it.
Comment: Yes, i am aware of capitalization issues, but this is not it. As i have mentioned that the two party list fields Resources and Customers (these are their schema names), in Service Activity, are not returned as part of the ServiceAppointment object. I think the query for these fields might be related to another entity like AppointmentSet or maybe ActivityParty, i will continue digging.

It is CRM Online environment the one i am working on but thanks for LinqPad, hadn't used it before, i will check it out.
Comment: Hi D! Have you ever used the syntax from the answer above yours, where the replier specified the guid for his *ServiceAppointment* in the parenthesis **before** the question mark? I value your input on this one.


What do you mean by the tonic chord feels as 'home'?

Question: I am new to the world of music theory and have some basic knowledge of the different modes of the major scale.
As per my knowledge, every scale has a tonic chord which is essentially the one all other chords seem to revolve around. The tonic chord needs no furthur resolution, blends in extremely well within the entire piece and when the listener listens to this chord they feel 'at home'. All other chords lack this central vibe and are unresolved.
Now, when I read about the Locrian mode, for example, I read that its tonic chord is a diminished chord. Well, that is quite ambiguous, since that is quite unstable in itself. And if that is the case, the diminished chords and other chords should reverse roles when in a Locrian piece right? What I mean is, when a piece is in the Locrian mode, and suppose I play a major (or minor) chord, will one get a feeling of instability? Will the piece then have a tendency to resolve to a diminished chord?
Also, talking about tonic chords, if there exist scales with diminished chords as the tonic chord, there must be scales with suspended chords, augmented chords, and chords with more than 3 notes as the tonic chord, right? Can someone please give examples of such scales and do the same rules apply to them too?
I would really appreciate it if anyone can throw some light on these things since the idea of it is very unclear to me.
Answer: About the "tonic"
Not every scale has a tonic chord.
Tonic is primarily a concept in major/minor Tonality and does not apply (the same way) in modality or to non major/minor-Tonal music. When other kinds of musical structures are involved (the Locrian mode, for example), one more generally speaks of a pitch center, which is a more general term that can apply to most music that is not atonal.
"Tonic" vs. I-chord
In the major/minor Tonal system, the tonic chord and the I (or i) chord — that is, the chord with the first scale degree as its root — are synonymous. This is not true in other systems. The I chord does not necessarily serve a "tonic" function: i.e., is not a point of resolution, as is clearly the case in Locrian. In Locrian, specifically, the first scale degree can function as the pitch center, and that individual pitch might function like a tonic, but there is no "tonic chord" in the sense of a "place of rest".
Major/minor chords in Locrian
When using the Locrian mode, one would tend to avoid prominent major or minor chords. It is generally in the nature of these chords to sound stable, and to draw the ear, and so they would tend to undermine the unique sound of Locrian and shift the music toward sound like major or minor.
Chords within scales
A definition of "chord"
For this to have meaning, we need to adopt a mildly restrictive definition of chord. For our purposes, let's say a chord comprises three pitches separated, each separated by one scale pitch.
So, for example, in C major, C E G is a chord, but C D G is not, because there's no scale pitch between C and D. C F G would also not be an allowed chord, because there is more than one pitch between C and F.
Without this rule, we could construct most any chord from most any scale.
Chords generated by different types of scales

Suspended chords: technically, these cannot occur. A suspension is a pitch held over from a previous harmony and so is not properly part of the chord with which it occurs. "Sus" chords are a shorthand for certain non-thirds-based chords. Allowing that a chord is "every other note" in a scale, then the C minor blues scale (for example) has a I chord of C F G, which is typically labeled a Csus4.

Augmented chords: The whole-tone scale contains only augmented chords (again, assuming the usual every-other-note pattern.

Four-note chords: A chord, by most definitions, only requires three notes. One can (almost) always add a fourth note. But any scale with a four-note chord trivially also contains a three-note chord (by removing the fourth note).

Diminished chords: The diminished scales (octatonic scales) contain diminished chords.

Major and minor scales, within the Tonal system, follow the rules being asked about. Other scales follow their own rules — or the rules imposed on them by the composer.

As an aside, I know of one piece in which a major chord takes on (or can take on) a dissonant quality: "A Riveder le Stelle", by Ingvar Lidholm. Almost the entire piece consists of tone clusters, but there is a point at which a C Major chord suddenly emerges. The resonance of it, especially live, can be quite shocking if you don't know (when) it's coming.
Comment: The (minor) blues scale has a tonic chord that is a sus4 chord according to your "Allowing that a chord is 'every other note' in a scale" rule. Maybe not as contrived as you think?
Comment: @Dekkadeci Good call! Do you mind if I include that in my answer?
Comment: @LaurencePayne, I thought the typical way to say something was a mixolydian tonic was by chord relationships, like `G` mixo using `G`, `F`, `dm` or just a strong `F` in mostly `G` major... well, along with phrasing to highlight `G`.
Comment: I don't think the tonic chord necessarily *needs* to be uniquely representative of the mode it's in... I agree with Michael Curtis, @LaurencePayne, although including more notes in the tonic chord for stylistic reasons is certainly fine.
Comment: Major and minor keys can be pretty well defined by a three-note 'tonic' chord.   Maybe even a two-note one.   But introduce the possibility of other modes, we might need a four-note tonic chord.   Otherwise how is a Mixolydian tonic  to be distinguished  from a major? A Dorian from a minor?
Comment: Thank you for the answering my question. However I couldn't help asking that why have we defined a chord that way?
As far as I know if we talk about diatonic chords, they can be any chord with all the notes belonging in that scale. Ain't that right?
Comment: @Ninad Yes, that's true. The only problem is that allowing any notes in the scale to form a chord is overly broad; when talking about other scales, there might be multiple notes that could fit into a single scale degree's chord *(in A Harmonic minor: F is the diatonic F chord, but Fm can be created as well with an enharmonic spelling. E is the diatonic dominant triad, but the sound of E+ is also possible without leaving the scale)*. It is also an unnecessary distinction in major keys and their modes, and generally tonal harmony assumes this rule for its understandings of chords.
Comment: @Aaron - I don't mind if you include the blues scale in your answer!
Answer:
What do you mean by the tonic chord feels as 'home'?

If it doesn't feel like home, you shouldn't call it a tonic. If it doesn't feel like a center, don't give it the number 1. If you TRIED to make it sound like home, but it did not sound like home, then you FAILED. As simple as that. Maybe you tried to do something that's nearly impossible to begin with, and requires extremely high skills. You can say "Locrian", but you can also say "30 feet jump". Easy to say, not so easy to do.

As per my knowledge, every scale has a tonic chord which is
essentially the one all other chords seem to revolve around. The tonic
chord needs no furthur resolution, blends in extremely well within the
entire piece and when the listener listens to this chord they feel 'at
home'. All other chords lack this central vibe and are unresolved.

It's not about which scale and which notes you use, it's how you use them. I highlighted the part that you got wrong.  Let's fix it:

A piece or a passage of music CAN HAVE a tonic chord, which is essentially the one all other chords seem to revolve around. The tonic
chord needs no further resolution, blends in extremely well within the
entire piece and when the listener listens to this chord they feel 'at
home'. All other chords lack this central vibe and are unresolved.

Whether a chord is a central chord that everything revolves around, depends on what happens. Listen to the notes. Does chord X feel like being the center? If not, then it's not a tonic! Music CAN have a tonic, IF the composer or improviser is skillful and able to make something sound like a tonic.
If you play the white keys of the piano randomly, the keys being white does not  guarantee anything about which modal feeling, if any, you create. If you play totally randomly, then it will be a chaos and none of the notes or chords will be a center. But if there's some kind of order and logic in what you play, then one of the notes might feel like a center. If you can play only white keys so that B feels like the center note and B diminished feels like the center chord, then congratulations, you managed to create a Locrian feel. Be careful with what notes and chords you play, you can break the modal feeling easily.
Answer: You're correct about the Locrian mode. It's rarely used, because 'home' is supposed to be a diminished harmony. Which in itself is unstable. So it's somewhat of an oxymoron. In Western music, it's well established that simple major or minor harmonies (chords) are way more stable than any other. Could that be why the vast majority of pieces are deemed to be in major or minir keys? And even the modes present themselves thus: Dorian = minor, Mixolydian = major, etc.
Scales and modes are man-made things, as we love to pigeon-hole everything! And it just happens that some contain weird chords. That's the nature of ordering things. Doesn't necessarily mean they're useful, just that they exist. The make-up of a diminished chord (as in Locrian) is that it contains what we consider dissonance, which in itself we feel needs to be resolved. Just as when we hear G7 we feel it needs to be resolved to C (o.k. not talking Blues here!), and part of that G7 has BDF contained within it. So in reality, there's no sensible way Locrian can be perceived as 'home', as it is, by definition, unstable. Music has been composed using it, but a lot of the time, its purpose is to use its instability, leaving listeners on the edge of their seats.
Comment: Locrian is a nasty unstable place, but if you live there long enough, you'll accept it's your home. ;) It feels bad, but you have to go back there because the composer convinced you that it's your home.
Comment: @piiperiReinstateMonica - sounds just as bad as Turmoil - couldn't get along with being there either...
Answer: Your Tonic chord is simply the core triad, either major or minor that a piece of music is based on.  It has nothing to do with "white keys, or black keys" (Sharps or flats). It it the resolution of a perfect 5th in which the third tone of the fifth is the 7th of the base tonic. A simple example: the take a song in the key of C major. That is comprised of  C-E-G notes. The fifth note is the G. A major cord build on G is G-B-D. If you have been playing and establishing C as your basis and the play a G chord, your ear and instinct will almost compel you to return to the C chord as the resolution or "Tonic".
Why does this happen?  In the example above when we build out the G chord it is a B natural in it.  The B is  just off enough from C, the human ear feels it to be out of place given that tonality has been set to C for a while in the song. It feel resolved when the next note we hear after that B is the C and for the G to also "resolve" back to C. This a V-I resolution and all  keys have them.  If the G chord has a flatted 7th tone (F natural) you ear and brain will feel compelled to shift that F to the E  and the B to C when resolving to the core tonality that was set.  We are hard wired to hear tones resolve this way across all cultures with tonal music. The combination of the B natural and the F Natural (Tri-tone) on its own feels odd to the human ear so you will fell at "Home" once the C chord is played immediately after.
Comment: This does a good job answering the title of the question, but it does seem to be mostly information acknowledged in the premise of the question. The question asks about how all of this would work *outside of the normal major and minor keys*.
Answer: Your understanding of the tonic chord seems just fine.
Your real question is about locrian mode an whether a diminished chord can be a tonic.
I think you should make a distinction between what are musical conventions and some notion of absolute, objective musical qualities.
There is a very long traditional and some acoustical support of the sense of stability in root position major/minor triads. The perfect fifth is what really gives the sense of stability to these chords and therefore the lack of stability in diminished or augmented triads. Another way to think of the "instability" is augmented triads and (fully diminished seventh) diminished chords do not have one single root position inversion. That particular aspect of augmented/diminished chords is often called symmetry, it gives them a certain ambiguous quality, and that ambiguity could be thought of as the "instability."
Another very old tradition is starting and ending a work on the same chord, the tonic chord. There isn't any acoustical rationale for this, but you can make various comparisons to other arts: an architectural arch, the hero returning home in narrative plot, etc.
Neither of those two traditions is a physical law of the universe. As much as people want to invoke acoustics and the overtone series as a rationale for why root position (major only) chords would be perceived as stable these traditions are cultural choices. Being conventions a musician (that an artist not a scientist) can conform to the conventions or buck them intentionally however they see fit.
I think a nice composition to use as an example is Chopin's Mazurka, Op. 17 No. 4, in A minor. Neither the start nor ending use an A minor chord, nor even a root position major/minor chord. The first clear confirmation of A minor isn't until around the 20th measure, and just before the final phrase there is a clear A minor statement. Incidentally, the very first chord is in ascending order A B F, which you could say is a half diminished chord in fourth inversion, that would superficially be a tonic chord for B locrian. Sonically, you can hear the diminished quality of the chord, but I don't really think it's a locrian tonic, I'm just pointing out the coincidence.
We can play around with metaphors and say the ambiguous opening/ending phrases are introduction/coda representing some emotional or nostalgic turning away while the A minor statements are affirmations, some kind of "home." You could turn it around, the ambiguous opening/closing is some kind of tragic "home" and A minor, and the whole middle section, is some escape fantasy, etc. etc. You can go on and say anything you like about it metaphorically. In technical musical terms Chopin started and ended with an ambiguous phrase using inverted chords of the sixth and placed statements around a tonic A minor internally using the harmonic conventions of tonic/dominant harmony. Nowhere in the music did anyone or anything "go home."

What do you mean by the tonic chord feels as 'home'?

If you don't know music theory terms, explaining tonic with a technical explanation about leading tone, perfect fifth, root position, etc. won't make sense. But, a metaphor that fits a lot of music listening experience will. We could play something simple like Handel's famous sarabande in D minor, point out the starting on a D minor chord, the movement to other chords, and then final return to D minor, have all agree this feels like the music is coming to a conclusion, metaphorically call in returning to "home", and then say that "home" feeling is what make the D minor chord the tonic. The technical fact that those "home" tonic D minor chords are all directly connected to dominant chords is skipped... unless the person is starting to learn music theory. In that case the tonic/dominant relationship is exactly what you point out and explain is actually the way the tonic is defined in music.
Can locrian mode, or a diminished chord be a tonic? Well, by long established historic conventions: no. It would literally be reserving the harmonic roles. A diminished chord normally acts as a dominant or the iio in minor is a subdominant.
If we broaden the meaning of tonic to just mean some "main", "central", "focus", etc. tone or chord - sort of the "home" idea - but rather than being defined harmonically with tonic/dominant chords, it will probably be achieved rhythmically, you could have a so-called locrian tonic. Adam Neely has a good video showing several musicians playing in locrian mode. To the extent that the stuff is in locrian mode we have a locrian center, a tonic.

Making the LOCRIAN mode sound good
Answer: You have described perfectly why the Locrian Mode (as a tonic of an entire piece at least) exists almost exclusively in textbooks and contrived exercises.   You understand the feeling of 'home', and recognise that a diminished triad doesn't do it very well!
AS to tonic chords:
If major and minor are the only choices of mode, they can be defined by a three-note 'tonic' chord.   Maybe even a two-note one.   But introduce the possibility of other modes, we start need a four-note tonic chord.   Otherwise how is a Mixolydian tonic  to be distinguished  from a major one? A Dorian one from a minor one?   And when we enter the forest of Synthetic modes, ones that aren't derived from the 'white note' scale, even more complex tonic chords are needed.  Perhaps the whole scale!
Answer: Take any Baby song, children song, folksong, Spiritual and you will recognize that the song is ending on the root tone and root chord, the tonic.
Ex.:
doremifa sososo_ sofamire dododo_
do mi so - so fa mi re do
latidore mimimi- rerere- mimimi- latidore mimimi- miredoti la—-
Mozart's first composition ended all: lasofa mi re do.
other clauses in common practice are: solati do or doreti do.
Also church mode tunes are ending stepwise ascending or descending, so it's like the melody is landing on the ground, like "coming home".
(Forget the locrian! This mode is so rarely, and its root tone is normally a leading or passing tone of other modes. Our ear will miss the home feeling here.


Get class on item.below (child item of menu) inside  tag in menu--main.html.twig

Question: Hi I can't insert class in child item of main menu and remove existing.
Part of my code looks like this:
{% for item in items %}
  {%
    set item_classes = [
    'menu-item-edot',
    item.is_expanded ? 'dropdown',
    item.is_collapsed ? '',
    item.in_active_trail ? 'is-active',
  ]
  %}

    {%
      set link_classes = [
      'nav-link',
      item.in_active_trail ? '',
    ]
      %}

    {{ link(item.title, item.url, attributes.addClass(link_classes)) }}
    {% if item.below %}
      {{ menus.menu_links(item.below, attributes.removeClass('nav-link'), menu_level + 1)  }}
    {% endif %}

So all li tags return:

But I need just top menu items return upper code and all other child menu items to return:

I didn't find way to remove class "menu-item-edot" and add "dropdown-item" to menu child items.
Please help
Comment: Use the `menu_level` variable to determine level and set the classes you want.
Answer: Thank you sonfd this my code now and it's working!
{% for item in items %}

  {% if menu_level == 0 %}

    {%
      set item_classes = [
      'menu-item-edot',
      item.is_expanded ? 'dropdown',
      item.is_collapsed ? '',
      item.in_active_trail ? 'is-active',
    ]
    %}

    {% elseif  menu_level == 1 %}

      {%
        set item_classes = [
        'dropdown-item',
        item.is_expanded ? 'dropdown',
        item.is_collapsed ? '',
        item.in_active_trail ? 'is-active',
      ]
      %}

  {% endif %}
    {%
      set link_classes = [
      'nav-link',
      item.in_active_trail ? '',
    ]
      %}

    {{ link(item.title, item.url, attributes.addClass(link_classes)) }}
    {% if item.below %}

      {{ menus.menu_links(item.below, attributes.removeClass('nav-link'), menu_level + 1)  }}

    {% endif %}