Get the  element in a simple table while clicking  element

Question: There is my issue.
I have a simple table like this (for the example) :

$('#tab tbody tr td').on('click', function() {
  var val = $(this).parent().find('table tbody tr th').text();
  console.log(val);
});

        Test 1

        Test 2

        Test 3

        Test 4

      A
      B
      C
      D

      E
      F
      G
      H

And I am trying to console.log(..) the name of the column while i am clicking a  element.
I think it may be a simple solution but i can't find it.
Thanks in advance
Answer: You can use :eq() & index() to achieve this.
Demo Code :

$('#tab tbody tr td').on('click', function() {
  var val = $(this).index(); //get index no of td
  console.log($("thead th:eq(" + val + ")").text().trim()); //get th value
});

        Test 1

        Test 2

        Test 3

        Test 4

      A
      B
      C
      D

      E
      F
      G
      H

Comment: Oh yes sure, didn't think about the var index. I'm beginning in this, thanks for your answer.
Comment: Glad i was able to help :)


font-family rule: Must I include spaces in local font names?

Question: Although I have installed the Liberation Sans font on my Windows machine, it is not used by Google Chrome when it renders the first line in the snippet below. Apparently this is because the font-family rule uses the PostScript name LiberationSans (without a space). When I add the space (as for the second line), it works:

Must I always include the spaces in local font names in a font-family rule? I ask because this stylesheet uses PostScript names without spaces in order to address a flaw in wkhtmltopdf.

.psname {
  font-family: LiberationSans, Arial;
}
.name {
  font-family: "Liberation Sans", Arial;
}

Jove, look at this font!

Jove, look at this font!

Answer: If you want to refer to local font family, you have to write it exactly as the font family is spelled on any given OS. In practice, if you need to support legacy names, you'll need to spell the font-family in both ways. List even more names if it turns out that the same font has yet-different spelling on some system. For example:
font-family: "Liberation Sans", "LiberationSans", "Arial", sans-serif;

Note that I added keyword sans-serif as a fallback, too, in case the OS wouldn't have any of the listed local font families. You should use quotes for all strings and no quotes for the keywords. Due historical reasons most browsers supports leaving out the quotation characters with spaceless names but you shouldn't trust on that. The official syntax is just strings or predefined keywords.
As for the wkhtmltopdf, it has been so buggy in my experience that you probably do not want to use it. I'd recommend using electron-pdf instead, if you can install the required dependencies (basically npm with recent enough Node.js, maybe xvfb-run, too, if you want to run electron-pdf headless).
Answer:
You need to add fonts folder on you'r project folder and import that fonts in CSS file like my attached screenshot.
In CSS import using that:
@font-face {
            font-family: "LiberationSans-Bold";
            src: url("./fonts/LiberationSans-Bold.ttf");
        }


Jenkins running protractor test

Question: I'm trying to launch my protractor test with selenium and protractor.
To do that on my pc I start on console 1 a selenium server:
webdriver-manager update
webdriver-manager start

Then on console 2 I launch tests:
protractor test.config.js

I would like to do the same in Jenkins. The problem is that after starting selenium I cannot do anything because the console is locked with selenium server running. So what I need is to launch the selenium server in background (in parallel) to other processes. Am I right? Maybe there is a Jenkins plugin to achieve that?
=== EDIT
Thanks for your responses. Finally I decided not to use the headless browser but to use selenium-plugin to run test on remote machines. However I have found other problems to configure my test environment. What I achieved till now is establishing connection between selenium hub and nodes. When I'm executing my protractor.config.js file I have the following error :
E/launcher - Error: Error: Could not find chromedriver

What I don't understand is how to set the path of the driver? And which driver should it be, the one from hub or the one from host. In the selenium-plugin config page there is an input to set a Chromedriver path but it's not taken into account. I also tried to set the chromeDriver param in protractor.conf.js file, but I still recieve the same error. Here is my protractor.config.js:
exports.config = {

    directConnect: true,

    // path to driver on node server
    chromeDriver: '/usr/local/lib/node_modules/selenium-standalone/.selenium/chromedriver/2.21-x64-chromedriver',
    // path to driver on hub server
    // chromeDriver: '/u01/apps/jenkins/data/tools/jenkins.plugins.nodejs.tools.NodeJSInstallation/NodeJS_5.12.0/lib/node_modules/selenium-standalone/.selenium/chromedriver/2.21-x64-chromedriver',

    // Capabilities to be passed to the webdriver instance.
    capabilities: {
        'browserName': 'chrome',
        shardTestFiles: true,
        maxInstances: 3
    },

    ...
};

Comment: You have a few choices. Did you want to run the tests headless which is what will happen if you add the selenium server step to the Jenkins build process (on windows this runs in session zero and can cause some elements to not be visible because the screen size is limited). I previously used grunt and the grunt plugin grunt-shell-spawn to run the selenium server asynchronously but this will be in headless mode. If you have a selenium server hub and node open on your desktop Jenkins will route the tests to that and run them visibly on your desktop in the browser. I can provide samples for both.
Comment: I was in the same boat as you a few months back and applied the same solution as you did, using the Selenium Grid plugin. I was not able to set the path to Chrome driver in conf. file. But as a workaround, if you add chromdriver's path in your path environment variable, it works for both local and remote. What I mean is whichever local/remote machine is giving this problem, set path variable in that machine itself, no need to set it from Jenkins or your tests. P.S. Sorry to add this an answer but don't have privileges to add comments.
Answer: Two quick work arounds and One ideal case i could think of:
work-around1: would be to run the webdriver manager in a separate bat file and call it in your batch script (Windows environment)
server.bat
webdriver-manager update
webdriver-manager start

batch script
call "path to your server.bat"
========Server Started========
protractor "path to you protractor config file" // if protractor is installed globally else change directory to specific folder where it is installed & execute the same command

work-around2: would be to get rid of webdriver-manager and use directConnect= true in your config file which would directly interact with firefox & chrome browsers if set.
Noe: There is an overhead for chrome browser. you need to do webdriver-manager update for downloading the chrome driver or manually put it in the specific location.
Ideal Case It is a good practice to separate our testing environment with that of selenium server which is always running. There are two good providers- Saucelabs & BrowserStack you can choose either of them based on your needs.
I hope this would give you some understanding!
Answer: This is how we have done it:
Under build, add a "Execute Shell" step and do something similar:
cd $WORKSPACE/ && npm update && npm install
$WORKSPACE/node_modules/protractor/bin/webdriver-manager update --standalone
$WORKSPACE/node_modules/protractor/bin/webdriver-manager status
grunt run-e2e-tests:<PASS NECESSARY PARAMETERS>

This will be then executed on the Jenkins slave running the job.
Hope it helps. :)

Jenkins running protractor test


Entropy for random variable and probability distribution

Question:
Let $(\Omega, \mathbb{P})$ be a finite probability space. Then one can
define the entropy of probability distribution $\mathbb{P}:\Omega\to
 [0,1]$ as follows: $$H(\mathbb{P})=\sum \limits_{\omega \in
 \Omega}\mathbb{P}[\omega]\log _2\frac{1}{\mathbb{P}[\omega]} \quad
 \quad \quad (1)$$
If $X:\Omega\to \mathbb{R}$ is a random with a range $S$, then its
entropy can be defined as follows: $$H(X)=\sum \limits_{x\in
 S}\mathbb{P}[X=x]\log_{2}\frac{1}{\mathbb{P}[X=x]} \quad \quad \quad
 (2)$$

