Como saber se o Modal está com scrolling ativo?

Question: Tenho um modal que faz scrolling quando o conteúdo da janela é maior na tela..., gostaria de colocar uma classe diferente quando o scrolling do modal estivesse ativo, no exemplo abaixo ele muda a classe mesmo sem scrolling:
Meu controller do modal:
app.controller("ModalController", ["$scope", "$uibModal",
    function($scope, $uibModal) {

        $scope.verifyScroll = function() {
            var doc = $(document).height(); //gostaria de saber aqui qual elemento eu devo capturar baseado no html abaixo?
            var win = $(window).height();
            $scope.scroll_option = (doc > win) ? 'scrolling' : '';
        };

    }]);

HTML renderizada do modal:

            <button type="button" class="close close-modal" ng-click="cancel();hideTooltip()" title="Fechar" aria-label="Fechar">

            </button>

Atribuir tarefa

                    Título da tarefa:
                    <input ng-if="!content.dados.indicacao" ng-model="nome_indicacao" name="nomeIndicacao" id="nomeIndicacao" type="text" class="form-control ng-pristine ng-untouched ng-valid ng-scope ng-empty">

                        Início:
                        <input ng-if="!content.dados.indicacao" name="date_start" type="date" id="date_start" value="2018-08-10" class="form-control form-date date-indication ng-scope">

                        Término:
                        <input ng-if="!content.dados.indicacao" value="" ng-model="date_end" ng-blur="onChangeDateEnd(date_end)" name="date_end" type="date" id="date_end" class="form-control form-date date-indication ng-pristine ng-untouched ng-valid ng-scope ng-empty">

                            <input ng-if="!content.dados.indicacao" name="status" type="checkbox" id="statusIndicacao" ng-true-value="'1'" ng-false-value="'0'" class="form-check-input ng-scope" ng-checked="true" checked="checked">

                            Ativar tarefa

 0">

                        Selecione as atividades a serem atribuídas:

                            Pré
Leitura 1

                            Pré
Leitura 2

                            Leitura

                            Pós
Leitura 1

                            Pós
Leitura 2

                    Pré Leitura 1:

                        <textarea ng-focus="placeholderIndication.pre1 = ''" ng-blur="placeholderIndication.pre1 = placeholder" placeholder="Escreva aqui as instruções para os seus alunos." ng-model="tarefasProfessor.pre1" name="pre-leitura-1" class="box-text-teacher ng-pristine ng-untouched ng-valid ng-binding ng-empty" style=" resize: none;background: #f7f7f7;height: 64px;width: 99%; overflow: auto;"></textarea>

                    Pré Leitura 2:

                        <textarea ng-focus="placeholderIndication.pre2 = ''" ng-blur="placeholderIndication.pre2 = placeholder" placeholder="Escreva aqui as instruções para os seus alunos." ng-model="tarefasProfessor.pre2" name="pre-leitura-2" class="box-text-teacher ng-pristine ng-untouched ng-valid ng-binding ng-empty" style=" resize: none;background: #f7f7f7;height: 64px;width: 99%; overflow: auto;"></textarea>

                    Leitura:

                        <textarea ng-focus="placeholderIndication.leitura = ''" ng-blur="placeholderIndication.leitura = placeholder" placeholder="Escreva aqui as instruções para os seus alunos." ng-model="tarefasProfessor.leitura" name="texto" class="box-text-teacher ng-pristine ng-untouched ng-valid ng-binding ng-empty" style=" resize: none;background: #f7f7f7;height: 64px;width: 99%; overflow: auto;"></textarea>

                    Pós leitura 1:

                        <textarea ng-focus="placeholderIndication.pos1 = ''" ng-blur="placeholderIndication.pos1 = placeholder" placeholder="Escreva aqui as instruções para os seus alunos." ng-model="tarefasProfessor.pos1" name="pos-leitura-1" class="box-text-teacher ng-pristine ng-untouched ng-valid ng-binding ng-empty" style=" resize: none;background: #f7f7f7;height: 64px;width: 99%; overflow: auto;"></textarea>

                    Pós leitura 2:

                        <textarea ng-focus="placeholderIndication.pos2 = ''" ng-blur="placeholderIndication.pos2 = placeholder" placeholder="Escreva aqui as instruções para os seus alunos." ng-model="tarefasProfessor.pos2" name="pos-leitura-2" class="box-text-teacher ng-pristine ng-untouched ng-valid ng-binding ng-empty" style=" resize: none;background: #f9f6f6;height: 64px;width: 97%; overflow: auto;"></textarea>

                            Sugerido para:
                            4º ano

BICHARADA

Crônica da Nathalie

Edição 139 | Publicado em 03/04/2018

                        <button class="btn btn-default btn-blue-plano-aula" ng-click="loadPlanoAulaSugestoes(300,content.dados)">Plano
de aula</button>

                            <button class="btn btn-default btn-green-teacher" ng-click="accessActivities()">Acessar
agora</button>

                                <button class="btn btn-default btn-actions ng-binding" ng-click="assignTasks()"> Fechar a tarefa</button>

                                <button class="btn btn-default btn-actions ng-binding" ng-click="configContent();">Conteúdo escondido</button>

                                <button class="btn btn-default btn-actions ng-binding" ng-click="setFavorite(content.is_favorited)">Adicionar aos meus interesses</button>

Answer: Você deve inspecionar o elemento com a classe "modal-body".
Para saber se tem scroll, verifique se propriedade scroll é maior que o client, para width ou height, assim:
var scrollHorizontal = $('.modal-body').scrollWidth > $('.modal-body').clientWidth;
var scrollVertical = $('.modal-body').scrollHeight > $('.modal-body').clientHeight;

Answer: Eu resolvi da seguinte maneira, mas obrigado pelas ajudas:
$scope.verifyScroll = function() {
                $timeout(function() {
                var doc = ($('.modal-detalhes-block').height());
                var win = $(window).height() - 58;
                $scope.scroll_option = (doc > win) ? 'scrolling' : '';
                //console.log(doc+'>'+win);
               }, 0);
            };

Answer: Usando element.offsetHeight, element.offsetWidth , element.scrollHeight e element.scrollWidth, você pode determinar se seu elemento tem um conteúdo maior que seu tamanho.
Exemplo:

if (document.getElementById('hello')) {
}

var element = document.querySelector('#element');
if( (element.offsetHeight < element.scrollHeight) || (element.offsetWidth < element.scrollWidth)){
   // Se o "scrolling" estiver ativo o background será amarelo
  element.className = "mmm"; //muda a classe do elemento
}
else{
  //O "scrolling" não está ativo
}
div{
  width:150px;
  height:40px;
  overflow:auto;
}
.mmm{
   background-color: yellow;
}

Esse é um texto qualquer

Se o conteúdo for maior do que o tamanho do elemento a ele vai mudar para a classe "mmm" com a cor de fundo amarela


Python Matplotlib how to plot multiple graph in the same figure

Question: This is my code
import matplotlib.pyplot as plt
import matplotlib.animation as animation

from matplotlib import style

style.use('fivethirtyeight')

def animate(i):
    graph_data = open('data.txt','r').read()
    lines = graph_data.split('\n')
    xs = []
    ys = []

    for line in lines:
        if len(line) > 1:
            x, y = map(int, line.split(','))
            xs.append(x)
            ys.append(y)
    ax1.clear()
    ax1.plot(xs,ys)

fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)

ani = animation.FuncAnimation(fig, animate, interval=30000)
plt.show()

data.txt and data2.txt are just like:
0,1040
1,1074
2,1106
3,1123
4,1093
5,1067
6,1099
7,1121
8,1139

Now I have another data2.txt file and I need to plot the graph in the same figure like "overlapping". How to do this with this code?
Comment: Does this answer your question? [How to plot multiple functions on the same figure, in Matplotlib?](https://stackoverflow.com/questions/22276066/how-to-plot-multiple-functions-on-the-same-figure-in-matplotlib)
Comment: Hi Botticelli69. Welcome to StackOverflow. Could you please edit your question and paste files: data.txt and data2.txt ? The better your question is, the easier it gets for someone to answer it. Please read: https://stackoverflow.com/help/how-to-ask
Comment: oh yeah sorry! Just edited
Answer: You can make use of matplotlib's interactive mode by invoking plt.ion(). Assuming your files are named in the format data {data1, data2, data3..}, store them as a list using glob. You can then get overlapping lines read from the different files as shown here:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import style
import glob

style.use('fivethirtyeight')
#data files stored as a list in files
files=glob.glob('*data*')

fig, ax = plt.subplots()
plt.ion()
plt.show()

for i in files:
    x,y = np.loadtxt(i,unpack=True,delimiter=',')
    line = ax.plot(x,y,label=i)
    plt.gcf().canvas.draw()
    plt.legend(loc=2)
    plt.pause(1)

Comment: Yes it works! But I need the graph to stay rather than disappear after 1 second, and it need to process data in real time


.htaccess autoindex not working, 403 error

Question: I want to enable the Directory Index with Apache 2.4 on CentOS 6. First I edited httpd.conf but it didn't work so I ended up with placing a .htaccess file in the desired folder, hoping that no setting could override the .htaccess directives.
But it didn't work either, when I request the directory I get a 403.
Here is what I tried so far:

Checked that .htaccess file is working by putting garbage in it
Put those lines in httpd.conf:
<Directory "/var/www/path/to/folder">
    AllowOverride All
</Directory>

Wrote those lines in .htaccess:
DirectoryIndex disabled
Require all granted
Allow from all
Options +Indexes

Checked if mod_autoindex is enabled
Ran apache2ctl configtest -> Syntax OK
Changed file and directory ownership and group to apache, .htaccess permissions to 666

But nothing works, I just get the fancy "Testing 123.." Apache/CentOS Error page...
After Michael Hamptons comment I added the following step:

Set httpd.conf error level to 'debug'
-> Nothing is logged in error_log
-> access_log logs just:
"GET / HTTP/1.1" 403 4897 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64)
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36"

... followed by 4 font requests fo the Error page, which seems to me like I am looking in the wrong file, or the error level setting doesn't work?
Comment: Check your logs.
Answer: I turned out that there is a file named /etc/httpd/conf.d/welcome.conf which has  a directive that overrides the one in the .htaccess file:
By commenting this line out I solved my problem:
<LocationMatch "^/+$">
    #Options -Indexes
    ErrorDocument 403 /.noindex.html
</LocationMatch>

Answer found on Stackoverflow


Definition of "optimal" instruments

Question: The book I read (Davidson,MacKinnon - Econometric Theory and Methods) describes the definition of "optimal instrument variables" as the following:

