Permanova outputs with or without random factor

Question: My question is similar to this previous post but remained unanswered. I am having trouble understanding the output of an adonis models with and without the argument "strata" in the formula.
I want to compare microbial communities associated with healthy and diseased reef algae.
Healthy and diseased algae have been collected in different islands. I am more interested in the difference between the Healthy and Diseased group, I am not really interested in comparing the islands but still would like to take the islands into account. From what I read it looks like a way to do it is to include Island as a random factor in my model.
Variable: Bray-Curtis dissimilarity matrix (dist)
Fixed factor: Disease (Dis)
Random factor: Island
adonis1<- adonis(dist ~ Dis, strata = Island, data = meta)
adonis2<- adonis(dist ~ Dis, data = meta)
However, I get the exact same output for both models:
]1
Could someone please explain to me why outputs are identical?
Thanks a lot.

Thanks for your response.
In order to provide you with a reproducible example, I was preparing a subset of my data and ran the two models again and got the same results as your example with the dune  data set. That is: exactly the same output besides a different p-value.
Do you think you could explain what is it that adonis makes differently when running with or without strata? I am sorry if that sounds trivial but I don't really understand why R2, SumsOfSqs and MeanSqs are exactly identical with or without the strata argument. I'd like to understand better what's behind it.
Answer: I am afraid I cannot reproduce your similar results.. see below for a reproducible example, maybe you can provide the example dataset so that we can explore it further:
library(vegan)
data(dune)
data(dune.env)

table(dune.env$Management)

BF HF NM SF
 3  5  6  6

set.seed(111)
adonis(dune ~ A1, data = dune.env,strata=dune.env$Management)

Blocks:  strata
Permutation: free
Number of permutations: 999

Terms added sequentially (first to last)

          Df SumsOfSqs MeanSqs F.Model      R2 Pr(>F)
A1         1    0.7230 0.72295  3.6389 0.16817  0.031 *
Residuals 18    3.5761 0.19867         0.83183
Total     19    4.2990                 1.00000

adonis(dune ~ A1, data = dune.env)

Permutation: free
Number of permutations: 999

Terms added sequentially (first to last)

          Df SumsOfSqs MeanSqs F.Model      R2 Pr(>F)
A1         1    0.7230 0.72295  3.6389 0.16817  0.007 **
Residuals 18    3.5761 0.19867         0.83183
Total     19    4.2990                 1.00000

R2, SumsOfSqs and MeanSqs are calculated based on your observed data, and it depends on your model, so for both codes (with or without strata) this is unchanged.
To understand why the p-values might be different, adonis "uses a permutation test with pseudo-F ratios." (see vignette). This would entail permutating the rows of the dissimilarity matrix (or whatever is on the LHS), and re performing the test under the condition where association between the response variable (distance in this case) and your variable of interest is lost. It collects this permutated F values and calculates how many of these are larger than your actual F value (in my dune example it is 3.6389), giving you a p-value. Maybe check out this for more explanation
If there is a structure to your data, you might want to restrict the way this permutation goes, for example in your case, you want to preserve the effect of island, and randomize the disease effect, then you specify the strata to be island. In my example, I specify it to be Management.
In your situation, you might want to check whether there is any difference in the dissimilarity matrix between island. If not, then most likely the strata is unlikely to have an effect.


How to normally bind forms in angular

Question: I have a template form, which I wrote from guides and they don't really work though.
I have several of models:
export class User {
  constructor(public userId?: UserId,
              public firstName?: String,
              public lastName?: String,
              public address?: Address) {
  }
}

export class Address {
  constructor(
    public street?: String,
    public city?: String,
    public zipCode?: String) {
  }
}

I have component:
Component({
  templateUrl: 'user.html'
})
export class MyComponent implements OnInit, OnDestroy{
  user: User;
  userForm: NgForm;
  ngOnInit(): void {
  }

And page itself:
<form novalidate #userForm="ngForm">

        <input required minlength="4" type="text"
               id="firstName"
               [(ngModel)]="user.firstName" name="firstName">
        Not valid!

        <input required ng-minlength="4" type="text"
               id="lastName"
               [(ngModel)]="user.lastName" name="lastName">

            <input required ng-minlength="4"
                   type="text"
                   id="address-house"
                   [(ngModel)]="user.address.address1" name="address.address1">

                <input required ng-minlength="4"
                       type="text"
                       id="zipCode"
                       [(ngModel)]="user.address.zipCode" name="address.zipCode">

                <input required ng-minlength="4"
                       type="text"
                       lass="form-control input-lg"
                       id="city"
                       [(ngModel)]="user.address.city" name="address.city">

    <button type="button" (click)="checkAndProceed()">Continue</button>

</form>

The only thing I want to do is to add validation - that's all. None of the guides helped. Can we do in-html validation or ts validation? It would be nice to call validation when clicking 'Continue' button and making it valid if it is so.
In this case of validation I additionally get console error:
Cannot read property 'valid' of undefined
Answer: There are lots of attributes on input elements. We have name, Id, and template reference variable. Your code is missing the template reference variable. It is the template reference variable that holds onto the reference to the element and has the valid, dirty, and other flags associated with it.
For example, change your code to include a template reference variable like this:

    <input required minlength="4" type="text"
           id="firstName"
           [(ngModel)]="user.firstName" name="firstName"
           #firstNameVar="ngModel">
    Not valid!

Notice the #firstNameVar. That is the template reference variable. It can be named the same thing as your Id and name attributes. I just named it something different so it could be readily distinguished between the other two attributes.
Notice also that the *ngIf is then changed to use firstNameVar.valid
For more information on template reference variables, see this: https://angular.io/guide/template-syntax#ref-vars

How to normally bind forms in angular


How to prove this inequality 4

Question: Let $x_1,x_2,...,x_n$ be positive real numbers ; $n\geq 2$, such that $\displaystyle\sum_{i=1}^n x_i=1$.
How to prove that $\displaystyle\sum_{i=1}^n \sqrt{\dfrac{1-x_i}{x_i}}\geq (n-1)\displaystyle\sum_{i=1}^n \sqrt{\dfrac{x_i}{1-x_i}}$ ?
Thank in advances.
Comment: Have you try something? You can try to change xi step by step to make it look like your expression and look what happen to 1.
Comment: Keep in mind that $1-x_i=\sum_{i\neq j} x_j$
Comment: Let $\frac{1-x_i}{x_i}=a_i$, so that $\sum\frac{1}{1+a_i}=1$ and we need $\sum \sqrt{a_i}\ge (n-1)\sum\sqrt{\frac{1}{a_i}}$. This is then an old inequality, see for example page three here: http://vjimc.osu.cz/hist/j12solutions.pdf
Answer: Suppose that $$x_1 \ge x_2 \ge \cdots \ge x_{n - 1} \ge x_1 \ge 0$$
$$\iff [\cdots] \iff \frac{1}{\sqrt{x_1(1 - x_1)}} \le \frac{1}{\sqrt{x_2(1 - x_2)}} \le \cdots \le \frac{1}{\sqrt{x_{n - 1}(1 - x_{n - 1})}} \le \frac{1}{\sqrt{x_n(1 - x_n)}}$$
Using the Chebyshev inequality, we have that
$$\left(\sum^n_{i = 1}x_i\right)\left[\sum_{cyc}\frac{1}{\sqrt{x_i(1 - x_i)}}\right] \ge n\left[\sum^n_{i = 1}x_1 \cdot \frac{1}{\sqrt{x_i(1 - x_i)}}\right]$$
$$\sum^n_{i = 1}\sqrt{\frac{1 - x_i}{x_i}} + \sum^n_{i = 1}\sqrt{\frac{x_i}{1 - x_i}} \ge n\sum^n_{i = 1}\sqrt{\frac{x_i}{1 - x_i}} \iff \sum^n_{i = 1}\sqrt{\frac{1 - x_i}{x_i}} \ge (n - 1)\left(\sum^n_{i = 1}\sqrt{\frac{a_i}{1 - a_i}}\right)$$

How to prove this inequality 4


getting no result in terminal window

Question: I have just started coding in C++ and I am using codeblocks. My build log is giving me 0 errors and 0 warning but I do not know why when I run it, it is giving me no result in the terminal.
Terminal Window Result:

Process returned -1073741571 (0xC00000FD)   execution time : 1.252 s
Press any key to continue.

my code:
    #include <iostream>
    #include<math.h>
    using namespace std;
    int main() {
    int n;
    cin>>n;

    int a[n];
    for(int i = 0; i <n ; i++){
        cin>>a[i];
    }
    const int N = pow(10, 6);
    int idx[N];
    for(int i = 0; i< N; i++){
        idx[i] = -1;
    }

    int minidx = INT_MAX;

    for(int i = 0; i<n; i++){
        if(idx[a[i]] != -1){
            minidx = min(minidx, idx[a[i]]);
        }
        else{
            idx[a[i]] = i;
        }
    }
    if (minidx == INT_MAX){
        cout<<"-1"<<endl;
    }
    else{
        cout<<minidx+1<<endl;
    }
    return 0;
}

Please help me in finding my mistake in the code.
Comment: 1) "_My build log is giving me 0 errors and 0 warning_" That is very low bar at judging code quality. 2) If I remember correctly `0xC00000FD` means "Stack Overflow". 3) `int a[n];` where `n` is not known at compile time is non-standard C++. Which, on compilers that support VLAs, due to an extension, might cause stack overflow for sufficiently large values of `n`.
Comment: Use `std::vector` instead of those non-standard variable-length arrays (whose size is most likely the source of your problems).
Comment: When using C++, stick to C++ provided headers. Use `` over ``. Also, indentation helps.
Comment: I believe the problem is the declaration of an array of size `1e6` in main(). Either make it global or use a standard container. VLAs are an extension provided by compilers. Don't use them.
Comment: Can confirm that irrespective of the size you enter at runtime of array `a` as size `n`, the crash will definitely be caused by the other array `idx [N]` where `N=1e6`. You can't declare an array that size in a function simply because of stack overflow.
Comment: afaik `cin>>n; int a[n];` never was the intended use case for VLAs, also in C (where VLAs are coming from) there are other solutions to this.
Comment: For gcc you need to use the `-pedantic` flag to get warnings for non-standard extensions: https://godbolt.org/z/a6vdao add `-Werror` to make it impossible to miss important warnings: https://godbolt.org/z/qnP7jM (warnings are always important!)
Answer: This:
int n;
std::cin >> n;

int a [n];

for (int i = 0; i < n ; i++) {
    std::cin >> a [i];
}

is bad practice. Don't use VLAs whose size you don't know at compile time. Instead, if I guess correctly that this is some Competitive Programming problem, you'll probably know what the max size will be as stated in the problem. So, do it this way instead:
int n;
std::cin >> n;

constexpr int max_size = 1000000;
int a [max_size];

for (int i = 0; i < n; i++) {
    std::cin >> a [i];
}