Since probability distribution $\mathbb{P}
$ is also random variable, then equalities $(2)$ and $(1)$ should be equal.
Consider the probability space $(\Omega,\mathbb{P})$, where $\Omega=\{\omega_i\}_{i=1}^5$ and $\mathbb{P}[\omega_1]=\mathbb{P}[\omega_2]=\frac{1}{4}$, $\mathbb{P}[\omega_3]=\mathbb{P}[\omega_4]=\mathbb{P}[\omega_5]=\frac{1}{6}$.
The first definition implies that $H(\mathbb{P})=\sum \limits_{i=1}^{5}\mathbb{P}[\omega_i]\log_2\frac{1}{\mathbb{P}[\omega_i]}=1+\log_2\sqrt{6}$
But if we use the second definition with $S=\{\frac{1}{4},\frac{1}{6}\}$, we obtain $$H(\mathbb{P})=\sum \limits_{x\in S}\mathbb{P}[\mathbb{P}=x]\log_2\frac{1}{\mathbb{P}[\mathbb{P}=x]}=1.$$
What am I doing wrong?
Comment: you haven't normalized the distribution of the RV, so you are using a conditional distribution
Comment: Why should (1) and (2) be equal in cases where $X$ is not a $1-1$ function?
Comment: @Henry, so are they different definitions of the entropy?
Comment: @kodlu, what do you mean by normalization of the random variable?
Answer: The main idea is there's less entropy on the range of $\mathbb P$ then the domain of $\mathbb P$ in your example, and that the probability distribution on $S$ is technically different. Your range could be considered a finite probability space $(S, \mathbb Q)$ where
$$\mathbb Q[s] = \mathbb P[\mathbb P=s] $$
So
$$H(\mathbb Q) = \sum_{x \in S} \mathbb Q[x] \log_2 \frac{1}{\mathbb Q[x]} = -2 \left (\frac{1}{2} \right  )(-1) = 1$$
is simply a probability distribution with less entropy. It takes two values equally often, instead of considering every possible $\omega \in \Omega$ it could have come from.
Comment: Yeah definition (2) is for probability distributions in the range created by random variables where you "forget" what the inputs are. Definition (1) is for  the domain where you know all the possible inputs.
Comment: I guess the easiest way to think about it is the two definitions are for different things.  Definition (1) is for $(\Omega, \mathbb P)$ and Definition (2) is for $(S, \mathbb Q)$.
$$\mathbb Q[s] = \mathbb P(\omega \in \Omega:  P(\omega)=s)$$
$$\mathbb P[\omega] = \mathbb P[\omega] $$
They're two different probability distributions on two different spaces, so it makes sense it is sometimes different, especially if $\mathbb P$ isn't 1-1 or anything.
Comment: If $X(\omega) = \mathbb P(\omega)$
$$H(X) = -\sum_{x \in S} \mathbb P(X=x) \log_2 (\mathbb P(X=x)  $$
$$= -\sum_{x \in S} \mathbb Q_X[s] \log_2 \mathbb Q_X[s] = H[Q_x] $$
But $\mathbb Q_X$ is a different distribution than $\mathbb P$.
Comment: What do you mean by $\mathbb{Q}_X$?
Comment: Sorry, I went past the edit timer
$$\mathbb Q_X[s] = \mathbb P[\omega \in \Omega: X(\omega)= s] $$
Answer: Sorry to say this, but there seems to be a lot of confusion of what probability measures are and what are random variables. Random variables are measurable functions. With what respect is the probability measure measurable?
The main point is, that in your interpretation $X$ is a random variable with range $S=\{1,2,3,4,5\}$ where
$\mathbb P(X=1)=\mathbb P(X=2)=1/4$ and $\mathbb P(X=3)=\mathbb P(X=4)=\mathbb P(X=5)=1/6$. The entropy then is about 2.3, which is the same result as in your version with the measure $\mathbb P$.
So, to be precise, the measure $\mathbb P_X:=\mathbb P\circ X^{-1}$ has the same entropy as the $\mathbb P$ in your measure version.
Comment: I'm sorry, a probability distribution is not a random variable! Not even with finite sample space.
As for your first question, the definitions are similar. You just like in (1) at a probability measure, and in (2) at the probability measure induced by a random variable.
Comment: Please look up the definition of random variable and probability measure again. This is really basic stuff. I don't mean to be arrogant, but your question hints at missing fundamentals. The expression $\mathbb P(\mathbb P=s)$ is really non sensical.
Answer: TL;DR -- Your first computation is for the entropy of a discrete probability distribution on $\Omega$, and your second computation is for the entropy of a non-invertible random variable defined on $\Omega$. If the r.v. were invertible, then these entropies would necessarily be the same; but they are not generally the same in the non-invertible case.
Your r.v. can be described as $X=p(I)$, where $p()$ is the probability mass function of a discrete probability measure $P,$ and $I$ is the identity r.v.  $I:\Omega\to\Omega:\omega\mapsto\omega,\,$ so
$$\begin{align}H(X)&=-\sum_{x\in X(\Omega)}p_X(x)\log_2 p_X(x)\\[1ex]
&=-\sum_{x\in p(I(\Omega))}P\{\omega:p(I(\omega))=x\}\log_2 P\{\omega:p(I(\omega))=x\}\\[1ex]
&=-\sum_{x\in p(\Omega)}P\{\omega:p(\omega)=x\}\log_2 P\{\omega:p(\omega)=x\}\\[1ex]
&=-\sum_{x\in p(\Omega)}\left(\left(\sum_{\omega:p(\omega)=x}p(\omega)\right)\log_2 \left(\sum_{\omega:p(\omega)=x}p(\omega)\right)\right)\\[1ex]
\end{align}$$
and this won't generally reduce to $-\sum_{\omega\in\Omega}p(\omega)\log_2 p(\omega)=H(P)$ unless $\{\omega:p(\omega)=x\}$ is just a singleton, i.e. unless for each $x$ there is only one $\omega$ such that $p(\omega)=x$.

Remarks on the definitions
The general context here is a probability space $(\Omega,\mathcal F,P)$ where $\Omega$ is finite, $\mathcal F$ is a $\sigma$-field subsets of $\Omega$, and the probability measure $P$ is specified by some probability mass function $p()$. (To avoid confusion, I won't use your symbol $\mathbb P$.)
Now, the entropy of such a distribution is defined as
$$H(P):=-\sum_{\omega\in\Omega}p(\omega)\log_2 p(\omega)\tag{1}$$
and if $X:\Omega\to\mathcal X$ is a r.v., then the entropy of $X$ is defined to be the entropy of its distribution:
$$H(P_X):=-\sum_{x\in X(\Omega)}p_X(x)\log_2 p_X(x)\tag{2}$$
where $p_X()$ is the probability mass function of $X.$
NB: Using (2), $H(P)$ can also be seen as the entropy of the identity r.v. $I:\Omega\to\Omega:\omega\mapsto\omega\,$:
$$H(P_I)=-\sum_{\omega\in\Omega}p_I(\omega)\log_2 p_I(\omega)=H(P).$$
Comment: What do you mean by "TLDR"?
Comment: @ZFR Internet slang for "too long; didn't read".
Comment: Thank you! But I am really confused with the notion of entropy and don't know which answer is correct. Can you take a look please?
Comment: @ZFR I've added some remarks on the definitions, which might help. Note that **the entropy of a r.v. is just the entropy of its probability distribution**. So you can think of your first entropy as the entropy of the identity r.v. $I$ on $\Omega$, and the second one as the entropy of $X=p(I)$. Since $I$ and $p(I)$ clearly have different probability distributions -- because $p()$ is not one-to-one-- we shouldn't expect them to have the same entropy.
Comment: Thank you for the addendum! Let me read all this.
Comment: Excuse me but I am really confused with that sentence "Your r.v. can be described as $X=p(I)$, where $p()$ is the probability mass function of a discrete probability measure $P,$ and $I$ is the identity r.v.  $I:\Omega\to\Omega:\omega\mapsto\omega,\,$"
Comment: My random variable $X:\Omega\to R$ is defined as $X(\omega):=P(\omega)$. But you wrote it can be described as $X=p(I)$, where $p$ is the probability mass function of $P$. Then $X(\omega)=p(I(\omega))=p(\omega)$. But what is $p(\omega)$? It does not make since $p$ is a probability mass function of $P$ so it is domain should be $\mathbb{R}$ be definition.
Comment: @ZFR You're confusing the measure $P$ with the mass.fn. $p.$ The measure $P$ is defined on *subsets* of $\Omega$ , whereas $p$ is defined on the *elements* of $\Omega$; so $X(\omega)=p(\omega)=p(I(\omega)),$ because $I(\omega)=\omega$ for all $\omega\in\Omega.$ I introduced $I$ so we can speak of both of the entropies that you calculate as being entropies of *random variables* (i.e., of $I$ and $p(I)$). We could dispense with $I$ and just speak of both entropies as being entropies of *probability distributions*, (i.e. of $P$ and $P_X$, with $X:=p$).
Comment: Hmm. Ok so let's take a look at the following situation: $(\Omega,P)$ with $|\Omega|<\infty$ and $P(\omega)=\frac{1}{|\Omega|}$ for each $\omega\in \Omega$. The definition (1) tells us that $H(P)=\log_2|\Omega|$. But if we apply definition (2)  we will get $H(P)=0$ because $p_P(\frac{1}{|\Omega|})=P\{\omega: P(\omega)=\frac{1}{|\Omega|}\}=1$. What is wrong? I am so confused.
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/136509/discussion-between-zfr-and-r-e-s).


How are the axioms defined in the fundamentals of set theory

Question: I am reading Enderton Elements of set theory and something keeps bothering me. At the start he defines the axioms in terms of the symbols
$$\forall, \exists, \in, \neg, \&, \text{ or }, \iff.$$ Then he goes on to define functions as specific types of set. However, it feels to me that the axioms and the theorems are sentences in some kind of formal language. And to evaluate the truth of a statement, means to define an interpretation of the statement in the 2 element set $$S:= \{\text{true, false}\}.$$ For instance, $$x\iff y$$ derives a function on the set $S$ such that $$\left((x\iff y)_S = \text{ false}\right)\text{ iff } \left(x_S = \text{ true and } y_S = \text{ false}\right).$$ My issue is how can this be if you need the axioms to define functions in the first place. It feels like the foundations of mathematics are self referential?
I appreciate my question is perhaps unclear, but I feel my understanding is too limited to ask a more precise question at this stage.
Comment: You examples are not exactly formulas of predicate logic: and example will be the following definition: $\forall x [x \in A \cup B \leftrightarrow (x \in A \lor x \in B)]$.
Comment: It sounds like you're charging the axiomatization of set theory as circular:  the formal axiomatization of sets (or at least its semantics) requires the very notion of a set. This is a common sentiment/worry, and yes, there is a notion of set that we already have in mind and kind of have to accept as a given when doing this kind of axiomatization.  But note: *of course* we have to start with *something* as a basis: we can't be asking "But what's the justification/definition for *that*?!" forever.
Comment: Yes, axioms of e.g [Zermelo-Fraenkel Set Theory](https://plato.stanford.edu/entries/set-theory/ZF.html) are formulas of predicate logic. See e.g. the Null Set Axiom: $∃x \forall y ¬ (y \in x)$.
Comment: Thus, theorems of set theory are formulas expressed in the language of the theory that are provable from the axioms of the theory using the rules of predicate logic.
Comment: See also the post [Axioms of set theory and logic](https://math.stackexchange.com/questions/185351/axioms-of-set-theory-and-logic) as well as [Axioms of First Order Logic and ZFC Axioms](https://math.stackexchange.com/questions/4602425/axioms-of-first-order-logic-and-zfc-axioms) and [Are "formulas" in Axioms of ZFC indefinite?](https://math.stackexchange.com/questions/1631680/are-formulas-in-axioms-of-zfc-indefinite)
Comment: *functions* in set theory are sets, i.e. [sets with a specific property](https://people.umass.edu/partee/NZ_2006/Set%20Theory%20Basics.pdf). See the post [Exact definition of a function](https://math.stackexchange.com/questions/2201237/exact-definition-of-a-function).
Answer: You can formally describe the language and rules of predicate logic using set theory, but that formality isn't necessary in order to use predicate logic, as long as we have a shared understanding of the rules for forming valid sentences and proofs.
So it's not that the foundations of math are self-referential, it's just that they can't be "formally defined all the way down": our capacity for logical reasoning must exist to some degree before we can describe it, because if it didn't, there'd be no tools to define it into existence. Propositional and predicate logic are the levels where we start being formal, so you should consider the exposition of these systems (at least in the context of introducing set theory) to be informal or self-evident.
When we eventually want to study logical systems abstractly and need a way to express their properties as mathematical statements (i.e. do metamathematics), we can use set theory to define objects that model the logical primitives and then prove things about those objects. I'd argue that these objects are not actually "at work" when we use logic; they're just mathematical models for a real-world activity.


Normalize vector according to ellipse

Question: I have an ellipse (of width $w$ and height $h$) centered in $c$ and a vector $v$ (whose origin is $c$).

$v$ can cross the ellipse or not. My objective is to find out the point where $v$ touches (or would touch) the ellipse if it was at least big enough to touch it.
Comment: Assuming you are in 2D, then the vector $v$ can be written in the form $(t, \alpha t)$ for some variable $t$. You have the equation of the ellipse. Plug in the point $(t, \alpha t)$ and solve the quadratic for $t$.
Comment: Where is $c$?  Why is $v$ the label of the center?  And what have you tried?  Where did you encounter difficulties?
Comment: $c$ is the center of the ellipse, where $v$ is written. I wrote $c$ in the center just to emphasize that it goes from the center to somewhere.
Answer: $$\frac{v_y}{v_x}=\frac{h\sin\theta}{w\cos\theta}$$ gives
$$\tan\theta=\frac{v_yw}{v_xh}.$$
So $$h\sin\theta=\frac{v_ywh}{\sqrt{v_y^2w^2+v_x^2h^2}},
\\w\cos\theta=\frac{v_xwh}{\sqrt{v_y^2w^2+v_x^2h^2}}.$$

Normalize vector according to ellipse


How to make Audacity play in loop?

Question: In Audacity, how to make a selection or a whole track play in a loop, i.e. start over at the end.
Answer: Click the Play button while holding Shift. Shift + Space for short.
Answer: Perhaps maybe this will help: https://manual.audacityteam.org/man/tutorial_looping.html
Comment: Yes, just now I noticed it mentions the 'Loop play'. Thanks.

How to make Audacity play in loop?


How to resolve the error about 'A partially-completed form was found'?

Question: Yesterday I have updated Webform module from 7.x-4.0-beta3 to 7.x-4.13.
After doing so, I am getting this notification message, throughout the site:

A partially-completed form was found. Please complete the remaining portions

I have also checked some threads.
When I check log entries I got this error :

Notice: Undefined property: stdClass::$is_draft in webform_client_form()

And deleting partially filled nid in webform submissions table is not working for me.
What can I do with it?
Answer: Since "deleting partially filled nid in webform submissions table" (as in your question) seems to not solve your issue, you may want to have a look at comment nr 2 in issue 2560907, which states:

A webform node is being displayed on that page and there is a draft submission for the current user. You don't have to find the id -- the form will be displayed, unless theming or another module is preventing it.


Magento checkout cart feature control

Question: I have a site, 1.5 magento, and the cart functionality (and the customer account functionality) seem to be disabled. When i attempt to go to the url 'checkout/cart', just the homepage displays.
Ive checked all the usual suspects..including:

checked the url_rewrites table (there is one entry in their referencing checkout/cart...but goes from checkout/cart to checkout/cart, so dont see this is an issue, but did edit it just to rule it out)
enabling/disabling of the module itself, looking at both the etc/modules files and removing, and checking the module listing in system->config->advanced area.
trying to step through the code..try detect where the change over of pagedata occurs - struggling here.
looking for certain terms in the codebase...and database SQL file.
the htaccess file, looking for a rewrite
local/community modules..and any rewriting of the checkout

Im starting to think a hack is in place here to show the homepage when visiting checkout url. The url : www.mysite.co.uk/checkout/cart remains in the address bar, but i see homepage data.
Anyone know where else i can check...or easily locate the cause of this issue?
Many thanks
S
Comment: customer and cart modules can't be disabled, without them magento will not work.. have you deleted your cache btw? have you tried in another browser?
Comment: Hi.   Yes and yes.
Ive just tried changing the template...a clean base, and the modern theme. It STILL displayed the homepage.

Thinking this must be database related now. Going to export and clear the rewrites at the minute...
Comment: Cleared the rewrites table....can access cart! Dammit...it was in their all along. Ill find the record....
Answer: Did you look in backend under Configuration -> Sales -> Checkout ?
There is a field called "Enable One-Page Checkout" which has to be enabled. If you disable it, your store will just run fine but neither registered customers nor guests can check out anymore.
Comment: yes, thx, i checked those settings. Seems a rewrite was placed in the db...by hand i think.
Answer: Turns out this was rewrites added to the rewrite table manually. Didnt find them at first.

Magento checkout cart feature control


Provide condtional 403 response when a user tries to view a node

Question: Use case:
I have two roles: "Teacher" and "Student". Each Teacher has been assigned a set of Students.
This relationship is tracked by a custom entity: "Students by teacher" which has two fields:

Teacher (single value) - a teacher.
Student (unlimited values) - the set of Students supervised by this teacher.

There is also a custom node content type called "Assignment". Upon completion of an assignment, a student will save it in the Drupal database as a published node.
The Teachers have the permission "View published content". This means that with my current setup, all Teachers can view all published assignments, whether the author is a student they supervise or not.
What I want is this: If the assignment is authored by a Student they supervise, they shall see it. If it is not, they get a 403 ("Access denied") response.
I've been looking for a Drupal extension to solve this, and the best one I've found is Flexi Access. That extension has not been upgraded to Drupal 9, so I cannot use it.
I've been thinking about solving this by means of some hook that is ran when a user tries to view a node. The logic inside the hook shall be this:

Check if the author of the node is supervised by the person trying to view the node.

If "Yes", show the node. If "No", show "Access denied".

However, I've searched the API, and have so far not been able to find a hook (or some other means) that let me do this.
Somewhere at the back of my brain, I have a notion that Drupal 9 provides some other mechanism than hooks for implementing access control.
Question: How do I provide a 403 response when a user tries to view a node and some specific criteria is not satisfied?
Answer: Found out just after posting this question.
One can use hook_ENTITY_TYPE_access() like this:
<code>use Drupal\Core\Access\AccessResult;
use Drupal\Core\Session\AccountInterface;
use Drupal\node\NodeInterface;

function mymodule_node_access(NodeInterface $node, $op, AccountInterface $account) {
  if ('view' == $op && CONTITION NOT SATISFIED) {
    return AccessResult::forbidden();
  }
  return AccessResult::neutral();
}
</code>


Propriedade value de input não funciona com Angular

Question: Estou tendo alguns problemas com a propriedade value de um campo de texto:

  <form class="row">

      <input
        id="campo"
        type="text"
        value="exemplo de texto"/>
      campo

  </form>

Ao utilizar a propriedade no componente, o Angular simplesmente a ignora, e o campo sai vazio, mesmo que seja utilizado números ou texto. Como posso corrigir isso?
Comment: Se entendi bem, sem fazer **property binding - []** não via funcionar mesmo.
Comment: e não é que era isso mesmo?
Answer: Importa o modulo FormsModule e usa [(ngModel)] no lugar de  value.


Laravel 8 database won't update using HTML form

Question: I am currently creating an HTML form for the user to insert their information in the database table. However, even after I create the controller, models, and routes, the database won't update.
Here are my files,
Controller file, updateDatabase.php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Models\Application;

class updateDatabase extends Controller
{
   public function update(Request $request)
   {
        return $request->input();
        $data= Application::find($request->id);
        $data->plateno=$request->plateno;
        $data->type=$request->type;
        $data->colour=$request->colour;
        $data->brand=$request->brand;
        $data->model=$request->model;
        $data->save();

        return redirect('application');
   }
}

Model file, Application.php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Application extends Model
{
     /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'plateno',
        'type',
        'colour',
        'brand',
        'model',
        'id',
    ];

    public $timestamps=false;
}

View File, application.blade.php
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">

    <link href="{{ asset('css/user.css') }}" rel="stylesheet">
    <title>Application</title>

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">

                </button>

                        Profile

                    <form method="POST" action="{{ route('logout') }}">
                    @csrf

                        <x-responsive-nav-link :href="route('logout')"  style="color:white"
                                onclick="event.preventDefault();
                                this.closest('form').submit();">
                              {{ __('Logout') }}
                        </x-responsive-nav-link>

                    </form>

                           Home

                            Application

                           Status

Particulars of Applicant

Please check your details

                            Name:

{{ Auth::user()->name }}

                            Email:

{{ Auth::user()->email }}

                            Student / Staff

{{ Auth::user()->type }}

                            Phone Number:

{{ Auth::user()->phone }}

                <form method="POST" action="/application">
                     @csrf

Particulars of Vehicle 1

                            Vehicle Registration Number:
                            <input id="plateno" class="form-control form-control-sm" type="text" name="name" placeholder="Vehicle Registration Number" :value="old('plateno')" required autofocus>

                            Colour(Vehicle):
                            <input id="colour" class="form-control form-control-sm" type="text" name="colour" placeholder="Vehicle colour" :value="old('colour')" required autofocus>

                            Type of vehicle
                            <input id="type" class="form-control form-control-sm" type="text" name="type" placeholder="Motorcycle / Car" :value="old('type')" required autofocus>

                            Brand of vehicle
                            <input id="brand" class="form-control form-control-sm" type="text" name="brand" placeholder="Brand, Eg : Honda" :value="old('brand')" required autofocus>

                            Model of vehicle
                            <input id="model" class="form-control form-control-sm" type="text" name="model" placeholder="Model, Eg : EX5" :value="old('model')" required autofocus>

*Please recheck your vehicle details

                                    <input class="form-check-input" type="checkbox" value="" id="invalidCheck" required>

                                        Agree to terms and conditions

                                        You must agree before submitting.

                                <button type="submit" class="btn btn-default" style="background-color: #003D7B; color:white">Submit</button>

                    </form>

Copyright 2020  |  Developed By IIUMVeRS

Route File, web.php
<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\updateDatabase;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
    return view('welcome');
});

//auth route for both
Route::group(['middleware' => ['auth']], function() {
    Route::get('/dashboard', 'App\Http\Controllers\DashboardController@index')->name('dashboard');
});

// for users
Route::group(['middleware' => ['auth', 'role:user']], function() {
    Route::get('/dashboard/myprofile', 'App\Http\Controllers\DashboardController@myprofile')->name('dashboard.myprofile');
});

//User's Application
Route::get('/application', function () {
    return view('application');
})->middleware(['auth', 'role:user'])->name('application');

Route::post('/application', [updateDatabase::class, 'update']);

//User's Status
Route::get('/status', function () {
    return view('status');
})->middleware(['auth', 'role:user'])->name('status');

//User's Profile
Route::get('/userprofile', function () {
    return view('userprofile');
})->middleware(['auth', 'role:user'])->name('userprofile');

//Admin's Profile
Route::get('/adminprofile', function () {
    return view('adminprofile');
})->middleware(['auth', 'role:admin'])->name('adminprofile');

//Admin Application Record
Route::get('/records', function () {
    return view('records');
})->middleware(['auth', 'role:admin'])->name('records');

//Admin Application Approval
Route::get('/approval', function () {
    return view('approval');
})->middleware(['auth', 'role:admin'])->name('approval');

require __DIR__.'/auth.php';

Answer: Right off the bat I see that your updateDatabase controller has a return $request->input(); before you perform any attribute updates.
Answer: why you're return $request->input() at first in the update function your code will stop and will not update anything because you're use return at first of the function so it'll just run first line I mean return $request->input(); line, remove it then try again


Understanding `score` in LightGMB

Question: I'm newly introduced to the LightGBM for a regression problem. Having read the documentation of LightGBM (here), I got puzzled about the score. You can track a few metrics as well as the objective value as the training goes by. But this score is not any of them. It probably, somehow, represents the goodness of fit, but I didn't find any mathematical formula for that.
Can someone explain what does this quantity represent and what are the links, if any, between that and the objective value during the training, validation, and testing? I'm particularly interested in huber loss.
Answer: Having a look at sklearn documentation, I guess I found the answer to my question. I'm dealing with a regression decision tree and for a regression problem, a measure for goodness of fit is defined similar to $R^2$ in OLS; If $\hat{y}_i$ is the prediction of data point $i$ with features $\textbf{x}_i$ and label $y_i$, then score is defiend as:
$$ S = 1- \frac{ \sum_i {(y_i - \hat{y}_i)^ 2}}{\sum_i{(y_i - \langle y \rangle )^ 2}} $$
although it's not mentioned anywhere in LightGBM's doc.

Understanding `score` in LightGMB


How to parse pixel data of an online image python

Question: For a project I am needing to parse pixel data from a large number of online images. I realised it could well be faster to load the images into programme memory with a get request, carry out the required operations, then move onto the next image - removing the necessity for reading and writing these into storage. However in doing this I have ran into several problems, is there a not (overly) complicated way to do this?
Edit: I didn't include code as as far as I can tell everything I've seen (scikit-image, pillow, imagemagick) is a complete dead end. Not looking for somebody to write code for me, just a pointer in the right direction.
Comment: welcome to stack overflow. your approach isn't bad, but you should show us what it is and what the problems you are running into are if you want any help. unfortunately stackoverflow is not the place to ask for general advice
Comment: Taking a step back, what is the point of this?
Comment: We have no idea what the required operations, the problems, the desired output or even the specifics of the inputs are. It's very difficult to suggest a good approach without having at least some concrete information.
Answer: Its easy to load image directly from url.
<code>import PIL
from PIL import Image
import urllib2

url = "https://cdn.pixabay.com/photo/2013/07/12/12/58/tv-test-pattern-146649_1280.png"
img = PIL.Image.open(urllib2.urlopen(url))
</code>
Image is now loaded.
Getting pixels is also easy: Get pixel's RGB using PIL
Comment: Nice! You'd probably want to do (eg.) 10 requests at once, since the `get` will involve a lot of waiting. Does urllib2 support async open?


Connected components of a given set

Question: Let $H_1,H_2,H_3, H_4$ be four hyperplanes in $\mathbb{R}^3$ . I need to find the maximum number of connected components of $\mathbb{R}^3-H_1\cup...\cup H_4$. I have no idea how to visualise it. This is easy to do in $\mathbb{R}^2$ . Also can we construct a general formula for maximum number of connected componets In $\mathbb{R}^n$ with $m$ hyperplanes.
Answer: Yes, this is known as the cake number.
In general, the maximum number of components into which $m$ hyperplanes inside  $\mathbb R^n$ cut $\mathbb R^n$ is:
$\binom{m}{n}+\binom{m}{n-1}+\dots+ \binom{m}{1}+\binom{m}{0}$.
Comment: Thank you ! This really helped
Comment: sure, no problem.

Connected components of a given set


Como alterar o nome da Rota para minusculo?

Question: No swagger aparece a primeira letra de cada palavra em maiusculo WeatherForecast:

Pesquise e não encontrei como faço para exibir tudo em minusculo e preciso que tudo fique em minusculo e acrescentei o atributo Name = "weatherforecast" mas vejo que isso não é o suficiente:
[ApiController]
    [Route("[controller]", Name = "weatherforecast")]
    public class WeatherForecastController : ControllerBase
    {
        private static readonly string[] Summaries = new[]
        {
        "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
    };

        private readonly ILogger<WeatherForecastController> _logger;

        public WeatherForecastController(ILogger<WeatherForecastController> logger)
        {
            _logger = logger;
        }

        [HttpGet(Name = "GetWeatherForecast")]
        public IEnumerable<WeatherForecast> Get()
        {
            return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = Random.Shared.Next(-20, 55),
                Summary = Summaries[Random.Shared.Next(Summaries.Length)]
            })
            .ToArray();
        }
    }

