How can I use the chain rule in this strange case?

Question: I have to do the partial derivative of a compound function $Z$ with respect to $X$ and then with respect to $Y$.
I have that $X$ is my independent variable, then $Y$ depends on $X$, and $Z$ depends both on $X$ and $Y$. The problem is this, usually we have compound functions going from $X$ to $Y$ to $Z$. In this case is different because $Z$ depends both on $X$ and $Y$. Can I use normal chain rule for this partial derivative ?
The second question is, how can I calculate it with respect to $Y$, knowing that $Z$ depends both on $X$ and $Y$?
As you can see, we drive with respect to variables that are not independent from each other.
Excuse me for my bad layout but I can't use latex.
Thanks
Comment: Why can't you use LaTeX? Did you even try?
Comment: It's a muddled problem.  Giving a specific function $Z(X,Y(X))$ would allow Readers to give a specific solution.  When function $Z$ has both a direct dependence on one argument, its first in my notation, we can take a partial derivative of $Z$ with respect to that argument *holding the second argument fixed*.  This is implicit in the definition of partial derivatives, that a function has arguments that can be varied independently.  If you want to break away from that circumstance, so that one might talk about a "total derivative" with respect to $X$, it is essential to pin down details.
Comment: See [this brief introduction](https://math.stackexchange.com/help/notation) to posting math notation with $\LaTeX$ and `MathJax`.  It gives you links to more advanced/detailed instructions.
Answer: I think what you're saying is your situation is $z = z(x,y) = z(x,y(x))$. In this case, you can still use the chain rule, but it's a bit more complicated. You have essentially a function of one variable, but it doesn't look it. What I like to do is change the variable names to avoid confusion, call them say, $s,t$ and write $z = z(s,t)$. Then take the $x$ derivative:
$$\frac{dz}{dx} = \frac{\partial z}{\partial s}\frac{ds}{dx}+\frac{\partial z}{\partial t}\frac{dt}{dx}$$
This is true for any function $z(s,t)$ where $s,t$ are both functions of the single variable $x$. So now you can formally compute what $\frac{\partial z}{\partial s}$ is using whatever your formula is, and then substitute $s = x, t = y(x)$ in, and you'll obtain:
$$\frac{dz}{dx} = \frac{\partial z}{\partial x}+\frac{\partial z}{\partial y}\frac{dy}{dx}$$
which is the derivative you want.
This also reveals what's going on for the $y$ derivative. You just want the formal derivative $\frac{\partial z}{\partial t}$. All of this is covered by pretty much any book on multivariable calculus.


Goodness of fit test/index for a regression tree

Question: I have fitted a regression tree on my data and would like to demonstrate that it is a good model. Are there any standard goodness of fit test or index for a regression tree?
I understand that I can calculate the Confusion Matrix or Gini's index etc. to assess performance of each node but are there any way to assess the fit of the whole tree?
Comment: Welcome to Cross Validated! Don't you have the overall predictions from the whole tree that you can stick into the various calculations of interest like a confusion matrix or Gini index? // Are your observed outcomes discrete categories?
Comment: you mean comparing the model output and actual values? // the output is a continuous variable.
Comment: That's the standard way to do it.
Answer: The standard way to proceed is to make predictions from the entire tree (or whatever model you are using). You then evaluate the predicted values compared to the true values in terms of some statistic(s) of interest, such as mean squared error for the regression tree you are using.
This statistic of interest is then your measure of performance for the entire tree, not just of an individual node.
There are many concerns downstream of this (discussed in the comments), and this is why methods like cross validation and bootstrap validation exist. However, all of them will begin with sending your features down the decision tree to get a prediction for the entire tree, just as you would do for any other supervised learning model.
Comment: Regression trees are notorious for non-reproducibility unless n > 100,000 subjects in many cases.  The easiest way to invalidate a tree is to bootstrap your dataset and compare tree structures over multiple repeats of the tree-building process.  You'll see a disappointing amount of instability in the trees that make their use questionable.  Not to mention unreliability of predicted values.  For more see https://hbiostat.org/rmsc/genreg.html


Stepwise regression, moderation effects, main effects

Question: I have a simple model:
$A$ is hypothesized to be a predictor / regressor / explanatory / input variable
$B$ is hypothesized to be the response / regressand / explained / outcome variable
So, the relationship looks something like:
$A\longrightarrow B$
Additionally, $C$ is hypothesized to be a moderator of the relationship between $A$ and $B$.
When I run the regression by including all the variables ("enter" procedure in SPSS), none of the relationships are significant.
When I use "step-wise" regression, and let SPSS choose the variables to include, $C\times A$ has a statistically significant effect on $B$, but SPSS stops the "step-wise" regression procedure before including $A$. I suppose one can assume that $A$ doesn't have a statistically significant effect on $B$ (after the inclusion of $C\times A$ in the model).
Thus, I have a statistically significant moderation term $(C\times A)$ , but the main term $(A)$ has not been included in the model.
What can I do with such a result? I was taught that moderation effects are not valid if main effects were not included in the model. Is there a way around that admonition? Is there some way I could still employ this result profitably?
Comment: Use entering in blocks. Block1= A C (method enter); Block2= AC (method stepwise or forward). Hereby, you force main effects first. Then, if the prediction allows, the interaction will be added.
Comment: `Thus, I have a statistically significant moderation term (C×A), but the main term (A) has not been included in the model.` What SPSS command you use? Linear regression command does not create interactions internally. Did you compute AC youself first and include three variables A, C, AC?
Comment: @ttnphns Yes, I computed AC and included A, C and AC.
Answer: The easiest solution is to just force the main effects in your model. You should not use step-wise anyhow, see: here.
Comment: Did you make sure that the value 0 on both $A$ and $C$ are meaningfull and near the range of the data? For example, if $A$ is year of birth, than the value 0 would be the year 0, which in most cases is way outside the range of the data. In that you would need to center the offending variable(s) before computing $A \times C$.
Comment: When I use the "enter" method (i.e. not "step-wise), nothing turns up significant. But I see your point, and thank you for the link.
Comment: I didn't think of centering the data. I just checked my data and I don't think centering will be applicable here. But very good point for the future. Standardization and centering can both be very important. So thank you for reminding me!


Setting cookie expiry time

Question: I am setting a cookie to launch a modal on page load.
Currently, the modal only happens once.
I need it to reset every month, so that it keeps popping up once a month for every visitor.
Is it possible to modify my code to make this happen or do I need to do it another way? Any help appreciated.
$(document).ready(function () {
//if cookie hasn't been set...
if (document.cookie.indexOf("ModalShown=true")<0) {
    $("#newsletterModal").modal("show");
    //Modal has been shown, now set a cookie so it never comes back
    $("#newsletterModalClose").click(function () {
        $("#newsletterModal").modal("hide");
    });
    document.cookie = "ModalShown=true; expires=Fri, 31 Dec 9999 23:59:59 GMT; path=/";
}

});
Answer: Just don't set a static expiration date in your cookie but a dynamic one:
var now = new Date(); //get the current date
now.setMonth(now.getMonth() + 1); //add one month to it
document.cookie = "ModalShown=true; expires=" + now.toUTCString() + "; path=/";

Comment: What happens if current month is december(11)?
Comment: Sorry, December, the twelfth month
Answer: Hey I'm going to give simple code for setting remove and add cookie which might help you
function setCookie(name, value, expire) {
    document.cookie = name + "=" + escape(value) + ((expire === null) ? "" : ("; expires=" + expire.toGMTString()));
}

function checkCookie(name) {
    if (document.cookie !== "") {
        var toCookie = document.cookie.split("; ");
        for (var i = 0; i < toCookie.length; i++) {
            var CookieName = toCookie[i].split("=")[0];
            var CookieValue = toCookie[i].split("=")[1];
            if (CookieName === name) return unescape(CookieValue);
        }

    }
}

function removeCookie() {
    var CookieAlert;
    CookieAlert = document.getElementById('cookie');
    var expire = new Date();
    expire.setMonth(expire.getMonth() + 1);
    setCookie('agreeCookies', 'yes', expire);
}

window.onload = (function () {
    //IF cookie exists do something
    if (checkCookie('agreeCookies') !== 'yes') {
        //Do something in your case dont start modal
    } else {
        //START MODAL
    }
});

So in html you can use onclick="removeCookie()" on your close button in modal, basically you show modal and on close modal you set cookie, then after month when cookie expires you show it once again
Comment: be careful using [`toGMTString()`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Date/toGMTString) this function has been deprecated: `Deprecated
This feature has been removed from the Web standards. Though some browsers may still support it, it is in the process of being dropped. Do not use it in old or new projects. Pages or Web apps using it may break at any time.`
Comment: oh good to know thank you @empiric :)
Answer: All you need to do is update the expiration date to be now + 1 month rather than 'Fri, 31 Dec 9999 23:59:59 GMT', but do it outside of the check for the cookie to ensure existing users with the old expiry date get an updated cookie.

Setting cookie expiry time


MUI Autocomplete multiple freesolo; how to get new values?

Question: I'm implementing a generic autocomplete that will allow users to select multiple items, either from a list or by typing a new value, similar to how recipients are managed in email. Everything is functioning, I can add items to the list (including new items), remove, etc. See below.
What I want to do is identify when an item is new (not already in the list), so I can take other actions (for example to show a dialog so that user can add some other associated details). I suppose I can compare the list before and after a change, figure out which item is new, and see if it's already in my list of options, but that seems cumbersome.
Any suggestions on how best to do this?
Answer: Figured it out, thought I'd post this in case anyone else has the same question.
The OnChange event has an optional parameter titled 'reason'; the value will be either removeOption (when deleting), selectOption (selecting an existing item from the list), or createOption (adding a new item).
Problem solved!


Is there any status of review comments in gerrit

Question: we are going to use gerrit for the source code reviewing and code repository. as we know, for each change, anyone can review it, and give the comments in specific line of source code.
My question is, is there any state of the review comments such like (new/open/closed)? or how to check previous review findings have been fixed or still open there?
Is there any life cycle of review comment? and how to measure it?  I used gerrit REST API to read it, but no such information there, or I miss something?
Answer: No there isn't. It would be useful as a new patchset will hide previous comments and it is not clear which comments have been fixed and closed.
Answer: This is not currently possible.  Comments don't have a state or any kind of tracking between patch sets.
Basically you have to rely on the change owner adding a "Done" comment at the same line (on the same patch set).
Also note that if there are multiple comments on the same line, it's not possible to reply to a specific one.


$11^{-1}$ modulo $91$ is $58$. Why?

Question: I am reading wiki article about Quadratic Sieve and it says
$11^{-1}$ modulo $91$ is $58$
Why? How is it been calculated?
Comment: If your question is more about the *how* than the *why*, have a look at [modular multiplicative inverses](https://en.wikipedia.org/wiki/Modular_multiplicative_inverse), and in particular look at the part about the *Extended Euclidean Algorithm*.
Answer: $$11\cdot 58 = 638 \equiv 1 \pmod{91}$$
In other words, $11^{-1} = 58$ in $\mathbb{Z}_{91}$.
$\mathbb{Z}_{91} = \{\bar{0},...,\bar{90}\}$ where $\bar{a} = \{x\in \mathbb{Z}|x \equiv a \pmod{91}$}. Now $11^{-1}$ in $\mathbb{Z}_{91}$ is 58 since $$11\cdot58 = 58\cdot 11 = 1 \text{ in } \mathbb{Z}_{91} $$
And this is how we define the inverse. But of course we have $11^{-1} = \frac{1}{11}$ in $\mathbb{R}$, and you must be careful not to confuse the two.
Comment: In particular, $a$ in $\mathbb{Z}_b$ has an inverse iff $\gcd(a,b) = 1$.
Comment: Without any theory we have, modulo $91 , $  $ 11.58\equiv 22.29\equiv (-69)(-62)\equiv 22.214.171.124\equiv 2.23.93\equiv 2.23.2\equiv 92\equiv 1.$ A more sophisticated way, about 25 centuries old (Euclid) as mentioned by PM 2Ring (above) is the algorithm for finding integers $x,y$ such that $11 x+91 y=1$. And then $11 x \equiv 1 \pmod {91}.$
Comment: Can you provide explanation to what you just wrote. May be you can link me to an article about this.
Comment: @Ilya_Gazman, he showed $11\cdot 58 = 638 \equiv 1 \pmod{91}$. now, as $\gcd (11,91)=1$ you can divide both side by  $11$, that does not harm $91$. So, thus you get the required result.
Comment: @SubhadeepDey I don't get it. What I type in my calculator $\frac{1,11} \mod{58}$ I am getting a number smaller than 1. I am building trying to implement this algorithm in Java, so I need to be able to do this calculation. I don't get it just yet
Comment: @Ilya_Gazman By definition, the number $11^{-1}$ is the number $x$ such that $11 \cdot x \equiv 1 \pmod {91}$. So this is why $58$ works. I don't think there exists a "smart" algorithm for doing this except trying all the possble values. Note that some numbers may not have an inverse
Comment: @Ant: There certainly _is_ a smart way to calculate the [modular multiplicative inverse](https://en.wikipedia.org/wiki/Modular_multiplicative_inverse). The usual way is to use the extended Euclidean algorithm mentioned earlier by Tormod Haugland. This is (usually) taught fairly early in an introductory number theory course.
Comment: @PM2Ring I stand corrected.  Thank you :-)
Answer: The reason $58 = 11^{-1} \pmod{91}$ is
$$58 \cdot 11 = 638 = 7 \cdot 91 + 1 \implies 58 \cdot 11 \equiv 638 \equiv 1 \pmod{91}$$
The reason $11$ has an inverse $\pmod{91}$ is that $\gcd(11, 91) = 1$.
To calculate the inverse, we use the extended Euclidean algorithm. First, we use the Euclidean Algorithm to solve for $\gcd(11, 91)$.
\begin{align*}
91 & = 8 \cdot 11 + 3\\
11 & = 3 \cdot 3 + 2\\
3 & = 1 \cdot 2 + 1\\
2 & = 2 \cdot 1
\end{align*}
Working backwards, we express $1$ as a linear combination of $11$ and $91$.
\begin{align*}
1 & = 3 - 1 \cdot 2\\
  & = 3 - 1(11 - 3 \cdot 3)\\
  & = 4 \cdot 3 - 1 \cdot 11\\
  & = 4(91 - 8 \cdot 11) - 1 \cdot 11\\
  & = 4 \cdot 91 - 33 \cdot 11
\end{align*}
Hence,
$$-33 \cdot 11 = 1 - 4 \cdot 91 \implies -33 \cdot 11 \equiv 1 \pmod{91}$$
Thus, $-33 \equiv 11^{-1} \pmod{91}$.  Moreover, any number of the form $-33 + 91t$ is an inverse of $11 \pmod{91}$ since
$$
11(-33 + 91t) = -363 + 11t \cdot 91 = 1 - 364 + 11t \cdot 91 = 1 + 91(11t - 4)$$
Thus, $11(-33 + 91t) \equiv 1 \pmod{91} \implies -33 + 91t \equiv 11^{-1} \pmod{91}$.
In particular, if $t = 1$, we obtain
$$11^{-1} \equiv -33 + 91 \equiv 58 \pmod{91}$$

$11^{-1}$ modulo $91$ is $58$. Why?


Finding planar representation of graph

Question: If it is known that a graph is planar, how do we find a planar representation of the graph?
Is there any method other than trial and error?
Thanks a lot.
Comment: The title of this [thesis](http://igitur-archive.library.uu.nl/dissertations/01855269/full.pdf) looks promising: "Algorithms for Drawing Planar Graphs".
Answer: http://en.wikipedia.org/wiki/Planarity_testing

Finding planar representation of graph


Using Views API to create a status field based on other field values (Sortable and Filterable)

Question: I need a status field to appear in a view with a table format that has values like "Needs Attention", "Awaiting Payment", "Not Interested", etc...
These values are based on values of other fields attached to the node such as a date field indicating the last time of interaction, payment received toggle, etc...
This field needs to be sortable and filterable for good reporting; so, I've started reading-up on the Views API to create custom Views Data, but I'm having trouble figuring-out where to attach the SQL expression that calculates the value.  I've seen some tutorials that are close, but they talk more about getting your custom SQL table into views and using expressions on those, but not one working with existing node field values.
Does anyone know how and where to set this up, or has anyone found something on the web describing this?
Answer: I had started in the right direction this morning Thanks to this article:  Drupal 7: Using SQL Expressions in Views 3
This afternoon, after some digging, I found that you can manually join the tables that you need to work with in the same handler as mentioned in the article, and this expression field can be added to the "views" index of the data variable, and it will still be added to the base query.
So in, mymodule.views.inc
function mymodule_views_data() {
    $data = array();

    $data['views']['student_status'] = array(
        'group' => 'Content',
        'title' => t('Student Status'),
        'help' => t('The current status of a student based on when they we last interacted with, paid, etc...'),
        'field' => array(
          'handler' => 'mymodule_views_handler_field_expression',
          'click sortable' => TRUE,
          'expression' => "
                CASE
                    WHEN
                        field_data_field_some_table.field_some_value = 1
                    THEN 'Registered'

                    WHEN
                         DATEDIFF(NOW(), field_data_field_last_interaction_date.field_last_interaction_date_value) > 30
                    THEN 'Needs Attention'

                    ELSE 'Unregistered'
                END
            ",
      'expression_alias' => 'student_status',
    ),
   'filter' => array(
     'handler' => 'mymodule_views_handler_filter',
     'allow empty' => TRUE,
   ),
    'argument' => array(
      'handler' => 'mymodule_views_handler_argument',
     'allow empty' => TRUE,
    ),
   'sort' => array(
     'handler' => 'views_handler_sort',
   ),
  );

 return $data;
}

And then in mymodule_views_handler_field_expression.inc
class mymodule_views_handler_field_expression extends views_handler_field {
  var $expression_alias = 'unknown';
  var $expression = NULL;
  /**
   * Construct a new field handler.
   */
  function construct() {
    parent::construct();
    if (!empty($this->definition['expression'])) {
      $this->expression = $this->definition['expression'];
    }
    if ( !empty($this->definition['expression_alias']) ) {
      $this->expression_alias = $this->definition['expression_alias'];
    }
  }

  /**
   * Called to add the expression as a field to a query.
   * Overrides and based on views_handler_field->query().
   */
  function query() {
    // Make sure the table is available, and get the alias.
    $table_alias = $this->ensure_my_table();

    // Boilerplate from views_handler_field->query().
    $params = $this->options['group_type'] != 'group' ? array('function' => $this->options['group_type']) : array();

    //HERE'S THE NEW STUFF
    $this->query->add_table('field_data_field_last_interaction_date');
    $this->query->add_table('field_data_field_some_table');

    // Insert the table alias into the expression and its alias, and use the add_field method of the underlying query object.
    // See add_field() in views_plugin_query_default.inc
    $this->field_alias = $this->query->add_field(NULL, $this->expression, $this->expression_alias, $params);

    // More boilerplate.
    $this->add_additional_fields();
 }

}

ALSO NOTE:
In order to use this custom field in the Context Filter and Filter Criteria, I had to create custom argument and filter handlers to replace the WHERE statement with a HAVING statement, as well as, clean-up the alias that it uses.
Argument
class mymodule_views_handler_argument extends views_handler_argument {
     /**
   * Set up the query for this argument.
   *
   * The argument sent may be found at $this->argument.
   */
  function query($group_by = FALSE) {
    $this->ensure_my_table();
    $this->query->add_having('Content', $this->real_field, $this->argument);
  }
}

Filter
class mymodule_views_handler_filter extends views_handler_filter_string {

     /**
   * Add this filter to the query.
   *
   * Due to the nature of fapi, the value and the operator have an unintended
   * level of indirection. You will find them in $this->operator
   * and $this->value respectively.
   */
  function query() {
    $this->ensure_my_table();
    $field = $this->real_field;

    $info = $this->operators();
    if (!empty($info[$this->operator]['method'])) {
      $this->{$info[$this->operator]['method']}($field);
    }
  }

  function op_equal($field) {
    $this->query->add_having($this->options['group'], $field, $this->value, $this->operator());
  }

  function op_contains($field) {
    $this->query->add_having($this->options['group'], $field, '%' . db_like($this->value) . '%', 'LIKE');
  }
}


Dart: library and export for web apps

Question: I am experimenting with my first Dart web app and do not expect to make any part of my app a reusable library for other apps/libs. As such, I do not have a lib directory in my project; rather, I have a web directory.
I guess my intent is to have my web directory look like this:
web/
    Main.dart <-- where my main method is
    logging/
        Logger.dart
        LogLevel.dart
    model/
        Signin.dart
        Signout.dart
    view/
        SigninView.dart
        signinView.html
    presenter/
        SigninPresenter.dart
    ...lots of other packages

Several questions:

Should my entire application (everything under web) be considered to be a part of the same library? If so, would I then put library myapp; at the top of every Dart file? Otherwise, what is the level of granularity for a library? Should I put it package-level, and have Logger and LogLevel inside library logging;? Is it at the class/file level and have a library logger and a library log_level?
Is my web directory set up correctly? I'm coming from Java so I'm treating web the same as Java/Maven's src/main/java directory, and setting up a package structure under web that makes sense to me...
I understand that the import keyword is for importing source types from other packages. But what about export - what does that do?
Comment: Please, keep one question per post instead of spawning several at once.
Comment: Thanks @Braiam (+1) but that is always a judgement call.  I feel like if you have several, similar questions, and they all require the same setup/backstory/SSCCE, that it's better to just group them into one question rather than bog SO down with the extra text from multiple questions.
Comment: SO is not a forum, no one feels bogged, also your question should be searchable, if I need to know what `export` does in dart sources, how can I find [this](http://stackoverflow.com/q/20789600/792066) question? And if you ask several questions in one post is more likely that yours will be closed as duplicated just because it answers one of your many questions.
Answer: I would recommend that you have a lib/ directory and put shared code within it. If the code isn't directly to be used by other parts of your app, move that code to the src/ directory within lib/.  I realize that you are not planning to make your app reusable by other apps, but code which is consumed by different parts of your app should probably live within lib/.
A lot of this is a matter of convenience and convention, but I try to keep my web/ directory pretty lean, even going so far as to place only those .dart files in it that are directly referenced in a .html file. Your mileage may vary, but I find that this convention (putting shared code in lib/ and web-specific code in web/ helps keep things clear).
As for library directives, I like to use a single namespace which is the same as the name of the app.
So, a library in lib/models.dart could be declared like this:
library myApp.models;

A library in `web/foo/bar.dart' could be declared like this:
library myApp.web.foo.bar;

Comment: Thanks @Shailen Tuli (+1) - very sound advice. I guess I'm confused over the **purpose** of the library. What's the difference between placing `web/foo/bar.dart` in a library named `myapp.web.foo.bar` or putting it in one called `myapp.web.foo`? What are the benefits/cons to either approach? Thanks again!

Dart: library and export for web apps


$\omega_1$-closedness and fullness for $\searrow$ $\omega$-sequences

Question: Let $\pi$ is a $\Bbb{P}$-name for a partial order, i.e. there is a name $\pi'$ and $\pi''$ such that $$1\Vdash_\Bbb{P} \pi '' \in \pi\land (\text{$\pi'$ is a partial order of $\pi$ with largest element $\pi''$}).$$
We call $\pi$ is full for $\searrow$ $\omega$-sequences if whenever $p\in \Bbb{P}$, $\rho_n\in\operatorname{dom} \pi$ for each $n<\omega$ and
$$p\Vdash \rho_n\in\pi \land \rho_{n+1} \le \rho_n$$
for each $n$ then there is a $\sigma\in\operatorname{dom} \pi$ s.t. $p\Vdash \sigma\in\pi$ and $p\Vdash \sigma\le \rho_n$ for each $n$.

I try to prove following statement: if $\Bbb{P}$ is $\omega_1$-closed and $\pi$ is full for $\searrow$ $\omega$-sequences, then
$1\Vdash \text{$\pi$ is $\omega_1$-closed}.$
I made two 'proofs' which the former one is regarded as false and the latter one is incomplete. The 'false proof' goes as follow:

Let $\rho$ is a $\Bbb{P}$-name satisfying
  $$1\Vdash \forall n<\check{\omega}:\rho(n+1)\le \rho(n) \,\land\, \rho(n)\in \pi .$$
  so for each $n$, $1\Vdash \rho(n+1)\le \rho(n)$ and $1\Vdash \rho(n)\in\pi$. (*)
Therefore, since $\pi$ is full for $\searrow$ $\omega$-sequences, we can find a name $\sigma$ such that $1\Vdash \sigma\le \rho(n)$ for all $n<\omega$ and $1\Vdash \sigma\in\pi$, so $1\Vdash \forall n<\check{\omega}: \sigma\le\rho(n)$ (**) and therefore $1\Vdash \text{$\pi$ is $\omega_1$-closed}$.

I doubt the part (*) and (**) are problematic. Is it right? I didn't get why they are problematic so I need an explanation for them.
I guess the 'proof' given below goes to right direction:

Let $p\in \Bbb{P}$ be arbitrary and $\rho$ be a $\Bbb{P}$-name satisfying
  $$p\Vdash \forall n<\check{\omega}: \rho(n+1) \le\rho(n)\,\land\, \rho(n)\in\pi.$$
  Since $p\Vdash \exists x \in \pi : \rho(\check{0}) = x$, there is $p_0\le p$ and $\Bbb{P}$-name $\sigma_0$ s.t.
  $$p_0 \Vdash \sigma_0\in \pi\,\land\, \rho(\check{0}) = \sigma_0.$$
  Similarly, we can take $p_1\le p_0$ and a $\Bbb{P}$-name $\sigma_1$ satisfying
  $$p_1 \Vdash \sigma_1\in \pi\,\land\, \rho(\check{1}) = \sigma_1.$$
  and so on. Since $\langle p_n : n<\omega\rangle$ is decreasing $\Bbb{P}$-sequence, we can find some $q\in \Bbb{P}$ with $q\le p_n$ for all $n<\omega$.
  For such $q$ should satisfy
  $$q\Vdash \sigma_{n+1}\le\sigma_n\,\land\, \sigma_n\in\pi$$
  for each $n<\omega$, so we can find a $\Bbb{P}$-name $\sigma$ s.t.
  $q\Vdash \sigma\le\sigma_n$ and $q\Vdash \sigma\in\pi$ for each $n$.

In above proof, however, I wonder can I conclude that $q\Vdash \forall n<\check{\omega} : \sigma\le \rho(n)$ holds.
I would appreciate any help, thanks!
Comment: What comes to my mind concerning the first proof is: In the assumption needed to apply "fullness", we need a name $\rho_n$ for every $n<\omega$, but in your proof, you only use one name $\rho$. (*) is correct, but it doesn't enable you to apply the consequence for "full".
Answer: The answer to your last question is affirmative: Any extension by a generic filter that contains $q$ will satisfy the formula on the right side. (For the same reason, your steps (*) and (**) are correct, but the problem with the first proof is a different one I think, see my comment.)
Your proof is almost done. To complete the argument, we could assume for a contradiction that there is $p$ so that
$p\Vdash (\rho : \check{\omega} \to \pi) \land (\forall n<\check{\omega} \ (\rho(n)\in\pi \land \rho(n+1)\leq \rho(n)))\land  (\forall x\in\pi \,  \exists n<\check{\omega} \ x \not \leq \rho(n))$
Then by your argument we get $q\leq p$ with $q\Vdash \sigma\in\pi \land \forall n<\check{\omega}\ \sigma \leq \rho(n)$
so $q$ forces a contradiction, which is impossible.


Relation between end point of focal chord of parabola

Question: Consider a parabola $y^2 = 4ax$ , parameterize it as $x=at^2$ and $y=2at$, then it is found that if we have a line segment passing through focus, with each points having value of $t$ as $t_1$ and $t_2$ for the parameterization, then it must be that:
$$ t_1 \cdot t_2 = -1$$
Hope for hints.
Comment: Write the equation for chord passing through points $t_1,t_2$ and let it pass through $(a,0)$. Also, your coordinates are swapped. Points should be $(at^2,2at)$.
Comment: I got $ \frac{1}{t_1} + \frac{1}{t_2}=2$
Comment: You must have made some error. I get $t_1t_2=-1$
Answer: Chord passing through $(at_1^2,2at_1)$ and $(at_2^2,2at_2)$ is
$$y-2at_2=\frac{2at_1-2at_2}{at_1^2-at_2^2}(x-at_2^2)$$
$$y-2at_2=\frac{2}{t_1+t_2}(x-at_2^2)$$
It should pass through focus $(a,0)$
$$\Rightarrow -at_2=\frac{1}{t_1+t_2}\,a(1-t_2^2)$$
$$\Rightarrow t_1t_2=-1$$
Answer: Hint:
Let the parameters be $p,q$. So the eq of the line is $(y-2ap)(ap^2-aq^2)=(x-ap^2)(2ap-2aq)$. What point does this pass through so that it is a focal chord?
Comment: what parameterization have you used?
Answer: Working back from geometry makes everything supremely trivial, following blue's post, it must be that at the tangent vectors at end point of focal chord is perpendicular.
Our curve is given as $\gamma(y) = ( \frac{y^2}{4a},y)$, the tangent vector is given as: $\tau(y) = (\frac{y}{2a},1)$, let the two points we want be at height $(y_1,y_2)$, then due to tangents at end point being perpendicular:
$$ \tau(y_1) \cdot \tau(y_2)=0$$
Expanding everything out:
$$ y_1 y_2 = -4a$$
Now plugging in the parameterization, we find the parametric version of the result.


How to create a List message for whatsapp using Twilio

Question: How to create a List message for whatsapp using Twilio
How to create a List message for whatsapp using Twilio
Comment: Please read the [Tour](https://stackoverflow.com/tour) and [how to ask a good question](https://stackoverflow.com/help/how-to-ask). What did you already try and where are you stuck? StackOverflow is not a code writing service.
Answer: As of today, Twilio only supports templates with quick reply buttons or call to actions. This might be a good alternative if you have only a few options.

I know this is not perfect and hopefully there will be more message types in the future.


BIND resolved IP address into logfile

Question: I have a challenge where the log files are not recording the resolved IP address in the logged information. How is it possible to enable this? So the url and resolved IP address should be in the logfile. Here is the code:
Configuration:
logging {
    channel query_log {
    file "/var/log/named/query.log";
    severity info;
};
category queries { query_log; };

Current Log file:
04-Nov-2015 08:28:39.261 queries: info: client 192.168.169.122#59319: query: istatic.eshopcomp.com IN A + (10.10.80.50)
04-Nov-2015 08:28:39.269 queries: info: client 192.168.212.136#48872: query: idsync.rlcdn.com IN A + (10.10.80.50)
04-Nov-2015 08:28:39.269 queries: info: client 192.168.19.61#53970: query: 3-courier.sandbox.push.apple.com IN A + (10.10.80.50)
04-Nov-2015 08:28:39.270 queries: info: client 192.168.169.122#59319: query: ajax.googleapis.com IN A + (10.10.80.50) 04-Nov-2015 08:28:39.272 queries: info: client 192.168.251.24#37028: query: um.simpli.fi IN A + (10.10.80.50)
04-Nov-2015 08:28:39.272 queries: info: client 192.168.251.24#37028: query: www.wtp101.com IN A + (10.10.80.50) 04-Nov-2015 08:28:39.273 queries: info: client 192.168.251.24#37028: query: magnetic.t.domdex.com IN A + (10.10.80.50)
04-Nov-2015 08:28:39.273 queries: info: client 172.25.111.175#59612: query: api.smoot.apple.com IN A + (10.10.80.50)
04-Nov-2015 08:28:39.275 queries: info: client 192.168.7.181#45913: query: www.miniclip.com IN A + (10.10.80.50)

Desired Log file:
.... istatic.eshopcomp.com 184.108.40.206 ....
.... idsync.rlcdn.com 18.104.22.168 ....
.... 3-courier.sandbox.push.apple.com 220.127.116.11  ....
.... ajax.googleapis.com 18.104.22.168 ....
.... um.simpli.fi 188.8.131.52 ....
.... www.wtp101.com 220.127.116.11 ....
.... magnetic.t.domdex.com 188.8.131.52 ....
.... api.smoot.apple.com 188.8.131.52 ....
.... www.miniclip.com 126.96.36.199 ....

Assistance will be truly appreciated.
Comment: @kasperd, is there any news over that question? it interesting for me too
Answer: If you were actually the authoritative source, the config below should work with:
Configuration:
logging {
    channel query_log {
    file "/var/log/named/query.log";
    severity info;
    print-time yes;
    print-severity yes;
    print-category yes;
};
category queries { query_log; };
However, you are not an ISP or a domain service.  You are likely not authoritative and you yourself do not manage those records.  Unless you manually enter overrides in your bind database, it doesn't look like your local bind wants to get involved with logging someone else's response, if it can.
Comment: So is there an option to print resolved IP address? The once in the above example do not print the resolved IP address in the DNS server.
Comment: I updated my answer above since I originally made some assumptions that later proved not to be true.
Answer: Why don't you parse your logs asynchronously and issue the queries with a script?
If you have a caching DNS server, that would work without much load.

Otherwise passivedns may be what you want.
Also this might be what you are looking for.

BIND resolved IP address into logfile


When submitting a hidden form to pass variables, how can we prevent the next form from resending the data?

Question: I have a login form displayed always at the top right of my website. When an invalid username/password combination is found, a hidden form is generated based on the server response and submitted in order to redirect to a larger login (i.e. login.php)... When I submit my new attempt to login on the login.php login form after being redirected via the hidden form, the browsers warns "To display this page, Firefox must send information that will repeat any action (such as a search or order confirmation) that was performed earlier." Wierdly enough, this message is only displayed on successful logins ( correct username/password as per database ).
Here is the Javascript function that handles the servers response when attempting to login
handleLoginXML: function(xml){
        var loginValue = xml.getElementsByTagName('info')[0].firstChild.nodeValue;
        if(loginValue === "success"){
        location.reload();
        }
        if(loginValue === "failed") {
        this.post('?page=login', { login_error : 'Invalid Email/Password'});
        }
    },

Also, here is the post function that submits the hidden form on failed login
post: function(path, params, method='POST'){
        const form = document.createElement('form');
        form.method = method;
        form.action = path;
        for(const key in params) {
            if(params.hasOwnProperty(key)){
                const hiddenField = document.createElement('input');
                hiddenField.type = 'hidden';
                hiddenField.name = key;
                hiddenField.value = params[key];
            form.appendChild(hiddenField);
            }
        }

        document.body.appendChild(form);
        form.submit();
    }

How can I prevent the form on ?page=login from resending the hidden form data? Is it the way i'm dealing with successful logins that is the problem? Thanks
Comment: Both forms are using handleLoginXML
Comment: So when the second form submits successfully the page is being reloaded.. maybe I need to redirect this I suppose
Comment: If you login from the header the reload is fine
Answer: This is the problem right here location.reload();, it is reloading the page like hitting the refresh button.
An easy alternative is: window.location.href = window.location.href; That should redirect the user back to the same URL without resubmitting of the form.
Comment: On debugging this, the only problem I found was if somehow a user logs in on example.com/# this will redirect to example.com/# I submit the login and nothing happens but after removing the # the session shows up
Comment: @JustinHarris you can always do this `window.location.href = `?page=login';` that will redirect the user back to your login page. You can always redirect them really to any page like a member dashboard page etc..
Answer: you can also reset the form: document.getElementById("myForm").reset();


Inserting elements in a QSet and retrieving , removing the last item of the QSet

Question: I have the following dataset:
 QSet<QString> set;

I tried to insert 3 elements to the QSet.
set.insert("A");
set.insert("B");
set.insert("C");

After adding the above three elements,its showing the size of my QSet as 3, but total 16 elements are visible,among which 13 elements are being shown as Empty.
And every time,I  try to debug this, the element "A" is on the top of the list once and next time, "C" appears on the top of the list.
Due to this, I am not able to retrieve the last element of the QSet. I want to retrieve the element,which is inserted at the last to theQSet.
I Am using the following lines of code,for retrieving and removing the elements from QSet.
QString str1 = QString( *( set.end() - 1 ) ); //to get the last element

set.remove( *( set.end() - 1 ) ); //to remove the last element

I think,it has to do something with properly initializing my QSet, but I still could not figure out the problem exactly
I would be glad if someone can explain me better
Thanks in advance!
Comment: What do you mean by "16 elements are visible"? Where do you see these?
Comment: @Thomas: While debugging, I had a look at my QSet, it was displaying like this:  [0] emtpy, [1] empty,...., [2] "C",....[5] "A",......., [12] "B",....[16] Empty. Hope you understood
Comment: @Math_Enthusiast, probably you insert in your set something else too or it wasn't initially empty?
Answer: QSet does not store it's elements in any particular order. As you have noticed, the no particular order is not even stable between runs of your program. In a very real sense, there is not a "last element", which is why there is no front or back member
The order of insertion is not recorded anywhere. If you want to maintain the insertion order, you will need a SequenceContainer, such as std::vector or QVector.
Answer: QSet is based on Hash table and so unordered. Use QMap, if you need ordering by key.
Comment: In that case, QVector should be the choice as it gives better performance than QList and it always stores elements sequentially in memory. append on QVector is relatively fast and it typically allocates more memory than needed. So, it can grow without reallocating entire vector each time.
Comment: Then, I think, it is better to use QList right? Because,I just want to retrieve last element and then also remove the last element from the list. By, last element,I mean, newly added element in the list.
Comment: ah great.So,I will use QVector now. Is there any way to add only Different elements in QVector? I mean,if I have an element called "X" in my QVector.If I try to add "X" again, it is added again.Is there any way to ignore such cases,if element already exists? Any effective way?
Comment: Well if you prefer not to have duplicate entries then I would suggest to use QMap. It allows only one value per key, if you insert an element with already existing key then previous value will be erased.


Using VoiceOver to jump to internal links

Question: I am looking for a way to go from my navigational links using voice-over accessibility to jump to the internal part of the page that link I connected to.
For example:
I have a list of links on my left-hand side. One is for Forms. When I click on "Forms" my list of forms will populate to the right of that panel, and then if you click on a specific form, that Form will appear to the right of that panel. The page contains 3 panels with Navigation on the left, list in the middle, Form on the right.
Right now if I click on the Form link, I have to tab through my entire nav panel to get to the newly opened Forms list.
Are there some ARIA elements I am missing that will help tab directly into my Forms List from the Forms link?
Comment: It sounds like you need to solve the selection issue first and then the voice accessibility issue will solve itself.
Answer: There are two simple ways to do this.
Note that neither of the following ways need any aria to work, the aria in the following examples is purely for best practices when adding sections and headings to a page.
Option 1 - anchors
The first is using anchors pointing to ids on the page.
in your side bar
forms

main page section

Forms

Notice how I gave the page content a heading (pick an appropriate heading level) and then labelled the section with aria-labelledby. None of this is required to make this method work but it is a good practice.
The only thing you need to do is to make sure your href matches the ID of the heading.
However given that you are populating the forms on the right side of the page (I am assuming with an AJAX call) you may want to manually manage focus with JavaScript....
Option 2 - Use JavaScript and .focus()
If you are using JavaScript it is a similar principle, give the section heading an ID, but this time once the forms list has loaded set focus on the list heading.
html

forms

Forms

JavaScript

// start: however you have this implemented at the moment
const formsLink = document.querySelector("#getForms");

formsLink.addEventListener('click', function(e){
    e.preventDefault();
    get('yourURL').then((data) => {
        // populate the list
        list.update(data);
        // end: however you have this implemented at the moment

        // once the list is populated set focus on the heading (last thing to do after everything else is done)
        document.querySelector('#forms').focus();
    });

});

Notice how in this example the
 has a tabindex="-1".
We need this to allow programmatic focus. We use -1 so we can focus the heading via JavaScript but it does not get added to the page focus order (so you can't access it with Tab).


One Drupal site affecting another cloned site

Question: I have a weird situation with cloned site, I have copied the entire content from a production server, and made a different directory for testing environment. The steps I did to clone a site is:

Copied all the contents from the main folder /www/d7/ to new folder
/www/test/
Made a separate server config in nginx to browse the content from browser
Original site can be browsed via http://d7.example.com and the copied site can be browsed via http://test.example.com, the nginx have separate logs for both
Dumped the original database after flushing drupal cache, created new database called 'test', with new username 'test' and new password 'test', imported the dumped database to new database 'test'.
Changed the database connection parameter in the file /www/test/sites/default/settings.php to accumulate newly created database.

Now, when I put the production site in offline mode, the test site also goes to offline mode, how come this is possible ? The most weird thing is if I put the site to online mode from test site, the production site also goes to online mode. I even tried creating new database, new database user and changing the settings.php still same issue.
I tried installing different modules to different sites, and the installed modules shows in their respective sites.
Can anyone tell me what's going on here ?
Update with Answer:
As Clive commented below, I changed the memcached_storage settings in settings.php file to $conf['memcache_storage_key_prefix'] = 'test_site'; and I don't have any issues now.
Comment: If you have any special caching enabled in settings.php (e.g. Memcache) make sure you're specifying unique bins for each site
Comment: aye, might be memcached as you said. I copied contents from one site to another without changing the memcached settings... thank you for pointing this... I will change the memcached settings and inform again
Comment: @Clive, thank you very much for pointing towards memcached, it is working after changing the memcached bins for test site.
Comment: If you solved your problem you can answer your own question and accept the answer (after a period of time). That way this will appear as answered, and may help someone in the future with the same issue.
Answer: As beth, said in the comment, I am answering this, even after updating the question with answer.
The culprit was Memcached bin, since I am using memcahce_storage module for memcached, the bins of the main site and test site were same, hence, creating this confusion.
I edited the settings.php page of test site and changed the prefix for memcached for test-site as $conf['memcache_storage_key_prefix'] = 'test_site';, now everything is perfect !!!


Nested for loop in nodejs seems to be running asynchronously

Question: So I have two for loops, and one is nested inside another but the results they return seem to be running the first loop and returning its results than the nested loop. How could I make it run in a synchronous behavior?
For example, all the topicData gets printed in a row instead of printing one topicData and moving on to the nested for loop.
I'm not sure if this is the proper way to implement the async await. Any pointers would be appreciated. Thanks
exports.create = (event, context, callback) => {

  var topicTimestamp = "";
  var endpoint = "";

  sns.listTopics(async function(err, data) {
    if (err) {
      console.log(err, err.stack);
    } else {
      console.log(data);
      for (var topic in data.Topics){ //first loop
        //var topicData = "";
        //retrieve each topic and append to topicList if it is lakeview topic
        var topicData =  await data.Topics[topic].TopicArn;
        topicTimestamp = topicData.slice(22, 34); //get only the topic createdAt

        var params = {
          TopicArn: topicData //topicData
        };
        console.log("SUBS per" + params.TopicArn);

        //retrieve subscriptions attached to each topic
        sns.listSubscriptionsByTopic(params, async function(err, subscriptionData){
          console.log(subscriptionData);
          //console.log("SUBS per" + params.TopicArn);
          if (err) {
            console.log(err, err.stack); // an error occurred
          } else  {
            var endpointList = [];
            for (var sub in subscriptionData.Subscriptions) { //nested loop

              endpoint = await subscriptionData.Subscriptions[sub].Endpoint;

              console.log("ENDPOINT:: " + endpoint);
              endpointList.push(endpoint);
            }
          } // end of else listSub

          //put topic info into table
          var topicsParams = {
            TableName: tableName,
            Item: {
              id: uuidv4(),
              createdAt: timestamp,
              topicCreatedAt: topicTimestamp,
              topic: topicData,
              phoneNumbers: endpointList
            },
          };

          endpointList = [];  //reset to empty array

          dynamoDb.put(topicsParams, (error) => {...}

Comment: Use a promise interface (or create a promise wrapper if a promise interface doesn't already exist) for all your asynchronous operations and use `await` with those promises.  That will let you sequence `for` loops with asynchronous operations.  It will also make error handling much cleaner (which you don't really do a proper job of at all.
Answer: There are couple of issues here

You are trying to do callback style code in loops while you have promise methods available.
You could also do things in parallel using promise.all
Because of callback style the code is very complicated
You are awaiting where it is not required. For example in the callback

You can try to use this way
exports.create = async (event, context, callback) => {

  try {
    let topicTimestamp = "";
    let endpoint = "";
    const data = await sns.listTopics().promise();
    // eslint-disable-next-line guard-for-in
    for (const topic in data.Topics) { // first loop
    // var topicData = "";
    // retrieve each topic and append to topicList if it is lakeview topic
      const topicData = data.Topics[topic].TopicArn;
      topicTimestamp = topicData.slice(22, 34); // get only the topic createdAt

      const params = {
        "TopicArn": topicData // topicData
      };
      console.log(`SUBS per${ params.TopicArn}`);

      const subscriptionData = await sns.listSubscriptionsByTopic(params).promise();
      const endpointList = [];
      // eslint-disable-next-line guard-for-in
      for (const sub in subscriptionData.Subscriptions) { // nested loop
        endpoint = subscriptionData.Subscriptions[sub].Endpoint;
        console.log(`ENDPOINT:: ${ endpoint}`);
        endpointList.push(endpoint);
      }

      // put topic info into table
      const topicsParams = {
        "TableName": tableName,
        "Item": {
          "id": uuidv4(),
          "createdAt": timestamp,
          "topicCreatedAt": topicTimestamp,
          "topic": topicData,
          "phoneNumbers": endpointList
        }
      };

      // Similarly use dynamodb .promise functions here
    }
  } catch (Err) {
    console.log(Err);
  }
};

aws-sdk by default supports callback style. To convert them to promise you need to add .promise() at end.
At the moment this example is using for loop but you could do the same thing using Promise.all as well.
Hope this helps.


Implement the facebook connect on uiwebview using HTML5/JavaSCript for iphone sdk

Question: I need to implement the facebook connent on UIWebview using HTML5/ Javascript. Presently what I implemented is working fine on iphone safari but not in native application. Please Suggest. Thanks
Comment: Post your code, without it we can help you.
Answer: when the app loads up have it open a web view that point to a website that does what you want it to. see facebooks graph api documentation for web apps/websites
Comment: I need Facebook API to be work on my native application's webview. As I am using UIwebview than I am unable to implement iphone Graph API and I am working on native application, the website facebook connect not fuctioning.
Answer: I'm working on this kind of app also. I haven't finished it yet but after googling I found just this link that seems to work with UIWebView
http://suhinini.me/2011/05/24/embedding-facebook-social-comments-plugin-to-an-ios-application/
I've tried the HTML5 code on the comment plugin page but it doesn't work. The UIWebView just shows nothing.
I'm still looking for the best solution.
edited
Ok now I got my app working. What I did was creating a HTML file, containing the code from facebook comment plugin page, and put it in my project (I think this should work fine with file on server also). I use this
<code>[UIWebView loadHTMLString:baseURL:]
</code>
since my HTML file is local.
This is the facebook comment plugin page
https://developers.facebook.com/docs/reference/plugins/comments/


Java Download Large File Stops Unexpectedly

Question: I am downloading a large file (500MB to 1GB) from a java spring tomcat application.
The method below to download the file has been working great in the past, but today it started behaving weirdly. Only about the first 20MB - 50MB would get downloaded before the browser (chrome) thought the file was finished.
@RequestMapping(value = "/DownloadPDFSaved/{group}", method = RequestMethod.GET)
public void downloadGroup(@PathVariable String group, HttpServletResponse response) {
    if(!StringUtils.hasText(group)) {
        response.sendError(400, "Group is empty");
        return;
    }
    InputStream is = new FileInputStream(new File(getPDFZipFilePathForGroup(group)));
    IOUtils.copy(is, response.getOutputStream());
    response.flushBuffer();
}

In the tomcat logs, I can see a ClientAbortException, but it doesn't give too much useful information.
Do I need to set the content length? If so, would I set the content length to the size of the file? Can you see anything else that would be causing an issue downloading a large zip file?
Stacktrace
org.apache.catalina.connector.ClientAbortException: java.net.SocketTimeoutException
at org.apache.catalina.connector.OutputBuffer.realWriteBytes(OutputBuffer.java:389) ~[catalina.jar:8.0.9]
at org.apache.tomcat.util.buf.ByteChunk.flushBuffer(ByteChunk.java:426) ~[tomcat-util.jar:8.0.9]
at org.apache.tomcat.util.buf.ByteChunk.append(ByteChunk.java:339) ~[tomcat-util.jar:8.0.9]
at org.apache.catalina.connector.OutputBuffer.writeBytes(OutputBuffer.java:414) ~[catalina.jar:8.0.9]
at org.apache.catalina.connector.OutputBuffer.write(OutputBuffer.java:402) ~[catalina.jar:8.0.9]
at org.apache.catalina.connector.CoyoteOutputStream.write(CoyoteOutputStream.java:97) ~[catalina.jar:8.0.9]
at org.springframework.security.web.context.SaveContextOnUpdateOrErrorResponseWrapper$SaveContextServletOutputStream.write(SaveContextOnUpdateOrErrorResponseWrapper.java:457) ~[SaveContextOnUpdateOrErrorResponseWrapper$SaveContextServletOutputStream.class:3.2.5.RELEASE]
at org.apache.poi.util.IOUtils.copy(IOUtils.java:135) ~[IOUtils.class:3.11]
at web.controllers.TrialController.downloadGroup(TrialController.java:281) [TrialController.class:?]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.8.0_11]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[?:1.8.0_11]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:1.8.0_11]
at java.lang.reflect.Method.invoke(Method.java:483) ~[?:1.8.0_11]
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221) [InvocableHandlerMethod.class:4.1.6.RELEASE]
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137) [InvocableHandlerMethod.class:4.1.6.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110) [ServletInvocableHandlerMethod.class:4.1.6.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:776) [RequestMappingHandlerAdapter.class:4.1.6.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:705) [RequestMappingHandlerAdapter.class:4.1.6.RELEASE]
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) [AbstractHandlerMethodAdapter.class:4.1.6.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959) [DispatcherServlet.class:4.1.6.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893) [DispatcherServlet.class:4.1.6.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966) [FrameworkServlet.class:4.1.6.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:857) [FrameworkServlet.class:4.1.6.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:618) [servlet-api.jar:?]
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842) [FrameworkServlet.class:4.1.6.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:725) [servlet-api.jar:?]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291) [catalina.jar:8.0.9]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) [catalina.jar:8.0.9]
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) [tomcat-websocket.jar:8.0.9]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239) [catalina.jar:8.0.9]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) [catalina.jar:8.0.9]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) [FilterChainProxy$VirtualFilterChain.class:3.2.5.RELEASE]
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:118) [FilterSecurityInterceptor.class:3.2.5.RELEASE]
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84) [FilterSecurityInterceptor.class:3.2.5.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) [FilterChainProxy$VirtualFilterChain.class:3.2.5.RELEASE]
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113) [ExceptionTranslationFilter.class:3.2.5.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) [FilterChainProxy$VirtualFilterChain.class:3.2.5.RELEASE]
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103) [SessionManagementFilter.class:3.2.5.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) [FilterChainProxy$VirtualFilterChain.class:3.2.5.RELEASE]
at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113) [AnonymousAuthenticationFilter.class:3.2.5.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) [FilterChainProxy$VirtualFilterChain.class:3.2.5.RELEASE]
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:154) [SecurityContextHolderAwareRequestFilter.class:3.2.5.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) [FilterChainProxy$VirtualFilterChain.class:3.2.5.RELEASE]
at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45) [RequestCacheAwareFilter.class:3.2.5.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) [FilterChainProxy$VirtualFilterChain.class:3.2.5.RELEASE]
at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilter(BasicAuthenticationFilter.java:150) [BasicAuthenticationFilter.class:3.2.5.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) [FilterChainProxy$VirtualFilterChain.class:3.2.5.RELEASE]
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:199) [AbstractAuthenticationProcessingFilter.class:3.2.5.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) [FilterChainProxy$VirtualFilterChain.class:3.2.5.RELEASE]
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:110) [LogoutFilter.class:3.2.5.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) [FilterChainProxy$VirtualFilterChain.class:3.2.5.RELEASE]
at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:50) [WebAsyncManagerIntegrationFilter.class:3.2.5.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [OncePerRequestFilter.class:4.1.6.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) [FilterChainProxy$VirtualFilterChain.class:3.2.5.RELEASE]
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87) [SecurityContextPersistenceFilter.class:3.2.5.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) [FilterChainProxy$VirtualFilterChain.class:3.2.5.RELEASE]
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192) [FilterChainProxy.class:3.2.5.RELEASE]
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160) [FilterChainProxy.class:3.2.5.RELEASE]
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:344) [DelegatingFilterProxy.class:4.1.6.RELEASE]
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:261) [DelegatingFilterProxy.class:4.1.6.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239) [catalina.jar:8.0.9]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) [catalina.jar:8.0.9]
at web.spring_config.CaseInsensitiveRequestFilter.doFilterInternal(CaseInsensitiveRequestFilter.java:23) [CaseInsensitiveRequestFilter.class:?]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [OncePerRequestFilter.class:4.1.6.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239) [catalina.jar:8.0.9]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) [catalina.jar:8.0.9]
at org.apache.logging.log4j.core.web.Log4jServletFilter.doFilter(Log4jServletFilter.java:66) [Log4jServletFilter.class:2.0-beta9]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239) [catalina.jar:8.0.9]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) [catalina.jar:8.0.9]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219) [catalina.jar:8.0.9]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106) [catalina.jar:8.0.9]
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:503) [catalina.jar:8.0.9]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:136) [catalina.jar:8.0.9]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79) [catalina.jar:8.0.9]
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610) [catalina.jar:8.0.9]
at org.apache.catalina.valves.RemoteIpValve.invoke(RemoteIpValve.java:676) [catalina.jar:8.0.9]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88) [catalina.jar:8.0.9]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:526) [catalina.jar:8.0.9]
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1078) [tomcat-coyote.jar:8.0.9]
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:655) [tomcat-coyote.jar:8.0.9]
at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:222) [tomcat-coyote.jar:8.0.9]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1566) [tomcat-coyote.jar:8.0.9]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1523) [tomcat-coyote.jar:8.0.9]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [?:1.8.0_11]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [?:1.8.0_11]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-util.jar:8.0.9]
at java.lang.Thread.run(Thread.java:745) [?:1.8.0_11]
Caused by: java.net.SocketTimeoutException
at org.apache.tomcat.util.net.NioBlockingSelector.write(NioBlockingSelector.java:134) ~[tomcat-coyote.jar:8.0.9]
at org.apache.tomcat.util.net.NioSelectorPool.write(NioSelectorPool.java:173) ~[tomcat-coyote.jar:8.0.9]
at org.apache.coyote.http11.InternalNioOutputBuffer.writeToSocket(InternalNioOutputBuffer.java:139) ~[tomcat-coyote.jar:8.0.9]
at org.apache.coyote.http11.InternalNioOutputBuffer.addToBB(InternalNioOutputBuffer.java:197) ~[tomcat-coyote.jar:8.0.9]
at org.apache.coyote.http11.InternalNioOutputBuffer.access$000(InternalNioOutputBuffer.java:41) ~[tomcat-coyote.jar:8.0.9]
at org.apache.coyote.http11.InternalNioOutputBuffer$SocketOutputBuffer.doWrite(InternalNioOutputBuffer.java:320) ~[tomcat-coyote.jar:8.0.9]
at org.apache.coyote.http11.filters.ChunkedOutputFilter.doWrite(ChunkedOutputFilter.java:118) ~[tomcat-coyote.jar:8.0.9]
at org.apache.coyote.http11.AbstractOutputBuffer.doWrite(AbstractOutputBuffer.java:257) ~[tomcat-coyote.jar:8.0.9]
at org.apache.coyote.Response.doWrite(Response.java:492) ~[tomcat-coyote.jar:8.0.9]
at org.apache.catalina.connector.OutputBuffer.realWriteBytes(OutputBuffer.java:384) ~[catalina.jar:8.0.9]
... 86 more