Usually, and this is seen very often in other textbooks which cope with regression models, we want to estimate ${\mathbb E}\left(y | X\right)$. Another way of saying the same thing but in a more general sense is that we want to estimate ${\mathbb E}\left(y | \Omega\right)$. $\Omega$ is a information set containing all variables which determine the outcome of $y$.
In the context of instrument variable estimation we consider the usual model $y = X\beta + u$ with homoscedastic $u$'s. Now it is assumed that at least one explanatory variable of X is endogenous. Hence we want to find a matrix $W$ of instruments which minimize the asmyptotic covariance matrix of $\beta_{IV}$.

Here I get lost. It is assumed that in general $X$ can be assumed to satisfy the relation $X = \bar X + V$ where $E(V|\Omega) = 0$ and $\bar X = E(X|\Omega)$. Now $\bar X$ is supposed to be the optimal matrix of instruments but I don't get what $\bar X$ is supposed to be. Yes, it is the the expected outcome of $X$ given all the information which is in $\Omega$, but if one variable in $X$ is assumed to be endogenous and I replace this variable with a linear combination of the remaining variables which are assumed to be exogenous and that $\bar X$, I ask myself why $\bar X$ is a viable instrument. Why is this $\bar X$ not correlated with $u$ no more?
I'm not looking for a technical solution nor for a mathematical proof of some sort just. I would like to understand the idea behind this approach.
Comment: Druss, could you provide page number references to the Davidson and MacKinnon book?
Comment: Druss, I haven't had a chance to take a look at this yet. I intend to do so soon.
Comment: Hey fg nu, the page number is 318. The equation number is 8.18. I guess ive already developed a good idea. Since 2SLS estimates $E(X|W)$, which is not equal to $E(X|Ω)$ but a approximation, this is nothing else what 2SLS actually does.
Comment: Not to worry :-) You already helped me alot!
Answer: I haven't read the particular page in the book, but here is my take on that.
$\bar X = E(X|\Omega)$ $\rightarrow$ that's your 'ideal' first stage regression here. $\bar X$ is the set of all variables that are informative after controlling for everything else ($\Omega$) that determines Y.
$E(V|\Omega) = 0$ $\rightarrow$ that's the validity assumption. The unobserved factors of $\bar X$ are not correlated with the determinants of Y.
I provide you an example, Card (1992) instruments "years of education" with "travel distance to school" to determine the return on wages. He assumes that "intelligence" or "ability" is an unobserved factor that has not been controlled for. "Education" is therefore assumed endogenous as it relates to "ability".
What is the set of optimal instruments? It is the set that fulfills the definition by Davidson and MacKinnon.
Although Card uses only one instrument, the intuition can be exemplified here. In the first stage regression, $\bar X = E(X|\Omega)$, you would regress education on "distance to school" AND anything else that determines wages, e.g. age, grades, experience etc. If you can safely assume that after doing so, $E(V|\Omega) = 0$, then you have found your proper instrument.
That the first assumption includes the whole information set $\Omega$ is necessary. It is wickedly conceivable that "distance to school" is related with "age" which is assumed to be related with "wage" but also "ability", as for example, older people live farther away from cities where schools were built but may be less/more able as they are a different generation. Failing to control for that, would invalidate your second assumption, $E(V|\Omega) = 0$.
So the ideal set of instruments, needs to be correlated with your regression after 'partialling out' anything else that is known determine Y.
Comment: This gives the overall intuition of IV regressions but the current explanation falls a bit short regarding the intuition behind the optimal matrix of instruments $W$ which minimizes the asymptotic covariance matrix. It's not really a problem given that the OP's main confusion seems to lie with IV in general but for future readers this should be kept in mind. In this sense the Card example doesn't apply because he only has one instrument whereas Davidson and MacKinnon talk about the case of many instruments.
Comment: I didn't want to go into details. The op specifically asks the intuition behind why is X a viable instrument and not correlated with u. It is not correlated with u by assumption after partialling out any other effect of V.
Comment: That's why you got a +1 from me ;) I just wanted to highlight to future readers that the paragraph in the book is about something slightly different in case people have a similar question.
Comment: Thanks ;) In fact, I am trying to answer a related question posted a few days ago and sidelined into this one.

Definition of "optimal" instruments


Is mean centering required in regression? if so, what does it do?

Question: Let say we have a dataset, $\mathbf{X}$ of $m$ instances, and $n$ features, and a target scalar variable $\mathbf{y}$ ($m$ instances).
Now I want to do a regression so, I try to fit a hyperplane $ y = \mathbf{x} .\mathbf{w}$ + c.
Note : $\mathbf{w}$ is a $ n \times 1$ vector of coefficients that we need to find out.
and the $\mathbf{W} = (\mathbf{X}^T \mathbf{X})^{-1} \mathbf{X}^T \mathbf{y}$.
(Least Squares PseudoinVerse)
Now does mean centering reduce $c=0$, ie does mean centering make the fitting hyperplane pass through the origin of the new coordinate system formed after mean centering is perormed?
Comment: A similar question: http://stats.stackexchange.com/q/22329/3277
Answer: To answer the question in the text: If you center both $\mathbf{X}$ and $\mathbf{y}$, then $c$ will be 0 (up to machine precision).
To answer the question in the title: It is not necessary, but it can sometimes help in the interpretation of results, especially if you include interaction terms. Even than I would normally center on some substantively meaningful value within the range of the data, rather than the mean.
Comment: A simple example is a regression on calendar year, and nothing else. If you use years such as 2014, then the intercept will be the value predicted for the year 0. Setting aside the small detail that there was no such year, such an intercept will in many applications be way outside the range of the data and/or look absurd in any case. Switching to an origin of some round date roughly in the middle of your data (e.g. using year $-$ 1950, or year $-$ 2000) will ensure a meaningful intercept (which can then be ignored, or pointed out to beginners as perfectly sensible).


Concept of JVM thread and relation to OS thread

Question: Here is my fundamental understanding of the CPU and threads(naive!). The processor can run one thread per core.
System information on my laptop reads as show below
Processor   Intel(R) Core(TM) i7-8650U CPU @ 1.90GHz, 2112 Mhz, 4 Core(s), 8 Logical Processor(s)
**Can run 8 threads in parallel **
In order to validate my understanding i create a Spring Boot(embedded tomcat) to handle each request
<code>@GetMapping("/ping")
public String ping(@RequestParam String id) throws InterruptedException {
System.out.println(MessageFormat.format("The request id is {0}", id));
int i = Integer.parseInt(id);
long now = System.currentTimeMillis();
long period = 5000L;
long later = System.currentTimeMillis();
if (i % 2 == 1) {
  while (later - now <= period) {
    later = System.currentTimeMillis();
  }
}
return PING_SUCCESSFUL;
</code>
}
I also set the max threads on tomcat to the following

server.tomcat.max-threads=200

I now use Apache JMeter to trigger 200 requests in a duration of 1 seconds
My expectation is my system is constrained to run only 8 threads and hence the total run time of the requests should be at least (200 / 8)*5 = 125 seconds
However even the 125 seconds is not realistic as there are other applications running on my system like Browser, JMeter, IntelliJ which should account for some threads themselves.
I observe a contrasting behavior - the total runtime observed is 5 seconds . How is this possible for the system to run more threads than the limit?
( I find some understanding amiss about the threads and how the underlying processors seem to paralelize the threads)
Comment: JVM threads are 1::1 with OS threads, but these are not 1::1 with processor threads, which is what you're really asking about. Any processor thread can be pre-empted or rescheduled to wait while it is blocked on some external event such as I/O completion.
Answer: It is true that the system can run only 8 threads simultaneously, but the operating system schedules which of the eight are running at any given time and can both preempt and time slice processes to schedule other (waiting) processes for some portion of time. Java threads are isomorphic to native threads, so it's literally the operating system scheduling them (and if your computer worked like you thought, the network would stop working while your program ran).


How to link classes to project in eclipse

Question: I just extracted some classes from a jar file using a program JD GUI. Everything is great when i open the classes manually in eclipse but i would like the classes already in the project to open declarations of the classes i extracted. For now i get 'Source not found' as project is linked to the jar file.
Answer: You have a few options. For the first two, your sources will need to be in a ZIP or JAR file. I believe JD GUI has an option to export all sources to a ZIP.

When you try to open a class that doesn't have a source attachment, there should be an 'Attach Source...' button that you can click on and attach the source.
You can find the jar you want to attach sources to in the Project/Package explorer, right-click on it, and select 'Properties'. That will bring up a property dialog - select the 'Java Source Attachment' on the left-hand menu and then attach the source there.
Perhaps the easiest - since you are using sources generated by JD GUI, why not just use the Eclipse plugin from the same author? I've used it, and it works quite well: http://java.decompiler.free.fr/?q=jdeclipse.
Comment: Thanks a lot. I just used the zip file generated by the JD GUI :)


Endomorphisms in an exact sequence of vector bundles

