Variables for Local Economic Environment

Question: I'm working on a regression to explain store sales (cross section data over a number of stores in one time frame only).  Some of my variables are 'min distance to competitor x'.  However, the results keep showing that the closer a store is to competitor x, the higher  sales are.  This is clearly a wrong sign, likely due to competitor x putting their stores in areas with a better economic profile.  However, every time I try to include a variable to capture local economic effects, nothing seems to fix the wrong sign (have to go at zip code level; I've tried local average tax returns, local business payroll, etc).  Any thoughts on what I could due to fix the wrong sign I'm getting here?
Thanks.
Answer: It sounds like you have an endogenity problem. In this case, the most likely culprit is that the placement of the nearest competitor is endogenous (non-random), due to, as you explained above, the tendency for competitors to put their business in communities that are better off. You will need to use the instrumental variable approach as your estimation strategy to control for the endogeneity. To do this, you need to find an instrument or exclusion restriction--variable(s) related to $Minimum Distance$ that is not related to $Sales$, except through $Minimum Distance$--in your dataset. Consult the literature for instruments that have been used in your field. Your theoretical framework is also a good source of ideas for potential instruments.
Once you find a suitable instrument, you can jointly model $Sales$ and $Minimum Distance$ using instrumental variable regression, assuming your outcome is continuous, as follows:
At first stage:
$MinDist_i = Instruments_i + X + \nu_i$
At second stage:
$Sales_i  = \hat{MinDist}_i + X + \epsilon_i$
If using Stata, you can use the built-in ivregress command or the user-written ivreg2 command. If using other packages, search the web for which command or package to use to run an instrumental variable regression--most statistical packages will have some IV routine either built-in or written by its users.
See Antonakis et al. (2010) for a primer on causality using non-experimental data (link in references section).  He also has a great video on endogenity on YouTube (Link: http://youtu.be/dLuTjoYmfXs).  Another good resource for IV is Khandker et al.'s (2009) Handbook on Impact Evaluation published by the World Bank (Ch. 6). For a more detailed treatment of the subject, see Wooldridge (2003).
References

Antonakis, J., Bendahan, S., Jacquart, P., & Lalive, R. (2010). On
making causal claims: A review and recommendations. The Leadership
Quarterly, 21(6), 1086–1120.
http://doi.org/10.1016/j.leaqua.2010.10.010.  A PDF is accessible
here if you do not have institutional access to the journal.
Khandker, S., B. Koolwal, G., & Samad, H. (2009). Handbook on
Impact Evaluation. Washington, DC: The World Bank.
http://openknowledge.worldbank.org/bitstream/handle/10986/2693/520990PUB0EPI1101Official0Use0Only1.pdf?sequence=1
Wooldridge, J. M. (2003). Introductory Econometrics: A Modern
Approach (Vol. 2nd). Thomson South-Western.


assistance needed for error when embedding youtube video

Question: All I'm trying to do is embed one youtube video onto my web page using the iframe tag :

Whenever I hit play I get an error message saying please try again later, and I'm given a playback id. I've tried searching for answers since this is a common issue but haven't had any luck. What should I change?
Answer: Try

Youtube's iframe embed is not compatible with the format of URL you used.
Answer: As I see you have a malformed embed url in the code. YouTube embed codes don't contain the watch? option. Try changing the code from
https://www.youtube.com/embed/watch?v=GieJ52nBkGg to https://www.youtube.com/embed/GieJ52nBkGg
This should fix your issue


Torsion-Free Module over Dedeking Ring

Question: Let $\phi: R \to A$ be a finite morphism of Dedekind rings (so $A$ is a finitely generated $R$-module) and $M$ a finitely generated $A$-module. Obviously, if we restrict the action of $A$ on $M$ to $R$ via $(r,m) \mapsto \phi(r) \cdot m$ we obtain an $R$-module $M_R$.
My question is:

If the restriction $M_R$ is a torsion-free $R$-module how to show that $M$ is a torsion-free $A$-module?

My ideas:
By classification theorem for finitely generated modules over Dedekind rings $M= A^r \oplus T_A$ with torsion $T_A$ and $M_R = R^s \oplus T_R$. since $M_R$ torsionfree $M_R= R^s$.
Why does this already imply that $M$ torsionfree as $A$-module (therefore $T_A=0$)?
Background: this question arises from following problem: Consider a finite and locally free morphism $f:C→\mathbb{P^1}$ where $C$ a curve. Furthermore let $F$ be a quasicoherent sheaf of finite type on $C$. The aim is to show that if the pushforward $f_*F$ is locally free then $F$ is already locally free.
Answer: Let me keep the discussion with a general ring homomorphism $\varphi: R \rightarrow A$ between Dedekind rings (which corresponds to the originally asked question).
1) The implication "$M_R$ torsion-free $\Rightarrow M$ torsion-free":
The implication holds if and only if maximal ideals of $A$ contract to maximal ideals of $R$. A module $M$ has torsion iff $M$ has an associated maximal ideal $\mathfrak{P}$ of $A$, but then $M_R$ has an associated prime $\mathfrak{p}=\varphi^{-1}(\mathfrak{P})$, showing that $M_R$ has torsion in this case as well. On the other hand, if there is a maximal ideal $\mathfrak{P} \subseteq A$ such that $\mathfrak{P} \cap R=0,$ then $M=A/\mathfrak{P}$ is a module that becomes torsion-free over $R$, but it is a torsion $A$-module.
For example, when $R \rightarrow A$ is $\mathbb{Z} \rightarrow \mathbb{C}[X]$ and $\mathfrak{P}=(X)$, we see that $\mathbb{C}=\mathbb{C}[X]/(X)$ is torsion-free $\mathbb{Z}$-module which is a torsion $\mathbb{C}[X]$-module.
2) The implication "$M_R$ torsion-free $\Leftarrow M$ torsion-free":
The implication holds if and only if the map $\varphi: R \rightarrow A$ is injective. If it is, and $M$ is a torsion-free $A$-module, then it is torsion-free as $R$-module since for any $m \in M$, $\mathrm{Ann}_R(m)=\varphi^{-1}(\mathrm{Ann}_A(m))=\varphi^{-1}(0)=0$. On the other hand, by the same reasoning any $A$-module $M$ is always annihilated by $\mathrm{Ker}\,\varphi$ as an $R$-module, so if $\varphi$ is not injective, every $A$-module $M$ will have torsion as an $R$-module.
(A concrete example is, similarly, $\mathbb{Z}\rightarrow \mathbb{F}_p[X]$. Then all $\mathbb{F}_p[X]$-modules are obviously $p$-torsion Abelian groups.)
3} Regarding the assumption that $\varphi$ is finite:
The condition that $R \rightarrow A$ is finite (or, more generally, integral) is sufficient for both the implications 1} and 2) to hold. Such morphism is necessarily injective (note that any non-trivial quotient $R/I$ is $0$ dimensional, so $R/I \subseteq A$ finite implies $A$ is $0$-dimensional), showing that 2) holds. Also the fact that maximal ideals contract to maximal ideals follows by the going-up property of integral (e.g. finite) extensions, showing that 1) holds as well.
Comment: Yes indeed I was a bit unprecise. Assume that $\phi$ makes $A$ be a finitely generated $R$-module. $\phi$ inherits all properties which are induced from the fact that $f$ is a finite morphism. So especially it is integral. I updated my question.
Comment: One remark: What is the obstruction for the "only if" direction? If we assume that $M$ has a torsion element $t$ and $I_t$ is it's torsion ideal then $\phi^{-1}(I)$ annulates also $t$ in $M_R$. Or do you need the properties " injective and integral" only for the other direction?
Comment: @KarlPeter: I edited the answer to reflect the assumption of finiteness of $\varphi$ (I left the original discussion regardless). This should hopefully cover all the possible implications. Part 3) cover the assumption of finiteness (or integrality).

Torsion-Free Module over Dedeking Ring


What kind of delivery is Nathan Lyon's "Jeff"?

