Do you have to manually dispose streams from a streamprovider in Flutter?

Question: I can't find this in the official documentation  for the provider package, does streamprovider automatically handle disposing of streams they are providing or do you have to do this manually? If so, what is the best practice of where to dispose a stream exposed using stream provider?
Comment: Did you end up finding an answer?
Answer: No, it is not necessary to manually clean up streams when using StreamProvider.
StreamProvider extends DeferredInheritedProvider, whose documentation states that the object being listened to will be automatically disposed of when the DeferredInheritedProvider is removed from the tree.
Actually, assuming that you're not making the Stream yourself, then there is not much you can do in terms of cleaning up the actual Stream, as explained in this GitHub comment. The library providing the Stream should clean up the Stream. If, for example, I am listening to a Stream from the Firebase Auth plugin about users signing in and signing out of my app, it is the responsibility of that plugin to clear up that stream.
However, the thing listening to a Stream (StreamProvider in this case) does have a responsibility to clean up its StreamSubscription to that Stream, which StreamProvider does.
You can see in the Provider's source code here that when creating an instance of DeferredStartListening, listen is called against the stream, which returns a StreamSubscription. At the end of the method, cancel is invoked against that subscription, which cleans up the StreamSubscription.


Setting up development environment in Windows 10 without admin rights

Question: Let me give a quick background of the work I do and then I'll explain the problem I am facing.
I am a software developer with more than 15+ years work experience. My work involves a lot of varied tasks:

data analysis using R, Python
development of web applications using Ruby on Rails, JS, etc.
building models using open source libraries
So far, I have been doing all this  in my personal laptop (Ubuntu 18.04) and have faced no issues.

But I would soon need to start using a laptop provided by the organisation that I am working for. This org is not a IT company, it's a public body. They only use Windows (10) and don't provide admin access to anyone. It's very hard to get permission to install any kind of "approved" software. Just to give an example, they refused to install Chrome in my laptop as they wouldn't be able to control the updates.
So here's my problem - what do I do to work peacefully using their laptop? The primary reason I have to use the work laptop is that there are a lot of important documents kept in shared drives that are accessible only in their machines.
I have been looking at options like WSL or Hyper-V. But, before I put in a request to the IT team to get them to agree, I wanted to know a few things:
1) Which among WSL or Hyper-V would be the better approach for setting up the dev environment that I want?
2) IF I get the IT team to install WSL/HV, would I be able to set up everything else without having to go back to them for each software? Is there a way of secure local admin access these options would provide that will ease their concerns?
3) Is there some other way of setting up what I want?
Comment: If execution of downloaded portable software is possible/allowed you should check what programs of your development stack is available as portable software - I would assume that a large part of them is available. Anyway the main question is what is the target platform your developed apps will run on?
Comment: Nope, not possible to install portable software. E.g. I downloaded the RStudio executable file. When I try to run it (to install), it asks for Admin credentials (which I don't have) :|

The target platform for my developed apps are very varied. I would need to deploy some web-apps on an (AWS) Ubuntu server. In other cases, I would just need to perform data analysis and export my findings in a format (document/spreadsheet) that other colleagues can use.
Comment: If it asks for admin permissions you don't have a portable version. Anyway a locked down Windows machine is not a good development machine. You are not a user you are a developer. Ask your admins for a solution.
Answer: If still applicable and actual I can share my solution:
If you should work on a windows machine where you don't have administrative privileges, you can very easily make a portable R/Rstudio installation.
Download a recent version of R from the CRAN site and the recent version of RStudio. After download extract RStudio installation exec with 7Zip and copy files from $_OUTDIR to the desired location (in case you making an update, simply overwrite all files, that already exist). Your RStudio executable will be in
your-chosen-directory/bin/rstudio.exe

Then run CRAN-R installation, ignore the warning that you don't have administrative privileges and go forward until installation will complete. Run RStudio, from the menu
Tools->Global Options

locate where your R installation is located.
If you performing an update (more recent version of R), copy all files from the library subfolder of the old R installation into new, but this time DON'T OVERWRITE! This operation vill preserves the packages you have installed in the previous version of R. After copying update all your packages from the RStudio window (Packages->Update). When the packages update process will end check which packages failed to update (You will see warning messages near them in the RStudio console). Remove these packages (write down names of failed packages and delete corresponding folders from library subfolder). For this, you will need to exit from RStudio. After deletion launch RStudio again and execute the packages install command in the RStudio console:
install.packages(c("package1", "package2", "package3"))

Congratulations, You are ready to go!


Learning MimeType on active files, through Google Apps Script

Question: I will create an Add-on.
I want it to work for docs, sheets and forms. To make the menu, I need to know the file-type. How do I find it?
I could use DriveApp to check MimeType, but I will need the fileId.
Answer: This should solve it but the add-on-menu is not working properly. Worked once, then never again.
<code> function onOpen(e) {
  var menu;
  if(SpreadsheetApp.getActiveSpreadsheet() != null)
    menu = SpreadsheetApp.getUi().createAddonMenu();
  else if(DocumentApp.getActiveDocument() != null)
    menu = DocumentApp.getUi().createAddonMenu();
  else if(FormApp.getActiveForm() != null)
    menu = FormApp.getUi().createAddonMenu();
  if(menu)
    menu
    .addItem('Text', 'func1')
    .addToUi();
}
</code>


Programmatically Updating a document library in Sharepoint

Question: Im quite new to SHarepoint. I have a requirement like, i need to move some documents from different document libraries to a document library named "Region". So that each time a document is updated in these document libraries , the document should be updated in the library "Region" as well.
I wrote a c# function in a class library,to copy the documents to the library and added the dll to that sites Bin folder.Function is working fine. But Im stuck up , Im n ot sure where to call this function.In which event should i write it, so that each time any of these documents are modified, that change has to be reflected in the "Region" library .
Answer: You have to create a SharePoint event handler and attach it to all the document libraries where you change the documents. You will then override the ItemAdded and ItemUpdated methods to perform the copying.
See more info in this StackOverflow discussion: SharePoint running a method when item added to a library
Answer: Using an event handler is probably the best way to go as mentioned by naivists. Alternatively, if the work you are carrying out is part of a larger whole, e.g. a Workflow, then you may want to consider creating a Visual Studio Workflow, which may be quite complex to get started with, or use a simple tool like the Workflow Power Pack that allows simple C# snippets to be added directly to SharePoint Designer Workflows.
Have a look at these articles. More info can be found here.
Note that I worked on the Power Pack so I am biased. Having said that it works great ;-)


botão envia value de campo input hidden

Question: Estou com um problema quanto ao uso de um botão específico no projeto. Vou explicar: Tenho uma janela aberta pelo comando window.open, então nessa janela aberta tenho um botão que pega o valor de dois campos input hidden no qual está em while no banco de dados. Ao clicar nele, tem uma função onde envia o valor desse campo hidden para outro input da página em que executa o window.open (para simplificar, a página x.php abre via window.open a página y.php, então na página y.php tem um botão que envia um valor retornado do banco de dados para o campo input no x.php).
Aí que começa o problema, ao clicar eu até consigo enviar de um input ao outro, só que apenas o primeiro registro listado do banco de dados, os outros não enviam.
Segue a parte do y.php onde faz essa função:
Esse são os campos hidden:
$query = "SELECT * FROM equipamentos WHERE marker_id LIKE '$id'";

 $result = mysqli_query($conn, $query);

while ($row = mysqli_fetch_assoc($result)){

  ".$row['id']."
  ".$row['nome']."

".$row['lat'].">
".$row['lng']."

  <input type=\"hidden\" name=\"latMap\" id=\"latMap\" value ='".$row['lat'] ."'></input>
<input type=\"hidden\" name=\"lngMap\" id=\"lngMap\" value ='". $row['lng'] ."'></input>";

Então tenho o botão para enviar:
<button type=\"button\" id=\"btnLocalizar\" name=\"btnLocalizar\" class=\"btn btn-sm btn-primary\">
                            </button>

E o script para enviar:

O único problema é só conseguir enviar o primeiro registro, se alguém souber como fazer para pegar todos os registros listados pela query do banco de dados, seria de grande ajuda.
Comment: No y.php vc tem um while e que enviar todos os input hidden #latMap para um input na página x.php? Tudo num input só na página x.php?
Comment: Assim, tenho dois campos inputs na página x, e tenho dois input hidden na página y, só que esse input hidden só envia o value do primeiro registro listado da query. Eu queria que quando eu clicasse no botão do segundo registro (ex: registro 1 - brntwp; registro 2 - dvd) ele substituiisse o valor que tava naquele campo input lá do x, e conforme iria clicando no botões ao lado dos registros, trocaria lá nos dois inputs do x
Answer: Há alguns problemas no código, como duplicidade de ids. O botão da janela vai sempre enviar o primeiro id que encontrar. Ou você remove os ids ou coloque uma variável que diferencie os ids, como, por exemplo, uma variável de incremento no while:
$x = 0;
while(){
   ...
   <input type=\"hidden\" name=\"latMap\" id=\"latMap".$x."\" value ='".$row['lat'] ."'></input>
   <input type=\"hidden\" name=\"lngMap\" id=\"lngMap".$x."\" value ='". $row['lng'] ."'></input>";
   ...
   $x++;
}

Se estava usando os ids apenas para capturar os elementos, você não
  irá precisar deles e pode removê-los. A mesma coisa com o name e id dos botões dentro do while.

Outra coisa são estas duas linhas:
var input1 = document.getElementById('latMap').value;
var input2 = document.getElementById('lngMap').value;

Não devem servir para nada, então pode removê-las também.
O e.preventDefault(); também não tem serventia, já que os buttons são de cliques e não de submit. Pode remover essa linha também.
Como os botões estão na mesma linha da tabela que os input, você pode pegar o evento click pela classe .btn, capturando o valor do input hidden pelo name. Então seu código de envio dos valores ficaria assim:
$(document).ready(function(){
   $('.btn').click(function(){
      var linha = $(this).closest('tr');
      var input_valueLat = linha.find('[name="latMap"]').val();
      var input_valueMap = linha.find('[name="lngMap"]').val();
      $(window.opener.document)
      .find('#latMap')
      .val(input_valueLat);
      $(window.opener.document)
      .find('#lngMap')
      .val(input_valueMap);
   });
});

Comment: Perfeito! Funcionou do jeito que eu queria! uma dúvida por fora, não sou muito experiente com javascript, mas eu consigo fazer esse mesmo botão executar a função de outro do x.php? Pois no caso eu já consigo enviar os valores para o input de lá, e se fizer executar a mesma função de lá (no caso ele usa o valor dos inputs do x.php para marcar em um mapa) ficará melhor ainda, mas muito obrigado!
Comment: Nãi sei se entendi direito, vc quer que esse botão da janela aberta chame insira os valores no input e chame uma função na janela que abriu?
Comment: Já consegui fazer, coloquei um window.opener.document.getElementById('localizar').click(); logo abaixo da última linha do script que você fez. Uma dúvida é que tem como ele focar de volta para a pagina x? algo como window.opener.focus()?
Comment: Entendi, só que estranho que ele foca no navegador mas abre uma guia about:blank, não volta para a mesma janela parent
Comment: Aaaah, identifiquei o erro, não estava colocando dentro do script que abre o window.open, agora tudo certo, ví que só funciona no chrome mesmo, tanto no firefox quanto o explorer (um não foca e outro abre uma nova janela window.open). Mas disso eu já sabia, novamente, muito obrigado pelas respostas, tudo perfeito!

botão envia value de campo input hidden


How to exclude query string with specific parameters from .htaccess redirect

Question: I have a Wordpress site and I am discarding query strings with the following rules:
RewriteCond %{QUERY_STRING} .

RewriteRule ^ %{REQUEST_URI} [QSD,R=301,L]

The above rules work fine, but I want to exclude some URLs with specific parameters in the query string. I have tried to insert the following rules between the two rules above, but I am apparently missing something and the exclusion doesn't work:
RewriteCond %{QUERY_STRING} !^/?post_type=project

RewriteCond %{THE_REQUEST} !^/?post_type=project&p=14507&et_fb=1&PageSpeed=off

RewriteCond %{REQUEST_URI} !^/?post_type=project

RewriteCond %{REQUEST_URI} !^/?post_type=project$

My goal is to exclude URLs if they contain some or all of the parameters:
post_type=project

et_fb=1

PageSpeed=off

Answer: You may use this rule right below RewriteEngine On line (and above front controller WP rule):
RewriteEngine On

RewriteCond %{QUERY_STRING} !(?:^|&)post_type=project(?:&|$) [NC,OR]
RewriteCond %{QUERY_STRING} !(?:^|&)et_fb=1(?:&|$) [NC,OR]
RewriteCond %{QUERY_STRING} !(?:^|&)PageSpeed=off(?:&|$) [NC]
RewriteCond %{QUERY_STRING} .
RewriteRule ^ %{REQUEST_URI} [QSD,R=301,L,NE]

# more rule below this line

I am using 3 separate RewriteCond to be able to match these query parameters anywhere in query string (note use of OR clause).
Comment: @Yavor: Did this work out?


Bash - Compare 2 filelist and show the difference

Question: I am trying to compare filelist2 to filelist1. But somehow my code is not working, it always shows the first file as missing file, please assist
For example,
filelist1
app-663.tar.bz2
deb-663.tar.bz2
misc-663.tar.bz2

filelist2
app-663.tar.bz2
deb-663.tar.bz2

Here is my code
while IFS= read -r f; do
    if [[ -e $2/$f ]]; then
        printf '%s exists in %s\n' "$f" "$2"
    else
        printf '%s is missing in %s\n' "$f" "$2"
        exit 1
    fi
done < "$1"

output

app-663.tar.bz2 is missing in filelist2.txt
Comment: You are checking whether file named `filelist2.txt/app-663.tar.bz2` (`[[ -e $2/$f ]]`) exists. It is not comparing 2 lists. If you need to compare 2 text files, then `diff filelist{1,2}.txt`, or `colordiff filelist{1,2}.txt` can do. If you want to know whether text `app-663.tar.bz2` (`$f`) exists inside a text file `filelist2.txt` (`$2`), then `grep -x "$f" "$2"` would do.
Answer: awk is  your friend :
awk 'NR==FNR{rec[$0];next}!($0 in rec)' filelist2 filelist1

Output
misc-663.tar.bz2

All good :-)