Comment: Post the stack trace in your question. Always.
Comment: Have you tried with browsers other than Chrome?
Comment: Yes same issue with IE and FireFox. Just seems to be this one file...
Comment: Very strange. I've never heard of a socket timeout exception in a write in Java. Also curious that it comes from Coyote code and not the JDK.
Answer: Adding the content-length header seems to fix the problem. I am guessing that the browser was cutting the download short without the header and that was causing the ClientAbortException.
Here is the updated and working code:
@RequestMapping(value = "/DownloadPDFSaved/{group}", method = RequestMethod.GET)
public void downloadGroup(@PathVariable String group, HttpServletResponse response) {
    if(!StringUtils.hasText(group)) {
         response.sendError(400, "Group is empty");
        return;
    }

    File zipFile = new File(getPDFZipFilePathForGroup(group));
    //set content-length header
    response.setHeader("Content-Length", Long.toString(zipFile.length()));
    InputStream is = new FileInputStream(zipFile);
    IOUtils.copy(is, response.getOutputStream());
    response.flushBuffer();
}


Action of $GL_2(\mathbb R)$ on the space of lattices

Question: A lattice in $\mathbb C$ is an abelian subgroup of $\mathbb C$ isomorphic to $\mathbb Z^2$ that generates $\mathbb  C$ over $\mathbb R$. Define on the space $M$ of lattices in $\mathbb C$ a structure of smooth manifold as follows. Define a transitive action of $GL(2,\mathbb R)$ on $M$, find a stabilizer of a certain $x \in M$ and verify that it is a closed Lie subgroup. What is the dimension of $M$.
I do not really see how the action need to be defined. Any explanation or clarification of this would be helpful.
Comment: Your title question has complex numbers it it, which makes no sense.
Comment: The action is the action of $GL_2(\mathbb R)$ on the additive group $\mathbb C.$ It will send any lattice to a lattice.
Comment: Is $C$ the complex numbers?
Comment: Yes @Thomas Andrews
Comment: It's not clear how this makes $M$ a manifold.
Answer: Considering the basis $\{1,i\}$ of $\mathbb{C}$, a lattice $\Gamma$ can be obtained as the free abelian group $\left\langle\{A_\Gamma(1),A_\Gamma(i)\} \right\rangle_{\mathbb{Z}}$ generated by the images of $1$ and $i$ through a matrix $A_\Gamma\in GL_2(\mathbb{R})$. The stabiliser of a lattice $\Gamma$ is the group $ GL_2(\mathbb{Z})$. The latter group acts on $GL_2(\mathbb{R})$ via the left action
$$
GL_2(\mathbb{Z})\times GL_2(\mathbb{R})\rightarrow GL_2(\mathbb{R})
\qquad
(Z,A)\mapsto Z\,A.
$$
The obtained quotient $GL_2(\mathbb{R})/GL_2(\mathbb{Z})$ is said "set of the invariant geometric lattices" and it is the $M$ you are looking for. It is a manifold of dimension $n^2$ giving in our case $\dim(M)=4$.
Comment: This a consequence of the definition of lattice. Let $\{v_1,v_2\}$ be a basis of the lattice $\Gamma$. Then, every element $\gamma\in\Gamma$ can be written as $\gamma=n_1\,v_1+n_2\,v_2$ with $n_1,n_2\in\mathbb{Z}$. Now, pick up another basis $\{w_1,w_2\}$ and let us denote $n_{ij}\in\mathbb{Z}$ the coordinates of $w_i$ wrt to initial basis. This gives you a transformation matrix belonging to $_2(\mathbb{Z})$.
Comment: This is related to the fact that $GL_2(Z)$ is a discrete subgroup
Comment: Thanks!. You mean that $A_{\Gamma}$ acts on $(1,0)$ and $(0,i)$ as column vectors? Why does the stabilizer equal $GL_2(Z)$?
Comment: Yes, $A_\Gamma$ acts like that
Comment: why is the dim of $M=GL_2(R)/GL_2(Z)=2^2$?


