Grid variando o tamanho conforme o texto

Question: Preciso deixar o section FAQ com uma posição fixa, nas imagens fica mais facil de entender o que está acontecendo
preciso q o faq tenha uma posição fixa e não mude dependendo do tamanho do texto dos elementos acima

function initUlOverflow() {
  const tabMenu = document.querySelectorAll('[data-tab="menu"] li');
  const tabContent = document.querySelectorAll('[data-tab="content"] section');

  if (tabMenu.length && tabContent.length) {
    tabContent[0].classList.add('ativo');

    function activeTab(index) {

      tabContent.forEach((section) => {
        section.classList.remove('ativo');
      });

      const movimento = tabContent[index].dataset.anime;
      tabContent[index].classList.add('ativo', movimento);

    }

    tabMenu.forEach((itemMenu, index) => {
      itemMenu.addEventListener('click', () => {
        activeTab(index);
      });
    });
  }
}

initUlOverflow()
.grid-container {
  display: grid;
  grid-template-columns: minmax(160px, 1fr) 3fr 300px;
  grid-template-areas: "header header  header" "nav    nav     nav" ".      grid-section ." '.      faq     .';
}

/* UL */

.grid-section {
  margin-top: 60px;
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-gap: 20px;
  grid-gap: 20px;
}

.praias {
  grid-area: grid-section;
}

.grid-section h1 {
  font-size: 3.5em;
  grid-column: 1 / 3;
  margin-bottom: 30px;
}

.prais-lista {
  height: 450px;
  overflow-y: scroll;
}

/* Permite personalizar o scroll do overflow */

.prais-lista::-webkit-scrollbar {
  width: 18px;
}

.prais-lista::-webkit-scrollbar-thumb {
  background: #b07dfb;
  border-left: 4px solid #faf6ed;
  border-right: 4px solid #faf6ed;
}

.prais-lista::-webkit-scrollbar-track {
  background: #faf6ed;
}

.grid-section p {
  line-height: 1.4em;
  margin-bottom: 15px;
}

.grid-section h2 {
  margin-bottom: 20px;
}

/* FAQ */

.faq {
  grid-area: faq;
}

.faq .titulo {
  font-size: 3.5em;
  grid-column: 1 / 3;
  margin-bottom: 30px;
}

As melhores praias de surf

Baía Formosa, Rio Grande do Norte

          A primeira da lista é, na verdade, uma cidade. Trata-se de Baía Formosa, município localizado no extremo leste do estado do Rio Grande do Norte. A sua vantagem é que ela não possui não apenas uma, mas três praias para surfar que são um deleite para os
          amantes do esporte.

          Depois da sessão de surf, se você quiser relaxar e aproveitar mais das belezas que a cidade oferece, a recomendação é conhecer as águas escuras da Lagoa Coca Cola e admirar o pôr do sol na Praia do Porto.

Boca da Barra – Itacaré, Bahia

          Mais uma praia do Nordeste na lista. A vez agora é da Boca da Barra, localizada na cidade de Itacaré, litoral sul da Bahia. O município baiano recebe uma etapa das qualificatórias do Mundial de Surf da WSL no mês de outubro, evento conhecido como Itacaré
          Surf Music. Além da competição, a praia é palco de shows musicais no período.

          Boca da Barra, diferentemente das praias de Baía Formosa, não é indicadas para surfistas iniciantes. Algumas das mais longas ondas do Brasil acontecem lá, bem no meio do oceano. A orientação é difícil e as correntezas são violentas, portanto é necessário
          ter muita habilidade e experiência para poder aproveitar o pico sem correr perigo.

Cacimba do Padre – Fernando de Noronha, Pernambuco

          Fernando de Noronha não poderia ficar fora da lista de praias para surfar no Brasil. Com muita preservação do meio ambiente, as praias do arquipélago encantam qualquer um. Uma das principais é Cacimba do Padre, que oferece excelentes condições para os
          surfistas.

FAQ

Qual a idade dos animais?

As raposas são animais mamíferos e onívoros pertencentes à família Canidae. São vulpídeos de porte médio, caracterizados por um focinho comprido e uma cauda longa e peluda.

Eles são fantásticos?

Também apresentam como particularidade suas pupilas ovais, semelhantes às pupilas verticais dos felídeos.

Qual a diferença?

As raposas são animais mamíferos e onívoros pertencentes à família Canidae. São vulpídeos de porte médio, caracterizados por um focinho comprido e uma cauda longa e peluda.

Como proteger?

Também apresentam como particularidade suas pupilas ovais, semelhantes às pupilas verticais dos felídeos.

Answer: Resolvi seu problema:
https://codepen.io/querocriarsite/pen/BaNyVbB

    .prais-lista li {
  margin: 10px;
  width: 100%;
  height: 100%;
}

.prais-lista li:nth-child(1) {
  background: url("https://image.freepik.com/fotos-gratis/estrada-quadrada-urbana-e-o-skyline-da-paisagem-arquitetonica_1417-4370.jpg") no-repeat center center;
  background-size: cover;
}

.prais-lista li:nth-child(2) {
  background: url("https://www.urbanarts.com.br/imagens/produtos/204318/0/Ampliada/primeiros-raios-dourados-no-rio-de-janeiro-quadrada.jpg") no-repeat center center;
  background-size: cover;
}

.prais-lista li:nth-child(3) {
  background: url("https://farm1.static.flickr.com/886/40661406140_d54942002b_b.jpg") no-repeat center center;
  background-size: cover;
}

ul li {
    list-style-type: none;
}

.praias-descricao {
  height: 450px;
  overflow-y: scroll;
}


Temporal Order of Control Variables in 2SLS

Question: I am analyzing pooled cross-sectional data with the instrumental variable being educational policy, the independent variable as high school graduation, and the dependent variable as subjective class consciousness. I am considering whether 'marriage' can be used as a control variable in this context.
Regarding the temporal sequence, high school graduation and marriage typically precede the measurement of subjective class consciousness. Hence, in stage two of the analysis, there seems to be no issue with the causal order. The model for subjective class consciousness is: b1 + b2 * high school graduation hat + b3 * marriage + error.
However, the problem arises in stage one. Commonly, if marriage is included as a control variable in stage two, it is also included in stage one. Therefore, it is used to predict high school graduation. This presents a challenge as marriage usually occurs after high school graduation. It implies that past high school graduation is being predicted based on future marriages, creating a temporal causality issue. The stage one model is: high school graduation = a1 + a2 * educational policy + a3 * marriage + error.
My question is, to avoid this problem in instrumental variable two-stage least squares (2SLS) analysis, do control variables need to temporally precede not only the dependent variables but also the independent variables? Additionally, if the time order is problematic and a variable like 'marriage' must be excluded from the control variable in stage one, can it be excluded from the stage one model but included in the stage two model?
Answer: Because marriage is an outcome (potentially) of your independent variable, it is a mediator, or in the words of Angrist & Pischke (2009, 2014), a bad control. Here is a simulation of the issue with adjusting for a mediator ($M$) for the effect of $X$ on $Y$ and why it would be bad. Assume the following equations:
$$ X = \rho Z + \lambda U + \varepsilon_X$$
$$ M = \phi X + \theta U + \varepsilon_M $$
$$ Y = \beta X + \gamma M + \delta U + \varepsilon_Y$$
where $U$ is an unmeasured confounder and $Z$, $U$, $\varepsilon_X$, $\varepsilon_M$, and $\varepsilon_Y$ are independent random variables. We can use $Z$ as an instrument for $X$ to estimate the total effect of $X$ on $Y$ (this is $\beta + \gamma\phi$) but not its partial effect ($\beta$) by adjusting for $M$, because this would introduce bias from $U$.
rho <- 1
lambda <- 1
beta <- 0.25
gamma <- 0.25
delta <- 1
phi <- 1
theta <- 1

Based on these numbers the partial effect is 0.25 and the total effect is 0.5.
library(AER)
n <- 100
nsim <- 10000
res <- list()
set.seed(123)

for (i in 1:nsim) {

  if(i%%1000==0) {message(paste(i, "simulations done"))}
  z <- rnorm(n)
  u <- rnorm(n)
  e_x <- rnorm(n)
  e_y <- rnorm(n)
  e_m <- rnorm(n)

  x <- rho*z + lambda*u + e_x
  m <- phi*x + theta*u + e_m
  y <- beta*x + gamma*m + delta*u + e_y

  fit0 <- ivreg(y ~ x | z)
  fit1 <- ivreg(y ~ x + m | z + m)

  res[[i]] <- c(coef(fit0)["x"], coef(fit1)["x"])

}

res <- do.call(rbind, res)

> round(apply(res, 2, mean),3)
     x      x
 0.488 -0.433

Without the mediator, we get something very close to 0.5 (the difference seems slightly too large to be a coincidence; my guess is that it is due to the fact that 2SLS is not unbiased, only consistent, so there is a small bias that should shrink with the size of $\rho$). However, adjusting for $M$, we are way off from 0.25.
So, to answer your questions more directly. Yes, the control variables have to be determined before the independent variable. This applies also when your not doing 2SLS (if $\lambda=0$ you could have esimated the total effect by OLS, but not the parital effect unless also $\theta=0$). And No. That would be a form of forbidden regression. I am not sure if this question/answer covers it perfectly, but it should get you started.
Consider why you would want to adjust for marriage to begin with? The point of a control variable in a case like this would typically be to adjust for the fact that the policy variable was not randomly assigned, so there could be some unobserved non-random differences between regions (?) with and without the policy.
REFERENCES:

Angrist, J. D., & Pischke, J. S. (2009). Mostly harmless econometrics: An empiricist's companion. Princeton University Press.
Angrist, J. D., & Pischke, J. S. (2014). Mastering'metrics: The path from cause to effect. Princeton University Press.


Unable to find package Microsoft.NETCore.App with version(>=3.0.0)

Question: I am trying to migrate my WPF(.net framework) project to WPF(.net core 3).
So i have installed this Visual Studio Extension and i m now able to create a new Wpf(.net core) project , but the problem starts when i add a nuget package ! , VS throws me this error :
Unable to find package Microsoft.NETCore.App with version (>= 3.0.0-preview6-27730-01)
- Found 69 version(s) in nuget.org [ Nearest version: 3.0.0-preview5-27626-15 ]
- Found 0 version(s) in Microsoft Visual Studio Offline Packages    TestwpfCore C:\Users\sintware\source\repos\TestwpfCore\TestwpfCore\TestwpfCore.csproj   1