Note: If you're starting with awk, check this [book]


Logistic regression: What are use cases for logistic regressions where $n \neq 1$, i.e., $n >1$?

Question: NOTE: This question relates to Binomial logistic regression. Thus, the $n$ in the title, refers to the parameter of the Binomial distribution.
Most real-world use cases of logistic regression introduced in statistics courses and employed in machine learning models are about binary logistic regression where $n = 1$.
Given that the logistic regression, in general, is based on a Binomial distribution (as can be seen, for example, in the application of logistic regression models in R, where the R library/package, glm, requires the user to set the argument family to binomial, in order to perform logistic regression.
My question is thus: What are use cases of logistic regression where $n \neq 1$, i.e., $n >1$?
Answer: Assuming that your $n$ is the number of cases of each type, you end up looking at proportions of each successful rather than $0-1$ and you weight by $n$.
Stealing from https://stackoverflow.com/questions/50078497/weighted-logistic-regression-in-r gives an example of sample data of proportions of successes (prop) plus sample sizes (n) for each value of the independent variable (x)
datf <- data.frame(prop  = c(0.125, 0,  0.667, 1,  0.9),
                   n     = c(8,     1,  3,     3,  10),
                   x     = c(11,    12, 15,    16, 18))

glm(prop ~ x, family=binomial, data=datf, weights=n)

which gives
Call:  glm(formula = prop ~ x, family = binomial, data = datf, weights = n)

Coefficients:
(Intercept)            x
    -9.3533       0.6714

Degrees of Freedom: 4 Total (i.e. Null);  3 Residual
Null Deviance:      17.3
Residual Deviance: 2.043    AIC: 11.43

you get a reasonable model producing a sensible looking chart like
though you also get a warning about non-integer #successes which you can ignore, and the wrong values for degrees of freedom, deviance and AIC.
Comment: @CausalQuestions I think that is what I have provided in my example, but note that the values in `prop` are proportion of successes rather than numbers of successes, so in the first case when $x=11$ you have $1$ binomial success out of $n=8$ attempts shown as a proportion of $0.125$.
Comment: With $n$, I mean the number of trials (Binomial distribution, i.e., number of Bernoulli trials). The chart looks like a logistic regression which allows values other than $\{0,1\}$, i.e. any real value in interval $[0,1]$. Is that thinking correct? Clarification comments about your answer. In the example, the dataset comes with an additional variable (here sample sizes $n$), that represents the number of trials $n$ used to get the proportion values $prop_i$? If I were to replace each $n_i$ in the dataset with 1, would the fitted model then be a binary logistic regression again?


$n^{q}\equiv1~(\text{mod $p$})$ is possible solve this?

Question: I have the following situation:
Let $p, q$ be a prime numbers were $p>q$ and $n\in\{0,1, \ldots, p-1\}$. In this conditions is possible solve (in function of $n$) this equation, $n^{q}\equiv1~(\text{mod $p$})$ ?
Comment: Solve for $p$ or $p$ and $q$ and $n$?
Comment: Without being told what the unknown is, I can refer you to computation of discrete logarithms as generally the kind of problem this is.
Comment: Soluble for $n$
Comment: The nonzero elements of $\mathbb{Z}/p\mathbb{Z}$ form a multiplicative group of order $p-1$, in fact the cyclic group of that order.  So unless $q$ happens to divide $p-1$, there will not be a solution.
Answer: If $q$ is not a divisor of $p-1$, then $n\equiv 1\pmod p$ in the only solution.
If $q\mid p-1$, then there are $q$ solutions, and you can find them by brute force by computing $n=1^d,2^d, \dots, (p-1)^d$ where $qd=p-1$.


Rearrange equation with variable exponents

Question: I want to understand how I might rearrange an equation with variable exponents to solve for a desired variable.
Take this equation, for example:
$d = \frac{(l(r(1+r)^{m})(s(1+s)^{n}))}{(-r+(1+s)^{n}(r+(-1+(1+r)^{m})s))}$
How can I isolate and solve for $s$?
Answer: You can rearrange the equation to be of the form:
$$s(s+1)^{n}[(lr-d)(r+1)^m+d]-rd(s+1)^n+rd=0$$
Which is a polynomial of degree $n+1$ in $s$.
You have 6 unknowns including $s$ here.
The types of solutions for $s$ depend on the values for the other unknowns, and the value of $n$ dictates what degree the polynomial is, and how the polynomial could be solved.
Eg the case $n=1$ is much simpler than $n=2,3$ etc.
Comment: How would your rearrangement look for m = 3 and n = 33, then? Is n = 33 going to be a nightmare?
Comment: Try it and see :-D. You may want to use some of the online solvers.. :)


Adding a value to ActionController::Parameters on the server side

Question: I want to add some value I'm evaluating on the server to the params.
  def my_params
    params.require(:my_model).permit(:my_field1, :my_field2, :my_field3)
  end

  def update
    # ..................

    # checking
    my_params["my_value"].class # => ActionController::Parameters
    my_params["my_value"] # => nil

    # adding
    my_params["my_value"] = "my value's value" # => "my value's value"

    # but it's still nil
    my_params["my_value"] # => nil

    # ..................
  end

Why can't I add it into my_params?
Answer: my_params is a method not a variable, use an instance variable instead, as below
def my_params
    @my_params = params.require(:my_model).permit(:my_field1, :my_field2, :my_field3)
end

def update
  @my_params["my_val"] = "my value"
  #....
end

Comment: Just access the params directly... `params[:my_val] = 'my value'`
Comment: @DamienRoche that's bad, since he is whitelisting some params
Comment: ...and where are you whitelisting `my_val`?
Comment: @DamienRoche `params.require(:my_model).permit(:my_field1, :my_field2, :my_field3)` is to whitelist `params` that are not trusted, `my_val` is coming from the server so it is trusted and does not need whitelisting
Comment: @bjhaid I'm afraid you're contradicting yourself. If the controller is setting the param, then why is it "bad, since he is whitelisting some params" because I accessed the `params` directly? There is nothing wrong with `params[:my_val] = 'my value'`.
Comment: In fact, you're code doesn't work. The `@params` instance variable isn't even assigned when you access the `update` method, and you're not permitting `my_val`. Permit `my_val` and simply use `my_params[:my_val] = 'my value'`. No need to assign `@params`.
Comment: @DamienRoche what would be the value of `params` after it has passed through the `my_params` filter???, `my_params` does not mutate `params`, neither should you mutate it to avoid issues with debugging
Comment: Why do you think using `@params` is necessary or even a good idea? http://weblog.rubyonrails.org/2006/4/24/use-params-not-params/
Comment: @DamienRoche have you tested this code before claiming it does not work, the OP most likely has a `before_filter` that calls `my_params`, for me it is that he should use an instance variable that he can reference anywhere call it `@params` or not, your answer uses a method and not an instance variable, methods don't have state, so setting a key on the method does not change the state of the parameters
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/54072/discussion-between-bjhaid-and-damien-roche).
Comment: Have you tried to run your code? It doesn't work even with `my_params` called first because you're not permitting `my_val`! Why are you talking about methods and state?
Comment: whoa-ho-ho-ho, let's keep it funny. @DamienRoche here is right. bjhaid, that means you should listen to him.
Comment: I was actually mistaken about mutating params via `my_params[:key] =`, not sure why I received a positive. And @bjhaid does have a good point about not directly accessing `params`. Maybe my Rails install is borked, but `@params[:anykey] = 123; my_params[:anykey]` does not work because `my_params` simple reassigns `@params`. It works if you use `@params ||= [...]` within `my_params` but then allows any key. Yet if you are going to fetch with `@params[:key]`, you might as well use `params[:key]` directly for the above reason (filter is not applied, anyway).


Assigning object to ivar when already assigned to that particular ivar

Question: In a situation where I am assigning an object to an ivar which the object may already be assigned to, is there any benefit to first checking whether it is already assigned to that ivar.
For example, is there any benefit to code A over code B?
A
if (ivar != anObject)
{
    ivar = anObject;
}

B
ivar = anObject;

Answer: its not strictly necessary, I believe the @property/@synthesize generated setters do this as an optimisation and to stop unneseccary memory management calls on the same object (for a strong property the old object is released and the new one is retained, but if they are the same pointer the end result is the retain count is unchanged)
Comment: In addition to memory management methods the check will also prevent unnecessary KVO notifications from being made.
Comment: @BenedictCohen i dont think thats true. KVO notifications are sent in a subclass's implementation of the setter, so they dont know if the actual value was changed
Comment: Yes, you're correct. My bad. `@synthesize` doesn't fire the KVO notifications, they are handled by `NSObject`. If automatic notification is turned off (with `automaticallyNotifiesObserversForKey:`) then the `@synthesize`d properties do not raise KVO notifications.
Comment: Also, in MRC releasing the old object before retaining the new one will result in premature deallocation if it's the same object. (unless, of course, the retain count is greater than 1) This is more serious an issue than emitting redundant retain/release calls.


Migrate a CSV into two entities with reference