Proof that $1-\frac12+\frac13-\frac14+\dots=\ln2$

Question: Proof that $\displaystyle 1-\frac12+\frac13-\frac14+\dots=\ln2$.
I have read this answer but I don't understand the fifth line.
\begin{align*}
S_{2n}&=1-\frac12+\frac13-\frac14+\dots+\frac1{2n-1}-\frac1{2n}
\\&=\left(1+\frac13+\dots+\frac1{2n-1}\right)-\left(\frac12+\frac14+\dots+\frac1{2n}\right)
\\&=\left(1+\frac12+\frac13+\dots+\frac1{2n}\right)-2\left(\frac12+\frac14+\dots+\frac1{2n}\right)
\\&=\left(1+\frac12+\frac13+\dots+\frac1{2n}\right)-\left(1+\frac12+\frac13+\dots+\frac1n\right)
\\\color{gray}{[\text{ why? }]}\quad&=[\ln 2n+\gamma+o(1)]-[\ln n+\gamma+o(1)]
\\&=\ln2+o(1)
\end{align*}
when $n\to\infty$, with $\gamma=\displaystyle\lim_{x\to\infty}\left(1+\frac12+\frac13+\dots+\frac1n-\ln n\right)$.
Otherway, $S_{2n+1}=S_n+\displaystyle\frac{1}{2n+1} \implies \lim_{n\to\infty}S_{2n+1}=\lim_{n\to\infty}S_{2n}=\ln2$
Comment: This is a "well known fact" (for certain definitions of "well known"). The idea is that we can approximate $\sum_{i \leq n} \frac{1}{i}$ by $\ln(n)$. In fact, we can do it to relative error $\gamma$, the so called "Euler-Mascheroni Constant". You can read more on the wikipedia page for [harmonic numbers](https://en.wikipedia.org/wiki/Harmonic_number#Calculation).
Comment: Thank you. This information's amazing.
Answer: This proof uses the fact that $\lim_{n\to\infty} \left ( \left(\sum_{k=1}^n \frac{1}{k}\right) - \ln n\right )$ converges to a particular value, $\gamma\approx0.577...$ By using the definition of a limit, we can write:
$$
\gamma = \left(\sum_{k=1}^n \frac{1}{k}\right) - \ln n + \epsilon
$$
Where $\epsilon$ can be made arbitrarily small by making $n$ larger and larger. (Values that behave this way can also be denoted by "$o(1)$")
Comment: Thank you. I understood.


Cannot initialize type with a collection initializer because it does not implement 'System.Collections.IEnumerable'

Question: I have 3 entities for main menus. and sub menus. I created menu view model.
My Entities:
MainMenu.cs:
public UstMenuler()
{
    AltMenuler = new HashSet<AltMenuler>();
}

public int ID { get; set; }
public string Name { get; set; }
public bool AktifMi { get; set; }
public int YetkiID { get; set; }
public string ControllerName { get; set; }
public string ActionName { get; set; }
public virtual Yetkilendirme Yetkilendirme { get; set; }
public virtual ICollection<AltMenuler> AltMenuler { get; set; }

SubMenu.cs:
public partial class AltMenuler
{
    public AltMenuler()
    {
        UstMenuler = new HashSet<UstMenuler>();
    }

    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int ID { get; set; }
    public int? YetkiID { get; set; }
    public string Name { get; set; }
    public string ActionName { get; set; }
    public string ControllerName { get; set; }
    public virtual Yetkilendirme Yetkilendirme { get; set; }
}

MyViewModel:
public class MenuViewModel
{
    public UstMenuler UstMenuler { get; set; }
    public AltMenuler AltMenuler { get; set; }
}

My Controller:
dbContext = new MarkettingDbContext();

int sessionYetkiID = (int)Session["yetkiID"];
MenuViewModel menuler = new MenuViewModel();

var query = (from menu in dbContext.UstMenuler
             where (menu.YetkiID == sessionYetkiID)
             select new MenuViewModel
             {
                 menuler.UstMenuler.ID = menu.ID,
                 menuler.UstMenuler.Name = menu.Name,
                 menuler.UstMenuler.YetkiID = menu.YetkiID,
                 menuler.UstMenuler.ControllerName = menu.ControllerName,
                 menuler.UstMenuler.ActionName = menu.ActionName
             }).ToList();

I am getting error when I execute my query. For example my sessionID is 1, I want to take my main and submenus.
Comment: Please include more details on your error messages.
Answer: The problem is your object initializer:
select new MenuViewModel
{
    menuler.UstMenuler.ID = menu.ID,
    menuler.UstMenuler.Name = menu.Name,
    menuler.UstMenuler.YetkiID = menu.YetkiID,
    menuler.UstMenuler.ControllerName = menu.ControllerName,
    menuler.UstMenuler.ActionName = menu.ActionName
}

Firstly you're using menuler in the object initializer, and I'm not sure why. Next, you're trying to assign to subproperties, which even if it did compile, would result in a NullReferenceException. Collectively, that's basically not what you want to do :)
Instead, I'd use one of the two options below.
If you're happy to just copy the UstMenuler reference from the menu parameter into the new view model instance, you can do that really easily:
select new MenuViewModel { UseMenuler = menu }