Question: In the recent Test series against South Africa, the Australian right arm off-spinner Nathan Lyon occasionally employed a delivery that spun the other way (away from a right hand batsmen instead of towards). I understand he has named this delivery "Jeff" for unknown reasons. There has been some sparse media coverage of this, see for instance here, but I have not managed to find any suitable footage to work out how he is doing it, such as a super slo-mo zoomed in view of the bowling hand or any articles explaining the details.
There are several ways off spinners can get a ball to go the other way. The most famous is the 'doosra' employed most notably by Muttiah Muralitharan, which requires extremely flexible elbows and wrists and long fingers in order to rotate the hand around to impart spin in the desired direction. No non south asian player has ever been able to deliver this ball legally due to the different physiology of Anglo/European players, so I doubt that this is it exactly but a modified version something along these lines might be possible.
The other option is to use the fingers to flick the ball the other way, almost like a regular leg break but using the middle finger to impart spin instead of the whole hand and wrist. Ajantha Mendis uses this and calls it a 'caroom' ball, while Ravichandran Ashwin calls it his 'sudoku' ball. I believe that Jason Krejza has also experimented with this (and probably a number of other spinners as well).
So, does anyone know if "Jeff" falls into either of these categories or is it something else? It has also been described as a 'backspinner', which makes it more likely to be the caroom ball style delivery, or some variant of that.
I'm really looking for a definitive answer here, if one can be obtained, rather than speculation or an explanation of different possibilities, which is why I've outlined at least some of them myself here in the question.
Comment: http://www.smh.com.au/sport/cricket/nathan-lyon-says-he-is-working-on-australian-carrom-with-murali-20140620-zsgim.html It doesn't explain exactly how Lyon bowls his Jeff, but this article does explain that he uses neither Muralitharan's doosra or Mendis' caroom ball method, but something else.
Answer: There's no mystery - it's a doosra, he admits so himself here -
http://www.theaustralian.com.au/sport/opinion/nathan-lyon-lifts-the-covers-on-jeff-the-bastard-son/story-e6frg7uf-1226521541045
The doosra is the off spinners version of the googly explained here -
http://news.bbc.co.uk/sport1/hi/cricket/skills/4174244.stm
The doosra and googly are both essentially the same thing, they're balls that spin in the opposite direction to the way you're expecting them to spin.
How he's achieving it is irrelevant - there are many different ways of getting the ball to spin in the opposite direction mostly by using a combination of wrist flick and finger spin, with some backwards and sideways movement, each bowler has his own way of achieving this. There is no one single way of bowling doosras or googlys.
The real secret to effective doosra's and googly's is to keep (as far as possible) the same arm action and wrist movement as the bowlers stock or standard ball for the simple reason that the bowler does not want to give thr batsman any indication that the ball the bowler will bowl will be any different to his stock or standard ball. This is the reason you will not find any specific details as to what the bowler is doing to achieve the doosra or googly ball.
The doosra and googly don't generally spin as much (in terms of revolutions) as the bowlers stock ball due predominantly to the difficulty in achieving the change in spin direction but usually the very fact the ball does something quite different to what the batsman expects is enough to put doubts in his mind as to either how to deal with it or what he's going to get next.
It's a fallacy that balls that spin the most get the most wickets, they don't. Spin bowlers wickets are achieved by deception and quite frequently it's the ball that doesn't spin at all that gets the wicket.
Note: The Australian link may not work as it's a pay site.
Comment: Your question title asks: 'What kind of delivery is Nathan Lyon's 'Jeff'?. I've answered it - it's a 'doosra'. If you don't like the answer (which you clearly don't) perhaps you might like to consider rephrasing your question?
Comment: @Bogdanovist Then you've asked an unanswerable question and the question should be closed. No bowler is going to tell you the exact method he uses for making the ball spin in the opposite direction for the simple reason that he doesn't want batsmen to be able to 'pick' that ball. If they know how he does it they can 'pick' it. The 'Jeff' ball is a 'doosra' how he achieves it will not be explained to you in the detail you're looking for.
Comment: I appreciate the effort, but I think if you re-read the question (particularly the last paragraph!) you'll see that this is not what it was asking. The Australian article doesn't make it clear whether 'doosra' is being used in the generic sense of 'one going the other way' or specific to one technique for making it go the other way, of which there are several. You may thinks it is irrelevant how a particular bowler achieves this, but that's what the question was asking.
Comment: The question doesn't ask for Nathon Lyon to respond in person, so I'm not sure how that is unanswerable? You could ask "How does Murali bowl the Doosra?" or "How does Mendis bowl the Caroom ball?" and both are very much answerable and the answer are quite different. There are numerous good example of video clips comparing the stock ball of a bowler to the variations side by side on e.g. YouTube (there are also plenty of bad attempts at doing so, but none the less...). Plenty of technical articles have also discussed the different techniques each player uses.
Comment: Nathan Lyon has only been bowling this variation publicly for a short period (without a huge amount of success) so the same level of information is not available yet, however there is a reasonable chance that some footage showing the details of Lyon's delivery has been made and may reside somewhere (e.g. YouTube). I cannot find any but it is perfectly conceivable that it exists. You answer is a very reasonable comment, but it doesn't answer what is a reasonable and answerable question.
Answer: I reckon he just rolls his first finger the other way, hence he gets a lot of drift into a RH batsman and it's easy to pick. The dismissal of Jacques Rudolph in the second innings at Brisbane wasn't the variation I've discovered despite what many others have said, he simply bowled an arm ball which slid on. He may be using the caroom ball method though, it's hard to tell.
Comment: When you say "I've discovered", how exactly did you discover this? Do you have access to relevant footage that sheds some light on this? I still can't find anything useful on youtube etc that would help answer this question. If you could provide a link to some hard evidence, that would be great, even if as you say it is hard to tell exactly what he is doing.


What to fix on my code with two IF conditions inside a FOR loop referencing an environment variable defined by the IF conditions?

Question: Could you please guide me how to fix my script to get the trace route results to some IP addresses?
I want to get the tracert results for 220.127.116.11 and 220.127.116.11. I wrote the script below and it works fine:
@echo off
echo %date% %time%

SET DNS1=184.108.40.206
SET DNS2=22.214.171.124

for  %%i in (%DNS1% %DNS2%) do (
    echo ----------------
    echo tracert to %%i
    tracert -d %%i
)

echo %time%
exit

I want to add a function so that it can print host name automatically. I tried as below, but it doesn't work.
@echo off
echo %date% %time%

SET DNS1=18.104.22.168
SET DNS2=184.108.40.206

for  %%i in (%DNS1% %DNS2%) do (
    echo ----------------
    if (%%i == 18.104.22.168 set host=Google1
        %%i == 220.127.116.11 set host=Google2)
    echo tracert to %host%
    tracert -d %%i
)

echo %time%
exit

Could somebody please correct the code for me?
Comment: Two problems. The first being you need two if commands to set each variable. No parentheses are needed for that. The second is you will now fall into the infamous delayed expansion trap because you are creating environmental variables inside a parenthesised code block of the FOR command. This requires that you use a setlocal command to enable delayed expansion and you then reference those variables with exclamation point instead of percent symbols.
Comment: Dear Squashman. Thank you so much for your guidance. So I am the newbie, could you please help to guide me by writing the codes with the simplest algorithm so that the newbie likes me can understand easily? I am not the native English speaker so it's hard for me if just read your guidance.
Answer: The proper use to test multiple conditions using an IF command is used in this code. As a best practice I always use quotes around string comparisons. Also note the use of delayed expansion with the host variable. This is required because you are creating a variable inside a parenthesized code block.
@echo off
setlocal enabledelayedexpansion

echo %date% %time%

SET DNS1=126.96.36.199
SET DNS2=18.104.22.168

for  %%i in (%DNS1% %DNS2%) do (
    echo ----------------
    if "%%i"=="188.8.131.52" set host=Google1
    if "%%i"=="184.108.40.206" set host=Google2
    echo tracert to !host!
    tracert -d %%i
)

echo %time%
endlocal
exit

Comment: To be honest. You taught me the first lesson in windows cmd programming. All I have is a too basic coding knowledge!! Thank you so much, Squashman. Have a nice day!
Answer: The batch file could be written like this:
@echo off
echo %DATE% %TIME%

setlocal EnableExtensions EnableDelayedExpansion
set "DNS1=184.108.40.206"
set "DNS2=126.96.36.199"

for %%i in (%DNS1% %DNS2%) do (
    echo ----------------
    if %%i == 188.8.131.52 set "host=Google1"
    if %%i == 184.108.40.206 set "host=Google2"
    echo tracert to !host!
    tracert -d %%i
)

endlocal
echo %TIME%
exit /B

Windows command processor executes one command line after the other. How a command line is parsed before execution is described at How does the Windows Command Interpreter (CMD.EXE) parse scripts? What is executed finally after parsing a command line can be seen on executing a batch file without @echo off from within a command prompt window as described at debugging a batch file.
A command block starting with ( and ending with matching ) is parsed completely by cmd.exe before the command is executed with makes conditionally or unconditionally use of the command block. During parsing the command block all environment variable references using syntax %variable% like %host% are substituted by current value of the referenced environment variable. In this case %host% is most likely replaced by an empty string before FOR is executed at all if the environment variable host is not defined by chance on starting the batch file.
The help output on running set /? in a command prompt window explains when and how to use delayed expansion on an IF and a FOR example. In code above delayed environment variable expansion is enabled and used to reference the current value of environment variable host on iterations of the loop body command block on which the environment variable is defined and gets assigned a string value.
There would be also possible to use:
@echo off
echo %DATE% %TIME%

setlocal EnableExtensions DisableDelayedExpansion
set "DNS1=22.214.171.124"
set "DNS2=126.96.36.199"

for %%i in (%DNS1% %DNS2%) do (
    echo ----------------
    if %%i == 126.96.36.199 set "host=Google1"
    if %%i == 188.8.131.52 set "host=Google2"
    call echo tracert to %%host%%
    tracert -d %%i
)

endlocal
echo %TIME%
exit /B

The command line call echo tracert to %%host%% is modified during the parsing step of entire command block by Windows command processor to call echo tracert to %host% and because of command CALL this command line is parsed a second time on each execution of the command block before ECHO command is executed resulting in printing the current value of environment variable host to console window.
But I suggest to use this much better code:
@echo off
echo %DATE% %TIME%
echo/

setlocal EnableExtensions DisableDelayedExpansion
set "DNS1=18.104.22.168=Google1"
set "DNS2=126.96.36.199=Google2"

for /F "tokens=2* delims==" %%I in ('set DNS 2^>nul') do (
    echo ----------------
    echo tracert to %%J
    echo %SystemRoot%\System32\tracert.exe -d %%I
)

endlocal
echo/
echo %TIME%
exit /B

One or more IP addresses and their host names are assigned to one or more environment variables starting with the string DNS. IP address and host name are separated by an equal sign.
The command FOR runs in a separate command process started with cmd.exe /C in background the command line:
set DNS 2>nul

Command SET outputs to handle STDOUT (standard output) all environment variables starting with DNS sorted alphabetically with name=value which means for this example:
DNS1=18.104.22.168=Google1
DNS2=220.127.116.11=Google2

The error message output by SET to handle STDERR (standard error) on not finding any environment variable starting with the string DNS would be suppressed by this code by redirecting it to device NUL.
Read also the Microsoft article about Using Command Redirection Operators for an explanation of 2>nul. The redirection operator > must be escaped with caret character ^ on FOR command line to be interpreted as literal character when Windows command interpreter processes this command line before executing command FOR which executes the embedded set command line with using a separate command process started in background.
FOR with using option /F captures everything output to handle STDOUT in background command process and processes this output by ignoring empty lines and lines starting with a semicolon.
The captured lines start all with DNS and so there is definitely no line ignored as no line starts with a ;.
FOR with using option /F would also split each line into substrings using space/tab as delimiter with assigning just first substring to specified loop variable I. But this line splitting behavior is not useful for this task.
For that reason the option string "tokens=2* delims==" redefines the line splitting behavior. Now = is used as delimiter between the strings instead of space and tab.
And instead of assigning the first = delimited string to loop variable I which would be the name of the environment variable, the second equal sign delimited string is assigned to loop variable I because of tokens=2 which is the IP address.
And there is additionally assigned to next loop variable J according to ASCII table the rest of the line after the equal sign(s) after second = delimited string without any further string splitting on an equal sign. So the host name is assigned to loop variable J, even on containing one or more = as long as not containing them at beginning of host name.
This code is obviously better as the DNS environment variables can be defined all at top of the batch file with IP address and host name and nothing must be changed on the command lines below because it simply processes from 0 to n environment variables starting with DNS and having at least a second = delimited substring.
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

call /?
echo /?
endlocal /?
exit /?
for /?
if /?
set /?
setlocal /?
tracert /?


Oracle 11g r2: strange behavior on index

Question: I have the query:
    SELECT count(*)