However, even doing it this way will crash your program anyway. This is simply because of stack overflow when you declare an array that size inside a function. For slightly smaller sizes however, that would be okay. Just don't use VLAs the way you're using them.
One solution is to use a standard container like std::vector as the allocation takes place on the heap. Note that using std::array will crash too as the allocation is not on the heap.
Another solution is to make your array a global. This way you can increase to sizes well over 1e6. Not really recommended though.
In your code above, irrespective of what the size n for array a is (even if it's a fairly small size to fit on the stack), your code will definitely crash when you declare the array idx [1000000]. Reason is the same, stack overflow.
Also, please post indented code and use good indentation practices.
Comment: "Don't use VLAs whose size you don't know at compile time" its a matter or wording, but you never know the size of a VLA at compile time, thats what makes it a VLA
Comment: @idclev463035818 Right, I messed up my wording a little bit. Anyways, my point was that you can't declare huge arrays inside a function as it would crash no matter what you did.
Comment: i didnt comment on your point, only on that sentence on VLAs which doesn't make sense
Comment: @idclev463035818 Off topic but I must say, you've got a nice `About Me` section.

getting no result in terminal window


Checkbox-Field Tree Menu

Question: When creating content, I'd like to have something akin to a drop down menu.  You could hover over an item and a list of checkboxes would appear.  Essentially it'd be a Select List with sub-items.  Is there any easy way to do this?
Answer: You can try Hierarchical Select module. Project page says

This module defines the "hierarchical_select" form element, which is a
  greatly enhanced way for letting the user select items in a hierarchy.

It will give you a way to select hierarchical items using select boxes.

Checkbox-Field Tree Menu


Teradata SQL - Very Large Pulls

Question: So I have a query that's returning more rows than MS Excel can handle (2 million), does anyone have any advice on getting Teradata to export to multiple Excel tabs, or maybe a way to break big query results up so that I can run the query to only pull more manageable chunks each time?
I know there are commands like TOP and SAMPLE which will only return a given portion of a pull, but I'm unclear on what the logic would be to rank a query and then return, say the TOP 100000, and then to run the same/similar query a second time but this time to have it return records 100001 - 200000, and then the time after that it returns 200001 - 300000, and so on.
Any tips would be greatly appreciated!  I know I can export to a text CSV but it would definitely be easier if I can figure out a way for Teradata to play nice with Excel. Thanks!
Answer: You can use ROW_NUMBER() to assign an "ID" value to each row in your result set and then get the results in whatever chunks you want.  Something like:
SELECT col1, col2, ...
FROM MyTable
QUALIFY ROW_NUMBER() OVER(
    ORDER BY Unique_Col
) BETWEEN <Start_Number> AND <End_Number>

Just make sure to use a Unique column or columns in the ORDER BY so that tbe ROW_NUMBER function applies the same ordering each time you run the query.
This doesn't take into account if there are changes to rows in your result set (i.e. added/deleted rows) in between query runs.  If that's a concern, copy the rows first to a temp table and then run your queries against the temp table.
Comment: Thank you so much, that is exactly what I was looking for!  Appreciate it very much.   :)
Comment: No prob bob :) .

Teradata SQL - Very Large Pulls


What's wrong with my creation of Google PULL queue?

Question: I'm a newbie in Google App Engine, so would you be so kind to clarify something for me?
I'm creating a new PULL queue, this is my queue.xml
<queue-entries>
    <queue>
        <name>app-metered-queue</name>
        <mode>pull</mode>
    </queue>
</queue-entries>

In my service, I instantiate a Queue instance with the following line of code
private final Queue appMeteredQueue = QueueFactory.getQueue("app-metered-queue");

After I'm adding some data in it:
final List<TaskOptions> taskOptions = new ArrayList<>();
for (final Map.Entry<Long, Map<String, Map<String, Long>>> entry : bundledData.entrySet()) {
       taskOptions.add(TaskOptions.Builder
               .withPayload(mapper.writeValueAsString(entry.getValue()))
               .tag(String.valueOf(entry.getKey()))
       );
   }
appMeteredQueue.add(taskOptions);

but, unfortunately, an exception is thrown in .add() method:
java.lang.IllegalArgumentException: Only PULL tasks can have a tag.
    at com.google.appengine.api.taskqueue.QueueImpl.fillAddRequest(QueueImpl.java:335)

Could you please specify, what I'm doing wrong?
Answer: queue.xml isn't enough.
You should add .withMethod(TaskOptions.Method.PULL) to TaskOptions.Builder on a stage when you assemble TaskOptions.


Putting the  data into the table with only one header

Question: I made the changes and now they are in the same table but not under the correct column and the address is not completely rendering.  It appears to only be taking the first word which is numbers and leaving off the rest.
enter image description hereIt
    $header = false;

    $result = mysqli_query($db, "CALL Webc") or die("Query fail: " . mysqli_error());

  while ($row = mysqli_fetch_assoc($result)){
    if ($header == false ) {
      echo "

            Customer ID
            Active
            TDate
            Student Type
            First Name
            Last Name
            Address
            City
            State
            Zip
            UserName
            Email
            Password	";

        $header = true;
  }
  echo "<form action=update_students.php method=post>";

   echo "
" . "<input type=text name=CustomerID value=" .$row["CustomerID"].   "
";
   echo "
" . "<input type=text name=active  value=" .$row["active"].   "
";
   echo "
" . "<input type=text name=TDate  value=" .$row["TDate"].   "
";
   echo "
" . "<input type=text name=StudentType value=" .$row["StudentType"].  "
";
   echo "
" . "<input type=text name=FirstName  value=" .$row["FirstName"].  "
";
   echo "
" . "<input type=text name=LastName  value=" .$row["LastName"].  "
";
   echo "
" . "<input type=text name=Address  value=" .$row["Address"].  "
";
   echo "
" . "<input type=text name=City  value=" .$row["City"].  "
";
   echo "
" . "<input type=text name=State value=" .$row["State"].  "
";
   echo "
" . "<input type=text name=Zip  value=" .$row["Zip"].  "
";
   echo "
" . "<input type=text name=Email value=" .$row["Email"].  "
";

       echo "".  "<input type=submit name=update value=update>".   "	";
    echo "".  "<input type=submit name=delete value=delete>".   "	";

        echo '
';
     echo "</form>";
  }

Comment: Add the language tag too (php?). That's not valid HTML as the tags should be closed, the th and td should be in tr tags, and the table should be inside of of the form https://www.w3schools.com/html/html_tables.asp
Comment: Need them in one table with correct data in the correct column under the correct Header Name is what I meant.
Answer: Here  in output you missed  in
here is an expample from you code:
echo "
" . "<input type=text name=CustomerID value=" .$row["CustomerID"].   "
";

should be written a
echo "
" . "<input type=text name=CustomerID value=" .$row["CustomerID"].   "
";

Comment: Thanks  -  That is a slight improvement but the second column "Active"  should have the 'yes" go under that header but it appearing right underneath the "CustomerID".  Is there a way to increment it to the next column?
Comment: can you just share the html code for the same. I can figure out a solution for that.
Comment: It is all in the table now but not horizontally.  How would I get them into the right columns


Prepared statements: MySQLi or PDO?

Question: I'm using mySQL database and found out that using Prepared statements offer lots of benefits. However by browsing Stackoverflow I noticed that every expert encourages to use PDO, but no one talks about MySQLi. As far I have understood, PDO supports multiple databases, if thats not the concern, why PDO is preferred over mySQLi?
Thanks
Comment: also see: http://stackoverflow.com/questions/13569/mysqli-or-pdo-what-are-the-pros-and-cons
Answer: PDO is more mature. It offers more features and is easier to use. It has fewer bugs. The choice has nothing to do with the number of drivers supported by PDO; you would need to rewrite your SQL anyway if you decided to change the RDBMS.
PDO is simply a much better extension for communication with the database.
Answer: PDO is interface for accessing databases, so you can use various drivers.
This mechanism gives you abstraction, so it's preferrable.
Comment: I dont understand, i never used more than one database, and mysqli is faster, so why use PDO?
Thanks for answers

Prepared statements: MySQLi or PDO?


Is there a `.should()` assertion that takes a `criteria` callback, and passes when `!!criteria(yield) === true `?

Question: I use this code to check it .tml-tag's text content is a valid XML element
const isXmlTag = (tagStr: string) =>
  tagStr.startsWith('<') &&
  tagStr.endsWith('>') &&
  getCharacterUseCountInString(tagStr, '<') === 1 &&
  getCharacterUseCountInString(tagStr, '>') === 1

cy.get('.xml-tag')
  .invoke('text')
  .should(text => assert(isXmlTag(text)))

But it feels overly complicated - is there a way to use one of the predefined should assertions to evaluate if yield passes my callback criteria (isXmlTag)?
Something like:
cy.get('.xml-tag')
  .invoke('text')
  .should('satisfy', isXmlTag)

Comment: You want to do it without isXmlTag func? And document is actually XML not HTML? Can you please show the XML or relevant fragment.
Comment: No - I want to use my `isXmlTag` criteria function, but more directly than in my 1st example - I want something closer to my 2nd example (second example is pseoudo-code, it doesn't actually work). Anything specific to XML is besides my question.
Comment: Ok, but actually `.should('satisfy', isXmlTag)` looks close to functional. Check out the chaijs docs.
Comment: Check out [How to check that element has either of classes in Cypress](https://stackoverflow.com/a/62023455/16997707)
Answer: satisfy is a valid chai matcher that can take a function, so if you run
cy.get('.xml-tag')
  .invoke('text')
  .should('satisfy', isXmlTag)

you should pass the test.
The yielded subject text is automatically passed into your function.


How to naturalize "artificial" keys in initial_data.json?

Question: When I try to load data from my initial_data.json file, I get the error IntegrityError: Could not load auth.Permission(pk=24): columns content_type_id, codename are not unique.
As I learned from another question, it is necessary to add the -n argument, when exporting data to initial_data.json (manage.py dumpdata -n auth.Permission).
But how can I correct this error now, when I already exported it without natural keys, deleted the old database and can't reimport the data due to the error stated before?
I tried to change the pk field to another number (see below), but it didn't help (new error: IntegrityError: Could not load auth.Permission(pk=10024): columns content_type_id, codename are not unique).
Answer: I fixed the problem by removing from the JSON file all entries except data from my model and importing them.


am I over thinking this?

Question: I was presented with the following homework problem:
Consider the following C program segment. Rewrite it using no goto's or breaks.
j = -3;
for (i = 0; i < 3; i++) {
    switch (j + 2) {
        case 3:
        case 2: j--;
        break;
        case 0: j += 2; break;
        default: j = 0;
    }
    if (j > 0) break;
    j = 3 - i;
}

After studying this for a few minutes, I came to the conclusion that the code segment would simply produce j = 1. Unless I am wrong, the case statement will never produce anything but default, and after the i = 2 iteration of the loop, j will just end up being j = 3 - i(2) which is 1. Am I overthinking this?
Comment: Do you have to use switch statement?
Comment: Note that the final value of `i` is also part of the  observable behaviour
Comment: No. I can remove it as well.
Comment: you could just `j= 1;` and be done with it. And maybe that is the _trick_ in the question.
Comment: Since the values and computation steps are all deterministic and known, you can just run it to check the final values and replace this code with simple assignments, making this a silly assignment.
Comment: This is for a college senior level course. I feel like this is a bit below me, which is why I am thinking I am overthinking it. I ran through all iterations and came up with the j == 1 as I stated above. I think the purpose of the question is to make sure we know how to write structured code, but I think it is a stupid question.
Comment: @Nick what course is this?
Comment: @GRC A course entitled Structures of Programming Languages.
Comment: I don't think you are overthinking it, your analysis was correct.
Comment: Wouldn't it be true that the code produces two outputs, not one? i=3 and j=1?
Comment: @jeff6times7 there is no output to the code. The only variable ever set within the loop is j, and i is just used for the for loop... after the loop runs, i would be 3, you are correct.
Comment: I meant outcome. I assumed that since you and I both used the word "produce" that my meaning would be understood. The side effect of running the code is i=3 and j=1. If you hand in code that reads j=1, then you might not get an A or you would get extra credit if you showed that you better understand the greater effect of executing the code.
Comment: @Nick what book are you using?
Comment: @GRC Concepts of Programming Languages 11th edition. The question comes from chapter 8, I believe, in the programming exercises.
Comment: @Nick https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=4&ved=0ahUKEwiSnO-nrNTZAhWRylkKHVaSAq4QFghFMAM&url=http%3A%2F%2Fwww.emu.edu.tr%2Faelci%2Fcourses%2Fd-318%2F2005-spring%2Fanswerstoselectedproblems.doc&usg=AOvVaw2mhgHgH628gpYp7ueKMRmh we were all overthinking it :)
Comment: @GRC For anyone who is curious about it, to find the "answer" in that doc you linked, search the Word document for `j = -3;`. However, that answer _does_ use a `break` statement, and it also is a similar but not identical problem. But just like this problem, there is no need for a loop at all! The lengthy and convoluted answer in the Word doc is equivalent to `i = 10; j = -6; key = -1;`. No, I didn't figure that out by mentally stepping through the code - I don't have the patience for 10 iterations. I just pasted it into a simple console app and ran it with a breakpoint after the code. :-)
Answer:
j will just end up being j = 3 - i(2) which is 1