Or if you want to create a new UstMenuler and copy properties from menu:
select new MenuViewModel
{
    UstMenuler = new UstMenuler
    {
        ID = menu.ID,
        Name = menu.Name,
        YetkiID = menu.YetkiID,
        ControllerName = menu.ControllerName,
        ActionName = menu.ActionName
    }
}

Either way, you don't need your menuler variable which you appear not to be using anywhere else.
As it sounds like you're using LINQ to Entities, it sounds like you may want to separate the database query part from the projection part. The simplest way to do that in your case is to avoid the query expression syntax, so you can call AsEnumerable easily. So for example:
var query = dbContext.UstMenuler
    .Where(menu => menu.YetkiID == sessionYetkiID)
    .AsEnumerable() // Do the projection in-process
    .Select(menu => new MenuViewModel
                    {
                        UstMenuler = new UstMenuler
                        {
                            ID = menu.ID,
                            Name = menu.Name,
                            YetkiID = menu.YetkiID,
                            ControllerName = menu.ControllerName,
                            ActionName = menu.ActionName
                        }
                    })
    .ToList();

Comment: Hello Daisy

I tried your first solution I am getting this error on my layout page;

Error executing child request for handler 'System.Web.Mvc.HttpHandlerUtil+ServerExecuteHttpHandlerAsyncWrapper'.