FROM
(
SELECT
 TBELENCO.DATA_PROC, TBELENCO.POD, TBELENCO.DESCRIZIONE, TBELENCO.ERROR, TBELENCO.STATO,
 TBELENCO.SEZIONE, TBELENCO.NOME_FILE, TBELENCO.ID_CARICAMENTO, TBELENCO.ESITO_OPERAZIONE,
 TBELENCO.DES_TIPO_MISURA,
 --TBELENCO.RAGIONE_SOCIALE,
 --ROW_NUMBER() OVER (ORDER BY TBELENCO.DATA_PROC DESC) R
 ROWNUM R
FROM(
 SELECT
  LOG.DATA_PROC, LOG.POD, LOG.DESCRIZIONE, LOG.ERROR, LOG.STATO,
  LOG.SEZIONE, LOG.NOME_FILE, LOG.ID_CARICAMENTO, LOG.ESITO_OPERAZIONE, TM.DES_TIPO_MISURA
  --,C.RAGIONE_SOCIALE
  --ROW_NUMBER() OVER (ORDER BY LOG.DATA_PROC DESC) R
 FROM
  MS042_LOADING_LOGS LOG JOIN MS116_MEASURE_TYPES TM ON
   TM.ID_TIPO_MISURA=LOG.SEZIONE
--  LEFT JOIN(
--   SELECT CUST.RAGIONE_SOCIALE,STR.POD,RSC.DATA_DA, RSC.DATA_A
--   FROM
--    MS038_METERS STR JOIN MS036_REL_SITES_CUSTOMERS RSC ON
--     STR.ID_SITO=RSC.ID_SITO
--    JOIN MS030_CUSTOMERS CUST ON
--     CUST.ID_CLIENTE=RSC.ID_CLIENTE
--  ) C ON
--  C.POD=LOG.POD
  --AND LOG.DATA_PROC BETWEEN C.DATA_DA AND C.DATA_A
  WHERE
   1=1
   --AND LOG.DATA_PROC>=TRUNC(SYSDATE)
   AND LOG.DATA_PROC>=TRUNC(SYSDATE)-3
   --TO_DATE('01/11/2014', 'DD/MM/YYYY')
) TBELENCO
)
WHERE
 R BETWEEN 1 AND 200;

If I execute the query with AND LOG.DATA_PROC>=TRUNC(SYSDATE)-3, Oracle uses the index on the data_proc field of the MS042_LOADING_LOGS (LOG) table, if I use, instead, AND LOG.DATA_PROC>=TRUNC(SYSDATE)-4 or -5, or -6, etc, it uses a table access full. Why this behavior?
I also execute a :
ALTER INDEX MS042_DATA_PROC_IDX REBUILD;

but with no changes.
Thank,
Igor
--***********************************************************
SELECT count(*)
FROM
(
SELECT
 TBELENCO.DATA_PROC, TBELENCO.POD, TBELENCO.DESCRIZIONE, TBELENCO.ERROR, TBELENCO.STATO,
 TBELENCO.SEZIONE, TBELENCO.NOME_FILE, TBELENCO.ID_CARICAMENTO, TBELENCO.ESITO_OPERAZIONE,
 TBELENCO.DES_TIPO_MISURA,
 ROWNUM R
FROM(
 SELECT
  LOG.DATA_PROC, LOG.POD, LOG.DESCRIZIONE, LOG.ERROR, LOG.STATO,
  LOG.SEZIONE, LOG.NOME_FILE, LOG.ID_CARICAMENTO, LOG.ESITO_OPERAZIONE, TM.DES_TIPO_MISURA
 FROM
  MS042_LOADING_LOGS LOG JOIN MS116_MEASURE_TYPES TM ON
   TM.ID_TIPO_MISURA=LOG.SEZIONE
  WHERE
   1=1
   AND LOG.DATA_PROC>=TRUNC(SYSDATE)-1
) TBELENCO
)
WHERE
 R BETWEEN 1 AND 200;

Plan hash value: 2191058229

-------------------------------------------------------------------------------------------------------
| Id  | Operation                       | Name                | Rows  | Bytes | Cost (%CPU)| Time     |
-------------------------------------------------------------------------------------------------------
|   0 | SELECT STATEMENT                |                     |     1 |    13 | 30866   (2)| 00:06:11 |
|   1 |  SORT AGGREGATE                 |                     |     1 |    13 |            |          |
|*  2 |   VIEW                          |                     | 94236 |  1196K| 30866   (2)| 00:06:11 |
|   3 |    COUNT                        |                     |       |       |            |          |
|*  4 |     HASH JOIN                   |                     | 94236 |  1104K| 30866   (2)| 00:06:11 |
|   5 |      INDEX FULL SCAN            | P087_TIPI_MISURE_PK |    15 |    30 |     1   (0)| 00:00:01 |
|   6 |      TABLE ACCESS BY INDEX ROWID| MS042_LOADING_LOGS  | 94236 |   920K| 30864   (2)| 00:06:11 |
|*  7 |       INDEX RANGE SCAN          | MS042_DATA_PROC_IDX | 94236 |       | 25742   (2)| 00:05:09 |
-------------------------------------------------------------------------------------------------------

Predicate Information (identified by operation id):
---------------------------------------------------

   2 - filter("R"<=200 AND "R">=1)
   4 - access("TM"."ID_TIPO_MISURA"="LOG"."SEZIONE")
   7 - access(SYS_OP_DESCEND("DATA_PROC")<=SYS_OP_DESCEND(TRUNC(SYSDATE@!)-1))
       filter(SYS_OP_UNDESCEND(SYS_OP_DESCEND("DATA_PROC"))>=TRUNC(SYSDATE@!)-1)

Plan hash value: 69930686

---------------------------------------------------------------------------------------------
| Id  | Operation             | Name                | Rows  | Bytes | Cost (%CPU)| Time     |
---------------------------------------------------------------------------------------------
|   0 | SELECT STATEMENT      |                     |     1 |    13 | 95921   (1)| 00:19:12 |
|   1 |  SORT AGGREGATE       |                     |     1 |    13 |            |          |
|*  2 |   VIEW                |                     |  1467K|    18M| 95921   (1)| 00:19:12 |
|   3 |    COUNT              |                     |       |       |            |          |
|*  4 |     HASH JOIN         |                     |  1467K|    16M| 95921   (1)| 00:19:12 |
|   5 |      INDEX FULL SCAN  | P087_TIPI_MISURE_PK |    15 |    30 |     1   (0)| 00:00:01 |
|*  6 |      TABLE ACCESS FULL| MS042_LOADING_LOGS  |  1467K|    13M| 95912   (1)| 00:19:11 |
---------------------------------------------------------------------------------------------

Predicate Information (identified by operation id):
---------------------------------------------------

   2 - filter("R"<=200 AND "R">=1)
   4 - access("TM"."ID_TIPO_MISURA"="LOG"."SEZIONE")
   6 - filter("LOG"."DATA_PROC">=TRUNC(SYSDATE@!)-4)

Comment: remove commented code from your example. Also give us relevant execution and plan and indexes.
Comment: Hi Atilla Ozgur,thanks for reply; in my main post I added the informations required.
Answer: The larger the fraction of rows that will be returned, the more efficient a table scan is and the less efficient it is to use an index.  Apparently, Oracle expects that inflection point to come when the query returns more than 3 days of data.  If that is inaccurate, I would expect that the statistics on your table or indexes are inaccurate.


How to stop htmlpy ui blocking

Question: I was working on a small downloader for Youtube videos using trollius (for async), htmlpy and pafy (and youtube-dl). Now i have a problem where once i click the download button, the UI freezes up while the backend is downloading the video.
I have tried to make the downloader class its own thread and run that alongside the UI but that doesn't seem to work. I also tried to uses coroutine to have the video download asynchronously while the UI continues. Neither seemed to work.
Here is some code
class Downloader(htmlPy.Object,threading.Thread):
dd = os.path.join(os.getenv('USERPROFILE'), 'Downloads')  # dd = download director
dd = dd + "/vindownload/"

def __init__(self, app):
    threading.Thread.__init__(self)
    super(Downloader, self).__init__()
    # Initialize the class here, if required.
    self.app = app
    return

@htmlPy.Slot(str)
def download_single(self, json_data):
    form_data = json.loads(json_data)
    print json_data
    url = form_data["name"]
    dt = form_data["dt"]  # Download type is audio or video
    if url.__contains__("https://www.youtube.com/watch?v="):
        if dt == 'audio':
            print "hello1"
            loop = trollius.get_event_loop()
            loop.run_until_complete(self._downloadVid(url, vid=False))
            loop.stop()
        else:
            print "hello1"
            loop = trollius.get_event_loop()
            loop.run_until_complete(self._downloadVid(url, vid=True))
            loop.stop()
        self.app.evaluate_javascript("document.getElementById('form').reset()")
    else:
        print "Incorrect url"
    print form_data

 @trollius.coroutine
def _downloadVid(self, url, vid=False, order_reverse=False, vinName=None):
    print "hello123"
    video = pafy.new(url)
    print video
    name = u''.join(video.title).encode('utf8')
    name = re.sub("[<>:\"/\\|?*]", "", name)
    if not vid:
        file = video.getbestaudio()
    else:
        file = video.getbest()
    if (order_reverse):
        file.download(self.dd + vinName + name + ".mp4", quiet=False,callback=self.mycb)
    else:
        file.download(self.dd + name + ".mp4", quiet=False,callback=self.mycb)

def mycb(self,total, recvd, ratio, rate, eta):
    print(recvd, ratio, eta)

and my initialize.py
BASE_DIR = os.path.abspath(os.path.dirname("initilize.py"))

app = htmlPy.AppGUI(title=u"Vin download", width=700, height=400, resizable=False)

app.static_path = os.path.join(BASE_DIR, "static/")
app.template_path = os.path.join(BASE_DIR, "templates/")

app.web_app.setMaximumWidth(830)
app.web_app.setMaximumHeight(600)

download  = Downloader(app)
download.start()

# Register back-end functionalities
app.bind(download)
app.template = ("./index.html", {"template_variable_name": "value"})

# Instructions for running application
if __name__ == "__main__":
    # The driver file will have to be imported everywhere in back-end.
    # So, always keep app.start() in if __name__ == "__main__" conditional
    app.start()

Now my question is. Is there a way where i can free up my UI while downloading so it doesn't look like the application crashed.
I am using: Python 2.7, Trollius, Pafy, Youtube-dl, HTMLPY.
Thank you for your time.
Answer: Alright i found the answer to my question, here is what i did. i changed my download_single method to the following:
@htmlPy.Slot(str)
def download_single(self, json_data):
    form_data = json.loads(json_data)
    print json_data
    url = form_data["name"]
    dt = form_data["dt"]  # Download type is audio or video
    videoDown = videoDownload(url, dt, self.app, self.dd)
    videoDown.start()
    print form_data