Correct:
#include<stdio.h>
int main(void)
{
 int i,j;

 j = -3;
 for (i = 0; i < 3; i++)
 {
    switch (j + 2)
    {  // j = -1 ->

        case 3:
             printf("3\n");
        case 2: j--;
             printf("2\n");
        break;

        case 0:
        j += 2;
             printf("0\n");
        break;

        default:
        j = 0;
        printf("j=%d  i=%d  default:\n", j, i);
    }

    if (j > 0){
          printf("j>0\n");
          break;
    }

    j = 3 - i;
    printf("j=3-i  j=%d i=%d \n", j, i);
  }

  printf("j=%d  i=%d  END\n", j, i);
  return 0;
}

Output:
j=0  i=0  default:
j=3-i  j=3 i=0
j=0  i=1  default:
j=3-i  j=2 i=1
j=0  i=2  default:
j=3-i  j=1 i=2
j=1  i=3  END

Therefore, for the above code, the minimum simplification is:
j = 1;
i = 3;

Comment: The code in the question changes both `i` and `j`. This answer shows only `j`.
Comment: @GRC Thank you for your question. The whole piece of  code produces simple outcome ` j=1;` and `i=3;` My take is that the code fragment can be replaced with those two lines of code.
Comment: "Rewrite it using no goto's or breaks."

am I over thinking this?


How to get the relative MIP optimality gap after timelimit is met?