I tried your second solution on my controller ;

The entity or complex type 'MVC.UstMenuler' cannot be constructed in a LINQ to Entities query.
Comment: @user9582479: This is the problem with only knowing part of your context... we didn't know what LINQ provider you were using at all. I can't tell what's wrong with the first example just based on "Error executing child request" - you'd need to get a more detailed exception. I'll edit to give a "safer" version though.
Comment: @user9582479: I've added an extra sample at the bottom of my answer.
Comment: Daisy ;

select new MenuViewModel { UseMenuler = menu }

It is okey :)

How can I take submenus relational main menu ?
Comment: @user9582479: I'm afraid I don't understand what you're asking, but that sounds like it should be in a new question anyway.


Split plot design with psudo replicates

Question: I am working on a project and need to analyze data that I know is an example of a split plot design but I am having trouble setting the model up correctly.
Here's the situation:
A bakery is testing cookies.  They are interested in how sugar levels and freshness impact taste ratings (on a scale of 1 -10).  They bake cookies at three sugar levels (1/2 of what the recipe calls for, the regular amount, and double what the recipe calls for) and hand out 5 cookies to 5 random customers on each of 3 days (the day the cookies are baked - day 1, the following day - day 2, and the following day - day 3).  The bakery bakes 9 batches of cookies and each batch is randomly assigned to one of the 3 sugar levels.  So we have information on 135 cookie ratings.
I know that the 5 cookies per batch are psudoreplicates so I averaged those to come up with 3 average taste ratings per batch - one for each freshness level (day 1, day 2, and day 3).
I am trying to analyze this using a mixed model with average taste rating as a response variable, sugar level and freshness as random factors and batch(sugar level) as a covariate.  But my model isn't coming out correctly.  Thus far I am working in Minitab but I could also use SAS.
Comment: You should use the raw data, not be averaging, I think. Maybe start out with some graphics. Can you post (a link to) the data?
Answer: You should model the raw data as is, not replace by averages. And, this are not really pseudoreplicates, the five cookies are given to five different persons, yes? And, as the response is the ratings, not some measured characteristics of the cookies, the variation in the ratings is what is relevant.
Before going into the split-plot model. some comments on the design.
Design of experiments for food sensory research is a very specialized field, some links. By only asking some persons about giving the product some rating, how do you know they interpret/use the scale the same way? Maybe it would have been better to ask some more specific questions and even better a design where the same experimental persons where asked of comparing/evaluating different variants of the cookies ...
So you have a data file with 135*5=675 observations, in a format something like:
rating    batch   level    day
  .         1       1       1
  .         1       1       1
  .
  .
  .
  .         1       1       2
  .