And the code i had in it earlier is now transferred to a new class called videoDownload taking all those attributes stated above.
videoDownload.py
class videoDownload(threading.Thread):
def __init__(self, url, dt, app, dd):
    threading.Thread.__init__(self)
    self.url = url
    self.dt = dt
    self.app = app
    self.dd = dd

def run(self):
    threads.append(self)
    if self.url.__contains__("https://www.youtube.com/watch?v="):
        if self.dt == 'audio':
            print "hello1"
            self._downloadVid(self.url, vid=False)
        else:
            print "hello1"
            self._downloadVid(self.url, vid=True)
    else:
        print "Incorrect url"

def _downloadVid(self, url, vid=False, order_reverse=False, vinName=None):
    print "hello123"
    video = pafy.new(url)
    print video
    name = u''.join(video.title).encode('utf8')
    name = re.sub("[<>:\"/\\|?*]", "", name)
    if not vid:
        file = video.getbestaudio()
    else:
        file = video.getbest()
    if (order_reverse):
        file.download(self.dd + vinName + name + ".mp4", quiet=False, callback=self.mycb)
    else:
        file.download(self.dd + name + ".mp4", quiet=False, callback=self.mycb)
    threads.remove(self)

def mycb(self, total, recvd, ratio, rate, eta):
    pass

This solved the issues i had with ui being blocked. The thread will end itself once leaving the run method and it will be removed from a threads array that is defined above the class.
Have a great day all
~Ellisan

How to stop htmlpy ui blocking


Is $ (1+ |x|^2)\operatorname{Id} - x \otimes x $ positive definite?

Question: How can I prove the matrix $$ (1+ |x|^2)\operatorname{Id} - x \otimes x $$ where $x$ is a vector in $\mathbb{R}^n$, is positive-definite?
Comment: I assume that $x \otimes x$ is your notation for the matrix $xx^T$
Answer: Hint: Verify that
$$
y^T\left[(1+ |x|^2)\operatorname{id} - x \otimes x\right]y =
(1+ |x|^2)|y|^2 - (x^Ty)^2
$$
If $y$ is non-zero, then this quantity must be positive.
Answer: For any $v \ne 0$ we have
$$\left\langle (1+\|x\|^2)v - \langle v,x\rangle x, v\right\rangle = (1+\|x\|^2)\|v\|^2 - |\langle v,x\rangle|^2 = \underbrace{\|v\|^2}_{>0}+\underbrace{\|x\|^2\|v\|^2 - |\langle v,x\rangle|^2}_{\ge 0 \text{ by Cauchy-Schwarz}} > 0$$


Can I mount an ext3 filesystem on linux so files on the mount are owned by a userid?

Question: I'd like to mount an ext3 filesystem via /etc/fstab so that the files in the mount are owned by a particular user. Is this possible ?
I've looked at man mount but couldn't find an option to do this. ( Similar to setting uid and gid for a vfat mount ).
Is there any option besides doing running chown on the whole mounted filesystem ?
Answer: No, this isn't possible to do in fstab or mount with ext3 because the ownership info is stored within the file system, as opposed to being a property of the file system. Run chown -R.
Answer: As mentioned in an answer to this question, bindfs can be used to create a remapped mounting of a directory or filesystem with modified userid.  This seems to work acceptably for me.  I just did sudo bindfs -u myusername fs-mountpoint new-mountpoint and it happened.  I'm not sure how well this will work in fstab, though, since bindfs is a FUSE filesystem.
Answer: There's a patch around for mounting ext2/3 with a fixed uid for all files, I couldn't figure out if it has made it into the kernel yet, but if it has it's in 2.6.31+ .
The option is anyway uid=userid, as in e.g. mount -o uid=500 /dev/sda1 /mnt/mydisk
It'll certainly be handy if you have removable drives formatted as ext3, moving it back& forth between machines where your have a different user id.
Comment: Thanks, I'll have a look. I wanted this for the same reason you mentioned.
Comment: This still doesn't seem to work—I get a vague error message that lists, among other possible causes, bad mount option; the `uid=` option is not documented for ext* file systems.


Arithmetic with Integer numbers

Question: I reckon this is a kid question, but I was solving a simple problem today and I got stucked in a basic topic: Arithimetic using integer numbers:
My question is: Can someone explain in a logical example or in a logical way why subtracting a negative number gives us a positive one?
For example:
    3 - (-2) = 5 OR
    1/2 - (-1/3) = 5/6
Thanks in advance
Comment: As my old school teacher loved to say: If you love to love, that's good. If you love to hate, that's bad. If you hate to love, that's bad, and if you hate to hate, that's good. In the same way, adding a positive number increases something, adding a negative number decreases something, subtracting a positive number decreases something, and subtracting a negative number increases something.
Comment: You will need to clarify what you mean by "*in a logical way*."  To a trained mathematician, we will tell you to remember that the subtraction $a-b$ is *defined* as $a$ plus the additive inverse of $b$, that is to say $a-b = a+(-b)$.  We then remember that the additive inverse of $-2$ is equal to $2$ since $(-2)+(-(-2))=0=(-2)+2$.  As a result, we have $3-(-2)=3+(-(-2))=3+2=5$
Comment: To me, that is a perfectly logical explanation, but you may be looking for a more *intuitive* explanation instead, to which you might prefer thinking of adding and subtracting as "moving to the right or to the left" by various amounts respectively.  If we move to the left of $3$ by an amount of negative two, that is the same as moving to the right of three by an amount of two.
Comment: Draw the number line and mark on -3 and 2. What meaning would you give to $2-(-3)$?
Comment: It doesn't. $-3-(-1) =-2$
Comment: Thanks guys for all the support! I really appreciate
Answer: This is more of a didactic question, thus a didactic answer.
Money
Intuitive way of thinking about numbers can be the concept of money.

Positive value means you have that amount of money.
Negative value means you owe that amount of money.

Adding positive number means I give you money. Subtracting positive number means you give me money. Adding negative number means paid a debt, subtracting negative number means a debt has been forgiven.
Distance
Another concepts used for explaining negative numbers can be made on a road.

Addition of positive means going forward.
Addition of negative means going backwards.
Subtraction of positive means turning around and going forward.
Subtraction of negative means turning around and going backwards.

Arithmetic with Integer numbers


How to efficiently build a list of dicts without duplicates?

Question: In the code below, the 3rd and 4th elements are considered the same, because 'start' and 'end' are just switched:
{'start': '222',  'end': '333', 'type':'c'},
{'start': '333',  'end': '222', 'type':'c'}

I need to build a relations list or set which don't contain duplicates like above. Supposed the input is from list_of_dicts, and my code is the following to achieve the purpose:
relations = []
list_of_dicts = [{'start': '123',  'end': '456', 'type':'a'},
                  {'start': '111',  'end': '122', 'type':'b'},
                  {'start': '222',  'end': '333', 'type':'c'},
                  {'start': '333',  'end': '222', 'type':'c'},
                  ]

duplicate_keys = set()
for my_dict in list_of_dicts:
    duplicate_key = ''.join(sorted(my_dict['start'] + my_dict['end'] + my_dict['type']))
    if duplicate_key not in duplicate_keys:
        relations.append(my_dict)
        duplicate_keys.add(duplicate_key)

print(relations)