Question: Let X be a smooth projective variety over $\mathbb{C}$. And suppose we have an exact sequence of vector bundles over $X$.
$\qquad\qquad\qquad\qquad\qquad 0\longrightarrow A\longrightarrow B\longrightarrow C\longrightarrow 0$.
Suppose $C$ is simple, i.e. $End(C)=\mathbb{C}$, is $A$ simple too?
My argument is as follows. Since $A$ is a subsheaf of $B$, $End(A)\subset End(B)$. Choose $\phi\in End(A) \subset End{B}$. So $\phi$ is a morphism from $B\longrightarrow B$, such that $\phi(A)\subset A$. Hence it induces a morphism $C\longrightarrow C$. Hence $\phi\in\mathbb{C}$.
Is this argument correct? The step where I have a doubt is that $End{A}\subset End{B}$. Any feedback will be appreciated!
Thanks in advance!
Comment: The statement about containment $End$ is not true. $End$ is not a functor and there's no reason a map $A \to A$ should extend to a map $B \to A$ (or $B \to B$).
Comment: Ah thank you @JakeLevinson! Can you give me an example when this happens?
Answer: If $0\to A\to B\to C\to 0$ is exact, so is $0\to A\oplus A\to B\oplus A\to C\to 0$, where the second copy of $A$ maps as identity to the same factor in the middle. Surely, $A\oplus A$ is not simple.
Answer: Here's a counterexample. Let $X = \mathbb{P}^1$. Take $C = \mathcal{O}(2)$, which has three global sections, i.e. there is a surjective map $\mathcal{O}^{\oplus 3} \to \mathcal{O}(2)$, which is an isomorphism on global sections. Let $K$ be the kernel, a rank-2 vector bundle.
Since every vector bundle on on $\mathbb{P}^1$ splits as a sum of line bundles, $K = \mathcal{O}(a) \oplus \mathcal{O}(b)$. The Chern class of $K$ must satisfy
$$c(K) = (1+a[pt])(1+b[pt]) = \frac{1}{1+2[pt]} = 1 - 2[pt],$$
so $a + b = -2$. On the other hand, $K$ has no global sections, by construction, so $a,b\leq -1$. So $a = b = -1$ (incidentally, it's probably easy to see this directly, I'm just being lazy), and so $End(K) = \mathbb{C}^4$.
Moreover, in this example, $Hom(B,A) = Hom(\mathcal{O}^{\oplus 3},\mathcal{O}(-1)^{\oplus2}) = 0$.
Comment: Maybe we can just say that degree is additive in short exact sequences of vector bundles. So $deg(K)+deg(\mathcal{O}(2))=deg(\mathcal{O}^{\oplus 3})$. Hence, $a+b+2=0$.
Comment: I don't know what you mean. The fact that $End(\mathcal{O}^3) = \mathbb{C}^9$ and $End(K) = \mathbb{C}^4$ does not imply anything by itself -- a priori these are just two totally unrelated vector spaces. You would need to actually describe how $End(A)$ embeds in $End(B)$, and in general there is no such rule.
Comment: @poorna: Continuing with the ideas in the counterexample above, construct a short exact sequence $0 \to K = \mathcal{O}(a) + \mathcal{O}(b) \to \mathcal{O}^3 \to \mathcal{O}(n) \to 0$ by sending the three sections to $x^n, x^{n-1}y,y^n$ respectively. Then show $a+b+n = 0$ by counting degrees, and then show $H^1(K(n-3)) = \mathbb{C}$, which implies $\{a,b\} = \{1-n,-1\}$. Now for large $n$, $End(K) = \mathbb{C}^{n+1}$, which is way bigger than $End(\mathcal{O}^3) = \mathbb{C}^9$.
Comment: @poorna: The underlying issue with endomorphisms of vector bundles is that our inclusion $A \to B$ is not sufficient data to *naturally* convert an endomorphism $A \to A$ into an endomorphism $B \to B$, or vice versa. In other words, it does not induce any natural map $End(A) \to End(B)$ or vice versa. On the other hand, a *pair* of maps $A \to B$, $B \to A$ determines a pair(!) of maps $End(A) \to End(B)$ and $End(B) \to End(A)$. But, as in the above, there need not be *any* maps $B \to A$, let alone "good enough" maps to yield nice comparisons between $End(A)$ and $End(B)$.
Comment: That's brilliant. Thank you!
Comment: Sorry @JakeLevinson, $End(\mathcal{O}^3)=M_3=\mathbb{C}^9$ right? Then $End(A)$ is indeed contained in $End(B)$?
Comment: Ah thanks so much! I wish I could upvote your answer again! It is very clear now. @Jake Levinson
Comment: @poorna: Glad to be of help!


How to redirect to another page using the url alias?

Question: Here is my code where I am trying to redirect to a page using its url alias:
    $url= Url::fromUserInput('/thank_you_for_your_message')->toString();
    $form_state->setRedirect($url);
    return;

and I get this error : Symfony\Component\Routing\Exception\RouteNotFoundException: Route "/thank_you_for_your_message" does not exist. in Drupal\Core\Routing\RouteProvider->getRouteByName()
Is the fromUserInput the correct way to redirect to an internal url alias?
Answer: Here you can see an example that works for me:
I use 'internal:url-alias'
use \Drupal\Core\Url;
...

$search_page = '/en/faith-community/find-a-parish';
$form_state->setRedirectUrl(Url::fromUri('internal:' . $search_page));

Answer: to ensure that the internal alias exists, check for the route before trying to redirect
$search_page = Url::fromUri ('internal:/en/faith-community/find-a-parish');

if ($search_page->isRouted()) {
  $form_state->setRedirectUrl($search_page);
}

Comment: @TerranRich I have absolutely no clue what I was thinking  ¯\_(ツ)_/¯
Comment: How is `$search_page->getInternalPath()` supposed to work if it's a string?
Comment: It happens to the best of us!


If $\Sigma \models \phi$, then for some finite $\Delta \subset\Sigma$, $\Delta \models \phi$.

Question: This is an easy consequence (Doets calls it Compactness Theorem (version 2))  in Kees Doets' Basic Model theory:
Let $\Sigma$ a set of sentences and $\phi$ a sentence.
If $\Sigma \models \phi$, then for some finite $\Delta \subset\Sigma$, $\Delta \models \phi$.
The proof by contradiction reads:
"If $\phi$ does not logically follow from some $\Delta \subset \Sigma$, then the set $\Sigma \cup \{\neg \phi\}$ is finitely satisfiable and therefore, by compactness, satisfiable."
How do we know that $\Sigma \cup \{\neg \phi\}$ is finitely satisfiable?
From the fact that $\phi$ does not logically follow from some $\Delta$, we know that $\neg \phi$ follows from every $\Delta \subset \Sigma$. But how does this imply that there's a model for every finite subset of the set of sentences?
Answer: First, a quick comment. Your statement "From the fact that $\varphi$ does not logically follow from some $\Delta$, we know that $\neg\varphi$ follows from every $\Delta\subseteq \Sigma$." is incorrect: when $A$ is a set of sentences, "$A\not\models b$" is different from "$A\models\neg b$." We could have $b$ be independent of $A$ - that is, $A\not\models b$ and $A\not\models\neg b$.
What is true is that since $\varphi$ isn't entailed by any finite $\Delta\subseteq\Sigma$, $\neg\varphi$ must be compatible with every finite $\Delta\subseteq\Sigma$ in the sense that, for every $\Delta\subseteq\Sigma$, the set $\Delta\cup\{\neg\varphi\}$ will be satisfiable. (It's arguably more natural to say "consistent with" instead of "compatible with," but consistency is a syntactic property which isn't needed in this purely semantic question, so I want to avoid using language which might bring in confusion.)

This is in fact the crux of the problem!
Saying "$\Sigma\cup\{\neg\varphi\}$ is finitely satisfiable" just means "$\Delta\cup\{\neg\varphi\}$ is satisfiable for every finite $\Delta\subseteq\Sigma$." But "$\Delta\cup\{\neg\varphi\}$ is satisfiable" just means "there is some model of $\Delta\cup\{\neg\varphi\}$," which is to say $$\Delta\not\models\varphi$$ ("$\Delta\models\varphi$" means exactly "every model of $\Delta$ satisfies $\varphi$," which can't be true if there is some model of $\Delta\cup\{\neg\varphi\}$).

All that is to say that the statement "$\Sigma\cup\{\neg\varphi\}$ is finitely satisfiable" is equivalent to "For every finite $\Delta\subseteq\Sigma$, we have $\Delta\not\models\varphi$." But this latter statement is precisely our hypothesis "$\varphi$ does not logically follow from some [finite] $\Delta\subseteq\Sigma$!"
Note that the phrase "logically follow from" could confuse things here: it's meant in the semantic sense ($\models$), not the syntactic sense ($\vdash$).
Answer: My intuition about this does not (directly) use contradiction. Rather, it follows from the soundness and completeness of first-order logic:
If $\Sigma\vDash\phi$, then there is a proof of $\Sigma\vdash\phi$ (completeness), and since that proof is a finite object it mentions at most finitely many of the axioms of $\Sigma$. Therefore the same proof proves $\Delta\vdash\phi$ for some finite $\Delta\subseteq\Sigma$, and thus $\Delta\vDash\phi$ (soundness).
Comment: @HenningMakholm You're probably already familiar with this, but just in case: the semantic proof of compactness that really clicked for me - before the ultraproduct proof - was the fact that you can make Henkinization purely semantic. Let $\models_{fin}$ be the "finitary satisfaction relation," $A\models_{fin}b$ iff $D\models b$ for some finite $D\subseteq A$. We now proceed as usual, with $\models_{fin}$ in place of $\vdash$, and everything goes through basically unchanged. I also like this argument because it gives a(n interestingly, completely ahistorical) "story" for completeness: (cont'd)
Comment: in light of the coincidence of $\models$ with $\models_{fin}$, since the latter is finitary it's reasonable to hope that it is in fact computably enumerable. To find an appropriate $\vdash$, we now just look carefully through the proof that $\models_{fin}$ is all of $\models$, and each time we use a property of $\models_{fin}$ we get a corresponding proof rule. Of course, this isn't how it happened, but it's a natural enough story that I found it very helpful in learning the proof theoretic side of things: that the semantic result led naturally to the syntactic conjecture and ultimate success.
Comment: @HenningMakholm Comment 2 happens *after* comment 1. The "in light of" is *following* the proof of the compactness theorem above. My point is that, having proved compactness, it's now natural to look for a proof notion making the completeness theorem true; and having proved compactness specifically in the Henkin style, this becomes very straightforward.
Comment: Everything after "I also like" is not part of the proof of compactness, but an afterthought.
Comment: @AtticusStonestrom Yup, that tends to be exactly how I explain it. So far I've had good results, but to be fair I've only taught rather limited audiences with this so far.
Comment: To be fair, bringing the completeness theorem into a purely semantic problem is a bit overkill given that compactness can be proved without it.
Comment: @NoahSchweber I thought this is a purely syntactic problem, and bringing in models would make it semantic, now?
Comment: @Craig You have things backwards. "$\models$" is a purely semantic notion ($\Sigma\models\varphi$ iff every model of $\Sigma$ satisfies $\varphi$); "$\vdash$" is syntactic ($\Sigma\vdash\varphi$ iff there is a proof of $\varphi$ from $\Sigma$). Since the problem involves only "$\models$," it is (a priori) purely semantic.
Comment: @NoahSchweber Ohhh, I thought that $\models$ was interpreted as logical deduction when used in relation to sets of formulas. That should clear everything up, thanks.
Comment: @NoahSchweber: Well, this is the only way I could think about proving compactness either. But I'll admit to a strong bias in favor of proof theory ...
Comment: @NoahSchweber: Uhm, but ... isn't the fact that $\vDash$ coincides with $\vDash_{\rm fin}$ exactly what the compactness theorem states? If you're using that fact in your proof, then what is it you're _proving_?
Comment: @NoahSchweber ah, that's a very nice way of thinking about things!! out of curiosity, do you ever teach the compactness theorem using this $\models_{\text{fin}}$ proof? I very much like the idea of using it to motivate the definition of $\vdash$
Answer: Every $\Delta$ finite have $\Delta\vDash\lnot\varphi$, so every model of $\Delta$ is a model of $\Delta\cup\{\lnot\varphi\}$, and there is a model for every $\Delta$, namely, the model of $\Sigma$
Comment: So does Doets assume that $\Sigma$ has a model?
Comment: If there is no model to $\Sigma$, there is finite deduction sequence that proves contradiction, take $\Delta$ be all the elements of $\Sigma$ that appear in that sequence and you got a finite subset of $\Sigma$ that proves $\varphi$
Comment: @Holo "If there is no model to $\Sigma$, there is finite deduction sequence that proves contradiction" This uses the completeness theorem, which is overkill here.
Comment: @NoahSchweber that is true.. but this is the easiest way to look at this(at least the easiest from the ways I know)
Comment: @Holo I disagree - $\vdash$ isn't needed at all, this is just a direct application of the basic definition of $\models$.
Comment: @NoahSchweber I don't mean that we need $\vdash$, but I prefer to use it, I will read your answer now, you have more experience in this field than me, so it is likely you are correct, if so I would love to learn from this.