where rating is a numerical variable, the others are factors. Batch with 9 levels, level with 3 (sugar) levels, day with 3 levels.
There is a nesting structure batch/day and we model level (the focus variable) as a fixed effect. Maybe we are also interested in day as a fixed effect. I do not know about SAS but in R with package lme4 we could say:
library(lme4)
mod  <-  lmer(rating ~ level + day + (1 | batch/day), data=your_data_frame)

The notation | batch/day can be read within batch, and then for each batch, within day, and the 1 before it stands for a constant. So gives a set of random constants with that structure.
There are some similar questions, so look at split-split plot design with unbalanced repeated measures in lme4 or nlme (SAS translation),   Split plot in time mixed-effect model in R,    Cheat Sheet ANOVA Alphabet Soup & Regression Equivalents
EDIT

Trying to answer the question in the comment by @MichiganWater. It seems to me that pseudoreplication here maybe depends on the goal of the analysis. If the goal is to ascertain some objective property of the cookies, then the five people trying cookies from the same batch is pseudoreplication. But the OP speaks about taste ratings without further explication, and taste is not an objective property of the cookies, it is an interaction between cookie and the person eating it. As an example, I, as part of my Asberger, have sense hypersensitivity, and for me food tastes the same if cooked without salt as with (unless really to much). That would make me an outlier in a sense experiment, probably. I don't know how large the variation in subjective taste is, but it is there. So if subjective felt taste is the objective, then variation between persons should be relevant.
But, using the mixed model analysis I proposed, maybe this does not make a large difference. The mixed model analysis estimates the variance at each level (block(level)/day/person), and that information could be interesting itself. But in testing the effect of level, only the variance from the level below would be used. I quote from Casella "Statistical Design" (page 5)