This seems to work. My list_of_dicts are supposed to be large, for example, 100 millions. Is this the fast way to do it? Also, the list_of_dicts here are illustrative purpose for convenience, but the 'relations' list are built from similar input.
Comment: @CharlesDuffy He wants to treat `start: 1, end: 2` as equivalent to `start: 2, end: 1`. It has nothing to do with dictionary ordering.
Comment: If you want to be able to add them to sets, or use them as dict keys, see [`frozendict`](https://pypi.org/project/frozendict/).
Comment: No need to sort.  Just loop through and add both permutations as dict keys.
Comment: @user2263572, ...eh? No. They're _the same_. The ordering is not part of the dict itself. `{'a': 1, 'b': 2} == {'b': 2, 'a': 1}` is True. There's no reason whatsoever to add them as two separate items; and adding permutations is going to greatly increase memory usage.
Comment: _Ahhh_. In that case we can just sort the values and ignore the keys (for which ordering is independent). Make both `start: 1, end:2` and `start: 2, end: 1` evaluate to `lower: 1, higher: 2` and you're done.
Comment: @CharlesDuffy But only start and end are considered, not type.
Comment: @Barmar, ...right, hence the "for which ordering is independent" caveat.
Comment: Also, the list_of_dicts don't exist. Each dict in 'list_of_dicts' are produced in a loop and add to the relations list/
Answer: I think that is better to transform those dict into a specialize class, add to that class a hash function and let a set or a dict or similar take care of duplicates
>>> class MyObject:
        def __init__(self,start,end,type):
            self.data = (*sorted((start,end)),type)
        def __hash__(self):
            return hash(self.data)
        def __repr__(self):
            return f"{self.__class__.__name__}{self.data}"
        def __eq__(self,other):
            if isinstance(other,self.__class__):
                return self.data == other.data
            return False

>>> list_of_dicts = [{'start': '123',  'end': '456', 'type':'a'},
                  {'start': '111',  'end': '122', 'type':'b'},
                  {'start': '222',  'end': '333', 'type':'c'},
                  {'start': '333',  'end': '222', 'type':'c'},
                  ]
>>> new=[MyObject(**x) for x in list_of_dicts]
>>> new
[MyObject('123', '456', 'a'), MyObject('111', '122', 'b'), MyObject('222', '333', 'c'), MyObject('222', '333', 'c')]
>>> set(new)
{MyObject('123', '456', 'a'), MyObject('222', '333', 'c'), MyObject('111', '122', 'b')}
>>>

Answer: Try to use dict and tuples for keys:
list_of_dicts = [{'start': '123',  'end': '456', 'type':'a'},
                  {'start': '111',  'end': '122', 'type':'b'},
                  {'start': '222',  'end': '333', 'type':'c'},
                  {'start': '333',  'end': '222', 'type':'c'},
                  ]

for my_dict in list_of_dicts:
    k = tuple(sorted(my_dict.values()))

    if k not in relations:
        relations[k] = my_dict

print(list(relations.values()))

And one-liner with a little-bit different behavior:
list_of_dicts = [{'start': '123',  'end': '456', 'type':'a'},
                  {'start': '111',  'end': '122', 'type':'b'},
                  {'start': '222',  'end': '333', 'type':'c'},
                  {'start': '333',  'end': '222', 'type':'c'},
                  ]

relations = list({tuple(sorted(my_dict.values())): my_dict for my_dict in list_of_dicts}.values())

print(relations)

In this one-liner, latest value will be used in the dict.
This is equivalent to the full version, but without condition if k not in relations:.
Result:
[{'start': '123', 'end': '456', 'type': 'a'}, {'start': '111', 'end': '122', 'type': 'b'}, {'start': '333', 'end': '222', 'type': 'c'}]

Comment: What are d1 and d2? There's just a list of dictionaries.
Comment: How does this treat the dictionaries with `start: x, end: y` as equivalent to `start: y, end: x` and remove the duplicates?
Comment: d1, d2, ..., d_n - are your dicts.
Comment: Can you show how this works with a list of dicts? I still don't see how it swaps `start` and `end` when comparing.
Comment: It remove duplicates, like `start: x` and make one dictionary without duplicated key/value pairs.
Comment: Can you test your code and show the results?
Comment: I think you don't really understand the question.
Comment: Look, if you have two dicts (for the list it's similar), you'll have: `{'type': 'c', 'end': '333', 'start': '222'}`
Comment: The result is supposed to be a new list of dictionaries. You're just creating one dictionary.
Comment: Ah, yes, sorry, I didn't understand, what do you need as a result.
Comment: I don't need anything, I didn't write the question.
Comment: The result is supposed to be a list of dictionaries created from the original list, but without pairs of dictionaries that have the same start/end values in either order.
Comment: Corrected. Thank you for the comments, Barmar.
Answer: To generate a sorting key that's order-independent only for specific, named keys (as initially defined by the sortable_keys default parameter):
def order_independent_key(input_dict, sortable_keys=('start', 'end')):
    local_dict = dict(input_dict)
    sortable_vals = []
    for key in sortable_keys:
        sortable_vals.append(local_dict.pop(key))
    return tuple(sortable_vals) + tuple(sorted(local_dict.items()))

Thus:
list_of_dicts = [{'start': '123',  'end': '456', 'type':'a'},
                  {'start': '111',  'end': '122', 'type':'b'},
                  {'start': '222',  'end': '333', 'type':'c'},
                  {'start': '333',  'end': '222', 'type':'c'},
                  ]
deduplicated_dicts = {}
for item in list_of_dicts:
    deduplicated_dicts[order_independent_key(item)] = item

...will generate a structure like:
{('111', '122', ('type', 'b')): {'end': '122', 'start': '111', 'type': 'b'},
 ('123', '456', ('type', 'a')): {'end': '456', 'start': '123', 'type': 'a'},
 ('222', '333', ('type', 'c')): {'end': '333', 'start': '222', 'type': 'c'},
 ('333', '222', ('type', 'c')): {'end': '222', 'start': '333', 'type': 'c'}}

...for which doing a lookup by order_independent_key(another_dict) is an operation with performance characteristics that scale only with the number of keys in another_dict.
Answer: Something like this would be quite efficient for looping through a list of dicts and determining which are dupes (add anything to a set that is considered "seen").  Would require looping through each dict once, but constant time lookup to see if a key exists.
seen = set()

for my_dict in list_of_dicts:
    if (my_dict['start'], my_dict['end']) in seen:
        # dupe
        continue
    # not dupe
    seen.add((my_dict['start'], my_dict['end']))
    seen.add((my_dict['end'], my_dict['start']))

Comment: Yes, define 'seen' as a set should be fine.
Comment: Is this going to create a huge seen set? double of the original list_of_dicts?
Comment: @Barmar the dict seemed a little more explicit, but agree a set is more Pythonic.  My understanding is that performance should be similar with either.
Comment: Yes. A set is essentially the same as a dict with hidden values.
Comment: @marlon depends how many dupes there are...couldn't tell ya
Comment: If I define 'seen' as an instance variable, then self.seen.add(...) would be problematic in a multiprocessing program? I have 10 processes to use this function.
Comment: @marlon there are better resources available than anything I'd write in a comment.  https://stackoverflow.com/questions/6832554/multiprocessing-how-do-i-share-a-dict-among-multiple-processes


Can't change size within layout

Question: Well, I have a text editor with a button above it... I want the text editor to be inside a layout so that it increases and decreases its size the the QDialog, but I don't want to do that same with the button, which, by the way, doesn't have the size that I want and can't change it. What can I do?
Code:
from PyQt4 import QtCore, QtGui
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
class TextEditorDlg(QDialog):
    def __init__(self, parent=None):
        QtGui.QDialog.__init__(self, parent)
        self.resize(500, 400)
        self.Grid = QtGui.QGridLayout(self)
        self.button = QtGui.QPushButton(self)
        self.Grid.addWidget(self.button, 0, 0)
        self.lineEdit = QtGui.QLineEdit(self)
        self.textEdit = QtGui.QTextEdit(self)
        self.Grid.addWidget(self.lineEdit, 1, 0)
        self.Grid.addWidget(self.textEdit, 2, 0)
if __name__ == '__main__':
    app = QApplication(sys.argv)
    myapp = TextEditorDlg()
    myapp.show()
    sys.exit(app.exec_())

See the problem now?
Comment: Can you try to be more clear? My *guess* is that you can put the button in a `QHBoxLayout` with some spacers to avoid resizing(see the [`addStretch`](http://doc.qt.digia.com/qt/qboxlayout.html#addStretch) method).
Answer: First of all I do not understand why you are using a QGridLayout. Do you realize that you are not using the grid at all? You should simply use a QVBoxLayout.
Anyway, as I mentioned in a comment, you can probably obtain your desired "output" using a QHBoxLayout and the addStretch methods:
import sys
from PyQt4 import QtCore, QtGui

class TextEditorDlg(QtGui.QDialog):
    def __init__(self, parent=None):
        super(TextEditorDlg, self).__init__(parent)
        self.resize(500, 400)

        self.button = QtGui.QPushButton(self)
        self.lineEdit = QtGui.QLineEdit(self)
        self.textEdit = QtGui.QTextEdit(self)

        self.button_layout = QtGui.QHBoxLayout()
        self.button_layout.addStretch()
        self.button_layout.addWidget(self.button)
        self.button_layout.addStretch()

        self.grid = QtGui.QGridLayout(self)

        self.grid.addLayout(self.button_layout, 0, 0)
        self.grid.addWidget(self.lineEdit, 1, 0)
        self.grid.addWidget(self.textEdit, 2, 0)

        # Alternative using QVBoxLayout:
        #self.layout = QtGui.QVBoxLayout(self)
        #self.layout.addLayout(self.button_layout)
        #self.layout.addWidget(self.line_edit)
        #self.layout.addWidget(self.text_edit)

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    myapp = TextEditorDlg()
    myapp.show()
    sys.exit(app.exec_())

You can tune the stretch amount passing an integer to addStretch.
If you wanted to use a QGridLayout to place the button in a specific position, then you should have done something like this:
import sys
from PyQt4 import QtCore, QtGui

class TextEditorDlg(QtGui.QDialog):
    def __init__(self, parent=None):
        super(TextEditorDlg, self).__init__(parent)
        self.resize(500, 400)

        self.button = QtGui.QPushButton(self)
        self.lineEdit = QtGui.QLineEdit(self)
        self.textEdit = QtGui.QTextEdit(self)

        self.grid = QtGui.QGridLayout(self)

        # Use the row-span and column-span arguments!
        self.grid.addWidget(self.button, 0, 0, 1, 1)
        self.grid.addWidget(self.lineEdit, 1, 0, 1, 3)
        self.grid.addWidget(self.textEdit, 2, 0, 1, 3)

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    myapp = TextEditorDlg()
    myapp.show()
    sys.exit(app.exec_())

You can place the button exactly where you want using the correct row and column indexes and row-span and column-span values.

Edit: If you want to change the size of the QPushButton you must change the QSizePolicy of the button and the policy of the QTextEdit. For example:
import sys
from PyQt4 import QtCore, QtGui

class TextEditorDlg(QtGui.QDialog):
    def __init__(self, parent=None):
        super(TextEditorDlg, self).__init__(parent)
        self.resize(500, 400)

        self.button = QtGui.QPushButton(self)
        self.button.setSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Expanding)
        self.lineEdit = QtGui.QLineEdit(self)
        self.textEdit = QtGui.QTextEdit(self)
        self.textEdit.setSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Minimum)

        self.grid = QtGui.QGridLayout(self)

        # Use the row-span and column-span arguments!
        self.grid.addWidget(self.button, 0, 0, 3, 1)
        self.grid.addWidget(self.lineEdit, 3, 0, 1, 3)
        self.grid.addWidget(self.textEdit, 4, 0, 1, 3)

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    myapp = TextEditorDlg()
    myapp.show()
    sys.exit(app.exec_())

You'll see that the button is bigger. You can control how big by changing the row-span.
In the line self.grid.addWidget(self.button, 0, 0, 3, 1) increasing/decreasing the 3 will increase/decrease the vertical size(actually the number of rows occupied by the widget) and increasing/decreasing the 1 will change the horizontal size.
Note that if you place the widget at row 0 spanning for 3 rows then you have to be carefully to not create collisions adding new widgets to the layout.
Comment: Thanks a lot, but how to do I increase the height of the button in the second example?
Comment: You'll have to play with the row-span of the button **and** the `QTextEdit`. Anyway, as I already stated more than once, using a `QVBoxLayout` would be a lot easier in your situation.

Can't change size within layout


What is the intended way of using computed signals alongside ngrx selectors and where to put the logic?

Question: I am using Angular 16 and just started with signals. Those make working with ngrx even better. When transitioning I found myself presented with something that can be abstracted to this:
const state = {
 someArray: [1, 5, 7]
}

export const selectArray = createSelector(
  state,
  (state) => state.someArray
);

export const selectFirst = createSelector(
  selectArray,
  (someArray) => someArray[0]
);

export const selectLast = createSelector(
  selectArray,
  (someArray) => someArray[state.someArray.length-1]
);

export const selectLastMinusFirst = createSelector(
  [selectFirst, selectLast],
  (first, last) =>
    last - first
);

Now with signals this could be rewritten using computed signals in the component that wants to use it to something like this:
const someArray: Signal<number[]> = this.store.selectSignal(Selectors.SelectArray)
const first: Signal<number> = computed(() => someArray()[0]);
const last: Signal<number> = computed(() => someArray()[state.someArray.length-1]);
const lastMinusFirst: Signal<number> = computed(() => last() - first());

Or even using signals effects:
const first = 0;
const last = 0;
const lastMinusFirst = 0;

const someArray: Signal<number[]> = this.store.selectSignal(Selectors.SelectArray)

constructor() {
  effect(() => {
    if(someArray().length) {
      this.first = someArray()[0];
      this.last = someArray()[someArray().length - 1];
      this.lastMinusFirst = this.last - this.first;
    }
  });
}

What is the intended way of doing it? Are computed signals more efficient as they mention lazy evaluation and memoized?
Comment: more efficient - what does that mean ?  memory, number of characters in code, speed, storage ?  Change your question to "How do I use it" and dont put qualifiers such as better, or efficient,
Comment: What i meant to ask with that part of the question was: are computed signals more performant through the implementation of lazy evaluation nad memoization on their side in comparison to doing the computing part in the ngrx selector? Which in return would be an argument for choosing it over the other one.
Answer: computed() is better than a selector, because

Its dependencies are dynamic [1];
Resulted signal can be used in the template directly and will take care of the change detection without |async or dirty checking;
Dependencies are recursive - if inside computed() you call some function, that also uses signals, then the resulting signal will be updated when a signal in that function is updated. And this can happen somewhere deep in the stack, as long as it happens synchronously [2]. It allows to create very flexible and powerful things - derived signals, composed of derived signals.

Meanwhile, NgRx is working on integration with Angular Signals:

RFC: Integration with Angular Signals and NgRx packages
RFC: NgRx SignalStore

[1], [2] - You can read more about this topic in my free article: Dependency Graph in Angular Signals


Utilizando o stateparams não está retornando o json para exibir no detalhe

Question: Galera, estou com o seguinte problema:
tenho um arquivo json, e estou fazendo a chamada dele assim:
<code>$http.get("../templates/teste.json").success(function (response) {

    $scope.x = response;

});
</code>
Na minha rota, está assim:
<code>.state('app.detalhe', {
    url: '/produtos/:ProdutoId',
    views: {
        'menuContent': {
            templateUrl: 'templates/detalhe.html',
            controller: 'ProdutosCtrl'
        }
    }
})
</code>
No meu controller, está assim:
<code>$scope.produtoSingle = function () {

     x[$stateParams.produtoId]; }

}
</code>
A url está mandando correto:

E ele simplesmente nao me retorna nada do detalhe, alguem saberia me dizer oque está acontecendo?
Comment: essa chave depois do array `x[ ... ];` está sobrando... além disso o "x" é `this.x`
Comment: Corrigindo:
    x[$stateParams.produtoId];

}
Comment: produtoId no lugar de frutaId? Você pode editar seu post, vou corrigir pra ti. Como está o seu arquivo JSON?
Comment: isso, produtoId no lugar de frutaId. Meu json está assim:
Comment: [
  {
    "title":"Título",
    "subtitle":"Lorem ipsum",
  },
  {
    "title":"Título 2",
    "subtitle":"Lorem ipsum 2",
  },
  {
    "title":"Título 3",
    "subtitle":"Lorem ipsum 3",
  }
]
Comment: você definiu o `$stateParams` no `controller`? o seu `$stateParams.produtoId` está com syntax diferente do parametro no router, que é `ProdutoId`. Qualquer coisa se não resolver, atualize com seu controller completo (ou pelo menos a inicialização) para verificar.
Answer: Veja minha resposta em: https://pt.stackoverflow.com/a/100066/8386
Tente:
<code>$http.get("../templates/teste.json").success(function (response) {

    $scope.x = response;
    if (!$scope.$$phase) $scope.$apply();
});
</code>


