How to convert @tonicjs/tonic chord data to guitar chords?

Question: I am looking at https://github.com/tonaljs/tonal/tree/main/packages/chord which has a lot of music theory I'm less familiar with. When I was playing the guitar for many years 20 years ago, I learned a bit about jazz music theory. In that, we learned how to play 3-string chords (3 notes each), along the fretboard. So if I remember correctly, on strings 3, 4, and 5, you could play the same chord in 3+ different ways, something like that.
So "C major" chord can be C E G on the piano, or like these 5 notes on the guitar.

In that guitar chord, it seems the 3 is a C, and the 1 is a C, so you have some duplication. The 3, 4, 5 strings are 2 0 1, E G C, so that is how my jazz teacher would have had us make the chord. Then move up the fretboard for another position, etc..
The question I have is, given I can do Chord.get("Cmaj").notes === ["C", "E", "G"] from that tonaljs library (you don't need to know code really for this question, it's mainly music theory), I get the basic set of notes for the chord.
The next task that I want to figure out is, how do I compute all possible chords, across all possible tunings, across all possible sets of strings?
Say we have a 6-stringed guitar (or 4-stringed bass), with tunings like these. Given a chord is a minimum of 3 notes, we can choose 3, 4, 5, or 6 strings to play the chord on. Given the hand can reach about let's say 6 frets, that gives us a range of what notes we can play.
How should I go about figuring out how to create a function something like this?
getPossibleStringedInstrumentChords(numStrings, notes, tuning, maxFretDistance)

That is, the tuning would have all the information of which fret has which notes, would that be how you'd do it? The notes is a list like ["C", "E", "G"]. The numStrings is 6 on the guitar. And maxFretDistance is 6 for the finger stretching.
It seems then I would just have to figure out how to create an algorithm which would find all combinations of notes, that is the hard part I will have to work on.
But will this approach work is my overall question? Does it make sense? I guess then I'd wonder what are the most important chords from the set, if that can be automatically figured out somehow... Or you just have to manually create the lists of chords for each tuning for each instrument. Not sure.
Is there something that does this already? Or any more information on the topic that would be helpful? Or does my algorithm sound like the ideal approach to finding all "chord layouts" for a given chord on stringed instruments? I keep seeing things like the "tonic" and the "bass" and "root" and "chroma" and "degree" and "interval" and the like in this library, all new concepts to me, and there's also some midi code dealing with chroma, so I'm not sure if there's a more appropriate conceptual way of getting guitar chords from the chord name or chord notes list.
Comment: I think I once tried this, but I couldn't figure out what anyone could possibly have done with the results. A lot of it is unplayable, because a simple fret stretch limit isn't enough to say if the chord can be played, even if the note combination could theoretically have a meaningful musical purpose. It's much more useful to actually learn to play the guitar than go through thousands of random fingerings, IMO. My gut instinct says that there are too many useless combinations, it's better to learn how to build chords you actually need for a known musical purpose.
Comment: There are surely things that do this already, at least "hardcoded" to a given instrument, because there seem to be a million apps and websites that, for a given chord name, will give you all the possible fingerings...
Comment: Also btw see https://music.stackexchange.com/a/132314/78419 , though you're working in the opposite direction so don't have some of the same concerns
Comment: @piiperiReinstateMonica If I remember correctly, when improvising/soloing on jazz guitar, we memorized the possible 3 variations of each 3-string chord (strings 3/4/5), then that was tied to the scale. So you could memorize 3 * say 100 chords, and now you can match the base rhythm with a solo easily, then branch off from there.
Comment: You don't memorize all chords separately. You only memorize some basic _shapes_ and _patterns_, which can be moved across the fretboard, modified, altered, adapted to taste. And they can get different names depending on enharmonic spellings, voicings and interpretation. Quite often a guitarist leaves out some notes. It may look like a basic minor triad, but the guitarist is doing a 9 chord with those three notes, playing only the upper structure notes. It's not about memorizing a million things. You learn some basic patterns and gradually learn to apply the patterns to different contexts.
Comment: @piiperiReinstateMonica right, well where are the patterns written down? Anywhere on the web? I can't find them. I found https://github.com/tombatossals/chords-db which has >2000 chords, but they are all your standard beginner chords like CMajor at the base of the fretboard. I want jazz chord data...
Comment: I don't understand what you'd do with "data". Learn to play jazz songs and you'll learn chords. First one song, then another. Then learn the tunes in different keys, different arrangements. Find a tutorial about different chord voicings and substitutions. Drop voicings, upper structure triads, etc. Maybe buy or borrow a jazz guitar book?
Answer: Steps:

Transform your base chords to chromatic pitch classes say c=0 to b=11.
Transform your string tunings to chromatic pitch classes
The lowest fret of a chord must be a chord note, so you only need to consider fret positions where at least one string has a chord note
For each such position you get for each string a set of possible pitches, given by the empty pitch, no pitch, or position to position+span (realistically that span would depend on position, e.g. factor * 2^(position / 12)).
Form all combinations of such pitches, optionally with constraints (e.g. all notes must appear at least once, some notes have to appear at least once, the root note must be lowest, ...)

Example:

Chord: C-E-G ≈ 0-4-7
Tuning: E-A-D-G-B-E ≈ 4-9-2-7-11-4

Possible fret positions:

E-strings: 0=E, 3=G, 8=C, 12=E, 15=G, 20=C, 24=E
A-string: 3=C, 7=E, 10=G, 15=C, 19=E
D-string: 2=E, 5=G, 10=C, 14=E, 17=G, 22=C
G-string: 0=G, 5=C, 9=E, 12=G, 17=C, 21=E, 24=G
B-string: 1=C, 5=E, 8=G, 13=C, 17=E, 20=G

So relevant positions are:

0 (E-x-x-G-x-E)
1 (x-x-x-x-C-x)
2 (x-x-E-x-x-x)
3 (G-E-x-x-x-G)
5 (x-x-G-C-E-x)
7 (x-E-x-x-x-x)
8 (C-x-x-x-G-C)
9 (x-x-x-E-x-x)
10 (x-G-C-x-x-x)
and octaves of these positions (12, 13, 14, 15, 17, 19, 20, 21, 22, 24).

It is not necessary to generate positions that can be derived from other positions by leaving out strings, as these can be generated by combining a position with all ways of muting a string. This is relevant to make this example shorter ...
If we use an uniform span of at most 5 frets we get:

Position 0: (0-4)

(0,3,2,0,1,0) → E,C,E,G,C,E
(0,3,2,0,1,3) → E,C,E,G,C,G
(3,3,2,0,1,0) → G,C,E,G,C,E
(3,3,2,0,1,3) → G,C,E,G,C,G

Position 1: (0, 1-5)

(0,3,5,0,1,0) → E,C,G,G,C,E
(0,3,5,0,1,3) → E,C,G,G,C,G
(3,3,5,0,1,0) → G,C,G,G,C,E
(3,3,5,0,1,0) → G,C,G,G,C,G
(0,3,2,5,1,0) → E,C,E,C,C,E
...

...

All in all you can get the positions by pseudocode:
input: notes
input: tuning
input: span
input: maxfret
input: filter_pred

notes = semitone_dist(notes, c) % 12
tuning_bases = semitone_dist(tuning, c) % 12
first_octave_positions = [(notes - tuning_base + 12) % 12 for tuning_base in tuning_bases]
all_positions = extend_positions_by_octaves(first_octave_positions, maxfret)
flat_positions = sorted_unique(all_positions)

solutions

for pos in flat_positions:
    pos_span = pos + span(pos) - 1
    possible_positions = [(0, x, positions in pos:pos_span) for positions in all_positions]
    for combination in cartesian product of possible_positions where at least one coord is pos:
        if filter_pred(combination):
            solutions.append(combination)