Answer: Você pode mudar essa configuração através das configurações de rota do .net mesmo.
Inclua a configuração abaixo no registro das dependências da DI.
services.Configure<RouteOptions>(options =>
{
    options.LowercaseUrls = true;
    options.LowercaseQueryStrings = true;
});

Detalhes sobre a documentação aqui.


Two sample test on mostly independent samples

Question: I have a sample dataset of semi-finals of a swimming competition and there are multiple categories in which swimmers can participate. I want to do a hypothesis test (two-sample) on this to check if the result time differs in different categories.
But in the sample there are some swimmers who participated in more than one category, how am I supposed to handle this? Is a paired t-test the way to go?
Answer: Neither paired nor unpaired t-tests are appropriate if some of the data points are paired and some are not.  The paired test drops data from swimmers who only swim in one category, while the unpaired ignores the pairing. This can be handled in a linear mixed model with separate intercept terms for each swimmer, e.g., using the lme4 package for R:
your_model = lmer(time ~ 1 + category + (1|swimmer_id), data = your_data)


Can you use a cable with a single wire for a mono jack cable?

Question: I know that a mono jack has two poles:

So I always assumed that the cables for a mono jack would have two wires. But recently I have been told that if I ever were to make my own cable, I should use a shielded single wire cable and connect ground to the shielding.
Would that even work and is that a good idea?
Doesn't this destroy the whole purpose of the shielding?
Comment: **Not** grounding the shielding would destroy the purpose of it. The point of shielding is that it's grounded and therefore will allow any RF noise that hits the shield to be bled to ground.
Comment: I see. I thought the shielding was supposed to prevent the audio and the ground wire from interfering with each other. So is the shielding actually just to block radiation from external sources?
Comment: If there WERE two signal wires, they'd both be inside the shield anyway.  Though there is twin shielded single core cable available...   Look, there are SO many possible cable configurations.  But let's stick to explaining the common configurations for a domestic setup for now, OK?
Answer: You might even get a signal through with just a single-core cable, no screen, where a cable connects two items of mains-powered equipment (and are in a country civilised enough to provide an earth connection on all power outlets.) Like a telegraph system - there was only one wire, the return was the Earth.
But we often use single-core plus shield.  The shield will be grounded.  It acts both as signal return and as protection from RF interference.
Where signal levels are low, like a microphone cable, we DO use a 'balanced' connection, two cores plus a seperate screen.  In electrically noisy environments such as a TV studio (though they're a lot less noisy since the demise of crt monitors) Line signals are routinely balanced as well.  Probably unnecessary in a home studio, though the option is there on much semi-pro equipment.  You need a 3-contact connector of course, for the 3 electrical paths.  Typically a TRS jack or an XLR-3.
Answer: It depends on what type of wire you are using.  If you run your signal and neutral (ground) through two separate wires, then it is a good idea to also have a shield around them that is connected to ground. Often the wire comes in "twisted pair" to also help with noise reduction.
You may also use Coaxial cable for a guitar cable. In this case the second wire is the shield, being wrapped around a core wire. Coaxial tends to be used more often for instrument cables, as it is less expensive due to using less copper and one less wire.
Shielded wire is usually used inside instruments because it is more flexible and smaller, not having a plastic core around a center wire like coaxial does.
The shielding in both cases is to intercept electrical radio frequency signals that the wires will pick up (connected wire acts like an antenna). The RF interference is sent to ground and isn't picked up by your amplifier.
Answer: Entire books have been written on the subject of shielding and grounding. The unfortunate fact is that using the shield as the signal return (ground) path is a terrible idea. It greatly compromises the shield's effectiveness, though for historical reasons essentially all guitar cords work this way.
In the 1970's Gibson made a version of the Les Paul (the "Professional" IIRC) that had low-impedance, balanced pickups and wiring, with proper shielding. It had a beautifully clear and hum-free sound. AFAIK it was a flop on the market.


Read entity reference node field

Question: I have a referenced entity named - field_cp_level2_ref_level3. This field belongs to level3 content type. when I dump the $entity, I see the field as below:
entity:node:level3::field_cp_level2_ref_level3 => Drupal\Core\Field\EntityReferenceFieldItemList (9) Depth Limit

how to read the value of this field? I tried to read the value as below:
$var =  $entity->$node->field_cp_level2_ref_level3->value;

dpm($var) returns null. how to read this field?
Answer: You can use $entity->field_x->referencedEntities(); which will return an array of referenced entity objects
Comment: doing so, throws the below error - "Error: Call to a member function referencedEntities() on null "
Comment: That suggests there's nothing in your field. Maybe wrap it in an is null check.

Read entity reference node field


egrep: how to search for text that includes double quotes (win7 cmd window)

Question: I'm trying to make a TOC in my HTML file by searching for all HTML tags that contain one of three classes: article, section, and subsection.
I'm using GNU grep 2.4.2 in a Windows 7 cmd window. Now I've read at least 12 pages from my Google search and tried 20+ permutations of my grep command. I'm trying to find classes in my HTML file. Luckily in my HTML file there is only one HTML tag per line in the HTML file, which simplifies things.
I made a cmd batch file and tried running this and got various errors. I've tried escaping the double quotes, and not escaping them. I tried escaping the parens and not escaping them. I've tried different switches, with and without -E, etc. This is the regex I need to search for on every line and print the lines that match.
/class="\(article\|section\|subsection\)"/
This is one of my later grep attempts.
grep -i -E 'class="\(article\|section\|subsection\)"' ch18IP.htm
In this example I'm not getting any lines returned nor any error message. What am I doing wrong here?
Thank you!
Comment: Use PowerShell and `Select-String`. Multiple advantages: Far superior scripting language, built-in regular expression matching (`Select-String`) with substring extraction, etc. PowerShell is baked into the OS on Windows 7 and later.
Answer: You have three problems:
1) double quote " literals must be escaped as \" when using grep on windows.
2) meta-characters (, ), and | should only be escaped as \(, \), and \| when using basic mode. The -E exended regex option uses the more traditional unescaped form. This is documented at http://www.gnu.org/software/grep/manual/html_node/Basic-vs-Extended.html
3) If a parameter requires quoting on Windows, then double quotes are used, not single quotes. But in this case, enclosing quotes are not required, and would actually get in the way. I'll explain this later in the answer.
I also suggest that you add a word boundry assertion \b before class so that you don't mistakenly match something like subclass.
So either of the following should work:
grep -i -E \bclass=\"(article|section|subsection)\" ch18IP.htm
grep -i \bclass=\"\(article\|section\|subsection\)\" ch18IP.htm