Question: I have a CSV as below:
chapter, headings, sentences
1, heading one, "1,2,3,4,5,6,7"
2, heading two, "1,2,3,4,5"
2, heading three, "6,7,8"

I want to migrate it to Drupal. The heading columns have to be migrated to the taxonomy heading. Once a heading is added, it should loop through the value in sentences and update the sentence entity by adding a reference to it.
The entity to be updated should be loaded matching the sentence column and chapter column. The sentences entity is already pre-populated with data.
Fields in each entity:
Taxonomy:
heading(string)

Entity(sentences):
sentence_no(int)
heading_reference(entity_reference)
sentence(string)
chapter_no(entity_reference)

I tried this tutorial. While the link is straight forward it doesn't really help my need.
I am ok if I migrate to D7 or D8. However D8 is preferred.
Answer: It's fundamental to how the migration process works that it processes one item being written at a time. In this case, since it's sentence entities that are being updated, it needs a migration that processes one sentence at a time. The layout of your CSV here is not well-suited for that, and to work directly from that CSV would require significant hackery. The best approach would be to either generate your CSV in this format in the first place, or have a preprocessing step to put the data in this form:
chapter,sentence,headings
1,1,heading one
1,2,heading one
1,3,heading one
1,4,heading one
1,5,heading one
1,6,heading one
1,7,heading one
2,1,heading two
2,2,heading two
2,3,heading two
2,4,heading two
2,5,heading two
2,6,heading three
2,7,heading three
2,8,heading three

Then, you'd have a migration with source IDs chapter and sentence, setting the heading for each sentence from the headings column.


Intro stats, one-way repeated measures ANOVA finding standard deviation from missing data?

Question: I'm trying to do a one-way repeated measures ANOVA, but I'm missing some data in the question (I'm not looking for the answer, just a hint on what I'm missing here..). The data in question is:
Paint types:
1 data: {10,6.2,7.6}
2 data: {11.3, 9.2, 9.9}
3 data: {10.3, 9.2, 9.8}
4 data: {11.8, ?, ?}
The overall Standard deviation is 1.657.
Notice in the fourth paint type there is missing data. I have the SStr = 8.67, although I'm not sure how to find the SSE since from what I know I need the standard deviations for this.
There was a previous question with this same data but there were two factors and I was able to do the two-way ANOVA fine with the info given. Any tips for this one-way ANOVA?
Answer: Got the answer! Didn't know $SST = (N-1)S^2$. Was able to figure everything out from there. :-)
Comment: @kjetil In this case, it appears that the OP has managed to answer their own question. Though obviously this answer would be more helpful to future readers if it mentioned (though not necessarily explaining in detail) how one can go from the given formula to a solution to the problem.
Comment: Please don't add "thank you" as an answer. Instead, **[accept the answer](https://stats.stackexchange.com/help/accepted-answer)** that you found most helpful.  - [From Review](/review/low-quality-posts/157036)


How to adjust the vertical placement of markups in Lilypond