Comment: Wow this is unbelievable! Way more clever than [what I was imagining](https://stackoverflow.com/questions/78116718/algorithm-to-compute-all-possible-chords-on-a-guitar-i-e-all-possible-note-com)! Still trying to wrap my head around this.
Comment: I don't get the "relative position" numbers, can you expand them and provide variable names perhaps?
Comment: @Lance I've replaced the chromatic pitch numbers by notenames to be less confusing. Now the numbers all mean fret positions.
Comment: How does this algorithm generate, say, a C13 chord? It has seven notes.
Comment: @piiperiReinstateMonica Obviously it is not possible to play a chord with 7 notes on six strings. But you may omit certain notes. By specifying a suitable selection predicate we may decide which omissions we consider acceptable.
Comment: I was pointing out that practice is not a realization or "implementation" of theory, which the OP seems to assume. Theory is a description of practice. How you learn to play jazz guitar... definitely not by starting with theoretical formulas, and writing computer programs which "implement" the formulas. Without getting involved in the actual culture and learning what's happening, the who, the why, the when.


Problema com assign,

Question: class transaction:
...
def send(from_key, to_key, SN):
    if SN in from_key.parts:
        str(from_key)+str(to_key)+str(SN)=transaction(SN,from_key,to_key,True)

SyntaxError: can't assign to operator
Não consigo atribuir uma int à classe "transaction"...
Vamos supor que
from_key = a
 to_key = b
 SN = 123

Quero chegar no seguinte resultado:
ab123 = transaction(SN,from_key,to_key,True)
Manualmente (fora da função), funciona, mas quando tento automatizar na função recebo esse erro.
Update:
Preciso dar um nome para uma classe (transação) e determinei que esse nome será minha from_key + to_key + SN, no meu exemplo seria ab123.
O problema é que cada vez que eu for realizar uma transação esse nome vai mudar, e criei uma função para realizar esse assing sozinho (ab123 = transaction(...)).
Como posso fazer isso dar certo?
Comment: Isso está me parecendo um [Problema XY](https://pt.meta.stackoverflow.com/q/499/5878). Aconselho você a cogitar a ideia de [edit] a pergunta e explicar por texto o que está querendo fazer, no contexto geral. Não faz sentido definir uma variável dinâmica assim.
Comment: Você não consegue fazer uma atribuição dinâmica desta forma. O que você quer é gerar dinamicamente a variável "ab123" conforme os parâmetros da função? E o que você fará com essa variável?
Comment: Eu quero gerar a variável de acordo com o que eu inseri na função send, no meu exemplo seria `send(a,b,123)`.
O meu problema é quando tento atribuir a variável à uma classe.
Por que `ab123 = transaction(...)` funciona e `str(from_key)+str(to_key)+str(SN)=transaction(...)` não?
Comment: Por que precisa fazer isso? O que fará com a variável?
Comment: Não é possível atribuir um valor a outro valor. No caso você está fazendo algo como `"a" + "b" +"123" = transaction(...)`.
O que você pode fazer e criar um dicionário e inserir estes valores usando a string gerada como chave.
Comment: como eu faria isso @fernandosavio?
Comment: vou formular uma resposta pra facilitar
Comment: A variável deve passar a ser uma transação, que por sua vez guarda informação da mesma @AndersonCarlosWoss
Estou montando uma blockchain pro meu TCC, mas não tenho muito conhecimento na área de programação, se alguém estiver disposto a ajudar...
Comment: E por que ela não pode ser uma variável normal, tipo `trans = transaction(...)`?
Comment: Porque eu teria que fazer isso manualmente... eu quero que a função, de acordo com o que eu inseri nela, faça o assing automático.
Essa função realizará outras ações junto com essa...@AndersonCarlosWoss
Comment: Atualizei o post tentando explicar melhor @AndersonCarlosWoss
Answer: Tu pode criar um dicionário e usar a string gerada como chave:
cache = dict()

def send(from_key, to_key, SN):
    if SN in from_key.parts:
        key = str(from_key) + str(to_key) + str(SN)
        cache[key] = transaction(SN, from_key, to_key, True)

Para recuperar o resultado de transaction(...) é só usar:
print(cache['ab123'])  # ou qualquer que seja a chave

Comment: Retorna: `NameError: name 'cache' is not defined`
Comment: É preciso que cache esteja no escopo de onde tu está tentando acessá-la... Isso vai depender de como tu codificou.
Comment: estou programando na nuvem, em um jupyter notebook.
Comment: me refiro ao escopo do python mesmo.
olha [esse exemplo](https://repl.it/@fernandosavio/UnkemptBulkyOutsourcing) desde que se consiga acessar a variável cache dá pra guardar e ler informações
Comment: dessa forma que está no link ele não define a variável ab123.
Eu gostaria de poder definir a variável ab123 como sendo uma classe transação.
Comment: O resultado teria que ser o mesmo de `ab123 = transaction(...)`
Comment: João, não faz sentido você definir variáveis de forma dinâmica. Como acessará as variáveis depois se você não saberá os nomes das mesmas? O que você está fazendo definitivamente é um Problema XY e qualquer solução será gambiarra. Se quer um nome, passe por parâmetro uma *string*. Se quer persistir esse objeto em algum lugar, persista associando o nome ao objeto. Sem conhecer o problema inteiro, qualquer resposta aqui será mera especulação, com 96.37% de chance de ser gambiarra.
Comment: Um `dict()` serve justamente pra isso. No exemplo que te mandei poderia ser uma instância de `transaction`, sem problemas. A diferença é que ao invés de acessar como `ab123` se acessa `cache['ab123']`
Comment: O problema de se criar "variáveis dinâmicas" se resolve com `dict`, mas é como o @AndersonCarlosWoss comentou. O que sabemos do teu problema é muito raso, então só podemos torcer para que seja isso que tu precisa.
Comment: Desculpem por isso, como disse, não tenho conhecimento na área. Se quiserem dar uma olhada no código está aqui: https://github.com/veronamlima/notebook/blob/master/Blockchain%20V3%20(class).ipynb

Problema com assign,


Enum value not found for "Normal" Maui App.xaml

Question: Finishing migration from Xamarin to Maui .net 8 and i am getting the following error with no line numbers so i can pinpoint where the issue is.
below is app.xaml that it say erro is stemming from
In the code only thing using the normal enum is buttons.  I have searched have not seen this topic.  I am not in anyway a great xaml coder i am assembly and c embedded mostly.  SO take it easy on me.
<?xml version="1.0" encoding="utf-8" ?>
<Application
    x:Class="TwosenseChatterbox.App"
    xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:converters="clr-namespace:TwosenseChatterbox.Behaviors"
    xmlns:themes="clr-namespace:TwosenseChatterbox.Themes;assembly=TwosenseChatterbox"
    xmlns:vm="clr-namespace:TwosenseChatterbox.ViewModels">
    <Application.Resources>

        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <themes:LightTheme />
            </ResourceDictionary.MergedDictionaries>

            <vm:ViewModelLocator x:Key="locator" />
            <converters:StringToBoolConverter x:Key="EnabledWhenFilledConverter" />
            <converters:StringToFloatConverter x:Key="OpaqueWhenFilledConverter" />

            <Color x:Key="CustomerColor">White</Color>
            <Color x:Key="QrColor">White</Color>
            <Color x:Key="SummColor">White</Color>
            <Color x:Key="AWSColor">White</Color>

        </ResourceDictionary>

    </Application.Resources>
</Application>

Comment: You wrote "_i am getting the following error..._" but you never actually posted the full error message, details, and where you saw it (Build error list? XAML Binding Errors list? Runtime exception?)
Answer: I inferred that your error is here:

The enum Microsoft.Maui.Controls.FontAttributes type does not have a member named Normal - change it to None.
...curiously, Xamarin.Forms.FontAttributes also lacks a Normal member too, so I wonder where you got Normal from in the first place.
Comment: Yes that fixed it thanks i did check it is in my Xamarin code same way as well


Calcular reta tangente pela coordenada do mouse/rato

Question: Estou querendo calcular a reta tangente aos pontos X e Y encontrados pelo mouse, limitando-se ao circulo desenhado... Só consegui desenvolver até a metade do programa. Alguém pode me salvar??
Estou desenvolvendo o programa no processing para fins academicos.
Segue meu código até agora:
void setup() {
    size(300, 300);
}

void draw()
{
    int x = 0;
    float nX = mouseX, nY = pow(mouseX,2)/300;

    noStroke();
    fill(255);
    rect(0,0,300,300);

    fill(255,0,0);
    ellipse(nX,nY,10,10);
    text("  "+nX+" "+"/"+nY,nX,nY-5);

    fill(255,0,0);
    stroke(3);
    line(nX, 0, nX, 300);
    line(0, nY, 300, nY);

    while (x < 300) {
        fill(0);
        ellipse(x, x*x/300, 2, 2);
        x = x + 1;
    }

}

Comment: Hum... pra mim não ficou muito claro o que você quer fazer. Qual é o efeito que deseja? O programa vai desenhar um círculo no primeiro clique do mouse, e então vai desenhar a tangente ao círculo *num novo ponto* sob o círculo em que o usuário clicar, é isso? Pode incluir na pergunta uma ilustração do resultado final?
Comment: pode nos mostrar com um desenho o resultado final que vc espera?
Answer: Para calcular a reta tangente, precisamos calcular a derivada, que nos dará o coeficiente angular da reta:

Então desenhamos uma linha que passa pelo ponto do mouse e com o coeficiente angular igual a derivada aplicada nesse ponto.
Os dois pontos A e B que formam essa reta devem ter x = 0 e x = 300, respectivamente, e calculamos a altura usando a fórmula da reta tangente:

Sendo P o valor de x do mouse, fazendo as contas para os pontos, chegamos em:

Agora, finalmente... a programação:
Vendo que  é igual a nX e  é nY, e declarando coef como ...
float coef = nX / 150;
line(0, nY - coef * nX, 300 , nY + (300 - nX) * coef);

Pronto! Isso vai fazer a sua reta tangente!


Entendendo o escopo de arrow function + callback

Question: Gostaria de ter acesso ao valor de uma variável retornado de um callback fora da função callback, e também queria entender o porque que não acontece um erro de sintaxe quando tento usar uma variável que não existe dentro do escopo da função callback. Criei o exemplo abaixo para demonstrar:
var armazenarValor

var meuObj = {
  espera: function(valor, callback){
    setTimeout(()=>{
    callback(valor)
  },2000)
  }
}

meuObj.espera("valorQualquer", (valor)=>{
  armazenarValor = valor
  variavelQueNaoExiste = 'Eu não existo'
  console.log(variavelQueNaoExiste)
})

console.log(armazenarValor)

O valor da minha variável armazenarValor é undefined, mas gostaria que ela guardasse o valor do parâmetro valor, para mim utilizar em outras partes do código.
E a variável variavelQueNaoExistenão é declarada em nenhuma parte do código, mas mesmo assim ela funciona.
Answer: O JavaScript não pára a execução do código por teres um setTimeout, ele continua a correr o código até esse setTimeout terminar. Se a função desse retorno direto sem ter uma parte assíncrona, aí o valor de retorno poderia ser usado, ou se a callback fosse usada sem ser assíncronamente...
Isso quer dizer que console.log(armazenarValor) é corrido antes dessa callback correr, e por isso antes do valor de armazenarValor ser mudado.
Repare neste exemplo para perceber melhor a ordem de execução:

var armazenarValor

var meuObj = {
  espera: function(valor, callback){
    setTimeout(()=>{
    callback(valor)
  },2000)
  }
}
console.log('antes de chamar meuObj.espera()', armazenarValor);
meuObj.espera("valorQualquer", (valor)=>{
  armazenarValor = valor
  variavelQueNaoExiste = 'Eu não existo'
  console.log('dentro de chamar meuObj.espera()', armazenarValor)
})

console.log('depois de chamar meuObj.espera()', armazenarValor)

Leitura recomendada:

Alternativas de encadeamento de funções assíncronas
Usar o callback de uma função
O que é callback?
Comment: Obrigado Sergio! O uso do `'use strict'` faz com que ele aponte erro. Vou dar uma lida nos links que você me enviou primeiramente antes de criar uma nova pergunta, obrigado pelas referências!
Comment: Eu fiz um teste jogando tudo dentro de uma função async e utilizando o operador await para ver se seria possível ter o valor atualizado de `armazenarValor` mas mesmo assim não deu. O que eu de fato gostaria é conseguir ter acesso ao valor atualizado de `amazenarValor`sem ser somente dentro da função callback.
Comment: @FábioJunioAlvesSousa tens mesmo de usar o valor dentro da callback. Podes usar `async/await` mas nesse caso tens de ter uma promise e uma callback para o `.then` de qualquer maneira...
Comment: Juntei links de leitura à resposta para poderes ler mais sobre isso.
Comment: Eu criei esse exemplo para ilustrar a dúvida que estou tendo com a utilização de um pacote npm, o uso dele segue essa estrutura ai, como tenho que usar vários métodos e cada método depende do valor retornado do método anterior, acabarei criando uma cascata de métodos, então queria tentar escrever um código "mais limpo" evitado esse cascateamento de métodos. Em relação o uso da variável que não foi declarada em nenhuma parte do código, sabe me dizer pq isso funciona?
Comment: @FábioJunioAlvesSousa cria uma nova pergunta com o código em cascata que queres corrigir se precisares de ajuda. O primeiro link que coloquei no fim da resposta ajuda nisso. Em relação a `variavelQueNaoExiste` isso é (infelismente) possível em JavaScript. Mas se usares modo _strict_ ou boas regras de ESLint isso acusa erro.


Custom URL for Google Apps

Question: Requirement: I want to create custom URL to access my company google apps account.
Ex: mail.companyname.com
Effort made: https://support.google.com/a/answer/53340?hl=en
Error : users are still able to access email from gmail.com
Expectation:Employees should be able to access email through this custom URL only.
Comment: Hi Here is what i tried, https://support.google.com/a/answer/53340?hl=en     But end users are still able to access email from gmail.com
Answer: The original google URL will always still work.  Your custom URL doesn't replace it, but works in addition to it.

Custom URL for Google Apps


Safe user template system

Question: Is there a template system for users that would be very safe, and very simple? I'm looking for something along the lines of the following:

Hello [first_name],
We hope you have enjoyed the
  [product.name] purchased on
  [transaction.date] for
  [product.price].

I realize this is kind of a contrived example, but what I'm looking to do is give users the ability to customize some information but not give them PHP as that would be out of control.
I would use a filter editor, but I need to provide the context for the variables and I'm not sure how much it would complicate matters to have to provide that context, (which could not be done from a filters standpoint so far as I know because I'm providing one template for many nodes)
Comment: To which Drupal version are you interested?
Comment: Ah, I probably should have tagged that - drupal 6 would be best, but the answers I've got are very good.
Answer: You want http://drupal.org/project/token
There are also modules which allow to use tokens in nodes and other places, you can use it in custom places and also define your own tokens.
The token API is even part of Drupal 7 core.
Answer: There are some modules that implement an input filter which allows you to decide which text is replaced in the body of the node and with which text needs to be replaced.

Custom filter allows the administrator users to define, through regular expressions, which text is replaced and, through a string or PHP code, the replacement text. Normal users cannot decide neither which strings to replace nor the replacement strings; this means that they cannot do anything bad by creating a replacement rule using unsafe PHP code.
Regex Filters is a module with similar features.
Rep[lacement]Tags allows you to define tokens like {AUTHOR} which will be replaced.
Token Filter replaces, for example, text like [token user <token>] with the content of the user token implemented by a module. This module requires Token.

Safe user template system


React Router does not clear state when navigating to another URL with the same route but a different dynamic segment

Question: I'm using React Router 6.16.0 to create a single page application. The application has a route like /page/:pageId. This works fine.
When this page is opened it contains links to other pages with different pageId values, but still under the same route. So, for example, if I opened the URL /page/1, there could be links there to, say, /page/2 and /page/3. Clicking on these links navigates to those other pages which also works fine.
The /page/:pageId page also has some other interactive elements. I tested this with theexample of a counter:
const [counter, setCounter] = useState(0);

    Counter: {counter}
    <button type="button" onClick={()=>setCounter(counter+1)}>Klik me</button>

Clicking the button increases the counter, as expected.
However, what surprised me was that navigating to a different pageId via the above mentioned links does not reset the counter. Only if you navigate to a completely different route and then back again will the counter get reset.
On one hand this makes sense because from React's point of view it's still the same component being rendered. On the other hand, from a user's point of view they've navigated to a different page and it should be reset.
I could work this into the component itself (that it would detect the change of ID and reset itself) but it feels like this should be handled by React Router instead. Unfortunately I cannot find a setting that would control this behavior. Is there such a setting?
Answer: To get this behavior, you can use react keys. If you had multiple <Route>s with ids that are known up front, you could put the key right where you render the route:
<Route path="/page/1" element={<Page key={1}/>} />
<Route path="/page/2" element={<Page key={2}/>} />

In your case though where you're using a route parameter, you won't know the key at the time you render the route. So you'll need to handle it in the page component. I suggest splitting the page component into an inner and outer component. The outer component is just in charge of remounting the the inner component.
<Route path="/page/:pageId" element={<Page/>} />
//...

const Page = () => {
  const { pageId } = useParams();
  return <InnerComponent key={pageId}/>
}

const InnerComponent = () => {
  const [counter, setCounter] = useState(0);

  return

    Counter: {counter}
    <button type="button" onClick={()=>setCounter(counter+1)}>Klik me</button>

}

Comment: Hmm, yes, that would work. But it's really a workaround. Is there indeed no way to make React router do this by itself? It feels like this should be standard/default functionality.
Comment: Correct, there is no way to make react router do this by itself. The `` component looks through its children, evaluates their paths against the current location, and then outputs the corresponding element. When react does reconciliation, it just sees that element, not the logic that went into choosing it. Absent a key, the react will compare the element types, see that the type has not changed, and thus update the instance instead of unmounting. A key can be provided to override this behavior. https://react.dev/reference/react/useState#resetting-state-with-a-key
Comment: In principal, the `` component could have been built differently, so that instead of outputting 1 element, it outputs a bunch of nulls for inactive routes and 1 element for the active route. And then when the route changes, a null would become an element, and an element become a null, which could then cause mounting/unmounting. But they didn't design it that way. I don't know the history of why they implemented it the way they did.
Comment: Alright, thanks! I would think that the easiest way would be for React router to add a random `key` whenever navigation happens. But it doesn't do it, so it doesn't matter. No problem, I can add it myself.
Comment: Using a React key to force remount the routed component ***is*** a workaround. A "more correct" method could be to use a `useEffect` hook in the routed component to reset the `count` state when the path parameter changes. See the marked duplicate that covers both these use cases/solutions.
Comment: While that does work, I disagree that that's a "more correct" approach. It does give you the ability to do more targetted resets if you want, say, some states to reset and others to not. But if your goal is to do a complete reset (reset all states, blur the focused element if any, clear all uncontrolled inputs, etc), then changing the key is the standard way to tell react to mount a new instance when the element type alone is not enough.


Azure App Insights alert triggers but failure not found in logs?

Question: I'm new to Application Insights Alerts and think I may have misconfigured something. I need to be alerted when an Azure Function fails to execute.
Setup App Insights Alert

Trigger alert when count of failures > 1 within a 60min period

Alert triggered 3x in the past week

No failure conditions have existed on this Function since 12/2/2020

How do I correlate an App Insights alert with its corresponding log file?
Seems like this should be a "one-click thing" but I must be missing it somewhere.
EDIT 1: Here is the exceptions table. Same findings; no fails since 12/2.

EDIT 2: Here is the dependencies table. Nothing found in last 30d.

EDIT 3: Per the recommendation on another post, I changed the alert from the out-of-the-box Metric to a Custom log search.

I left the original alert (that failed for no reason) in place alongside the new one.
The original one just failed again for no reason

Details:

Alert emails say:

Start 2021-01-06 8:22 UTC
End 2021-01-06 11:22 UTC

Function Monitor shows Function ran SUCCESSFULLY at:

2021-01-06 08:13:21.368 UTC
2021-01-06 08:13:21.372 UTC

Detailed logs show the function ran successfully

At this point, I'm going to say the Metric version of alerts should be discarded. What ever its logic is based on has created false positives for me a number of times now.
Stick to the custom log search
Comment: can you please also check the `exceptions` table and `dependencies` table in azure portal -> application insights -> logs, to see if any errors there?
Comment: @IvanYang, please see Edit1&2 in OP. Nothing found in those tables.
Answer: The alert is triggered when at least 2 (because that is what the treshold of > 1 means) failures occur in a timespan of 1 hour. All three alerts of last week (2nd screenshot) where triggered on a different day.
Are you sure you don't need to set the threshold to Greater than 0 so that each failure triggers the alert?
Comment: Good point. I'll change that. Regardless of the threshold, there is no "failure" (`Success = False`) in the logs during that time period.


Contar numero de elementos de uma lista python

Question: tenho a seguinte lista:
lista = [ 'A','B','C','D']

eu quero que conte o numero de elementos ate determinado ponto, eu sei que se fizer len(lista) vai contar todos os elementos mas oque eu quero é por exemplo ate o C ele vai me dar o numero 3.
Comment: @WictorChaves sua resposta é diferente e também da o resultado esperado por ele, mais de uma solução é bem vinda sempre! :D
Comment: E se houverem dados repetidos na lista? Por exemplo, `['a', 'b', 'c', 'd', 'c']`, o resultado deve ser 3 ou 5? Deve sempre considerar a primeira ocorrência?
Comment: Um for não resolveria o seu problema?
Comment: mas tipo usei pra contar ate o C só como exemplo, eu quero fazer uma pergunta, e contar ate a letra que a pessoa responder
Comment: Mas isso da para fazer com for, vou fazer uma resposta como exemplo para você
Comment: Eu iria responder, mas o Marcos .p, fez um código melhor que o meu
Answer: Apenas pegue o índice e some com mais  1, já que o primeiro índice é 0.
lista = ['A','B','C','D']
print lista.index('C') + 1;

Para pegar o índice do array utilize o método "index".
Comment: Muito obrigado!
Answer: Você pode usar o index para encontrar a posição do elemento desejado e calcular a quantidade descontando do total de elementos, por exemplo:
lista = [ 'A','B','C','D']
indice = lista.index('C')
(indice + 1)

Answer: Outra forma seria usando o for, como o Wictor propos nos comentários:
i = 0
lista = [ 'A','B','C','D']

for x in lista:
  i+=1
  if x == 'C':
    break;
print(i)

Mas usando index() da resposta do Wictor é mais simples e elegante.


Redirect service on nginx

Question: I have a dynamic list of redirects from a relative url on my site to some other absolute url:
my_website_url_1 --> other_website_url_1
...
my_website_url_N --> other_website_url_N

This list consists of several hundreds of entries and is changed a few times per day.
(Actual list is in the DB, but it can be in a text file or in whatever form comfortable.)
"My site" is an nginx server.
I'm looking for a robust solution to deploy redirect list changes to an nginx server without interrupting the service.
Any advice?
Replacing nginx with something else is an option.
Answer: I wrote a small rack app a long time ago exactly for this purpose. You can check it out at http://github.com/minhajuddin/redirector
From the readme:

Redirector
A simple rack application which makes redirection of multiple domains a breeze.
Configuration
To configure the application all you have to do is edit the config.yaml file, the following is a sample configuration file:
cosmicvent.net: # <== This is the host name of the domain which you want to redirect
  status: 302 # <== status code with which it is redirected, 302 for temporary redirects, 301 for permanent redirects
  location: 'http://cosmicvent.com' # <== the domain which it is redirected *to*

'localhost:3030':
  status: 301
  location: 'http://cosmicvent.com:3030'

Answer: I'm not sure what the best option is in your case. I suppose that you could create a cron job that generates part of your nginx config and then reloads, but that seems like a dangerous hack to me.
Depending on how much load you are getting on the relative URLs, you could just have your application code fire off the redirects. For example, if you're using PHP, check the incoming URL to see if it is your redirect table, if it is, send back an HTTP redirect to the canonical URL.
Answer: One idea is to have a database (MySQL or what have you) table that you can populate with your redirects.  Every hour or so, cron can fire off a script that will examine that table, see if there are new entries from the last time it ran, and then generate a new nginx config based on what it finds in that table.
I'd suggest using something like Ruby + ERB to get this done.
Afterwards, it can issue a reload against nginx to avoid service outages.

Redirect service on nginx


Textarea inset box-shadow now showing up on mobile

Question: Box shadow is working fine for input and select fields. On desktop, textarea box shadow is working fine too. Even when I resize the window to mobile size. But when I check the site on Safari or Chrome on my iPhone, the box shadow does not show up for the textarea. Input and select fields show up fine on mobile. Here is the link to the page. How can I fix this?
Answer: Found the answer. I needed to put -webkit-appearance: none; in the CSS rules for the textarea.
Answer: Are you using '-webkit-box-shadow'?
Its required for Safari I think.
(https://css-tricks.com/almanac/properties/b/box-shadow/)
Edit: Maybe try just clearing cache for the site. The css files will refresh.
Comment: The answer doesn't necessarily provide solution to the question


Visualising hyperplanes arising from linear systems of curves

Question: From what I understand, projective plane curves $F$ of degree $d$ which pass through a point $P\in\mathbb{P}_K^{2}$ with multiplicity $\geq m$ form a linear system of projective curves in $\mathbb{P}_K^{D}$, where $D=\frac{1}{2}d(d+3)$ and it has co-dimension $\frac{1}{2}m(m+1)$. That is curves of degree $d$ passing through $P$ form a hyperplane in $\mathbb{P}_K^{D}$.
I would like to however come up with a concrete example of such a hyperplane that I can produce in MATLAB. I understand the intuition but I think such an example would help me visualise how such linear systems form hyperplanes.
Answer: Note that a plane curve of degree $d$ is given by the zeros of a degree $d$ polynomial
$$
F(x,y,z) = \sum_{i+j+k=d} a_{ijk}x^iy^jz^k
$$
which gives a vector $v = (a_{ijk})\in K^{\frac{(d+2)(d+1)}{2}}$. Since F is defined up to a scalar multiple $v$ is better suited as a point in $\mathbb{P}_K^{\frac{(d+2)(d+1)}{2}-1}= \mathbb{P}_K^{\frac{d(d+3)}{2}}$.
Now note that, for a fixed $P$, $F(P)$ is a linear combination of the $a_{ijk}$ with coefficients in $K$. This linear expression defines a hyperplane $H$ in $\mathbb{P}_K^{\frac{d(d+3)}{2}}$ with the property that $F(P)=0$ if and only if $v\in H$.
To compute it explicitly just write a polynomial $F$ with arbitrary coefficients, choose a point $P$ and compute $F(P)$.
If we choose $P=(0:0:1)$ and write $$F(x,y,z) = A(x,y)_d + A_{d-1}(x,y)z + \cdots+ A_1(x,y)z^{d-1}+A_0z^d$$
we can see how the other hyperplanes appear as the multiplicity grows.


Como colocar colunas bootstrap lado a lado com justify-content-around?

Question: Como posso colocar a coluna amarela colada no lado da coluna roxa?
clique para visualizar em seu tamanho original

<!DOCTYPE html>

  <link rel="stylesheet" href="https://email@example.com/dist/css/bootstrap.min.css" integrity="sha384-zCbKRCUGaJDkqS1kPbPd7TveP5iyJE0EjAuZQTgFLD2ylzuqKfdKlfG/eSrtxUkn" crossorigin="anonymous">
  <link rel='stylesheet' href='estilo.css' type='text/css' />
  <title>Site Com Bootstrap</title>

        ...

        ...

algo

Comment: É só colocar a classe `ml-auto` na coluna amarela
Comment: Não funcionou corretamente, foi pro lado do roxo? sim, funcionou, mas o justify-content-around foi modificado, quando usa esses margins eles colocam as colunas colada nas margens. Por exemplo, se alguem tentar posicionar a coluna roxa no lado do amarelo, esses margins não funcionam.
Answer: Amigo,
Faz uma estrutura assim:
Container
  Row
    Col
      Coluna Verde
    Col
      Container
        Row
          Col --> Aqui use o espaçamento que desejar
            Coluna Amarela
            Coluna Roxa

Comment: Sua resposta pode ser melhorada adicionando informações fundamentais. Basta [edit] para adicionar mais detalhes, como citações ou documentação para que outras pessoas possam confirmar que sua resposta está correta. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).
Comment: poxa, num tem algum comando tipo float:right?
Comment: float:right testei e não pegou ,gostaria de algo assim para eu colocar na coluna


ubuntu 12.04 - svn relocated and system restart

Question: I think my server has been hacked but I cannot be sure.
I had installed and got running svn on ubuntu 12.04. After installing I got one machine to checkout the repository on username joe. Last night I checked out the repository on my own machine on username john. But suddenly today I get this message when trying to commit:
'ERROR Repository moved temporarily to 'http://www.mydomain.com'; please relocate'
I don't know where to start looking here, some search results indicate it might be a hook script, other say sloppy config files.
I have svn installed with webDAV. The config file is:
/etc/apache2/mods-available/dav_svn.conf:
<Location /backuprepos/filesystem>
DAV svn
SVNPath /home/backuprepos/filesystem
AuthType Basic
AuthName "filesystem subversion repository"
AuthUserFile /etc/subversion/passwd
Require valid-user
</Location>

The passwords I added to the following file:
htpasswd -c /etc/subversion/passwd user_name

Really need to some help..
Answer: At long last I found the answer to my problem.
We had a htaccess blanket rule for all 404's which redirected to the index
SVN apparently uses 404 (not found) errors in order to add new resources. Thus the 404 redirected the svn to the rootYou must allow this one to pass through instead of making a redirection, or svn will get confused.


How to find window running with own UI thread in WPF application

Question: I have an application that uses a WPF Window with an own Dispatcher as startup splash window. This splash screen will show information to the user and is a TopMost window. I don't want to have it as the Application.MainWindow but has to show it before I create the MainWindow...
At any time durring startup or while the application is running, an background worker can detect an fatal error and need to show an message box before the application is terminated. This message box needs to be in front of any open window.
When this error happend while the splash window is visible, the message box is behind the splash screen. Using the splash screen as owner or hide the splash screen whould fix that, but i'm not able to find the splash screen. It's not in the Application.Current.Windows collection, I guess because it has a different Dispatcher...
Does anyone know how to get the window without passing them to the background worker?
The following code reproduces the problem. It whould be easy to pass all needed references to the worker but it's not what i want do to in the real application.
App.xaml
  <Application
     x:Class="Sandbox.App"
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  >
  </Application>

App.xaml.cs
     using System;
     using System.Linq;
     using System.Threading;
     using System.Windows;
     using System.Windows.Controls;
     using System.Windows.Media;
     using System.Windows.Threading;

     namespace Sandbox
     {
        public partial class App : Application
        {
           protected override void OnStartup(StartupEventArgs e)
           {
              base.OnStartup(e);

              var closeSplashEvent = App.LanuchSplashScreen();
              App.StartThreadInDifferentAssemblyWithoutRefToThis();

              // ...

              this.MainWindow = new Window { Title="MainWindow",  Width = 800, Height = 600, WindowStartupLocation = WindowStartupLocation.CenterScreen };
              this.MainWindow.Show();

              //  ...

              App.CloseSplashScreen(closeSplashEvent, TimeSpan.FromSeconds(5));
           }

           private static void StartThreadInDifferentAssemblyWithoutRefToThis()
           {
              ThreadPool.QueueUserWorkItem(_ =>
              {
                 // ...
                 Thread.Sleep(1000);

                 Application.Current.Dispatcher.Invoke((ThreadStart) delegate
                 {
                    // how to find the splash screen ???
                    var owner = Application.Current.Windows.OfType<Window>().FirstOrDefault(w => w.Title == "SplashScreen") ?? Application.Current.MainWindow;
                    MessageBox.Show(owner, "Should be in front of splash screen!", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                 });
              });
           }

           private static ManualResetEvent LanuchSplashScreen()
           {
              Dispatcher splashDispatcher = null;
              var startupEvent = new ManualResetEvent(false);
              var splashThread = new Thread(() =>
              {
                 splashDispatcher = Dispatcher.CurrentDispatcher;
                 startupEvent.Set();
                 Dispatcher.Run();
              });
              splashThread.SetApartmentState(ApartmentState.STA);
              splashThread.Start();
              startupEvent.WaitOne();

              Window aniSplashWindow = null;
              splashDispatcher.Invoke((ThreadStart)delegate
              {
                 aniSplashWindow = new Window
                 {
                    Width = 320, Height = 240, AllowsTransparency = true, Background = Brushes.Transparent, Topmost = true, WindowStyle = WindowStyle.None, WindowStartupLocation = WindowStartupLocation.CenterScreen,
                    Title="SplashScreen", Content = new Border { BorderBrush = Brushes.Black, BorderThickness = new Thickness(1), Background = Brushes.White, CornerRadius = new CornerRadius(5) }
                 };
                 aniSplashWindow.Show();
              });

              var closeSplashEvent = new ManualResetEvent(false);
              ThreadPool.QueueUserWorkItem(_ =>
              {
                 closeSplashEvent.WaitOne();
                 splashDispatcher.Invoke((ThreadStart) delegate
                 {
                    aniSplashWindow.Close();
                    splashDispatcher.BeginInvokeShutdown(DispatcherPriority.Normal);
                 });
              });

              return closeSplashEvent;
           }

           private static void CloseSplashScreen(EventWaitHandle closeSplashEvent, TimeSpan closeSplashTimeout)
           {
              ThreadPool.QueueUserWorkItem(_ =>
              {
                 Thread.Sleep(closeSplashTimeout);
                 closeSplashEvent.Set();
              });
           }
        }
     }

Answer: I assume that the splash screen exists only once. So why not make it a singleton?
The simplest solution would be to expose it via a global (static) property. Alternatively, (if you create some SplashScreen class), you could export and import it via MEF or some other composition framework.
Comment: I think passing them to the worker would be better than making the splash a static or singleton. Static/Singleton would require that the worker knows the splash screen/app which is a dependency I don't like. MEF or IoC would allow to fix the problem as well.

The point is that i really don't believe it's not possible to find the current active window in a WPF application when it has its own UI thread...


Deviance Residuals curvature

Question: I was wondering if somebody could help with a question concerning GLM diagnostic plots. Specifically, I am running a Binomial GLM and when I go through diagnostic plots such as Deviance Residuals vs Fitted values, I get the following:

Personally, it looks as if there is curvature so an issue with my model fit. Would people agree this plot suggests misfit?
Comment: I think you might be reading too much into this.  The impression of curvature entirely disappears if you remove just one or two selected points out of these 22.
Comment: If you want to assess whether your impression of curvature may just be noise or not, one approach is to simulate observations from the fitted model and plot their residuals -- say a dozen times to a couple of dozen times. If none of them look as curved, you have an indication that your plot suggests something else is going on. If several of them look as curved or more curved then you may be dealing with nothing more than noise. Even if you can be fairly confident it isn't just noise it may be that the effect is small enough that you don't especially care (*all models are wrong*, etc..etc... )
Comment: Thanks for the reply! One additional note on this, do we rescale the y-axis when plotting residuals vs fitted values? For example, I have set it at [-2,2] here because this is a standard range. The curvature does become more apparent if I do not rescale...
Comment: That's an interesting question about data visualization, which deserves more discussion than can occur in comments.  I do notice, though, that some of your points seem to be overplotted: it appears you might have more (perhaps far more) than 22 of them.  If that's the case, then it would be worthwhile to jitter them a little so you can see whether that makes a difference.
Comment: You are correct, there are 2 points overlapping - jittering really didn't make too much of a difference. Thanks for the replies!
Comment: Why would curvature from the simulated residuals indicate noise? Apologies for the naivety of the question, I haven't used simulations before.
Comment: What kind of model did this come from (normal, logistic, etc)?
Comment: It was a logistic model.
Answer: I agree with the comments that there is no indication of a problem in this plot.
That being said, even if you had more data, deviance residuals wouldn't be a good way to test for such a dependence, because also a perfectly fitting binomial model may exhibit inhomogeneous deviance residuals.
What works is the simulation approach suggested by Glen_b. This is implemented in the DHARMa R package, which uses simulations from the fitted model to transform the residuals of any GL(M)M into a standardized space. Once this is done, you can visually assess / test residual problems such as deviations from the distribution, residual dependency on a predictor, heteroskedasticity or autocorrelation in the normal way. See the package vignette for worked-through examples.

Deviance Residuals curvature


split column into character and numeric in R

Question: I split a data frame into X and Y. X has one column, Y has about 100.
x <- subset(tbl, , select = ordernum)
y <- subset(tbl, select = -c(ordernum, paid1num,
          weight, returnnum, order_only, multi_dep, sequence_id))

Next I correlate X with each column in Y which produces a frame with 100 columns and a single row.
corr <- cor(x,y)

Next I transpose,
corr.t <- t(corr)

and the (truncated) result looks like this:
                                   ordernum
HH_AFFORD_MOMS_BUY_GREEN      -0.0021281583
HH_AFFORD_SPORTS              -0.0047221159
HH_AFFORD_CLASSICAL_MUSIC     -0.0006594956
HH_AFFORD_HOME_DECOR           0.0052106766

I would like to split this single column, called ordernum, into 2 columns. A character field with the variable names, and a numeric with the correlations.
I appreciate any guidance. Perhaps if I use lm, instead of cor?
Answer: The output that you have stored as corr.t is a matrix, and the "variable names" you mention are the row names of the matrix, accessible using rownames().
To get your desired output, you can just do:
data.frame(id = rownames(corr.t), val = c(t(corr.t)))

A more general solution--applicable when your matrix is more than just one column--would be:
data.frame(ID = rownames(your-matrix),
           as.data.frame(your-matrix,
                         row.names = 1:nrow(your-matrix)))

The last line, row.names = 1:nrow(your-matrix), removes the row names from the output; they are no longer needed since they are now part of your data frame.

For what it's worth, you don't actually need to specifically transpose your data to get to the output you desire. Here's an example with one of the datasets available with R that demonstrates what you're trying to achieve:
(mycor <- cor(swiss[, 1], swiss[, 2:5]))
#      Agriculture Examination  Education  Catholic
# [1,]   0.3530792  -0.6458827 -0.6637889 0.4636847

# Now, make it into a data.frame
data.frame(id = colnames(mycor), val = as.vector(mycor))
#            id        val
# 1 Agriculture  0.3530792
# 2 Examination -0.6458827
# 3   Education -0.6637889
# 4    Catholic  0.4636847

Comment: I'm tempted to edit this just to add a little more explanation than "just do"...
Comment: please feel free to edit!
Comment: I think I overdid it. Maybe it's time I called it a night ;)
Comment: what the...!!?! yes, indeed! :P
Comment: Thank you very much. You completely solved my problem, and have helped me learn some R.


Display the day of the week

Question: I have a date field (field_date) and on the right of this field I have to display the day of the week
Comment: To do this you must create a custom field formatter and get the weekday using this function, https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Datetime!DateHelper.php/function/DateHelper%3A%3AdayOfWeek/8.2.x.
Comment: Are you trying to display the day on the admin interface or on the front-end interface?
Comment: Interesting, especially for the personalization of the field. I read the func in drupal.api, but I didn't understand where to put it.

the front-end interface
Answer: You can change how dates from date fields are displayed by changing it on the Manage display (/admin/structure/types/manage/[my_CT]/display) page for that Content type.
Custom date format for individual field
The quick and dirty way of doing it is by choosing Custom for Formatter and entering the code for the date, for example:
Y-m-d\TH:i:s, l

will give you "2019-09-09T17:30:19, Monday".
You can lookup the various date and time codes in the PHP manual:  https://www.php.net/manual/en/function.date.php
Overriding individual fields displays with custom date formats isn't the best way to go because you can't reuse it throughout the site, for other fields, or translate into other languages (different countries have different conventions about how to write dates).

Reusable Custom date format
The best way is to first add the new Date format to your site. This way you will be able to use anywhere where you can format Date output.
Go to Configuration > Regional and language > Date and time formats and Add a new format.
Name it so it makes sense to your case, enter the PHP date code you want into the Format string, select Language and add the format.
Now visit your Content type's Manage display page and change the Formatter of the Date field you want to affect to Default, and the Date format to the one you have just created.
Answer: If your question is for showing the day on the content create/edit form, and not displaying after saving that form (which I answered in the previous answer), you'll have to change the widget for the date field.
You can do that through some custom code, but I believe the Bootstrap Datepicker module can do that too (I haven't tried it).
That module has the Date format option where you can enter for example
mm/dd/yyyy DD
to get
09/10/2019 Tuesday
in the Date input field after selecting a date from the calendar popup.
Comment: Yes thank you, that's exactly what I have to do. I saw the datepicker mosule, but I would like to create a customized code, because then I would have to visualize the form and other information too and at this point instead of installing more modules, the code will be better analyzed.
I read something about how to edit custom fields and I also read that "allowed options" could also help, but I saw a partial example. Could you please give me a complete example of both the custom fields and the "allowed options" interface?

Thanks
Comment: What do you mean by "allowed options"? If you plan on creating a custom field in a custom module maybe you should open a new question and ask for the code solution specifically. You can probably find questions and answers here that can help, for example: https://drupal.stackexchange.com/questions/64928/using-date-popup-widget-with-custom-format-date-field
Comment: sorry I was referring to the "allowed values" described in this article. But I would need a complete example to better understand how to interact with drupal
thanks

Display the day of the week


How to run Dotnet run in background on windows server from Teamcity build step

Question: In a integrationtest running on Teamcity I am trying to

Launch a ASPNET Core app using dotnet run
Run Integration test
Stop webserver

Using powershell I am then trying to run the webserver in the background using
start-job -name someName -scriptblock {dotnet run}

But this just gives me

16     someName BackgroundJob   Completed True localhost  dotnet run

But the webserver is not running and no error is outputtet
Is there another way to launch a kestrel server in the background using dotnet command?
Answer: Found a solution
But swapped to using the compiled version of the webserver instead of dotnet run
Doing this to launch my webserver build step
Start-Process .\someName.exe -NoNewWindow -PassThru

Run tests
And this to end it
Stop-Process -name YourServiceName

Works
Comment: Start-Process .\AGPService.exe -NoNewWindow -PassThru is what I used
Comment: From where does it take the name AGPService?
Comment: If you start it with Start-Process .\someName.exe -NoNewWindow -PassThru then your service will have some name, mine is named AGPService
Comment: Got it. Once you start it, it tells you the service name as well. Thanks :)


Setting up my Fourier series for $B_n$

Question: Related but not necessary to know: here
Looking at the temperature distribution in an infinitely long cylinder of metal with insulated sides
and initial temperature distribution
 $f(x)= \left\{\begin{align}0,\quad|x|\lt L \\ C,\quad|x| \gt L \end{align} \right.$
$C$ is constant.
Now I want to workout $B_n$ for the fourier series, and I thought that I would want:
$$B_n = \frac2L\int_L^\infty C\sin\left(\frac{n\pi x}{L}\right) dx$$
But perhaps I haven't setup the integral correctly. Thank you for listening.
I based my choice off of the general form of the solution to the heat equation:
$u(x,t)=\sum \limits_{n=1}^\infty B_n e^{({-n\pi C/L})^2} \sin\left(\frac{n\pi x}{L}\right)$
With $B_n = \frac2L \int_0^L \sin\left(\frac{n\pi x}{L}\right) f(x) dx$
Comment: The Fourier *transform* should be more useful. But make the change of variables $v(x,t)=u(x,t)-C$ first, so that your initial data are zero for $|x| > L$, otherwise you're going to run into convergence problems again.
Comment: It's not a periodic function, so why are you trying to compute a Fourier series to begin with?
Comment: @HansLundmark My logic is added above
Comment: That's the solution to the heat equation on an interval $[0,L]$. It's not going to help you if the interval is unbounded, as in your case. You know that a Fourier series is something that's associated to a *periodic* function, don't you? It just doesn't make sense to try to compute Fourier coefficients for a function that's not periodic.
Comment: @HansLundmark That is a good point. I'll have to find some other way to find $u(x,t)$ thank you
Answer: It would seem you have a number of concepts confused, and I would personally suggest you refer to a textbook on this matter.
You want to use $$\frac{\partial u}{\partial t} = c^2 \frac{\partial^2 u}{\partial x^2}$$
which helps you obtain your standard $F''+p^2 F =0$ and $\dot{G} + c^2p^2 G=0$, if you can't get this you are in trouble.
$f(x)= \left\{\begin{align}0,\quad|x|\lt L \\ C,\quad|x| \gt L \end{align} \right.$
$C, L\lt x$ and $x\lt -L$
$u(x,t) = \frac{C}{2c\sqrt{\pi t}}\int_L^\infty$
(CURRENTLY EDITTING)

Setting up my Fourier series for $B_n$


How do we know establishing a bijection between two infinite sets suffices to prove they have the same number of elements?

Question: The method works for finite sets, but what proof do we have that the method extends for counting elements of infinte sets aswell? How do you justify that results obtained from using the method such as there are the same number of even numbers and all the natural numbers are correct?
Comment: That's how we *define* two sets to have the same number of elements.
Comment: They are only counterintuitive because your intuition relies entirely on your experience with finite sets. Rather than the results being considered counterintuitive, they could instead be considered as demonstrations of the differences between finite sets and infinite sets. After all, the definition that we use to say two infinite sets have the same number of elements is the same definition we use for finite sets. Why would we have two different definitions?
Comment: You understand what a bijection *is*, right? It is a way of exactly matching up the elements of two sets. That's all. So it is the only really meaningful way of saying that the two sets contain the same "number" of elements. Note that it in no way requires you to state what this common "number" is.
Comment: @MichaelAlbanese Yes, but if we look at the counter intuitive results we get from using this definition/technique, why do we keep on using it, and not come up with an alternative counting technique?
Comment: @bakhtiar: Because it's useful. And we do have other counting techniques in other situations where they're useful: e.g. ordinal numbers to count the places in generalizations of sequences, or asymptotic density for measuring subsets of integers. Or geometric measures in geometric contexts like length, area, and volume, or more generally, measure theory.
Comment: What you're calling counter-intuitive (that a set can have the same number of elements as a proper subset) is the definition of an infinite set.
Answer: The "size" of a set defines an ordering relationship.
You want your definition of that ordering relationship to have properties we commonly expect in an ordering relationship:

If $a < b$ and $b < c$ then $a < c$
Defining  "$a = b$" as the statement that neither $a<b$ nor $b<a$ holds, you want "=" to be transitive.

There is a sense in which (for example) the "number of" perfect squares of integers is "less than" the "number of" integers.  But say you defined  for sets $A,B$ that $N(A) < N(B) \Longleftrightarrow A \subset B$. Then the first of the two desired properties holds, but the second does not.
It turns out to be hard to come up with a suitable definition of the number of a set being less than that of another set, that is materially different than the bijection definition.
Comment: That is a horrible way to define equality. It also fails entirely without the axiom of choice when there are incomparable cardinals.
Comment: @AsafKaragila You're right and it's a good example of how intuition can fail us sometimes in mathematics.
Answer: Well, Micheal Albanese gave you the correct answer in his comments, but actually I can show you why we define it that way. Assume there is a bijection f between 2 nonempty finite sets A and B. Assume B has one more element then A. Then since f is a bijection from A onto B, f is surjective onto B. But that means since there is one more element in B then A, there must be at least 1 element in A which has 2 different values in the range B. But then f is not one to one and we have a contradiction. Also, if f is one to one,then every element x of A has a corresponding unique element f(x) in B.But by assumption, B has one more element of A.Therefore,B has one more element then Range (f). But then f is not onto B and we again have a contradiction. The exact same argument with the inverse function f produces the same contradictions for f-1 from B onto A.
So A and B must have the same number of elements if f:A --->B is bijective. That answer your question? Happy holidays!
Addenda: Goos has critized me to the hilt that this argument only applies to finite sets-for infinite sets, the argument doesn't hold. Ok,fair enough-but it does convey the basic idea why it's so.
Comment: You really need to go back and do a basic review of cardinality.  The entire reason mathematicians *developed* cardinality was to deal with the following problem: for infinite sets $A, B$ it is no longer meaningful to say one has "one more" element than the other, or "two more" elements, or any number of elements more than the other, or vice versa.
Comment: I am pretty sure this answer is nonsense.
Comment: Sorry @Mathemagician, your answer is (still) wrong.  You do know that if $|B \setminus A| = 1$ for infinite $A, B$ then they in fact have equal cardinality?  You cannot derive a contradiction from $|B \setminus A| = 1$ (i.e. from "Assume $B$ has one more element than $A$") because this statement in fact holds in all infinite cases.  Your flawed assumption is that the number of elements that one set has "more" than another set is a well-defined quantity, when in fact it could be literally any finite number or even an infinite cardinality.
Comment: My fan club. Sigh.
Comment: What in the world does it mean for one infinite set to have "one more element" than another?  Do you mean $A \subset B$ and $|B \setminus A| = 1$?
Comment: @Goos No,it's not nonsense.Apparently the OP didn't agree with you. And yes-the complement of A with respect to B is a singleton. Sorry this wasn't clear in the answer.
Comment: @Goos My only mistake with my intuitive argument for the OP was not insisting the sets be finite.that would have been more then sufficient to make the case. I tried to be too clever and ended up looking like an idiot.


Continuity of functions of several variables

Question: trying to understand this example of continuity of a a function on $R^2$
$$f(x,y) := \begin{cases}
    \frac{xy^2}{x^2 + y^2}& \text{if } (x,y) \neq (0,0)\\
    0              & \text{if } (x,y) = (0,0)
\end{cases}
$$
to prove continuity at (0,0) we need to show:
$$ \left|{\frac{x_ny_n^2}{x_n^2 + y_n^2} - 0}\right| = \left|{\frac{x_ny_n^2}{x_n^2 + y_n^2}}\right|  \xrightarrow{n \to \infty} 0 ~~~~~~~~~
\text{whenever} (x_n, y_n) \xrightarrow{n \to \infty} (0,0)
$$
can someone explain the above criterion, I am struggling to make sense of it.
The definition of continuity states $ \lim_{x \to x_0}  f(x) = f(x_0)  $ In this case $x_0~~ is ~~(0,0),$ we need to show that the limit from every direction is approaching $f(x_0)$. Is that right?
Thanks for the answers, I get the idea when x, y are scalar variables, but in the text they are vectors defined on a set $D \subset R^n$ with values in $R^k $  and my text has 3 conditions out of which one needs to be satisfied to prove continuity.

using the epsilon-delta definition
if every component function $f_i~~of ~~ \pmb{f} = (f_1, ...., f_k) $ is continuous at $x_0$
$\pmb{f}(x_n) \to \pmb{f}(x_0)$ as $ n \to \infty $ for every sequence $x_n$ in D for which $x_n \to {x_0}$

I believe it is the 3rd option they are using in the text for the above question and that is the one I am having most difficulty understanding. Can someone please explain the 3rd criterion in plain english.
Comment: Yes, that is correct. To show it, you can divide both numerator and denominator by $y_n^2$.
Answer: You definitely don't "need to show" this. Introducing sequences into the game just complicates matters and adds at least two additional nested quantifiers to the definition of limit.
You have to show that for any $\epsilon>0$ you can find a $\delta>0$ such that $r:=\sqrt{x^2+y^2}<\delta$ implies $|f(x,y)|<\epsilon$. Expressing $f$ in polar coordinates we have
$$\tilde f(r,\phi):=f(r\cos\phi,r\sin\phi)={r^3\cos\phi\sin^2\phi\over r^2}=r\cos\phi\sin^2\phi\qquad(r>0)\ .$$
It follows that $|\tilde f(r,\phi)|\leq r$, so that $\delta:=\epsilon$ is an allowed choice.


postgresql from group by table to another table with arrays

Question: I calculate data with simple group by as in for example
select formation,nsf_3,count(*) as number
from table a
group by formation,nsf_3

This query returns
formation   nsf_3       number
CAP         PRODUCTION  2
CAP         SERVICES    5

I want to use that information to put the data in another table with this structure
measure  list_values_dimensions  list_dimensions
      2  ['CAP','PRODUCTION']    ['formation','nsf_3']
      5  ['CAP','SERVICES']      ['formation','nsf_3']

Is there a simple way to do it in SQL (I use PostgreSQL) or do I have to write code outside SQL (I use Python and raw SQL with SQLAlchemy).
Answer: with get_numbers as (
  select formation, nsf_3, count(*) as number
    from table a
   group by formation, nsf_3
)
select number as measure,
       array[formation, nsf_3] as list_values_dimensions,
       array['formation', 'nsf_3'] as list_dimensions
  from get_numbers
;

Comment: Thank you very much sir. It is exactly what I needed and since I don't have your level of expertise on the subject it would have taken me a long time to figure that out by myself.
Comment: @loic_midy FYI, you do not need to do this in two steps if you do not need the intermediate result of `(formation, nsf_3, number)`.


XML error: SYSTEM or PUBLIC, the URI is missing when i fetch the data through curl

Question: Can anybody suggest for the same
Comment: And your question is...?
Answer: What URI are you using? Generally that means the address doesn't actually exist


How to return value from method without executing code using mockito

Question:    /*Please help  I ma trying from last 2 days but no luck. tried different solution but checkEnvironment method is not returning returning TRUE value . I want method should return value without execution of method .Please ignore compilation error if have. */

enter code here  @RunWith(SpringJUnit4Runner.class)
@WebAppConfiguration
@ContextConfiguration(classes = { webconfix.clss })
Public class LoginControllerTest {
        @Autowired
        private WebApplicationContext webcontext;
        @Mock
        LoginServiceImpl serviceimpl;
        @InjectMocks
                LoginController loginController
        private MockMvc mockmvc;
        ObjectMapper objMapper = new ObjectMapper();

        @Before
            @public void Setup() throws Exception{

                MockitoAnnotations.initMocks(this);
                mockMvc=MockMvcBuilders.standalonSetup(loginControllerTest)
                        .build;
             mockMvc=MockMvcBuilders.WebAppContextSetup(webcontext)
                        .build;

            }

        @Test
            public void loginTest() throws Exception{
                LoginServiceImpl lgservice= spy( new LoginServiceImpl );
                Login lg=new Login("test");
                String requestData=objMapper.writeValueAsString(login);
                Mockito.doReturn(Boolean.TRUE).when(lgservice).checkEnvironment("abc");
                // Mockito.when(lgservice.checkEnvironment("abc")).thenReturn(Boolean.TRUE);

                MvcResult result=mockMvc.perform(MockMvcBuilders.post("/login").content(requestdata).contentType(MediaType.APPLICATION_JSON).andExpect(status().isOk)).andReturn();

            }

    }

please help  I ma trying from last 2 days but no luck. tried different solution but checkEnvironment method is not returning returning TRUE value . I want method should return value without execution of method .Please ignore compilation error if have.
Answer:  @Mock
         LoginServiceImpl serviceimpl;

Check login controller declaration. Is there any bean with type :

LoginServiceImpl

Correct me if I wrong you have interface declaration in the controller right ?


How to Use StyledPlayerControlView of Exoplayer in Jetpack Compose

Question: I am trying to use the custom controller in ExoPlayer and I used AndroidView Composable but don't know how to set its custom controller layout and confused that whether it would be an XML layout or a Composable.
Thank You.
Comment: PlayerView & PlayerControlView is the Compose form of StyledPlayerView & StyledPayerControlView. Refer - https://developer.android.com/guide/topics/media/exoplayer/mappings#class-renamings
Answer: @Composable
fun VideoPlayer(videoUrl: String) {
    val context = LocalContext.current

    val exoPlayer = remember {
        ExoPlayer.Builder(context).build().apply {
            addMediaItem(MediaItem.fromUri(videoUrl))
            prepare()
            playWhenReady = true
        }
    }

    val playerView = remember {
            StyledPlayerView(context, null, 0).apply {
            player = exoPlayer
        }
    }

    Surface(color = Color.Black) {
        AndroidView(
           modifier = Modifier.fillMaxSize(),
           factory = {
               playerView
           }
        )
    }
}

Answer: In order to use a custom controller for exoPlayer using JetpackCompose, you must use the android ViewBinding API. Look here for more detail.
DisposableEffect(AndroidViewBinding(
        modifier = modifier,
        factory = ExoPlayerAbbreviatedBinding::inflate
    ) {
        this.exoPlayer.apply {
            hideController()
            useController = true
            resizeMode = AspectRatioFrameLayout.RESIZE_MODE_ZOOM
            player = exoPlayer
            layoutParams = FrameLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT
        }
    }) {
        onDispose {

            exoPlayer.pause()
            exoPlayer.release()

        }
    }

The ExoPlayerAbbreviatedBinding is a custom exoPlayerView, with a custom controller layout set.
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <com.google.android.exoplayer2.ui.PlayerView
        android:id="@+id/exo_player"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:controller_layout_id="@layout/custom_player_controller_abbreviated"/>

</FrameLayout>


How can i make a button clicked when i just click a div

Question:

    <button style="visibility:hidden; float:left"></button>

I wanna make the hidden button as is clicked when someone click the div "mydiv".
Comment: Note, you have an extra quote here: `style=" visibility:hidden;" float:left;"` should be `style="visibility:hidden;float:left;"`.
Comment: @Syscall yeah its just a mistake
Comment: You even tagged `[onclick]` why not use that?
Comment: @Luca yeah i tag onclick because my code needed a js function to make a div clickable on onclick
Answer: As AndrewL said, you don't need a button for this. But if you want to use a button anyways, simply assign a eventListener to your div that simulates a click on the button:
document.querySelector('#mydiv').addEventListener('click', () => {
    document.querySelector('button').click();
});

Example
(I added some CSS rules and an extra function for visualization.)

document.querySelector('#mydiv').addEventListener('click', () => { // Listen for clicks on the div
  document.querySelector('button').click(); // Simulate a click on the button
});

function test() { // This function gets called when clicking the button
  console.log("Click!");
}

    <button style=" visibility:hidden; float:left; " onclick="test()"></button>

Comment: @HassanElkhalifte I'm glad my answer is helpful! Please consider marking it as the accepted answer, so it's easier for future users to find a solution if they are facing the same problem.
Answer: You dont need a hidden button for this. Just assign a click listener to the div itself using js like this:
const btn = document.getElementById('mydiv');

function doSomething(){
    //run your script here when div is clicked
}

btn.addEventListener('click', doSomething);

Answer: You don't really need the hidden button to catch the click event. But if you really need it:

click on me

    <button id="btn" style="display:none;" ></button>

Answer: With jQuery, you can do something like this:
$('#div_id').click(function(){$('#btn_id').trigger('click');});

$('#btn_id').click(function(){//Business logic here on btn click
});


Issue starting method from other class

Question: i am trying to do something that should be quite simple, call a method from a another class, I have allready done it once in my project but this time it doesn't work.
How I am calling the method:
Characters.Character_One.MoveLeft();

this is the contents of the method I am trying to call:
public static void MoveLeft(Character_One c)
{
    c.s.Top -= movespeed;
}

Comment: This is pretty basic stuff, I suggest you dive into a book first.
Answer: You're not passing it the parameter it requires - an instance of Character_One.
var charOne = new Character_One();

Characters.Character_One.MoveLeft(charOne);

Issue starting method from other class


How to print node id in a block in a module?

Question: I have created a ctools jump menu in a block in a module. I need to get the node id for use in the links. How can I get the node id printed in the block?
Here is my code;
<?php

function boathood_block_info() {
$blocks = array();
$blocks['boathood_ABC'] = array(
'info' => t('Boathood Block'),
);
return $blocks;
}

 function boathood_block_view($delta = '') {
 $block = array();
switch ($delta) {
case 'boathood_ABC':
  $block['subject'] = '';
  $block['content'] = _boathood_BLOCK_ABC_CONTENT();
  break;
 }

  return $block;
  }

 function _boathood_BLOCK_ABC_CONTENT() {
$output = boathood_page();
 return $output;
 }

 function boathood_page() {
 global $user;
 ctools_include('ajax');
 drupal_add_js($sample_style, 'setting');
 ctools_add_js('ctools-ajax-sample', 'ctools_ajax_sample');
 ctools_add_css('ctools-ajax-sample', 'ctools_ajax_sample');
 ctools_include('jump-menu');
 $form = drupal_get_form('boathood_jump_menu_form');
 $output .= drupal_render($form);
 return array('markup' => array('#markup' => $output));
 }

  function boathood_jump_menu_form() {

 $mynid = $node->nid;

 $url = url('node/' . $mynid);
 $url2 = url('node/' . $mynid);
 $url3 = url('node/' . $mynid);
$form_state = array();
$form = ctools_jump_menu(array(), $form_state, array($url =>    t('one!'),$url2 => t('two'),$url3 => t('three')), array());
return $form;
}

Comment: Is the block on a full node page (whose nid you need), or is the node embedded somewhere else in the page?
Comment: Yes the block is on a full node page whose nid I need.
Answer: You can get the ID of the current full-page node with menu_get_object:
$node = menu_get_object();
if ($node) {
  // Do something with $node->nid
}

Comment: I tried the following code:                                                                                $node = menu_get_object();
if ($node) {
$mynid = $node->nid;
}  But the $url doesnt recognise the $mynid variable.
Comment: Interpolation is done with double quotes (not single), so: `$url = url("node/$mynid");` or `$url = url('node/' . $mynid);` will work
Comment: Still not working. Instead the page Im being redirected is to node/%24mynid
Comment: Maybe I've put it in the wrong place? I've added your code just after `function boaterhood_jump_menu_form() { `
Comment: It's in the right place if you're seeing a nearly correct url - are you sure you've updated all 3 urls?
Comment: Almost working but it seems special characters are getting rewritten ie:  `$url3 = url("node/add/facility?og_group_boathood_ref=" . $mynid); ` is getting changed to  `node/add/facility%3Fog_group_boaterhood_ref%3D44`  when the link redirects. The node id does happen to be 44 so thats working.
Comment: Params go separately: `url('node/add/facility', array('query' => array('og_group_boaterhood_ref' => $mynid)))`
Comment: Gettting even closer... Now the only url that does not work is `url = url('node/add/classified-ad', array('query' => array('og_group_boathood_ref' => $mynid)));`
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/37135/discussion-between-meggy-and-clive).


Parameter name containing special characters on Helm chart

Question: In my Helm chart, I need to set the following Java Spring parameter name:
company.sms.security.password@id(name):
  secret:
    name: mypasswd
    key: mysecretkey

But when applying the template, I encounter a syntax issue.
oc apply -f template.yml

The Deployment "template" is invalid: spec.template.spec.containers[0].env[79].name: Invalid value: "company.sms.security.password@id(name)": a valid environment variable name must consist of alphabetic characters, digits, '_', '-', or '.', and must not start with a digit (e.g. 'my.env-name',  or 'MY_ENV.NAME',  or 'MyEnvName1', regex used for validation is '[-._a-zA-Z][-._a-zA-Z0-9]*')

What I would usually do is defining this variable at runtime like this:
JAVA_TOOL_OPTIONS:
-Dcompany.sms.security.password@id(name)=mypass

But since it's storing sensitive data, obviously I cannot log in clear the password.
So far I could only think about defining an Initcontainer as a workaround, changing the parameter name is not an option.
Edit: So the goal is to not log the password neither in the manifest nor in the application logs.
Answer: Edited:
Assign the value from your secret to one environment variable, and use it in the JAVA_TOOL_OPTIONS environment variable value. the way to expand the value of a previously defined variable VAR_NAME, is $(VAR_NAME).
For example:
- name: MY_PASSWORD
  valueFrom:
    secretKeyRef:
      name: mypasswd
      key: mysecretkey
- name: JAVA_TOOL_OPTIONS
  value: "-Dcompany.sms.security.password@id(name)=$(MY_PASSWORD)"

Constrains
There are some conditions for kuberenetes in order to parse the $(VAR_NAME) correctly, otherwise $(VAR_NAME) will be parsed as a regular string:

The variable VAR_NAME should be defined before the one that uses it
The value of VAR_NAME must not be another variable, and must be defined.
If the value of VAR_NAME consists of other variables or is undefined, $(VAR_NAME) will be parsed as a string.

In the example above, if the secret mypasswd in the pod's namespace doesn't have a value for the key mysecretkey, $(MY_PASSWORD) will appear literally as a string and will not be parsed.
References:

Dependent environment variables
Use secret data in environment variables
Comment: Thanks but it doesn't work, if I log into the pod and grep for the environment variable I see: company.sms.security.password@id(name)=$(MY_PASSWORD). So the MY_PASSWORD env does not get parsed.
Comment: Another requirement is: I need to loop for different values inside @id(name). So I need a Helm loop for all the names.
Comment: @parax I've edited my answer and added more information to explain the conditions for the parsing of the variable, hope it will help you. About the helm loop, can you provide an example of how the JAVA_TOOL_OPTIONS variable should look like in runtime with all the names and passwords in it?
Comment: It seems that helm is always setting JAVA_TOOL_OPTIONS in the template before my vars, that's probably why they don't get parsed. However, the solution proposed would not be a fit for my case anyway, since it would log in clear the password in the pods.
Comment: In any case, it might be useful to make it work. So, the process I'm following is: helmfile -f helmfile.yaml -l name=service > template; oc apply -f template. After the helmfile step, the template I have is order alphabetically so I'm not sure how to have the parameter parsed by Helm.


Using "$path" on view in aws Athena

Question: i have a table which has a complex type field inside (kind of json).
i created a view on that table to unnest the complex type to table.
CREATE OR REPLACE VIEW test AS
SELECT
, "t1"."first"
, "inner"."inner_first"
, "$path"
FROM
t t1
, UNNEST("inners") t (inner)
LIMIT 10
i use the $path function to query my data based on the file name.
unfortunately, when i tried query $path on the view it doesnt work, simply returned nothing.
So i decided to add to my view the $path field in order to query it outside (as you can see above).
but it still dosent work, when i query:
select * from test
where "$path" = 'x'
i dont get the relevant result.
it seems like something inside the s3 path is making problems.
when i try: where "$path" like '%s3://bucket/output/table/part-00000-01131f4f-3fba-4711-8372-11df66a4224a-c000.snappy.parquet%' -> it still not working.
when i try:

where "$path" like '%c000.snappy.parquet%'
or
where "$path" like '%part-00000-%'
it suddenly works on very small set of characters.

but i cannot understand the logic, i thought about hidden character but in the bottom line it just a regular s3 path, for example:
s3://bucket/output/table/part-00000-01131f4f-3fba-4711-8372-11df66a4224a-c000.snappy.parquet
please let me know if you faced that weird case.
thanks!
Comment: Can you update exactly the query that you are trying to run with $path?  in your query you mentioned s3 twice '%s3://bucket/s3://bucket/output/table/part-00000-01131f4f-3fba-4711-8372-11df66a4224a-c000.snappy.parquet%' which definitely will not work
Comment: yea yea its a mistake of course , the path is '%s3://bucket/output/table/part-00000-01131f4f-3fba-4711-8372-11df66a4224a-c000.snappy.parquet%'. i edited the question - thanks!

as for the query, im trying:
select * from test where $path='s3://bucket/output/table/part-00000-01131f4f-3fba-4711-8372-11df66a4224a-c000.snappy.parquet'

i dont get anything back. tried also like '%part-00000-01131f4f-3fba-4711-8372-11df66a4224a-c000.snappy.parquet%'...still not working :(
Comment: Can you tell me why do you want to compare it with the full file name? It will not only scan this file but it will scan all files then filter the result. I just tried a query SELECT "$path" FROM "testtt"."test0101010" where "$path" like '%s3://test0101010/part-00079-tid-730451297822678341-1dda7027-2071-4d73-a0e2-7fb6a91e1d1f-0-c000.json%' and it gave me result fine.
Comment: First of all, thanks a lot for your responses!!

As for the purpose, im trying to create a process that get files paths from Kinesis, query the inner complex field (using that "test" that has Unnest function in it) of the file and insert it to Aurora DB using Lambda function. I need to query by the path in order to get the specific data.

Do you familiar with that kind of process, maybe a better way to query a parquet file and doing unnest on complex types?
Answer: You need to give "$path" an alias to be able to query the column, or use the default _col4. For example:
create view myview as select "$path" as path from...

then
select path from myview

Using "$path" on view in aws Athena


explicit "switch to mobile theme" link with Theme Key

Question: I'm using Theme Key https://www.drupal.org/project/themekey to switch automatically between themes dependent on browser and/or OS id.
Now I would like to allow the user to explicitly switch to or from to one or the other theme by clicking a link too. ThePersistant URL https://www.drupal.org/project/purl module might be helpful for this but how exactly can I go about implementing this?
EDIT 1
I followed Answer 1, added drupal_add_library('system', 'jquery.cookie'); into the already existing function marinelli_preprocess_page(&$vars) in my template.php.
I setup two ThemeKey rules like:
system:cookie = "theme=marinelli" THEME [Marinelli]

and
system:cookie = "theme=skeleton" THEME [Skeleton]

and
added following html to my page:

Switch to Marinelli Switch to Skeleton

But clicking the links, doesn't do anything, seems like I might be missing something or it might not quite work this way because href="#" doesn't actually reload the page if that was the actual idea...?
Comment: Well, using theme key or not - you will most definitely have caching problems if you have theme switching ability for anonymous users and have page caching enabled.  Your options are to disallow theme switching for anonymous users or disable page caching.  If either of those are an option I can post an answer for you.
Comment: Are you going to use different domains or subdomains for each theme?  If not, and you have any caching enabled, you could run into problems where the wrong theme gets cached unintentionally.
Comment: @PatrickRyan there was no intention to use different urls - if I have to, I can just manually link to one or the other but then the usage of `Theme Key` becomes obsolete, doesn't it?
Comment: @PatrickRyan I will be able to disable caching. Thanks for providing an answer! Alternatively, will I be able to use the Devel module and set "Rebuild the theme registry on every page load"? Will that resolve the caching issue too?
Comment: You definitely don't want to do that on a production site
Answer: One way would be to nest each theme switching rule inside another rule using
system:cookie = theme=theme1
     Theme switching rule here

system:cookie = theme=theme2
     Another theme switching rule here

You will need to set up your theme switching links to create a cookie using your method of choice, PHP or jquery.cookie
An example using jquery.cookie could be something like:
template.php:
function THEMENAME_preprocess_page(&$vars) {
  drupal_add_library('system', 'jquery.cookie');
}

Your theme switching links:
Switch to Theme1
Switch to Theme2

Keep in mind that this is not page caching friendly.  If you want this to work for anonymous users, you will need to disable page caching.
Comment: Is it enough to disable caching under `admin/config/development/performance`?
Comment: Is there a global `template.php` that gets processed in any case (for any theme)? Or shall the `drupal_add_library()` go into each's `page.tpl.php` template e.g.?
Comment: To answer my own question, I found this: https://api.drupal.org/api/drupal/includes%21theme.inc/function/template_preprocess_page/7 - a default `page.tpl.php` is located in `modules/system/page.tpl.php` and I believe `THEMENAME_preprocess_page` should be `template_preprocess_page` instead, is this right @PatrickRyan?
Comment: Yes that is how you disable the built in caching.  All themes have a `template.php` file usually at `sites/all/themes/yourtheme/template.php`.  This is where the above function goes, just replace THEMENAME with your themes machine name.
Comment: Please see **EDIT 1** above
Comment: Correct, the page needs to reload.  You can add replace the link with whatever you want or you can add `location.reload()` to your onclick.  Example edited above.
Answer: To make it to work with cache you can use the Mobile Cache module, at least as inspiration to make your own module using the library Mobile Detect.
https://www.drupal.org/sandbox/acy76/1962696
But you need to modify this line in the module and must look like this
_mobile_cache_add_query_string('device=' . $data['device'] . '&theme=' . $_COOKIE['theme']);

Notice that the idea is add the theme name to the cache
I'm using Authcache and Filecache
Thanks @PatrickRyan


Time-independent variables in survival analysis

Question: In any non-cross-sectional, prospective (whether it be longitudinal, survival, etc) study there are baseline variables which contain the status of the variable at the beginning of the study, and these remain fixed for the duration of observation. But these are distinct from other time-invariant predictors which may contain information (usually some form of summary) about the value of the variable during the study. What comes to mind here is mainly a survival-type analysis and considering smoking as an example of exposure. Am I correct in stating how one could define smoking as a time-invariant exposure?

Baseline - is the person currently a smoker / have they ever smoked / etc: yes/no. This is the value of smoking status in the study start.
Time-invariant - did the person ever smoke during the study: yes/no. This is a summary of smoking status over the person's observation time.
Time-invariant. Even though probably not the most appropriate summary in this particular example, you could also calculate the proportion/percentage of the total observation time that the person was a smoker.

The issue with using time-invariant measures for variables that change status during observation is that you run the risk of immortal-time bias, which is why you might consider using a time-varying covariate.
What I mainly want to get at here is that there aren't any 'rules' specifically for survival analysis that say you shouldn't use post-baseline data for formulating time-invariant predictors. I think I have conflated baseline and general time-independent variable concepts after reading page 2 of this document that discusses 'not looking into the future'.
https://cran.r-project.org/web/packages/survival/vignettes/timedep.pdf
Thanks.
Answer: In a proportional hazards model, the associations of covariates with outcome are evaluated based on the current values among all those still at risk at each event time in the data set.
The first thing to consider is what representation of a covariate is most closely related to the current risk at any time. Although you certainly can't "look into the future," you can represent the past history of a variable in any way that makes sense if you are using time-dependent covariates in your model.
If you want to restrict your model to time-invariant covariates that represent the status at time = 0, however, then neither method 2 or 3 would be appropriate, as both methods involve values of covariates that were only observed after time = 0. Values determined by those methods would not correctly represent the risk at times before the later observations were made.
Method 1 is often appropriate for some characteristics like smoking, as the association with risk typically is a function of long-term exposure. In that case, any exposure change over the few-year course of many survival studies won't make much difference, so the status at time = 0 is a reasonable approximation to current risk throughout the study.
Comment: Thanks @EdM. I think you confirm what I intuited, but have had researchers use methods 2 and 3 and I have been thinking about their validity. So it's really using only baseline or tvc's - any other time-invariant 'summary' (i.e. over the prospective course of the study) covariate representation is really using future data at any event time to predict the current risk. And that's not appropriate. Is that a fair summary?
Comment: @LucaS I think that's a fair summary. Note that even using time-varying covariates in a model can lead to "looking into the future" types of problems if you try to make predictions from it. See [this page](https://stats.stackexchange.com/q/488992/28500) for some discussion.


What does H.V. mean in music notation?

Question: On a music sheet I am reading, the letters "H.V." (without quotation marks) are written occasionally just above specific notes, above the top line of a bar, but lower than where chords are written, and in a smaller font. The music sheet is for trumpet. I have tried googling, as well as looking for it on here, but without finding anything.
Guessing from the acronym and the context, I thought it might mean high volume, but I can't find anything by googling that either.
Thanks for any help
Comment: What is the piece and what instrument is it for?  Can you post an image, so we can see it in context?
Comment: "Half valve", perhaps?
Comment: It's a jazz piece originally written for Bb trumpet, and I am transposing it for guitar. HV seems to mean half-valve, and I now wonder if it is similar to a bend on guitar
Answer: If this is jazz/swing music, then quite possibly "Half - valve,"  as described in the online Dolmetsch dictionary,

the opening of stops or valves on instruments like the trumpet,
  French horn, cornet and tuba, used by jazz musicians when they are
  approaching a glissando, attempting to change the pitch of a tone
  without hitting the note or its closest interval, and in the process
  of highlighting blue notes, for vibrato effects and tremolos
Comment: Sounds right, this is jazz music. If I understand correctly, a glissando by half-valve on the trumpet would be similar to a bend on the guitar? (That is my target instrument for this trumpet piece)

What does H.V. mean in music notation?


Show u^2|u|^(p-3) is Holder continuous (derivative of power nonlinearity)

Question: I am trying to show that the function $f:\mathbb{C}\rightarrow \mathbb{C}$ given by $f(u)=u^2|u|^{p-3}$ is (uniformly) Holder continuous for $p\in(1,2)$ (so $p-3\in(-2,-1)$, this ensures that $f$ is continuous but not differentiable at $0$). I think it should/want it to be Holder continuous of degree $p-1$, like $|u|^{p-1}$, but having tried many approaches now the closest I have got is that
$$|f(u)-f(v)|\lesssim_p |u-v|^{p-1}+|v|^{p-1}|u|^{-2}(|u|+|v|)|u-v|$$
and the coefficient in front of the second difference, $|v|^{p-1}|u|^{-2}(|u|+|v|)$, blows up as $u$, $v$ get small.
Does anyone know how to prove (or disprove!) the Holder continuity?
(context: this term appears in the derivative of the nonlinearity for the nonlinear Schrodinger equation)
Answer: Let $f(z) = z^2|z|^a$ for $a \in (-2,-1)$. We prove that $f$ is uniformly
$(a+2)$-Hölder continuous in $\mathbb C$, i.e. there exists $C > 0$ such that
$$|f(z)-f(y)| \leq C|z-y|^{a+2} \quad \forall z,y \in \mathbb C \quad (\star)$$
Without loss of generality, $z$ and $y$ are non-zero. Observe that if we have proved ($\star$) for any $z \in \mathbb C^*$ and $y = 1$, then one would get
$$|z^2|z|^a - y^2|y|^a| = |y|^{a+2} \left| \left( \frac{z}{y}\right)^2 \left| \frac{z}{y}\right|^a -1 \right| \leq C |y|^{a+2} \left| \frac{z}{y}-1 \right|^{a+2} = C\left| z-y \right|^{a+2} \quad \forall z, y \in \mathbb C^*$$
Hence, without loss of generality, we will assume that $y = 1$.
Let $0 < \varepsilon < 1/2$ and consider $U = B_{\epsilon}(1) \subset \mathbb C$ the ball of radius $\varepsilon$ around $1$.
On $U$, $f(x+iy)$ is real-differentiable, so for $z \in U$, the mean value theorem applies :
$$|f(z) - 1| \leq \sup_{v \in U}||Df(v)|| \cdot |z-1|$$
Moreover,
$$|z-1| = |z-1|^{a+2}|z-1|^{-a-1} \leq \varepsilon^{-a-1} |z-1|^{a+2} \quad \forall z \in U$$
If $z \in U^c \setminus \{0\}$, one writes
$$z^2|z|^a - 1 = (|z|^{a+2}-1)\left( \frac{z^2}{|z|^2} -1\right) + (|z|^{a+2}-1) + \left( \frac{z^2}{|z|^2} -1\right)$$
so that
$$|z^2|z|^a - 1| \leq 3||z|^{a+2}-1| + 2$$
Letting $C = 2(\min_{z \in U^c}||z|^{a+2}-1|)^{-1} \neq 0$, one gets
$$|z^2|z|^a - 1| \leq (C+3)||z|^{a+2}-1|$$
and one can use the fact that $x \mapsto |x|^{a+2}$ is uniformly $(a+2)$-Hölder continuous in $\mathbb R$ (see here for example) to conclude that
$$||z|^{a+2}-1| \leq C ||z|-1|^{a+2} \leq C|z-1|^{a+2}$$


Generate an exact pivotal quantity for theta

Question: Given a random sample $x_1,...,x_n$ from $f(x|\theta)=\frac{\theta}{(x+1)^{\theta+1}}$, $x\ge0$
How to generate an exact pivotal quantity for $\theta$?
Comment: Hi, welcome to the site. This appears to be a standard textbook style question. Please note the [faq discussion](http://stats.stackexchange.com/faq#questions) relating to homework questions, and the tag-wiki info for the [self-study](http://stats.stackexchange.com/tags/self-study/info) tag (the two are synonyms).

So ... What have you tried? Do you know what a pivotal quantity is?
Answer: Can you work out the distribution of $Y=ln(X+1)$?
Can you see a way to proceed from there?