It gets tricky if you want to enclose your search argument in quotes because the search term also includes quote literals, as well as poison characters like | that have special meaning to the cmd "shell". So you may end up having to escape some characters for both grep and cmd.exe. See https://stackoverflow.com/a/19816688/1012053 for more info.
In your case, here are two options for how you could quote your search term for Windows.
grep -i -E ^"\bclass=\"(article|section|subsection)\"^" ch18IP.htm
grep -i -E "\bclass=\"(article^|section^|subsection)\"" ch18IP.htm

That last form looks mighty weird if you decide to use the basic regex:
grep -i "\bclass=\"\(article\^|section\^|subsection\)\"" ch18IP.htm

Answer: Getting double-quotes as input on Windows cmd.exe command line is notoriously problematic.  See if this works for you: https://www.gnu.org/software/gawk/manual/html_node/DOS-Quoting.html
Comment: The only info in your "answer" is a link. That is appropriate for a comment, but not an answer.


Qt : How to send keyevent to system?

Question: I am doing a Qt project, and I want to send keyevent to system in programming.
I have tried the code below, but it doesn't work,
QKeyEvent event = QKeyEvent(QEvent::KeyPress, Qt::Key_B, Qt::NoModifier);

QApplication::sendEvent(this, &event);

To make my question more clearer, what I am doing is : I generate char in my app, and then want to send keyevent to User.exe, so that the IME can catch the input char. ( A custom  input method )
Answer: I think QApplication::sendEvent can not implement what you desired. If you have a keyboard connected to your computer, there is a file in the directory of "/dev/input" named event0 or event1 or event3... and one file corresponds to your keyboard. You can try to open the file with linux API and construct input_event, then write the event to the file. Then your application will accept a key event just like you press a key on your keyboard.