struggling with template_preprocess in module

Question: I know there is a lot of documentation on this function on google, but I am still not able to get this hook to run for my holidayautosxml_carsearch_form. Could anyone advise on what I am doing wrong.
The Theme function is running fine. If I put exit(); in that function I get white screen of death. However if I put exit(); in the template_preprocess function nothing happens.
I have cleared all the caches.
my template is called holidayautosxml-carsearch.tpl.php and it is located in the module folder.
Here is my theme function
function holidayautosxml_theme(){
return array(
            'holidayautosxml_carsearch' => array(
                    'template'=>'holidayautosxml-carsearch',
                    'render element'=>'form',
            ),

    'halocationresults' => array(
        'template' => 'halocationresults',
        'variables' => array('haresults' => NULL,),
    ),
    'hapriceslist' => array(
        'template' => 'hapriceslist',
        'variables' => array('haprices' => NULL,),
    ),
);
}

Here is my template_preprocess function
function template_preprocess_holidayautosxml_carsearch(&$variables){

$variables['holidayautosxml_carsearch'] = array();
$hidden = array();
//Provide variabels named after the form keys so themers can print each element independently.
foreach (element_children($variables['form']) as $key){
    $type = $variables['form'][$key]['#type'];
    if ($type == 'hidden' || $type == 'token'){
        $hidden[] = drupal_render($variables['form'][$key]);
    }
    else{
        $variables['holidayautosxml_carsearch'][$key] = drupal_render($variables['form'][$key]);
    }
}
//Hidden form elements have no value to Themers. no need for seperation.
$variables['holidayautosxml_carsearch']['hidden'] = implode($hidden);
//collect all form elementsto make it easier to print the whole form
$variables['holidayautosxml_carsearch'] = implode($variables['holidayautosxml_carsearch']);
}

and here is my form function
function holidayautosxml_carsearch_form($node, &$form_state){

    $country_list = _get_country_list();
    $form['country'] = array(
            '#type'=>'select',
            '#title'=>'Select Country',
            //'#description'=>'Select the country where you want to collect the car',
            '#options'=>$country_list,
            '#ajax' => array(
                'callback' => 'update_officename_autocomplete',
                'wrapper' => 'haofficename',
            ),
    );

    $citylist = _get_city_list($form_state['values']['country']);

$form['officename'] = array(
    '#type'=>'select',
    '#title'=> t('Location'),
    //'#description' => t('Select the location where you want to pick up the car'),
    '#required' => TRUE,
            '#options' => $citylist,
            '#width' => 50,
            //'#autocomplete_path'=>'location-autocomplete',
            '#prefix' => '
',
            '#suffix' => '
',
);

    if (!empty($form_state['values']['country'])){
        $form['officename']['#autocomplete_path'] = 'location-autocomplete/' . "{$form_state['values']['country']}";
    }
    $dateformat = 'd-m-Y H:i';
    $form['datefrom'] = array(
        '#required'=>TRUE,
        '#type'=>'date_popup',
        '#date_format'=>$dateformat,
        '#title'=>t("Pickup date"),
        //'#description'=>t("The date you are picking up the car"),

        );

    $form['dateto'] = array(
        '#required'=>TRUE,
        '#type'=>'date_popup',
        '#date_format'=>$dateformat,
        '#title'=>t("Dropoff date"),
        //'#description'=>t("The date you are bringing the car back"),
    );

$form['submit'] = array(
'#type'=>'submit',
'#value'=>'Search Now',
'#submit'=>array('holidayautosxml_carsearch_form_submit'),
);

return $form;
}

Answer: I think it should be  holidayautosxml_preprocess_holidayautosxml_carsearch(&$variables).
Basically the syntax is [yourModuleName|yourThemeName]_preprocess_[themeFunctionName](&$variables).
Also you need to flush your cache after you make the change.
Comment: Hi Junedkazi, I tried what you said but that does not work. I think you only have to specify the module name first if you are refering to theme declared in another module. But this Theme is declared by the same module. Also this is a template_preprocess function, your suggestion does not mention template in the function name so I am not sure how Drupal would call that function when preprocessing templates. Thanks any way Simon
Comment: If you are doing it at the module level then it is modulename_preprocess_[themeFunctionName](&$variables) and if you doing it at the theme level then themename_preprocess_[themeFunctionName](&$variables).
Answer: OK, I found the solution. The code I posted above only seems to work when I add, $form['#theme'] = 'holidayautosxml_carsearch';
to the form specification.
Hope this helps someone.
Simon


Mostrar JSON no HTML

