Search query for multiple tables with count(*)?

Question: I have a search field for an online shop that uses MySQL query for 2 different tables. The first table is vinyls which has 13 columns, and the second table is products which has 10 columns. The result I want is that if you enter a keyword, it will search the album_name and artist_name columns of table vinyls, and the name column in table products to find any matches.
My php code first counts the number of times a hit is made, and if it does, uses a query again to display the hits like online stores do. However, when I tested it, it only shows results from the vinyls table and not the products table. I've tried using UNION but because both tables have a different number of columns, it results in an error. I've used NULL to fill up the missing columns needed for union but it doesn't work too. Joins doesn't help either as the two tables do not have any similar column. What complicated it is the use of count(*) for the first query.
My SQL query using UNION and COUNT:
(SELECT COUNT(*) AS numrows
FROM vinyls
WHERE (     album_name LIKE :keyword
        OR  artist_name LIKE :keyword)
      )
union
(SELECT COUNT(*) AS numrows
FROM products
WHERE name LIKE :keyword)

My php code for search field:
$stmt = $conn->prepare("(SELECT COUNT(*) AS numrows
                        FROM vinyls
                        WHERE (     album_name LIKE :keyword
                                OR  artist_name LIKE :keyword)
                              )
                        union
                        (SELECT COUNT(*) AS numrows
                        FROM products
                        WHERE name LIKE :keyword)");

$stmt->execute(['keyword' => '%'.$_POST['keyword'].'%']);
$row = $stmt->fetch();