Qt : How to send keyevent to system?


Nested logistic regression in R

Question: I am trying to find a way to do Nested Logistic Regression in R that fits my needs.  I have a very large data set with almost 200 variables available.  I have found my "best" model and it contains 12 of these variables.  I am aware of the problems of using 12 variables in logistic regression and don't want to cover those here.  I am using the model to predict the probability a student will drop out of high school.  The dataset I'm using that includes the students I am predicting the probability for has some missing data.  So for example say my model is:
Dropout ~ AttendanceRate + Enrollments + AgeDiff + Race + Absences

Now say it is not known for a particular student how many Absences he has had.  I am using the predict function to find the dropout probabilities from my model.  If one of the variables is missing or "NA" then there is no predicted probability as it is NA.  To fix this problem I want to use Nested logistic regression.  So for a student with a missing value in "Absences" the model would be
Dropout ~ AttendanceRate + Enrollments + AgeDiff + Race

I am currently using the glm function to do my logistic regression.  I understand it cannot do nested logistic regression.  So how do I do Nested Logistic regression from my full model so that I can predict a students dropout probablity no matter which variable or variables may be missing.  I realize using Nested models will hurt the strength of my model for prediction purposes but I am willing to sacrifice that for my purposes.
Any Suggestions?
Comment: I find it very unfortunate that terms get used in different ways; it makes it harder for people to understand these topics & communicate w/ each other. You seem to be using "nested" in the sense of *nested model tests* (checking if a version of your model w/o a covariate fits significantly worse than the full model), whereas more typically, "nested logit" might refer to something like modeling the probability of students passing a test, when those students are nested w/i classes, which are nested w/i schools, etc. It's worth being clear on this distinction b/c it can be quite slippery.
Comment: On a different note, I am not aware of a problem w/ using 12 variables in logistic regression. Can you clarify what you are referring to?
Comment: "Nested logit" usually means something quite different from what you are proposing; this might be why you aren't finding what you're looking for.
Comment: In this case, as can be determined from my example above, I am referring to "nested Model tests". The problem I'm referring to with 12 variables is overfitting but obviously I'm not worried about that because I have no problem using 12 or more variables.  I am now starting to think that replacing my missing values with one of the methods of doing so might be a better way to go, such as replacing the missing values with the median or mode(if it is a categorical variable).
Answer: I suggest looking into multiple imputation for the missing data. Like other methods, this relies on them being missing at random, but may perform well even if they are missing not at random.
In R one package that does this is mice.
Answer: What you're using is called a complete factor approach to handling missing data for prediction. It's not the best way, but it's certainly easy. Are you fitting submodels using all available data or only subsets with missing data in the omitted variables?
Doing this with one model is not possible. You'll have to do it the brute force way: fit each necessary submodel, then inspect rows of data to match to your dataset and select fitted values from each model.
Comment: I don't mean visual inspection, use a loop to detect which missing variables you have and select which one you'd like to use. It should be fairly easy to determine which combinations of factors have missing variables. R has some convenience functions for fitting nested models this way. Check out the help pages around "dropterm" and related functions.
Comment: The Brute force method is what I'm trying to get away from, I have thousands of students to find probabilities for so there's no way for me to do each one.  I haven't actually found my sub models yet, looking for the easiest way to do this before I do that.  Right now it appears there would be so many submodels that another method may be better.

Nested logistic regression in R


Functions - if statement in equation: applying discount to total price for up to 10 products

Question: I came across this question on a test.

A video game store sells video games for \$30 each. The store has a
  coupon for $9 off the total purchase for up to 10 games.
Determine the equation of the function that describes the relationship
  between the total cost and the number of video games a customer buys.

I am in grade 11 and with the things we learned, I don't think there is a way to solve this. In code, I can figure out an easy way of solving this by using if statements. I am not sure about how to solve this in math?
I was thinking:
Let c be total cost
Let g be one game
c = g(30) - 9

But that would not work for more than the discount.
How would one go about doing this?
Please help. Thank you.
Comment: Why would it not work?
Answer: I think your answer is correct and that the question is confusing. As it's written, the calculation of the discount doesn't depend at all on how many games you buy, as long as you buy at least one. The "up to 10 games" has no effect. So yes, the equation is
$$
c = 30g -9 .
$$
That's a better way to write it than $g(30)$, and you should probably say "let $g$ be the number of games".
If the question said there was a coupon of $10 per game for up to 10 games (rather than for the total)  then you would indeed have to write a formula with an implicit "if":
$$
c = \begin{cases}
21g & (1 \le g \le 10)  \\
210 + 30(g-10) & (10 < g)
\end{cases}
$$


Backbone.js Unable to parse response from collectio.toJSON()

Question: I am learning Backbone and it would be great if someone can help me with this issue. After I do a fetch on my collection, in success callback I get the parsed data using collection.toJSON(), this actually returns an object and I am unable to get anything out of this object. This object actually has data that I need.

My question is how do I access rows property in my object. Here is my code for your reference
  var testCollection = Backbone.Collection.extend({
    model:myModel,
    url: '/myApiEndPoint',
    data: '',
    initialize: function(models, options) {
        this.data = models.data;
    },
    fetch: function(options) {
        var ajaxConfig = {
            url: this.url,
            data: this.data,
            type: 'POST',
            dataType: 'text',
            contentType: 'text/xml',
            parse: true
        };
        options = _.extend({}, ajaxConfig, options);

        return Backbone.Collection.prototype.fetch.call(this, options);
    },
    parse: function(xmlResponse) {
            // I have some parsing logic to extract uid and rows from my xmlResponse
            return {
              uid: uid,
              rows: rows
            };
      },
  });

var collObj  = new testCollection({data: xmlQuery1});
collObj.fetch({
  success: function(collection){
    // This code block will be triggered only after receiving the data.
    console.log(collection.toJSON());
  }
});

Answer: As the name toJSON suggests, it returns you the array of JSON objects where each object is a Model's JSON object. You can fetch the required properties in this way:
collObj.fetch({
  success: function(collection){
    // This code block will be triggered only after receiving the data.
    console.log(collection.toJSON());
    var uid = 'uid-of-an-object-to-access';
    var rows = collection.get(uid).get('rows');
    console.log(rows);
  }
});


Changes made by merge commits not found by `git bisect` or `git log -S --all`

Question: I made a fix to a file, and committed it to my git repository.
Some time later, I found that it had regressed. I wanted to know in which commit the fix had been taken out, so I tried git bisect and git log --all -S TERM, where "TERM" was a string added by my fix and which appeared nowhere else in the project.
I found that git bisect blamed an unrelated commit, and I found that git log --all -S TERM only listed the commit in which I added TERM, and didn't list any commits as having removed it, even though it was no longer in the file at "master".
After some manual searching, I found that there had been a merge commit between two branches. One branch had my fix and one did not. The merge author had picked the branch without my fix (strange, as there was no conflict in the file).
My questions are:

Why can git bisect not find merge changes? I don't see anything in the manpage about this limitation. Is there a different way to use it that will find the bad merge in the above scenario?
Why does git log --all -S TERM not list the merge commit? The manpage says it lists commits which "introduce or remove an instance of ". Does that merge commit not remove my string? Is there a different way to use it that will find the bad merge in the above scenario?
If git bisect and git log -S are useless in the above scenario, what is an efficient way to find the bad merge? It look me quite a long time to track down the change in question without these tools.
Comment: git bisect _can_ find merge commits but if there's an older commit (e.g. ancestor on the far side) in the range which you are bisecting that has the "broken" version of the file then obviously that will be preferred.
Comment: Yes, that's probably what happened to me. Are there any workarounds to get `bisect` to find the real culprit in that case?
Comment: That's a good question, you really need to limit your bisect range to only those commits that have your fix as an ancestor... not sure
Comment: You really need a combination of `--ancestry-path` from `rev-list` and `bisect`. I'm not sure if you can use both together, though. If you could, the first merge that wiped your change ought to get fingered.
Comment: git reflog and git reflog --all will give you the commit hashes of the mis-placed commits. try to find using that.
Answer:
Why does git log --all -S TERM not list the merge commit?