This is an example of a nested design, where Tanks are nested in Diets
  and Fish are nested in Tanks. In such designs the testing is
  straightforward – the nested factor provides the error mean square for
  the factor in which it is nested. (See Section 1.5.) Of course, we can
  test the significance of tanks using MS(Tank)/MS(Fish), but this is
  wasted effort. There is typically no interest in assessing the
  significance of tanks; they are merely there to hold the fish!

So in using the modern mixed model formulation, maybe the question about pseudoreplication is taken care of automatically? I would like to look at this with a simulated example, but that will have to wait. Will think more about this. But anyhow, the original data should be used, and not the reduction to summaries, since they are more informative.
Comment: (1.25 years later!) I just ran across this question today on a web search and thought "this seems oddly familiar"...then I saw the answers, haha!  For some reason I missed that you added more in an Edit, responding to my question.  Thanks for doing that.  I want to spend more time thinking through what you've said, but in the meantime I noticed you said 675 observations.  I figured only 135 observations (9 batch * 3 day * 5 people) so I'm wondering if there's a disconnect here regarding the design proposed by the OP? (3 batches/sugar level)
Comment: Hi kjetil. I disagree that the 5 cookies are not pseudoreplicates.  I have given more explanation in my Answer to Megan, but I'd like to know whether you agree or disagree, given my rationale.  Thanks.
Answer: I know nothing of SAS, but if you are using Minitab to try and analyze this dataset, the first thing to note is that Batch is not a covariate according to Minitab's definition (a covariate is a continuous variable).  Batch is a factor.  In addition, Batch will be nested within Whole Plots.  I've given some code below that should generate the design with some simulated (fake) data, along with the analysis using Minitab 18's General Linear Model tool, which I assume you're using.  See if that helps you to understand how to structure things.  If you're not used to using session commands, let me know and I'll put more description around using the GUI.
I disagree with kjetil regarding whether the 5 cookies should be considered pseudoreplicates.  I think they are pseudoreplicates.  Before going any further I do want to acknowledge that this gets complicated real quick because of the 5-cookies-to-5-different-people, so it's certainly an easy mistake to make. I'm pretty sure I'm correct, as I'll explain below, but I'm certainly open to arguments the other way.
Now, on to the issue of pseudoreplication.  Because the five cookies were produced by the same process at the same time, any variations in the process steps will be common to those five cookies (actually to all 15 cookies that are baked together).  Let's say that the oven lost power for a short period of time while it was baking batch #4.  The variation would be common to all 5 cookies, and so they are not independent of each other.  Those cookies baked together do not capture the batch-to-batch variation, which would be required to consider the cookies independent.  The only way to make them independent would be to bake each individual cookie by itself.  That's why I see them as pseudoreplicates.
What about the fact that each cookie is given to a different person? To me the only thing that makes sense is to consider that as simply part of the measurement noise, and it's just rolled into the uncertainty around your estimates (e.g. the confidence interval widths).
For anyone reading this that doesn't have access to Minitab, the table of factors and response should look like this, except that I can't get the headers to line up with the columns:
WP  SugarHTC    Day AvgResponse
1   0.5 1   3.71173
1   0.5 2   6.25209
1   0.5 3   3.81954
2   1.0 1   4.58830
2   1.0 2   5.13217
2   1.0 3   5.15029
3   2.0 1   4.78808
3   2.0 2   6.75095
3   2.0 3   4.19827
4   0.5 1   5.76470
4   0.5 2   4.94079
4   0.5 3   5.97733
5   1.0 1   7.28974
5   1.0 2   3.73834
5   1.0 3   4.80945
6   2.0 1   5.29424
6   2.0 2   6.84974
6   2.0 3   4.09316
7   0.5 1   6.11799
7   0.5 2   3.77689
7   0.5 3   4.33160
8   1.0 1   4.17665
8   1.0 2   3.73358
8   1.0 3   6.10543
9   2.0 1   4.61165
9   2.0 2   5.01459
9   2.0 3   6.66854

Also, you could analyze the raw data, assuming you get the multilevel structure correct, but as long as the number of cookies in that lowest level (the groups of five) is identical for each treatment condition, then you can use the averages and the results of the analysis will be the same.
Stephen Senn recently covered this tangentially in this article:

Now consider a second equivalent analysis of this. This just uses the average at baseline and outcome per hall. In other words, it is based on 20 pairs of values (baseline and outcome) not 200. This analysis produces the table in Figure 2. Note that the result is exactly as before, showing the irrelevance of the variances and covariances within halls. That is to say, that although the mean squares change, because now based on averages of 10 students per hall, the ratio of the term for treatment to its residual is the same and so are all inferences. The equivalence of summary measure approaches to more complex models for certain balanced cases is well known (Senn, S. J. et al., 2000).