Comment: You can now install the latest .net core 3.0 preview6 version from [this link](https://dotnet.microsoft.com/download/dotnet-core/3.0)(which released 6.12). Then rebuild your solution to check if it helps. Actually, I've checked the extension you mentioned and use it to convert my wpf app, but it works well when adding that MahApps.Metro package.
Comment: Hi friend, just checking in if this issue won't block you:) If same issue persists, you can share a simple sample(After deleting the core code) so that we can check it directly.
Comment: The error comes when i install, **MahApps.Metro**, it supports only .NetFramework, but even when i install abp (that supports core 2)  the error is triggred
Answer: As dotnet core 3.0 is still in preview, you should put the following in a file called NuGet.Config in the root of your project (or merge with your existing file):
<configuration>
  <packageSources>
    <add key="dotnet-core" value="https://dotnetfeed.blob.core.windows.net/dotnet-core/index.json" />
    <add key="dotnet-windowsdesktop" value="https://dotnetfeed.blob.core.windows.net/dotnet-windowsdesktop/index.json" />
    <add key="aspnet-aspnetcore" value="https://dotnetfeed.blob.core.windows.net/aspnet-aspnetcore/index.json" />
    <add key="aspnet-aspnetcore-tooling" value="https://dotnetfeed.blob.core.windows.net/aspnet-aspnetcore-tooling/index.json" />
    <add key="aspnet-entityframeworkcore" value="https://dotnetfeed.blob.core.windows.net/aspnet-entityframeworkcore/index.json" />
    <add key="aspnet-extensions" value="https://dotnetfeed.blob.core.windows.net/aspnet-extensions/index.json" />
    <add key="gRPC repository" value="https://grpc.jfrog.io/grpc/api/nuget/v3/grpc-nuget-dev" />
  </packageSources>
</configuration>

This will make sure the preview versions can be found!
This information can be found here:
https://github.com/dotnet/core-sdk#installers-and-binaries
As soon as dotnet core 3.0 is released you should be able to remove these package sources.
Answer: Notice the error message says it's trying to find a package with version 3.0.0 preview6. If you go to https://dotnet.microsoft.com/download/dotnet-core/3.0 you can see the latest public preview is preview 5. Therefore you, or the tool you used to migrate, is trying to use a nightly build of the .NET Core SDK, not a published version. The .NET SDK normally ships with its packages which get put in the NuGet Fallback Folder, so it appears that version of the .NET Core SDK wasn't installed correctly.
I know nothing of that extension you linked, plus it's not a Microsoft extension, so while I appreciate the effort the developer made to create it, I don't know if it works "correctly". Plus .NET Core 3.0 still isn't generally available, so maybe the extension worked with previous previews but something changed.
My suggestion is to install the latest .NET Core 3.0 preview from the download page, go to an empty directory and run "dotnet new wpf", then copy all your code and xaml into that new directory. I don't trust migration tools, I prefer to do it myself manually, so I understand what's being changed.
Comment: I installed net core 3 from github before using the tool.
i took your advice , with a cmd i create the wpf project, but adding abp with nuget returns the same error.
so apparently as  i said core3 works with core3 nuget packages !
Comment: I don't know why your fallback folder doesn't contain the packages, or why your project isn't using the fallback folder, but you'll need to install the publicly released preview to have a version with packages on nuget.org. The install script on github installs a nightly build that does not have matching packages on nuget.org.
Answer: I encountered a similar issue, which ended up being caused by my global nuget.config file being empty. Although my solution nuget.config was correct it seems that the generated project builds without using the solution nuget.config, and instead uses the global one, which being empty, did not work.
The solution was to include the nuget.org package source in the package sources in the %AppData%\NuGet\NuGet.config file, so that it looked like this:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <packageSources>
  <add key="nuget.org" value="https://api.nuget.org/v3/index.json" />
  </packageSources>
  <packageRestore>
    <add key="enabled" value="True" />
    <add key="automatic" value="True" />
  </packageRestore>
  <bindingRedirects>
    <add key="skip" value="False" />
  </bindingRedirects>
  <packageManagement>
    <add key="format" value="0" />
    <add key="disabled" value="False" />
  </packageManagement>
</configuration>

Answer: After getting @Lance is comment , i downloaded the Core 3 preview 6 and finally the problem is gone ,i can install nuget package without any problem.
Answer: Bumping up the Agent Specification from windows-2017 to windows-2019 did it for me


JQuery > operation not work

Question: i have an operation into if condation that its not working true in this line    if( score > tot){
i have two number in these variable it doesnt check true and total is bigger than score but return false not work .
$(document).ready(function(){
        $(".saveMarkList").click(function(event){
            var score = $(this).closest('tr').find('input').val();
            var total = $(this).closest('tr').find('label').text();
            var tot = $.trim(total);
                if( score > tot){
                return false;
                }else if(score == '' ){
                return false;
                }else if( tot == '' ){
                return false;
                }
            var row = $(this).closest('tr');
            var savebtnTD =  $(this).closest('tr').find('span');
            var subjectId = $(".suid").prop('id');
            var senfId = $(".senfid").prop('id');
            var studentId = $(this).closest('tr').find('td').next('td').prop('id');
            var assesmentId = $(this).closest('tr').find('select').val();

            var url = "<?php echo base_url().'examination/saveMarkList';?>";

            $.ajax({
                url: url,
                data: {'subjectId': subjectId, 'senf_id':senfId, 'studentId': studentId, 'assId': assesmentId, 'score': score},
                type: 'post',
                success: function(result){
                    if(result){
                        //row.css('border', '2px solid green');
                        savebtnTD.css('border', '2px solid green; color: green;').html('دخیره شد');
                    }else{
                        alert(result);
                    }
                },
                error: function(){
                    alert("Some technical problem");
                }
            });
        });
    });

Comment: Can you show an example of score and total?
Comment: when i put variables in alert its show me true my number but in checking its not work
Comment: *total is bigger than score* then the condition is right, score is not bigger than total. Did you mean  `if(tot > score){`
Comment: create a simple demo in jsfiddle.net with values set and expected results
Answer: You need to convert them to int, before comparing. Like this., Also add a check if those strings are integer or not using isNaN .
if( parseInt(score) > parseInt(tot))
Comment: To prevent some input "mistakes", one should use the radix as well: `parseInt( stringVal, 10 )`.
Comment: typo `pareseInt` vs `parseInt`?
Answer: You need to compare the values as numbers, not strings.
You can convert values to ints faster than parseInt using ~~
e.g.
if( ~~score > ~~tot)

JQuery > operation not work


Note naming convention while creating scales

Question: I am having some trouble with naming notes in a major scale.
The major scale formula is
0 , 1, 1 , 1/2 , 1 , 1 , 1 , 1/2
If I use this formula to calculate notes in G# major scale, I get the notes as:-
G# A# C C# D# F G G#
However I see many sites and apps use the following notes in a G# major scale:-
G# A# B# C# D# E# G G#
This really confuses me.
Why are notes such as B# and E# present.
I even remember seeing some scales which have notes such as Cb and Fb.
Please help me clearing out my note naming concepts.
Thanks,
Rajeev
Comment: my answer below details the rules for ya.  The G# key signature is never used since the number of accidentals are way above the number you'ld need for the equivalent Ab key signature.
Comment: Both examples are inaccurate - scales use consecutive letter names, and neither of these do. Writing music using these notes just will not work. See my answer below.
Answer: Your formula of half- and whole-steps is correct, but the spelling is not.
Different ways of spelling the same pitch are called Enharmonics. You already know that all of the "black key" notes on the piano have more than one name, but you can also alter notes further than a semitone, or make an alteration to two "white keys" that are next to one another.
You are already familiar with b/# notation: accidentals that modify the pitch by a half step, or semitone. There are also double-sharp and double-flat accidentals that modify by whole steps, or by two semitones.
The reason for using these is to spell every note in the scale with a distinct letter name, and thus, distinct and orderly placement on the musical staff. With enough accidentals, I could spell the "G#" scale as, say...
G# Bb B# B## Eb E# G G#
But written out on a staff this would be pretty incomprehensible, especially for someone sightreading.
To solve this problem, we start with every note name on the staff:
G A B C D E F G
... and then modify those notes with accidentals to suit the scale in question:
G# A# B# C# D# E# F## G#
Now, this is still a lot of symbology on the page, so to simplify, we use key signatures to put all of this information in one place. Double sharps are almost never used in key signatures, however, so as others have mentioned, the typical spelling of this scale would be its enharmonic equivalent of Ab major (which only has four flats as opposed to 8 sharps).
Comment: I'd just like to add here that when spelling a scale, *each letter can only be used once.* NReilingh cited one reason for this rule.  Also, enharmonic spellings may show harmonic motion or recontextualization pertinent to the music, so, even though "B#" and "C" and "Dbb" all *sound* the same, they are *very* different notes.  Lastly, "sharp" notes tend to stay in sharp keys and "flat" notes tend to stay in flat keys. Again, it would be hard to read a G# major scale the way NReilingh showed us in his answer.
Comment: Yes. Please NO ONE EVER WRITE THAT :-)
Comment: Haha, some scary things come across my desk...
Answer: To provide a very simple answer ,as above are complex. You are aware of the notes which constitute G major. To arrive at G# major, simply # each and every note of G. This will give ## on occasions, so that's correct. Since the formula TTSTTTS works for a major scale, it will work for all of them. HOWEVER, G# is such an impractical key to work in, no-one uses it. Why would they, when Ab contains exactly the same notes when played, but only 4 bs when written.
One could take this to ridiculous ends, and write, for example, in Cb, with loads of flats, but B maj., with 'only' 5 #s, would make life easier, wouldn't it ?
Comment: @StephenHazel What do you mean? This works fine as far as I'm concerned.
Comment: @StephenHazel I don't know that rule... and an augmented 5th or diminished 5th above the root is going to be the same letter as the dominant. You might be able to come up with some reliable shortcuts for simpler music that doesn't stray very far from the key signature, but for most purposes, MIDI and standard notation are not isomorphic.
Comment: Why? I don't know. But it happens: see wikipedia's C-sharp major page (http://en.wikipedia.org/wiki/C-sharp_major). As for G# major (http://en.wikipedia.org/wiki/G-sharp_major): "The final pages of A World Requiem by John Foulds are written in G-sharp major with its correct key signature shown in the vocal score including the Fdouble sharp."
Comment: @StephenHazel Which particular 5 notes outside the major scale are you referring to ? Any notes which do not appear in a normal scale, such as major anything, will have all 7 notes to play. Any which are # or b will be shown in the key sig. Any other notes not actually in the scale itself will be dealt with by using accidentals- #, b, x, bb or naturals, showing that those particular notes do not in fact belong to the said key.
Comment: You can't just # every note of G keysig to get G#'s.  That'll break the rules of spelling scales correctly.
Comment: @NReilingh well, there are 12 notes you need to spell in each key signature.  G is spelled:

G Ab A Bb B C C# D Eb E F% F

If you "just sharp them", you get:

G# A A# B B# C# Cx D# E E# F# Fx

Hey, ya know, you're right!  Sorry bout that.
The seperate letter per step and tonic,dominant having their own letter still hold.

I dunno though.  I'm not sure that'd still be the case with all key signatures (just sharping them).  But it is with this one at least.
Comment: @StephenHazel It should always work when you use it in this fashion, because the starting scale is going to have the correct pattern of note names. If you alter each note by the same number of half steps without changing the letter, then you'll still have the same pattern. (For what it's worth, you're the only person I know of who takes into consideration all 12 tones when working with a tonal key signature. You're accurate, but typically the use of chromatic pitches is so contextual that the notes may or may not be related to the key signature as such.)
Comment: @NReilingh I dunno, I'd think that the "dominant HAS to have it's own letter" rule could throw a wrench in that.

The reason I care about all 12 notes of the keysig is that given a midi file, my program has to draw correct standard notation for it.
Comment: @StephenHazel Anyway this is off topic -- we can discuss in chat if you like.
Comment: @NReilingh well, the aug or dim5 wouldn't show up in sheet music on the same line as the 5th.  So it wouldn't be spelled with the letter of the 5th...  Right?  Scale spellings map which line/space the note sits in.
Comment: let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/10327/discussion-between-nreilingh-and-stephen-hazel)
Comment: @StephenHazel - There is no can of worms here ! As I stated in my answer, it all works.There are NOT 12 notes you need to spell each key signature, any more than there are 17 notes you need to write a tune - C,C#,Db,D,D#,Eb, etc.A key in Western music contains 7 diatonic notes.                                    To successfully write these notes, EACH has to have its own letter name, thus place on a line or a space. Otherwise it would be nigh on impossible to read. MIDI has its own conventions, but we're talking MUSIC here !
Comment: All the above points to some very good reasons why G# is rarely, if ever, used as a key in its own right. There's nothing going for it. Why would anyone write in G# when Ab is available ?
Comment: @Tim scale spelling is also used to place notes on the staff.  Spelling a scale is not too difficult.  The trick comes when there are notes outside the scale used.  There are 5 notes outside the major scale that must be placed on the staff if used.  Standard notation specifies which line/space and whether to #/b/X/bb/% the note.
Comment: @StephenHazel - I think you mean the missing notes from the 12 available. If so, they get put in the appropriate place.E.g. if in Cmaj., there is a note from Fmin.chord, it gets called Ab. However, if the same note belongs to a C+ chord, it'll be called G#.They get put in their proper place, and musicians who are aware of chord structure, etc., will know why they've been called by that particular name, and hung on that particular line or space.
Comment: @NReilingh I can't figure out how to make that chat thing work to save my life (and I'm a computer programmer!)  You can go ahead and chop out my comments if you don't mind.
Answer: Welcome to the tricky world of standard notation :)
Scales need to be "spelled" in a very exacting way.
There are also things like double sharps (X) and double flats (bb) to think about.
rules:

start with spelling of 7 scale tones per keysig's sharp else flat
7 tones of scale ALL on DIFFerent letters
if minor, M6 and M7 are ALWAYS m6,m7 SHARPED (naturaled flat/doublesharped) since "sort of in the scale as almost tones"
SINGLE LETTER for tonic, dominant - not duped even for tones outside scale
no letter used 3 times when making outside the scale tones (2 =max=)

checking:

vertically, sharps should read fcgdaeb
vertically, flats  should read beadgcf
cols should have SAME letter:  2,3  4,5  6,7  9,10  11,12

So the usual spellings work out like this:
==================== MAJOR KEYS ===================      ! means PLAIN cuz ksig
            xx      xx          xx      xx      xx       % means natural
flats   KEY m2  M2  m3  M3  4   tri DOM m6  M6  m7  M7   d double flat, x db shp
0       C   db  D   eb  E   F   f#  G   ab  A   bb  B
1       F   gb  G   ab  A   B!  b%  C   db  D   eb  E
2       B!  cb  C   db  D   E!  e%  F   gb  G   ab  A
3       E!  fb  F   gb  G   A!  a%  B!  cb  C   db  D
4       A!  bd  B!  cb  C   D!  d%  E!  fb  F   gb  G
5       D!  ed  E!  fb  F   G!  g%  A!  bd  B!  cb  C
6       G!  ad  A!  bd  B!  C!  c%  D!  ed  E!  fb  F    or F#
7       C!  dd  D!  ed  E!  F!  f%  G!  ad  A!  bd  B!   B in sharps preferred

            xx      xx          xx      xx      xx
sharps  KEY m2  M2  m3  M3  4   tri DOM m6  M6  m7  M7
1       G   ab  A   bb  B   C   c#  D   eb  E   f%  F!
2       D   eb  E   f%  F!  G   g#  A   bb  B   c%  C!
3       A   bb  B   c%  C!  D   d#  E   f%  F!  g%  G!
4       E   f%  F!  g%  G!  A   a#  B   c%  C!  d%  D!
5       B   c%  C!  d%  D!  E   e#  F!  g%  G!  a%  A!
6       F!  g%  G!  a%  A!  B   b#  C!  d%  D!  e%  E!   or Gb
7       C!  d%  D!  e%  E!  F!  fx  G!  a%  A!  b%  B!   Db in flats preferred

==================== MINOR KEYS ===================
            xx          xx      xx          %#      %#
flats   KEY m2  M2  m3  M3  4   tri DOM m6  M6  m7  M7
0       A   bb  B   C   c#  D   d#  E   F   f#  G   g#
1       D   eb  E   F   f#  G   g#  A   B!  b%  C   c#
2       G   ab  A   B!  b%  C   c#  D   E!  e%  F   f#
3       C   db  D   E!  e%  F   f#  G   A!  a%  B!  b%
4       F   gb  G   A!  a%  B!  b%  C   D!  d%  E!  e%
5       B!  cb  C   D!  d%  E!  e%  F   G!  g%  A!  a%
6       E!  fb  F   G!  g%  A!  a%  B!  C!  c%  D!  d%
7       A!  bd  B!  C!  c%  D!  d%  E!  F!  f%  G!  g%

            xx          xx      xx          #x      #x
sharps  KEY m2  M2  m3  M3  4   tri DOM m6  M6  m7  M7
1       E   f%  F!  G   g#  A   a#  B   C   c#  D   d#
2       B   c%  C!  D   d#  E   e#  F!  G   g#  A   a#
3       F!  g%  G!  A   a#  B   b#  C!  D   d#  E   e#
4       C!  d%  D!  E   e#  F!  fx  G!  A   a#  B   b#
5       G!  a%  A!  B   b#  C!  cx  D!  E   e#  F!  fx
6       D!  e%  E!  F!  fx  G!  gx  A!  B   b#  C!  cx
7       A!  b%  B!  C!  cx  D!  dx  E!  F!  fx  G!  gx
Comment: This is tablature, not note-naming.  Granted it's not completely clear, but I read the OP's question as "What is the correct nameset for G#-Major per standard harmony theory?"  in which case the answer is "G# A#, B#, C#, D##, E#, F##,G# "  Edit: apologies if you posted that -- I can't render the first image you posted.
Comment: @NReilingh Yep, the 'tablature' version has gone away. So the tables provided don't "go up" to G# Major -- maybe we should add my first comment in.  Also -- the "!" character seems to be indicating "#" or "flat" when in the "KEY" column
Comment: There seems to be a key for what ! means at the top. Also I'll note your first comment is slightly inaccurate -- no D##.
Comment: That ! is a "steve-ism", sorry.  I had to work these out all on my own, and so ! means "don't show the #/b as it's implied by the key signature".  I don't think G# is a standard key signature.  You'ld use Ab normally.
Comment: @StephenHazel - can you elucidate on your 3rd rule. It seems to be stated backwards. The major scale, Ionian mode, is the starting place for notes, not the minor.
Comment: @Tim I don't know what you mean by "the major scale is the starting point for notes"...  Are you familiar with the naming of intervals?  In C minor, m6 and m7 would be Ab and Bb while M6 and M7 would be A and B.  But they'd be spelled out in sheet music with m6 and m7 at A and B with keysig flatting them both and M6 and M7 would be naturalled
Comment: It's generally accepted that ,for example, the parallel minor has a flat 3rd, rather than the parallel major has a sharp 3rd. The datum point being from a major standpoint.
Answer: I'm not completely sure about this, but I remember reading about the circle of fifths (linked) that among other things, it also shows how many sharps or flats there are in each key.
So for example if you are talking about the key of F#, it should have 6 sharp notes in it, so you would be using all the "sharp" names for the notes and not the "flat" or "regular" names.
Also, I'm pretty sure that as a general rule, you would never use a "flat name" for describing the notes in a "sharp" key scale, and vice versa.
Hope this helps, and I also hope I'm not wrong or misleading, because I'm not 100% sure about this.


How monitor open files and kill its PID by shell script?

Question: My system gets me an error that saying 'Too many open files'. I investigated this error and turned out that <code>/usr/bin/uwsgi</code> created sockets(?) more than 1020. If it creates more than 1020, I guess, the above error comes up with.
So What I try to do is to run a shell script that monitors the number of open files and if it exceeds more than 1000, to kill its PID to resolve this error at this stage.
<code>#uwsgimonitor.sh
#!/bin/bash

#filename=/usr/bin/uwsgi

filename=/usr/bin/uwsgi
Cnt= lsof | awk '/uwsgi/ {print $1,$2}' | uniq -c | sort -r | head -1 | awk '{print $1}'
PROCESS_ID = lsof | awk '/uwsgi/ {print $1,$2}' | uniq -c | sort -r | head -1 | awk '{print $2}'

if [ $Cnt gt 1000 ]
then
    echo "Found the number of socket open exceeds $Cnt."
    kill -9 $PROCESS_ID
else
    echo "" #nothing to do.
fi
</code>
In crontab, I added this line but it seems not to kill the PID that I meant.
<code>* * * * * sh /home/root/scripts/uwsgimonitor.sh
</code>
What am I missing?
Thank you in advance.
Comment: This won't really solve your problem - you need to look at how to configure UWSGI/your webserver to limit the number of sockets opened, or allow the user it runs as to open more files via ulimits.conf.
Comment: I should've mentioned the background. I am an automation tester and this issue on the track fixed. Meanwhile, I just use this shell script to prevent any error message from popping up. It is just a temporary solution to test my app.
Answer: For those who want to how my situation went.
<code>#!/bin/bash

count=$(lsof | awk '/uwsgi/ {print $1,$2}' | uniq -c | sort -r | head -1 | awk '{print $1}')
PROCESS_ID=$(lsof | awk '/uwsgi/ {print $1,$2}' | uniq -c | sort -r | head -1 | awk '{print $2}')
expectLimit=1000

echo "open socket:$count"
echo "pid:$PROCESS_ID"

if [[ ${count} -gt ${expectLimit} ]]
then
        echo "Found uwsgi exceeds limit :${expectLimit}"
        kill -9 $PROCESS_ID
else
        echo "" #nothing to do.
fi
</code>
This one works for me.
Thanks.


bootstrap-select wrong selection made to options

Question: Here is my snippet :
<form action="/Section/Save">
<select class="selectpicker show-tick" id="CourseID" name="CourseID">
    <option>Pick One</option>
            <option value="1" title="Microsoft Office" data-content="

1

Microsoft Office

">Microsoft Office</option>
            <option value="2" title="DTP" data-content="

2

DTP

">DTP</option>
            <option value="4" title="Microsoft Office" data-content="

4

Microsoft Office

">Microsoft Office</option>
            <option value="5" title="Microsoft Office" data-content="

5

Microsoft Office

">Microsoft Office</option>

</select>
<input type="submit" value="Submit" />