You must add the -m option to it:
git log -m --all -S TERM

In order to understand why a special option is needed in that case, let's first look at the operation of git log -p which must include the changes in the listed history. As you can easily check, by default for merge commits changes are NOT shown. The reason is that a change is the difference between two revisions whereas for a merge commit we have three (or more) revisions. The -m option to git log addresses that problem:

Diff Formatting
...
-m
This flag makes the merge commits show the full diff like regular commits;
  for each merge parent, a separate log entry and diff is
  generated. An exception is that only diff against the first parent is
  shown when --first-parent option is given; in that case, the output
  represents the changes the merge brought into the then-current branch.

Then, assuming that git log -S works as if by processing the diff returned by git log -p you should admit that by default the merge commits would be excluded from the results. However, fortunately you can combine the -S and -m options in git log and it works as expected.
Comment: Unfortunately this doesn't seem to work correctly for me on git 2.15.1.windows.2. The output includes merge commits that don't appear to change the given text - and the same is true of `-G`.
Comment: @RobinGreen Did you look at the output of `git log -m -p`? Does it make sense? Are the results of `git log -m -S` consistent with the output of `git log -m -p`?
Comment: Thanks for your answer, this is very useful! I haven't accepted it yet, as it doesn't cover `git bisect`. Also, you might want to put the command `git log -m --all -S TERM` at the top of your answer, as it is currently buried right at the bottom and not fully spelled out.
Comment: @Rich Agree. Updated.
Comment: Note that this solution doesn't work when we specify a specific file to git log (`git log -m --all -S TERM path/to/file/toSearch`): the normal commits are correctly searched, but the merge commit are not shown. I don't know why.
Comment: @Jidehem Specifying the `path` argument to git log makes it list only those commits in which the file `path` was modified. Are you sure that the merge commit that is not shown modifies your file?
Comment: @Leon: yes, the file is modified. Or rather: the file is kept unchanged in respect to merge parent A. However, it is modified in respect to parent B. Merge handling is tricky.
Answer: Solution using git bisect
git bisect start $badCommit $goodCommit
git bisect run bash -c "! git merge-base --is-ancestor $goodCommit HEAD || git grep -q $TERM"
bit bisect reset

Note: this solution use git bisect run for simplicity. You can use git bisect in "interactive" mode too. See Explanation section below.
Main idea
The idea is to restrict the commits analyzed by the bisect algorithm to the ones in the ancestry path.
The idea was suggested by CB Bailey in this comment, although I didn't find a way using git rev-list.
Explanation
For the part about git bisect, the explanation is a bit tricky.
It is based on how the bisect algorithm works.
The algorithm makes the assumption that all ancestors of a good commit are good.
Thus, when testing a specific commit in git bisect, you must mark commits that are not descendants of the good commit as good too. This typically not the case when using only a simple grep function.
You can tell if commits are descendant of another commit using git merge-base --is-ancestor $goodCommit HEAD (more details on How can I tell if one commit is an ancestor of another commit (or vice-versa)? or checking if a commit is an ancestor of another)


Does the recursion theorem give quines?

Question: Wikipedia claims that the recursion theorem guarantees that quines (i.e. programs that output their own source code) exist in any (Turing complete) programming language.
This seems to imply that one could follow the algorithm given in the proof of the recursion theorem to create a quine. However, the proof of the recursion theorem (and indeed the recursion theorem itself) only seems to guarantee the existence of a program that outputs its own index, which is, strictly speaking, different from outputing it's source code.
The simple observation that no Turing machine whose tape alphabet consists solely of $0$'s and $1$'s can output its own source code, since its source code is a finite set of tuples, implies that quines cannot exist there. However, it seems likely as long as the alphabet is sufficiently rich (or the language sufficiently limited) it should be possible to write a bona fide quine.
Question 1. Can the proof of the recursion theorem be transformed into a quine in any sufficiently expressive programming language?
Question 2. If the answer to Question 1. is "no", how do we know if and when quines exist?
Comment: Also, for all you know the index *is* the source code of the program, literally, if we use finite strings for our indexes. The use of natural numbers instead is just a choice of presentation, because we mathematicians typically study number-based rather than string-based models of computation. But we could perfectly well use "idealized C" as our model of computation, in which case all the inputs and outputs could be finite strings, literally including programs.
Comment: In the context of Turing machines, a Quine would be a Turing machine program that takes no input, writes itself as output, and then halts. Such Turing machine programs do exist, by the recursion theorem; they are fixed points of the Turing-computable function $F$ that given $e$ produces a Turing machine program to print $e$.
Comment: If we're talking about programs that output numbers (in some particular encoding), it must be possible to interpret the source code as such a number.  In a reasonably expressive language it is possible (maybe even easy) to write a program that will translate from one particular encoding to another.
Comment: @Quinn Culver: is there an aspect of the question that hasn't been answered?
Comment: @CarlMummert I'm still considering it. In particular, I'm trying to figure out how I would follow the proof to write a quine in any (sufficiently rich) language (other than one like LISP where self-reference is inherently possible). I'm not sure if I agree that it's just as good to output an index. It somehow seems better to output the *bona fide* code. Henning indicated that even that is possible, so I want to know exactly why and how.
Comment: @Quinn Culver: I tried to explain that in the bullets in my answer;. If you could you point out the first place that explanation goes off track for you, I can try to expand it.
Comment: Don't you mean "If the answer to Question 1...."?
Answer: The variant of the recursion theorem you have seen is formulated in terms of indices because it assumes a "programming language" where indices of Turing machines are what program texts look like. We define that a "program" in this language consists of an index in some well-defined enumeration of Turing machine, so if we find a machine that outputs its own index, that index is a quine from the perspective of this programming language.
However, the theorem generalizes to any reasonably behaved notion of programming language, as long as we fix a way to encode a program text as something that can be (part of) the input and output of a running program. Here's how the theorem is stated in Jones, Computability and Complexity from a Programming Perspective:

Theorem 14.2.1 (Kleene's second recursion theorem.) For any $\tt L$-program $\tt p$, there is an $\tt L$-program $\tt q$ satisfying, for all inputs ${\tt d}\in{\tt L}\text{-}\mathit{data}$:
  $$ \tt [\!\![q]\!\!](d) = [\!\![p]\!\!](q,d) $$
  Typically $\tt p$'s first input is a program, which $\tt p$ may apply to various arguments, transform, time, or otherwise process as its sees fit. The theorem in effect says that $\tt p$ may regard $\tt q$ as its own text, thus allowing self-referential programs.

(Here $\tt[\!\![{\cdot}]\!\!]$ is the function that takes a program text to its meaning as a partial function, and the equals sign means that either the two sides are defined with the same value, or both sides diverge).
In particular if $\tt p$ is a program that outputs its first argument, $\tt q$ will be a quine.
This more general statement can be proved using basically the same techniques as the one for Turing machine enumerations that one finds in mathematicians' textbooks.
Comment: @QuinnCulver: The point is that it works with _any_ coding you'll care to specify, as long as program executions and certain other, very simple, program manipulations are computable with the coding you select. The general technique can certainly be used to produce a C quine, though it would be a very complex one, incorporating one or several layers of C self-interpreters to do the job.
Comment: @QuinnCulver: It does not make sense to "distinguish between programs that output their own index and ones that output their actual source code" -- in the "programming language" we're considering here **the index IS THE SOURCE CODE**. To answer your question: The general technique can certainly be used to produce a C quine, though it would be a very complex one, incorporating one or several layers of C self-interpreters to do the job.
Comment: I don't fully understand your answer, since I don't know exactly how the coding works in Jones' book (though I intend to understand). But are you saying that one could indeed write a program (in, say, C) that outputs its own code simply by following the proof of the recursion theorem?
Comment: Okay. Does your current answer make that point clear? I.e. is it clear from your answer that if I wanted to write my own *bona fide* quine (I use '*bona fide*' to distinguish between programs that output their own index and ones that output their actual source code) in, say, the language C, I could follow the proof of the recursion theorem to write one?
Comment: Indeed "index" is just a jargon term for "program", which we use because we want to emphasize that the results we prove work for any acceptable indexing, not just for some specific programming language.
Answer: The Wikipedia article has an explicit example in LISP of how to use the method of the proof to generate a Quine. The proof of the recursion theorem is entirely constructive and syntactic, so it can be implemented in any other Turing complete language.
Looking at the section there called Proof of the second recursion theorem:

The programming language will be able to implement the function $h$ defined at the top of the proof, because $h$ is computable and the language is Turing-complete

In particular, $h$ is a program that takes as input a program (source code) $x$ and produces as output a program (source code) $h(x)$. The source code given by $h(x)$ does the following: on input $y$, $h(x)$ first simulates the running of source code $x$ with itself as input. If that produces an output $e$, then $h(x)$ proceeds to simulate running the program $e$ with input $y$.
The program $h$ can be implemented in any Turing complete language; the main point is that you have to write an interpreter for the language within the language itself, so that $h(x)$ can use that interpreter as a subroutine to simulate running any source code on any input.

Furthermore, the language will be able to implement $F \circ h$ because $F$ is also computable. To do this, just use the source code for $h$ and then use its output as an input to the source code for $F$.
Let $e_0$ be a specific program (source code) that implements $F \circ h$. Let $e = h(e_0)$.
Then the program $e$ will compute the same function as the program $F(e)$, as the proof shows.
Thus, in the special case where $F(e)$ returns source code for a program that does nothing but return $e$, because program $e$ computes the same function as $F(e)$, program $e$ also returns the source code for $e$ when it is run.

In fact, program $e$ does something stronger than computing the same function: examining the proof show that program $e$ actually computes the source code for $F(e)$ and then runs (or interprets, or simulates) that. So if $F(e)$ has side effects, like printing something, $e$ has the same side effects.

For any Turing complete language, you can follow this sequence of steps to get a Quine in that language.
The interest for people who write Quines is generally to make ones that are shorter than the ones obtained by this method. The proof of the second recursion theorem is more general than is needed for that special purpose, and the Quines it generates would be very long, because the program that computes $h$ includes, in most cases, an interpreter for the language at hand. So to implement $h$ in $C$, you have to write a $C$ interpreter in $C$. This is why LISP gives a better example, because it is much more straightforward to interpret LISP in LISP.
Comment: The usual literature doesn't emphasize that it would be possible to have a numbering where not every index is actually a valid program. This is because, in any reasonable programming language, the set of syntactically valid programs is decidable (in fact primitive recursive), and so we could just declare *by fiat* that any program that is syntactically incorrect will now compute some fixed function, at which point every string is now a "valid" program in the new sense. But even if the set of indices that are valid programs is not decidable, most results go through anyway.
Comment: I think my main concern is that we must consider every string to be a program; i.e. we must have a (computable) bijection between strings and programs. Of course, some of those strings were already programs, but many were not. I'm worried that what will be output will be only the program's corresponding string and that then the "quine" gotten by following the recursion theorem's proof will only output its corresponding string.
Comment: The construction still works if only some strings are valid programs. In that situation the simulator can do whatever it wants with an invalid program. Regardless of what it does, the output of $h$ will always be a syntactically valid program (regardless whether the input $x$ is valid), and $e$ will still be a syntactically valid program, which will be a quine.
Comment: When you say, "then the program $e$ will compute the same function as the program $F(e)$, as the proof shows.", I think you mean "then the program $h(e)$ will compute the same function as the program $F(h(e))$, as the proof shows."
Comment: I'm now convinced. I think what I didn't realize is that $F$, in the proof, doesn't have to be an arbitrary function from strings to strings, but can merely be one that only takes programs and always outputs programs, as the special case in your point 5. can be taken to be.
Comment: Thanks for the correction. One benefit of fixing it is that it makes it more clear that $e$ is actually a syntactically correct program, because it is $h(e_0)$ and $h$ of anything is a syntactically correct program due to the definition of $h$.
Answer: Regarding your doubts about source code being the same as the index (or not), you can think of it this way:
The source code of a program is some string of characters.
Those characters are encoded in some way with numbers, let's say ASCII codes.
Now you can think of each character as a digit in a base-$256$ number system.
So you start with the first character and take its ASCII value, then add to it the second character's ASCII value multiplied by $256$ (the first power of $256$), then add the third character's ASCII value multiplied by $256^2$ (second power of $256$), and so on, up to the last character.
This way you will get a very huge natural number, which uniquely represents this particular program (its source code). So this number is the index of that program.
Sure, there would be indices which does not represent any valid program (since not all possible outputs are programs, just a subset of them are). But it doesn't matter. The only important thing is that every program has its own unique index.
Here's an example program in my own toy language:

say "Hi!";

and here's its index:

279 249 219 322 602 409 517 427

and how I calculated it:
$'s'\cdot256^0 \;+\; 'a'\cdot256^1 \;+\; 'y'\cdot256^2 \;+\; '\ '\cdot256^3 \;+\; '"'\cdot256^4 \;+\; 'H'\cdot256^5 \;+\; 'i'\cdot256^6 \;+\;\\
'!'\cdot256^7 \;+\; '"'\cdot256^8 \;+\; ';'\cdot256^9
\\=\\
115\cdot256^0 \;+\; 97\cdot256^1 \;+\; 121\cdot256^2 \;+\; 32\cdot256^3 \;+\; 34\cdot256^4 \;+\; 72\cdot256^5 \;+\; 105\cdot256^6 \;+\;\\
33\cdot256^7 \;+\; 34\cdot256^8 \;+\; 59\cdot256^9
\\=\\
115\cdot1 \;+\; 97\cdot256 \;+\; 121\cdot65\,536 \;+\; 32\cdot16\,777\,216 \;+\; 34\cdot4\,294\,967\,296 \;+\;\\
72\cdot1\,099\,511\,627\,776 \;+\; 105\cdot281\,474\,976\,710\,656 \;+\; 33\cdot72\,057\,594\,037\,927\,936 \;+\;\\
34\cdot18\,446\,744\,073\,709\,551\,616 \;+\; 59\cdot4\,722\,366\,482\,869\,645\,213\,696
\\=\\
115 \;+\; 24\,832 \;+\; 7\,929\,856 \;+\; 536\,870\,912 \;+\; 146\,028\,888\,064 \;+\; 79\,164\,837\,199\,872 \;+\; 29\,554\,872\,554\,618\,880 \;+\; 2\,377\,900\,603\,251\,621\,888 \;+\; 627\,189\,298\,506\,124\,754\,944 \;+\; 278\,619\,622\,489\,309\,067\,608\,064
\\=\\
279\,249\,219\,322\,602\,409\,517\,427
$
Therefore, when a quine prints its own source code, it can be thought of as outputting a single natural number, which is exactly the same as the number which represents its source code (its index).
Comment: This is just a matter of interpreting the output of the program. After all, it's just a stream of bits, which can be interpreted as bytes (base-256 digits of that number), and then those bytes as characters. But it is not the problem of the program how do we interpret these bytes. It's the choice of the operating system, execution environment and the user. You can set up your execution environment to display stream of bits instead of textual output, but it doesn't affect the program and how it works. We, users, see characters. Computers see only streams of bits.
Comment: I understand how Gödel numbers work. My problem was that I wanted a program that output not it's index, but it's actual, human-readable, code (which can be gotten from the index).
Comment: My point is that if I wanted, say, to impress someone by writing a Quine, but all they saw was a program that output it's own Gödel number, the person probably wouldn't be too impressed. See what I mean?

Does the recursion theorem give quines?


How to alter the output of a file-field as a custom field-widget

Question: I am implementing a custom field-widget for the file-field in Drupal 8.
I extended the FileWidget class as my widget uses most of the file-field-widget functionality.
There is just a small part I want to theme/customize from the file upload form, the part I marked in the following screenshot:

What is the best way to alter the output from a field-widget?
I want to add some surrounding container elements and similar things you do in a theme function.
Comment: What do you want to change, just the styling? File fields are different from others when it comes to styling, most of it is done by the browser. There are a few possblities though, but it isn't as straight forward as you'd think, here's an example: https://css-tricks.com/snippets/css/custom-file-input-styling-webkitblink/
Comment: Thank you, but this is not about css. I want to theme the file field marked in the screenshot. I want to add some surrounding containers and so on. The usual things you do in a theme function.
Comment: I updated the question to make it more clear
Answer: The file field for uploading is defined in the render callback of ManagedFile:
public static function processManagedFile(&$element, FormStateInterface $form_state, &$complete_form) {
  ...

  // The file upload field itself.
  $element['upload'] = [
    '#name' => 'files[' . $parents_prefix . ']',
    '#type' => 'file',
    '#title' => t('Choose a file'),
    '#title_display' => 'invisible',
    '#size' => $element['#size'],
    '#multiple' => $element['#multiple'],
    '#theme_wrappers' => [],
    '#weight' => -10,
    '#error_no_message' => TRUE,
  ];

So one way to change the output of the field is to define a custom form element which extends File. The element can be themed as wanted.
And in the process callback of the custom widget the type of the upload element can be overwritten to use the newly defined element:
public static function process($element, FormStateInterface $form_state, $form) {
  $element = parent::process($element, $form_state, $form);
  $element['upload']['#type'] = 'myCustomFileElement';
  return $element;
}

Answer: To add custom html wrapper around, you should use drupal form API #prefix and #suffix attribute to form element.
For example:
function HOOK_form_FORM_ID_alter(&$form, &$form_state, $form_id){
  $form['field_my_field']['#prefix'] = '
';
  $form['field_my_field']['#suffix'] = '
';
}

Here you need to replace HOOK with your custom module name,and FORM_ID with id of form.
Hope it will help.
Comment: You're right, that would be working. I could also override a theme function, but I want to do this as a field widget.
Comment: What do you mean by "What is the best way to alter the output from a field-widget?" in your Original Post? Do you mean the field-widget will alter the output? Or are you trying to customize the look of the field-widget? Or...?
Comment: I want to provide my own file field widget. This widget is based on the file field widget but has some modifications and also has a different look. Therefore I need to alter the markup of the upload form. So yeah, I want to customize the look of my widget.


Pra que serve o mappedBy do JPA?

Question: Exemplo:
@OneToMany(mappedBy = "chemical", fetch = FetchType.LAZY)
@LazyCollection(LazyCollectionOption.EXTRA)
@JsonIgnore
private List<SimulationChemicals> simulationChemicals;

Porque o uso do mappedBy é obrigatório ou importante? não entendi ainda a função dele.
Answer: O mappedBy é para indicar qual é o lado inverso ou não dominante da relação.
Diferente da annotation @JoinColumn que indica que a entidade é a responsável pelo relacionamento.
Ex:
public class Endereco {

    @Id
    @GeneratedValue
    private long id;

    private long numero;

    @OneToOne(mappedBy = "endereco") //Endereço não é o lado dominante
    private Pessoa pessoa;

    //getters e setters
}

Answer: Pode existir relacionamento Unidirecional ou Bidirecional. Quando é unidirecional apenas uma classe tem a referência, que é o atributo, e este é anotado.
@Entity
public class SystemUser {
  @OneToOne
  private Debt debt;
}

Quando é Bidirecional as duas classe tem um atributo referenciando uma à outra.
@Entity
public class SystemUser {
  @OneToOne
  private Debt debt;
}

@Entity
public class Debt {
  @OneToOne
  @JoinColumn(mappedBy = "debt")
  private SystemUser systemUser;
}

Adiciona o atributo mappedBy no lado que não é dominante. Na class SystemUser tem um atributo debt, este é o nome que será usado do mappedBy.
Caso não fosse usado o atributo mappedBy, iria ser criado dois relacionamentos entre SystemUser e Debt. Cada relacionamento com um lado dominante.
Tome cuidado com relacionamentos Bidirecionais. Procure mais sobre eles.

Pra que serve o mappedBy do JPA?


ListActivity não funciona Android

Question: Eu tenho uma Activity com um botão chamando uma List Activity. Essa ListActivity cria rapidamente uma lista de string, só quero mostrar essa lista na tela e exibir em um Toast o item selecionado.
Mas não está funcionando! Segue o código da classe Lista
public class Lista extends ListActivity{

    protected void OnCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        String[] itens = new String[]{"João","josé","pedro",};
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,itens);
    setListAdapter(adapter);
    }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);

        Object o = this.getListAdapter().getItem(position);
        String item = o.toString();
        Toast.makeText(this, "Clicou em: "+item, Toast.LENGTH_SHORT).show();
    }

}