https://errorstatistics.com/2018/11/22/stephen-senn-on-the-level-why-block-structure-matters-and-its-relevance-to-lords-paradox-guest-post/
Here is the code for running Minitab's session commands:
name c1 "WP" c2 "SugarHTC" c3 "Day" c4 "AvgResponse"

Set 'WP'
  1( 1 : 9 / 1 )3
  End.
Set 'SugarHTC'
  3( 0.5 1 2 )3
  End.
Set 'Day'
  9( 1 2 3 )1
  End.

Random 27  'AvgResponse';
  Normal 5 1.0.

GLM;
  Response 'AvgResponse';
  Nodefault;
  Categorical 'WP' 'SugarHTC' 'Day';
  Nest 'WP'('SugarHTC');
  Random 'WP';
  Terms 'WP' 'SugarHTC' 'Day' 'SugarHTC'*'Day';
  TMethod;
  TAnova;
  TSummary;
  TCoefficients;
  TEquation;
  TFactor;
  TEMS;
  TVariance;
  TDiagnostics 0;
 GFOURPACK.

One final thing to consider is the distribution of the response (at each treatment condition).  Both the raw data and the averages will be bounded between the upper and lower limits of the scale used for the ratings, and that could introduce problems with assuming Normality for the analysis. For cookies made at the normal sugar level, on Day 1, are they almost all at the highest rating, or at least very close to it? Or for 2x sugar and 3 days later, are they all near the bottom of the ratings?  If so, you might have issues with floor and ceiling effects.  If that's the case, I'd recommend opening a new Question to elicit responses from others who are more familiar with how to deal with that and give advice specific to your situation.

Split plot design with psudo replicates


why does sudo su; su tomcat doesn't switch to tomcat user?

Question: In Redhat linux. from my user if I issue command
sudo su -> changes to root
su tomcat --> changes to tomcat user
Why does tailing the commands in single line doesn't work?
sudo su; su tomcat --> stil in root. Doesn't switch to tomcat
Answer: The commands
sudo su; su tomcat

are two commands. The shell will run the first and when it completes it will run the second. Note that the shell does not pass the second command as an argument to the first command.
When you exit the first command it will run the second
sudo su ; su tomcat
[sudo] password for iain:
root@host:iain]$ exit
exit
Password: <---- this is the prompt from the second su command.

You can use sudo to transition to the tomcat user directly
sudo -u tomcat <some command>

or use -s to get a shell e.g.
whoami
iain
sudo -s -u tomcat
whoami
tomcat

Answer: When you divide your sudo and su commands with a ; sign the su will be executed after the sudo has finished. I.e. in that case you execute the su as your normal user.
To achieve your desired result try to execute the whole in one command:
sudo su - tomcat

Comment: And you might want to make sure you inherit `tomcat`'s environment as well; try `sudo su - tomcat`.
Comment: @MadHatter: Yes, of course ;) - I changed my answer
Comment: You already had my +1, can't add another - sorry!


Regular Expression Using Ant

Question: I am new to ant and I am trying the following :-
I have a file called info.2013.tar.gz .It is in a location memo.dir . I have to pass this file into a variable in ant and write a regular expression to get the year i.e. 2013 in an ant target .
I have been working on perl and I know how to do it using perl ,but I have no clue how to do that using ant.
Can anyone please help me .
<target name = "new" depends="load-props,classpath">
          <fileset dir = "${memo.dir}">
            <include name = "*.tar.gz"/>
          </fileset>
</target>

I tried something like this but it did not help .
Answer: <pathconvert property="year">
    <mapper type="regexp" from="([^.]+)[.]tar[.]gz" to="\1"/>

    <path>
        <fileset dir="${memo.dir}">
            <include name="*.tar.gz"/>
        </fileset>
    </path>
</pathconvert>

<echo>year: ${year}</echo>

Comment: Can you please explain me the regex you have used?How do I get info from info.2013.tar.gz?
Answer: You may use script task with builtin (since JDK 6) javascript engine, f.e. :
<project>

<macrodef name="splitstring">
  <attribute name="str" />
  <attribute name="by" />
  <attribute name="index" />
  <attribute name="result" />
  <sequential>

  </sequential>
</macrodef>

 <fileset dir = "${memo.dir}" id="whatever">
  <include name = "*.tar.gz"/>
 </fileset>

 <splitstring by="." str="${toString:whatever}" index="1" result="foobar" />

 <echo>$${foobar} => ${foobar}</echo>

</project>

output :
[echo] ${foobar} => 2013

Note that project.setProperty() may overwrite an existing property with the same name, otherwise use project.setNewProperty(), so :
<property name="foobar" value="value"/>

<splitstring by="." str="${toString:whatever}" index="1" result="foobar" />

would result in :
[echo] ${foobar} => value

Regular Expression Using Ant


How can a metronome with a bell help with my practice?

Question: I ordered a pretty standard mechanical Wittner metronome, the cheapest I could find plastic/no bell. But after I ordered it I realized there are metronomes that have a bell, so it got me thinking about if I should've gotten one with a bell. :/
A bell is used to accent the first beat of a 4/4 time, 3/4 time, etc.  But I'm still iffy if it's needed in practice. But what are some situations where this could help vs a normal metronome that only has tempo?
Comment: Always better with a bell.
Answer: Different people have different feelings about how to use a metronome.
I personally don't like the bell when I'm using a metronome, and always turn it off. I think its usefulness is limited, since I don't think that the best use of a metronome is to teach you how to count measures.
Metronomes are best used to make sure that your tempo in a piece is consistent, not speeding it up in some places and slowing it down in others. This is especially useful when slow practicing to learn a piece; it's very easy to speed up easier parts and slow down harder parts as you are learning, and these changes can be hard to unlearn as you speed up your work.
The metronome tick should also be seen as a fairly rough guideline. Music naturally speeds up and slows down, has pauses, and so on, for dramatic effect. Too strict adherence to the metronome makes the music dull: if a critic calls your music "metronomic" it isn't a compliment!
Comment: It depends on whose "theory" you're using. The use for a bell is to tell you when beat 1 of a measure occurs. I don't find that useful, personally; I don't need the help and the bell is distracting. It might be useful for complete beginners who haven't yet internalized a count, but I wouldn't recommend using it to my students.
Comment: so theoretically is there a use for the bell? why would someone need to know when a measure starts.
Answer: A bell reminds you where ONE is - in music that sticks to the same time signature throughout anyway.   But if you're playing sloppily enough to get a whole beat out you don't need a bell, you need to practice slower.
There are free 'apps' that will do everything the Wittner can, and more.  But there's something nice about a mechanical device, isn't there!  :-)
Comment: It doesn't *have* to remind you where ONE is, in the same way that you can use a metronome to have the click in between beats, heck, whatever you want. But most would use it initially to help with beat ONE. It's also useful for players starting on 5/4 time.
Comment: I'd forgotten about that, but now you mention it, it does ring a bell...
Comment: I want one of these!  https://www.wittner-gmbh.de/metronome_tiere_e.html
Comment: I worry about you! Would you like my psychiatrist's number..? He's good. Says he'll have me cured in less than 20 yrs.
Comment: The Wittner models with bell seem to offer 2, 3, 4 and 6 divisions .  Not 5.    https://www.wittner-gmbh.de/pdf/maelzel_gebrauchsanleitung.pdf
Comment: It's simple: you set it for 4, and the ping is on beat 1, 1st bar, beat 2, 2nd bar, beat 3, 3rd bar - see the pattern? There are other ways, too... Like I said, ping doesn't *have* to be beat ONE!
Comment: And it doesn't have to ping at all!
Comment: I have a lovely electronic one which seems to let me choose **any** time signature, and use whatever tone beeps I want as my accents. It's very cool.
Comment: @DoktorMayhem - as a collector of metronomes (there must be a term for that) I need to know make and model. Thanks!
Comment: I have a free mobile app that does tons of great stuff. I like the appeal of a mechanical metronome but why spend the cash when you can use an app? Also sort of annoying that the bell rings at a pitch. Isn't that annoying when you are playing a key that is dissonant compared to the bell.
Comment: I have a METAL metronome, with stove enamel finish.  Traditional pyramid design.  It makes a very unpleasant sound.
Comment: Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/80845/discussion-on-answer-by-laurence-payne-how-can-a-metronome-with-a-bell-help-with).
Answer: Actually I find electronic metronomes much more convincing. They frequently offer lots of choices, not only emphasizing the first beat of a bar, but beyond the normal second level also a third level for triplets etc. Single-step beat increment is easy. They also provide a knob for volume adjustment, a headphone plug or an optical-only mode, just flashing LEDs. So the disadvantages boil down to requiring batteries and needing some effort to choose to find the most convenient device (maximum volume is an interesting property).
Comment: yes but electronic metronomes have no soul
Answer: Absolutely do not get a mechanical metronome, other than as a piece of art for your studio.
Aside from the flexibility of electronic ones -- some can provide all sorts of sub-beat accent patterns --- there isn't a mech in the world that doesn't lose its symmetry on the slightest tilt to its base, or when a little dirt sneaks into the guts.
Comment: @foreyez You still need to take Carl's point into account. Try tilting it a little to one side and watch the effect. Then see if you can get the click to be absolutely accurate. It isn't easy. Also, don't love it too much. Nobody else wants to hear your "little drummer" when you're playing for them!
Comment: I disagree, I just got my mechanical one and I'm completely sold on how useful this is. It's like a little drummer beside my instrument, I love it. I like watching the pendulum swing.
Comment: @BobRodes this is mainly for practice. I'm thinking for performing/recording to get a soundbrenner pulse which is a silent metronome watch that vibrates.
Comment: @foreyez I would repeat that "metronomic" is not a compliment. :) I wouldn't use a metronome of any sort in performance, any more than I would go bike riding on a bike with training wheels. Metronomes are good for spot checking your internalized ideas about tempo, and are not good for keeping your sense of tempo for you.
Comment: @BobRodes that's a good point probably ditch it when I get more advanced we'll see.
Comment: @foreyez Yeah, probably. I would resist using one in performance, and that pulse watch probably wouldn't be an investment you'd be happy with.
Comment: @BobRodes just got the pulse watch. love this! great for recording and live performance. my mechanical metronome would make that ticking sound in recording when I recorded myself so this is handy.
Comment: @foreyez if your pulse watch has a bell thing please don't use it, you'll have to wait so long after making an error in performance to continue!
Comment: @kat haha thanks. it doesn't have a bell, it uses vibrations. but after using a metronome I've realized I just need tempo most of the time anyway.
Comment: Having played for many years, I only use mechanical metronomes. To me, the electronic ones are nice little gadgets, but most always sound hideous and, frankly, most professional pianists I know personally will describe the difference as being akin to an electric piano versus a 'real' piano. One does not need quartz accuracy in a metronome. It is not such a good thing. I'll go further and say that you should have a real wooden mechanical metronome on your 'real' acoustic piano, preferably a gran piano :). Also, If you've played for several years, I would suggest that you use a metronome only on