Question: I'm working on a large scale MIP. So I have to set the time limit to a reasonable value. But the problem is that after the timelimit is met, I don't know how to evaluate the solution, in another words, the gap between lower and upper bounds. Yes, the gap will be shown on screen. But if there is a way to get its value with Python API? So I can output it or do some following statistcs. I have to solve more than 10 MIP at once, it's hard to find the gaps one by one on screen.
Thx for your help!
Answer: Your tags indicate that you are using Gurobi with the Python API to solve your models.
To retrieve the relative MIP gap, you can query the MIPGap attribute (see http://www.gurobi.com/documentation/6.5/refman/mipgap.html)
Python example:
from gurobipy import *

model = read("model.mps")
model.params.TimeLimit = 100
model.optimize()
print("Final MIP gap value: %f" % model.MIPGap)

Comment: This really helps, sorry for not being able to comment immediately.


Hello SO, i just changed a React with MartyJS flux from SSR to Client side rendering, having issues with react-router

Question: So as the title describes im doing an app available on github  at denlillemand/react. It has a express backend that just serves a simple html template that imports my bundle.js. And the app initially renders just fine, but none of the routes seem to work.
Below is the components that are involved:
./Application.js
<code>   import React from "react";
   import Marty from "marty";
   import actions from "./actions";
   import stores from "./stores";
   import queries from "./queries";
   import sources from "./sources";
   import Router from "./Router";
   import RealApp from "./components/App";

class Application extends Marty.Application {
  constructor(options) {
  super(options);
  this.register(actions);
  this.register(stores);
  this.register(queries);
  this.register(sources);
  this.router = Router;
  }
}

var app = new Application();
var { ApplicationContainer }  = require('marty');

app.router.run(function(Handler,state){
      React.render((
              <ApplicationContainer app={app}>
                      <Handler{...state} />
              </ApplicationContainer>
      ), document.getElementById("app"));
});
</code>
./components/App.js
<code> import React from "react";
 import Router from "react-router";
 import Header from "./core/Header";
 import Footer from "./core/Footer";

 var RouteHandler = Router.RouteHandler;

 export default class App extends React.Component {
   constructor(props) {
    super(props);
    this.state = {
    }
  }
  render() {
    return (
      <div>
       <Header />
       <RouteHandler />
       <Footer />
      </div>
     );
   }
}
</code>
./Routes.js
<code> import React from "react";
 import {Route} from "react-router";
 import {DefaultRoute} from "react-router";
 import App from "./components/App";
 import About from "./components/About";
 import ChapterOne from "./components/chapterone/ChapterOne";
 import ChapterTwo from "./components/chaptertwo/ChapterTwo";
 import ChapterThree from "./components/chapterthree/ChapterThree";
 import ChapterFour from "./components/chapterfour/ChapterFour";

  export default (
          <Route name="app" path="/" handler={App}>
                <Route path="/about" handler={About}/>
                <Route path="/chapters/chapterone" handler={ChapterOne} />
                 <Route path="/chapters/chaptertwo" handler={ChapterTwo} />
                 <Route path="/chapters/chapterthree" handler={ChapterThree} />
                 <Route path="/chapters/chapterfour" handler={ChapterFour} />
                 <DefaultRoute name="default" handler={About}/>
         </Route>
  );
</code>
./Router.js
<code>  import Router from "react-router";
  import routes from "./Routes";

  let location = () => {
       if(typeof window !== undefined){
         return Router.historyLocation;
       }
   }

    export default Router.create({
         routes:routes,
         location:location()
     });
</code>
The default route seems to be the only one that works, since im hitting the About component. This app worked when it was SSR not long ago, and im kind of wondering if ive setup react-router correctly, but looking at the DOCS it seem like i have.
Answer: i guess i have to answer my own question,
The creator of MartyJS recently killed off his own project,
if you follow his twitter he announced it ..
so i guess im moving to redux since it has like 3500+ github starts i suppose it will be easier to find support for redux issues that arise .
Thanks .


Fourier coefficients, $\sum_{n=1}^\infty(|a_n|+|b_n|)<\infty$

Question: Suppose $f$ is absolutely continuous on $[0,2\pi]$ with $f'\in L^2[0,2\pi]$ and $f(0)=f(2\pi)$. I would like to prove
$$\sum_{n=1}^\infty(|a_n|+|b_n|)<\infty.$$
By using Parseval's identity, I have shown that
$$\frac{1}{\pi}\int_0^{2\pi}|f'|^2=\sum_{n=1}^\infty n^2(|a_n|^2+|b_n|^2).$$
Does this help? Thanks.
Comment: use $2|a_n| \le n^2|a_n|^2+1/n^2$ and same for $|b_n|$ and you are done
Answer: By Cauchy-Schwarz,
$$ \sum_n |a_n| \leq \left( \sum_n n^2|a_n|^2 \right)^{1/2} \left( \sum_n \frac{1}{n^2} \right)^{1/2} \leq \|f'\|_{L^2} \left(\sum_n \frac{1}{n^2}\right)^{1/2} < \infty.$$ Do similar estimate for $\sum_n |b_n|$ and the proof is complete.
Comment: Thank you. Can we use this result to infer that the Fourier series of $f$ converges to $f$ uniformly on $[0,2\pi]$?


Local HTML image saved in project folder fails to load in page

Question: Attempting to set up a logo button for my project, which would reload the page on-click. As of now, the file is saved in the images folder in the project itself. However, it doesn't show up on the page. I tried taking out the styling from the button, to no avail.
Below is the HTML for the button. The img src is the relative path copied from the file in VS Code.

      <button id = "logo" style="text-align:center;font-size:30px;font-family:Courier New;color:yellow;background-color:black;border: 1px solid" value = "Ryder">

      </button>

I tried using the absolute path with file///: as other answers mentioned, and even changing it to an input of button type, doesn't work. Any help would be great!
Comment: Try to use forward slashes (`/`) instead of backslashes (`\ `) to define the path of your image. You may learn more [here](https://developer.mozilla.org/en-US/docs/Learn/HTML/Multimedia_and_embedding/Images_in_HTML).
Comment: Thanks for the reference! That doesn't seem to help, but hopefully I can find something in the reference
Comment: Not a fix but note that the [](https://html.spec.whatwg.org/dev/embedded-content.html#the-img-element) tag does not use and does not need a closing slash and never has in any HTML specification.
Answer: Maybe if you specify the full path to the image like
c:/path-to-image-folder/images/bykr_logo.jpg

or if you base your path from the current working directory, notice the dot at the beginning like
./images/bykr_logo.jpg

Comment: If you vote down you need to give an explanation as to why you voted down.
Answer: this code is working for me.

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

      <button id = "logo" style="text-align:center;font-size:30px;font-family:Courier New;color:yellow;background-color:black;border: 1px solid" value = "Ryder">
    </button>
    <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAH0AAAB9CAMAAAC4XpwXAAAAZlBMVEX///8jHyAAAAAcFxgfGxz39/f7+/vy8vIJAAAUDhAYExTV1NQeGRq1tLTd3d2qqamPjo7Ew8N7eXnn5+eIh4ehoKA8OTpEQUIPBwljYWJTUVJLSEkuLCzMy8uVk5O+vb1ta2xbWloYKsSeAAAEaUlEQVRogd2b25aqMAyGbSjQFqh4ggoo8P4vudGZcUZQSaWpa+3/2sVnStocGlar/0thctgWffgRts5LI6Qq4g+wkw4gZYzxD9D1ESS7yj89zEGxbwWV5/ee1MBuUke/8IypXzgze6/w9dXZboK1T3gG7E6gPcI3IzhTkT+4Dvg9XG79wcNKjkyHkz96Pl53zvzB9RjO4OCPXgQjeFr487mJvzPIvMFX1dh02fszPZmYrjyeNHszXnePh2xcpCO4x4NmsvCm9ggfYtu9x5Vec5qtuYfvfMJX/d+cAirP2Vz163QBnP2yV2H5Q0+h9hjY7uhcinL9gfqhBAFCNt3mI5VTdj6vN9oDOgpxkFgnm81J71zFmlC3+bEqi6Lu81a/eGqks23dKCOEkazo883i7R+d9jUf3q1KOQ+UAFadk4eLEOm8YmBuGWaqAJp+veQPxOsKxH0gCUBUh8kzd4dKwDjUM66AbZN34VkzfeLXH+jaP28gao/m4Q+vuxH6t+xPCuCPHznkEABde93icTsU7erZ775+u7d2wWj/zJxvScHr/NxzM07npxKF5fLvajH7UKaEeGn17w95awPXzbxFNuI2mW6iXq/6G8LjE5POP84aj1x8zZxbzi7lHcr1ohLnSraSJSZSbCcVghMFJkfQp5WZE5kGk/zEzdMDbongiArQexLTAddD0yQeJ3IUfFQfOBLS8pVGnO7WEh0OTmJ6WiDhKwqXQ3cuWwI6vmXcufd4zrBVTkhgOr57d3JP5w06pzy732/4tx717uM6vmNMEGAsbqemDd/FUh0WTrHbLfrVBwI6vp+Su3d5wNdwW7cVxJWOb+cc3Z+zKb6r0junc4anTzr9y+nNJ+nso7Yz81G6xY5z73UM8E0Lgh1n0TQgOG0s5gAITtoAfztHEGWYQLsdRT6Nv5+bXiwuF378ZOfe6wY8ds/FJUHjwKBvJwk2/OB32DKOIJ8flh57O0rh9Pg24Y6oV4bb8xFNv0oir0gJTvqLkK2T8cCUKwEKHxPRmUAdeSVFd/oLj3A9kh1/lUHczSRkdBbAfMOSbOkHgZnLsygyjJs4FK9rWpou8U1znUOSOPej2TSP6sC5ajbPiguSs/6bPltYTSYV3Qkx7kkUZi/C1FVEgW7wOUyjniKxvgpX1B1pjEeZfrkEJqFjy5qOAh9gh+80RajBl/IEF5KqQtfSk2nN5bLoobivK4TVsKljx+PSav4ufD7p845sh6udRlpj/QmLwwGItLGee4xrZ1kObGzhDrPr92Zd127WXtXvTTl2Lqzn8+nUE5UOYu3736/sisWet+QLkqRZiF82XZ00T6MtVwYuEvJ5SMJOmzyTDh5aHwDIar/O2jY7d8WzyUpE2TqjuJhsPA7QH/5WZHHWyekYpnLxCUe0vbOMSyjO00ZEnI1Gb1Oo3x6lvdOpAsl/0E23eXxqh8m+FELxn7+4djXdHW2OzAwKii571X+JT+e+4VLy5nva1pVCfTolqKbjTmsk+R/6k0dRcUDNkwAAAABJRU5ErkJggg==" />

just make the directory name "images" in the project and name the logo "bykr_logo.jpg.jpg"
if you want to use the absolute path with file///:
just right-click on the file in vs code and click copy path and paste it into the browser URL,  browser loads your image wi the absolute path.
Comment: Doesn't work for me sadly. I think I'm going to test with other images to see if the image I'm using is the problem


What happens when there are 2 turnovers on 1 play?

Question: During the last seconds of the 2015 AFC Championship (Broncos vs Patriots), the ball was intercepted by a Bronco, and while the guy was running, he accidentally fumbled the ball and the Patriots recovered.
However, the Patriots still had to do an onside kick.
My question is why? Why didn't the Patriots get 4 new downs?
I am kind of a rookie and not a fan of either team but this really bothers me.
Comment: The down (the play, the "try") isn't over until officials rule a "dead ball". As such, the "try" ended with Patriots in possession but unsuccessful.
Answer: The play in question took place on a 2-point conversion, defined by the 2015 NFL rulebook in Rule 3, Section 41 as a "Try" and covered in more detail in Rule 11, Section 3.
A kickoff follows a 2-point conversion, no matter the outcome of said try. This is covered in Rule 11, Section 3, Article 4: "After a Try, the team on defense during the Try shall receive the kickoff."

SECTION 41 - TRY
A Try is the attempt by a team that has scored a touchdown to add one
  point (by a field goal) or two points (by a touchdown) during one
  untimed scrimmage down (11-3).

Rule 3, Section 18, Article 5, Item 1 states (emphasis mine):

A Kickoff is a kick that puts the ball in play at the start of each
  half, at the start of overtime, after each Try, and after a successful
  field goal.
Comment: Great answer.  I watched that game, and couldn't understand why he was trying to return it - I suppose the 2 points would've meant a patriots onside kick and then field goal doesn't win them the game, but with 12 seconds left and no time outs, it seems unlikely the Patriots would be able to get in field goal range (the recovery spot is the 45 typically, so at least 15-20 yards downfield even for a 'hard' score) in that span of time.  More likely?  He fumbles and they recover for a 2 point conversion.
Comment: The real question is why did the Patriots not go for 3 on one of their several previous 4th downs that ended in turnover on downs. They could have won by one point, and given where the turnovers on downs occurred, the Broncos field position would have been comparable after the ensuing kickoff. But I think only Bill can answer that question.
Comment: @Ellesedil See edit...no matter the outcome of the try (offensive conversion, defensive conversion of a turnover, one-point safety, failed conversion), a kickoff would have followed it. I removed the scoring possibilities of a Try in a previous edit because it wasn't relevant to the question being asked.
Comment: Thanks, @Joe. I actually had this same conversation with a coworker earlier today. I hold the opinion that it made sense to return it, if for nothing else, to make it a 4-point game rather than a 2-point game. Yes, it is probably the smartest and safest play to not return it to keep it a 2-point game, but it isn't out of the realm of possibility that the Patriots could recover at the 45, have a well-designed 20-yard out to the sideline to set up a potential game winning ~52 yard field goal. At the same time, your "more likely" scenario could also take place.
Comment: Because the touchdown + 2 point would have caused a draw, whereas getting an (earlier) field goal would still have required a TD and leave Denver in possession with enough time for a making a scoring drive. (unless onside kick success). The TD + 2 point attempt was the 'safer' attempt.
Comment: @AllanS.Hansen Keep in mind the Patriots were in Denver territory with adequate distance to make a field goal in a previous drive (with more time on the clock), but went for it on 4th down and didn't convert. Yes, it still would have required a TD afterwards, but the Patriots would have taken the lead regardless at that point. I believe that's what Snowman was referring to. Oh, the possibilities.


Help with solving an equation involving a hyperbolic function

Question: I have been analysing a problem involving catenaries and I have derived an equation of the following form:
$$\big(Ax + B\big)\sinh\left(\frac{k}{Ax + B}\right) = Cx + D$$
In this equation, $x$ is the only variable. Everything else is a constant.
I have been trying to solve this equation but haven't been able to. Could you please provide pointers as to how I might be able to solve it? Thanks!
Comment: I am inclined to believe this is numerically solvable. Doubt an analytic method exists to solve.
Answer: This problem will require numerical methods or approximations
You want to find the zeros of function
$$f(x)=\big(Ax + B\big)\sinh\left(\frac{k}{Ax + B}\right) -(Cx + D)$$ In order to make it simpler, let
$$t=\frac{k}{Ax + B} \qquad a=\frac{AD-BC}{A k} \qquad b=\frac CA$$ and consider the function
$$g(t)=\sinh(t)-(at+b)$$ which is much simpler.
Graphing, you have an estimate of the root(s) and you can polish the solution using Newton method.


Application Insights for WebAPI how see requests per second

Question: We are developing a WebApi2 REST API. Now I would like to see the API requests per second in a AI tile/section. There is a metric for ASP.NET request rate, but this is not showing any data for me. Any idea why this could be the case?
Answer: Not sure what the reason is with ASP.NET request rate not showing up, but if you have request data flowing into AI from this application you should be able to create a chart with Metric Explorer in Application Insights UI on Azure Portal:

Pick "Request Rate (Rate)" metric in the settings and select the appropriate chart type.
Then you can pin this chart to Azure dashboard or overview page in AI.

If AI data is not collected at all - it is slightly different topic.


Create a block with information regarding the number of comments and contents created in a specific group

Question: I am using Drupal commons 3.31.
I would like to know how many contents and how many messages are written within a group and  make a block out of it. Also be able to see how many comment,page a specific user has created.
Thank you
Answer: It sounds like this can be accomplished using the views module. Create a view of content from the group you are wanting, and then turn on aggregation. For each field, you can set it to display a count() of the field results.
For the per user part, just set up a filter/contextual filter for the UID.


Contar páginas html com o php

Question: Estou com um pequeno problema, Criei um página grande em html (mas contém várias páginas html)como se fosse um pdf, porém eu preciso  numerá-las e conta-las, como posso fazer isso em php? exemplos: 1 de 40
Comment: Você quer contar arquivos .html, ou você quer criar um sistema de paginação?
Comment: @GuilhermeNascimento conversei com a autora no chat e pelo que me falou ela pretende fazer um sistema de paginação (acho que é possível você ver a conversa apesar de já ter uns 2 dias).
Comment: @RicardoHenrique O problema é que se a pergunta tem um ou mais sentidos, ou nenhum sentindo o passo (em minha opinião) a se seguir é suspender, para evitar tentativas de respostas para algo que não está claro. Podendo neste caso ser *não é claro o que você está perguntando* ou *amplo demais*. Claro que o chat pode ajudar a entender a duvida, mas o ideal é que no final ao menos a pergunta tenha algum sentido com as respostas e que ela estive-se "trancada" (suspensa) enquanto não estiver "aprimorada".
Answer: Segue exemplo de um código para paginação, todas as linhas estão comentadas.
<?php
    //inclusão da conexão com banco de dados
    require('config/conectaBd.php');
    //A quantidade de valor a ser exibida
    $quantidade = 3;
    //a pagina atual
    $pagina     = (isset($_GET['pagina'])) ? (int)$_GET['pagina'] : 1;
    //Calcula a pagina de qual valor será exibido
    $inicio     = ($quantidade * $pagina) - $quantidade;

    //Monta o SQL com LIMIT para exibição dos dados
    $sql = "SELECT * FROM novidades ORDER BY  data DESC LIMIT $inicio, $quantidade";
    //Executa o SQL
    $qr  = mysql_query($sql) or die(mysql_error());
    //Percorre os campos da tabela
    while($ln = mysql_fetch_assoc($qr)){?>

        <?php echo $ln['titulo'];?>

        <img src="fotos/<?php echo $ln['foto'];?> " style="width:250px; float:left; margin-right:25px; margin-bottom:15px; padding:10px; border:2px solid #D8D8D8;"/>

        <?php echo $ln['descricao']?>

        <?php }?>

        <?php
  /**
   * SEGUNDA PARTE DA PAGINAÇÃO
   */
  //SQL para saber o total
  $sqlTotal   = "SELECT id FROM novidades";
  //Executa o SQL
  $qrTotal    = mysql_query($sqlTotal) or die(mysql_error());
  //Total de Registro na tabela
  $numTotal   = mysql_num_rows($qrTotal);
  //O calculo do Total de página ser exibido
  $totalPagina= ceil($numTotal/$quantidade);
   /**
    * Defini o valor máximo a ser exibida na página tanto para direita quando para esquerda
    */
   $exibir = 3;
   /**
    * Aqui montará o link que voltará uma pagina
    * Caso o valor seja zero, por padrão ficará o valor 1
    */
   $anterior  = (($pagina - 1) == 0) ? 1 : $pagina - 1;
   /**
    * Aqui montará o link que ir para proxima pagina
    * Caso pagina +1 for maior ou igual ao total, ele terá o valor do total
    * caso contrario, ele pegar o valor da página + 1
    */
   $posterior = (($pagina+1) >= $totalPagina) ? $totalPagina : $pagina+1;
   /**
    * Agora monta o Link paar Primeira Página
    * Depois O link para voltar uma página
    */
  /**
    * Agora monta o Link para Próxima Página
    * Depois O link para Última Página
    */
    ?>

        <?php
        echo 'primeira | ';
        echo "anterior | ";
    ?>
        <?php
         /**
    * O loop para exibir os valores à esquerda
    */
   for($i = $pagina-$exibir; $i <= $pagina-1; $i++){
       if($i > 0)
        echo ' '.$i.' ';
  }

  echo ''.$pagina.'';

  for($i = $pagina+1; $i < $pagina+$exibir; $i++){
       if($i <= $totalPagina)
        echo ' '.$i.' ';
  }

   /**
    * Depois o link da página atual
    */
   /**
    * O loop para exibir os valores à direita
    */

    ?>
    <?php echo " | próxima | ";
    echo "  última";
    ?>

Há uma pergunta parecida com a sua que contém a resposta acima.
Se isso não for o suficiente, tente visitar essa página. Há um tutorial completo sobre como fazer paginação em PHP.
Answer: Segue um exemplo de paginação que envolve uma busca no banco de dados:
<?php
    //conexão com o banco de dados
        mysql_connect("localhost","root","");
        mysql_select_db("banco_teste" );

    //verifica a página atual caso seja informada na URL, senão atribui como 1ª página
        $pagina = (isset($_GET['pagina']))? $_GET['pagina'] : 1;

    //seleciona todos os itens da tabela
        $cmd = "select * from produtos";
        $produtos = mysql_query($cmd);

    //conta o total de itens
        $total = mysql_num_rows($produtos);

    //seta a quantidade de itens por página, neste caso, 2 itens
        $registros = 2;

    //calcula o número de páginas arredondando o resultado para cima
        $numPaginas = ceil($total/$registros);

    //variavel para calcular o início da visualização com base na página atual
        $inicio = ($registros*$pagina)-$registros;

    //seleciona os itens por página
        $cmd = "select * from produtos limit $inicio,$registros";
        $produtos = mysql_query($cmd);
        $total = mysql_num_rows($produtos);

    //exibe os produtos selecionados
        while ($produto = mysql_fetch_array($produtos)) {
            echo $produto['id']." - ";
            echo $produto['nome']." - ";
            echo $produto['descricao']." - ";
            echo "R$ ".$produto['valor']."
";
        }

    //exibe a paginação
    if($pagina > 1) {
        echo "« anterior";
    }

    for($i = 1; $i < $numPaginas + 1; $i++) {
        $ativo = ($i == $pagina) ? 'numativo' : '';
        echo " ".$i." ";
    }

    if($pagina < $numPaginas) {
        echo "proximo »";
    }
?>

Banco de dados de teste para ver como funciona a paginação:
CREATE TABLE `produtos` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `nome` varchar(50) DEFAULT NULL,
  `descricao` text,
  `valor` varchar(10) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;

insert  into `produtos`(`id`,`nome`,`descricao`,`valor`) values (1,'Caneta','Caneta azul','3,00');
insert  into `produtos`(`id`,`nome`,`descricao`,`valor`) values (2,'Caderno','Caderno 200 páginas','8,00');
insert  into `produtos`(`id`,`nome`,`descricao`,`valor`) values (3,'Borracha','Borracha para lápis','1,00');
insert  into `produtos`(`id`,`nome`,`descricao`,`valor`) values (4,'Mochila','Mochila escolar preta','35,00');

Fonte: Paginação PHP

Contar páginas html com o php


Subalgebra in $End(V)$ generated by an endomorphism $A \in End(V)$

Question: How could one describe this subalgebra?
I read that it is given by the powers of $A$ :
${\{A^k:k\in \mathbb N}\}$
is it true? why does it form a subalgebra?
Im trying to understand this proof: On algebra dimensions for an endomorphism
where it is said in the accepted answer that $\mathbb Q[A]$ is generated by the powers of $A$
Comment: In general, that set will not be closed under addition
Comment: Well, there is a differnce between the set of powers, which is what you wrote, and the *span* of the set of powers.
Comment: Is $V$ a finite dimensional space?
Comment: I just added context with the edit
Comment: @JonathanBaram, the set you wrote is genrally not even a subspace of the endomorphism algebra. For example, unless $A$ is nilpotent it does not contain zero!
Comment: yes I understand this, that is why I was wondering why in this proof http://math.stackexchange.com/questions/2115199/on-algebra-dimensions-for-an-endomorphism/2115210?noredirect=1#comment4350249_2115210
it is said that $\mathbb Q[A]$ is generated as a vector space by the powers of A
Answer: Assume $V$ is a vector space over $\mathbb{F}$. Given $A \in \operatorname{End}(V)$, the algebra $\mathbb{F}[A]$ is defined by
$$ \mathbb{F}[A] := \operatorname{span} \{p(A) \, | \, p \in \mathbb{F}[X] \}. $$
More explicitly, the algebra $\mathbb{F}[A]$ consists of all the operators which are polynomials in $A$ so have the form
$$ a_0 \cdot I + a_1 A + \dots + a_n A^n $$
for some $n \in \mathbb{N}_0$ and $a_i \in \mathbb{F}$. This is a vector space that is spanned by $\{ I = A^0, A, A^2, \dots, \}$ and a commutative algebra (where the multiplication is given by composition of operators).
Answer: $\newcommand{\A}{\mathfrak{A}}$$\newcommand{\B}{\mathfrak{B}}$$\DeclareMathOperator{\End}{End}$You are looking for the smallest subalgebra $\A$ of $\End(V)$ containing $A$.
Since $\A$ is a subalgebra, the identity $I \in \A$. Since $A \in \A$, and $\A$ is a subalgebra, we have that $A^{2} = A \cdot A \in \A$, $A^{3} = A^{2} \cdot A \in \A$, etc. Thus all $A^{n}$ are in $\A$. Since $\A$ is a subalgebra, all (finite, of course) linear combinations of the $A^{n}$ are in $\A$.
So $\A$ contains the set $\B$ of all linear combinations of the $A^{n}$. Now $\B$ is a subalgebra of $\End(V)$ (sums and products of linear combinations of the powers of $A^{n}$ are themselves such linear combinations), and contains $A$. By the minimality of $\A$, we have $\A = \B$.


How to get Memory usage history from chromedriver using selenium

Question: I am using chromedriver to test a javascript webapp. How can I get the memory usage information (the kind of information shown on the "History" tab of the chrome dev tools) through chromedriver and selenium.
This strikes me that it should be possible since chromedriver uses chrome's devtools's debugging system to interact with and control chrome.
The language I'm currently using for selenium is java but if you can provide examples in any language that would be aprreciated.
Comment: Since chromedriver uses the devtools debugging system you can't have it launch a devtols window and scrape/read from that...
Answer: I did something like this in chrome for getting my application's javascript memory usage
Chrome driver should be opened with below chromeOptions.
<code>        ChromeOptions chromeOptions = new ChromeOptions();
        chromeOptions.addArguments("--enable-precise-memory-info"); // enabling this flag to get precise js heap memory info for chrome browser
        WebDriver driver = new RemoteWebDriver(new URL(localhost:4444+"/wd/hub"), chromeOptions);
</code>
& then using below logic , we can get JavaScript memory usage of chrome instance
<code>  JavascriptExecutor executor = (JavascriptExecutor) driver;
  long value = (long) executor.executeScript("return window.performance.memory.usedJSHeapSize");
  long valueInMB = value / (1024 * 1024);
</code>
PS : I was able to find this only for chrome browser & not for firefox.
Answer: As you mentioned in your comment, you cannot launch devTool when you are using Selenium.
However, there is an interesting discussion about retrieving memory usage (heap snapshot) via chrome API (javascript): https://code.google.com/p/chromium/issues/detail?id=448379.
If Chromium dev team implement this, you can use Selenium to execute JavaScript to get heap snapshot.


how to get the value from [{"clanid":57}] in php

Question: I am using laravel framework and getting a function's return value as-
[{"clanid":57}]
But I am interested in 57 only.
How to et 57 from this .
I think some array method will work.
Answer: doesn't seem like a real laravel issue to me. hope this helps.
<code>
$json = '[{"clanid": 57}]';
$val = json_decode($json);
$val[0]->clanid; // here you go
</code>


Limite mínimo e máximo de um número em um input do tipo number

Question: Olá, gostaria de saber como posso colocar um limite, um número mínimo e máximo que poderá ser digitado no campo. Por exemplo, fazer com que o número digitado no campo abaixo não possa ser menor do que 0 e maior do que 9.
Obs: apenas números inteiros de 0 a 9.
<input type="number" id="nota" name="nota" class="form-control">

Comment: Só pode conter um número de 1 a 9, isso?
Comment: sim, isso mesmo
Answer: Você pode utilizar os atributos min e max caso esteja usando HTML5

<input type="number" min="1" max="10">
Comment: @Techies min e max são atributos do html5, seria justo informar a sua compatibilidade: http://caniuse.com/#search=min
Comment: Adicionei a tag HTML5 pra facilitar outros usuários tbm @Highlander
Comment: bah, isso mesmo. Eu ia dizer que o usuário  continua podendo digitar qualquer número, mas na hora do submit ele da o aviso. Muito obrigado!
Comment: Sim, kkk por nada @RaylanSoares. Se a resposta te ajudou marque-a como correta para que possa ajudar outros usuários com o mesmo problema.
Comment: @Highlander  eu já ia pesquisar se funcionava em outras versões rs, valeu pelo comentário.
Comment: Estava esperando o tempo mínimo para marcar como correta =) @Techies
Comment: Tranquilo @RaylanSoares. Boa sorte nos estudos.


Need help defining an arc

Question: I'm trying to form similar arcs (like the blue one) to join points X-Z, and A-B at both ends of the line BX in the following picture.
XY and YZ are unknown but equal.
How do I find the radius of the arc and the exact position of BX relative to the rest of the shape?
Comment: Is this what you want? Trace the line through $Z$ perpendicular to $YZ$ and the line through $X$ perpendicular to $XY$. Consider the intersection of these two lines call it $O$. Then draw the circle with center at $O$ and radius $OX=OZ$.
Comment: That is close, but assumes I know the absolute position of BX, which I don't.
Answer: Let $t = XY = YZ = AC=BC$ (where $C$ is the intersection of the vertical and slanted lines near $A$ and $B$).  Let $D$ be the intersection of the horizontal and vertical lines at top left.  Thus $CDY$ is a $45$ degree right triangle with hypotenuse $30+2t$ and legs $30-t$, so $30+2t = \sqrt{2} (30 - t)$.  Solve for $t$.
The centre of arc $AB$ is then a point $P$ such that $ACP$ and $BCP$ are congruent right triangles, with angle $APC$ of $22.5^\circ $ .  Thus $AP = t \cot(22.5 ^\circ)$.
Comment: I think this might be what I'm looking for. A question though: Are ACP and BCP actually right triangles? Wouldn't P be slightly closer to C than the line AB needed to form right triangles? (Either way will be close enough for my purposes.)

Need help defining an arc


Why can't I import only one function from a module?

Question: (Python 3.11.1)
I only want to use the split() method from the re module but it doesn't work.
My IDE says that re is not defined.
from re import split
def to_camel_case(text):
    first_big_letter = True if (65 <= ord(text[0]) <= 90) else False
    arr = re.split('-|_', text)

    return arr

When I import the whole re module like this:
import re

the function works
Comment: when you 'import re' you are importing whole module so you can access the functions with re.**** notations. but if you use 'from re import split' then you are importing just split function and no need to use re.**** , instead you can directly use split() function.
Comment: One clue here would be the complete error message and its context. If the _import_ had failed, you'd see an error on line 1. You are likely seeing an error on line 4, where you try to _use_ it. So the question isn't why you can't import the function, but why the call to `re.split` is failing. Please always include exact, complete error messages when asking questions here. Paraphrasing never adds clarity, and it often obscures important details.
Answer: Yourself gave the answer. You can use what you import. If you import re by import re then re will be defined in your file. You will be able to access whatever re has inside, in particular calling re.split will be legal. But if you write from re import split, what have you imported? You imported split. The function split is defined in your file and re is not. So the interpreter has no idea what to do whenever it finds re.
Answer: If you want both re and split to be bound in the current scope, use two import statements.
import re
from re import split

The first actually creates the module (or will, if re isn't already defined as a built-in module in your Python implementation, as it is in CPython). The second notes that the re module is already defined behaves the same as
split = re.split

(which you could use as well, though for multiple name bindings the from ... import ... is simpler.)
from foo import ... will create the module foo if necessary, but it won't bind the resulting module to the name foo in the current scope.

Related, and different, an import like
import urllib.parse

will import the module urllib.parse, but bind the name urllib to the package that contains the module. But
from urllib import parse

will import the same module, but bind the module to the name parse, leaving the package imported by not bound to any name.


How to parse json in angular 7?

Question: I have the following output from my node rest api :
{
    "workorder": [
        {
            "id": 1,
            "Workorderno": 110,
            "Nfno": 23,
            "Amount": 230,
            "Orderno": 34,
            "createdAt": "2019-03-02 00:19:49.495 +00:00",
            "updatedAt": "2019-03-02 12:40:36.647 +00:00"
        }
    ]
}

I want to read the output and display it in a table using angular 7 ? Could anyone guide me through as to do that? I tried making changes in my rest API, but it failed I could get the results
Comment: What stage are you at currently? Are you successfully using `HttpClient` in Angular to call your API and retrieve the data?
Answer: You need something like this using ngFor,

                Id
                Workorder No

            {{work?.id}}
            {{work?.Workorderno}}

and your Interface should be like this,
  export interface Workorder {
        id: number;
        Workorderno: number;
        Nfno: number;
        Amount: number;
        Orderno: number;
        createdAt: string;
        updatedAt: string;
    }

and then in your component,
  data : Workorder;
  constructor(private service: nowService) {

  }

  ngOnInit() {
    this.service.getAll().subscribe((data) => {
       this.data = data;
    })
  }
}

Comment: i need the type script part as i'm getting object Object as output
Comment: still getting error typeerror cannot read property of undefined ?
Comment: use safe navigation operator
Answer: Try add to tr tag: ngIf="data.workorder!=null"

How to parse json in angular 7?


MakeFile to Visual Studio project

Question: Currently i am using makefile to build the project but i want to convert it into visual studio 2010 project? After some research i can not find a single tutorial or guide to do this. Can any one help me by pointing to any of the relevant resource or step by step guide for it.
P.S: I have only elementary knowledge of makefile
Comment: See this thread: http://stackoverflow.com/questions/15061381/convert-a-makefile-to-a-vs-project
Comment: @yegorich:- If I do it manually, how will i decide which Flag of MakerFile will correspond to what in visual studio project?
Comment: That's a good question. SO far I was just going to compiler/linker flags and looked at different options and tried to determine, what flags the produce. With CMake you can just reuse the flags as they are: `set(CMAKE_CXX_FLAGS_DEBUG "/Od /D \"_DEBUG\" /RTCs /D \"_CRT_SECURE_NO_WARNINGS\" /MDd /GS /W3 /nologo /c /Zi /TP" CACHE STRING "MSVC MT flags " FORCE)`
Comment: Look at these tools: http://www.cmake.org/Wiki/CMake#Basic_CMakeLists.txt_from-scratch-generator
Answer: I'd suggest to use CMake for creating VS projects. You just define your project structure, i.e. sources, headers, resources and CMake creates appropriate project/solution files for your target IDE: makefiles, Visual Studio etc.
After installation CMake provides a GUI, where you can choose your target IDE.
I know, this is not a direct answer to your question, but it is a way to make your projects more portable.

MakeFile to Visual Studio project


"Identifier expected" how to solve and what does it mean to keep it inside the method

Question: I get this error:
<identifier> expected : stayer.stretchPeriodicity();
                                                 ^

And I see people telling that this needs to be inside a method but it's already a method ? and I just want to call it ?
what do I do then ?
Here is my code
class Runner {
    double pace;

    public Runner(double averagePace) {
        pace = averagePace;
    }

    public void workout(double distanceKm) {
        System.out.println(distanceKm + " километра позади");
    }
}

public static void main(String[] args) {
        Runner stayer = new Runner(4.47);
        stayer.start();
        stayer.workout(14.3);
        /* Под этим комментарием вызываете метод stretchPeriodicity */
        stayer.stretchPeriodicity();
    }
}

// класс Athlete
class Runner extends Athlete {

    public void stretchPeriodicity() {
        System.out.println("Рекомендуемая периодичность растяжки: после каждой тренировки");
    }
}

Comment: Your `main` method needs to be inside of the class definition.
Comment: The first `Runner` class should be the `Athlete` class!
Comment: Problem solved! Thank you!
Answer: Why do you have two Runner classes?
You can merge them together or rename the upper class and need to correct the closing braces, main method has been orphan.
Answer: Your code has problems:

You can't have two classes with the same name. to solve: change your second class name.
Your main method must be in a class. to solve: put your main method into the first class.
You can have one class for the main method and one class for Runner class like this:

public class MainClass {
public static void main(String[] args) {

    Runner stayer = new Runner(4.47);

    stayer.start();

    stayer.workout(14.3);
    /* Под этим комментарием вызываете метод stretchPeriodicity */
    stayer.stretchPeriodicity();

}

}
class Runner extends Athlete {
double pace;

public Runner(double averagePace) {

    pace = averagePace;

}

public void workout(double distanceKm) {

    System.out.println(distanceKm + " километра позади");

}

public void stretchPeriodicity()

{

    System.out.println("Рекомендуемая периодичность растяжки: после каждой тренировки");

}

}

Remember your file name should be the same with the first class name. here your file name should be "MainClass".
Good luck.


Best way to ingest a list of csv files with dataflow

Question: I'm looking for a way to read from a list of csv files and convert each row into json format. Assuming I cannot get header names beforehand, I must ensure that each worker can read from the beginning of one csv file, otherwise we don't know the header names.
My plan is to use FileIO.readMatches to get ReadableFile as elements, and for each element, read the first line as header and combine header with each other line into json format. My questions are:

Is it safe to assume ReadableFile will always contain a whole file, not a partial file?
Will this approach require worker memory to be larger than file size?
Any other better approaches?

Thanks!
Comment: Does this answer your question? [Reading CSV header with Dataflow](https://stackoverflow.com/questions/41297704/reading-csv-header-with-dataflow)
Answer:
Yes, ReadableFile will always give you a whole file.

No. As you go through the file line-by-line, you first read one line to determine the columns, then you read each line to output the rows - this should work!

This seems like the right approach to me, unless you have few files that are very large (GBs, TBs). If you have at least a dozen or a few dozen files, you should be fine.

An extra tip - it may be convenient to insert an apply(Reshuffle.viaRandomKey()) in between your CSV parser and your next transform. This will allow you to shuffle the output of each file into multiple workers downstream - it will give you more parallelism downstream.
Good luck! Feel free to ask follow up questions in the comments.
Comment: This is very helpful! Thank you!


Solving $yy'-2y+A=0$

Question: I checked a bunch of other posts on here first to see if I could glean info from them but they came up short.  Is it possible to solve the following differential equation in closed form?
$$yy'-2y+A=0$$
where $A$ is a constant and $y$ is a function of $t$. It looks simple, but the constant terms throws the whole thing into another category of difficulty because it can no longer be separated.
The only method I can think of that might work is by finding and using the Green's function, but I would like to avoid this if it is possible to find a analytic form instead of a integral form of the solution.
EDIT:
Okay so from the answer, I tried to get it myself and this is what I got:
$$\frac{dy/dt}{2-A/y}=1\rightarrow \int\frac{1}{2-A/y}dy=t+B$$
Just focusing on the integral: Let $U = 2-A/y$, then $dU = (A/y^2)dy$ and $y=A/(2-U)$.   This gives:
$$A\int\frac{1}{U(2-U)}dU=\frac{A}{2}\int\left(\frac{1}{U}+\frac{1}{2-U}\right)dU = \frac{A}{2}\left(\ln|U|+\ln|2-U|\right)=\frac{A}{2}\ln|U(2-U)|$$
So all together, the equation becomes:
$$\ln\left|2-\frac{A}{y}\right|+\ln\left|\frac{A}{y}\right|=\frac{2(t+B)}{A}$$
I don't have terms of $y$ and $\ln(y+C)$ as you said and I am unsure on how to connect to the Lambert W function (I have never heard of that before today so please excuse my ignorance!)
Comment: Have you tried isolating y'?
Answer: $$y'=2-\frac Ay$$
$$\frac{y'}{2-A/y}=1$$
$$\int\frac{y'}{2-A/y}\,dx=x+B$$
Comment: Integrating the left-hand side gives terms in $y$ and $\log(y + C)$ for some constant $C$. So, writing $y$ in terms of $x$ requires something tantamount to the Lambert W function, which most people do not consider usable in "closed form" expressions.
Comment: I have a few more additional questions, see original post.

Solving $yy'-2y+A=0$


Ansible Findall capture groups and list

Question: I think I'm confused with Python and Ansible findall. Can I use capture groups in Ansible?  For example, How can I capture group 1 and group 2 then reverse the position in the resulting list?
For example, I'm pulling some block devices info of a VM from a KVM host.  The part in the XML looks like this. I'm trying to get the device name vda and the underlying file win01.qcow2
<disk type='file' device='disk'>\n
<driver name='qemu' type='qcow2'/>\n
<source file='/var/lib/libvirt/images/win01.qcow2' index='2'/>\n
<backingStore/>\n      <target dev='vda' bus='virtio'/>\n
<alias name='virtio-disk0'/>\n
<address type='pci' domain='0x0000' bus='0x05' slot='0x00' function='0x0'/>\n

I use the virt module to pull the XML and then remove the newlines thinking it is easier to deal with regex.  The result is set in a fact, say cleanxml
I did the following and get a list.
- name: Get list of block device
  set_fact:
    listblockdev: "{{ cleanxml | regex_findall(_q) }}"
  vars:
    _q: "<disk type='file' device='disk'>.*?source file='(.+?)'.*?<target dev='(\\w+)'"

The result is
ok: [testhost] => {
    "msg": [
        [
            "/var/lib/libvirt/images/win01.qcow2",
            "vda"
        ],
        [
            "/var/lib/libvirt/images/win01-1.qcow2",
            "vdb"
        ]
    ]
}

Is there way I can have "vda" comes in front of the qcow2 file in the list?
Or the sequence of the list is not fixed?
Ideally I can trying to do things like
cleanxml | regex_findall(_q, '\\2', '\\1') and have the result similar to
[['vda','/var/lib/libvirt/images/win01.qcow2'], ['vdb','/var/lib/libvirt/images/win01-1.qcow2', 'vdb']]
Answer: XML is a pain and it is wrong to start with regex on XML.  The answer is not really regex_findall.  It is more on how to deal with libvirt XML

I started in the wrong track to remove all the \n from the XML.  There may be \n in the actual data between some XML tags

I found this question where the libvirt XML is piped to ansible.utils.from_xml.  I can get the device and file info from the libvirt output.

e.g.
  - name: Get XML
    set_fact:
      xmldict: "{{ lookup('file','./test.xml') | ansible.utils.from_xml }}"

  - name: debug
    debug:
      msg: "{{ item['target']['@dev'] }} {{ item['source']['@file'] }}"
    with_items: "{{ xmldict.domain.devices.disk }}"
    when: item['@device'] == "disk"

Ansible Findall capture groups and list


OG menu default links are not adding up

Question: I am using og_menu 7.x-3.x-dev I am trying to create some default links to the og menu, but links are not adding.With a new group node its creating the og menu but the default links are not coming.Do I need to apply any patch? Thanks in advance. On the og menu settings page I have checked the "Automatically create a OG Menu for new Organic Group" checkbox and in the default links section I have tried adding absolute url and internal drupal path but no success.Am I missing some settings.
Comment: I can see the links are added in the database but they are not showing up.
Answer: I figure out later the link I was adding were actually the nodes I was creating programmatically as a new group is created and I was creating the path alias programmatically as well, when i check the db table menu_links I found there was no router for these node menu links,so to make them work I am putting the default links as external urls for example http://yoursite/node/test, I believe there must be a better way to get this done,good for now.

OG menu default links are not adding up


Java android FloatingActionButton set image and color

Question: I want to do this : FloatingActionButton  I want to set an Image and change color to : GREEN . I try do this :
 <com.smok.maps.fab.FloatingActionButton
            android:id="@+id/list"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ikona2"
            android:tint="@color/green"
            app:layout_anchor="@id/mapview"
            app:layout_anchorGravity="bottom|left|end" />

But this floatingActionButton still is red
Comment: see my answer **i set button *or* background color** @kpokrywja
Comment: You are changing the `tint`, aren't you supposed to change the background(tint)?
Comment: which gradel are you using?
Comment: try `app:backgroundTint="@color/green"`
Comment: @farhana i use : .build:gradle:2.3.3
Comment: I mean for FloatingActionButton which Github library , you are using
Comment: @ZUNJAE I did this but It doesn't work I have  :                                                                java.lang.NullPointerException: Attempt to invoke virtual method 'android.graphics.drawable.Drawable android.graphics.drawable.Drawable$ConstantState.newDrawable()' on a null object reference
Comment: @RahulMandaliya Whhen I did this I see this :                                                                java.lang.NullPointerException: Attempt to invoke virtual method 'android.graphics.drawable.Drawable android.graphics.drawable.Drawable$ConstantState.newDrawable()' on a null object reference
Comment: You have an issue somewhere else I guess. What does the onCreate look like from your Activity?
Comment: @MohammadAli butI want to set this and this
Comment: here is explanation of your problem https://stackoverflow.com/questions/30870443/inflateexception-with-floatingactionbutton-from-official-design-library#answer-30895974
Comment: i don't getting you what you want ?
Comment: see your question you want to change background color and set image so i provide code @kpokrywja
Answer: Pragmatically you can change background color:
aBu.setBackgroundTintList(ColorStateList.valueOf(getResources().getColor(R.color.white)));

in xml you can use :
app:backgroundTint="@color/red"

Or Set a Button using below code:
aBu.setImageResource(R.drawable.ic_image_name);

Answer: Try app:backgroundTint .FloatingActionButton is from support library so you must use app namespace. android namespace can lead to crash or improper working
android is usually used for attribute coming from Android SDK itself.
app is often used if you are using the support library.
<com.smok.maps.fab.FloatingActionButton
            android:id="@+id/list"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ikona2"
            app:backgroundTint="@color/green"
            app:layout_anchor="@id/mapview"
            app:layout_anchorGravity="bottom|left|end" />

For setting Image try:
floatingActionButoon.setImageResource(R.drawable.ic_image_name);

Answer: I Hope this will work for you.
Instead of this
android:tint="@color/green"

Use
android:backgroundTint="#008000"


What is the relationship between ordinary least squares and poisson model?

Question: I am a beginner in learning Statistics with some knowledge of machine learning, some concepts really confused me recently.
Starting from the linear regression and OLS, I think the former is a model with parameters/coefficient and the latter is the method I used to estimate the parameters for the linear regression model. So the relationship between them is the model and estimating method.
However, I read papers using the Gravity Model to describe some phenomena or test hypotheses, some of them estimate the parameters by OLS, but the others use "models" like Poisson, negative binomial to "estimate" the parameters.
I am confused, how can I use one "model" to estimate the parameters of another?
It must be something wrong with my concepts system, and I really need someone to correct me.
In addition, I want to use econometrics methods/models to perform my research (not in the field of statistics or econometrics), is there any books with practical examples and code I can read? Since textbooks I read pay a lot of attention to prove something and lack a macro view of the whole system, I am still not able to perform actual experiments even I obtain that knowledge. Maybe books with some end-to-end examples can help.
Comment: You may find [Gravity Model of International Trade: A User Guide](https://www.unescap.org/resources/gravity-model-international-trade-user-guide-updated-version) by Ben Shepherd illuminating. See the section on Alternative Estimators in particular. There are Stata and R versions of the code as well.
Comment: Hi: A regression model is used when the model is linear and the error term is normally distributed. For other assumed distributions ( poisson, binomial whatever ), there are generalized linear models which can be viewed as generalizations of regression models. I would look at a book or notes on glms for a detailed explanation of them. John Fox has a textbook that does a pretty good job with glm's. There are also specific texts just focus on glm's but, I think, for someone starting out, John's book would be a good starting point. Also, I'm sure there should be notes on the internet.
Comment: @mlofton Thanks! But I still don't know which category should Gravity Model, OLS, Poisson, and binomial fall in. According to your comment, Poisson and binomial are GLMs, what about OLS? How can I use GLMs to estimate the parameter of another model (like Gravity Model)? Could you elaborate? Thanks again!
Comment: @mlofton Instead of the regression model, what are the others and where they locate in the system of econometrics? I can't find books on this topic.
Answer: Hi: It is too broad of a topic to explain here. But, the first thing you should do, in order to keep things clear,  is not use the term "normal linear  regression model.". Call it a linear model with a normally distributed error term. In this way,  every single model ( poisson, binomial, linear model with normally distributed error term, probit ) can be viewed as a generalized linear model. I don't know what a gravity model is but any decent econometrics book will have a chapter on a few generalized linear models. The problem is that the econometrics text will not call them generalized linear models. Still, if you want to look in econometrics texts, look at william greene's, judge and hill or madalla.  I suspect that each of those will have a chapter on what they call limited dependent variables which are a smaller specific set of glms and therefore make things more confusing. ( econometrics only considers a few glms ).  That's why I said to look at John Fox's text. He will actually call them generalized linear models and he'll cover most if not all of them.  The drawback with using his text is that he won't come at  them from a econometric standpoint. Still, I think it's better to look at generalized linear models first and then, once you have those straight, then look at limited dependent variable models for specific "econometric" type glm's. This is not an answer but I decided to write it here since there was more space. I hope it helps a little.
Comment: @Tom Leung: I'm glad it helped. I know that's a famous, good book but it tends to come at things from a bayesian perspective so keep that in mind. and the hierarchical models  complicate things even further.  When I have time, I'll look around for some good notes on the internet for just plain old GLMs. McCullough is the bible but it's pretty theoretical. If anyone can recommend any applied, clear GLM books, feel free to chime in. I used them a long time ago so I'm not up to speed on what's out there. Fox is decent even though it's general and GLMs are just a chapter or two.
Comment: Your answer really helps a lot! I am currently reading Gelman's Data Analysis Using Regression and Multilevel/Hierachical Models.
Comment: After I read the chapter on GLMs, I think I understand my original question a little bit more. The gravity model was transformed into a Poisson model by a link function and the authors used an estimate method called Poisson Pseudo-Maximum Likelihood Estimator to get the coefficients. Do I get it right?
Comment: That sounds okay but I'm not sure about pseudo part. In  GLM's, you are essentially doing MLE ( in an indirect way ) so maybe they are using a slight variant of the standard Poisson GLM for the gravity model ?  I'm not familiar with that model. Maybe someone can comment on the term "pseudo" in the context of GLMs.   This link looks like like a decent set of notes for GLMs. I would try to understand them in their generality first ( i.e: why can a linear model with normal errors be viewed as a GLM ) and then take a look at the Poisson chapter.  https://data.princeton.edu/wws509/notes/#


NOT EXISTS - SQL Query

Question: I have two tables in my sql database

I need to write SQL query, that will find customers that didn't rent any movie. Looking at the table, those customers have id of 3 and 4
I've tried this, but it's not working. I seem to be missing simple logic in creating queries
SELECT name, last_Name, movie_name
FROM Customers, Rented_movies
WHERE Rented_movies.customer_id = Customers.customer_id
AND NOT EXISTS(customer_id);

Any help? Much appreciated!
Thank you
Answer: try this way fellow
SELECT name, last_Name, movie_name
FROM   Customers
WHERE  customer_id NOT IN (SELECT customer_id FROM Rented_movies)
Comment: This is not valid based on the schema provided. Change "WHERE ID" to "WHERE customer_id" and it becomes valid.
Comment: welcome :)     if this work for you don't forgot to mark like a good answer this help another people too in the future
Answer: Try this:
 SELECT * FROM Customers WHERE customer_id NOT IN (SELECT customer_id FROM Rented_movies);

If you MUST use a NOT EXIST statement, then this should also work:
SELECT * FROM Customers C
WHERE NOT EXISTS(SELECT * FROM Rented_movies WHERE customer_id = C.customer_id);

Comment: yes that is it. thank you very much! i get the logic now...this is nesting queries right?
Comment: @fokz8 yes this is an example of a nested query.
Comment: thanks... and not "not exists" is not a must. was first thing i came up with :)

NOT EXISTS - SQL Query


Diagnostic plots for lmer

Question: I am trying to produce a glmm using the lme4 package in R. To validate my model I would like to produce some diagnostic plots but am having trouble doing so as many of the packages that work for lm() models like CAR do not work for lmer() models. I have tried using the languageR and asuR packages but am just getting errors. I am particularly interested in creating partial residual plots.
I have been able to produce qqplots, residual vs fitted plots and look at cooks distances manually. Any suggestions of further plots I should try or packages that would help would be greatly appreciated.
fm <- lmer(Average.payoff ~ Game + Type + Others.Type + Game*Type + Game*Others.Type +
  Type*Others.Type + (1|Subjects), REML=FALSE, data=Subjectsm1)

library(asuR)
inspect(fm)
Error in .setupMethodsTables(fdef, initialize = TRUE) :
  no slot of name "group" for this object of class "derivedDefaultMethod"

library(languageR)
plotLMER.fnc(fm)
warning: I don't know how to handle  Game
Error in preparePredictor.fnc(predictors[i], model, m, ylabel, fun, val = NA,  :
  object 'dfr' not found

Answer: Consider fitting your model using the "lme" function of the R-package "nlme" instead. The book "Mixed Effects Models in S and S-Plus" by Pinheiro & Bates contains a thorough description of the functionalities of the package, including a large variety of diagnostic plots.
Comment: Thanks for the suggestion. My model does appear to be suffering from a degree of heteroscedasticity which lme has a convenient method of handling so I think this may be a better option taking this also into account. I will in the near future be needing to model a binary response variable in which case I will need the lmer function, so any further suggestions would be useful.

Diagnostic plots for lmer


How many numbers from 1 to 2^n have '11' as a substring in binary representation?

Question: For example:
say $n = 2$.
The numbers from $1$ to $2^2$ are $1, 2, 3, 4$.
i.e. $1, 10, 11, 100$ in binary.
So the result is $1$, because only one number i.e. $3$ is there such that it has 11 in it.
For $n = 3$,
$3, 6, 7$ have '11', so the result is $3$.
Answer: Let $E_n$ be the set of integers between $1$ and $2^n$ for which $11$ doesn't appear in the binary representation. If $k$ is such a number, then either

The binary representation of $k$ starts with $0$, i.e. $k \in E_{n-1}$, or
The binary representation of $k$ starts with $10$ (can't be $11$ of course), and the rest is an arbitrary string of $n-2$ digits with no $11$, i.e. $k - 2^{n-1} \in E_{n-2}$

The above actually describes a one to one mapping between $E_n$ and $E_{n-1} \sqcup E_{n-2}$ , where $\sqcup$ represents a disjoint union. From this we get $|E_n| = |E_{n-1}| + |E_{n-2}|$. Noting $|E_2| = 3$ and $|E_1| = 2$, we finally have $|E_n| = Fib(n+2)$, where $Fib$ is the Fibonnaci sequence.
Back to your original question, the answer is now obviously $2^n - |E_n|$ = $2^n - Fib(n+2)$


Docker: adding rsa keys to image from outside of build context

Question: So I want to include an rsa key in my image so I can clone a git repo into my image when its building. But I really don't want to have to keep this key in the docker build repo. Does anyone have a good recommendation on how to handle this? From the docker documentation and various other threads it seems that there is no way to COPY files from outside of the build context. Apart from the following solutions that I am not interested in using:
How to include files outside of Docker's build context?
Is there a better solution to this? Or am I going to have to either keep the key in the build repo or build from the location of the of the rsa key I want to use?
I guess a possible way to do it would be to gitignore the key from the build repo and just put it in whenever I clone it, and make a note of it in the readme so other developers know to do this too.
--- My Solution ---
I don't think there is a "correct" answer for this but here was the solution I went with.
I create a linux user (somewhere) and generate a key for it. Then create a user on gitlab with only repo cloning rights. I add the public key from the linux user to the gitlab user. Then for the build I create the .ssh folder and copy in the users private key with a config file. I just store that users key in the docker build repo.
build steps:
RUN mkdir ~/.ssh
RUN touch ~/.ssh/known_hosts
RUN ssh-keyscan -t rsa gitlab_host > ~/.ssh/known_hosts
COPY ./ssh/config /root/.ssh
COPY ./ssh/id_rsa_app /root/.ssh
RUN chmod 600 /root/.ssh/id_rsa_app

ssh config file:
Host gitlab-app
  HostName gitlab_host
  IdentityFile /root/.ssh/id_rsa_app
  IdentitiesOnly yes

Now the git clone works inside of the build.
Answer: What about using a build argument?  Do something like this in your Dockerfile:
ARG rsakey
RUN test -n "${rsakey}" && { \
      mkdir -p -m 700 /root/.ssh; \
      echo "${rsakey}" > /root/.ssh/id_rsa; \
      chmod 600 /root/.ssh/id_rsa; \
    } || :

Then, when you build the image, use the --build-arg option:
docker build -t sshtest --build-arg rsakey="$(cat /path/to/id_rsa)" .

This will inject the key into the image at build time without requiring it to live in your build context.
Comment: thanks, this would be a workable solution. but we decided on creating a linux user called 'app', created a key for it and then created an 'app' user on our gitlab with only rights to clone repos. We then just put this key in our docker repos with a config file. see above.
Comment: It's not an ideal solution. The content of the key is appended to the command line executing `docker build`, which might end up in some logs at the end (it happened to us building the docker images with gradle)


$MR(tp(a/acl(A))=MR(tp(a/A))$ where MR is morley rank

Question: $MR(tp(a/acl(A))=MR(tp(a/A))$ where MR donotes morley rank. I can't relate $acl(A)$ to $A$. Taking $\varphi(x;a)$ in the $tp(a/acl(A))$ having same rank of the type, I thought there should be some $a'$ conjugate of $a$ over $A$ with $a'\in A$ so that  $tp(a)=tp(a')$ and $\varphi(x;a')$ has same rank as $\varphi(x;a)$  but I don't properly do this.
Answer: Clearly we have $MR(tp(b/acl(A))) \leq MR(tp(b/A))$, so let us prove $MR(tp(b/A)) \leq MR(tp(b/acl(A)))$.
Let $\varphi(x, a) \in tp(b/acl(A))$ be of minimal rank $\alpha$, where $a$ denotes the parameters from $acl(A)$. Then the type $tp(a/A)$ is algebraic and is thus isolated by some algebraic $L(A)$-formula $\psi(y)$. Denote by $\{a_1, \ldots, a_n\}$ the realisations of $\psi(y)$, then
$$
\exists y(\psi(y) \wedge \varphi(x, y))
$$
and
$$
\varphi(x, a_1) \vee \ldots \vee \varphi(x, a_n)
$$
are equivalent. So
$$
MR(\exists y(\psi(y) \wedge \varphi(x, y))) = MR(\varphi(x, a_1) \vee \ldots \vee \varphi(x, a_n)) = \max(MR(\varphi(x, a_1)), \ldots, MR(\varphi(x, a_n))).
$$
For every realisation $a_i$ of $\psi(y)$, we have that $\varphi(x, a)$ and $\varphi(x, a_i)$ have the same Morley rank since the Morley rank only depends on the type of the parameters. So we have for all $1 \leq i \leq n$:
$$
MR(\varphi(x, a_i)) = MR(\varphi(x, a)) = \alpha.
$$
This means that $MR(\exists y(\psi(y) \wedge \varphi(x, y))) = \alpha$. Now the result follows because $\exists y(\psi(y) \wedge \varphi(x, y))$ is an $L(A)$-formula that is in $tp(b/A)$.


C# How to delete certain part of string from text not to delete the rest text

Question: Like in the title, how to delete a certain part of text without deleting the whole text. The example how it should work.
"Some text I put in the richtextbox. Date time 14.05.2022" ->
after pressing button/checkbox the result->:
"Some text I put in the richtextbox."
Some code:
<code>    private void checkBox30_CheckStateChanged(object sender, EventArgs e)
    {
        if (checkBox30.CheckState == CheckState.Checked)
        {
            richtextbox.Text += "Some text I put in the richtextbox. Date time 14.05.2022";
        }
        else
        {
           richtextbox.Text.Replace("Date time 14.05.2022","");
        }
    }
</code>
The replace method doesn't work. Nothing happens after clicking a checkbox.
Comment: Replace return the new string. You must set that string. richtextbox.Text = richtextbox.Text.Replace("Date time 14.05.2022","");
Answer: This should work. You missed assigning the output back to the original variable.
<code>private void checkBox30_CheckStateChanged(object sender, EventArgs e)
{
    if (checkBox30.CheckState == CheckState.Checked)
    {
        richtextbox.Text += "Some text I put in the richtextbox. Date time 14.05.2022";
    }
    else
    {
        richtextbox.Text = richtextbox.Text.Replace("Date time 14.05.2022","");
    }
}
</code>
Comment: Many thanks to you it works as a miracle !!!!
Comment: Please accept/mark as an answer if this really works for you. Also, you are missing space in front of `Date` in the string in the replace. ;)
Comment: I'll do it in some minutes


Passing a parameter along with callback?

Question: This is my code:
var title = 'test'

function onlineStatus(callback){
    $.ajax({
    url: "https://blabla,
    cache: false,
    success: callback
});

onlineStatus(function(test) {
    // doing stuff with `test`
    $('#forTest').attr('title', title);
});

The problem is that the onlineStatus call doesn't see title, which is correct, because it is out of scope. Is there a way to pass it into the function, so that the title is seen?
Comment: I think the issue is that the test argument is scoped locally to the anonymous callback function.
Answer: function statusCheck (test) {
    console.log(test);
}

function onlineStatus (callback) {
    callback (arguments[1]);
}

onlineStatus (statusCheck, "test");


Is there a closed form to this summation?

Question: I cannot get a closed form for
 $\sum\limits_{r=0}^{m} \frac{(m+r) !}{(m-r)! (2 r)!}$ '
Does anyone have any idea on what it is?
Answer: Hint:
$$\frac{(m+r)!}{(m-r)!(2r)!}= {{m+r} \choose {2r}}$$
Comment: Do you have a proof for this?
Comment: I'm not saying the series equals that, but rather you can simplify $a_n$.
Comment: Sorry yes I understood your answer. I meant to comment this on the other answer. Apologies and ty for the help :)
Answer: This sum is the Fibonacci number $F_{2 m+1}$.
Comment: Do you have a proof for this?