O que está faltando?
Comment: Qual o erro apresentado no console? O método chega a ser chamado? (coloque o debug ou um sysout para verificar)

Se uma melhor descrição do cenário fica difícil ajudar
Answer: O código Java é case-sensitive, isso quer dizer que Double é diferente de double, String é diferente string e assim por diante.
Logo, você tem um erro no seu código já que o método OnCreate não existe na classe ListActivity (e por sua vez, na Activity) que foi herdada e acontece que ela nunca é executada em sua classe. Portanto, você só precisa alterar o erro de grafia para onCreate na assinatura do método:
protected void onCreate(Bundle savedInstanceState)

É sempre bom utilizar a anotação @Override, assim garante que o método que está querendo redefinir realmente existe na super classe.
Comment: Entendi. Bom, sou iniciante no java, neste momento não posso testar isso, mas vou validar sua resposta o quanto antes.

ListActivity não funciona Android


Specific chord confusion: why the C# in Eb7 b9 13?

Question: needing the expert help on the forum as I simply can't understand this. Following a vid, the player mentions he plays Eb7 9b 13 chord. The melody note is C, and he plays 1-3 (Eb, G) in left hand. What I don't understand is that in his right hand hes playing  C#,E,G,C. Does he misspoke? Or is it simply something basic I don't understand. The 9b and 13 I understand, moves the root and 7 a half step. But the C# I got no idea.
Comment: Reference to the video would reveal which actual notes (their octaves) are involved. Assuming it's piano.
Answer: The C# is enharmonically Db, which is the b7 of the Eb7 chord. As for the 9b, it is typical to put the accidental before the chord tone, b9 instead of 9b. Also, the b9 should not be an E but rather an Fb because the letter E is used by the root. This chord can also more simply be named Eb13b9.
From low to high you have Eb, G, Db, Fb, G, C.
This is R, 3, b7, b9, 3, 13.
This particular voicing has a doubled 3rd and no 5th.
Answer: I'm guessing you shouldn't call it C# but rather Db... which is the seven in Eb7.


How to add both long-term and short-term interest rates as variables for a GARCH model?

Question: I was facing some difficulties with a model of mine. I want to look up how the portfolio reacts to interest rate changes and I would like to use a GARCH model. However, both the short-term and long-term rates have unit roots and therefore I need to change them up I believe? I tried to dlog both of them, but since short-term interest rates from my period have been zero, EViews pops up an error. Is there a better way to deal with this, as I need to discuss the interest rate risk on a certain portfolio?
Answer: Consider including changes in interest rates, i.e. simple differences without taking the logarithm first. Logarithms work well for variables (such as GDP) that grow exponentially over time. Interest rates do not do that, and thus are not usually modelled with logarithms.
Actually, even taking the first differences of interest rates is questionable, as discussed e.g. in Cochrane "A Brief Parable of Over-Differencing" (2018). But over short intervals of time the high level of persistence in interest rates may justify differencing.
Comment: Thank you for the swift reply! Do I take the simple difference (Interest at t MINUS interest at t-1) or I take the simple growth (interest/interest(-1))-1?
Comment: @VeryPleasant, take the simple difference: $\Delta x_t:=x_t-x_{t-1}$. The growth rates you propose are very similar to diff(log(.)), and the latter do not make much economic sense.
Comment: So in Eviews if I want to estimate the interest rate risk on my portfolio, I would put into the Garch estimator window dlog(portfolio) c dlog(market) deltatbill deltatbond ar(1)? Or is there something wrong with a model like this?
Comment: @VeryPleasant, it has been more than a decade since I used EViews last, and I have mostly forgotten the syntax. Could you write the model equation(s) mathematically instead?
Comment: Not sure how to correctly write this in a mathematical way but I'll try to write this as clear as I possibly can.
For the garch model my variables are:
First log difference on portfolio value (20years of data);
C as a constant, i.e. alpha;
First log difference on the S&P index prices;
Simple difference of Tbill rates (interest at time t MINUS interest at time t-1);
Simple difference of Tbond rates (interest at time t Minus interest at time t-1);
Comment: The problem I'm getting is that all of the portfolio is based on insurance companies, which are exposed to interest rate risk. However, whenever I run a regression like this, I get that both the changes in tbill and tbond rates are insignificant, therefore I believe I'm making a mistake somewhere or I'm using the model incorrectly
Comment: @VeryPleasant, I do not know enough about the subject matter to comment on that.
Comment: @VeryPleasant, what do you think about my answer? If it is helpful, consider accepting it by clicking on the tick mark to the left. Otherwise, you may ask for further clarification. This is [how Cross Validated works](https://stats.stackexchange.com/tour).


Convergent series and divergent series $\sum\limits_{n=1}^\infty \frac{n}{n^3+1}$ and $\sum\limits_{n=1}^\infty \frac{n^2+1}{n^3+1}$

Question: Hi I have two questions.
First, $\sum_{n=1}^\infty \frac{n}{n^3+1}$.
Is it divergent or convergent? I think it seems like it is positive and decreasing function so we can apply integral test. however, integrating this function is not an easy task.
Is there any other test I can use?
Second, $\sum_{n=1}^\infty \frac{n^2+1}{n^3+1}$.
I can't think of any test,,
Can anyone give me an idea please~
Comment: Don't the terms in the first sum resemble $1/n^2$? And in the second sum, don't they resemble $1/n$?
Comment: So for the first one I can use comparison test so that 1/n^2 is greater than that and is convergent and it must be converegent
Comment: for the second part I think I could use comparison test but can't see which  one shall I use
Answer: A great starting point on these questions is to "ignore all the small pieces" and see what happens. For instance, for large $n$, the $+1$ in the denominators won't really matter. So the first really looks like
$$ \sum_{n \geq 1} \frac{1}{n^2}$$
and the second looks like
$$ \sum_{n \geq 1} \frac{1}{n}.$$
Some calculus books have a so-called "limit comparison" test that makes this analysis rigorous. Barring that, let's see if we can do better.
In the first,
$$ \sum_{n \geq 1} \frac{n}{n^3 + 1} < \sum_{n \geq 1} \frac{n}{n^3} = \sum_{n \geq 1} \frac{1}{n^2}.$$
In the second, $$\sum_{n \geq 1} \frac{n^2 + 1}{n^3 + 1} > \sum_{n \geq 1} \frac{n^2}{n^3 + n^3} = \frac{1}{2}\sum_{n \geq 1}  \frac{1}{n}.$$
Comment: Thanks makes a lot sense to me
Comment: I made the numerator smaller and the denominator bigger.
Comment: for the second part, how can I show that n^2/n^3+n^3 is less than n^2+1/n^3+1?


Angular 2 Typescript class property allows incorrect type to be assigned

Question: Why doesn't this cause an error?
export class Foo {
    a: any;
    b: number;
}

export class MyClass {
    public data: Array<Foo>;
}

I assign a string to property of MyClass and no error is caused. Shouldn't this cause an error?
export class MyComponent {
    classyClass: MyClass;

    constructor() {
        this.classyClass = new MyClass();
    }

    myFunction = function() {
       this.classyClass.data = 'abc';
    }
}

Answer: If you use
myFunction = function() {
    this.classyClass.data = 'abc';
}

then this will point to myFunctions instance and not to your component. You should use:
myFunction(){
    this.classyClass.data = 'abc';
}


Nginx does not serve large files

Question: When trying to download a large file (not sure what size is enough, trying to download 5Gb), connection is stuck:
$ wget --verbose http://example.net/large.zip -O /dev/null
--2016-12-14 12:52:38--  http://example.net/large.zip
Resolving example.net (example.net)... 188.8.131.52
Connecting to example.net (example.net)|22.214.171.124|:80... connected.
HTTP request sent, awaiting response...

And this is going on forever, and by forever I mean 10 minutes at least.
nginx config for this kind of files:
location ~* ^.+\.(css|js|ogg|ogv|svg|svgz|eot|otf|woff|mp4|ttf|rss|atom|jpg|jpeg|gif|png|ico|zip|tgz|gz|rar|bz2|doc|xls|exe|ppt|tar|mid|midi|wav|bmp|rtf)$ {
   access_log off;
   log_not_found off;
   expires 7d;
}

Small static files (and by small I mean for example 50Mb ones) are served fine.
Turning access_log off; to "on" does not help, there is nothing in logs on this request.
Changing file type from zip to another type does not help.
The most strange thing is that if I start the download and after this restart nginx, the download starts just fine. But only this one. If you start another download after server restart, it doesn't work in the same way.
Answer: For me the remedy were these two settings:
In the file:
    /etc/nginx/nginx.conf
Add:
proxy_max_temp_file_size 0;
proxy_buffering off;

Between the lines client_max_body_size 128M; and server_names_hash_bucket_size 256;:
http {

client_max_body_size 128M;
proxy_max_temp_file_size 0;
proxy_buffering off;
server_names_hash_bucket_size 256;

Comment: `client_max_body_size` was enough for me. I had an app in Django with Gunicorn, and on Nginx access.log, `504` was present always and I thought that maybe, some timeout on Nginx or in Gunicorn, or even `limits.conf` (a lot of files were being requested), but there was a process on my app for generating PDF files containing dozens of images, and the report, had 171Mb. That's my story :).
Comment: `client_max_body_size` was enough for me too! I use nginx as a reverse proxy and it was failing when the backend sent huge images. Now it works perfectly!
Answer: The answer appears to be in these links. One, two. Basically, disable the disk cache
location / {
  proxy_max_temp_file_size 0;
}

Comment: Nothing of these works, unfortunately. aio on; sendfile off; proxy_max_temp_file_size 0;
Comment: Sorry, found the problem. See my answer below
Answer: Oops my mistake.
There was a CDN configured in front of this server. And it needed too much time to get those files completely before it started to serve them. That's why the download started instantly when I restarted nginx. CDN was giving the incomplete file.
Comment: Well I ALWAYS forget this particular detail about this particular server. Next time I need a checklist with the only item "Is it because of CDN?"
Comment: Ah, interesting. This is why explaining the whole environment in a question is good. Please accept your own answer.

Nginx does not serve large files