Creating a Pandas DataFrame from a dictionary that contains key and nested list of dictionary items

Question: I'm hoping to find an answer to an issue I'm facing. I am currently trying to scrape financial data for a project and am in the final step of creating a DataFrame to store my data for downstream manipulation.
My issue is that I have created a dictionary of key value pairs, where the key is a company symbol, and the value pair is a list that contains a nested dictionary of key value pairs which correspond to the market data of that company. Below is an example of the raw data.
{'MMM': [{'Market Cap': '102.234B'},
  {'Beta (5Y Monthly)': '0.95'},
  {'PE Ratio (TTM)': '19.09'},
  {'EPS (TTM)': '9.25'},
  {'Earnings Date': 'Apr 26, 2021 - Apr 30, 2021'},
  {'Forward Dividend & Yield': '5.92 (3.35%)'},
  {'Ex-Dividend Date': 'Feb 11, 2021'},
  {'1y Target Est': '183.43'}],
 'AXP': [{'Market Cap': '106.104B'},
  {'Beta (5Y Monthly)': '1.28'},
  {'PE Ratio (TTM)': '34.94'},
  {'EPS (TTM)': '3.77'},
  {'Earnings Date': 'Apr 22, 2021 - Apr 26, 2021'},
  {'Forward Dividend & Yield': '1.72 (1.31%)'},
  {'Ex-Dividend Date': 'Jan 07, 2021'},
  {'1y Target Est': '130.32'}],
 'AMGN': [{'Market Cap': '133.816B'},
  {'Beta (5Y Monthly)': '0.73'},
  {'PE Ratio (TTM)': '18.82'},
  {'EPS (TTM)': '12.31'},

I have tried to create a DataFrame using .from_dict and an index orientation but this is the result I get..
    0   1   2   3   4   5   6   7
MMM {'Market Cap': '102.234B'}  {'Beta (5Y Monthly)': '0.95'}   {'PE Ratio (TTM)': '19.09'} {'EPS (TTM)': '9.25'}   {'Earnings Date': 'Apr 26, 2021 - Apr 30, 2021'}    {'Forward Dividend & Yield': '5.92 (3.35%)'}    {'Ex-Dividend Date': 'Feb 11, 2021'}    {'1y Target Est': '183.43'}
AXP {'Market Cap': '106.104B'}  {'Beta (5Y Monthly)': '1.28'}   {'PE Ratio (TTM)': '34.94'} {'EPS (TTM)': '3.77'}   {'Earnings Date': 'Apr 22, 2021 - Apr 26, 2021'}    {'Forward Dividend & Yield': '1.72 (1.31%)'}    {'Ex-Dividend Date': 'Jan 07, 2021'}    {'1y Target Est': '130.32'}
AMGN    {'Market Cap': '133.816B'}  {'Beta (5Y Monthly)': '0.73'}   {'PE Ratio (TTM)': '18.82'} {'EPS (TTM)': '12.31'}  {'Earnings Date': 'Apr 28, 2021 - May 03, 2021'}    {'Forward Dividend & Yield': '7.04 (3.04%)'}    {'Ex-Dividend Date': 'Feb 11, 2021'}    {'1y Target Est': '254.20'}

How would I go about extracting the key/value pairs, such that the keys are the column names and the values are the datapoints?
Any help would be appreciated... thanks
Answer: You can flatten nested dictionaries first and pass to DataFrame.from_dict:
d = {k: {k1: v1 for y in v for k1, v1 in y.items()} for k, v in d.items()}

df = pd.DataFrame.from_dict(d, orient='index')

Solution with convert nested values to Series and then use concat with tranpose:
df = pd.concat({k: pd.concat([pd.Series(y) for y in v]) for k, v in d.items()}, axis=1).T
print (df)
    Market Cap Beta (5Y Monthly) PE Ratio (TTM) EPS (TTM)  \
MMM   102.234B              0.95          19.09      9.25
AXP   106.104B              1.28          34.94      3.77

                   Earnings Date Forward Dividend & Yield Ex-Dividend Date  \
MMM  Apr 26, 2021 - Apr 30, 2021             5.92 (3.35%)     Feb 11, 2021
AXP  Apr 22, 2021 - Apr 26, 2021             1.72 (1.31%)     Jan 07, 2021

    1y Target Est
MMM        183.43
AXP        130.32

Comment: Thank you this works perfectly, just so that I can learn better, what is the .T call for?
Comment: @kt190090 - It is for transpose, looking for betetr answer.


Just how much do I want to make virtual?

Question: I am writing an abstract superclass where literally every method is going to be overridden. There is some default functionality I could implement, but most of the time it's enough to leave the implementation to the subclass writer.
Since just about every method is going to be overwritten, how much should I make virtual and how much should I just leave as regular methods? In the current incarnation, everything is virtual, but I still haven't let this loose to anyone to use, so the design is flexible.
What advantages/disadvantages are there to virtual functions? Links to good reading material about this would be appreciated.
Comment: If you don't use virtual, you are not overriding in the child classes, you are hiding.  If cast as the parent type, calls to these hidden methods will call the parent method not the child.
Answer: Virtual function calls are slower than non-virtual ones, but if you need runtime polymorphism, there's no alternative. Virtual function calls have a roughly constant overhead regardless of how many you have, so there's little disadvantage. You can see the design of many professional classes- like IDirect3D9Device- have many, many virtual methods in one class.
Comment: Well I can't foresee my needing runtime polymorphism in my own applications anytime soon, but I Can imagine very legitimate uses for my library that would. How significant is the performance hit?
Comment: Depends on the use case, however they're not substantially slower than regular function calls. It can be just a couple of ops.
Answer: Using virtual is about being able to use derived class code having only the abstract class type in hand.
If you always have the exact type of your object in hand, you don't need virtual, and your abstract class is useless anyway.
If you want to use your objects through Abstract&. Use virtual function member.
You may want to read this.
(... since when interfaces exist in standard c++ ?)
If you really really really want interface: Use the boost interface library
Comment: Well, not strictly an interface, but rather a header file that defines my abstract superclass.
Comment: "interface" had a general meaning before languages started building in formal features called "interface." I don't understand why people are so stuck up about referring to abstract base classes with nothing but pure virtual functions in C++ as "interfaces"
Comment: It is actually a very good idea but c++ is disappointing on this point. One "easy" way to force derived class to implement functionalities is to template the abstract class with the exact type E of the derived class and then make dummy method calls on E in the base class constructor. Take a look at Bil if you want to learn more about this.
Comment: Well you are right ! But "Simply use interfaces !!! :)" is still a wrong answer here. Moreover C++ "interfaces" are bad interfaces since they don't complain at compile time...
Answer: Any method that you want to be override-able should be declared virtual.
The advantage of a virtual method is that in this instance:
<code>BaseClass * o = new SubClass;
o->MyVirtualMethod();
</code>
... it is SubClass::MyVirtualMethod() that will be called (which is typically what you want, if SubClass defined a MyVirtualMethod).  If the method was non-virtual, then BaseClass::MyVirtualMethod() would be called instead, because the pointer (o) is of type BaseClass.
The disadvantage of a virtual method is that it is slightly more expensive (in terms of CPU cycles used) to call than a non-virtual method.
Answer: The answer is already part of your opening post - You already said that every method is going to be overridden. Simply make all functions which should be overrideable virtual and leave the rest non-virtual.
Answer: This is called interface programming - there's nothing wrong with it, and in fact, it's often a great idea!
Answer: Virtual functions let you call a method on a base class pointer and get the correct class' behavior, without knowing whether the object is of the base or derived class. That is the "advantage" of virtual functions, though really it's the very essence, and the very thing  they were designed for.
So, whether you need this feature or not should be plainly and clearly evident from the design and intended use of your class. It shouldn't be a matter of "hmm, what are the tradeoffs", but rather "Without virtual functions, the implementation will be a complicated mess."
Given that, there are run-time costs to virtual functions, but that should never be a factor in determining whether to use them or not; the costs are trivial compared to the advantage. Rather, the option of having non-virtual functions in C++ is there so that if you know you don't need them, you don't have even that small overhead. In Java, all functions are virtual; there is no option to not have it, the reasoning being even if you don't need it, you get it anyway, it hardly costs anything anyway compared to the runtime overhead of everything else in the language.
Answer: If everything is going to be overriden, why not implement this as an interface?
Comment: This would be great advice, if C++ had interfaces.
Comment: Just because there's no formal language feature called "interface" doesn't make this a bad answer. The general term "interface" certainly applies to an abstract base class with nothing but pure virtual functions.
Comment: And even then, it wouldn't really apply here. The OP does mention that the base class implements some basic functionality.
Comment: Depending on the target compiler, interfaces are not available as a native option. For example, in Borland C++ Builder 6.0, interfaces are mapped to abstract classes by using simple define's.
Answer: Make as few methods virtual as will do the job. Try to consider aggregation over inheritance.


What is container orchestration?

Question: I have a GitLab repo, which uses docker container registry.
I want to push some of built containers to production using only one button click.
I heard that Kubernetes and Docker Swarm can help me, but I don't understand what it is
Can you explain in human language what is docker swarm and how can I use it to solve my task?
Answer:
I want to push some of built containers to production using only one button click

You don't need docker orchestration for that, just docker.
More specifically, docker image push (previously docker push)
see "GitLab Using Docker Build"
Container orchestration is what is needed to transition from deploying containers individually on a single host, to deploying complex multi-container apps on many machines.
That is not what you are trying to do here: you just need to push images to a registry.

What is container orchestration?


What is the best way to develop a theoretical approach to practical harmony for guitar?

Question: I am playing guitar approximately ten years but I know only basic harmony and rhythm guitar.
I want to develop theoretical and practical harmony. What can I do for this?
Answer: Guitarists tend to learn chord shapes, and to learn rules about what chord can come next.
But chords aren't stand-alone entities, they're a collection of notes which, seperately or in combination, create tensions which can be resolved by moving to other notes.   You know that G7 wants to go to C.  (Otherwise why would it be a pleasant surprise when it goes to Am instead?)   You need to get inside that G7 chord, feel the G pulling towards C (particularly if it's in the bass), the F pulling towards E, the B pulling towards C.  And, hey - all those pulls are satisfied by going to a C chord!  Most of them are satisfied by going to Am.  Some of them by going to A major or Ab.  None of them by going to F#.   So that's why G7 - C is the "standard" move, G7 - Aminor or G7 - Ab sound interesting but possible, and G7 - F# sounds way-out.
I could show you this very easily.  I suggest you sit down with someone who can.  Otherwise you'll try to do it all by numbers and rules, and get bogged down in the Circle of 5ths diagram.


Show that $\langle x,y,z \rangle$ has order $42$ for $x,y,z$ with given properties

Question: A similar question to what I asked here $|x|=7$,$|y|=3$ then $|\langle x,y \rangle |=21$
Let $G$ be a group of order $336$ and $x,y,z \in G$ with $|x|=7,|y|=3,|z|=2$ and the following relations: $yxy^{-1}=x^2$, $yz=zy$, $zxz^{-1}=x^6$. I also know for example $(zy)^2=y^2, (zy)^3=z.$ Now I have to show that the group $\langle x,y,z \rangle$ is of order $42$.
So in the previous question, it was shown that $\langle x,y \rangle$ is of order $21$. Following a similar style,$zyx=yzx=yx^6z=(yx)x^5z=x^2yx^5z=x^2(yx)x^4z=x^4yx^4z=x^4(yx)x^3z=x^6yx^3z=x^6(yx)x^2z=xyx^2z=x(yx)xz=x^3yxz=x^5yz$ so any element can be written below as
 $$\langle x,y,z \rangle=\{x^iy^jz^k: 0\leq i \leq 6, 0\leq j \leq 2, 0\leq k \leq 1\}.$$
Is this correct?
Answer: Except for the common identity element between them the cyclic subgroups $\langle x\rangle,\langle y\rangle,\langle z\rangle$ are pairwise disjoint because their sizes are coprime. $\langle x\rangle$ is a normal subgroup of $G$ because $x,y,z\in\mathcal N(\langle x\rangle)$ ; i.e. $yxy^{-1},zxz^{-1}\in\langle x\rangle$. Therefore, it suffices to show that the quotient group $\frac{G}{\langle x\rangle}$ has size $6$. Naturally, $G\over\langle x\rangle$ is generated together by $yG,zG$ which commute it was given $yz=zy$ yielding the internal direct group product $G\over\langle x\rangle$ $=\langle yG\rangle\oplus\langle zG\rangle$ where $\text{ord}(y)=\text{ord}(yG)=3$ and $\text{ord}(z)=\text{ord}(zG)=2$ so that $|\langle yG\rangle\oplus\langle zG\rangle|=3\cdot 2=6$.
Comment: This result is true in its fullest generality when we let $$G=\langle x,y,z\;|\;x^7,y^3,z^2,yxy^{-1}x^{-2},yzy^{-1},zxz^{-1}x^{-6}\rangle$$
Comment: So, is my solution wrong, or is this another way to show it?
Answer: By $\langle x, y, z\rangle$, I'm assuming you mean the cyclic subgroup $\langle (x, y, z)\rangle $ of $G\bigoplus G\bigoplus G$, in which case
$$\begin{align}
|\langle (x, y, z)\rangle|& = |(x, y, z)| \\
&={\rm lcm}(|x|, |y|, |z|)\\
& ={\rm lcm} (7, 3, 2)\\
& = 42.
\end{align}$$
Comment: $\langle x,y,z \rangle$ is the subgroup generated by elements $x,y,z$ (contains all their powers, products etc. It is not a truple.


GSON not deleted

Question: Why in my APK there is GSON even though I have nothing to implement GSON in Gradle?
Result Analyze APK
My Gradle :
//main
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation "org.jetbrains.anko:anko-commons:0.10.5"
implementation "androidx.appcompat:appcompat:1.1.0"
implementation "androidx.constraintlayout:constraintlayout:1.1.3"
implementation "androidx.recyclerview:recyclerview:1.1.0"
implementation "androidx.paging:paging-runtime:2.1.1"
implementation "androidx.navigation:navigation-fragment-ktx:$nav_version"
implementation "androidx.navigation:navigation-ui-ktx:$nav_version"
implementation "androidx.lifecycle:lifecycle-extensions:$lifecycle_version"
implementation "androidx.lifecycle:lifecycle-common-java8:$lifecycle_version"
implementation "androidx.room:room-runtime:$room_version"
implementation "androidx.multidex:multidex:2.0.1"
implementation "com.android.volley:volley:1.1.1"

//google
implementation "com.google.android.gms:play-services-location:17.0.0"
implementation "com.google.android.material:material:1.0.0"
implementation "com.google.firebase:firebase-auth:19.2.0"
implementation "com.google.firebase:firebase-firestore:21.3.1"
implementation "com.google.firebase:firebase-storage:19.1.0"
implementation "com.google.firebase:firebase-messaging:20.1.0"
implementation "com.firebaseui:firebase-ui-storage:3.3.0"

// third party dependencies
implementation "com.balysv:material-ripple:1.0.2"
implementation "com.facebook.shimmer:shimmer:0.5.0"
implementation "com.squareup.moshi:moshi-kotlin:1.9.2"
implementation "com.tbuonomo.andrui:viewpagerdotsindicator:4.1.2"
implementation "com.github.bumptech.glide:glide:$glide_version"
//noinspection GradleDependency
implementation "com.journeyapps:zxing-android-embedded:3.6.0"

//kapt
kapt "com.github.bumptech.glide:compiler:$glide_version"
kapt "androidx.room:room-compiler:$room_version"
kapt "androidx.annotation:annotation:1.1.0"

// test
testImplementation 'junit:junit:4.13'
androidTestImplementation "androidx.test:runner:1.2.0"
androidTestImplementation "androidx.test.espresso:espresso-core:3.2.0"

I want to reduce my apk size, so I deleted the libary that I didn't use.
Answer: One or more of your dependencies has GSON in self.
i think it might be Glide or someone else.
for redecuing apk size check this topic might be helpful: Reduce the APK size - Android Developers

GSON not deleted


Background problems with wikia css

Question: The wiki that I admin has had no changes to its css in quite some time, but recently it seems to be that the page size is too small or something, as the transparent green background is appearing either side of the borders.
You can see this happening on the wiki here http://rollplaydnd.wikia.com/wiki/Rollplay_Wiki
Any assistance in how to cover or remove the green background would be appreciated!
Answer: To remove green background:
in your Qualaroo.scss file find this class
.WikiaPage .WikiaPageBackground
and remove background property in this class
And if it is not available in your source then try following.
In menu item's a tag you can write inline style sheet.
Articles

Comment: there doesn't seem to be a `.WikiaPage .WikiaPageBackground` class in my css O.o
Comment: I'm afraid I don't understand. "In menu item's a tag you can write inline style sheet" I don't understand this sentence sorry.
Answer: As answer suggested by Emipro Technologies Pvt is some how fix your problem
but i think real problem was originated from code below
@media only screen and (max-width: 1595px) and (min-width: 1084px)
.WikiaPage {
  padding: 0 20px; //remove this line or use padding in internal container
  width: 1024px;
}

EDIT: padding make your internal division to shrink and your parent container will get control on that extra area
i hope this may help you
Comment: I can't find this exact line of code in the css. Are you sure this is there?
Comment: i got this code from your site only, its in Qualaroo.scss file only
Comment: Qualaroo.scss is external style so it will not be available in source. Instead in menu item's a tag write inline style sheet. `Articles`

Background problems with wikia css


C++ objdump use and disassembly

Question: On a linux server, the command would be
$ objdump -t exercise11 > symbol_table.txt
The intention is to find the memory address and size (in bytes) for the three global variables in a program.
The second portion is equivalent to
$ objdump -S exercise11 > disassembly.txt
The intention here is to search the text file and find the instruction for assigning a valuable to a variable.
My problem is that I am using Visual Studio 2017 on a local machine. I am in the visual studio command prompt but either I need something different or I am misunderstanding what I am reading in the output files. I have also used dumpbin commands but it did not seem to produce the correct information, either. Could you please show me how to do this in Visual studio and how to find the information I am searching?
Comment: "I have also used dumpbin commands but it did not seem to produce the correct information, either." How did you use it and what did you get as a result?
Comment: It seems dumpbin and objdump commands produced the same result. I used modifiers like -SYMBOLS and other commands that was listed with the help function, but none of it produced a memory address or the machine code for the function doSomething()
Comment: 3 downvotes without comments? Now I remember why I quit using this site.
Comment: Afaik, memory addresses are assigned when linker composes all object files. They are not delivered within a particular obj file.
Comment: I know this works in netbeans on a linux terminal, I have done it. I just can't figure out how to do it in visual studio.
Comment: It's such a simple question... I'm completely confused on how no one knows and the question is only down voted without comment. You shouldn't be able to down vote without a reason.
Answer: You can go to the project's property pages. Click Linker. Click debug and there are a couple options for generating a Map file which will allow you to see the memory address of variables and such.
0004:00000000       ?variable1@@3HA            00420000     Excercise11.obj
The question itself is not hard, but finding the right option in Visual Studio instead of NetBeans was problematic.

C++ objdump use and disassembly


Neural Network Architecture Search

Question: I'm applying NN for regression purpose. The model has 30 Input nodes, 1 hidden layer and 1 output. In order to find the optimal architecture of the hidden layer, I've constructed a loop that:

tests all possible hidden layer neurons (e.g. from 1 to 30)
Calculates cross validation error for each loop iteration
Filters the iteration that has the minimum error (e.g. 12 neurons)
Applies the 12 neurons to the full data set

Can I consider this a form of regularization?
Reason for asking is because the package I deploy doesn't support L2 or dropout.
Answer: I think the first thing you need to set right is learning rate, which is very important. Usually, Adam or SGD optimzers should work. Also, you may need to make 3 partitions of data. Train data, on which you train the model. Validation data on which you try to fine tune the model, and finally the test data on which you finally evaluate the model.
If you don't have L2 or Dropout, you can consider "Early Stopping". Early stopping is also a method of regularization.
There are lots of concepts to understand. It's better you go through proper tutorials. Particularly, I find Lecture by Stanford on Convolutional Neural Networks for Visual Recognition very good. I assure you, once you go through all the tutorial, you'll be much better equipped. Here is the link  - https://www.youtube.com/watch?v=vT1JzLTH4G4&list=PL3FW7Lu3i5JvHM8ljYj-zLfQRF3EO8sYv
For neural network architecture search, there are three things you can consider - Random Search, Grid Search, and Bayesian Search or Model based search. I suggest you go for random search of hyperparameters.
All the best.
Comment: Thank you. I do apply early stopping indeed :)
Comment: This is not exhaustive, but will help you understand some very important basic concepts about deep learning. https://www.youtube.com/watch?v=SKq-pmkekTk&list=PLlMkM4tgfjnJ3I-dbhO9JTw7gNty6o_2m  Enjoy!
Comment: Check out Bayesian Optimization, widely used for architecture search

Neural Network Architecture Search


Reference to another field in model.py // Django

Question: I would like to return in str method of the Chapter, title of the Chapter and title of the Book (from book model). I need it for better display at the admin pages. How to do that?
Should I create some new method in Book or use Model instance reference https://docs.djangoproject.com/en/1.11/ref/models/instances/#model-instance-methods ?
Or maybe I should use Retrieving specific objects with filters?
https://docs.djangoproject.com/en/1.11/topics/db/queries/#retrieving-objects
I am new to the django, thank you in advance for the solutions.
class Book(models.Model):
    author = models.CharField(max_length=200)
    title = models.TextField()
    created_date = models.DateTimeField(
            default=timezone.now)

    def __str__(self):
        return self.title+" ("+self.author+")"

    def book_author(self):
        return self.author

class Chapter(models.Model):
    book = models.ForeignKey(Book, on_delete=models.CASCADE)
    title = models.TextField()
    created_date = models.DateTimeField(
            default=timezone.now)
    body = models.TextField()
    hierarchy = models.IntegerField()
    sort = models.IntegerField(unique=True)

    def __str__(self):
        print(repr(Book))
        print(repr(Book.author))
#       print(repr(Book.objects.all().filter(id==1)))
#        print(repr(Book.objects.get(id=1)))
        print(repr(Book.book_author(self)))
        return self.title+"(book: "+")"

Comment: `self.book.author`?
Answer: def __str__(self):
    return '%s (%s)' % (self.title, self.book.title,)

Comment: Thank you. It is so intuitive and nice solution!
Answer: To print your object data in admin panel more nicely you should overide __str__ method for your models.
For example your code should look like:
class Book(models.Model):
    author = models.CharField(max_length=200)
    title = models.TextField()
    created_date = models.DateTimeField(
            default=timezone.now)

    def __str__(self):
        return 'Book with title: {} writen by {}'.format(self.title, self.author)

`
Comment: Thank you for your solution, but I wanted to return title of the Chapter and title of the book in __str__ method of Chapter.
Comment: This was an example. It is simple to adjust it to what you want. Isn't it?
Comment: No, I wanted to use title from Book in Chapter model, self.book.author


Vertical Tabs in Front End (Drupal 7)

Question: I am trying to use Vertical Tabs on the front end of my site.
Normally, I would just add a jQuery plug-in to my theme. However, vertical tabs are built into Drupal 7, so it seems silly to use a plugin, when the functionality already exists.
I'm just not sure how to call the built-in vertical tabs.
Dan Silver's blog has an excellent tutorial on how to call the built-in tabs. However, his tutorial is for horizontal tabs. I am not sure how to convert them to vertical ones.
I would appreciate if anyone could give me some hints.
(P.S. I am aware that modules exist to do this. However, for my purposes it seems overkill to use a module when I can achieve it with a few simple lines of theming).
Answer: The examples module will provide you some custom code to implement this, have a look at the API documentation which add a vertical tab to the node form.
The only restriction I can think of is that this code is for forms so if you want to theme a node output you should use jQUery UI tabs. The tutorial you linked seems fine, but you'll need to change a little its CSS classes in order to output vertical tabs, compare its code tho this demo.
Comment: Does this mean that the vertical/horizontal aspect is controlled fully by CSS? (I.e. the Jquery remains the same regardless if you want a horizontal or vertical menu?)
Comment: That is correct, compare the source code of the [default tabs implementation](http://jquery-ui.googlecode.com/svn/trunk/demos/tabs/default.html) vs [the vertical one](http://jquery-ui.googlecode.com/svn/trunk/demos/tabs/vertical.html), there's only a few CSS lines that differ for the class `.ui-tabs-vertical`.

Vertical Tabs in Front End (Drupal 7)


MaterialPageRoute not opening new screen

Question: I am trying to navigate to a new screen when a PopupMenuItem is tapped. I am using showMenu() to create the popup menu.
The code calling the new screen looks like this:-
items: [
    PopupMenuItem(
      onTap: () {
        print(movie.title);
        // Navigator.of(context).push(MaterialPageRoute(
        //     builder: (context) => MoreInfo(movie: movie)));
        Navigator.push(
            context,
            MaterialPageRoute(
                builder: (context) => MoreInfo(movie: movie)));
      },
      child: InkWell(
          onTap: () {
            Navigator.push(
                context,
                MaterialPageRoute(
                    builder: (context) => MoreInfo(movie: movie)));
          },
          child: Text("More info")),

and MoreInfo screen code looks like this:-
Scaffold(
  backgroundColor: Colors.indigo,
  appBar: AppBar(
    leading: InkWell(
      onTap: () {
        Navigator.pop(context);
      },
      child: Icon(Icons.arrow_back_outlined),
    ),
    title: Text(widget.movie.title),
  ),

However, using the onTap field of PopupMenuItem does not open a new screen. It is printing out movie.title though. I also have the text of the menu item wrapped with an InkWell, when I do click on the text, a new screen does show up, but there is no content on it. Just an empty screen with Colors.indigo background color as specified in MoreInfo, but with none of the other elements such as AppBar.
What could be going wrong here? Do I need to use another type of Navigation?
Comment: remove the InkWell from the PopupMenuItem. You already got onTap !! Just place the Text  as child to the PopupMenuItem.
Answer: this piece of code works as well:
class MyHomePage extends StatefulWidget {

const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            InkWell(
              onTap: () {
                showMenu(
                    context: context,
                    position: const RelativeRect.fromLTRB(0, 0, 0, 0),
                    items: [
                      PopupMenuItem(
                        onTap: () {
                          Navigator.push(
                              context,
                              MaterialPageRoute(
                                  builder: (context) => MoreInfo()));
                        },
                        child: InkWell(
                            onTap: () {
                              Navigator.push(
                                  context,
                                  MaterialPageRoute(
                                      builder: (context) => MoreInfo()));
                            },
                            child: const Text("More info")),
                      )
                    ]);
              },
              child: const Text('push me'),
            )
          ],
        ),
      ),
    );
  }
}

class MoreInfo extends StatefulWidget {
  MoreInfo({Key? key}) : super(key: key);

  @override
  State<MoreInfo> createState() => _MoreInfoState();
}

class _MoreInfoState extends State<MoreInfo> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leading: InkWell(
          onTap: () {
            Navigator.pop(context);
          },
          child: const Icon(Icons.arrow_back_outlined),
        ),
        title: const Text('widget.movie.title'),
      ),
      body: const Center(
        child: Text('hi'),
      ),
    );
  }
}


Azure backup folder exclusion

Question: I tried to find a way to do it, but I am not sure if it's possible or not.
Using Recovery services on Azure, I installed the Microsoft Azure Backup Agent on an IIS server.
We have multiple websites hosted and each website use ELMAH for logging. We also use SVN to deploy website update. The thing is, some of our log folder contains thousands of log files and there's also the .svn files which contains tons of files. I would like to exclude these folders, for performance purpose. However, I don't want to add one hundred manual exclusion list, I would like to add a generic filter to do so.
I know I can exclude a specific folder in the backup agent and that we can exclude certain file types, but I don't want to exclude all .xml files, for example, as they are important files to be backuped.
Did anyone find a way to exclude part of folder path from the Azure Backup Agent tool?
It most likely apply to Windows Server Backup too. It's fine if I need to script a file with the exclusion listed in it too.
ie.

C:\inetpub\wwwroot\website\log\1.xml
C:\inetpub\wwwroot\website\log\2.xml

Exclude: C:\inetpub\wwwroot\*\log\*
Exclude: C:\inetpub\wwwroot\*\.svn\*

Thanks in advance!
Comment: Perhaps an obvious question, but can you move the logs to somewhere else, away from the backup root?
Comment: In poking around at it I didn't see a way to do that, even if there was I'd still suggest moving the logs
Comment: While we could move out the logs elsewhere as a work around, I don't think we can move out the .svn folders. Thanks for the suggestion.
Comment: Hi P-L (from quebec :D) We also try to configure azure backup to add "wildcard" exclusion, did you find a solution since last year? thank you!
Comment: Hi Frederic, yeah I should definitively change my profile picture!
To answer your question, unfortunately no. I left that company since and didn't check back about the solution as we're using a different backup solution here. From what I remember, there was a new backup agent client being released, but I didn't have time to look at it. We might move to azure backup here too, so if anyone find a solution for this problem please share it here!
Answer: Just had a talk to a support engineer and he confirmed that it's currently not possible to use wildcards other than in file extensions.
I explained my use case and remarked that it was a useful feature.
Added a user voice item to track this, votes are welcome:
https://feedback.azure.com/forums/258995-azure-backup/suggestions/35201827-exclusions-based-on-minimatch-patterns
To work around it, at the moment the only option is to use powershell to search for folders to exclude and then update the backup schedule. Or to include updating the backup schedule as part of your deployment scripts/pipeline.
Answer: If you are talking about an Azure VM backup through the extension (full VSS backup) then I am not aware of a way to exclude files or folders. However, you can install the Agent for Windows Server or System Center Data Protection Manager or Windows Client like you would use for an on-premise machine in an Azure VM and configure it with just the files and folders you want to backup.
https://azure.microsoft.com/en-us/documentation/articles/backup-azure-backup-windows-server/
If you want to automate the process, you can script it with PowerShell using the following documentation:
https://azure.microsoft.com/en-us/documentation/articles/backup-client-automation/
Keep in mind that this is a file/folder backup, so you wouldn't be able to use it to restore the entire VM. If you needed to restore an Azure VM using this method, you would need to build a new VM, install the agent, then perform the restore using the Recover to an alternate machine method described here.
https://azure.microsoft.com/en-us/documentation/articles/backup-azure-restore-windows-server/#recover-to-an-alternate-machine
Comment: Doesn't in any way try to answer the wildcard question and the dos are VERY fuzzy on this topic.

Azure backup folder exclusion


How to combine results from multiple tables?

Question: I want to print data from multiple tables in single with given date range
Tables
Users (PF_NO,NAME,DESIGNATION,LEVEL,DUTY_TYPE)
Holiday(id, DATE,PF_NO,Reason)
entry(id, DATE, PF_NO, f1,f2 etc)

I only mentioned required fields, All tables are connected by PF_NO ,
So basically I want to get details like below
| PF_NO | NAME | DESIGNATION |LEVEL |DATE| DUTY |DUTY_TYPE|REASON| F1|F2|
So scenario here is if user has entry in Holiday table for a given date then it will show No and REASON will contain REASON from Holiday table and the fields after reason will be blank, if he don't have an entry in a given date in Holiday table he has an entry in table entry then DUTY will be Yes and DUTY_TYPE will be printed from users table and other details from table entry will be printed, & I want to generate a report from given dates. Please help me
What I Tried?
NAME_OF_STAFF,PF_NO,DESIGNATION,LEVEL,BASIC,MOBILE,EMAIL
from user
Join holidays on(holiday_reason BETWEEN From_Date and To_DATE)

Select NAME_OF_STAFF,PF_NO,DESIGNATION,LEVEL,BASIC,MOBILE,EMAIL
from user
join holidays on id,PF_NO
join holidays_reason on ID
where date between

Comment: Are you using MySQL or Oracle?  Tag only with the database you are really using.  Sample data and desired results would also make your question much clearer.
Comment: I'm using MySQL, but I thought query will be same in both, SO more people can see
Comment: This should be a simple LEFT JOIN.
Comment: Can you please help me? I'm beginner in this
Comment: Thanks Sir, I tried but I'm new in JOINS, I will share What I tried
Comment: [SQL LEFT JOIN Keyword](https://www.w3schools.com/sql/sql_join_left.asp).
Comment: Use `LEFT JOIN` with both `Holiday` and `entry` tables. You can then use `IFNULL()` to either show `Holiday.reason` or `users.Duty_type`
Comment: Ok, I updated question with what I tried
Comment: @Barmar can you have a look? I updated question
Comment: It looks like you don't even know the correct syntax of a JOIN. You need to learn the basics.
Comment: What is `holidays_reason`? That's not one of the tables you listed at the beginning of the question.
Comment: I tried in example but nothing to do with db,
Answer: SELECT A.PF_NO,A.NAME,A.DESIGNATION,A.LEVEL,B.DATE,
    CASE WHEN ISNULL(B.id,0)<>0  THEN 'No'
         WHEN ISNULL(B.id,0)=0  &&  ISNULL(C.id,0)<>0  THEN 'Yes' END Duty,
    CASE WHEN ISNULL(B.id,0)=0  &&  ISNULL(C.id,0)<>0  THEN ISNULL(A.Duty_type,'') ELSE '' END Duty_type,
    ISNULL(Reason,'') as Reason, ISNULL(C.F1,'') C.F1,ISNULL(F2,'') F2
FROM user A LEFT JOIN holiday B on B.id = A.PF_NO
          LEFT JOIN holidays_reason C on C.ID=A.PF_NO
where C.date BETWEEN From_DATE and To_DATE

Comment: Thank you for answer but I'm facing issue "  Incorrect parameter count in the call to native function 'ISNULL'
"
Comment: If you want I can provide you the export file of db
Comment: I think he's usage of `ISNULL` is for MSSQL. In MySQL `ISNULL` takes one parameter. So you need to remove the second parameters of `ISNULL`s and change the results accordingly, have a look at https://dev.mysql.com/doc/refman/8.0/en/comparison-operators.html#function_isnull
Comment: Change `ISNULL(B.id,0)<>0` to `ISNULL(B.id) = 0` and `ISNULL(B.id,0)=0` to `ISNULL(B.id)=1`.
Comment: Or just `B.id IS NOT NULL` or `B.id IS NULL`


Why is ridge regression called "ridge", why is it needed, and what happens when $\lambda$ goes to infinity?

Question: Ridge regression coefficient estimate $\hat{\beta}^R$ are the values that minimize the
$$ \text{RSS} + \lambda \sum_{j=1}^p\beta_j^2. $$
My questions are:

If $\lambda = 0$, then we see that the expression above reduces to the usual RSS. What if $\lambda \to \infty$?  I do not understand the textbook explanation of the behaviour of the coefficients.
To aid in understanding the concept behind a particular term, why is the term called RIDGE Regression? (Why ridge?) And what could have been wrong with the usual/common regression that there is a need to introduce a new concept called ridge regression?

Your insights would be great.
Answer: Since you ask for insights, I'm going to take a fairly intuitive approach rather than a more mathematical tack:

Following the concepts in my answer here, we can formulate a ridge regression as a regression with dummy data by adding $p$ (in your formulation) observations, where $y_{n+j}=0$, $x_{j,n+j}=\sqrt{\lambda}$ and $x_{i,n+j}=0$ for $i\neq j$. If you write out the new RSS for this expanded data set, you'll see the additional observations each add a term of the form $(0-\sqrt{\lambda}\beta_j)^2=\lambda\beta_j^2$, so the new RSS is the original $\text{RSS} + \lambda \sum_{j=1}^p\beta_j^2$ -- and minimizing the RSS on this new, expanded data set is the same as minimizing the ridge regression criterion.
So what can we see here? As $\lambda$ increases, the additional $x$-rows  each have one component that increases, and so the influence of these points also increases. They pull the fitted hyperplane toward themselves. Then as $\lambda$ and the corresponding components of the $x$'s go off to infinity, all the involved coefficients "flatten out" to $0$.
That is, as $\lambda\to\infty$, the penalty will dominate the minimization, so the $\beta$s will go to zero. If the intercept is not penalized (the usual case) then the model shrinks more and more toward the mean of the response.
I'll give an intuitive sense of why we're talking about ridges first (which also suggests why it's needed), then tackle a little history. The first is adapted from my answer here:
If there's multicollinearity, you get a "ridge" in the likelihood function (likelihood is a function of the $\beta$'s). This in turn yields a long "valley" in the RSS (since RSS=$-2\log\mathcal{L}$).
Ridge regression "fixes" the ridge - it adds a penalty that turns the ridge into a nice peak in likelihood space, equivalently a nice depression in the criterion we're minimizing:

[Clearer image]
The actual story behind the name is a little more complicated. In 1959 A.E. Hoerl [1] introduced ridge analysis for response surface methodology, and it very soon [2] became adapted to dealing with multicollinearity in regression ('ridge regression'). See for example, the discussion by R.W. Hoerl in [3], where it  describes Hoerl's (A.E. not R.W.) use of contour plots of the response surface* in the identification of where to head to find local optima (where one 'heads up the ridge'). In ill-conditioned problems, the issue of a very long ridge arises, and insights and methodology from ridge analysis are adapted to the related issue with the likelihood/RSS in regression, producing ridge regression.

* examples of response surface contour plots (in the case of quadratic response) can be seen here (Fig 3.9-3.12).
That is, "ridge" actually refers to the characteristics of the function we were attempting to optimize, rather than to adding a "ridge" (+ve diagonal) to the $X^TX$ matrix (so while ridge regression does add to the diagonal, that's not why we call it 'ridge' regression).
For some additional information on the need for ridge regression, see the first link under list item 2. above.

References:
[1]: Hoerl, A.E. (1959). Optimum solution of many variables equations. Chemical Engineering Progress,
55 (11) 69-78.
[2]: Hoerl, A.E. (1962). Applications of ridge analysis to regression problems. Chemical Engineering Progress,
58 (3) 54-59.
[3] Hoerl, R.W. (1985). Ridge Analysis 25 Years Later.
American Statistician, 39 (3), 186-192
Comment: This is extremely helpful. Yes, when I was asking for insights, I was looking for intuition. Of course the mathematics is important, but I was also looking for conceptual explanations, because there are some parts when the math was just beyond me. Thanks again.
Comment: It's a good question; there's no need for it to be weighted unless the original regression was weighted. I have removed the adjective. It's *also* possible to write it as a weighted regression (which if you're already doing weighted regression might be very slightly easier to deal with).
Comment: Why do you have the word "weighted" in bullet point 1?
Answer:
If $\lambda \rightarrow \infty$ then our penalty term will be infinite for any $\beta$ other than $\beta = 0$, so that's the one we'll get. There is no other vector that will give us a finite value of the objective function.

(Update: Please see Glen_b's answer. This is not the correct historical reason!)

This comes from ridge regression's solution in matrix notation. The solution turns out to be
$$
\hat \beta = (X^TX + \lambda I)^{-1} X^TY.
$$
The $\lambda I$ term adds a "ridge" to the main diagonal and guarantees that the resulting matrix is invertible. This means that, unlike OLS, we'll always get a solution.

Ridge regression is useful when the predictors are correlated. In this case OLS can give wild results with huge coefficients, but if they are penalized we can get much more reasonable results. In general a big advantage to ridge regression is that the solution always exists, as mentioned above. This applies even to the case where $n < p$, for which OLS cannot provide a (unique) solution.
Ridge regression also is the result when a normal prior is put on the $\beta$ vector.
Here's the Bayesian take on ridge regression:
Suppose our prior for $\beta$ is $\beta \sim N(0, \frac{\sigma^2}{\lambda}I_p)$. Then because $(Y|X, \beta) \sim N(X\beta, \sigma^2 I_n)$ [by assumption] we have that
$$
\pi(\beta | y) \propto \pi(\beta) f(y|\beta)
$$
$$
\propto \frac{1}{(\sigma^2/\lambda)^{p/2}} \exp \left( -{\lambda \over 2\sigma^2} \beta^T\beta \right) \times \frac{1}{(\sigma^2)^{n/2}} \exp \left( \frac{-1}{2\sigma^2} ||y - X\beta||^2 \right)
$$
$$
\propto \exp \left( -{\lambda \over 2\sigma^2} \beta^T\beta - \frac{1}{2\sigma^2} ||y - X\beta||^2 \right).
$$
Let's find the posterior mode (we could look at posterior mean or other things too but for this let's look at the mode, i.e. the most probable value).
This means we want
$$
\max_{\beta \in \mathbb R^p} \ \exp \left( -{\lambda \over 2\sigma^2} \beta^T\beta - \frac{1}{2\sigma^2} ||y - X\beta||^2 \right)
$$
which is equivalent to
$$
\max_{\beta \in \mathbb R^p} \ -{\lambda \over 2\sigma^2} \beta^T\beta - \frac{1}{2\sigma^2} ||y - X\beta||^2
$$
 because $\log$ is strictly monotone and this in turn is equivalent to
$$
\min_{\beta \in \mathbb R^p} ||y - X\beta||^2 + \lambda \beta^T\beta
$$
which ought to look pretty familiar.
Thus we see that if we put a normal prior with mean 0 and variance $\frac{\sigma^2}{\lambda}$ on our $\beta$ vector, the value of $\beta$ which maximizes the posterior is the ridge estimator. Note that this treats $\sigma^2$ more as a frequentist parameter because there's no prior on it but it isn't known, so this isn't fully Bayesian.
Edit: you asked about the case where $n < p$.
We know that a hyperplane in $\mathbb R^p$ is defined by exactly $p$ points. If we are running a linear regression and $n = p$ then we exactly interpolate our data and get $||y - X\hat\beta||^2 = 0$. This is a solution, but it is a terrible one: our performance on future data will most likely be abysmal. Now suppose $n < p$: there is no longer a unique hyperplane defined by these points. We can fit a multitude of hyperplanes, each with 0 residual sum of squares.
A very simple example: suppose $n = p = 2$. Then we'll just get a line between these two points. Now suppose $n = 2$ but $p = 3$. Picture a plane with these two points in it. We can rotate this plane without changing the fact that these two points are in it, so there are uncountably many models all with a perfect value of our objective function, so even beyond the issue of overfitting it is not clear which one to pick.
As a final comment (per @gung's suggestion), the LASSO (using an $L_1$ penalty) is commonly used for high dimensional problems because it automatically performs variable selection (sets some $\beta_j = 0$). Delightfully enough, it turns out that the LASSO is equivalent to finding the posterior mode when using a double exponential (aka Laplace) prior on the $\beta$ vector. The LASSO also has some limitations, such as saturating at $n$ predictors and not necessarily handling groups of correlated predictors in an ideal fashion, so the elastic net (convex combination of $L_1$ and $L_2$ penalties) may be brought to bear.
Comment: OLS can't find a unique solution when $n<p$ because the design matrix is not full rank. This is a very common question; please search the archives for a description of why this doesn't work.
Comment: @cgo: user777's explanation and suggestion to search about is a good one, but for the sake of completeness I've also added a (hopefully) intuitive explanation.
Comment: I appreciate your response. Thank you. Just another question though, I do not follow the statement: 'this applies even to the case when $n<p$...'.

$p$ is the number of predictors, and $n$ is the number of samples right? What happens when $n<p$? Please give a very basic example why OLS can't give a unique solution.
Answer:
why is the term called Ridge Regression?

From Ridge Regression: Biased Estimation for Nonorthogonal Problems (1970):

A. E. Hoerl first suggested in 1962 [9] [11] that to control the inflation and
general instability associated with the least squares estimates, one can use
$$\beta^* = [X'X + kI]^{-1}X'Y; k \geq 0 (2.1) \\\\ = WX'Y (2.2)$$
The family of estimates given by $k \geq 0$ has many mathematical similarities
with the portrayal of quadratic response functions [10]. For this reason, estimation and analysis built around (2.1) has been labeled "ridge regression."
Comment: This is historically correct, but it doesn't quite get to the answer: the reason for this term lies in the fact that Ridge Regression was conceptualized as (1) being applied to the *negative* of the objective function (that is, as a maximization problem) and (2) being used when the original quadratic (for $k=0$) is degenerate or very nearly so.  The simplest non-trivial case of this situation is exemplified by the equation $z = -y^2$ whose graph in $(x,y,z)$ coordinates indeed looks like an anticline or "ridge" of a mountain chain.  @ glen_b's answer explains and illustrates the second point.


Epsilon-Delta Proof $ \lim\limits_{n\to\infty}\frac{n+\sin(n)}{n+1} = 1$

Question: How To Construct a Epsilon-Delta proof $\displaystyle \lim\limits_{n\to\infty}\frac{n+\sin(n)}{n+1} = 1$ ?
The beginning:
Fix $\epsilon$ > 0. Is there an $N\in \mathbb{N},$ such that
$$n\ge N \implies\left|\frac{n+\sin(n)}{n+1}-1 \right|<\epsilon?$$
$$\left|\frac{n+\sin(n)}{n+1}-1 \right|<\epsilon \iff$$
$$\left|\frac{\sin(n)-1}{n+1}\right|<\epsilon \iff$$
$$\ldots$$
I got that $n > \frac{2}{\epsilon}-1$, is that right?
N=(max or min ?) {0, $\lfloor\frac{2}{\epsilon}-1\rfloor$}
I hope that the task is understandable.
Thank you for answering.
Comment: $|\sin n-1|\leq2$.
Comment: So far so good.  Note that the numerator is bounded.
Comment: No `\displaystyle` in titles, please.
Answer: Hint: Use the triangular inequality for the numerator and the boundedness of $\sin(n)$ by $|\sin(n)|\leq 1$:
$$\biggl|\frac{\sin(n)-1}{n+1}\biggr|\leq \frac{|\sin(n)|+1}{|n+1|}\leq \frac{1+1}{|n+1|}=\frac{2}{n+1}$$
Comment: Minor addendum but we could even skip the triangle equality step and say $\left|\frac{\sin(n)-1}{\ldots}\right|=\frac{|\sin(n)-1|}{|\ldots|}\leq\frac{2}{|\ldots|}$ since we know that $-2\leq\sin(n)-1\leq0$. Great answer regardless :)
Comment: @Jam: You are right, but I would still prefer the triangular inequality because it makes it explicit what is implicitly hidden in $-2\leq \sin(n) -1 \leq 0$.
Comment: You could also use $1- \sin(n) =  2\sin^2(n/2 + \pi/4)$ to derive that inequality.
Answer: Try these:
$|x-y| \leq |x| + |y|$ and $|\sin(x)|\leq1$.
Comment: https://math.stackexchange.com/questions/2442833/how-can-i-prove-that-lim-limits-n-to-infty-fracn-sin-nn1-1/2442899#2442899


Campo de busca some ao adicionar produto no carrinho

Question: Ao adicionar algum produto em meu carrinho de compra o campo de busca do site não aparece e não consigo identificar o porque, fui eliminando o que pude dos arquivos .css que tenho e mesmo assim não consegui chegar a um resultado.
Creio que possa ser algo relacionado com o clearfix, mas meu conhecimento em css não me permite uma análise melhor.
A página pode ser visualizada aqui: Inserção de Produtos no carrinho
O campo de busca está assim configurado:
<form id="search-form" action="busca.php" method="post">
<input id="s" type="text" name="s" placeholder="Busca" style="display: none;">
<input id="search-submit" type="submit" name="search-submit" value="Search">

A chamada do meu carrinho está assim:

MEU CARRINHO

      <?php
            $class->setURL($url);
            $class->carrinho();
        ?>

E o css que monta o carrinho é esse:

.product-image {
  float: left;
  width: 20%;
}

.product-details {
  float: left;
  width: 37%;
}

.product-quantity {
  float: left;
  width: 10%;
}

/* This is used as the traditional .clearfix class */
.group:before,
.shopping-cart:before,
.column-labels:before,
.product:before,
.totals-item:before,
.group:after,
.shopping-cart:after,
.column-labels:after,
.product:after,
.totals-item:after {
  content: '';
  display: table;
}

.group:after, .shopping-cart:after, .column-labels:after, .product:after, .totals-item:after {
  clear: both;
}

.group, .shopping-cart, .column-labels, .product, .totals-item {
  zoom: 1;
}

/* Apply clearfix in a few places */
/* Apply dollar signs */
.product .product-price:before, .product .product-line-price:before, .totals-value:before {
  content: '$';
}

label {
  color: #aaa;
}

.shopping-cart {
  margin-top: -45px;
}

/* Column headers */
.column-labels label {
  padding-bottom: 15px;
  margin-bottom: 15px;
/*  border-bottom: 1px solid #eee;
*/}
.column-labels .product-image, .column-labels .product-details, .column-labels .product-removal {
  text-indent: -9999px;
}

/* Product entries */
.product {
  margin-bottom: 20px;
  padding-bottom: 10px;
}
.product .product-image {
  text-align: center;
}
.product .product-image img {
  width: 100px;
}
.product .product-details .product-title {
  margin-right: 20px;
  font-family: "HelveticaNeue-Medium", "Helvetica Neue Medium";
}
.product .product-details .product-description {
  margin: 5px 20px 5px 0;
  line-height: 1.4em;
}
.product .product-quantity input {
  width: 40px;
}
.product .remove-product {
  border: 0;
  padding: 4px 8px;
  background-color: #c66;
  color: #fff;
  font-family: "HelveticaNeue-Medium", "Helvetica Neue Medium";
  font-size: 12px;
  border-radius: 3px;
}
.product .remove-product:hover {
  background-color: #a44;
}

/* Totals section */
.totals .totals-item {
  float: right;
  clear: both;
  width: 100%;
  margin-bottom: 10px;
}
.totals .totals-item label {
  float: left;
  clear: both;
  width: 79%;
  text-align: right;
}
.totals .totals-item .totals-value {
  float: right;
  width: 21%;
  text-align: right;
}
.totals .totals-item-total {
  font-family: "HelveticaNeue-Medium", "Helvetica Neue Medium";
}

.checkout {
  float: right;
  border: 0;
  margin-top: 20px;
  padding: 6px 25px;
  background-color: #6b6;
  color: #fff;
  font-size: 25px;
  border-radius: 3px;
}

.checkout:hover {
  background-color: #494;
}

/* Make adjustments for tablet */
@media screen and (max-width: 650px) {
  .shopping-cart {
    margin: 0;
    padding-top: 20px;
    /*border-top: 1px solid #eee;*/
  }

  .column-labels {
    display: none;
  }

  .product-image {
    float: right;
    width: auto;
  }
  .product-image img {
    margin: 0 0 10px 10px;
  }

  .product-details {
    float: none;
    margin-bottom: 10px;
    width: auto;
  }

  .product-price {
    clear: both;
    width: 70px;
  }

  .product-quantity {
    width: 100px;
  }
  .product-quantity input {
    margin-left: 20px;
  }

  .product-quantity:before {
/*    content: 'x';
*/  }

  .product-removal {
    width: auto;
  }

  .product-line-price {
    float: right;
    width: 70px;
  }
}
/* Make more adjustments for phone */
@media screen and (max-width: 350px) {
  .product-removal {
    float: right;
  }

  .product-line-price {
    float: right;
    clear: left;
    width: auto;
    margin-top: 10px;
  }

  .product .product-line-price:before {
    content: 'Item Total: $';
  }

  .totals .totals-item label {
    width: 60%;
  }
  .totals .totals-item .totals-value {
    width: 40%;
  }
}
Comment: Porque aquele `style="display: none;"` no input?
Comment: Olá @EduardoSilva, mesmo retirando essa marcação e ajustando o css na parte do height: 16px; no meu style.css o campo fica pequeno, diferente das demais páginas.
Comment: tente utilizar um display:block para setar altura no campo.
Comment: Olá @LuanFagundes, o problema não está na altura e sim na largura do campo, valeu pela dica.
Answer: Pelo que verifiquei no seu site, isso só acontece quando a tela não tem largura suficiente para exibir o menu inteiro. Assim, o campo de pesquisa só é exibido quando se clica no ícone da busca.
A questão não está no CSS, pelo menos não na parte que você postou. Certamente isso é feito via Javascript, no momento em que a página é carregada e quando o tamanho da tela é alterado.
Procure no seu código por funções como window.onload e window.onresize, pois é numa delas que ocorre essa manipulação.