Question: Using Lilypond 2.20 on Ubuntu 20.04.
This code:
...
%% fingering symbols
fngaLong = \finger\markup{\box{\pad-markup #0.2 \override #'(font-name . "pipa") \fontsize #7 "a-"}}
...
\appoggiatura{c8-3} a2-1\trill\fngaLong
...

renders like this:

But I must place the trill under the boxed fingering symbol. In another word, I must swap the vertical position of the trill symbol and the boxed fingering symbol. How to do this?
Another question: The finger number 3 is smaller than the finger number 1. I'd like to make the 3 as big as the 1. How to do this?
Many thanks in advance!
Answer: The order in which several things are stacked vertically is controlled by the outside-staff-priority. The lower the priority, the closer to the staff. You can find all the info in the in the corresponding section of the docs.
As for the fingering, the easiest way would probably be using a tweak (at least if you want to do this in one place only). Instead of something like c8-3, you would write c8-\tweak font-size #2 -3. If you would like to do this globally for all the grace notes, then, sadly, I don't know how to do that. Maybe you could manipulate the Grace_engraver in your \layout block somehow, but I don't know what to do.
Answer: I read the answer from @Ramillies, the document is comprehensive but I did not figure out how to use the commands correctly. Then I found a very simple example in the doc page Expressive marks attached to notes.
Now this vertical stack of markups is exactly what I want:

My source code:
...
%% fingering symbols
fngaLong = \finger\markup{\box{\pad-markup #0.2 \override #'(font-name . "pipa") \fontsize #7 "a-"}}
...
\once \override TrillSpanner.script-priority = #-300
\appoggiatura{c8-3\startTrillSpan^\fngaLong} a2-1
c8\stopTrillSpan d4\fermata c8


To prove subspace of given vector space of functions

Question: V is the set of all real-valued functions defined and continuous on the closed interval [0,1] over the real field.
 Prove/disapprove whether the set of all functions  W belonging to V, which has a local extrema at x=1/2, is a vector space or not.
P.s : I am confused at second derivative test, as the linear combinations of 2 functions may result in a function whose second derivative at x=1/2 is zero.
Comment: what does you mean you are confused with the second derivative test ? Looking like it is a vector subspace of the vector space V.
Comment: Do you mwan that $1/2$ is a critical point?
Comment: let's suppose f and g are two functions belonging to W and a,b belongs to field. Since both have a extrema at x=1/2, at their second derivative is greater or less than zero. But a*f + b*g may have second derivative equal to zero.
Comment: yes. x =1/2 is a critical point.
Answer: Let $f(x)=(x-1)(2x-1)^2$ and $g(x)=x(2x-1)^2$.
Then $f^{\prime}(x)=(2x-1)(6x-5)$ and $g^{\prime}(x)=(2x-1)(6x-1)$,
so $f$ and $g$ are both in W $\;\;$(since f has a local max. at $\frac{1}{2}$ and g has a local min. at $\frac{1}{2}$).
However, $f+g$ is not in W,
since
$(f+g)(x)=(2x-1)^3$ and $(f+g)^{\prime}(x)=6(2x-1)^2,\;$
so $f+g$ is always increasing.
Therefore W is not a subspace of V.
Comment: well $(f+g)'(\frac{1}{2})=0$ and so $f+g\in W$, right ?
Comment: @MohamadMisto No, I don't think so; the tangent line to the graph of $f+g$ is horizontal at $(1/2,0)$, but $f+g$ doesn't have a local extremum at $1/2$
Comment: i thought he asked for only a critical point idk thats why i asked
Answer: Let $h: [0,1] \to \Bbb R$ be defined by
$\tag 1 x \mapsto x - \frac{1}{2}$
Define $f(x) = \text{max}\big(h(x),0\big)$ and $g(x) = \text{min}\big(h(x),0\big)$.
We have $f,g \in W$.
The function $f + g$ is equal to $h$ but $h \notin W$.


Similarity in shapes

Question: I have been thinking which countries in the world are similar in shape, then I had this problem.

For example we have country maps as seen in the figure and we need to determine which country is similar in shape to the country A. Intiutively we can say that the 5.th country is more and less similar, but it is difficult to determine the second most similar country.
The sizes of the maps do not matter, we have option to scale. I have been thinking to solve the problem like least squares method but we have to determine the functions of the maps.
Is there any branch of mathematics study these things?
Comment: See http://en.wikipedia.org/wiki/Shape_analysis_(digital_geometry).
Answer: This would fall under the heading "shape registration" or "shape matching", and is a common task in computer vision - for instance, the mail sorting machines used by the post office use shape recognition to read the addresses on letters and packages.
You might take a look in to image registration for starters, and possibly this paper about shape similarity measures.  The bibliography in that paper would also be a good place to look.
In general, the problem isn't as easy as one might think, since like you say we have to consider mappings of the shapes in addition to just their boundaries.  It is always possible to measure the "distance" between two shapes using the Hausdorff distance, but that measurement only will only help for your problem once the shapes have been "registered", i.e. shifted and scaled so they match as closely as possible.
One naive numerical method might be to use the Hausdorff distance to register the shapes as follows:

Approximate the center of mass of the shapes, and translate one so their centers match up
Minimize the Hausdorff distance between the shapes by rotating and scaling
The minimized Hausdorff distance gives a measurement of the distance between the two registered shapes

Here's another link I've just found.  This is fun stuff to play with, enjoy!

Similarity in shapes


Simple query is slow in laravel (with paginate) but very fast in phpmyadmin

Question: I've looked at similar questions, and the answers I get is to put limit in my query, which I did.
Here is the query
  $sql = DB::table('inventorysku_tb as isku')
     ->leftJoin('inventorytrackingmodules_tb as itm', function ($join) {
        $join->where('itm.coID', '=', 4)
           ->whereBetween('itm.effectiveDate', ['2021-05-01', '2021-05-31'])
           ->on('itm.skuID', '=', 'isku.ID');
     })

  $sql->paginate(25);

  return $sql;

This query takes around 17 seconds to run, now if I run ->toSql() on the query above and paste it in phpmyadmin (changing the ? values)
select *
from `inventorysku_tb` as `isku`
    left join `inventorytrackingmodules_tb` as `itm`
        on `itm`.`coID` = 4
        and `itm`.`effectiveDate` between '2021-05-01' and '2021-05-31'
        and `itm`.`skuID` = `isku`.`ID`

This one only takes 0.2 seconds to run in phpmyadmin...
That is all on the laravel code, there are no other codes above it...
Another weird thing is if I change to left join to inner join in laravel, the query is now fast (878 ms)..
Comment: Hey, so a few things you can try. Firstly you can use [Laravel Debugbar](https://github.com/barryvdh/laravel-debugbar), which will show you the queries run on each page and will make it easier for you to debug. Another thing, which may help is adding indexes on your tables.
Answer: according to Laravel doc:
On clauses can be chained, e.g.
$join->on('contacts.user_id', '=', 'users.id') ->on('contacts.info_id', '=', 'info.id')

will produce the following SQL:
on contacts.user_id = users.id and contacts.info_id = info.id

so, for you case the code could be:
$sql = DB::table('inventorysku_tb as isku')
     ->leftJoin('inventorytrackingmodules_tb as itm', function ($join) {
        $join->on('itm.coID', '=', 4)
           ->on(function ($query){
                $query->whereBetween( 'itm.effectiveDate',['2021-05-01',
                   '2021-05-31']);
           ->on('itm.skuID', '=', 'isku.ID');
     })

this way, I think you could produce the same query that you used in phpMyAdmin
Answer: Remove LEFT.  Since you are limiting things in the WHERE it is a JOIN.
Add this to itm:  INDEX(coID, skuID, effectiveDate)


How to check if ratio of 2 numbers is a perfect square without actually finding the ratio?

Question: How to check if ratio of 2 numbers is a perfect square without actually finding the ratio?
For example, if $a = 27$, $b = 3$, then their ratio $\frac{27}{3} = 9$ is a perfect square.
Can we determine whether ratio of 2 numbers is a perfect square without actually finding the ratio?
Comment: This is equivalent to $\sqrt{ab}\in\mathbb{Z}$ with $b\mid \sqrt{ab}$.
Comment: One way is to find the prime factorisations of both numbers. If the difference between the exponents of the factor is odd (say $2^2$ and $2^3$), then the result is not a perfect square. Only if all the differences are even will the ratio be a perfect square.
Answer: One way is to find the prime factorisations of both numbers. If the difference between the exponents of the factor is odd (say $2^2$ and $2^3$), then the result is not a perfect square. Only if all the differences are even will the ratio be a perfect square.
Another way is to use Euclid's algorithm to find $\frac{a}{\gcd{(a, b)}}$ and $\frac{b}{\gcd{(a, b)}}$, where the $\text{gcd}$ is the greatest common divisor of $a$ and $b$. Then these two numbers must be coprime since they have already been divided by the greatest common divisor. If the largest number out of $a, b$ is a perfect square, their ratio ($\frac{b}{\gcd{(a, b)}}$ divided by $\frac{a}{\gcd{(a, b)}}$) is a perfect square.


What are the differences between ANOVAs and GLMs?

Question: I'm wondering how different are generalized linear model and ANOVA. I thought it was because of categorical vs continuous variables, but it doesn't seems to be the case.
Also, I know that it's possible to add mixed effects in a GLMM. Is it the case for ANOVAs?
So, why would one use GLM vs ANOVAs?
Here is an example:
# Difference regression vs ANOVA vs GLM
gr1 = rnorm(10,10,1)
gr2 = rnorm(10,20,1)

df=data.frame(nm = c(gr1,gr2),
              gr = c(rep(0,length(gr1)),
                     rep(1,length(gr2))))

ANOVA
summary(aov(nm~gr, data = df))

            Df Sum Sq Mean Sq F value  Pr(>F)
gr           1  496.4   496.4   621.1 2.1e-15 ***
Residuals   18   14.4     0.8
---
Signif. codes:
0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

GLM
glm(nm~gr,family = "gaussian", data = df)

Call:  glm(formula = nm ~ gr, family = "gaussian", data = df)

Coefficients:
(Intercept)           gr
     10.050        9.964

Degrees of Freedom: 19 Total (i.e. Null);  18 Residual
Null Deviance:      510.8
Residual Deviance: 14.39    AIC: 56.17

And once we are there, why not comparing linear regressions and t-test!
Linear regression
summary(lm(nm~gr, data = df))

Residuals:
     Min       1Q   Median       3Q      Max
-1.13990 -0.85335  0.00061  0.41865  1.92899

Coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept)  10.0502     0.2827   35.55  < 2e-16 ***
gr            9.9638     0.3998   24.92  2.1e-15 ***
---
Signif. codes:
0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.894 on 18 degrees of freedom
Multiple R-squared:  0.9718,    Adjusted R-squared:  0.9703
F-statistic: 621.1 on 1 and 18 DF,  p-value: 2.095e-15

t-test
tt=t.test(df$nm~df$gr);tt
    Welch Two Sample t-test

data:  df$nm by df$gr
t = -24.922, df = 17.914, p-value = 2.347e-15
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
 -10.804012  -9.123526
sample estimates:
mean in group 0 mean in group 1
       10.05023        20.01400

(tt$statistic)^2
       t
621.0907

Comment: ANOVA assumes *Gaussian* distribution of the residuals (and uses a linear model that minimizes the sum of squares, which can be used in a F-statistic). GLM generalizes the linear model used in ANOVA by allowing any other type of distribution of the residuals (and optimizes the likelihood function, which only allows a t-test based on an estimated error of the coefficients).
Comment: *So an ANOVA is GLM*. It is a bit semantic now. 1) GLM *includes* ordinary least squares. You can't really say OLS *is* a GLM (since GLM is general and OLS is not). Better would be to say that OLS is GLM with identity link and variance functions. 2) ANOVA is not exactly the same as OLS. It is the analysis performed on a linear regression (on the sum of squares of residuals). Also, ANOVA refers to analysis of reduced var_residuals which you can't do (makes no sense) with GLM. However, in practice, people doing ANOVA often do OLS and model effects. But technically $ANOVA \neq OLS \in GLM$,
Comment: Whoa! For some people GLM is general linear model and for some is GLM is generalized linear model, not all identical. This thread hasn't avoided confusion.
Comment: So an anova is an Glm, but a Glm is not only anovas.
Comment: The *normal* linear model is a special case of GLM, while OLS is a distribution free algorithm to find its  solution. The classic t-test is a special case of the normal linear model.
Comment: OK, and OLS is a special (as well as ANOVA and t test) case of linear model which is a special case of GLM,
Answer: This is a common point of confusion, as the word ANOVA is used with different meanings in different textbooks / software packages. I'll try to sort this out a bit:
Historically, ANOVA is a method to partition out the contribution of different factors to the variation in a continuous variable. The classical ANOVA measured this contribution via the sum of squares, which corresponds to the assumptions of an lm (iid normal and so on), thus you will often read that AVOVA = normal distribution. This also implies that it doesn't matter if you calculate an ANOVA directly, or first an lm and then perform the ANOVA on the fitted lm, it's basically the same model.
This obviously doesn't generalise to GLM(Ms), but people would still like to test for the significance (and contribution) of factors or factor groups in those models. Thus, the ANOVA concept has been extended, and a more modern way to look at ANOVA is that an ANOVA is just a series of tests that add / remove predictors or predictor groups in a regression to test for their overall significance, as well as changes in some metric of fit (pseudo R2, there are multiple definitions, most based on deviance).
So, regardless of lm, glm, glmer, if you have a model with a predictor color = red, green, blue, in R
m1 <- lm/glm/glmer(res ~ color)
summary(m1)

will give you p-values for the contrasts between red, green, blue, while
am1 <- anova(m1)
summary(am1)

will essentially do a (likelihood ratio) test to decide if the predictor color improves the fit significantly (note that adding color, you are adding 2 df / parameters at once), and it will also provide a feedback about the improvement of fit.
In R there are different ANOVA functions (aov, anova, car::ANOVA) that slightly differ in their use and appropriateness for particular regressions and questions. car::ANOVA is very versatile and allows changing between type II, II ANOVA (explanation here)
Note that you can also use the anova command in R to do a LRT between two models, as in anova(m1, m2), so in a way you can see anova(m1) simply as a shorthand to compare m1 all of its smaller submodels via a LRTs.
Answer: regression & ANOVA are General Linear Models - for Normally distributed data. Example of Generalized Linear Models can be Logistic Regression that uses logistic-function, or logistic-curve (S-shaped), that converts log-odds to probability of belonging to certain class (in binary classification) or other non-linear functions assigned in arguments of API's glmm-implementation

Also, I know that it's possible to add mixed effects in a GLMM. Is it
the case for ANOVAs?

yes ANOVA can be GLMM for analysing within-group & between-group variability e.g. having several experiments repeated (as random effect) & compaaring it to the group after any treatment (as fixed effect)


Where is Create Unit Test in VS 2017?

Question: I understand that this question has been asked before on SO and it appears that this feature was removed from VS at some point. But I am looking at a Microsoft tutorial right now and that says there should be a Create Unit Test function in VS 2017.
I'm trying to test ASP.NET Core MVC controllers. I have followed the steps for creating a test project. But I still can't see any such option when I right click a namespace/class/method.
EDIT: I'm using Visual Studio 2017 Community Edition
Comment: I think this post answers the question http://stackoverflow.com/questions/42974497/create-unit-tests-context-menu-option-missing-in-visual-studio-2017/
Comment: @MichaelFreidgeim it's not actually a duplicate I don't think; the other question is referring to full .net projects, whereas this is specifically .net core related.  The expected behaviour turns out (unhelpfully) to be different depending on the .net version.
Comment: I am having the same problem.
I was using this in 2015, but I can't find it in 2017.
[https://www.visualstudio.com/en-us/docs/test/developer-testing/getting-started/create-unit-tests-menu]
Comment: Could be because I'm using .NET Core? I'll try with a normal project
Comment: Possible duplicate of [Create Unit Tests context menu option missing in Visual Studio 2017?](https://stackoverflow.com/questions/42974497/create-unit-tests-context-menu-option-missing-in-visual-studio-2017)
Answer: The answer below relates to .NET Core/Standard only.  If you're missing the Create Unit Tests option for a full .NET Framework project see here.
Current status: It's now working for .NET Core!
I now have the Create Unit Tests context menu in my Core 3 solution running on Visual Studio Professional 2019 Version 16.3.0 Preview 3.0.  Not sure exactly when it reappeared as I've been updating regularly with each new preview version.
History
See the updates below for more history and details.
Original answer June 2017
This GitHub entry from Microsoft's Jayarani Garg, confirmed it is only available for projects targeting the full .NET framework:

Jayarani Garg [MSFT] · Feb 27 2017 at 06:09 AM Hi,
Thank you for your feedback. "Create Unit Test" is currently not
  supported for .Net Core projects.

That's by design rather than a bug according to this Visual Studio Team comment on that same Visual Studio Developer Community page:

Visual Studio Team ♦♦ · Mar 10 2017 at 01:06 PM
Thank you for your feedback! The Visual Studio team has determined that this issue
  is not a bug. However, we will consider this feedback and have created
  https://github.com/Microsoft/vstest/issues/592 to track this. Please
  feel free to vote for the issue.

The github issue referred to above on the Microsoft VS Test repo Create Unit Test Context Menu Missing (.net core projects) is slightly confusing.  It's asking for this feature to be added for .NET Core projects too but then a Microsoft employees talk about having a fix for an issue. I believe that employee is referring to the old bug where the context menu option wasn't working for full .NET framework projects either as discussed in this question which is also mentioned in that thread. As far as I can see that thread is not saying they've added the menu option for .NET Core projects.
I've also just checked on a copy of Visual Studio Professional 2017, version 15.2 (26430.6) and I do have the Create Unit Tests option for a project that targets the full .NET framework (this one targets .NET Framework 4.5.1):

But I don't have it for a project that targets .NETCoreApp 1.1:

Update June 2018
Microsoft have taken notice of the upvotes for the feature request and are planning to introduce the context menu option for .NET Core projects in release 15.8:

Manish Jayaswal [MSFT] replying to Daniel Tibi · Apr 06 2018 at 10:30 PM
Getting this functionality added to .NET Core projects requires some
  significant changes in the new project system - which drives the .NET
  Core projects. This work is getting tracked in project system GitHub
  repo in this issue
  (https://github.com/dotnet/project-system/issues/3425) . This issue is
  expected to be resolved in 15.8 release timeframe so unfortunately,
  create unit test functionality for .NET Core projects would not be
  available in the upcoming 15.7 release. We fully understand that this
  is a key feature and would do our best to make it available as early
  as possible.

Update July 2018
The Create unit test method stubs with the Create Unit Tests command page has been updated now to reflect that this doesn't work for .NET Core.
Update August 2018
As pointed out by @gartenriese below, the GitHub issue 3425 Microsoft described as tracking this work was moved to the 15.9 milestone on 02 August 2018.
Update January 2019
The unit testing feature seems to be reliant on, or blocked by, another part of the development.  That part is now slated for VS 16.1, i.e VS 2019, and is also further down the priority list than EF Core 3.0 (which is one of the main features of VS 16) according to this GitHub post by Microsoft's David Kean.
May 2019 update
The Create Unit Tests context menu option isn't supported (yet) for projects that target .NET Core and .NET Standard.
The documentation was updated to reflect this in July 2018 and now states:

The Create Unit Tests menu command:

Is available in the Community, Professional, and Enterprise Editions of Visual Studio 2015 and later.
Supports only C# code that targets the .NET Framework.
Is extensible, and supports emitting tests in MSTest, MSTest V2, NUnit, xUnit format.
Is not yet available in .NET Core projects.

This feature was slated for release in Version 15.9 of Visual Studio, but now appears to have been pushed back to Version 16.1.
I've tested this in a .NET Core 2.2 project in Visual Studio Professional  2019 RC (version 16.0.0) and I can confirm it's still not working there - as expected as per the above answer.
I've also just tested Visual Studio Professional 2019 Preview (version 16.1.0 Preview 2.0) and it's not available there either, so it doesn't look like Microsoft have got to this yet.
Comment: It's been pushed back to 15.9.
Comment: thank you very much for taking the time to update.
so far, 15.8 seems like its going to be a major release.
Comment: @tomRedox: In the issues it says (relatively at the end) "Pilchie modified the milestones: 15.8, 15.9 on 2 Aug". I don't think I can directly link to that.
Comment: It is November 2018 and we are still on 15.8.9 with no unit testing (creation) on .NET Core/Standard projects.
Comment: @tomRedox It was based on the automated GitHub notification at the bottom of the Issue: "drewnoakes modified the milestones: 16.3, 16.4 2 days ago". The relevant issue (#3425) is now in https://github.com/dotnet/project-system/milestone/29
Comment: @gartenriese, do you have a link for that at all?  I'll add it into the answer if so
Comment: 23-SEP-2019: Moved to the 16.4 Milestone
Comment: @jboeke do you have a link for that?  I'll update the answer if so

Where is Create Unit Test in VS 2017?


Debug.Assert versus conditional compilation

Question: Consider the code below:
#if DEBUG
    if (Systems.Contains(system))
        throw new InvalidOperationException("System already registered");
#endif

    Debug.Assert(!Systems.Contains(system), "System already registered");

Previously I used to do the former, I've since discovered Debug.Assert.
Is there a reason why I should not always prefer Debug.Assert?

It only exists in debug code (it has the attribute [Conditional("DEBUG")]).
It seems to me to be more suited to my intention (code sanity checks, rather than raising exceptions to be handled later).
It's less code to write.
Comment: to be honest I'd rather throw in release mode as well 99% of the time, so rarely use either
Comment: Debug.Assert wins every time for me
Comment: @jk.: True. In this case it's for a game, so checks like these are best avoided if possible but are ok for getting an error sooner when debugging.
Answer: You can always use Debug.Assert(), because this class is complied with the DEBUG conditional as well:
[Conditional("Debug")]

Indicates to compilers that a method call or attribute should be
ignored unless a specified conditional compilation symbol is defined.
ConditionalAttribute is applied to the methods that are defined in the
Debug and Trace classes.
http://msdn.microsoft.com/en-us/library/system.diagnostics.conditionalattribute.aspx
Comment: +1 Thanks for the info, although I was already aware of the [ConditionalAttribute](http://msdn.microsoft.com/en-us/library/system.diagnostics.conditionalattribute.aspx) (edited to make that clear).
Comment: Great, so then I would use your "3. It's less code to write." as the main reason for Debug.Assert() :-)
Comment: Thanks, I'll leave this open for a while longer to see if there are any other responses (haven't forgotten to accept).


Commerce coupon only one coupon active at a time

Question: I have 3 types of coupons on my site, 2 of them are contrib(fixed amount and percentage amount) and 3rd one is custom(pretty much copy of percentage).
  I need to make sure, that only one coupon of custom type can be active at given time. Which hooks should I use to make sure that when one coupon of custom type is made active, the other one becomes not active?
Thanks in advance
Answer: My solution is as follows.
1. Check if entity created is a coupon and that coupon type is the one im checking using hook_entity_insert and hook_entity_update
2. Check if coupon changed or inserted has been put active if yes then load all other coupons of right type and turn them inactive


How to get calculated values result and add new row

Question: i have three  inputs , am subtracting values in two inputs and binding result in result input . but i want to add new row on button click, i tried giving ng repeat in tr but not working
var ReceiptsApp = angular.module('ReceiptsApp', []);

ReceiptsApp.controller('ReceiptsController', function ($scope) {
 $scope.rvm = [{}];
   $scope.addRow1 = function (index) {
        //alert('ss');
       $scope.result = $scope.r.val1 - $scope.r.val2;
        if ($scope.rvm.length == (index + 1)) {
            $scope.rvm.push({
            });
        }

    }

});

find code  here
 https://jsbin.com/qutuyodite/edit?html,js,output

Answer: ReceiptsApp.controller('ReceiptsController', function ($scope) {
 $scope.rvm = [{}];
   $scope.addRow1 = function (index, r) {
        // pass the particular array object on which you want to perform calculations when the function is called from ng-click and access those particular objects values using r.val1 and r.val2
        //Access particular "rvm" object using index
        $scope.rvm[index].result = r.val1 - r.val2;
        if ($scope.rvm.length == (index + 1)) {
            $scope.rvm.push({
            });
        }

    }

In HTML

   <input type="text" lass="input-large" ng-model="r.result" name="res" />

  <button type="button" class="btn btn-default" ng-click="addRow1($index, r)">Add</button>

Working JSBin
Comment: Did this answer your question or are you facing any issues?
Comment: Thank you ravi,in my requirement i have add button out side of ng repeat and code here   https://jsbin.com/repanijitu/edit?html,js,output
Comment: You are saying you want to have only `one` add button?
Comment: actually i have that calculations(two inputs )in model popup , if i add i want to show result in table grid by closing popup   https://jsbin.com/pugoxohile/edit?html,js,output
Comment: Can you exactly describe how user will interact between popup and table?
Comment: i have 3 columns in my table grid
input(result) and two buttons .
one is pendings ,if i click this am showing modal popup(bootstrap) in that i have that two inputs and Add button
if i click Add am closing popup and want to those calculated result in this result input in main grid
second button is for adding new row
Comment: When you click on `pendings` button `push` a new `object` into main array. Then pass that newly created object to `modal` and `bind` properties in new `object` to input fields in modal. If you do this whatever user inputs  in the modal will automatically bind to the new object(since, in JS object is a reference type). Then once you close  the the modal you can get values from the object. Use index to keep track of object.
Comment: .Am getting data ravi but when i add row that same result binding in second row also
Comment: In my answer in html I did a change.. did you make that change in your code? `ng-model="r.result"`. Notice `r.result`, which means I am pointing `result` property to a particular `r` object.
Comment: can you please go for this link and get result, if i get this my application also works  https://jsbin.com/bayisocapa/edit?html,js,output
Comment: In your app don't you have `add` button inside the table which is inside `ng-repeat`. Your table rows should be inside the `ng-repeat` right? While input fields inside modal is not in `ng-repeat`..


Expected time to visit all countries by random flight paths

Question: Say there are $n$ different countries, the flight starts from some initial country. At each step, the flight can go to a random country other than the one where it currently is. The probability of going to other countries are equal. Let random variable $X$ be the number of steps until the flight has visited all the countries at least once. What is $\mathbb{E}[X]$?
I drew some examples and got $1/(n-1)^n$, but I don't know what to do next. I think it needs linearity of expectations.
Answer: This sounds like a homework problem, so I will only give a hint, rather than a full solution.  Your problem is a slight variation on the coupon collector's problem, where the variation in your problem is that no two consecutive coupons (countries) can be the same.  A simple way to solve this problem would be to look at the expected time in the standard coupon collector's problem (where the same coupon can occur consecutively), and then subtract the expected number of times that the consecutive coupons will occur.  (Don't forget to also take account of the fact that you start in one of the countries, so you don't need to get a flight to that country.)


What is exactly the relation between vectors, matrices, and tensors?

Question: I am trying to understand what Tensors are (I have no physics or pure math background, and am starting with machine learning).
In an introduction to Tensors it is said that tensors are a generalization of scalars, vectors and matrices:
Scalars are 0-order tensors, vectors are 1-order tensors, and matrices are 2-order tensors. n-order tensors are simply an n-dimensional array of numbers.
However, this does not say anything about the algebraic or geometric properties of tensors, and it seems from reading around the internet that tensors are algebraically defined, rather than defined as an array of numbers.
Similarly, vectors are defined as elements of a set that satisfy the vector space axioms. I understand this definition of a vector space. And I understand that matrices are representations of linear transformations of vectors.
Question: I am trying to understand what a Tensor is more intuitively, and what the algebraic and intuitive/geometric relation is between tensors on the one hand, and vectors/matrices on the other. (taking into account that matrices are representations of linear transformations of vectors)
Comment: Read the Wikipedia entry https://en.wikipedia.org/wiki/Tensor
Comment: http://math.stackexchange.com/questions/657494/what-exactly-is-a-tensor
Comment: Obviously, I've read the wikipedia article and tried to understand it, but it didn't clarify it for me. I find wikipedia more useful for math topics I already largely understand.
Comment: @Hello, Ive read that post, but the explanations didn't clarify for me. they gave very abstract definitions, and I'm looking for something more intuitive.
Comment: As a programmer im sure you know about arrays and matrices. Put $n$ numbers one next to another, you obtain array. Put $m$ arrays one next to another you obtain matrix. Now put $k$ matrices of same type "one behind" another and you obtain third order tensor. It's like writing numbers inside cube (each number has row = "width", column="height" and "depth").. You can continue with this process to obtain $n$-th order tensor.
Comment: @MaliMish. I already stated that in my question.
Answer: I will try to do things as concretely as possible by working in $\mathbb{R}^n$.
As you've mentioned, matrices represent linear maps. Tensors represent multi-linear maps.
Let's start with vectors. There are broadly speaking two "kinds" of vectors. We have column vectors, which are just the usual things we call vectors, and we also have row vectors. You may not see the point of distinguishing the two, but it is actually important. To distinguish the two, I will call column vectors simply as vectors whereas row vectors will be termed covectors. To distinguish the two, I will use boldface notation like $\mathbf{v}$ for vectors, with an added tilde $\mathbf{\tilde{v}}$ for covectors. To distinguish the spaces that they live in, I will say that vectors are elements of $\mathbb{R}^n$ whereas covectors are elements of $\mathbb{R}^{n*}$.
Suppose that we have a vector $\mathbf{v}$ and a covector $\mathbf{\tilde{u}}$. Then we may multiply the two get
$$\mathbf{\tilde{u}}\mathbf{v} = \begin{pmatrix}u_1 & \cdots & u_n\end{pmatrix}\begin{pmatrix}v_1 \\ \vdots \\ v_n\end{pmatrix}=u_1v_1 + \cdots + u_nv_n.$$ Notice that the result is just a scalar number (in fact, it is a dot product). Thus, $\mathbf{\tilde{u}}$ is naturally an object that takes a vector and returns a number. The object $\mathbf{\tilde{u}}$ is a linear map that maps vectors to numbers, i.e., $\mathbf{\tilde{u}}:\mathbb{R}^n \rightarrow \mathbb{R}$.
We can go one step further. In the above product, $\mathbf{\tilde{u}}$ naturally acts on $\mathbf{v}$ from the left to give a number. But we can also turn this around to say that $\mathbf{v}$ acts on $\mathbf{\tilde{u}}$ from the right to give a number. Thus we can also regard $\mathbf{v}$ as a map that takes covectors to numbers, i.e., $\mathbf{v}:\mathbb{R}^{n*}\rightarrow \mathbb{R}$. This restores the symmetry between the two.
The take away message so far is that vectors are objects that take covectors to numbers whereas covectors are objects that take vectors to numbers.
Now, what do matrices do? A matrix $A$ can be viewed in three distinct ways:
i) It takes a vector $\mathbf{v}$ to the vector $A\mathbf{v}$, i.e., $A:\mathbb{R}^n \rightarrow \mathbb{R}^n$.
ii) It takes the covector $\mathbf{\tilde{u}}$ to the covector $\mathbf{\tilde{u}}A$, i.e., $A:\mathbb{R}^{n*} \rightarrow \mathbb{R}^{n*}$
iii) Most importantly for our purposes however, is the fact that it takes a vector $\mathbf{v}$ and a covector $\mathbf{\tilde{u}}$ and gives back a number $\mathbf{\tilde{u}}A\mathbf{v}$. Thus we can view matrices as objects that take both a vector and a covector and gives back a number, i.e., $A:\mathbb{R}^{n*}\times \mathbb{R}^n \rightarrow \mathbb{R}$.
Notice that the first two properties can be seen as consequences of the last. If we give the matrix a vector, then we are still missing a covector in order to get a number. Thus when a matrix gets a vector, it becomes an object that maps covectors to numbers. These are precisely vectors as we've previously shown. Likewise, if we give the matrix a covector, then we still need a vector to get a number. Thus a matrix maps covectors to things that map vectors to numbers, i.e., covectors.
What we've shown is that the three ways of looking at matrices are equivalent. Symbolically, we can write
$$A:\mathbb{R}^n \rightarrow \mathbb{R}^n \cong A:\mathbb{R}^{n*} \rightarrow \mathbb{R}^{n*} \cong A:\mathbb{R}^{n*}\times \mathbb{R}^n \rightarrow \mathbb{R}.\tag{1}$$
A simple way to remember these equivalences is to remember that we can move $\mathbb{R}^{n}$/$\mathbb{R}^{n*}$ from the left of the arrow to the right of the arrow along with adding/removing the $*$.
So far this seems like a lot of pointless linear algebraic gymnastics, but in fact we are almost there. Matrices take $\mathrm{(covector,vector)}$ pairs to numbers, but there is another very natural object that does the exact same thing, namely the $\mathrm{(vector,covector)}$ pairs. Given a $\mathrm{(vector,covector)}$ pair $(\mathbf{v},\mathbf{\tilde{u}})$, we can have it act on a $\mathrm{(covector,vector)}$ pair $(\mathbf{\tilde{x}},\mathbf{y})$ as follows:
$$(\mathbf{v},\mathbf{\tilde{u}})(\mathbf{\tilde{x}},\mathbf{y}) = (\mathbf{\tilde{x}}\mathbf{v})(\mathbf{\tilde{u}}\mathbf{y}).$$
Notice that we are simply using the fact that the vector $\mathbf{v}$ takes the covector $\mathbf{\tilde{x}}$ to the number $\mathbf{\tilde{x}}\mathbf{v}$ while the covector $\mathbf{\tilde{u}}$ takes the vector $\mathbf{y}$ to the number $\mathbf{\tilde{u}}\mathbf{y}$.
The similarity between $\mathrm{(vector,covector)}$ pairs and matrices is more than skin-deep. Every matrix map can be expressed as a linear combination of these $\mathrm{(vector,covector)}$ pairs. In fact, it is rather trivial to do. For example a matrix $A$ with entries $A_{ij}$ can be written as
$$A = \sum_{i,j=1}^nA_{ij}\mathbf{e}_i\mathbf{\tilde{e}}_{j},$$
so the map $A:\mathbb{R}^{n*}\times \mathbb{R}^n \rightarrow \mathbb{R}$ can be equivalently represented as
$$A\cong \sum_{i,j=1}^n A_{ij}(\mathbf{e}_{i},\mathbf{\tilde{e}}_j).$$
In the present context, we typically don't use brackets $(\ ,\ )$ to denote $\mathrm{(vector,covector)}$ pairs. Instead, we use these neat little circles $\otimes$ instead:
$$(\mathbf{v},\mathbf{\tilde{u}}) := \mathbf{v}\otimes \mathbf{\tilde{u}}.$$
The pairs of vector/covectors are the objects that we call tensors. They live inside the tensor space $\mathbb{R}^n \otimes \mathbb{R}^{n*}$. Specifically, these are $(1,1)$ tensors, tensors comprised of a vector and a covector. What we've also shown is that
$$\mathbb{R}^{n,n} \cong \mathbb{R}^n \otimes \mathbb{R}^{n*},$$
that is, the vector space of $n\times n$ matrices $\mathbb{R}^{n,n}$ is isomorphic to the $(1,1)$ tensor space $\mathbb{R}^n \otimes \mathbb{R}^{n*}$.
The generalization is now clear. We can consider objects comprised of $r$ vectors and $s$ covectors:
$$\mathbf{v}_1 \otimes \cdots \otimes \mathbf {v}_r \otimes \mathbf{\tilde{u}}_1 \otimes \cdots\otimes \mathbf{\tilde{u}}_s.\tag{2}$$
These are $(r,s)$ tensors, multi-linear maps that take $r$ covectors and $s$ vectors, returning a number. In explicit, gory detail:
$$\begin{eqnarray}(\mathbf{v}_1 \otimes \cdots \otimes \mathbf{v}_r \otimes \mathbf{\tilde{u}}_1 \otimes \cdots \otimes \mathbf{\tilde{u}}_s)(\mathbf{\tilde{x}}_1,\cdots,\mathbf{\tilde{x}}_r,\mathbf{y}_1,\cdots,\mathbf{y}_s)\\
=(\mathbf{\tilde{x}}_1\mathbf{v}_1)\cdots(\mathbf{\tilde{x}}_r\mathbf{v}_r)(\mathbf{\tilde{u}}_1\mathbf{y}_1)\cdots(\mathbf{\tilde{u}}_s\mathbf{y}_s)\end{eqnarray}.$$
That's it. Tensors are nothing more than multi-linear maps
$$\underbrace{\mathbb{R}^{n*} \times \cdots \times \mathbb{R}^{n*}}_{r\ \text{copies}} \times \underbrace{\mathbb{R}^n \times \cdots \times \mathbb{R}^n}_{s\ \text{copies}} \rightarrow \mathbb{R}. \tag{3}$$
You can convince yourself that any multi-linear map of this kind can be written as a linear combination of primitive tensors of the form given in $(2)$, i.e., we have the vector space isomorphism
$$\underbrace{\mathbb{R}^n \otimes \cdots \otimes \mathbb{R}^n}_{r\ \text{copies}} \otimes \underbrace{\mathbb{R}^{n*} \otimes \cdots \otimes \mathbb{R}^{n*}}_{s\ \text{copies}} \cong \{\text{multi-linear maps of the form }(3)\}.$$
Of course in practice, tensors are very versatile. Using the same kind of reasoning that gave us equality $(1)$, we can move $\mathbb{R}^n$/$\mathbb{R}^{n*}$ from the left of the arrow to the right. Thus we can have identities of the form
$$\begin{eqnarray} \underbrace{\mathbb{R}^{n*} \times \cdots \times \mathbb{R}^{n*}}_{r\ \text{copies}} \times \underbrace{\mathbb{R}^n \times \cdots \times \mathbb{R}^n}_{s\ \text{copies}} \rightarrow \mathbb{R} \\
\cong \underbrace{\mathbb{R}^{n*} \times \cdots \times \mathbb{R}^{n*}}_{r-k\ \text{copies}} \times \underbrace{\mathbb{R}^n \times \cdots \times \mathbb{R}^n}_{s-\ell\ \text{copies}} \rightarrow \underbrace{\mathbb{R}^n \times \cdots \times \mathbb{R}^n}_{k\ \text{copies}}\times \underbrace{\mathbb{R}^{n*} \times \cdots \times \mathbb{R}^{n*}}_{\ell\ \text{copies}}.\end{eqnarray}$$
Thus we can equivalently regard $(r,s)$ tensors as multi-linear maps that take $r-k$ covectors and $s-\ell$ vectors, in turn giving us $k$ vectors and $\ell$ covectors. This is similar to the corresponding properties that matrices/$(1,1)$-tensors had.
Hopefully you can see now that tensors are a very versatile concept which directly generalize the concept of linear mappings. I shouldn't have to convince you of the utility that such objects have. Ideally, I would close with a practical example, but this answer is already uncomfortably long, so I'll stop here.
Comment: When you say $$A = \sum_{i,j=1}^nA_{ij}\mathbf{e}_i\mathbf{\tilde{e}}_{j}$$ is $\mathbf{e}_i$ the vector with $1$ for the $i$th entry and $0$ for all others, and is $\mathbf{\tilde{e}}_{j}$ the covector with $1$ for the $j$th entry and $0$ for all others?
Comment: @ChaseRyanTaylor Yes, exactly.
Answer: <code>Scalars are 0-order tensors, vectors are 1-order tensors,
and matrices are 2-order tensors. n-order tensors are simply
an n-dimensional array of numbers.
</code>
This is almost correct.
But tensors are more than a bunch of numbers arranged into n-dimentional array. Tensors are something, that can be naturally represented as n-dimentional array.
Let's say you have some body moving with velocity $V$. It's natural to represent the velocity as 3 numbers $V_x, V_y, V_z$ (let's assume that everything happens in 3-dimentional space). But would these numbers be (3, 4 ,0) or (0, -5, 0) depends on your frame of reference. If you know the numbers in one frame of reference, you can find corresponding numbers in any other frame of reference using some simple rules same for all kinds of tensors. This is they key point.
One of definitions of tensors I encountered was "tensor is a multidimentional array of numbers which is modified when you change the frame of reference using the following rules:...". I do not like this definition. Velocity is not a bunch or numbers. Velocity is something that is very convenient to represent as a 1-dimentional matrix of numbers.
What is good in this definition is that it emphasize the importance of transformation rules. We call tensors only the things whose number's representation depends on frame of reference in a very specific way. For example there are "Christoffel Symbols". These symbols describe the metric of space. Some metric-related properties of space can be very naturally represented as 3-d matrix of numbers. The numbers depend on frame of reference, but when you move from one frame of reference to another these numbers are transformed in some "not-tensor" way. So Christoffel Symbols are not a tensor.
Answer: Vectors and Tensors are mathematical objects invariant under coordinate system chosen.
Matrices and Arrays for that matter are representations of rank-2 tensor or vectors in a given coordinate system.
As for the intuitive understanding part, take the analogy of a vector. By definition a vector is a magnitude and a direction. If I said  "5 miles an hour that a way" and point, that's a velocity vector. Until you put a coordinate system on it you can't write it down as an ordered pair. A tensor is the linear transformation that is invariant. Once you impose a coordinate system you can write it down as a matrix. That's why tensors are often used to describe material properties.


How to bind to the control's dependency property inside ControlTemplate

Question: I've extended PopupBaseEdit control by adding my own ControlTemplate and a new DependencyProperty PopupText to the extended control. The property PopupText is initialized from the control's consumer. No issues here. The question is; how do I bind TextBox.Text to my attached property inside ControlContent?
Here is the XAML:
<ControlTemplate x:Key="myPopuptemplate">
  <StackPanel>
    <TextBox Margin="5" Text="???????"/>
  </StackPanel>
</ControlTemplate>

Answer: Use a TemplateBinding.
Comment: when I am trying 'Text="{Binding Path={TemplateBinding PopupText}}"'  got _error MC3011: Cannot find the static member 'PopupTextProperty' on the type 'Control'_. However, such property exists
Comment: @user1153896: Have you even read the reference? TemplateBinding is **not** to be used in the path of a binding, it replaces a normal binding.
Comment: Text="{TemplateBinding PopupText}" - that gives the same compilation error. The attached property 'PopupText' is define
Comment: @user1153896: `TemplateBindings` are for normal DependencyProperties not attached properties, also: You neeed to set the `ControlTemplate.TargetType` to the type of your control, otherwise the compiler won't know which properties are there.
Comment:  - gives runtime error {"'myControl' ControlTemplate TargetType does not match templated type 'PopupContentControl'."}
Comment: @user1153896: You are setting the template as the `PopupContentTemplate` obviously the control it is going to be applied to is a `PopupContentControl`, that beind said, i kind of doubt that you will have access to the properties you mentioned...


How to autoupdate quiz question to newest version?

Question: We have round about 200 quizzes with 5-10 questions. And most of the questions were updated by us. But we realized that quiz shows only the old versions.
Only solution so far is to check quiz by quiz and click updated to newest version question by question.
In settings I didn't find any possibility to auto switch to newest version as soon as the question got updated.
Any ideas to solve this problem?
Of course, we can switch every question to newest version as soon as we update them. But what about all the aprox 1000/2000 questions in system that still run on old version instead of newest?
quiz.info: version = "7.x-5.0-alpha8+14-dev"
Comment: What version of quiz are you using?
Comment: quiz.info says `version = "7.x-5.0-alpha8+14-dev"`.
Comment: I think you may need to update and run update script and make sure manual revisioning turned off and it should work, there are many duplicates of this issues in the issue queue but on the current version with revisioning turned off it seems to be fixed.
Comment: But I've been wrong before :(
Comment: Thanks, that helped alot. Maybe you can post `manual revisioning turned off` as answer, so I can accept it as correct answer. Including the information about duplicates of this issue and maybe a link to drupal issue.
Comment: Awesome, glad I could help!
Answer: According to the issue queue its says that the update issues only happen when manual revisioning is enabled. You can find out more here: https://www.drupal.org/node/1652936
Also make sure to update to latest version and run update scripts.


Javascript: attempting to fill an array with a prompt but prompt is not displaying

Question: I am attempting to call a method that asks the user how many entries they would like to make into an array and then prompts the user for each entry. I know this is likely a simple error but I cannot tell why my prompt is not working.

Start Test score script

Comment: 1. you need a comma between `i++` and `whichScore++` - 2. you declare `scores`, then attempt to set `score`.
Comment: What do you see in the console?
Comment: Looks like you need to refresh your knowledge of how [`for`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for) works...
Comment: you also need to parseInt the response you get from prompt()
Comment: @Cruiser you don't in this case, but one should in general.
Comment: he's getting it as a string, so if the user enters 13, numberofScores will not iterate 13 times
Comment: @Cruiser You sure? https://jsfiddle.net/ye4z1ktz/
Comment: I stand corrected. i suppose the < operator casts the string as an int, if it can
Comment: @Cruiser It does indeed.
Answer: A loop is configured with 3 sections and thus two semi-colons. You had whichScore++ in a 4th section after adding a third semi-colon. You could have added it to the end of the configuration with a comma. But, adding it to the loop body, and not part of the loop declaration is cleaner. That said, the variable is not even needed. Just use (i + 1) and note that we're not modifying i here, we're just using an offset of it for display purposes only.
Also, in the loop: score[i], needs to be scores[i] and your  element should have an href="#" instead of an empty attribute.
Lastly, don't use inline HTML event handling attributes as they:

Make the code more difficult to read and lead to code duplication.
Cause global wrapper functions to be created around your supplied
attribute value that alter the binding of this in your function.
Don't follow the W3C DOM Event standard.

Use .addEventListener() in JavaScript instead:

// When the DOM content is ready
window.addEventListener("DOMContentLoaded", function(){

  // Get a reference to the hyperlink and create a click event handler for it:
  document.getElementById("makeScores").addEventListener("click", testScore);

  function testScore(){
    var numberofScores = prompt("enter the number of scores:","");
    var scores = new Array();

    for(var i = 0; i < numberofScores; i++){
      scores[i] = prompt("enter score " + (i + 1) + ":");
    }

    console.log(scores);
  }

});
Start Test score script
Comment: whichScore++ can still e a part of loop declaration. Infact you can eliminate it and use variable `i` only
Comment: Thank you! this has resolved my initial prompt issue however now I do not get a prompt for each score after as defined here  score[i] = prompt("enter score " + whichScore + ":");
Comment: @user3216792 See my code sample which does work and read my post. The code is not `score[i]`, it's `scores[i]`. Also, work with your developer tools open and the console showing (F12). This will show you what errors you have in your code and where.
Answer:

Start Test score script

your variable is scores
Use Array.push, since you did not declare the array length in array constructor. Edit : You can also use scores[i]. It will work as well.
Comment: `array.push()` is one way to add items to an array, but if you assign a value to an index that hasn't been used in the array yet, that index will be created.
Comment: Yes realized it later. Editing
Answer: Here is a JSFiddle using your code. You have a lot going on here
https://jsfiddle.net/tcoedqkf/
First off, your for loop needs to have a comma besides the increments (although for readability I would do it in the for loop)
for(var i=0; i<numberofScores; i++,whichScore++){

Your variable name in the for loop is incorrect (missing an S)
scores[i]=prompt("enter score "+whichScore+":");

Comment: No, It wasn't targeted to you. It was to the person who downvoted w/o commenting why he did so.
Comment: Looks like someone took self-promotion to mean demotion of others :P
Comment: I read that 10 times and I don't see what you mean. If you can point out what I wrote to demote someone then I would gladly edit it! I'm definitely not trying to put down anyone. Just trying to help out :)

In my defense, the question was to point out his errors of which I did well I think :P
Comment: ahhhh I follow!
Answer: for only have three sections (separated by a semicolon ;): initialization, the condition and the incrementation. If you want to initialize or increment more variables use a comma ,. Like this:
for(var i = 0; i < numberofScores; i++, whichScore++) {
    // ...

Since whichScore is basically just i + 1 you won't need to have two variables for that, just i will do:
for(var i = 0; i < numberofScores; i++) {
    score[i] = prompt("enter score " + (i + 1) + ":");
// ...

Note that the parenthesis in (i + 1) are necessary so the numbers are added instead of concatenated.


What is involved in upgrading from SSL 2.0 to SSL 3.0 in IIS 6?

Question: I am using a site security testing suite and it says SSL 2.0 has known vulnerabilities and I should change it to SSL 3.0.
Will my current certificates still work once I switch to SSL 3.0?
How do I make the switch? Is it only in IIS or could I need to change anything on my web application?
Thanks
Answer: Both SSL 2.0 and SSL 3.0 are enabled in IIS 6 by default. (IIS 7, too, for that matter--go figure!) The client and server negotiate to arrive at the version of the SSL protocol to use.
Your certificates will still work. Disabling SSL 2.0 will not invalidate your existing SSL certificates. This is a protocol-level thing handled by IIS and the OS network stack, so no changes to your web application will be required.
You can disable SSL 2.0 in IIS so it will no longer offer to use that version of the protocol during negotiation; the down side of this is that you will no longer be able to communicate with browsers that only support the SSL 2.0 protocol. (This is also the good thing, as you will no longer be open to vulnerabilities in the SSL 2.0 protocol!)
The SSL 3.0 protocol specification has been around since 1996, so the universe of potential browsers you will be locking out of your site by not supporting SSL 2.0 should be pretty small, unless, of course, your site caters to users of ancient web browsers...
Additional information, including instructions on editing the registry to disable SSL 2.0, can be found in Microsoft Support Article ID 187498.
If you're really curious about what goes on during that whole "protocol negotiation" thing, additional information and references can be found in Microsoft Support Article ID 299520.
Comment: I'm having the same issue, I made the registry change and still failed the PCI compliance scan. Is there a way to test this before I resubmit to another scan?


Trazer valor de outra célula para a fórmula sem ser String

Question: A fórmula no excel PROCV procura verticalmente um valor em uma tabela específica de uma coluna X.
Visto isso, tenho o seguinte problema com esta fórmula:
=PROCV(J7;JUL;6;JUL!C4:C35)

Com isso eu quero que essa fórmula seja dinâmica, onde através da função =hoje() o campo onde a fórmula =PROCV(J7;JUL;6;JUL!C4:C35) está, seja alimentado com o mês correto, mas ao fazer isso, buscando o valor de uma outra célula, é atribuído String, fazendo com que a fórmula encontre um erro, pois não é permitido string na fórmula (nessa parte no caso) pois seria o intervalo onde os dados que eu preciso, estão.
Exemplo:

Ao inserir a fórmula conforme a imagem, os dados recebidos ficam assim:
=PROCV(43651;$T$7;6;"JUL!C4:C35")

No campo T7 tenho uma condição onde eu faço a verificação, se o mês atual for 1, então a saída é "JAN", se for 2, então a saída é "FEV" e assim sucessivamente até "DEZ".
No campo T8 eu concateno o resultado da célula T7 com o intervalo que eu preciso que é !C4:35.
O resultado traz dois erros...

1º - Onde deveria ser a matriz da tabela está recebendo $T$7.
Deveria receber a tabela em questão, no caso JUL (que é o mês atual)
2º - Onde deveria receber o intervalo dos dados está vindo como string.
Deveria receber sem as aspas, pra fórmula não encontrar o erro.
Tendo como resultado final da fórmula assim:
=PROCV(43651;JUL;6;JUL!C4:C35)

E está saindo assim:
=PROCV(43651;$T$7;6;"JUL!C4:C35")

Como resolver isso ?
Comment: Não entendi muito bem, poderia editar com um exemplo do que você realmente deseja e alguns dados fictícios?
Comment: Acho que ficou mais claro agora!
Answer: Marcos, boa tarde!
Acho que a fórmula está com as variáveis invertidas no seu exemplo.
Entendo que a forma correta seria:
=PROCV($T$7;INDIRETO(T8);6;0)

Faça um teste, talvez seja necessário usar o INDIRETO no $T$7 também.
Abs!
Comment: Perfeito Paulo é isso mesmo, funcionou exatamente como eu queria!!
E a fórmula está correta, pois o primeiro parâmetro é onde eu pesquiso a data do dia, por isso é necessário colocar o campo J7. A fórmula ficou assim: =PROCV(J7;INDIRETO(T7);6;INDIRETO(T8)), trouxe exatamente como eu queria, obrigado!!


Double counting data in a Bayesian Model? Output is a derived random variable being the product of other observed random variables

Question: I've found a few studies that seem to touch on the possibility of double counting, but have yet to find any examples that fit this exact trope.
That said, is loading observed values in multiple distributions (sites) within a hierarchical Bayesian model allowable (insofar as no significance or signal strengthening is conjured from thin air, i.e. double counting), when the primary "observations" for the estimation of the posterior mean (here =mu[i]) are not derived explicitly from nature etc., but as the arithmetic equation involving the values of other random variables, whose values have actually been observed and whose probability distributions define a lower, or prior tier of distributions within the Bayesian model? (see example shown, however it could be most anything)
Given a toy example, if:
Y[i] ~ Norm(mu[i], tau)
mu[i] = v[i] * w[i] * z[i]
and the priors (variables) are normally distributed and have hyperpriors:
v[i]~ Norm [mu_v, sd];  Normal, Gamma
w[i] ~Norm [mu_w, sd]; Normal, Gamma
z[I] ~ Norm [mu_z, sd];  Normal, Gamma
Observations in nature have been made for random variable v[i], w[i] and z[i], for example
v[n=5]=   {1,2,3,4,5}   w[n=5]=   {1,2,3,4,5}     z[n=5]=   {1,2,3,4,5}
Ergo, giving the aforementioned equation for u[i] (such types of equations are quite common in the life sciences, growth rate, population stuff etc.), the "observations" of the "derived random variable" given the values of v[5], w[5] and z[5] (above) and the following equation
If:        mu[i] = v[i] w[i] * z[i]
Then:     the corresponding values of Y which (n=5) sample the mean are
              determined expressly as {1, 8, 27, 64, 125}
That being the case, what is the nature of the following scenarios:
1)   Is it "legal", not double counting etc., to load data for both the observed and "derived random variable"?  If so or if not, in terms of broad strokes theory how could you conclude that answer?
2)  Is loading data is more "truthful" in one arrangement?
3)  Is there some broader theoretical trope that I'm plainly missing that would even cause me to raise this question?
4)  Thnx for the feedback!
Comment: Welcome to CV! Just a small remark: Using simpler English may attract more answers. You first sentence is very difficult to read due to its length and the choice of words.
Comment: Using LaTeX would make the question more readable as well.
Comment: Hi Frans. Apologies I will certainly keep that in mind!  Additionally, there is a key period missing between the first and second sentences (between "trope" (.) and "Is").  Probably good to make sure one's first sentence is grammatically correct before the post goes live next time : ^ } Is there any way to do post-submission edits on a post as to clean it up if an error is noticed?
Comment: There is an edit link just under the question on the left (share, cite, edit, flag)
Answer: This is not double-counting. If you observe the values of $v_i$, $w_i$, and $z_i$, then (a) they are not strictly speaking prior quantities and (b) you should use them to make inference on the parameters $\mu_v$, &tc., while you can use the sample of the $y_i$'s to make inference on $\tau$.
Comment: Hi again, sorry for responding again out of the blue, however I just wanted to let you know I finally came across a paper that exactly articulates the question I posed some days ago and provided a concrete solution, within my general field no less!  It does seem to evoke a rather esoteric application of Bayesian infrence, but that is coming from my rather modest introduction to the larger field of statistics  Anyway I though you may appreciate it, I shall let it speak for itself: [link](https://www.stat.washington.edu/raftery/Research/PDF/rgz1995.pdf)


How to access a sql database from a widget application

Question: Because of some comments, the question in a nutshell:
How can a widget access its own sqlite database?
Why does it not work with a plain DatabaseAdapter class?
Are certain permissions required?
Are there limitations imposed upon a Remotevie/AppWidgetProvider to access its own database (without a ContentProvider)

The question seems simple, but details follow, if someone really wants to know why I am asking:
I have the following setup:

I have a normal android application, which comes with quite a lot of HTML pages in the assets folder. Because of the size of the app, the prefered install location is the external sd card. This works fine.
That means that the app cannot contain a widget, because he widget needs to reside in the internal ROM.
Instead, the widget will read from the app's database on the external sd card. This is achieved through a ContentProvider/ContentProviderClient.

So far that works fine.
Now, that widget needs to maintain some persistent configuration settings, on a per instance basis. Therefore, the AppWidgetProvider class cannot use the preferences, because they would apply on a per class basis.
So, to keep the (quite complex) instance-sepcific configuration data, I want the AppWidgetProvider class to have its own small sqllite database.
Now, while I can access the app's database from the widget via the contentprovider, it seems that the widget cannot access its own database. I have a database adapter class in the widget project; inside the AppWidgetProvider, I have the Context, but no writing seems to happen.
The calls to the database adapter get through OK (I've done some logging), but when I examine the tables, no writing has occurred.
Why is that? Do I really need a ContentProvider inside the widget to access the widget's database? I do not want to go down that road, because when I implemnented the access to the apps database from the widget, I had to go through the ContentProviderClient instead of the ContentProvider. That would be very cumbersome. As I need a bit more than CRUD acccess, that obviously would involve creating a custom ContentProviderClient. The android docs clearly state that "You don't need a provider to use an SQLite database if the use is entirely within your own application." So IMHO, that would mean, that the widget can access its on database directly? Do I need special permissions? I suspect that, because the widgets run as RemoteViews in the homescreen process, access to the db is somehow limited?
Any thoughts, ideas, hints on this?
Comment: You really expect people to read that mass of unformatted text, full of typos, and take time to answer you?
Comment: @Ollie_C, The question is not full of typos: English is a foreign language for its author. I suggest you follow a long tradition of the English language and treat people who are learning it in adulthood with sympathy.
Comment: do something to your question, no one is going to read it
Answer: i suggest to use a service if nothing else seem to work for you . it's a common thing to have a service for the app widget.
Comment: I actually misunderstand the nitty-gritty details of the ContentProvider (Not surprisingly, the docs are somewhat unclear). The solution is: have different URLs and inside the query method, I switch different database queries depending on the URI. That way, the 4 CRUD methods will always be sufficient for any sort of queries. I use a MatrixCursor to wrap the query results, so that I can always return the a cursor object, no matter what my actual query returns.


A pointwise Hadamard-Landau-Kolmogorov inequality for $C^2$ functions

Question: A well-known interpolation inequality proved by Hadamard (1914) and was generalized by Landau (1913) and Kolmogorov
(1939) asserts that
$$
|f'(x)|^2 \leq 2 \sup_{x \in \mathbf R} |f(x)|\sup_{x \in \mathbf R} |f''(x)|
$$
for any $x$ and for any function $f \in C^2(\mathbf R)$. Let us assume additionally
$$|f''(x)| \leq 1 \quad\text{for any } x.$$
Then the inequality becomes
$$
|f'(x)|^2 \leq 2 \sup_{x \in \mathbf R} |f(x)| \quad\text{for any } x.
$$
My question is: can we have
$$
|f'(x)|^2 \leq 2 |f(x)| \quad\text{for any } x.
$$
This could be too strong, so a weaker version is also meaningful, namely there is some $C>0$ such that
$$
|f'(x)|^2 \leq C |f(x)|
$$
for all $x \in \mathbf R$.
Answer: No, such a pointwise inequality may not hold, even with an arbitrary constant $C$. A simple counterexample is $f(x) = \sin(x)$ with
$$
 f'(k \pi) = \pm1 \ne 0 = f(k \pi)
$$
for all integers $k$.

If $f$ is nonnegative then $|f''(x)| \le 1$ for all $x \in \Bbb R$ does imply a pointwise inequality
$$
 f'(x)^2 \leq 2 f(x) \text{ for all } x \in \Bbb R \, .
$$
Proof: We start with Taylor's formula:
$$
 0 \le f(x-h) = f(x) - f'(x) h + \frac 12 f''(\xi) h^2
\le f(x) - f'(x)h + \frac 12 h^2 \, .
$$
It follows that
$$
 f'(x) \le \frac{f(x)}{h} + \frac h2
$$
and setting $h = \sqrt{2f(x)}$ gives
$$
 f'(x) \le \sqrt{2f(x)} \, .
$$
Similarly one shows $f'(x) \ge -\sqrt{2f(x)}$ by applying Taylor's formula to $f(x+h)$. This proves
$$
  -\sqrt{2f(x)} \le f'(x) \le \sqrt{2f(x)}
$$
for all $x$, i.e. $f'(x)^2 \le 2 f(x)$.
Comment: @QANgô: That can even be simplified: $0 \le f(x+h)=f(x)-f'(x)h +\frac{f''(\xi)}2h^2$ suffices to conclude that $f'(x) \le 2 \sqrt{f(x)}$. But you still need $\sqrt{f(x)} \le C f(x)$.
Comment: @QANgô That is correct but the factor can be improved, see the updated answer. It is a simplified version of your ideas.
Comment: It seems that if $f >0$, then the pointwise inequality is true. Here is an argument. By Taylor's expansion, there are numbers $\xi_+$ and $\xi_-$ such that
$$f(x+h)=f(x)+f'(x)h +\frac{f''(\xi_+)}2h^2$$
and
$$f(x-2h)=f(x)-2f'(x)h +2f''(\xi_-)h^2$$
for $h>0$. Adding these two identities gives
$$0 \leq f(x+h)+f(x-2h) = 2f(x) - f'(x)h + h^2 \Big(\frac{f''(\xi_+)}2+2f''(\xi_-)\Big) \leq 2f(x) - hf'(x) +\frac 52 h^2.$$
Hence
$$hf'(x) \leq 2f(x) + \frac 52 h^2.$$
Now we choose $h=\sqrt{f(x)}$ to get
$$f'(x) \leq \frac 92 \sqrt{f(x)}.$$
What do you think?
Comment: Thanks. For the reverse inequality, we argue similarly. Indeed, we have
$$f(x+2h)=f(x)+2f′(x)h+2f''(\xi_+)h^2$$
and
$$f(x−h)=f(x)-f′(x)h+\frac{f''(\xi_−)}2 h^2$$
for $h>0$ . Adding these two identities gives
$$0 \leq f(x+2h)+f(x-h) = 2f(x) + f'(x)h + h^2 \Big(\frac{f''(\xi_-)}2+2f''(\xi_+)\Big) \leq 2f(x) + hf'(x) +\frac 52 h^2.$$
Choosing $h=\sqrt{f(x)}$ gives
$$f'(x) \geq -\frac 92 \sqrt{f(x)}.$$
Answer: Thanks, Martin R. The final remark (too long for a comment) is as follows:

the factor $2$ is optimal in the sense that it cannot be replaced by any smaller positive constant and
the factor $2$ is never achieved.

For the former conclusion, the optimality can be proved by constructing suitable functions, namely given any $C \in (0, 2)$, there is some positive $C^2$ function $f$ such that $$f'(x)^2 > C f(x).$$ Indeed, let
$$f(x)=c+\left\{\begin{aligned}
& 0 & & \text{if } x \leq -2,\\
& \frac {(x+2)^2}2  & & \text{if } -2 < x \leq -1,\\
& x+\frac 32 & & \text{if } -1<x \leq 1,\\
& \frac {x^2}2  + 2 & & \text{if } 1<x \leq 2,\\
& 2x & & \text{if } x > 2,\\
\end{aligned}\right.$$
for some $c>0$ to be determined later. (This function is not of class $C^2(\mathbf R)$, but twice differentiable except at $\pm 1, \pm 2$, so it serves our proof.) Then, we get
$$f'(x)=\left\{\begin{aligned}
& 0 & & \text{if } x \leq -2,\\
& x+2  & & \text{if } -2 < x \leq -1,\\
& 1 & & \text{if } -1<x \leq 1,\\
& x & & \text{if } 1<x \leq 2,\\
& 2  & & \text{if } x > 2,\\
\end{aligned}\right.$$
Hence at $-1$ we should have
$$f'(-1)^2 - C f(-1) = 1 - C(c+\frac 12) > 0$$
provided $c \in (0, 1/C-1/2)$.
For the later conclusion, I believe that there is no positive function $f$ such that $f'(x) = 2 f(x)$ occurs at some point $x$.
Comment: Here https://math.stackexchange.com/a/3623256/42969 I reproduced Landau's example of a $C^2$ function that the factor $2$ is best possible.


How to Set Auth Module in Bokeh Server

Question: I'm running a Bokeh app as shown in standalone_embed.py and want to use an authentication hook with it, as shown here. How do I set the auth_module in bokeh.settings.settings in standalone_embed.py?
I tried
from bokeh.settings import settings

settings.auth_module = "auth.py"
settings.xsrf_cookies = True

but that doesn't seem to do anything. Any help appreciated, thanks!
Answer: Found the answer:
Server can take the authentication module as param as follows:
auth_module_path = <path to auth.py>
if auth_module_path:
    server_kwargs['auth_provider'] = AuthModule(auth_module_path)

server = Server(
    bokeh_applications,  # list of Bokeh applications
    io_loop=loop,        # Tornado IOLoop
    **server_kwargs      # port, num_procs, etc.
)

How to Set Auth Module in Bokeh Server


How to eliminate high multicollinearity with a continuous moderating variable, and a categorical independent variable

Question: I am looking at whether Corporate Venture Capital-backed firms (1) perform better than Independent Venture capital - backed firms(0) in their POST-IPO performance. My assumption is that this relationship is either strengthened or weakened by the amount of Experience (continuous).
After creating a new variable for Corporate VC*Experience, I then put these values in a regression and it gives me a VIF of over 23.
Comment: Try centering the continuous variable, that often helps.
Answer: To elaborate on Peter Flom's point:
People often centre moderator variables (i.e., subtract the mean from the variable) before forming the interaction term in order to reduce multicollinearity between the component moderator variables and the interaction term.
The step of centring will not change the r-square change you get in a hierarchical regression when including the interaction term in a discrete step, but it may make interpretation of the coefficients clearer.
Comment: So I can centre the moderator without having to do the same for the independent variable (dummy)?
Comment: You could centre the binary variable as well if you want. That should further reduce the multicollinearity. People often don't because binary variables coded zero one are easy to interpret.