Question: Queria perguntar se tem como remover alguns caracteres na hora de apresentar informações de um script, essas informações serão apresentadas no Browser.
Quero remover ( "", {}, - ).
Comment: De uma olhada nessa [pergunta](https://pt.stackoverflow.com/questions/280734/como-converter-html-em-json)
Comment: Amigo poste o código e não a imagem! As vezes a tag `` pode te ajudar... https://developer.mozilla.org/pt-BR/docs/Web/HTML/Element/pre
Answer: o ideal é você converter esse json para objeto php.
utilizando a função do json_decode
Você gera um objeto e exibe dai só os dados que quer na tela. =D
<code><?php

$json = '{"foo-bar": 12345}';

$obj = json_decode($json);
print $obj->{'foo-bar'}; // 12345

?>
</code>
Comment: É uma forma de se fazer, mas não consideraria a ideal, é muito mais simples e rápido fazer direto no javascript
Comment: podia ter enviado um código de exemplo como não postou nada acredito que deixou aberto.

Mostrar JSON no HTML


C++: Reading a character is incorrect

Question: Getting a weird problem trying to read chars from a text file in C++.  When it finds an apostrophe (hex 92) it reads it as multiple characters.  For the string "it's" I get this:
<code>i - 69
t - 74
' - ffffff92
s - 73
it's
</code>
Here's the code:
<code>{
    FILE* fp = fopen("word.txt", "rb");
    char buf[111];

    fscanf(fp, "%s", buf);

    for (int i = 0; i < strlen(buf);   ++i)
        printf("%c - %x\n", buf[i], buf[i]);

    printf(buf);
}
</code>
Opening as "r" gives the same result.  How can I read the apostrophe as the single char that it is?  Thanks!
Comment: If `char` is signed (likely), it will get sign extended when promoted to an `int` in a variadic function. Printing a signed value as unsigned could result in unexpected output.
Comment: Note that 0x92 is not a canonical apostrophe. That would be 0x27 (Unicode U+0027 APOSTROPHE) instead. 0x92 is outside of the ASCII range, so it is subject to charset interpretation. 0x92 is Unicode U+2019 RIGHT SINGLE QUOTATION MARK in Windows-1252, for instance, but is different/undefined in other charsets. When dealing with 8bit text data, charsets matter.
Comment: This looks more like C. Is this C?
Comment: It's C++, but it would also compile in C.  I get the same result using a stream.
Comment: Thanks Bo Persson; using an unsigned char array seems to have solved the problem.
Answer: Cast buf[i] to unsigned char - character is read correctly - but when printing - since it is negative - it is extended to int and then cased to unsigned int so you see ffffff92 - casting to unsigned should display the value correctly
<code>#include<cstdio>

int main() {

    char ch = static_cast<char>(0x92);
    printf("%c - %x/%x\n", ch,ch,static_cast<unsigned char>(ch));

    return 0;
}
</code>
Output
<code>$ ./test
� - ffffff92/92
</code>
Comment: @UserX  What is your compiler - since I got the predicted output with gcc 5.4

C++: Reading a character is incorrect


If $A^2 + A +I = 0$, then A is diagonalizable. True or false?

Question: Let $A$ be a real square matrix. We assume $A^2 + A +I = 0$. Then A is diagonalizable.
Is this statement true or false? Prove it.
I don't know which could be the first step to prove that. Could you give me any hint?
Thanks in advance.
Comment: Do you mean diagonalizable over the real numbers or over the complex numbers?
Answer: By definition, the minimal polynomial of $A$ divides $x^2+x+1$. But this last polynomial is irreducible over $\Bbb R$. So $m_A(x) = x^2+x+1$ and $A$ is not diagonalizable, as $m_A(x)$ is not the product of distinct linear factors.
Answer: $A$ cannot be diagonalizable. If $P^{-1}AP=D$, where $D$ is diagonal matrix, one easily derives that $D^2+D+I=0$, so for every element $\lambda$ on the diagonal we would have $\lambda^2+\lambda+1=0$. However, this equation has no real solutions.
Answer: Hint:
Consider $A=\pmatrix{-\dfrac12&-\dfrac{\sqrt3}2\\\dfrac{\sqrt3}{2}&-\dfrac12},$ which rotates $120^\circ$.
Answer: Yes, A is diagonalizable with non-real eigenvalues.
For example, consider $$A=\begin{bmatrix} -2 & -3 \\ 1 & 1 \end{bmatrix}$$that satisfies $A^2+A+I=0$,
it is diagonalizable. It being non-symmetric (non-Hermitian) has non-real eigenvalues as $w, w^2$ where $w$ is one cube root of unity.


Easy proof for existence of Lebesgue-premeasure

Question: In the lecture on measure theory I attended last semester, we had a sort of complicated technical proof for the existence of the Lebesgue-premeasure. However, I can't see why this easier argument does not work:
Let $\lambda((a, b]) = b - a$ finitely additive on the ring $R = \{ \mathrm{finite \, disjoint \, unions \, of \,} (a, b] \}$. Having a disjoint union of elements $A_n \in R$ that lies again in $R$, so $\bigsqcup_{n \geq 1} A_n \in R$ we may assume w.l.o.g. that $\bigsqcup_{n \geq 1} A_n = (a, b]$. Now one can easily see that $$\sum_{n \geq 1} \lambda(A_n) \leq \lambda((a, b])$$
hence the infinite sum is absolutely convergent and may be reordered. Reorder it such that $A_i = (x_i, x_{i + 1}]$ with $x_i < x_{i + 1}$ for all $i$. We then get a telescopic sum $$\sum_{i \geq 1} \lambda((x_i, x_{i + 1}]) = \sum_{i \geq 1} (x_{i + 1} - x_{i}) = \lim_{i \rightarrow \infty} x_i - x_1 = b - a$$
Hence we have equality.
The question now is: Does this proof work? Or is there something missing?
Comment: @JHW He's right about the first thing being easy. The point is that if $c_n\ge 0$ and you want to show that $\sum_{n=1}^\infty c_n\le a$ it's enough to show that $\sum_{n=1}^N c_n\le a$. But he's not going to be able to explain how to do the reordering, because it can't be done.
Comment: "*Now one can easily see that* $\sum_{n \geq 1} \lambda(A_n) \leq \lambda((a, b])$"

I don't see it easily. Would you elaborate on it?

"*Reorder it such that* $A_i = (x_i, x_{i + 1}]$ with $x_i < x_{i + 1}$ for all $i$".

Would you explain why this reordering is possible?
Comment: Okay, I guess David is right about the reordering. Now, about the first thing: $\lambda ((a, b]) = \lambda \left( \bigcup_{i = 1}^n A_n \right) - \lambda \left( (a, b] - \bigcup_{i = 1}^n A_n \right) \geq \lambda \left( \bigcup_{i = 1}^n A_n \right) = \sum_{i = 1}^n \lambda(A_n)$ and take the limit.
Comment: @DavidC.Ullrich About the first one, I knew that. The point is how you prove that the finite sum is smaller than or equal to $b - a$.
Comment: @JHW _Finitely many_ intervals _can_ be ordered the way he says. So we have $a\le a_1<b_1\le a_2<b_2\dots <b_n\le b$. Now $b-a$ is equal to the sum of the $b_j-a_j$ plus some other terms,,,
Comment: @DavidC.Ullrich *Finitely many intervals can be ordered the way he says.*
How do you prove this?
Comment: @JHW You're serious? These are disjoint intervals. So given two of them, $I$ and $J$, wlog $x<y$ for all $x\in I$ and $y\in J$. Say $I<J$ when that happens. We have a _finite_ totally ordered set. Show by induction that any totally ordered set with $n$ elements is order-isomorphic to $\{1,2,\dots, n\}$.
Comment: @DavidC.Ullrich *So given two of them, $I$ and $J$, wlog $x \lt y$ for all $x\in I$ and $y\in J$*.
How do you prove this?
I'm serious.
I know you can prove this. My point is that the OP's claim that the proof is easy is misleading.
Comment: @JHW If I'd known you were asking questions you knew the answer to, just so you could use my replies to illustrate your points regarding the OP's claims, I would have dropped this long ago. If you want to talk about math some time stop by...
Answer: I'm going to talk about $[a,b)$ instead of $(a,b]$. The reason being that that's the sort of half-open interval I tend to work with; hence really a lot of things in the first version of this post were simply wrong. The easiest way to fix it is just to change $(a,b]$ to $[a,b)$ everywhere...
You can't necessarily reorder that way! I don't mean you're not allowed to or things don't work if you do, I mean you literally cannot; in general there is no such reordering. The way those intervals fit together can be much more complicated than that.
Simple example: Say $I_n=[1-1/n,1-1/(n+1))$, so $[0,1)=\bigcup_{n=1}^\infty I_n$. Those intervals can be ordered the way you want, in fact they already are ordered that way.
But now say $J_n=[2-1/n,2-1/(n+1))$. So $[0,2)=\bigcup_{n=1}^
\infty I_n \cup\bigcup_{n=1}^\infty J_n$. You can't "reorder" the collection of all the $I_n$ and the $J_n$ the way you want.
That's enough to show your proof doesn't work. But it can be much worse. Say $I_n$ is as above. Now for each $n$ you can find countably many disjoint half-open intervals $I_{n,m}$ so $I_n=\bigcup_{m=1}^\infty I_{n,m}$. Now we have $$[0,1)=\bigcup_{n=1}^\infty\bigcup_{m=1}^\infty I_{n,m},$$and that collection of intervals is much worse than what you had in mind when you said "reorder"...
It really is trickier than you think. Folland points out that the way the intervals are arranged from left to right can be isomorphic to any countable ordinal, if you know what that means. His point is that it can be complicated. One can also say "oh, so it's no worse than a countable ordinal" and then give a cute proof by transfinite induction. But never mind that for now.
Comment: I THINK that even using countable ordinals, a proof based only in transfinite induction will not work.  At some point the topology of $\mathbb{R}$ must play a key role. Otherwise, the proof based only in transfinite induction would also show that $\lambda((a,b]\cap \mathbb{Q})=b-a$  defined on $\{(a,b] \cap \mathbb{Q} \,|\, a,b \in\mathbb{Q}\}$  is a premeasure (countably additive).  And we know that such $\lambda$ is not a premesure.
Comment: I can't imagine why you think I said otherwise.  I mean this is like I say one can prove some inequality by induction and you say no, we also need the fact that $(a+b)^2=a^2+2ab+b^2$.
Comment: You wrote: "Folland points out that the way the intervals are arranged from left to right can be isomorphic to any countable ordinal" and " One can also say 'oh, so it's no worse than a countable ordinal' and then give a cute proof by transfinite induction".

It sounded like you were saying that using a countable ordinal to represent the order the intervals one might produce a "cute" proof just using transfinite induction.
Comment: I have just pointed out that an idea like ordering the intervals, even using countable ordinals, and then adding their measures, even if it is done through transfite induction, would not be enough to prove the result.  At some point the topology of $\mathbb{R}$  must play a key role in the proof.
Comment: And my point is that well yes of course, your point is _obvious_. _My_ point was that the proof I have in mind _does_ make the proof much simpler and more straightforward.
Comment: Could you explain what was the proof (using countable ordinals and transfinite induction) you had in mind?  How it would be "much simpler and more straightforward" than the classical proof using compacity of $[a,b]$ in $\mathbb{R}$?
Comment: @Ramiro Ok, see http://math.stackexchange.com/questions/1408533/lebesgue-premeasure-vis-transfinite-induction
Comment: @Ramiro Actually wasn't sure until I wrote it out, but the place where the topology of $\Bbb R$ comes in is in the proof that the collection of intervals is well-ordered.
Comment: David, Thanks a lot.  I am not sure we can say it is "much simpler and more straightforward" than the classical proof using compacity of $[a,b]$, BUT, it is surely a VERY NICE and INTERESTING proof.  And yes, you are right, the place where the topology of $\mathbb{R}$  comes in the proof is that the collection of intervals is well-ordered by the order induced by the order $<$ in $\mathbb{R}$.  And when we look in the details in the proof, we see that this fact is, in some way,  a "compacity"-like argument, which is per si an interesting fact.  Very nice proof. Thanks.


Obter valor do XML

Question: Estou com dificuldades em obter o valor true deste XML:
<boolean xmlns="http://schemas.microsoft.com/2003/10/Serialization/">true</boolean>

tentei desta forma mas não o consegui:
var ns = xDoc.Root.GetDefaultNamespace();

            string strin = xDoc.Descendants(ns + "boolean").ToString();

Answer: Experimente isto:
var nodeName = XNamespace.Get("http://schemas.microsoft.com/2003/10/Serialization/") + "boolean";
string value = xDoc.Descendants(nodeName).First().Value;

O que isto faz:
Primeiro criamos um nome do nó, com o namespace e o nome indicado. O GetDefaultNamespace só funciona se o nó root tiver um xmlns de http://schemas.microsoft.com/2003/10/Serialization/. Quando o boolean for o root, então o GetDefaultNamespace funciona:
var nodeName = xDoc.Root.GetDefaultNamespace() + "boolean";
string value = xDoc.Descendants(nodeName).First().Value;

O Descendants (MSDN em inglês) devolve um IEnumerable<XElement> e não um elemento simples. Isto porque podem haver vários nós num documento XML com o mesmo nome.
Para converter o IEnumerable num XElement, usamos os métodos First, Single ou FirstOrDefault:

First (MSDN em inglês): Devolve o primeiro elemento encontrado com o nome indicado. Excepção se não houver nenhum.
FirstOrDefault (MSDN em inglês): Devolve o primeiro elemento encontrado com o nome indicado. Devolve null se não houver nenhum.
Single (MSDN em inglês): Devolve o único elemento encontrado com o nome indicado. Excepção se não houver nenhum ou se houver mais do que um elemento.

Por fim, tendo o nó, usamos o Value (MSDN em inglês) para obter o conteúdo textual do nó.

Obter valor do XML


Multivariate Gaussian with 3 Partitions

Question: Given that we partition a Gaussian random vector $\textbf{x}$ into three groups, $\textbf{x}_a$, $\textbf{x}_b$, and $\textbf{x}_c$, with a corresponding partitioning of the mean vector $\mu$ and of the covariance matrix $\Sigma$ in the form
$\mu = \begin{pmatrix} \mu_a\\ \mu_b\\ \mu_c\\ \end{pmatrix}, \enspace \Sigma=\begin{pmatrix} \Sigma_{aa} & \Sigma_{ab} & \Sigma_{ac} \\
\Sigma_{ba} & \Sigma_{bb} & \Sigma_{bc} \\
\Sigma_{ca} & \Sigma_{cb} & \Sigma_{cc} \\  \end{pmatrix} $
What is the expression for the conditional distribution $P(x_a|x_b)$ in which $x_c$ has been marginalized out? (Note the 3 groups are also multivariate)
Answer: Marginalising out $x_c$ means that you can forget about the last row and column of the covariance and $\mu_c$ in the mean vector.
http://en.wikipedia.org/wiki/Multivariate_normal_distribution#Conditional_distributions
$$p(x_a|x_b)=\mathcal{N}\left(\mu_{a|b},\Sigma_{a|b}\right)$$
Where $\mu_{a|b},\Sigma_{a|b}$ is given in the above link.
Comment: +1 for good answer, but it's essentially just the first sentence plus a link ... even though it's a standard result I think it would be better to give the values in an answer, perhaps with a link to a question which gives more details, [like this one](http://stats.stackexchange.com/questions/30588/deriving-the-conditional-distributions-of-a-multivariate-normal-distribution)

Multivariate Gaussian with 3 Partitions


É possivel exibir os dados de uma tabela separadamente?

Question: Tenho uma tabela no meu banco de dados e ela contem uma coluna com os seguintes dados:
link.com/1, link.com/2, link.com/3, link.com/4

O que eu gostaria de saber é se tem como eu fazer a consulta no PHP e retornar o valor da coluna onde cada valor venha só até á , numa linha e o outro em outra linha assim:
link.com/1

link.com/2

link.com/3

link.com/4

Há alguma possibilidade de fazer dessa forma?
Answer: Podes dividir a string através da vírgula, para isso usa a função explode:
<?php

$retorno_bd = "link.com/1, link.com/2, link.com/3, link.com/4";

// converte a string em um array
// utiliza a "," para fazer a divisao
$array = explode( ",", $retorno_bd);

foreach($array as $linha){
    echo "$linha \n";
}

?>

Veja o código no Ideone


What is the relationship of raginis to ragas?

Question: From Wikipedia

Rāginī (Devanagari: रागिनी) is a term for the "feminine" counterpart of a "masculine" rāga.[65] These are envisioned to parallel the god-goddess themes in Hinduism, and described variously by different medieval Indian music scholars. For example, the Sangita-darpana text of 15th-century Damodara Misra proposes six raga with thirty ragini, creating a system of thirty six, a system that became popular in Rajasthan.[66] In the north Himalayan regions such as Himachal Pradesh, the music scholars such as 16th century Mesakarna expanded this system to include eight descendants to each raga, thereby creating a system of eighty four.

Does a ragini have the same relationship to a raga that the second theme has to the first theme in a sonata or is the ragini used in place of the raga?
Comment: @xerotolerant If you went to an Indian *piano* teacher, I wouldn't be surprised if they knew nothing about Indian classical music. The piano is a Western instrument with no presence in Indian classical music (unlike say the violin). So the set of people in India who learn the piano would be quite different. If you went to an Indian veena or sitar teacher, they would presumably know a lot more about Indian classical music. :-)
Comment: I'm curious to see if you'll even get an answer. I have never met anybody who is well versed on the topic of Indian classical music. I had an Indian piano teacher from India who just told me she knows nothing about it. They teach western classical in their schools. I wonder if anybody on here knows...
Answer:
To a first approximation, there are only ragas; you don't have to care about raginis.
If you really want to know what raginis are, then (in the sense that you are most likely to encounter the term) primarily they are (female) personifications [as counterparts] of certain ragas, used in artistic (i.e. in paintings) depictions.
If you really want to consider ragas and raginis in the same category, then there exists an old (historical) categorization wherein, of (what are now called) ragas, some were categorized as (male) ragas, some as (female) raginis.

(I will try to edit and update this answer with more detail later. For now…)
Raga
Recall that a rāga is not just a "scale" or a "mode" but really something like: something that puts the listener in a certain mood. There is a set of notes yes, but there may also be allowed (or common) sequences: for example, notes A, B, C may all be present in a raga, but sequences "AC", "ABAC", may occur and "BC" never occur. Similarly, there may be certain notes used when "ascending" and a different set when "descending". Moreover, the raga may be associated with a certain time of day, a certain season, etc.
(The "feeling" is really more important than any technical definition. An anecdote: my father is a great lover and listener of (Indian classical) music, but has no musical training. He cannot identify a single note, but he can identify many ragas in seconds (after just a few notes), even before many experts who do recognize the notes have had enough information to narrow down the possibilities consistent with the notes heard so far. The reason he can do this, AFAICT, is that the musician too is trying to be consonant with a certain "feeling", that an experienced listener unencumbered by technical detail can grasp…)
Ragini (sense 1)
As every raga has a certain "character" and "personality", it is only natural that someone must have tried to represent them, and they became a popular subject of paintings for a few centuries in Indian art. Certain ragas were represented as women with that character, etc.
See Wikipedia (current version) on Raga-ragini system, Ragamala paintings.
(TODO: add some examples to illustrate. E.g. a raga with a feeling of "longing" may be depicted as a woman (ragini) who is longing for something, etc.)
Ragini (sense 2)
(It is arguable whether this is different from the above or I'm making a distinction that doesn't really exist, but anyway…)
Although an astronomical number of ragas are possible in principle, in practice after you have about 100 or so (or maybe even less), some of them begin to be "similar" to others. This gives the idea of "family relationships" between the "ragas": various music theorists have created categorizations where some ragas are male, they have female raginis as wives, together they have other ragas as children, etc.
See this article for a bit more detail and examples.
Of course, to reiterate what I said earlier, in practice if your interest is mainly in music (and not music history, or art related to music, etc.), then you can forget about "ragini" as a term. For example in a list of raginis you may find Bhairavi, Devagandhari, Dhanasri, Todi, etc., but to most musicians and listeners, these are simply ragas just like the supposedly "male" ragas like Bhairav and Malkauns; in practice no one calls any of them raginis.
(Disclaimer: I am not an expert.)


MySQL - How to find duplicate rows, based on single column?

Question:
I am trying to find all the rows in my table, which a certain column is duplicated in them. and identify them by the unique id column that each row has.

I want to delete them and leave only one copy(row), it doesn't matter which one. (if it can be done through SQL, it is preferred, if note, i will code it..)

(I'm using workbench)
I tried this:
SELECT
  *
FROM
  table_name
GROUP BY `field_name`
HAVING COUNT(*) > 1;

It failed.
My first problem was the sql_mode=only_full_group_by, so I fixed it by adding field names to the query. and it worked.. well, sort of. Since now I saw only the aggregated result without the id column.
SELECT
    field_name
FROM
    table_name
GROUP BY `field_name`
HAVING COUNT(*) > 1;

So, here I am..
How can I do it?
Answer: If I follow you correctly, you can use window functions:
select *
from (
    select t.*, count(*) over(partition by field_name) cnt
    from mytable t
) t
where cnt > 1

For each row, the subquery does a window count that computes how many rows share the same field_name value. Then, the outer query filters on rows whose field_name is not unique.
Note that this requires MySQL 8.0. In earlier version, an alternative uses exists:
select *
from mytable t
where exists (
    select 1
    from mytable t1
    where t1.field_value = t.field_value and t1.id != t.id
)

Answer: If I understand correctly, I'd do this with a sub query. The inner query finds all the column names that are duplicated. Take the name from that query, then pass it into the outer query to find the object id for those names.
You're using the system tables for this query which sometimes have elevated permissions.
I just read that you're using MySQL. This query works in MS SQL, so it may not work exactly as written, but I think the concept is solid so I'll post it.
--outer query
SELECT
    object_id
  , name
FROM
  sys.columns c
WHERE name in (
--Inner Query
    SELECT  Name
    FROM
        sys.columns o
     GROUP BY Name
    HAVING COUNT(*) > 1
)
ORDER BY 2


Data Source Connection in SSRS

Question: I have created a report using SSRS when the report is publish to the SSAS server (Different than DB Server), and I am trying to access the report I got strange error.
An error has occurred during report processing. (rsProcessingAborted)
Cannot create a connection to data source 'DD_BE'. (rsErrorOpeningConnection)
Login failed for user 'NT AUTHORITY\ANONYMOUS

then i go back to check the data source connection.
i set the credential is to use windows authentication (integrated).

here the connection in Data tool is fine

every thing seems fine here then I go to check SSRS Manager to check Data Source.

And I changed the credential and I got different error.
Answer: Check the option Use as Windows credentials when connecting to the data source.

Data Source Connection in SSRS


Python: how to print "word" without white space after and before ""

Question: I am new to Python. I have the following print statement in python:
print '"' This '"' is xyz'

It prints as follows: " word " is xyz
In other words, it has a white space before first " and a white space each before and after the word 'This'.
My question: how can I change the print statement so that the white space before the first " and white spaces before and after the word 'This' is  not printed?
Comment: The line of code you posted doesn't make sense, since the quotes are not balanced. What is the actual line of code?
Comment: @jonrsharpe Java has swing, and one swings when he plays cricket, so that has several puns.
Answer: If you meant to print the literal word "This", surrounded by quotes, try this:
print '"This" is xyz'

If you meant to print the variable This, which is bound to the string word, try this:
This = 'word'
print '"{}" is xyz'.format(This)

Answer: Is this what you want? You can use \" for a " in a string constant.
>>> print "\"This\" is xyz"
"This" is xyz
>>>

Comment: You don't even need the backslashes if you use a single-quoted string.
Answer: print '"This" is xyz'
print '"This" is xyz'