if($row['numrows'] < 1){
    echo '
No results found for '.$_POST['keyword'].'
';
}else{
    echo '
Search results for '.$_POST['keyword'].'
';
    try{
        $inc = 3;
        $stmt = $conn->prepare("(SELECT *
                                FROM vinyls
                                WHERE (     album_name LIKE :keyword
                                        OR  artist_name LIKE :keyword)
                                    )
                                union
                                (SELECT *
                                FROM products
                                WHERE name LIKE :keyword)");

        $stmt->execute(['keyword' => '%'.$_POST['keyword'].'%']);

        foreach ($stmt as $row) {...

I'm already stumped on how to search the 2 tables from only one search field and display the results from both tables and not only just one table. And it's a similar problem too when adding items to cart as they can be either from the two tables and I have to "join" the two tables again.
Where did I go wrong?
Edit:
Sample data

Vinyls table
+----+------------------+---------------------------+-----------+
| id | album_name       | artist_name               | genre     |
+----+------------------+---------------------------+-----------+
| 11 | Ravel Bolero     | Boston Symphony Orchestra | Classical |
| 12 | TV Calendar Show | Arthur Godfrey            | Orchestra |
| 13 | Flip Phillips    | The Phillips Quartet      | Jazz      |
| 14 | The Modern Idiom | Various artists           | Jazz      |
+----+------------------+---------------------------+-----------+
Products table
+----+-------------+------------------------------------------------------+
| id | category_id | name                                                 |
+----+-------------+------------------------------------------------------+
| 31 |          15 | Tonka/Diecast trucks and cars                        |
| 32 |          21 | Plate Number Georgia PQQ 1151                        |
| 33 |           6 | Walt Disney Read Along Casette Tapes                 |
| 34 |           7 | Herbert Von Karajan                                  |
| 35 |           8 | BANK IT! Board Game                                  |
| 36 |           9 | Iraqi Most Wanted Playing Cards                      |
| 37 |          10 | STAR TREK ( 1991,'92,'93 ) Stamp Oasis Rubber Stamps |
| 38 |          11 | Batman and Friends Action Figure Toys (4" - 5")      |
| 39 |          12 | Delta Dawn Porcelain Doll                            |
+----+-------------+------------------------------------------------------+

Expected result is similar to amazon's search bar, where you type a keyword and results show after you've entered. What I want in my site is that if I type orchestra in the search field, it will display Boston Symphony Orchestra's row. Or if I type cars, it will display the tonka row.
What I get is that it only shows the vinyls table and never the products table even if I type cars and there should have been a hit in the products table. Or I get an error because union is applicable only to tables with similar number of columns.
Comment: update your question add  a proper data sample and the expected  result
Comment: You can pass a field/column name to the COUNT function
Answer: You have 2 problems in your code.
First, your count query should work and throw no error, but you only look at the first result row (the one of your vinyls). But your query returns two rows. (It will return one row with the numrows field for the first unioned query (vinyls) and one row with the numrows field for the second query (products) in your union.
You could wrap it into a SUM to only get one result row back:
$stmt = $conn->prepare("SELECT SUM(numrows) AS numrows FROM
                        (SELECT COUNT(*) AS numrows
                        FROM vinyls
                        WHERE (     album_name LIKE :keyword
                                OR  artist_name LIKE :keyword)
                              )
                        union
                        (SELECT COUNT(*) AS numrows
                        FROM products
                        WHERE name LIKE :keyword)) AS sumQuery");

The second problem is the query, which loads your result and throws the exception because of the nonmatching column count. You have to define which columns of each of the two unioned queries should be returned, and they have to match on both. So f.e. do this:
        $stmt = $conn->prepare("(SELECT id, album_name AS name, artist_name
                                FROM vinyls
                                WHERE (     album_name LIKE :keyword
                                        OR  artist_name LIKE :keyword)
                                    )
                                union
                                (SELECT id, name, NULL AS artist_name
                                FROM products
                                WHERE name LIKE :keyword)");

Comment: Updated the query, please try again :)
Comment: I've tried it but it couldn't recognise numrows and throws a 'undefined index: numrows' error in the `if($row['numrows'] < 1)` line. I've also run a query in cmd and it still gives out two rows.


"esticar" linha no tablelayout

Question: Bom, estou programando android, e construindo layouts do meu app.
Meu problema: não consigo fazer o layout do meu app se adequar verticalmente a dispositivos diferentes.
meu código xml:
```

<code><TableRow
    android:id="@+id/tableRow2"
    android:layout_width="match_parent"
    android:layout_height="50dp" >

    <ToggleButton
        android:id="@+id/toggleButton1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="ToggleButton" />

    <ToggleButton
        android:id="@+id/toggleButton2"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="ToggleButton" />

    <ToggleButton
        android:id="@+id/toggleButton3"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="ToggleButton" />

    <ToggleButton
        android:id="@+id/toggleButton4"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="ToggleButton" />

    <ToggleButton
        android:id="@+id/toggleButton5"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="ToggleButton" />
</TableRow>

<TableRow
    android:id="@+id/tableRow3"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <ToggleButton
        android:id="@+id/toggleButton6"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="ToggleButton" />

    <ToggleButton
        android:id="@+id/toggleButton7"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="ToggleButton" />

    <ToggleButton
        android:id="@+id/toggleButton8"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="ToggleButton" />

    <ToggleButton
        android:id="@+id/toggleButton9"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="ToggleButton" />

    <ToggleButton
        android:id="@+id/toggleButton10"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="ToggleButton" />
</TableRow>

<TableRow
    android:id="@+id/tableRow4"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <ToggleButton
        android:id="@+id/toggleButton11"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="ToggleButton" />

    <ToggleButton
        android:id="@+id/toggleButton12"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="ToggleButton" />

    <ToggleButton
        android:id="@+id/toggleButton13"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="ToggleButton" />

    <ToggleButton
        android:id="@+id/toggleButton14"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="ToggleButton" />

    <ToggleButton
        android:id="@+id/toggleButton15"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="ToggleButton" />
</TableRow>

<TableRow
    android:id="@+id/tableRow5"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="" />

    <Button
        android:id="@+id/button1"
        style="?android:attr/buttonStyleSmall"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="Button" />

    <TextView
        android:id="@+id/textView4"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="TextView" />

    <Button
        android:id="@+id/button2"
        style="?android:attr/buttonStyleSmall"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Button" />
</TableRow>
</code>

```
Queria que meus botoes almentassem de tamanho sozinhos quando a tela aumenta, na horizontal isso ja acontece devido ao tablelayout stretchColumns mas como faço pra isso ocorrer na verticar tbm?
obrigado!
Comment: Joannis, dê uma olhada na minha resposta para essa pergunta: http://pt.stackoverflow.com/questions/33393/como-criar-bot%C3%B5es-com-tamanho-din%C3%A2mico-em-xml/33416#33416. Nela os botões se redimensionam conforme o tamanho da tela e orientação.
Answer: Bom, veja que você está utilizando TableRow.
O pai de TableRow deve ser TableLayout, pelas GuiLines do Google.
O seu TableLayout, com vários TableRows dentro, devem estar com fill ou match parent tanto na altura como na largura.
Se você deseja setar valor fixo para altura, como vi no seu exemplo, de 50dp, você pode definir um dimen.
Crie um arquivo Dimen na pasta values com:
50dp
Este será o atributo padrão.
Para outras resoluções, dimensões, densidades, etc...
Você pode criar outra pasta values, como values-small
E colocar esse mesmo dimen com valor menor, por exemplo.

"esticar" linha no tablelayout


Is it possible to have a V65/I if the following 2 chords are V42/iv then iv6

Question: I am a little stuck on the use of secondary dominants in relation to an assignment I have. I have posted the whole section for context, however I am confused on the first bar of the gm phrase.
From my understanding of secondary dominants, the chord preceding the iv6 would be a V42/iv (G major 4-2), with the iv being c minor. As that chord is the major version of the key signature, am I correct in assuming that the preceding chord of that would be a V65/major I chord?
If I am completely wrong in what I've written down, I would greatly appreciate if someone could point me in the right direction.
Thanks!
Answer: Yes, you're fine labeling it as V65/I.
The clearest way to show the "I" to "V42" relationship is to write both. Under the chord following, write a "I" then draw a vertical line to the left of it, connect a horizontal line underneath it going right, connect a 3rd line vertically to the left of it. Under this new "box" draw your secondary dominant label.
Your school may not be teaching you this method of labeling, but it is a clear way to show multiple tonal relationships for chords. Using this method, you can show that the G7 indeed resolved the D7 while simultaneously setting up a move to iv6.
Answer: Well, first off, regardless of what you call the second chord, the first chord is minor, not major.
I don't think calling it V65/I really adds much to the analysis here; I see what you're getting at, but it just seems like an unnecessary detail to me. When we hear the passage, we'll surely take it as a normal V65 (after all, the chords are the same) that turns out to just be a passing chord into the following harmony (this is the Burstein/Straus book, right? I think they've talked about passing V6 chords at this point…)
For the most part, there really isn't such a thing as secondary dominants of modal mixtures of I, because a) the chord is the same as its diatonic counterpart, so it tends to come off as overanalysis and b) any kind of "secondary" dominant of I is just a primary dominant. Again, I see your point: the chord does kind of lead to the next chord in a dominant-like way, almost like it's a V65 of V/iv, or V65/V/iv! But, especially in the more Schenkerian approach of Burstein/Straus, that second chord doesn't really have dominant function (secondary or otherwise) because the supposed leading tone doesn't resolve. This is just a passing chord harmonizing ^7 in the bass passing down to ^6.


Python 3.6 - Cannot get current stock prices from quandl, pandas and datetime

Question: I try to write a small "program" that gets the stock prices from Quandl.
The user should be able to enter a startring date (yyyymmdd) and the the program should then get the data from that date and forward to current date.
<code>import datetime as dt
import pandas_datareader as web

ticker = 'TSLA'

# Time variables for current and starting date as integers
current_year = int(dt.datetime.now().strftime("%Y"))
current_month = int(dt.datetime.now().strftime("%m"))
current_day = int(dt.datetime.now().strftime("%d"))

start_date = str(input("Starting date (yyyymmdd): "))
start_year = int(start_date[:4])
start_month = int(start_date[5:6])
start_day = int(start_date[7:8])

# Defines the total period
start = dt.datetime(start_year, start_month, start_day)           # Starting date, yyyy mm dd
end = dt.datetime(current_year, current_month, current_day)       # End date, yyyy mm dd

# Gets the data from start to end date for the stock definded as 'Ticker'
df = web.get_data_quandl(ticker, start, end)

print(start)
print(end)

print(df)
</code>
My problem is that I cannot seem to get any data newer than 2018-03-27.
Answer: The WIKI database is indeed no longer updated or supported starting from March 27, 2018. The closest alternative on Quandl is EOD, which is a value-priced end-of-day US stock price data feed.


cache issue - misaligned views cached output

Question: I am trying to set the view on the home page.
http://www.userbase.com/
The content gets misaligned for anonymous user. I can see proper output if I am logged in.
Any ides?
I am using following cache plugins:

Block Cache Alter
Render cache
Render cache for comments added to a node
Render cache for display suite views integration
Render cache for node_show
Render cache for views_plugin_row_node_view
Safe cache_form Clear
Comment: does clearing the cache have any effect?
Answer: It looks like you need to add clearfix to the css attribute of your views rows.
Comment: Thank you for the answer!! it worked. But I still have the missing rows. Any ideas? You can check now
Comment: You didn't say anything about missing rows. From a quick glance it looks like you need more filters on your view, maybe: content type, publish status, ?


Sudden login failure on RDS server on Windows 2012

Question: So, my knowledge on Remote desktop services is not so good, but I managed to get it up and running last year, it's been working just fine for eight months. Now today no Remote desktop users can login. Console sessions are working fine though. I checked and the licensing is okay, no errors. But users trying to login are logged in the security log such:

EVENT ID: 4625
Log Name:      Security
Source:        Microsoft-Windows-Security-Auditing
Date:          xxxxxxxx
Event ID:      4625
Task Category: Logon
Level:         Information
Keywords:      Audit Failure
User:          N/A
Computer:      xxxxxxxxx
Description:
An account failed to log on.
Subject:
Security ID:                 NULL SID

Account Name:                      -

Account Domain:                            -

Logon ID:                            0x0

Logon Type:                                      3
........

To narrow it down I followed this tip to get logging running in the netlogon.log-file https://social.technet.microsoft.com/Forums/windowsserver/en-US/1001bb80-c490-4ec6-828a-9090588c570c/cannot-remote-desktop-into-windows-2008-server-eventid-4625?forum=winserverTS
My log shows the following:

03/11 22:38:44 [LOGON] [3000] SamLogon: Network logon of domain\user from client Entered
03/11 22:38:44 [CRITICAL] [3000] NlPrintRpcDebug: Couldn't get EEInfo for I_NetLogonSamLogonEx: 1761 (may be legitimate for 0xc000006d)
03/11 22:38:44 [LOGON] [3000] SamLogon: Network logon of domain\user from client Returns 0xC000006D

When searching on the [CRITICAL] part of the above log it looks like it has to do with the wrong DC is answering or something. We used to have a BDC but it is gone since long. I can't figure it out, Any suggestions?
Answer: We are also experiencing the exact same problem since a few days.
Try setting the security level in the RDP-Tcp settings to RDP Security Layer instead of negotiate or SSL.
That (temporarily) fixed it for us.
Must be a Windows update or so...
Comment: Interesting. However I can confirm no update (neither Windows or third-party) was applied before it stopped working and after.
Answer: Try to check if DC's and user machines has correctly synchronized time. If so, check your RDP setting and try to disable NTLM authentication. Another thing can be that some profiles are broken (because of some migration when SID's are gone), did you tried create new profile and connect to RDP with sufficient privileges to RDP? Last thing it can do this problem is with bad configured DNS servers on workstations and DC's.
Comment: I mean creating whole new user account, because it's general problem and there could be more causes why it doesn't work. So try to create for example new domain admin user account and log-in with this account to your machine. I don't know if you tried this. EDIT: I haven't noticed your message below, so my advice with NTLM helped, but it's just half-soulution because NTLM should work withous problems.
Comment: @jtheman  I remember one last thing which could cause problems with NTLM, it can be caused by modified Group policy / Security policy settings of Network Security, e.g. http://1drv.ms/1C9kQmw and set **Network security: LAN Manager authentication level** value to **Send NTLMv2 response only** on your Domain Controller Group Policy Managment.
Comment: Thanks. Yes time is in sync. Sorry what kind of profile do you mean?
Comment: OK, thanks, I checked the NTLMv2 response and it's not the case. Yes NTLM has been working before, So I agree it's just a half solution.
Answer: I have no clue why this apparently got changed - or other thing made this not to work. But unselecting the "network level authentication for remote-desktop services" for the server worked. Now everyone can access.
I used this simple guide:

Source: http://www.2x.com/disabling-network-level-authentication-for-remote-desktop-services-connections-2/
Answer: Thanks Sam, setting the security level in the RDP-Tcp settings to RDP Security Layer fixed it for us.
Turns out the better fix was to uninstall update KB3002657 from the domain controllers - that was the cause of the Netlogon problem for us.


How to view functions called from button click to a request in Chrome Dev Tools?

Question: How can I see which functions and in what order were called after I clicked on a button, before a network request is sent? Should I pause with a mouse click breakpoint or XHR/fetch breakpoint? I want to find the origin of certain variables (in this case, request headers and parameters) how were they structured or generated when passed in a request
Comment: You can stop at either of them and take a look at the call stack of the event. It allows you to go back as far back as you'd like in the execution chain.
Answer:
The Call Stack shows the Chain of the call until the breakpoint

Also hovering on the initiator of the request in the network panel shows the call stack
Comment: Here, the breakpoint was in the script itself. What if the breakpoint is on the mouse click event? (Sources > Event Listener Breakpoints > Mouse > click)
Comment: then it would only show the `onclick` function in the `call stack`. the call stack won't show future functions
Comment: would it be possible to show them? what the the options at the top for? (skip over function call, step to next function call etc.)
Comment: i don't think there is a way to show future functions in the stack in chrome dev tools but i could be wrong. also the buttons at the top are to progress or regress the debugger
Answer: You can use the initiator tab if you are looking for the callstack which triggered the request.


Is it valid to use a difference score as an independent variable in a regression analysis

Question: I would like to see if the difference in the number of BPD symptoms from baseline to follow-up two years later can predict psychosocial functioning at the 2 year follow-up. So I wanted to do a linear regression using a difference score (BPD score T1- BPD score T2) as the IV and different measures of functioning at T2 as the DV's (e.g. SOFAS score as global functioning; peer rating scale as interpersnal functioning; and some binary measures such as work or no work at T2; so will need to complete a series of regressions).
Is it valid to use the difference score. I have read a lot about using a difference score as a dependent variable but am unsure if the same information would correspond to using a difference score as a IV?
I guess an additional question would be is it more approriate to use T1 measures of the outcome variables as covariates in the regression equation in order to measure change in that variable also? Or is that a seperate question?
I appreciate any comments as I am quiet unsure of how to proceed and am going around in circles in how best to get some clarity.
Comment: It is a little hard to follow what you're trying to do. What is your dependent variable and which variables do you want to have as independent. Do you want to do $\Delta BPD = \beta_0+\beta_1*work+\beta_2*...\beta_k$ or is it $Fancy\; outcome = \beta_0+\beta_1*work+\beta_2*\Delta BPI+\beta_3*...\beta_k$?
Comment: See also  https://stats.stackexchange.com/questions/3466/best-practice-when-analysing-pre-post-treatment-control-designs
Answer: Difference scores as independent variables are fine, but they impose a functionally more restrictive form on the equation. Consider;
$y = \beta_{11}(X_2) - \beta_{21}(X_1) + e_1$
Versus the equation;
$y = \beta_{12}(\Delta X) + e_2$
Where $\Delta X = X_2 - X_1$. You can see the second equation is a special case of the first when $\beta_{11} = \beta_{21}$. Only when you have very good reason to believe the more functionally restrictive form is reasonable, should you use the change scores.
You could actually have situations in which $\beta_{11}$ and $\beta_{21}$ have countervaling effects (e.g. $\beta_{11} = -\beta_{21}$, and the change score would appear to be inconsequential when in reality the two individual components contribute to the outcome.
Answer: As far as I know, there is no reason you can't use a difference score as an independent variable in a regression. It violates no assumptions.
Your second question is more complex. Your idea of using T1 measures as covariates is often done. People also sometimes use difference scores as a DV (as you probably know from your reading).
There are some problems with pre- post- testing when the variables are measured with error (as all psychological variables inevitably are). If I recall correctly, there are details in Collins and Horn.
Answer: Using a difference score as a predictor in multiple regression will usually lead to some loss of model fit, i.e. R-squared will be less than what it could be if you leave both variables in the difference score to be their own predictors with their own slopes.  That is, if you have a model like this:
$$
y' = a + b_1 d, \text{where}~~~ d = (x_1 - x_2)
$$
It is the same as forcing the two slopes to be equal in magnitude but opposite in sign.  That is via multiplication,
$$
y' = a + b_1 (x_1 -x_2)
$$
and $y' = a +b_ 1x_1 - b_1 x_2$.
So, in a sense it is forcing the linear restriction that you use +1 and $-1$ coefficients, or at least equal but opposite in sign slopes.
To maximize the fit of the model, use this approach instead, allowing the slopes for both variables to just be estimated freely (and if they happen to be equal but opposite in sign, then the difference score is okay):
$$
y' = a + b 1 x_1 + b_2 x_2
$$
The loss of R-square or model fit depends on how different the freely estimated slopes would be from the linear restriction of the difference score.  Running a simulation with different population slopes, we've found that the loss in R-square (predictable variance in the DV) ranges from zero to about .83, so it can be small or drastic.
Bottom line - just use the regular model with the two variables with their own estimated slopes as the last model above.  If the best fit results from time1 - time2 (difference score) then it will be estimated as such, and if not, then your model fit will be much better.
References:
Edwards, J. R.  (2001).  Ten difference score myths. Organizational Research Methods, 4, 264-286.  Download
Difference Scores in Linear Regression: Model Fit with Correlated Predictors MICHAEL C. HELFORD, ADRIAN L. THOMAS, MARLAINA M. MONTOYA, LONG H. NGUYEN, AYESHA P. JAMASPI, ASHLEY Y. CHUNG, Roosevelt University; email@example.com  A statistical simulation was used to estimate the loss of model fit in linear regression when using difference scores with correlated predictors compared to non-difference score models. Differences in model fit ranged from 0 to 0.84 across 9 simulated populations.
Comment: It is certainly true that your in-sample fit will decrease. However, by fitting a model w/ both variables you increase the risk of overfitting as well. This is especially true as the variables are likely to be correlated & if there is a theoretical reason to think the variable of interest is the (latent) difference rather than the original (manifest) variables.
Comment: The risk of overfitting is worth it.  It is very commonly the case that the last measured value is the dominant predictor of the outcome variable, i.e., that $b_{2} >> b_{1}$.


Proof by going the reverse way

Question: Proving a mathematical statement usually involves coming to the required result from a known/given result(s). Am I allowed to do this the other way round i.e. coming to a known result from the required statement? Here is a simple example:
Proof of AM-GM inequality for two numbers:
$ (\sqrt x - \sqrt y)^2 ≥ 0 $
$\implies x + y - 2\sqrt{xy} ≥ 0 $
$\implies \dfrac{x + y}2 ≥ \sqrt{xy} $
My presentation:
If
$ \dfrac{x + y}2 ≥ \sqrt xy $
$\iff x + y ≥ 2\sqrt{xy} $
$\iff x + y - 2\sqrt{xy} ≥ 0$
$ \iff (\sqrt x - \sqrt y)^2 ≥ 0 $
, which is true.
$\therefore (\sqrt x - \sqrt y)^2 ≥ 0 \implies \dfrac{x + y}2 ≥ \sqrt xy$
Is the second method considered a valid method of proof?
I know the second proof is just the reverse of the former but in some cases, it seems easier to go from the required statement to the given.
Answer: Your presentation is good, in fact almost perfect, however you should simply omit the initial word "If" which serves no purpose. The point of your presentation is that you are starting from the statement to be proved, then applying laws of algebra to find a sequence of equivalent statements, and then observing that the final statement of this sequence is true, hence all of them are true.
Comment: +1 The crucial part is that the statements are **equivalent**. So colloquially speaking, every step is reversible, and hence you have a proof by reversing all the steps
Comment: Do you think it would be better to use <= instead of <=>, as Lereau said?
Comment: It's kind of an aesthetic choice when writing a proof like this. But, I don't think it would be better. Hiding reasonably obvious facts can be confusing to a reader, who might think: "Am I missing something? Am I overthinking this?". Instead, at some point you (the writer) might add a comment like "Notice that we only need one direction of these bi-implications".
Comment: I want to note that the point of using "<=" is to make a reverse presentation of the proof possible. And this does not necessitate that all statements used on the way are equivalent!
Comment: @Lereau: I agree. That's how I teach $\epsilon,\delta$ proofs, for example.
Comment: @LeeMosher I think that is a great use-case!
Answer: Doing the proof in reverse is perfectly fine and you can even write your proof in the following way:
$$
\dfrac{x + y}2 ≥ \sqrt xy
~~\Longleftarrow~~ x + y ≥ 2\sqrt{xy}
~~\Longleftarrow~~ x + y - 2\sqrt{xy} ≥ 0
~~\Longleftarrow~~ (\sqrt x - \sqrt y)^2 ≥ 0
$$
where every "$\Longleftarrow$" should then be read as "is implied by". By noting that the last statement in the row is true, the first one must be too.
I have rarely seen this kind of backwards reasoning in proofs on paper, however it is the standard way proofs are done in most proof assistants.
Answer: The second method is what everyone writes down on a bit of scrap paper. Students often write it down as a proof as well, and often forget that a double-arrow is needed, which leads to proofs like this:

To prove $2 = 1$:
$2 = 1$
hence
$1 = 2$ as well.
Add these to get $3 = 3$, which is true.
so we're done and it's true!

That pattern has led to a general disdain for such proofs, even when they're valid (like yours, aside from the unnecessary initial "If".). It helps the reader a lot if you start with a preliminary declaration that you're going to prove equivalence to some known thing, so I'd write your proof like this:

I'll show that AM-GM is logically equivalent to the true statement $(\sqrt{x} - \sqrt{y})^2 \ge 0$ for any real numbers $x,y$ $u$, through a sequence of equivalences.
\begin{align}  \dfrac{x + y}2 &≥ \sqrt {xy} && \text{equivalent, by
multiplying/dividing by $2$, to}\\
x + y &≥ 2\sqrt{xy}&&
 \text{equivalent, by subtracting/adding $2\sqrt{xy}$ from both sides,
 to}\\
 x  - 2\sqrt{xy} + y & >= 0 && \text{equivalent, by factoring/expanding, to}\\ (\sqrt x - \sqrt y)^2 &≥ 0
 \end{align}
Because this final statement is true for all nonnegative $x,y$, so is
the AM-GM inequality.

But by the time you add all that stuff, including the reason for each double-implication, it's actually harder to read than the "first form" proof. Furthermore, it's generally interesting to prove equivalence between two familiar things, but the second thing, in this case, isn't nearly as interesting in its own right as AM-GM. So a proof that goes from "known but not particularly inspiring basic thing" to "new and widely-useful statement" will make more sense to your reader.
Comment: Thank you for including the false proof of 2=1 in your answer. Perhaps this is why my teacher is so hostile to such proofs.
Answer: The second argument is (almost) OK because you carefully used "if and only if" ($\iff$) rather than just "implies" ($\implies$).
You don't want to start that argument with "if".
I would recommend the usual straightforward implication even if the argument the other way is how you discovered your proof. The other way is prone to logical error.

Proof by going the reverse way


can we use dynamic sql in snowflake scripting?

Question: We make extensive use of dynamic SQL in Snowflake Stored Procedures for many reasons.
One of them being that we have several databases, each prefixed with the environment name.
Like PROD_DB1, PROD_DB2, etc...
Our code is not specific to one environment so all of our stored procedures start by checking which environment they are executing in (looking at the prefix of CURRENT_DATABASE()).
Then we adapt our table/view names accordingly when doing cross database stuff.
This is just one example of the various reasons for dynamic SQL.
Is there a way to do this sort of things in Snowflake SQL (as opposed to Stored procedures using javascript)?
Answer:
Is there a way to do this sort of things in Snowflake SQL (as opposed to Stored procedures using javascript)?

Yes, it is possible to build arbitrary query and execute it using with Snowflake Scripting. EXECUTE IMMEDIATE:

Executes a string that contains a SQL statement or a Snowflake Scripting statement.
<code>EXECUTE IMMEDIATE '<string_literal>'
 [ USING (bind_variable_1 [, bind_variable_2 ...] ) ] ;
</code>

Related: Snowflake dynamic SQL: Equivalent of DBMS_SQL/sp_executesql, Dynamic SQL in a Snowflake SQL Stored Procedure


Does starting on a "silent" string instrument compromise learning in any way?

Question: I'm looking at learning a string instrument (either violin, viola or cello), and I see that there's a few "silent violins" etc. on the market. Obviously this would have some perks, as my initial performance is going to be far from captivating for those in my home!
Though I'm concerned that as it's not the real thing, my learning may be askew. Specifically, there may be certain nuances of a truly acoustic violin that a "silent violin" won't represent. Is there any merit to these concerns?
Answer: I have a Yamaha silent (nylon string) guitar.  Although not a bowed instrument, the issues will largely be the same. It is great fun to play and I am happy to own it.
The most noticeable difference when compared to an acoustic instrument is in its treatment of dynamics.  When wearing headphones, the range of dynamics is much narrower than one who realise with a natural acoustic instrument.  I find myself having to greatly exaggerate the velocity with which I pluck a string in order to obtain the same range of dynamics.  These issues are the result of the electronics and effects included with the instrument and the result can be rather grating on the ear, especially when playing more sensitive phrases with intended pianissimo.  When one is a learner, it is tempting to use the built in effects to compensate for inadequacies elsewhere.
This problem is further compounded if one plays the instrument without the headphones.  Playing without the headphones produces volumes similar to an unamplified electric guitar and the dynamics are almost non-existent.  It's easy to get lazy and simply pick up the instrument without the headphones.  In fact, this is the most frequent way I play it.  If I learn a piece in this manner, when I pick up an acoustic instrument I routinely pluck the string with far to much velocity.
So I would say that it is probably not the best way to learn an instrument, even if it is great fun to play with when you have a bit of experience.  Also, the tone is obviously much different.
Answer: The majority of the technical feedback when starting to learn a string instrument is acoustic garbage.  Not even a silencer of comparatively benign effect will leave you with a representative noise spectrum.  Contributing factors are the contact point of the bow going all over the map instead of staying with the same point between bridge and fingerboard and non-constant bow pressure (pressure very much varies with bow position and thus needs compensation by the player).
Then the ongoing pitch control works via sympathetic vibration of neighbouring strings.  You hear when you are fingering correctly.  An acoustically dead instrument will not likely provide the same amount of acoustic coupling.
It's better to see whether there is some basement or shed where you can practice without fear.
Comment: You clearly haven't tried a Yamaha hollowbody (I have). Thru headphones, you get plenty of pitch and tonality response for any beginner.
Answer: When I first tried a real acoustic piano after digital one, the first immediate problem was how loud the acoustic piano is. The sound feedback was completely different. I has been using the sound level that looked comfortable for me with my headphones, and it was well below that a pianist usually hears.
This is of course not a problem as long as you are aware of it. However it may be good idea at least to try the acoustic version and then adjust the headphone sound setting to be comparable.
Answer: The two things I try to do are (1) sound good, and (2) play in tune.  You might be able to learn to play in tune, but you could never learn to make good tone unless you actually play the instrument.
I wouldn't do it.  I'd buy earphones for your family and your neighbors.


How to invalidate the template once set?

Question: Question
Please tell me how to invalidate the template once set with the setTemplateAfter method on Phalcon 3 so as not to refer to the template.

Overview
The current configuration is extended by IndexController ControllerBase.
In the initialize method of ControllerBase, set the template with setTemplateAfter as follows.
$this->view->setTemplateAfter('common');

In the expanded IndexController, since the template is unnecessary, an error occurs although the following is executed.
$this->view->setTemplateAfter('');

*I am thinking that I do not want to change to ControllerBase as much as possible because the template is used by another controller.

Error message
View 'layouts/' was not found in any of the views directory
#0 [internal function]: Phalcon\Mvc\View->_engineRender(Array, 'layouts/', false, true, NULL)
#1 [internal function]: Phalcon\Mvc\View->render('index', 'index')
#2 /mnt/raid/serverapps/www/lashca/public/index.php(42): Phalcon\Mvc\Application->handle()
#3 {main}

Source code
controllers/ControllerBase.php
<?php
use Phalcon\Mvc\Controller;
class ControllerBase extends Controller
{
    public function initialize()
    {
        $this->view->setTemplateAfter('common');
    }
}

controllers/IndexController.php
<?php
use Phalcon\Mvc\Controller;
class IndexController extends ControllerBase
{
    public function indexAction()
    {
        $this->view->setTemplateAfter('');
    }
}

Environment

CentOS 7.4(x64)
Apache 2.4.6
PHP 7.0.26
Phalcon Framework 3.2.4
MySQL Ver 14.14 Distrib 5.6.38
Comment: Do you completely want to remove the view layout? Then you can do `$this->view->disable()`
Comment: I do not want to use layout, but I want to use view.
`$this->view->disable()` certainly makes layout ineffective but view is also invalid, so I would like to know another way.
Answer: You can disable certain levels of view rendering via $this->view->disable().
For example, if you want to disable the "template after"-rendering you can do this:
$this->view->disableLevel([
    View::LEVEL_AFTER_TEMPLATE  => true
]);

Check the documentation if you want to disable other levels of the view.
Comment: Thank you for your advice. It was solved by setting the following.
`$this->view->setRenderLevel(View::LEVEL_LAYOUT);`


Can't scrape span tag python

Question: So I'm trying to scrape this url https://news.detik.com/berita/d-5259113/anies-usai-diklarifikasi-polisi-penjelasan-saya-jadi-laporan-23-halaman. And what I want to scrape is string on span tag.

I want to scrape "293" string from that url. But the result is AttributeError: 'NoneType' object has no attribute 'text' error. And even I'm using find() on div tag above that span tag and print it, the result is None. This is my code:
sol = ('https://news.detik.com/berita/d-5259113/anies-usai-diklarifikasi-polisi-penjelasan-saya-jadi-laporan-23-halaman')

chrome_options = Options()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-dev-shm-usage')

driver = webdriver.Chrome(executable_path='/usr/bin/chromedriver',chrome_options=chrome_options)
driver.get(sol)
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);var lenOfPage=document.body.scrollHeight;return lenOfPage;")

html2 = driver.page_source
soupa = BeautifulSoup(html2)

ala = soupa.find('span', {'class','comment__cmt_count_komen___12bbw'}).text
print(ala)

Any help would be appreciated.
Answer: Try to wait until comments number set:
from selenium.webdriver.support.ui import WebDriverWait

element = driver.find_element_by_css_selector('a.komentar > span')
WebDriverWait(driver, 10).until(lambda driver: element.text != '0 komentar')
print(element.text.rstrip(' komentar'))

Can't scrape span tag python


Difficulty in Proving Abel Theorem

Question:
Theorem : Suppose $\sum^\infty_{n=1}a_n$ converges.Then

  $lim_{r\to1,r<1}\sum^\infty_{n=1}r^na_n$=$\sum^\infty_{n=1}a_n$.

My Attempt:
I thought  to apply summation by parts.
So I get $\sum^N_{n=1}r^na_n=\sum^{N-1}_{n=1}A_n(r^n-r^{n+1})+A_Nr^N$
Where $A_N=\sum^N_{n=1}a_n$ As $n\to \infty, A_n\to A$
.
Here I wanted to use fact that $r\to 1$
I could not able to collect ideas to give proof.

Any Help will be appreciated
Answer: If a power series converges at a point $x_0=R$ then it converges uniformly in $[0,R]$. So in your case $\sum^\infty_{n=0}a_nx^n$ converges uniformly in $[0,1]$. And it is a known theorem that if a sequence of continuous functions converge uniformly then the limit function is continuous as well. In your example you have the sequence $f_k(x)=\sum^k_{n=0}a_nx^n$, and $f(x)=\sum^\infty_{n=0}a_nx^n$ is the limit function, hence it is continuous at the point $x=1$ when you take $x \to 1$, $x<1$.

Difficulty in Proving Abel Theorem


Getting a 500 internal server error for wordpress?

Question: I already tried doing the php.ini memory=20MB solution but it did not work. I uploaded it under the wp-admin/ folder.
I'm not really sure what else to try. Help?
Comment: Check your web server's error logs. It'll have to details about the 500 error. What you see in your browser is deliberately vague to prevent internal status/configuration data from leaking out.
Comment: Look at this - http://codex.wordpress.org/Editing_wp-config.php#Debug
Answer: The memory bump doesn't go into an .htaccess file in wp-admin. It goes into the .htaccess in web root. Use FTP to find and delete the .htaccess file you put in wp-admin.
Then forget about .htaccess files and try adding the line below near the top of your wp-config.php file, a few lines after the opening  <?php
define('WP_MEMORY_LIMIT', '64M');
Answer: Renaming plugin directory temporary solved the problem for me
Answer: This problem occurs because your php dont't have any xml or has a deprecated version xml, so if you manually instal or update your xml, the problem will be solve.
If you using Ubuntu, try execute this code in your terminal:
sudo apt-get install php-xml

After this you need to restart apache so it takes effect, for this execute the command:
sudo service apache2 restart

Answer: A 500 error is an Internal Server Error, which sometimes can be a hosting configuration problem, but in WordPress it is often a fatal PHP error.
First, just remove that php.ini file - some web hosts do not allow you to modify the PHP settings, so let's take that out of the mix first.
If it is a server error, temporarily rename your .htaccess file to something else (to take it out of the mix as well). Also, check for an error_log file in your filesystem, or the Error Logs in your hosting control panel.
If that doesn't tell you anything, it is likely a PHP issue. Turn on WordPress Debugging by adding the following code to your wp-config.php file:
// Enable WP_DEBUG mode
define( 'WP_DEBUG', true );

// Enable Debug logging to the /wp-content/debug.log file
define( 'WP_DEBUG_LOG', true );

// Disable display of errors and warnings
define( 'WP_DEBUG_DISPLAY', false );
@ini_set( 'display_errors', 0 );

// Use dev versions of core JS and CSS files (only needed if you are modifying these core files)
define( 'SCRIPT_DEBUG', true );

Make sure you comment out the line that says:
 define( 'WP_DEBUG', true );

Now, when you refresh the page and get the error, WordPress will write any PHP errors to wp-content/debug.log. Check that log for a fatal PHP error - it will tell you which file is causing the error, often a theme or plugin file.
Once you know the cause, rename that theme or plugin to temporarily remove it from WordPress. That should restore normal functionality.
Answer: Go to setting -> permalink and then select any common setting after that save it.
Reload the website. Everything will be fine.
Then reset it to previous common setting so that it will not effect for URL.
Answer: Another important fix for the internal server error is to try and upload a fresh version of wp-admin and wp-includes to your site.
This step should be a last resort, but if you've used the above solutions and still cannot find one that works, it's worth a try. Backup your site, and download a fresh version of WordPress from the main site.
Extract the files from the ZIP file, and open the extracted folder. Open your site's root directory in an FTP client, and upload the wp-admin and wp-includes from your fresh version of WordPress to your site's directory, overwriting the older versions.
Refresh the client, and refresh your site. If the error is gone, it was likely caused by a corrupted core file. If you still see the error, you may have no other option than to contact your host. Check it out for more WordPress internal server error fixes.


When are uni-grams more suitable than bi-grams (or higher N-grams)?

Question: I am reading about n-grams and I am wondering whether there is a case in practice when uni-grams would are preferred to be used over bi-grams (or higher N-grams). As I understand, the bigger N, the bigger complexity to calculate the probabilities and establish the vector space. But apart from that, are there other reasons (e.g. related to type of data)?
Comment: n-gram language models are meant to define probability vectors over words in a vocabulary, conditioned on a context (i.e. in unigrm case, the context is null hence the probabilities are basically defined as the maximum likelihood estimate: \frac{# of a particular word in the training data}{#of words in the training data} which weak way of computing a probability.
Comment: Vector space?! Do you mean the probability vectors, i.e. the multinomial distribution? - Withou 99% certainty, I can say that unigrams should never be used as n-gram language models.
Comment: As Lior mentioned below, I meant a vector space for e.g. TF-IDF.  How would you used probability vectors in this case?
Answer: This boils down to data sparsity: As your n-gram length increases, the amount of times you will see any given n-gram will decrease: In the most extreme example, if you have a corpus where the maximum document length is n tokens and you are looking for an m-gram where m=n+1, you will, of course, have no data points at all because it's simply not possible to have a sequence of that length in your data set. The more sparse your data set, the worse you can model it. For this reason, despite that a higher-order n-gram model, in theory, contains more information about a word's context, it cannot easily generalize to other data sets (known as overfitting) because the number of events (i.e. n-grams) it has seen during training becomes progressively less as n increases. On the other hand, a lower-order model lacks contextual information and so may underfit your data.
For this reason, if you have a very relatively large amount of token types (i.e. the vocabulary of your text is very rich) but each of these types has a very low frequency, you may get better results with a lower-order n-gram model. Similarly, if your training data set is very small, you may do better with a lower-order n-gram model. However, assuming that you have enough data to avoid over-fitting, you then get better separability of your data with a higher-order model.
Comment: Just a small additional remark: if tokens are *independent* then 1-grams work as good as n-grams. And e.g. naive bayes is an example that you can often neglect context/correlations. But as you answered, the main issue probably is that you need (exponentially?) more training data the longer your n-grams are.
Comment: @Anony-Mousse: Very good remark about independence. However, I think that, at least in NLP, true statistical independence of the phenomena you're trying to model in most tasks is pretty rare-- or am I wrong? Also, the amount of training data required [does indeed increase exponentially](https://www.cs.utexas.edu/~mooney/cs388/slides/ngrams.ppt).
Comment: It really depends on what you want to do. Naive bayes in spam detection is the prime example where 1-grams preform well. But in other cases, you  want to use at least bigrams.
Comment: @Anony-Mousse: Yes, I have heard that about spam classification, but would higher-order *n*-grams not still perform better?-- Otherwise, a sentence such as: "Nearly all the spam mails I get contain words like 'viagra', 'Vi@gr@', ' viaaggggra', 'via.gra' and so on" would ironically be strongly indicative of spam.
Comment: The error of using n-grams can be in *favor* of the desired decision. The estimated probability of NB is usually unusable; but the binary decision spam-nonspam is very good. The position information maybe does not add that much value for spam mails that are largely random words and "viagra"; maybe also because the nonspam texts are so diverse the n-grams there are largely unique.
Simply put: if "viagra" already is 99% indicative of spam, "buy viagra" probably only increases this to 99.9% - same outcome.
Comment: Is it true please that keeping low-frequency N-gram will cause the model to overfit?
Answer: Usually, n-grams more than 1 is better as it carries more information about the context in general. However, sometimes unigrams are also calculated besides bigram and trigrams and used as fallback for them. This is usefull also, if you want high recall than precision to search unigrams, for instance, you are searching for all possible uses of verb "make".
Lets use Statistical Machine Translation as an Example:
Intuitively, the best scenario is that your model has seen the full sentence (lets say 6-grams) before and knows its translation as a whole. If this is not the case you try to divide it to smaller n-grams, keeping into consideration that the more information you know about the word surroundings, the better the translation. For example, if you want to translate "Tom Green" to German, if you have seen the bi-gram you will know it is a person name and should remain as it is but if your model never saw it, you would fall back to unigrams and translate "Tom" and "Green" separately. Thus "Green" will be translated as a color to "Grün" and so on.
Also, in search knowing more about the surrounding context makes the results more accurate.


Automatic Serial Connection

Question: I'm making a Qt Quick project which involves creating a serial connection with qserialport, i was wondering if it's possible to make the serial settings(baud rate,  data bits, parity) automatically adapt to the serial device. Could someone help me with this?
Answer: That will be a tall order. It may be possible, but not recommended by the Qt people. Here is what the QSerialPort documentation for the "FramingError" status says:
<code>Framing error detected by the hardware while reading data.
This value is obsolete. We strongly advise against using
it in new code.
</code>
All of the serial error statuses have that same warning. I have no clue why they would be obsolete, and what would replace those status bits, but if you ignore the warning, there may be a inelegant solution.
I have implemented auto-baud on a number of devices, but each time I had better access to the hardware than QML allows. The easiest approach is when a timer can be programed onto the pin (a common capability of a MCU) to measure the rate directly, but that is probably not available in your hardware. The fall-back approach is to monitor serial-port errors and respond to them intelligently. "Framing error" is the most useful, along with "Parity error".
My algorithm starts by setting the baud rate to the highest expected value. That way, the errors come fast, and you can respond to them quicker. If I get errors at that rate, then I try the next slower baud-rate. I count errors over a period of time (about ten character periods), and use a threshold to determine whether to change the rate, so that an occasional error doesn't cause an unwanted change in rate.
But I only ever changed the baud-rate, and have always used eight data-bits, one stop-bit and odd-parity. Trying to add all of those additional variables to the algorithm would be pretty daunting. If you could ignore parity errors until you had the correct rate, and then cycle through the parity settings, then maybe you could accommodate parity as well. But the number of data-bits would be very difficult to determine.
I know that this doesn't help much, but I hope that it could be a start. Good luck.

Automatic Serial Connection


Likelihood function when there is no common dominating measure?

Question: When we have a statistical model $\{ P_\theta, \theta\in\Theta\}$ on some common probability space, usually we define "the" likelihood function $L(\theta)$ via a Radon-Nikodym derivative with respect to some common dominating measure, say $\mu$. For that to be possible it is necessary that all the $P_\theta$ are equivalent in the sense that they agree on which events have probability zero or one. Without that assumption there is no common dominating measure.
What can we do to get a likelihood function when this is not the case? For instance, in the nonparametric setting of Is Maximum Likelihood Estimation (MLE) a parametric approach?  there is no common dominating measure. Ideas or references?
Comment: Interesting question. Even in the non-parametric setting---take the classical fixed design non-parametric regression problem, in the large sample limit there are Radon Nikodym densities w.r.t. to a dominating measure (the Wiener measure), given by Girsanov's theorem. In this sense, "nonparametric" just means the parameter space for densities is infinite dimensional.
Comment: @Michael: I have to read up on Girsanov T then ...
Answer: (Not really an answer, simply an elaboration on the comment. Apologies in advance.
It is a very interesting question. Hopefully the comment will be complementary to the answer(s) when they come along.)
It seems that, in order to make meaningful statistical statements, one needs densities/likelihood functions. Therefore a dominating measure necessarily shows up somewhere in the formulation, even in the non-parametric setting.
For example, take the classical fixed design non-parametric regression problem
$$
y_t = f(t) + \epsilon_t, \;\;t = \frac{k}{n}, \; k = 0, \cdots, 1,
$$
where $\epsilon_t \stackrel{i.i.d.}{\sim} (0, \sigma^2)$, and $f$ lies in, say, $C[0,1]$, the continuous functions on $[0,1]$.
The problem of estimating $f$ from $(y_t)$ is asymptotically equivalent to estimating drift $f$ from a sample path $Y_t$ of the stochastic process (Ito diffusion)
$$
dY_t = f dt + \sigma dW_t
$$
where $W_t$ is standard Brownian motion.
In this formulation, the problem becomes estimating a element $f$ of an infinite dimensional "parameter space" $C[0,1]$.
Statistically speaking, $Y_t$ is a probability measure $\mathbb{Q}^f$ on the Skorohod space $D[0,1]$, with Radon-Nikodym density
$$
\frac{d \mathbb{Q}^f}{ d \mathbb{P}} =e^{\int_0^1 \frac{f}{\sigma} dW_t - \frac{1}{2} \int_0^1 \frac{f^2}{\sigma^2} dt}
$$
with respect to the Wiener measure $\mathbb{P}$, which defines the law of $W$ (i.e. $f = 0$).
This is exactly like the parametric setting, except the model $\{ \mathbb{Q}^f \}_{ f \in C[0,1] }$ has an infinite dimensional "parameter space".
I believe the notion of contiguity, introduced by Le Cam, is in similar spirit---to introduce a framework where one can speak about densities and likelihood functions, when the parameter space is not necessarily finite-dimensional.


Google geolocalização funciona no browser do pc, mas não no browser do android

Question: Usando Ruby, Sinatra, Slim, Javascript, Google maps v3 API.
A Geolocalização funciona perfeitamente no browser no PC, o mapa é gerado com o marcador do parceiro, quando se clica no botão é solicitado a geolocalização ao browser, cria um novo marcador nessa posição e gera a rota.
Porem no browser no android quando clica no botão cai no erro:
infoWindow.setContent(browserHasGeolocation ?
'Erro: O serviço de geolocalização falhou.'

Na minha API KEY ativei tudo o que era relacionado ao MAPS e ANDROID.
Fiz um Fiddle, e nele funciona no android, só que está sem API KEY.
Fiddle
EDIT 1:
  Descobri que o google só permite usar o getCurrentPosition() em conexões HTTPS:// (nunca iria funcionar acessando pelo meu IP local), no heroku só funciona se eu usar o https:// antes do endereço tanto no browser do PC quanto no browser do android.
<button id="rota">Rota até o parceiro.</button>

Answer: O google só permite usar o getCurrentPosition() em conexões HTTPS:// (nunca iria funcionar acessando pelo meu IP local), no heroku só funciona se eu usar o https:// antes do endereço tanto no browser do PC quanto no browser do android.
Referência:
https://developers.google.com/web/updates/2016/04/geolocation-on-secure-contexts-only
Comment: Se esta é a solução, marque a resposta como aceita.
Comment: Não posso, a resposta foi eu mesmo que dei. Só posso marcar como correta depois de dois dias.


Paired T-testing or ANOVA?

Question: I have data of the structure below. im confused about using paired sample t-testing vs ANOVA. Paired T-tests make sense to me, but im worried; because there are 7 outcome measures, am i violating some assumption with t-test, and thus should use a form of ANOVA?  if so, which type, as I am very confused.  Thanks for any help!
Comment: Can you elaborate on your data, what are these variables that you are showing us, what do they represent? Also some context on the design and experimentation.
Comment: Sure, sorry. So these are continuous numerical variables. Two time points, n=6 at each time point. At each time point 7 outcomes are measures for each subject.
Comment: Also these are matched. So for example where you see "Outcome1 - Subject 1 in the Time 1 group; thats the same subject being measured again on the same variable at Time 2.
Comment: See https://stats.stackexchange.com/questions/3466/best-practice-when-analysing-pre-post-treatment-control-designs. $n=6$ is low, maybe tell us much more about the practical context. What are (in real life terms) outcome1, ..., outcome6?
Answer: It depends on the dimension in which the outcome of the test will be useful for you.
If you want to find whether there is a change in the values from time  to time , irrespective of the outcome types, you can perform the paired t-test, for which you have the melt the data.
Let's say that your data looks like this.

head(data)

library(data.table)

set1<- data[c(1,2:7)]
set2<- data[c(1,8:13)]
mset1<-  melt(set1)
mset2<-  melt(set2)
colnames(mset1)<- c('Outcome', 'Subject', 'time1')
colnames(mset2)<- c('Outcome', 'Subject', 'time2')
mdata<- as.data.frame(cbind(mset1, mset2[3]))
model1<- t.test(mdata$time1, mdata$time2, paired = T)
model1

Output
Paired t-test
data:  mdata$time1 and mdata$time2
t = -1.4521, df = 41, p-value = 0.1541
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
-13.433714   2.195619
sample estimates:
mean of the differences
              -5.619048

Paired T-testing or ANOVA?


Chord-Scale Theory: Determine chord qualities

Question: I started to learn about the chord-scale theory lately which i find quite interesting. I came across this table of modes (scales) and their corresponding chords:
<code>Chord-Scales of the Major Modes:

Ionian:              Maj7(9 11 13)
Dorian:              m7(9 11 13)
Phrygian:            sus7(b9 #9 b13)
Lydian:              Maj7(9 #11 13)
Mixolydian:          7(9 11 13)
Aeolian:             m7(9 11 b13)
Locrian:             m7(b5)(b9 11 b13)

Chord-Scales of the Harmonic Minor Modes:

Aeolian #7:          mMaj7(9 11 b13)
Locrian #6:          m7(b5)(b9 11 13)
Ioanian-Augmented:   +Maj7(9 11 13)
Dorian #4:           m7(9 #11 13)
Phrygian-Dominant:   7(b9 11 b13)
Lydian #2:           Maj7(#9 #11 13)
Altered bb7:         +6(b9 #9 #11)

source: http://brunojazz.com/vt-Chords-Scales.htm
</code>
I think i get the basic concept of it, it's basically just writing out every scale as a 7-note chord. What i don't get is, why is for instance the Chord of the Phrygian mode a sus-chord and has a b9 and a #9 and no 11? I get that 4 and 11 are basically the same note, but why is it called sus in this case and in other chords it's just a 11 extension?
The same goes for the last entry in the table; the Altered bb7 chord-scale. Why is it called a 6-chord and does not simply has a 13 extension in it, but a b9 and a #9?
I checked with another source as well (Mark Levine: Jazz Piano Book) and the corresponding chords to the modes have similar names, although with some differences. He calls the chord of the Mixolydian mode a sus-chord too, for example.
I am a bit confused. Is it because, when the Phrygian mode is played as a chord it just sounds as a sus-chord and therfore is called that or did i miss something regarding the theory?
Thanks in advance!
Answer: Yup, when reading down the list I got to the susb9 Phrygian, and I kind of knew that it would feature in this question!
Essentially, Phrygian can be thought of as a natural minor with a b2, hence in the same format as the rest of the chords written above you could write it
m7 (b9, 11, b13)
I tend to think of it this way, and when I got the Mark Levine book I was surprised to see it as a susb9 chord instead. In the great-american-songbook tunes the pure Phrygian doesn't pop up too often. This is because -
When that scale degree is acting as a V in a minor ii V i it's turned into a dominant b9 chord by raising it's minor 3rd, in order to better push towards the minor tonic. (note the resulting dominant chord often keeps the token Phrygian b9!)
In the common iii VI ii V I progression the Phrygian iii is generally written as just a straight minor 7
These are the more common times you see Phrygian, probably down to the commonality of these songs changing chords in 4ths. There are pieces I can think of that rise up I, ii, iii etc. But again it only really appears as a straight minor7 chord (or maybe minor11), no phyrigian extensions.
The reason being is that the b9 AND b13 extensions on a minor chord are considered 'not very flattering' and not that useful. This is subjective of course, but you see very few minor b13 or minor b9 chords used in western music (I don't know about elsewhere). I've seen the b6 called an avoid note, as well (though this is a little misleading, it more means 'be aware it will clash' rather than 'don't use it'). So the Phrygian's natural extensions, when played over a minor7 chord, don't really do it any favours. Or even if some like the sound it's certainly harder to voice it and voice lead it in a way that works as easily as the rest of the extended diatonic chords.
However, voicing it as a susb9 gets rid of this. You have all the notes needed in there to make this chord, this chord utilitises the characteristic sounds of the mode and is arguably a more practical alternative to the angular min7b9 or min7b13 chord. It's a cool sounding chord and a good way of getting a Phrygian sounding chord thats not too clashy.
That said, they list all the intervals in the above list of chords, so by the time you play your susb9 with the #9 and b13 added back in it's just as clashy as the minor Phrygian chord was. But play eg. 1, 4, b9, 4, 5 on a guitar and it sounds very very useable. The Mark Levine book is slightly contentious because it popped up at a time when relating a scale to every chord was 'the thing' in jazz and it kind of presents that info as if it's 'the only way' but thats not at all true, and not how the majority of the earlier jazz musicians approached playing, really, until the modal thing hit, and even then it was a gradual change. So it's a great resource with tonnes of info but just treat it as one persons perspective. I'm a bass player and in the Mark Levine book when he said that bass players tune to an Asusb9 chord that was news to me, none of my teachers had ever mentioned it and I'd never seen ANYONE do it in all the gigs I've ever been to :D I first encountered Phyrigian being a susb9 in that book, and I've met many astronomically good jazz musicians who are oblivious to that which Mark sets out as gospel, but I CAN see the practical function of it, and it's a unique sound.
So anyway, there are some reasons you may want to voice phyrigian as a susb9 rather than a minor chord if you play a chordal instrument, but I still think of it primarily as a minor mode when I see it come up in it's diatonic form (ie, not converted to dominant etc.)
As for the 7th mode of the harmonic minor scale, the modes of this scale are used a fair bit less than those of the major and melodic minor scales, and as such there is a bit less of a strong convention for naming them, you could arguably call it a few things but the authors intention was to explain a 'base' chord and then three easy to digest extensions for the purposes of memorization, it seems. The altered (melodic AND harmonic) is a bit of a funny one, as when you first play the mode you'll notice it, named one way, has two seconds (a flat one and a sharp one) or named another way two 3rds (a flat one and a natural one), also, the major 3rd we get is actually a flat 4th degree... oddness! Really it is 1, b2, b3, b4, b5, b6, b7/6 (melodic/harmonic) but we don't tend to think of it that way.
As the melodic minor altered scale generally functions as a dominant chord we tend to ignore the flat 4 oddness, and just say it's 1, 3 and b7 with b9, #9, b5 and #5. It's just a dominant chord with all alterations available, hence named altered.
For this one, the harmonic minor one, we can't say it functions as a dominant because it has no b7. Indeed, a major with a 6th is often a comfortable substitute for a major7 chord. So the author has tried to name the base chord in such a way that he can place the extensions on the top and create a full chord.
With the +6 he is describing the 1, 3, #5, 6, and with the added extensions you get the full scale. You're right, he could have just added the 13 on top. In that way his spelling would become
plus (b9 #9 #11 13) (I use the WORD 'plus' because the forum formatting turns a + symbol to a bullet point!)
Remember, if we are thinking of it as a major type chord then what we are really doing is thinking of the b4th degree of the scale as a major third, meaning we end up with two 2nd's, or two 9ths. This is against standard convention of 'one of each interval' but in these dusty corners the interval naming system DOES get a bit stretched, we have to just accept that that's how it is!
Arguably though, you could think of it as a minor type chord but then you have to deal with a flat 11, you could probably voice it a few other ways but I suspect the authors suggestion is one of the better, more succinct ways of expressing it in this format. I'm not too keen of thinking of the 5th note of the scale as a #11, I would still think b5th personally but really the purpose of such an exercise is just to find a way that YOU remember it, so work out his chord, change the naming a bit if needed and then go out and use it! There is far from standard convention on the chords from the harmonic minor.
As long as you understand the theory I wouldn't get too hung up on the second one, usually we can utilitise the harmonic minor in our playing by just playing the basic harmonic minor scale and remember what root notes we can place it on in order to create different effects over given chords in a piece. We don't need to worry too much about the underlying chords in the same way we do in the major scale. However, it's always fun to try and find new sounds!
Comment: Thanks, that was very useful! It's kind of confusing how many different notations are possible for these chord-scales... but you made a good job in clarifying it a bit :D
Comment: No problem! Yes, and theres plenty more to come, but you seem to be getting it so keep at it, luckily there are only these intervals to deal with, from 1 to 13, once you are comfortable with talking in that 'language' you can very quickly unpick a new idea!


Incorporating Fixed Effects with Causal Impact

Question: I have observations on a dependent variable of interest, $Y_{ijt}$, where $t \in [1,2,...T]$ denotes the time, $i$ denotes a particular brand and $j$ a specific product item. At $t=k$, there was an intervention, corresponding to the opening of a marketing channel used by some of the brands $i$ for some of the product item $j$. I want to use Causal Impact analysis to look at the effect of the marketing channel on the variable $Y$.
If I were to use traditional difference-in-difference analysis to look at the effect, I can incorporate fixed effects corresponding to the brand $i$ and product $j$. How can I incorporate these fixed effects in causal impact analysis?
Answer: This is currently not possible with the CausalImpact R package. If it is reasonable to do that in the particular problem, you can aggregate some / all of the items for which a new marketing channel was opened, and check if there is an aggregate effect.


Meaning of this proportionality

Question: I'm having understanding the maths part of a certain chemistry concept. There's a formula that states:
$$\frac{A}{B}\sim v^{-3}.$$
From this I can say that as v gets bigger, the right side gets smaller, and because the two sides are proportional, the left side gets smaller as well. This happens because B gets bigger and A gets smaller.
Is all this correct?
Answer: The first concept is correct: as $v$ increases, the RHS decreases and thus the LHS must decrease as well.
However, how that decrease happens is not quite what you describe. Either $A$ must decrease or $B$ must increase. Either of those is sufficient.
Comment: See whether you agree with my alternate answer?
Answer: The statement $$\frac{A}{B}\propto v^{-3}$$ means that for some non-identically-zero function $k$ of variables that don't have another dependence on $A,B$ or $v,$ $$\frac AB=\frac k{v^3}.$$

as $v$ gets bigger.... $B$ gets bigger and $A$ gets smaller.

Not necessarily. Suppose that $k=1$ and that $(A,B,v)$ changes from $(1,1,1)$ to $\left(\frac1{16},\frac12,2\right);$ as $v$ gets bigger, both $A$ and $B$ get smaller.

as $v$ gets bigger, because the two sides are proportional, $\dfrac AB$ gets smaller.

Not necessarily. Suppose that $k=-1$ and that $(A,B,v)$ changes from $(1,8,-2)$ to $(1,1,-1);$ as $v$ gets bigger, $\dfrac AB$ gets bigger.

Meaning of this proportionality


Autoload classes if script need them. What if my php file is in another folder?

Question: I found useful code that helps me keep my code readable.
function class_autoload($classname) {
    echo "class_autoload";
    @require_once ("class-{$classname}.php");
}

spl_autoload_register('class_autoload');

It loads classes, when server need them to run my code.
But now I have a problem:
One of my php files is in another folder then the rest. So I can't use this:
@require_once ("class-{$classname}.php");

And I can't change path because another php files will end work :/
What I should do now?
Answer: require_once produces a fatal error if the specified file does not exist. The error control operator (@) does not change that. Use include_once instead, or test whether the file that you try to read actually exists.
You can call spl_autoload_register passing different function names every time. The auto loader will then call each of these functions to try to load the class. Use this feature to write a new function similar to class_autoload, but that knows where the class file is, that you cannot load with your current class_autoload. Call spl_autoload_register, passing that new function as an argument. Of course, if you do not change the require_once in class_autoload, that new function will never get called; your script will have died before the autoloader ever gets a chance to try your new function.
Also, take a look at PSR-0. This describes how class names should translate to directory- and filenames. Try to adhere to this standard when chosing where to put and how to name your class files. It makes life easier for you and for people who try to understand your code.
Comment: One more question: it is possible to get domain of my site using PHP and use absolute path? It will be useful if I move this files to another folder.


Can ISPs see which IP that has been assigned to a customer in each others network?

Question: Is there some sort of shared knowledge between ISPs that make them able to see which customer an IP has been given to, no matter which ISP the IP belongs to? I.e. is someone that is an ISP able to see which customer an IP address is assigned to, just because they are an ISP?
Answer: No, at least not in the United States or any other country that I'm aware of - ISPs do not communicate in any way with each other about IP assignments within their space; they have the exact same visibility into another ISP's address assignments as any other member of the public.


RAID on VMware, Ubuntu guest

Question: I am doing some local testing on VMware server. I have set up my VM with two hard drives. I am installing Ubuntu Server, and creating manually in the installation the luks above a RAID 1 configuration. My question is: Should I locate each virtual hard drive in a different physical drive to take advantage of RAID?  Otherwise, if they both are in the same drive, I see no actual point of having a RAID.
In any case, I know this is not a "desirable" configuration, and it would probably better to have a hardware RAID controller (like in a PowerDell f. ex.) and have the VMs inside without knowing about the RAID.
Answer:
Should I locate each virtual hard drive in a different physical drive
  to take advantage of RAID?

Erm...yes, anything else would be a waste of time/space as you say, and yes a HW controller would be better.

RAID on VMware, Ubuntu guest


Default images also as user selected image functionality

Question: I have a content type with a taxonomy and based on that taxonomy, I want to have a default image to show unless the user wants to upload a different image. I'm not sure how to go about this functionality. Is there a module that should one could recommend or any suggestions?
I have used this to display taxonomy images https://www.drupal.org/node/1224916 and it works great but it doesn't give the user the option to upload their own pic.
Answer: Representative_image

Allows you to define representative image or media fields for entities
  like nodes, taxonomy terms and the like. These can then be used in
  Open Graph meta tags (via tokens); or as fields in views. The media
  module is also supported. A default image can be defined for those
  entities without images.


What does $P(\overline{A}B)$ mean when $A$ and $B$ are two events?

Question: It is my belief that $P(\overline{A}B)$ means the $P(\overline{A} \cap B)$. However, I am not sure. What does it mean?
Answer: I would agree with your thought process. In the probability courses I've taken, it was standard practice to read something like $P(AB)$ as $P(A\cap B)$. In your scenario, $P(\overline{A}B):=P(\overline{A}\cap B)$ makes sense. However, I think we can take this one step further. Think of this in terms of a Venn diagram. We know that $P(\overline{A})$ represents the complement of $P(A)$, i.e., everything "not in" $P(A)$. When we take the probability of this intersected with the probability of $B$, we see the resulting area will be $P(B)$ without $P(AB)$.
Comment: The last part of your post seems to suggest that $P(\overline{A}B)$ means $P(B)$. Is that what you meant? If so it does not seem right to me.
Comment: Hey, Bob. I can see the confusion. What I'm trying to convey is the area representing $P(B)$ without the intersected middle portion. I'm not sure how to type it in LaTeX. Visually, this shaded region of a Venn diagram should look like whichever circle represents event $B$ with the overlapping portion for the intersection is removed.


Apollo / GraphQl - Type must be Input type

Question: Reaching to you all as I am in the learning process and integration of Apollo and graphQL into one of my projects. So far it goes ok but now I am trying to have some mutations and I am struggling with the Input type and Query type. I feel like it's way more complicated than it should be and therefore I am looking for advice on how I should manage my situation. Examples I found online are always with very basic Schemas but the reality is always more complex as my Schema is quite big and look as follow (I'll copy just a part):
type Calculation {
    _id: String!
    userId: String!
    data: CalculationData
    lastUpdated: Int
    name: String
}

type CalculationData {
    Loads: [Load]
    validated: Boolean
    x: Float
    y: Float
    z: Float
    Inputs: [Input]
    metric: Boolean

}

Then Inputs and Loads are defined, and so on...
For this I want a mutation to save the "Calculation", so in the same file I have this:
type Mutation {
    saveCalculation(data: CalculationData!, name: String!): Calculation
}

My resolver is as follow:
export default resolvers = {
    Mutation: {
        saveCalculation(obj, args, context) {
            if(context.user && context.user._id){
                const calculationId = Calculations.insert({
                    userId: context.user._id,
                    data: args.data,
                    name: args.name
                })
                return Calculations.findOne({ _id: calculationId})
            }
            throw new Error('Need an account to save a calculation')
        }
    }
}

Then my mutation is the following :
    import gql from 'graphql-tag';
export const SAVE_CALCULATION = gql`
    mutation saveCalculation($data: CalculationData!, $name: String!){
        saveCalculation(data: $data, name: $name){
            _id
        }
    }
`

Finally I am using the Mutation component to try to save the data:
<Mutation mutation={SAVE_CALCULATION}>
    {(saveCalculation, { data }) => (

 saveCalculation({ variables : { data: this.state, name:'name calcul' }})}>SAVE

    }}
</Mutation>

Now I get the following error :

[GraphQL error]: Message: The type of Mutation.saveCalculation(data:)
  must be Input Type but got: CalculationData!., Location: undefined,
  Path: undefined

From my research and some other SO posts, I get that I should define Input type in addition to the Query type but Input type can only avec Scalar types but my schema depends on other schemas (and that is not scalar). Can I create Input types depending on other Input types and so on when the last one has only scalar types? I am kinda lost cause it seems like a lot of redundancy. Would very much appreciate some guidance on the best practice. I am convinced Apollo/graphql could bring me quite good help over time on my project but I have to admit it is more complicated than I thought to implement it when the Schemas are a bit complex. Online examples generally stick to a String and a Boolean.
Answer: From the spec:

Fields may accept arguments to configure their behavior. These inputs are often scalars or enums, but they sometimes need to represent more complex values.
A GraphQL Input Object defines a set of input fields; the input fields are either scalars, enums, or other input objects. This allows arguments to accept arbitrarily complex structs.

In other words, you can't use regular GraphQLObjectTypes as the type for an GraphQLInputObjectType field -- you must use another GraphQLInputObjectType.
When you write out your schema using SDL, it may seem redundant to have to create a Load type and a LoadInput input, especially if they have the same fields. However, under the hood, the types and inputs you define are turned into very different classes of object, each with different properties and methods. There is functionality that is specific to a GraphQLObjectType (like accepting arguments) that doesn't exist on an GraphQLInputObjectType -- and vice versa.
Trying to use in place of another is kind of like trying to put a square peg in a round hole. "I don't know why I need a circle. I have a square. They both have a diameter. Why do I need both?"
Outside of that, there's a good practical reason to keep types and inputs separate. That's because in plenty of scenarios, you will expose plenty of fields on the type that you won't expose on the input.
For example, your type might include derived fields that are actually a combination of the underlying data. Or it might include fields to relationships with other data (like a friends field on a User). In both these case, it wouldn't make sense to make these fields part of the data that's submitted as as argument for some field. Likewise, you might have some input field that you wouldn't want to expose on its type counterpart (a password field comes to mind).
Comment: @YanickRochon GraphQL has [object types](http://spec.graphql.org/June2018/#sec-Objects) designated by the `type` keyword and [input object types](http://spec.graphql.org/June2018/#sec-Input-Objects) designed by the `input` keyword. The former is used for output, the latter for input.
Comment: I have no idea what this answer means by `have to create a Load type and a LoadInput input"
Comment: Once again thanks for clear answer about graphQL/Apollo
Comment: @DanielRearden thank you for the clarification, I'm beginning to use GraphQL and there is much I need to learn.
Answer: Yes, you can:
The fields on an input object type can themselves refer to input object types, but you can't mix input and output types in your schema. Input object types also can't have arguments on their fields.
Input types are meant to be defined in addition to normal types. Usually they'll have some differences, eg input won't have an id or createdAt field.


Ubuntu 18.04LTS KVM VM Not Assigned IP by Router DHCP

Question: I'm setting up KVM on Bionic Beaver, however my router isn't assigning the VM an IP address. I can however see it from the host.
Here are my netplan settings:
network:
  version: 2
  renderer: networkd
  ethernets:
    enp4s0:
      dhcp4: no
  bridges:
    br0:
      dhcp4: no
      addresses: [192.168.0.26/24]
      gateway4: 192.168.0.1
      mtu: 1500
      nameservers:
        addresses: [192.168.0.1]
      interfaces:
        - enp4s0

My host is set to be static on 192.168.0.26 and I can login just fine.
KVM setting:
virt-install ...
            --network bridge=br0,model=virtio

I've also added the iptable rule:
iptables -A FORWARD -p all -i br0 -j ACCEPT

However no joy at all, can't see another available device on the router screen.
UPDATE
I'm using a cloud image with the following cloud config:
#cloud-config
network:
  version: 2
  renderer: networkd
  ethernets:
    ens2:
      dhcp4: yes
users:
  - name: james
    groups: users, admin
    sudo: ALL=(ALL) NOPASSWD:ALL
    ssh_authorized_keys:
      - ssh-rsa

It's actually worked once, the VM was assigned an IP and access was straight-forward. But not on any subsequent attempts.
Thanks,
Comment: i aint see a nat rule?
Comment: Would that look like: iptables -A FORWARD -p all -i virbr0 -j ACCEPT?
Answer: i use a routed config, that means my bridge isnt directly connected to the eth interface
iface ens3 inet static
address x. x. x. x
subnet x. x. x. x
 gateway x. x. x. x
post-up echo 1 > /proc/sys/net/ipv4/conf/ens3/proxy_arp
    post-up /etc/iptab_up
    post_down /etc/iptab_down

auto vmbr0
#NAT sub network, not bridged
iface vmbr0 inet static
    address  10.0.0.1
    netmask  255.0.0.0
    bridge_ports none
    bridge_stp on
    bridge_fd 0
    post-up   echo 1 > /proc/sys/net/ipv4/ip_forward
    post-up         iptables -t nat -A POSTROUTING -s '10.0.0.0/8' -o ens3 -j MASQUERADE
    post-down iptables -t nat -D POSTROUTING -s '10.0.0.0/8' -o ens3 -j MASQUERADE

replace ens3/vmbr0 with your interfaces
Comment: Thanks for your answer, could you post a netplan example?
Comment: sorry i alwqys uninstall betplan and replace it with ifupdown
Answer: For completeness, the answer wasn't that there was anything wrong with configuration. One of my previous cloud-init attempts had modified the network settings in a way I could not solve.
To fix this, I started with a fresh cloud image (originally Xenial as I was sceptical then back to Bionic) and it attached to the bridge just fine. My advice: use a fresh image with every attempt to make the installation immutable.


Why do we distinguish the continuous spectrum and the residual spectrum?

Question: As we know, continuous spectrum and residual spectrum are two cases in the spectrum of an operator, which only appear in infinite dimension.
If $T$ is a operator from Banach space $X$ to $X$, $aI-T$ is injective, and $R(aI-T)$ is not $X$. If $R(aI-T)$ is dense in $X$, then $a$ belongs to the continuous specturm, it not, $a$ belongs to the residual spectrum.
I want to know why do we care about whether $R(aI-T)$ is dense, thanks.
Comment: It seems as we just emphasize this difference for the operator, but not for the Banach algebra, why?
Answer: The point $\lambda\in\mathbb{C}$ belongs to the spectrum of operator $T$ if the operator $T_\lambda:=T-\lambda I$ is not invertible.
What can prevent $T_\lambda$ from being invertible? Recall that we are working in Banach space $X$ so invertibility is equivalent to bijectivity. Thus we need to study reasons why operator $T_\lambda$ can't be bijective. We can distinguish two cases:

the operator $T_\lambda$ is not injective
operator $T_\lambda$ is injective but not surjective

Now we discuss these cases.
1) The first one is the most common. In this case $\mathrm{Ker}(T_\lambda)$ is non-trivial so $T_\lambda$ is not invertible, and we say that $\lambda$ is in the point spectrum. If $X$ is finite dimensional this is the only possible case for operator not to be bijective. The reason is that an injective operator on a finite dimensional space is automatically surjective. But in case $X$ is infinite dimensional there are examples of injective but not surjective operators!
2) In the second case we have injective but not surjective operators. This means that the image of the operator $\mathrm{Im}(T)$ (which is a linear subspace) is not the whole space $X$. If $X$ is finite dimensional it is impossible for the operator $T_\lambda$ to be injective but not surjective, so this is not the case. If $X$ is infinite dimensional there two possibilities for the subspace $\mathrm{Im}(T_\lambda)$ not to be the whole $X$. Here we have two cases:
2.1) $\overline{\mathrm{Im}(T_\lambda)}=X$, speaking informally $T_\lambda$ is "almost surjective". In this case we say that $\lambda$ is in continuous spectrum.
2.2) $\overline{\mathrm{Im}(T_\lambda)}\neq X$, speaking informally $T_\lambda$ is "essentially non-surjective", even the closure of its image is a proper subspace of $X$! In this case we say that $\lambda$ is in the residual spectrum.
There are other classifications of points of the spectrum, but this one is the most common.
Comment: Yes, this is nice, but I don't quite understand how this answers the question which is "*why* do we distinguish cases 2.1) and 2.2)?"
Comment: Well... this explanation shows that the two cases *are* different, so it is natural that they are distinguished!
Comment: That is a good reason, but I do not think it is enough. Maybe the following claim is helpful: T is invertible iff T is bounded below and dense range.
Comment: Theo, thanks for your edit. I see that my English is so poor... As for your question, I think we distinguish this cases because the measure "non-surjectiveness" of our operator. May this a bad explanation, this is just how I understand that.
Comment: Oh, my English is also poor. In fact, I want to know why do we emphasize the "almost surjective" from the "nonsurjective".
Comment: @Strongart, I think that another reason of such emphasizing is given in AlbertH's answer
Comment: It is not true that $T$ is invertibel iff it is bounded from below and have a dense range. The reason that for invertability we need bijectivity.
Comment: That is from the book "Banach Algebra Techniques in Operator Theory" by Ronald G. Douglas P76.proposition 4.8. Maybe it is because the difference about the definitions.
Comment: @Strongart I don't have this book, but if you want answer with definition of invertability from this book please write it here
Comment: I read the prove again and because of the below bounded condition, we can get the range is closed first,so Ran(T) is the whole space. But I also see some book treat the invertability as one-to-one, a Chinese popular functional analysis book by Gongqing Zhang is an example.
Comment: @Norbert: Yes it is true. Boundedness from below, i.e. existence of $C>0$ with $\|Tx\|\geq C\|x\|$ for all x, is equivalent to injectivity+closed image. So if you add 'dense image' then you get 'bijective', in both directions.
Comment: @wildildildlife, closedness of image follows from boundedness below if space $X$ is Banach. Otherwise, you can consider $$T:(C^1([0,1]),\Vert\cdot\Vert_\infty)\to (C([0,1]),\Vert\cdot\Vert_\infty):x\mapsto x$$
Comment: Obviously X is assumed to be Banach, otherwise we can't even apply the open mapping theorem and this whole discussion would be ridiculous.
Comment: Yes, Banach space is the stage. If X is not Banach space, we have another way to break the inverse of λI-T,(λI-T)^(-1) is exist but unbounded, I do not know what is the name for such spectrum.
Comment: In Kreyszig's functional analysis, the continuous spectrum is defined as $\sigma_c(T) = \{\lambda \in \mathbb C: R_\lambda(T) $ exists, $R_\lambda(T)$ is defined on a set which is dense in $X$, but $R_\lambda(T)$ is not bounded $\}$. Is this definition the same as yours? i.e. if it is "almost surjective" but not injective, does it imply that $R_\lambda(T)$ not bounded?
Answer: As pointed out by M. Reed, B. Simon in the section VI.3 of their "Methods of Modern Mathematical Physics: Functional Analysis":

The reason that we single out the residual spectrum is that it does not occur for a large class of operators, for example, for self-adjoint operators.
Comment: Yes, it is also true for the norm operator.


Cascading Select with jCombo

Question: i want create a triple nested select but first of all i try a simple select.
But the select remain blank.
Can you gime me some hint?
this is my page:

<select name="list1" id="list1"></select>

where my getBuilding.php is:
<?php
require_once 'dbconnection.php';
$db_server = mysql_connect($db_hostname, $db_username, $db_password);
if (!db_server) die("Unable to connection_aborted to MySQL: " . mysql_error());
mysql_select_db($db_database) or die ("Unable to connection_aborted to MySQL: " . mysql_error());

    // Esegui query nel giusto ordine
    //(value,text)
    $query = "SELECT * FROM Building";
    $result = mysql_query($query);
    $items = array();
   if($result && mysql_num_rows($result)>0) {
        while($row = mysql_fetch_array($result)) {
            $option = array("id" => $row[0], "value" => htmlentities($row[1]));
            $items[] = $option;
        }
    }
    mysql_close();
    $data = json_encode($items);
    // convertire in formato JSON e stampare
    $response = isset($_GET['callback'])?$_GET['callback']."(".$data.")":$data;
    echo($response);
?>

this page works. i obtain the data formatted correctly.
[{"id":"1","value":"Building1"},{"id":"2","value":"Building2"},{"id":"4","value":"Building3"},{"id":"5","value":"Building4"}]
but it not appear in the select.
Thanks
Answer: The problem was that firefox is not compatible with jcombo.. it works with explorer of chrome!

Cascading Select with jCombo


Use strings.xml values inside .Java Activities

Question: So I'm going to make my application Multilingual and making different String.xml's for different languages.
I'm also changing my texts, such as
String message = "Calling " + name;
                Context context = getApplicationContext();
                int duration = Toast.LENGTH_SHORT;

                Toast toast = Toast.makeText(context, message, duration);
                toast.show();

to
String message = toastCalling + name;

(From strings.xml)
<string name="toastCalling">Calling</string>

I'm facing a problem, that it apparently is an INT, and either cannot be resolved, or changes the value of toastCalling (Calling) to "278172" (Random Numbers)
Is there a way to get the ACTUAL value of R.String.toastCalling (Calling)
I have tried:
String whatever = getResources().getString(R.string.toastCalling);

But I don't think that's practical.
Thanks in advance!
Comment: You may not think it's practical, but that's how you're supposed to do it.
Comment: you can usually just call getString(R.string.blabla); but yeah that's the way you're supposed to do it and it's not that inconvenient ;)
Comment: Because `getResources()` is going to automatically point to the correct resource bundle for the current Locale.
Comment: @TomG But, Let's say the Phone's language is Spanish. It will be checking for string-es.xml. How is "getResources().getString(R.string.toastCalling);" going to get the SPANISH Xml?
Comment: @TomG Ah, if getResources() can get that automatically, there won't be a single problem. I was just having my doubts since there will be a language change as well. Thank you for your answers/comments!
Answer: If you're within the activity's scope, you can and are supposed to call getString(R.string.toastCalling); to receive the string. If you're not in the activity's scope, you need getResources, as in your example. This is how it is supposed to be done.
By the way, your three lines for the toast can be shortened into one: Toast.makeText(ctx, msg, Toast.LENGTH_LONG).show();
Comment: Yes, Thank you. I have the shortened code as well. But I keep it a bit  longer, "Easier" for the other people that work on this project as well. :).  I will be using getString();. Thank you! (Can accept in 11 minutes)