The problem is, every time I open the dropdown list, wrong item is selected (or) in some cases, nothing is selected
Comment: Are you providing some kind of variable to automatically select an item from the dropdown list? Your form seems to work just fine, what are you expecting to happen?
Comment: Dropdown list is supposed to select the last item the user has selected when the use opens the dropdown menu. In my case,  it is not selected (or) wrong item is being selected.
Comment: If you aren't storing the value anywhere or marking any value as "selected", then it's not going to automatically select anything but the first option. https://stackoverflow.com/questions/3518002/how-can-i-set-the-default-value-for-an-html-select-element
Comment: The code works fine when the page first load. It is not working properly when user select other option. I am using this [library](http://silviomoreto.github.io/bootstrap-select/examples/#custom-content)
Answer: In order to set a value as "selected", so that it appears as the first option when the user opens the page, you need to have stored the value and then check for it. An easy way to do this in PHP would be as follows (remember you have to have stored the value previously and be checking for it):
  <select>
    <option>Default if none pre-selected</option>
    <option <?php if($this_value=='this_option_value') { echo 'selected="selected"' }; ?> value='this_option_value'></option>
    <option <?php if($this_value=='this_option_value2') { echo 'selected="selected"' }; ?> value='this_option_value2'></option>
  </select>

Related answer: How can I set the default value for an HTML <select> element?
Comment: Yes. But in this case, it is not normal select, it is the modified bootstrap-select [Bootstrap-Select](http://silviomoreto.github.io/bootstrap-select/)
Comment: But don't you still have to set it to "selected" in a normal way, or at least do some kind of Javascript to set the value? (i.e., `$('.selectpicker').val('2');` will set the current value of the dropdown). Looking at docs for Bootstrap-Select, I don't see you doing anything aside from the data-content attribute.
Answer: Can you be more in depth on your problem and what you want helped with?
I did my best to try and understand what it was you're asking, is this what you were looking for?

<form action="/Section/Save">
  <select class="selectpicker show-tick" id="CourseID" name="CourseID">
    <option>Pick One</option>
    <option value="1" title="Microsoft Office" style="color: green">
      1 Microsoft Office<
    </option>
    <option value="2" title="DTP" style="color: green">
      2 DTP
    </option>
    <option value="3" title="Microsoft Office"style="color: green" >
      3 Microsoft Office
    </option>
    <option value="4" title="Microsoft Office" style="color: green">
      5 Microsoft Office<
    </option>

  </select>
  <input type="submit" value="Submit" />
Comment: Are HTML tags supported inside  tag?
Comment: Nope, look here: [link](http://stackoverflow.com/questions/3354979/styling-part-of-the-option-text)
The  element is only for Dropdown list items
although if someone does  then they can customize the option
Comment: Of course it doesn't have to be an id, could be a class, or in the example: inline styling.
Comment: I am using this [library](http://silviomoreto.github.io/bootstrap-select/examples/#custom-content)
Comment: Are you trying to make a specific character green then? You could try doing just: data-content="1" . But trying to do a list inside a list item won't work.
Comment: did a bit of digging. the class name selectpicker is deprecated, use bootstrap-select. And the data-content method is deprecated now
Comment: If that is, can you provide the correct technique of usage since I need to display rich information within option tag.
With best regards..
Comment: Instead of trying to use form/select/option use a dropdown div. Can you be more thorough on what you're trying to do with this? Is it for like a contact form? or some kind of votes?
Comment: If this is trying to  get/post data then use this as a base model [Bootstrapv4 Forms](http://v4-alpha.getbootstrap.com/components/forms/)
Answer: After two days of struggling with the problem, I have finally been able to identified the cause. It's because the

 tag in the data-content is messing up with the index of elements in the library. So, I have to avoid to use

 in the data-content attribute.


Is this really suited for 2-way ANOVA?

Question: My dataset is a biological analysis of a disease which takes 3 months to develop, and we're looking at treatment of that disease.  The data is gene expression data and we want to identify changes in gene expression over time.  This resembles a 2x2 design in which I have equal sized groups as:
<code>          trtmnt     no-trtmnt
1 month     10           10
3 month     10           10
</code>
After thinking about it, I'm not sure if this is really valid for a 2-way ANOVA.  The disease develops over the period of 3 months, so the 1 month subjects should look the same regardless of treatment.  There are multiple ways to look at this:
1)  I could compare trtmnt and no-trtmnt at the 3-month stage.  Simple two-group analysis.
2)  I could look at 1 month vs 3 month for trtmnt, and then 1 month vs 3 month for no-trtmnt.  This would be 2, two-group analyses.  But then I would have to compare the two different analyses to look for gene change in common or different.  This is where it starts to resemble a 2-way ANOVA, but not really.
I appreciate any thoughts.
EDIT:   I should have pointed out that these are animal studies, so we have 10 animals in each group. Rather than taking samples from each animal twice - once at 1 month and once at 3 months - we have 4 different groups, all of which were used for sampling. I hope that makes sense.
Answer: Doing a randomized-block-factorial ANOVA design (aka., repeated measures ANOVA with two conditions) will allow you to look at within-person change under both treatment and no-treatment conditions and to quantify the amount of that change very cleanly. This is sometimes known as a "mixed" design because it combines between-subjects and within-subjects variables and it deals with the non-independence of error terms.
You would hypothesize that in the 1-month condition, there should be no difference between treatment and no-treatment, but that the difference exacerbates (interacts) with time. Simple effects (or even better, treatment-by-contrast interactions) tests will allow you to do this nicely in your repeated-measures design. Thus, you would hypothesize (1) a main effect of treatment vs. control, (2) a main effect of time, and (3) a time-by-treatment interaction. This is completely appropriate so long as you use a block (rather than a pure factorial) ANOVA design.
Another approach (my favored) is to use a hierarchical linear (or nonlinear) model. If you can get baseline measures, then take measures at several timepoints along the way (time 0, 1 month, 2-month, 3 month), you can generate a model that essentially looks at the trajectories of the disease for people who have (or don't have) your treatment. But I know that is considerably more money, obviously. One advantage to the HLM approach is that you can more precisely estimate the shape of the trajectory.
Other approaches that might suffice include latent growth models, but you are starting to look at fairly complex approaches that require large sample sizes when you go down that road. For what you want, if you don't want to add additional timepoints, I would recommend a randomized-block (a.k.a., repeated-measures) ANOVA. Note that there are additional assumptions for this ANOVA design that must be considered.
Answer: You're right, 2-way ANOVA is not appropriate, but for a different reason: The gene expressions from the same subject are dependent. The (expected) identical distribution between both expression levels among the healthy subjects is not the reason.
You should take the difference of the expression levels (baseline - 3 months) and compare them, similar to your suggestion (1), but for the differences. The baseline values are informative. They should not be discarded. (In fact, discarding any measurements is alway suspicious.)
EDIT due to @KirkDCO's edit: If the four groups are independent, it is a 2-way ANOVA: Hypothesis is that there is no interaction.
Comment: Thanks for the comment.  I should have pointed out that these are animal studies, so we have 10 animals in each group.  Rather than taking samples from each animal twice, we have 4 different groups, all of which were used for sampling.  I hope that makes sense.
Comment: Both answers are great and help me with other questions in which we do have matched samples.
Answer: A 2x2 ANOVA is fine here. You are looking for an interaction. That means that the treatment effect has changed across months.
Do not test simple effects because it's a pointless increase in tests that would increase Type I error or cause corrections and increase Type II. The interaction tells you what you need to know, whether the effect of treatment varies over months.
(If you had records of outcome measures at 1 month for your 3 month trt group then you could do a mixed ANOVA on that group. That would be more powerful. Your N here is very small.)

Is this really suited for 2-way ANOVA?


Linear/Discrete Math Equivalence Classes

Question: I am confused on this question:

For each of the following binary relations on $\Bbb R$, state whether or not the relation is an equivalence relation. If it is an equivalence relation, describe the set of equivalent classes. If it is not an equivalence relation, explain why not.
$x \sim y$ if and only if $x-y \in  \Bbb Z$.

I don't get why the answer is [0,1)
Comment: Did you do any calculations to see if it is an equivalence relation (reflective, symmetric, and transitive)? If so, can you find *any*  numbers that belong to the same equivalence class?
Comment: Yes, that was the first part of the question and it worked for all of three! hmm not sure I know if you use like 5.5 then it the same as .5, but not sure how to get multiple equivalence classes.
Comment: I'm glad it got sorted out! Just for future reference, questions generally get more *positive* attention if you fill in some details about what you've tried and where you're stuck, like you did in the comments here :)
Answer: The set $[0,1)$ is not really the set of equivalence classes, it is instead $$\big\{\{x+n:n \in \mathbb{Z}\}:x \in [0,1)\big\}.$$
It seems $e \in [0,1)$ is being used as shorthand here for the equivalence class $\{e+n:n \in \mathbb{Z}\}$.
For any real number $r$, there exists one an only one real number in $[0,1)$ which is equivalent to $r$ under the equivalence relation $\sim$: specifically, for positive reals, it is the real number obtained by subtracting the integer component of $r$ from $r$ (e.g. $3.14159$ is equivalent to $0.14159$), and for negative reals $-r$ (where $r$ is positive), it is equivalent to the real number obtained by subtracting the integer component of $1-r$ from $r$ (e.g., $-0.7$ is equivalent to $0.3$).  This determines the equivalence class.
Here's a figure to illustrate:

Here the bouncy line identifies the real numbers equivalent to, say, $2.4124$, i.e., the real numbers that differ from $2.4124$ by an integer.  Precisely one of them falls in the interval $[0,1)$.
Comment: hmm ok..I am still not sure how you find an equivalence class. What do you mean subtract r from r to determine equivalence class? Like if am given the equivalence class of 1 and said to find it, I know how to do it. But still not sure how to create one.
Comment: So if e.g. $r=3.14159$, then it is equivalent to $0.14159$ (we ignore the integer component).  [Actually, it's a bit trickier with negative reals, I should correct that in my answer.]
Comment: Sorry..but how did you know that it was a decimal..could you use an integer like 3? Why do we ignore the integer component>
Comment: If it was $3$, then it's equivalent to $0$.  It's how the relation is defined: $x \sim y$ if and only if $x-y \in \mathbb{Z}$, i.e., they differ by an integer.
Comment: ahhh ok that makes sense! thank you!
Answer: $\def\zz{\mathbb{Z}} \def\rr{\mathbb{R}}$There are two issues here. The first is that you should know why $( \{ x+n : n \in \zz \} : x \in [0,1) )$ is really the sequence of all the equivalence classes. Specifically you need to check:

Every element in $\rr$ is in one of the claimed classes. Rebecca gave a nice illustration of that, but you need to actually work out the proof yourself.
Any two elements in each class are related by the equivalence relation.
Any two classes in the sequence are distinct.

The third condition is needed because if you just wanted the set of equivalent classes you would just take $\{ \{ x+n : n \in \zz \} : x \in \rr \}$ because duplicates are not counted when forming a set. Since the answer you are given is $[0,1)$, clearly you were expected to list each equivalence class only once.
The second issue is how to figure out the equivalence classes. In general it is ad-hoc, but you always just start with the definition of the set of equivalence classes, namely $\{ \{ y : y \sim x \} : x \in S \}$, where $\sim$ is the equivalence relation on a set $S$, and then try to see which are duplicates.
Answer: If $f:X\rightarrow Y$ is a function then the relation $\sim$ defined by: $$a\sim b\iff f(a)=f(b)$$ is an equivalence relation on $X$.
This is not difficult to prove.
Its equivalence classes are sets of the form $\{x\in X\mid f(x)=f(a)\}$ (the fibres of function $f$).
So for proving that the relation mentioned in your question is an equivalence relation it is enough to find a suitable function.
Here you could use function $f:\mathbb R\rightarrow\mathbb R$ prescribed by: $$x\mapsto x-\lfloor x\rfloor$$
This because it is evident that: $$x-y\in\mathbb Z\iff x-\lfloor x\rfloor=y-\lfloor x\rfloor$$


Structure of a music database - multiple or single table?

Question: I'm creating a music player, where the user can search for artists, albums, or songs.
I have created a script that reads all the tags from the mp3s in the music library, and updates a database of songs, in a single table, containing artist names, albums, track titles, etc.
Currently, this works well, because it can scan for any changes in the music library, and add/delete rows for corresponding songs in the database.
This scan routine is therefore a fairly short an easy to understand piece of code, because it maintains only a single table.
I understand the database would be more powerful if artists, albums, and tracks have their own table, and are all linked to each other. I haven't done anything about the search part yet -- how screwed am I, if I keep everything in one table?
Thanks.
Answer: Your database is not normalized.  You say it's all in one table, but you haven't given any information about the schema.
The kinds of problems which non-normalized databases have include problems with consistency related to storing redundant information - if you have something like:
Album, Track, Artist
then to change the Album name, you have to change it on every track associated with the Album.
Of course, there are all kinds of "database" systems out there which are not normalized, but these usually have mechanisms to handle these kinds of things which are appropriate to their paradigms.
Answer: In regards to the Pink/P!nk situation, if that's a big deal to you, then yes, normalization would be useful.
Your songs table would reference an artist_id.
You'd also have a table of artist aliases, which would map the various names that a particular artist has gone by to that artist_id.
But this can get pretty complex, and technically, it may not even be correct in your situation, as if an artist chooses to release projects under different names, they may not want them all lumped together.
In general, normalized databases are a safe place to start, but there are plenty of good reasons to denormalize, and it is more important to understand those reasons then blindly always do things one way.
Comment: Thanks @Daryn, that's what I was trying to illustrate. I don't think it's a good idea to normalize this particular data set, not yet anyways...
Comment: I disagree - if the OP can't fit their head around four tables they're already in grave danger.
Comment: The Pink/P!nk situation is not a big deal, as it would require to manually maintain the database, and there are endless cases of artists with different aliases. If Last.fm lists Pink and P!nk as two different entities, then having them as two different artists, is good enough for me.
Answer: pretty screwed, indeed.  it's hardly normalized.  go for separate tables.
if you've never heard of normalization or understood why it was important, perhaps you should read this.  it's a succinct, simple explanation without a lot of jargon.
or you could go straight to the source since you're already using mysql:
http://dev.mysql.com/tech-resources/articles/intro-to-normalization.html
think about the cardinalities and relationships in your model:

an album will have zero or more tracks; a track will belong to only one album (album-to-track is one to many)
an artist can create zero or more albums; an album can be created by one or more artists (artist-to-album is many-to-many)

you'll want to think carefully about indexes, primary, and foreign keys.  add indexes to non-key columns or groups that you'll want to search on.
this design would have four tables: album, track, artist, and artist_to_album many to many join table.
Comment: @drachenstern - Very seriously.  You assume that the OP doesn't know about normalization.  It's a good assumption, but one that I chose not to make.  I'll read your example and comment.
Comment: ~ Now that you've come back and added quite a bit more into it, I retract my complaint.
Comment: one does what one can in the time one has.  i don't always have the time to give the answer i want the first time.
Answer: So the subject you're asking about is called "Normalization" and while this is useful in many circumstances, it can't always be applied.
Consider the artist Pink. Some of her albums have her name as Pink and others P!nk which we recognize as the same visually, because we know it's her. But a database would by force see these two separately (which also makes searching for her songs harder, but that's another story). Also consider Prince, "The artist formally known as Prince", etc.
So it might be possible to have an artist ID that matches to both Pink and P!nk but that also matches to her albums Funhouse etc. (I'm really gonna stop with the examples now, as any more examples will need to be tabular).
So, I think the question becomes, how complex do you want your searching to be? As is, you're able to maintain a 1:1 correlation between tag and database info. It just depends how fancy you want things to be. Also, for the lookup I mentioned above, consider that most times that information is coming from the user, you really can't supply a lookup from P!nk to Pink any more than you would from Elephant to Pachyderm because you don't know what people are going to want to enter.
I think in this case, the naive approach is just as well.
Comment: Issues like "Pink" and "P!nk" can be solved using some kind of scrubbing prior to insertion.  I would have been far more impressed if you had given some description of normalization since you chided me for not doing so.  Your answer is rather disappointing, given the tone you took with mine.  I expected something far more insightful.
Comment: Also consider not just artists, albums, titles, but also producers, mixers, studios, band members, lyricists, etc... title art also. And then there's special edition re-releases of the same info as the original disc. It becomes complicated. The real question is what's your intent, what's your use case? Most people don't need all these factors in their music list.
Comment: Of course I didn't go into an indepth discussion of normalization here since Wikipedia has a good writeup on the topic and there's plenty of other threads here talking about normalization, but I identified it and tried to point out some things for him to consider. When I made my post your comment had about 10 words, which wasn't very helpful. As noted above, you've since corrected that. Just seemed like your heart wasn't in the answer.
Comment: I didn't anticipate so much controversy! :)
Also, I didn't know about normalization, so I guess I have a few things to learn.

I didn't mention other types of info, to keep my question simple. But producers, band members, composers etc, will also be added to the database.
Use case: if a user types "Prince", it should list all artists, albums, and songs that contain the string "Prince". Also, if "Prince" is the producer of an album from a different artist, it should list that album.
Comment: I think I have to read more on the subject of normalization, because I tend to think keeping everything in a single table would be a simple and working solution.
Comment: Turns out I'm already familiar with the concept of normalization, I just didn't know what it was called.


True for every formula.

Question: For a formula $ \gamma = r \iff (p_1 \vee p_2) $ there is true that: $\rho \models \gamma \iff \rho(r) = \max(\rho(p_1), \rho(p_2))$
Is it a true for every formula r?
Answer: Your question is very terse and hard to understand. It is particularly confusing to use a symbol like $\iff$ both as an object language symbol (i.e., to form formulas) and as a metalanguage symbol (i.e., to abbreviate assertions about formulas). Let me write out (rather verbosely, by way of contrast) what I think you mean:

If $\gamma$ is the formula $r \Leftrightarrow (p_1 \lor p_2)$, is it true that under any assignment $\rho$, $\rho$ satisfies $\gamma$ iff the truth value $\rho(r)$ of $r$ under $\rho$ is equal to the larger of the truth values $\rho(p_1)$ and $\rho(p_2)$ (where we adopt the usual ordering of truth values so that truth is greater than falsehood)?

Assuming the usual definitions of everything involved, this is true and can be proved quite directly from the definition of the satisfaction relation $\models$. If you are having problems with this, you need to give some more details about the particular definitions you are working with and what you have tried.

True for every formula.


I am getting this SQLServerException: "The result set has no current row". Not understanding

Question: I am trying to connect to DB and execute the results from DB.
I'm getting the below error.
Error: com.microsoft.sqlserver.jdbc.SQLServerException: The result set has no current row.
public void getData() {
    try {
        String query = "Select RetroRequestID, FirstName, LastName from RetroRequest_HMEarnOnOA where AccountNumber = 101930804";
        rs = st.executeQuery(query);
        System.out.println("Records from Database");
        while(rs.next());
        {
            String RetroRequestID = rs.getString("RetroRequestID");
            String FirstName = rs.getString("FirstName");
            String LastName = rs.getString("LastName");

            System.out.println("RetroRequestID: "+RetroRequestID+"   "+"FirstName: "+FirstName+"    "+"LastName: "+LastName);
        }
    } catch(Exception ex) {
        System.out.println("Error: "+ex);
    }

Comment: Are you certain that the raw query run on SQL Server directly would return any records?  My guess at an explanation is that the query is returning no rows.
Comment: Which line is throwing the error?
Comment: As error message says *The result set has no current row* may be your query is little bit wrong or there may be no value equal to your where clause, so the best thing to do is follow @TimBiegeleisen comment.
Comment: The Query returns the result.@TimBiegeleisen
Answer: There is a semi-colon after the if statement in while which acting as an empty statement:
 while(rs.next()); {  // remove the semi-colon

This causes the cursor of the ResultSet to traverse all the rows until there is no one it's pointing, thereby causing the exception.

I am getting this SQLServerException: “The result set has no current row”. Not understanding


DNSSec do you need to renew anything?

Question: I have followed this tutorial to configure DNSsec:
https://www.digitalocean.com/community/tutorials/how-to-setup-dnssec-on-an-authoritative-bind-dns-server-2
If you don't modify your zone, do you ever need to redo anything like in case of letsencrypt or other certificates they need renewal?
I have these 2 zone files recreated daily by bind automatically, there is no cron task for it so I assume bind does this automatically every day.
-rw-r--r--  1 _bind  _bind  22853 Mar 28 09:11 domain.se.signed
-rw-r--r--  1 _bind  _bind  78526 Mar 28 08:59 domain.se.signed.jnl

Answer: Yes, the signatures (RRSIG records) have a limited validity.
Here's an example for the iis.se domain: iis.se.         3600    IN  RRSIG   A 5 2 3600 20210407095501 20210328095501
The 2 numbers starting with 2021 are the "not valid before" and "not valid after" timestamps for this particular RRSET.
If your DNS software does not do on the fly signing (which I think named doesn't do), you have to sign and refresh the zone again before the RRSIG records expire.
Named can however take care of this for you, using the auto-dnssec maintain setting.
Comment: Thumbs up for `auto-dnssec maintain`, which really is the sensible option. Also see https://ftp.isc.org/isc/dnssec-guide/html/dnssec-guide.html#easy-start-guide-for-authoritative-servers for a brief guide on that.

DNSSec do you need to renew anything?


Solve $dy/dx = \sin(x+y)$

Question: Let $u(x)=x+y(x)$, which implies $\frac{du(x)}{dx}=1+\frac{dy(x)}{dx}$. The equation becomes separable : $$ \frac{du}{\sin(u)+1}=dx \iff \tan(u)-\frac{1}{\cos(u)}=x+C $$
This last equation seems to be a transcendental equation with no direct solution. However, the solutions are $y=-x-\pi /2+2k\pi$, or $\sin(x+y)-1=(x+C)\cos(x+y)$ or $y=-x-2\arctan(1+\frac{2}{x+C})+2k\pi$. Except for the first solution, I cannot manage to find those.
Answer: The key is the half-angle identity
$$
\tan \frac{\theta}{2} = \frac{1-\cos\theta}{\sin\theta}.
$$
Substituting $\theta\rightarrow \pi/2 - u$ gives
$$
\tan\left(\frac{u}{2} -\frac{\pi}{4}\right) = \frac{\sin u - 1}{\cos u} = \tan u - \frac{1}{\cos u},
$$
which is what you got from variable separation. Doing the algebra then leads to the solution
$$
y = 2\tan^{-1}(x + C) - x + \frac{\pi}{2} + 2k\pi.
$$
Comment: You use $\tan u - 1/\cos u = \tan(u/2 + \pi/4)$, then take $\tan^{-1}$ of both sides.
Comment: How do you solve the equation $tan(u)-1/cos(u)=x+C$ for $u$? The algebra is not clear to me.
Comment: Great answer. However, the solution is $y=-x-2arctan(1+\frac{2}{x+C})+2k\pi$. How do you turn $
y = 2\tan^{-1}(x + C) - x + \frac{\pi}{2} + 2k\pi
$ into this ? I tried but I don't see how

Solve $dy/dx = \sin(x+y)$


Adams' proof of Homotopy Extension Theorem for CW-spectra

Question: I'm studying stable homotopy category, but I find the language of model category hard to understand. For example, I was suggested reading this (which I call "MMSS")

Michael Mandell, Peter May, Stefan Schwede, Brooke Shipley, Model categories of diagram spectra, Proceedings of the London Mathematical Society, 82 (2001), 441-512 (pdf).

So I return to the classics and read part III of this book

J. F. Adams, Stable homotopy and generalised homology.

In this, Adams constructed the category of CW-spectra. It is fine until he proved Lemma 3.1, the Homotopy Extension Theorem for CW-spectra.

Let $X,A$ be a pair of CW-spectra, and $Y,B$ be a pair of spectra such that $\pi_{*}(Y,B)=0$. Suppose given a map $f:X\to Y$ and a homotopy $h:\operatorname{Cyl}(A)\to Y$ from $f|_A$ to a map $g: A\to B$. Then the homotopy can be extended over $\operatorname{Cyl}(X)$ so as to deform $f$ to a map $X\to B$.

Here $\operatorname{Cyl}(X)=I^{+}\wedge X$. He claimed that $f$ is represented by a function $f': X'\to Y$ (this is just definition), and $h$ by a function $h':\operatorname{Cyl}(A')\to Y$, where $X'\supset A'$, $X'$ is cofinal in $X$ and $A'$ is cofinal in $A$. Here the existence of $h'$ is questionable, since it is not known whether every cofinal subspectra in $\operatorname{Cyl}(A)$ contains $\operatorname{Cyl}(A')$ for some cofinal subspectra $A'$ of $A$ (I couldn't see it myself). Moreover, the proof relies on an argument using Zorn's Lemma, in which the existence of such $h'$ is indispensable.
A quick search tell me that CW-spectra is now called CW-prespectra, and is a special version of sequential spectra. Also, on nLab (see this) they advised to ignore section $III.3$ in Adams' book and follow the treatment in MMSS, so maybe this part of the book is already outdated. My questions are

Is the original proof correct? For example, one could show the existence of $h'$ somehow.
If the original proof is wrong, is the theorem still true? Is there a version of it in the modern theory? How can I prove it?

Any help will be appreciated. Also, some advice or sources about this topic would be very kind.
Comment: Even though not all cofinal subspectra in $\operatorname{Cyl}(A)$ is a cylinder, every cofinal subspectrum of $\operatorname{Cyl}(A)$ contains a cofinal subspectrum of the form $\operatorname{Cyl}(A')$ for some cofinal subspectrum $A'$ of $A$, so we may always find a representative for a map $\operatorname{Cyl}(A) \to Y$ of the form $\operatorname{Cyl}(A') \to Y$.
Comment: @JHF Hi, thank you for spending time on my question! But as I mentioned in the question, the fact you just pointed out is something I know that must be true, but don't know how to prove. Can you elaborate it in more details or give me some references? It'd be very kind of you to do so.
Answer: In the comments, I asserted the following.

Proposition. Fix a finite complex $K$ and a spectrum $A$, and let $C$ be a cofinal subspectrum of $A \wedge K_+$.  Then $C$ contains a subspectrum of the form $A' \wedge K_+$, where $A'$ is a cofinal subspectrum of $A$.

Proof. For each cell in $K$, let $C_e$ be the intersection of $C$ and $A \wedge e_+$ in $A \wedge K_+$.  We may regard $C_e$ as a subspectrum of $A \simeq A \wedge e_+$, and it is cofinal in $A$ since $C$ is cofinal in $A \wedge K_+$.  Let $A'$ be intersection of all the $C_e$ as $e$ varies over the cells of $K$.  Since $K$ only has finitely many cells, $A'$ is cofinal in $A$, and $A' \wedge K_+$ is a subspectrum of $C$.


open source user-security/password scheme

Question: I've read numerous discussions lately about different forms of security for mobile devices outside of the typical password/pin code setup.
The articles talk about recognizing the touchscreen as a human input device and that security measures in apps ought to evolve for that as well.
One such concept involved a graphical keylock like one you would see on a safe. The would have to use multiple fingers to twist it to the correct combination. I haven't done any OpenGL stuff so I wouldn't really know how to develop that, has it been done, is it open source?
I did read this:  Security Beyond a Username/Password? , but I am looking for other opinions.
Thanks for any suggestions and resources. Also please post resources instead of voting to close if it comes down to that.
Answer: I cann't say for all mobile devices, but iOS SDK provides UIGestureRecognizer class, you may create a subclass that UIGestureRecognizer that recognizes a distinctive gesture, character or some kind of gesture combination (in your case). I assume another mobile technologies also have similar methods to recognize keylock characters.
Hope it help you.


Is Azure Synapse Link a good way of loading the data in a Data Warehouse?

Question: Azure Synapse Analytics is the datawarehouse solution from Azure.
There are 3 ways to load the data into the warehouse:

COPY statement

PolyBase

Bulk insert

The fastest and most scalable way to load data is through the COPY statement or the PolyBase.
However now it is also possible to load the data through Synapse Links. Which allows near-real time data.
But I do not see any documentation referring to Synapse Links being used in a traditional Data Warehouse for analytics.
The use cases in the documentation are:

Supply chain analytics, forecasting & reporting
Real-time personalization
Predictive maintenance, anomaly detection in IOT scenarios

Which are use cases that need real time data.
I do not need near real time data. Therefore I assume "Synapse Link" has some disadvantages for a traditional data warehouse solution.
Could someone please tell me their knowledge about using "Synapse Link" in a traditional analytics data warehouse ?
Thanks in advance
Answer: With "Traditional datawarehouse solution" I assume you have ETL processes, that load/refresh your DWH say once a day.
The Synapse Link is a very convenient way to import Cosmos DB or Dataverse Data into a Data Lake connected to Synapse. The "real time" part of it shouldn't bother you, because you can always use batch jobs (dataflows) to load the data periodically from the lake into your datawarehouse.
With the Synapse Link you save time and development effort to bring the data properly from the Cosmos DB or Dataverse into your analytical environment. It works great for us.
Comment: Thank you Bernardo. So are using Synapse Link to load data in your DWH once per day ?
Found a post that does not include Synapse Link as a way to load the data in the DWH
https://learn.microsoft.com/en-us/answers/questions/1013993/synapse-link-vs-data-factory-vs-polybase.html?childToView=1022459#comment-1022459
Comment: Synapse Link synchronizes the data seamlessly. It is permanently synchronized in your Data Lake. From the data lake, I move it into my Dedicated SQL Server once a day.
Comment: @Bernando I wonder if this approach is cost efficient compared to a simple COPY task. I can imagine a seamless sync with the database source can be more expensive than a one-update COPY activity from source to datalake.
For use cases in which you need the data almost real time it makes sense. You pay for it. But for a DWH that needs a daily update it might end up consuming too much resources and thus budget


Clearing cached CSS when updating live web page

Question: I'm responsible for my company's webpage, and I'm having caching issues when updating it with the new CSS files. The CSS files are collected and minified as they should be, but when I update them, they should be cleared, so the page looks like it should.
How do I clear the cached CSS files in Drupal 7?
Comment: If the css are collected and minified properly (and I assum stored in the right dir with the same name as the previous version of the file) the problems seems to be on the client side, files being cached in the browser. If you hit ctrl+f5 does the page render properly?
Comment: The page rendered properly for me, however some co-workers experienced that they got the old faulty CSS cached from their browser. When they cleared the cache they got the correct CSS.

This isn't a problem at the office of course, but if they get old CSS so will some customers I presume?
Comment: Yeah, this is exactly what I'm talking about. It's not a matter of telling drupal to clear the cache but the customers have to clean their client-side chache. There is no general way to force them to clean the cache. Here http://stackoverflow.com/questions/2185872/force-browsers-to-get-latest-js-and-css-files-in-asp-net-application you can find a discussion about it (not drupal oriented)
Answer: Navigate to http://mysite.com/admin/config/development/performance and click the "Clear all caches" button :)

Or if it's an option, install drush on your server and use drush cc css-js, it will only clear CSS/JS cache so won't slow the site down while all the caches are rebuilt.
Comment: If you have the DB log module enabled you can find recent PHP messages at /admin/reports/dblog...it might help to work out what's going wrong
Comment: For some reason, that button doesn't seem to do anything for me. I don't know why, but I had to clear my cached pages by removing the generated html-pages in the cache folder. That doesn't clear the CSS/JS though. But I guess I could remove them from wherever they are stored aswell, and new ones would be generated?
Comment: Is it possible the web server can't write to the sites/default/files folder? That would stop it being able to clear the cache files. Checking the watchdog for evidence of that would be a good idea
Comment: Yes I'm having some permission issue (with Boost I think). I have to clear my cache through FTP and even then I have to do some sudo command to get permission first, every time :(

What is Watchdog?
Answer: If you use drush then you can use the command drush cc css-js
Comment: It's well worth the setup effort, saves loads of time in the long run :)
Comment: I don't use drush. Heard about it and it seems nice, will check it out.
Answer: You are confusing "client-side cache" with "server-side cache". Your problem is generated by clients caching the css of your site. How does it work? When the browser requests the css file and it finds out it already has one with the same name in the cache associated with your domain, it doesn't download it again but keeps using the one it has for improved performance. So, even if you modify your css but you give it the same name, the client browser won't know the difference and it keeps using the old one [unless the clients hits F5 or Ctrl+F5 in most browsers, effectively ignoring the cache]. It's not a matter of flushing Drupal (server-side) cache. They are totally unrelated.
You may want to check this module: http://drupal.org/project/advagg
Comment: @Downvoters: care to comment?
Comment: Thanks. Yes I was not clear of what the problem was. It's client side yes. But I thought that since the js and css are compressed and get's new filenames, the browser would pick that up and realise that it's not the same files.

Will check out that module.
Comment: Glad it helped. I have never used that module myself but the solution is creating css/js with different names on every deploy and it seems that module covers this aspect.


Pub failed to delete entry because it was in use by another process. This may be caused by a virus scanner or having a file in the directory open in

Question: I just updated flutter, now it started showing this. Any help??enter image description here
Comment: Sometimes, just turn off the system and re-start again works for such errors.
Comment: yeah I tried that but didn't work well
Answer: Okay I found the answer. Just reinstall the flutter again, it will work. And make sure the directory is same as previous or else you have to change the path and everything all. :)
Answer: <code>Here's what i have done:

1. I have tried "flutter clean" not worked
2. then have run "flutter pub cache repair" not worked
3. also deleted temp files by windows key + R and %temp% not worked
4. finally opened the "cmd as administrator" and then run "flutter packages get" in project folder. It Worked!! :)
</code>


Mask Jquery não funciona

Question: Estou tentando usar a mascara do jquery, vou usar ele um < input > adicionado pelo javascript pela ação de selecionar um < option >.

<select name="opcao" id="sel" onchange="muda()" class="form-control">
        <option value="option1">option1</option>
        <option value="option1">option1</option>
</select>

Answer: O jQuery Masked Input foi feito para funcionar com inputs de texto. Você está tentando inserir uma máscara em um campo tipo date (que, por si só, não precisa de formatação por trazê-la automaticamente respeitando as regras de padrão de datas baseadas no seu locale). Mude o type do seu input para text que a máscara deve funcionar.
Answer: O problema que ocorre é devido você adicinar a máscara quando a página é inicializada, porém quando isso ocorre ainda não existe o elemento com o id="dia" carregados no documento HTML.
Então como você está adicionando dinamicamente o elemento com id="dia" no documento, você também vai ter que adicionar a máscara dinamicamente depois que você adicionar os elementos no documento HTML.
Segue abaixo no exemplo como você pode resolver seu problema:

function muda() {
  if (document.getElementById("sel").value == "option1") {
    document.getElementById('rdo').innerHTML =
      "
Dia
<input class='form-control' type='date' name='dia' id='dia' required autofocus>

" +
      "
Hora
<input class='form-control' type='time' name='hora' required>

" +
      "
Local
<input class='form-control' size='251' maxlength='250' type='text' name='local' required>

" +
      "
Endereço
<input class='form-control' maxlength='500' type='text' name='endereco' required>

" +
      "
OBS
<input class='form-control' maxlength='500' type='text' name='obs'>

";
  } else {
    document.getElementById('rdo').innerHTML = "";
  }

  $("#dia").mask("99/99/9999")

}

<select name="opcao" id="sel" onchange="muda()" class="form-control">
        <option value="option1">option1</option>
        <option value="option1">option1</option>
</select>

Mask Jquery não funciona


Basic Function Question

Question: Can someone please help me , I've no idea how to do this:
Give an example of a quadratic function $f$ that satisfies $f(x) ≤ 0 ⇔ x ∈ (−∞,−5) ∪ (\frac{7}{2},∞)$.
Comment: Did you mean $f(x)\color{red}<0$ ?
Comment: If the domain of $f$ is all of $\Bbb R$, this is impossible
Comment: make $f(x)>0$ on $(-5,\frac72)$
Comment: Look at the roots you can get! $x=-5, \frac{7}{2}$, then factorise into brackets and you have your quadratic equation!
Answer: Hint:
Remember a quadratic (real-valued) function has the sign of its leading coefficient, except between its roots, if any.
Answer: let $f(x)$ be $a(x-b)(x-c)$, where $a, b, c ∈ ℝ$.
Firstly the bounds indicate that the roots are $-5$ and $\frac{7}{2}$, so
$$f(x) = a(x+5)(x-\frac{7}{2})$$
Next, when $a<0$, the graph would be a "sad" curve, showing that the conditions are satisfied.
So it is actually any $f(x) = a(x+5)(x-\frac{7}{2})$ where $a ∈ ℝ^+$.
Answer: There no such quadratic instead $f(x)<0$. If it is $f(x)<0$. Here is a simple way. Choose a quadratic with $-5$ and $\frac72$ as roots e.g $(x+5)(x-\frac72)$. Now since $f$ is negative, multiply it by a negative constant e.g:
$$f(x)=-\pi(x+5)(x-\frac72)$$
Answer: I'm picturing the graph of $f(x)$ vs. $x$ as a concave downward parabola
that intersects the $x$-axis when $x=-5$ and $\frac72$.
The peak of the parabola occurs when $x=
\frac12(-5+\frac72)=-\frac34$.
So one example is $-(x+\frac34)^2+c$.
To solve for $c$, set $-(-5+\frac34)^2+c=0$ [or $-(\frac{7}2+\frac34)^2+c=0$] and find $c=(\frac{17}4)^2=\frac{289}{16}.$
So my example is $-(x+\frac34)^2+\frac{289}{ 16}=-x^2-\frac32x+\frac{35} 2.$

Basic Function Question


Detect when a point belongs to a bounding box with distances

Question: I have a box with known bounding coordinates (latitudes and longitudes): latN, latS, lonW, lonE.
I have a mystery point P with unknown coordinates. The only data available is the distance from P to any point p. dist(p,P).`
I need a function that tells me whether this point is inside or outside the box.
Comment: Is this supposed to be on a sphere, or on a flat plane? If on a sphere what is the definition of `dist`?
Comment: So you have no knowledge of the coordinates of $P$, but you always have the distance *to $P$* available?
Comment: Ah, I think I now understand. You know the bounding latitudes and longitudes of a box. You have some mystery point $P$, that might be inside or outside the box, and you want to determine which. The only other data you have is the distance of $P$ from *any* point $p$. Is this right?
Comment: Yes that's it. It's a magic point!
Comment: Its is just a flat plane
Answer: Once we know the coordinates of P then the problem revers to a well known answer. To get the coordinates of $P=(x, y)$ we take three measurements. I have moved the coordinate system onto one corner and named the objects accordingly, with $a$ the horizontal side and $b$ the vertical side. In addition, we are going to find the coordinates of P in polar notation, with the distance $r$ and angle $\theta$.

Measuring $\vec{AP}$ we get the distance $r$. Measuring $\vec{BP}$ gives us the cosine and measuring $\vec{DP}$ gives us the sine, by means of the law of cosines.
$$ \cos\theta = \frac{r^2+a^2-d_{BP}^2}{2 a r} $$
  $$ \sin\theta = \frac{r^2+b^2-d_{DP}^2}{2 b r} $$
So the location of P is
$$ x = r \cos\theta = d_{AP} \frac{r^2+a^2-d_{BP}^2}{2 a r} $$
  $$ y = r \sin\theta = d_{AP} \frac{r^2+b^2-d_{DP}^2}{2 b r} $$
The point is inside if $x>=0$ and $x<=a$ and $y>=0$ and $y<=b$.
I have checked this with the above C# code
static void Main(string[] args)
{

    double a=2;
    double b=1;

    Point A=new Point(0, 0);
    Point B=new Point(a, 0);
    Point D=new Point(0, b);

    for(double x=-5; x<=5; x+=0.5)
    {
        for(double y=-5; y<=5; y+=0.5)
        {
            Point P=new Point(x, y);

            double d_AP=A.DistanceTo(P);
            double d_BP=B.DistanceTo(P);
            double d_DP=D.DistanceTo(P);

            double r=d_AP;
            double cos=(a*a+r*r-d_BP*d_BP)/(2*a*r);
            double sin=(b*b+r*r-d_DP*d_DP)/(2*b*r);

            double x_P=r*cos;
            double y_P=r*sin;

            P.inside=(x_P>=0&&x_P<=a)&&(y_P>=0&&y_P<=b);

            Point Q=new Point(x_P, y_P);
            if(P.DistanceTo(Q)>1e-6)
            {
                Console.WriteLine("({0},{1}) - ({2},{3})", x, y, x_P, y_P);
            }
        }
    }

}

public struct Point
{
    double x, y;  //private, not visible
    public bool inside;

    public Point(double x, double y)
    {
        this.x=x;
        this.y=y;
        this.inside=false;
    }

    public double DistanceTo(Point p)
    {
        return Math.Sqrt((p.x-x)*(p.x-x)+(p.y-y)*(p.y-y));
    }
}

and it all checks out ok. No need to check for signs and quadrants. It all works out cleanly.
Answer: There's a geometric way to do it, too.
Draw a rectangle and a point inside it. You can make four oriented triangles by connecting the point to the diagonals, and then uniformly drawing arrows on the edges so that they all "flow clockwise" or "flow counterclockwise".
Now if you imagine dragging the point over an edge, you'll see that three of the triangles retain their orientation, but the one whose edge has been crossed will flip orientation. If you go over a corner instead, two of the four triangles will flip orientation.
So, by uniformly representing these four triangles with vectors, you just have to check their cross products to see if they are all the same sign. If two disagree with the other two, you know the point lies on a diagonal outside. If one disagrees with the rest, it lies outside of one of the edges. If they all agree, the point is inside.
Here's the setup. Suppose you are given $(a_1,a_2),(b_1,b_2),(c_1,c_2),(d_1,d_2)$ as the corners of the rectangle (in cyclic order, say, clockwise), and $(e_1,e_2)$ is the point.
One triangle will have vector edges (in this order) $(a_1,a_2)-(e_1,e_2)$ and $(b_1,b_2)-(a_1,a_2)$.
The other three will be:
$(b_1,b_2)-(e_1,e_2)$ and $(c_1,c_2)-(b_1,b_2)$
$(c_1,c_2)-(e_1,e_2)$ and $(d_1,d_2)-(c_1,c_2)$
$(d_1,d_2)-(e_1,e_2)$ and $(a_1,a_2)-(d_1,d_2)$
They've all been set up so that if the point is inside, then taking the cross product of the first vector with the second in any of these four pairs, they will all have the same sign (all positive or all negative).
Given any four points in cyclic order like this, you can fill out the four equations and check all their cross products.
Comment: I realize it seems like a complex setup, but if you are given say 1000 rectangles, and you want to know if a given point is inside or outside of each of them, then a program does this pretty efficiently. Sorry if it doesn't fit your tools at hand: it's hard to match our answers to your resources, sometimes.
Comment: having e1,e2 is as easy as latS<e2<latN & lonW<e1<lonE, no need for  cross product, am I missing anything?
Comment: @JordiPlanadecursach I might agree, but the author mentions something about "lat" and "lon" not being available. Since I only have a vague notion of what both of you are thinking of, I just avoided it altogether.
Comment: I really like this, but my understanding is that we don't have $(e_1,e_2)$. We have some reference point $P$ that we do know the coordinates of, and we know the distance from $p=(e_1,e_2)$ to $P$, but not the values of $e_1$ and $e_2$. (I think - I'm still not completely sure I haven't misunderstood the question.)
Comment: @MattPressland Yeah, I agree. Let's see if we can get the OP to improve the question.
Comment: Improved, any solution so far?
Answer: As I understand your question, it is somehow similar to this:How to check if a point is inside a rectangle. I see that my answer (while received no votes), may be correct and may be simply applied in your case.
Comment: Where is your answer?
Comment: To locate my answer, please do a find on my name after you have clicked the link.
Answer: One (far-from-optimal, but straightforward) way to do it: since you have the box's coordinates available, you also presumably have the four corners of the box available.  Now, knowing $P$'s distances from the two points along one edge lets you narrow down the point's location to one of two points $i_1$ and $i_2$ (since the two circles $|P-p_1|=r_1$ and $|P-p_2|=r_2$ have at most two intersection points).  Similarly, knowing $P$'s distance from the two points along the other edge narrows down its location to one of two points $i_3$ and $i_4$.  (If you really want, I can flesh this out with the equations for those two points - but it's straightforward to find them yourself; it's just a bit of algebra or alternately a bit of geometry) Now, the kicker: the two sets of two points can't be the same, because $i_2$ is the reflection of $i_1$ about the edge $p_1p_2$ and $i_3$ is the reflection of $i_4$ about a different edge $p_3p_4$.  This means that you can compare to determine which of the points $i_1,i_2$ is identical to which point $i_3,i_4$ and that's enough to get your point precisely.  Once you have that, the standard point-in-rectangle tests should suffice.
Note that for algorithmic reasons, once you have $i_1$ and $i_2$ you may want to perform the point-in-rectangle test on both of them; they can't both be in the rectangle, but it's possible that they're both out of the rectangle, in which case you don't have to bother going on and finding $i_3$ and $i_4$.
Answer: The distance measurement from any point gives you a circle around that point as a locus of possible positions of $P$.
Make any such measurement from a point $A$.
If the question is not settled after this (i.e. if the circle crosses the boundary of the rectangle), make a measurement from any other point $B$. The two intersecting circles leave only two possibilities for the location of $P$.
If you are lucky, both options are inside or both outside the rectnagle and we are done.
Otherwise, a third measurement taken form any point $C$ not collinear with $A$ and $B$ will settle the question of exact position of $P$ (and after that we easily see if $P$ is inside or not.
One may wish to choose the first point $A$ in an "optimal" faschion such that the probability of a definite answer is maximized.
While this requires knowledge about soem a prioi distribution where $P$ might be, the center of the rechtangle seems like a good idea. The result is nondecisive only if the measured distance is between half the smallest side of the rectangle and half the diagonal of the rectangle.
Answer: Measure distances from the four corners of the rectangle.
Consider the four triangles formed from P and the four sides of the rectangle.
Apply the Law of Cosines to measure the angles of the four triangles next to the sides of the rectangle.
If any is larger than 90 degrees then you are outside. Otherwise you are inside.
EDIT 1:
Suppose your rectangle is $EFGH$ where the sides are $d(EF)=d(HG)=x$ and $d(FG)=d(EH)=y$.
Let the distance of $P$ from $E,F,G,H$ be $e,f,g,h$ respectively.
Now by Law of Cosines applied to  angle $EHP=\alpha$ we have $\cos (\alpha) = (y^2+h^2-e^2)/(2yh)$. If the angle is larger than $90^\circ$ then $y^2+h^2-e^2<0$. We need to apply a similar check 8 times. If any of the expressions is negative then we are outside. Else we are inside (or on boundary).  So you have to check the sign of  8 expressions.
If either of the following
$y^2+h^2-e^2$,  $y^2+e^2-h^2$, $x^2+e^2-f^2$, $x^2+f^2-e^2$, $y^2+f^2-g^2$, $y^2+g^2-f^2$, $x^2+g^2-h^2$, $x^2+h^2-g^2$
is negative $P$ is outside.
EDIT 2:
In case efficiency is a consideration: To test that $P$ is inside, or on the border, checking with respect to 3 sides will do. So it takes 6 inequalities. For example
$y^2+h^2-e^2\ge 0$, and  $y^2+e^2-h^2\ge 0$, and
$x^2+e^2-f^2\ge 0$, and $x^2+f^2-e^2\ge 0$, and
$y^2+f^2-g^2\ge 0$, and $y^2+g^2-f^2\ge 0$.
EDIT 3:
A similar approach will work for checking with respect to a convex polygon.
Comment: can you translate that into a boolean equation ?
Comment: I added a formulation.
Answer: You have the coordinates of the four corners of the box. I'll imagine that the box is situated so its sides are horizontal or vertical (This could be easily obtained by a rotation if box wasn't originally like this). So you can also get the coordinates of:
$p_M$, the center of the box (inside the box),
$p_L$, the point directly to the left of the center so that the left side of the box bisects the line joining $p_M$ to $p_L$,
$p_R$, the point directly to the right of the center so the right side of the box bisects the line joining $p_M$ to $p_R$,
two further points $p_A$ and $p_B$ respectively above and below the box, so that the top/bottom of the box bisects the line joing $p_M$ to $p_A$ or $p_B$.
Now for your mystery point P you find
$t_M=d(p_m,P)$, $t_L=d(p_L,P)$, and similarly for $t_R,t_A,t_B$.
Now use the fact that the mystery point $P$ is on the (half plane to the) left of the right side iff it is closer to the point $p_M$ than it is to $p_R$, i.e. iff $t_M>t_R$. Similarly $P$ is to the right of the left side iff $t_M>t_L$, and $P$ is below the top of the box iff $t_M>t_A$, and finally $P$ is above the bottom of the box iff $t_M>t_B$.
We now have that  p lies in the box iff each of the quantities $t_M-t_*$ is positive, where * is one of the four symbols $L,R,A,B$. For the function, define
$f(distances)=min(t_M-t_L,t_M-t_R,t_M-t_A,t_M-t_B)$. Then $f>0$ iff $P$ lies in the interior of the box, while $f>=0$ iff $P$ lies in the interior or on the boundary of the box.


Covariance of two random variables in a bivariate normal distribution

Question: http://www.econstreams.com/bivariateproof.jpg
Image uploaded to the link above. I'm just not seeing the connection between the 2nd equation on the left handside and the equation on the right. Expanding the terms yields a positive sign for $n\bar X \bar Y$ on the numerator.
Also, the $X_i\bar Y, \bar X Y_i$ terms are uncorrelated, and hence equal 0.
Anyone know how to solve this admittedly very simple proof as sequentially as possible? Any and all help is greatly appreciated! Thanks.
Answer: The version on the right is using a shortcut formula for the covariance and variance of a security's returns. The covariance of X and Y is $E(XY)-E(X)E(Y)$, which is the numerator on the left and the right (albeit different forms). Don't forget that the 1/n will cancel out in the fraction, so you are actually seeing sums, not averages, but that is just due to simplifiation.
in the formujla on the rignt, they just multiplied the shortcut formulas by n/n to get the forms you see so as to avoid fractions within fractions.


Given $a$ and $n$, find $y \equiv \frac{n!}{a^x} \bmod a$

Question: Take $n!$ and find $x$, where $a^x$ is the greatest power of $a$ who divides $n!$
Then find $y$, where $y \equiv \frac{n!}{a^x} \bmod a$
For example,
if $a=3$ and $n=6$ then
$6!=2\times3\times4\times5\times6=3^2\times80 \Rightarrow 3^2\times2 \Rightarrow (x=2, y=2)$.
How to find $x$ and $y$ without a computer or computing sucessives divisions? How can we do a explicit formula to find $x$ and $y$ to express $n!$ in this way in $a$?
Comment: I'm confused. The multiplicative inverse of ${a^x} \mod a$ does not exist since $a$ and $a^x$ are not coprime.
Comment: I think what OP means is what is $n!$ mod $a$ when you take out all powers of $a$ from $n!$. In that sense $n!/(a^x)$ is a well-defined integer and we can consider it mod $a$.
Comment: @J.D. We're obviously supposed to divide $a^x$ out of $n!$ before understanding it inside of $\mathbb{Z}/a\mathbb{Z}$.
Comment: Is there any purpose for this question or are you simply wondering?
Comment: When $a$ is prime, this is an extension of Wilson's Theorem: $(a-1)! = -1$ mod $a$ ($a$ prime). So if $n=ak+r$ where $0 \leq r < a$, then $n!/a^x = [(a-1)!]^k+r!=(-1)^k+r!$ (mod $a$) or something like that (consider $(2a)!/a^2=1\cdots (a-1) 1\cdots(a-1) = [(a-1)!]^2$ mod $a$). For a non-prime modulus this would seem to be quite complicated.
Comment: @PatrickDaSilva is right. $\frac{n!}{a^x}$ is always integer, because, $a^x$ should always divide $n!$.
Comment: The propose behind this question is I'm need a bit different way to calculate modulus. if $n>a$, $n! \equiv 0 \bmod a$, but, if we take all $a$ powers of $n!$, what's the final result? Interesting question, doesn't it?
Comment: @BillCook do this to primes it's still interesting. But looks like your formula it's a bit wrong. $\frac{(2a)!}{a^2}\equiv 1\times2\times...\times(a-1)\times1\times2\times...\times(a-1)\times2\equiv [2(a-1)!]^2\bmod a$. Yes a little dificult generalize this to non-primes and all $n$'s.
Answer: This is probably too unwieldy to be of use by hand, but it provides for a bit of reduction that might prove useful for a potential algorithm.
Factorize $a=p_1^{e_1}\cdots p_k^{e_k}$ and write $x=x_n(a)$ as a function of $a$. Decompose it as:
$$x_n(a)=\min\{x_n(p_1^{e_1}),x_n(p_2^{e_2}),\dots,x_n(p_k^{e_k})\}. \tag1$$
The exponent in the highest power of a prime $q$ dividing $n!$ is given by de Polignac's formula:
$$v_n(q)=\sum_{l=1}\left\lfloor \frac{n}{q^l}\right\rfloor;$$
The sum is finite with final index $l=\lfloor\log_qn\rfloor$. This tells us that our function for prime power arguments is $x_n(q^b)=\lfloor v_n(q)/b\rfloor$, which suffices to compute $x_n$ generally via $(1)$ above.
Now to compute $y=n!/a^x$, write it as a product of two parts: part A a product of all numbers that are $\le n$ and coprime with $a$, part B all other numbers in $1,\dots,n$. Since $\prod_{u\in\mathbb{Z}/a\mathbb{Z}^\times}u=1$ (that is, the product of all numbers in $1,2,\dots,a$ that are coprime with $a$, modulo $a$, is simply the multiplicative identity - this is a basic fact of abstract algebra) we may reduce the product of $A$ by ignoring all numbers coprime to $a$ in the intervals $[1,a],[a+1,2a],[2a+1,3a]\dots,[ma+1,(m+1)a]$, where we have that $(m+1)a$ is the last multiple of $a$ before or equal to $n$. Take all numbers in the last partial interval $[(m+1)a,n]$ and reduce them all modulo $a$, and you are left with $[1,(n)_a]$, where This makes part $A$ equal to $(n)_a!$ modulo $a$.
And to compute part $B$, first note that Polignac's formula says that the highest prime power of $p_i$ (one of the primes dividing $a$) that divides $n!$ is given by $v_n(p_i)$ defined above. So the product of all factors noncoprime with $n$ will be the product of all highest powers of primes $p_i$ dividing $n$, or
$$\large(\circ)=\prod_{i=1}^k p_i^{v_n(p_i)}.$$
If we divide this by $a^x$ we get
$$\large B=\prod_{l=1}^k p_l^{v_n(p_l)-xe_l}.$$
Comment: Thx about your explanation. Very relevant. Unfortunally after *"Now to compute..."* I didn't undestand very well. Can you explain a little more how to find A and B parts?
Comment: @GarouDan: I've put a little more work in but it might still be terse. Tell me if you want more clarification. (Also, I fixed part B because there was a slight error.)