Parametric equations for given line

Question: How would you find the parametric equations for:
1) a line through $(3,1)$ and $(-5,4)$.
2) a segment joining $(1,1)$ and $(2,3)$.
Can anyone show me the steps of doing it cause the way my textbook shows it, it has gotten me in a loop.
Answer: A line will be parameterized by $y\colon x\mapsto ax +b$. For instance, to solve 1), you want
$$
\begin{align*}
1 &= a\cdot3 +b \\
4 &= a\cdot(-5) +b
\end{align*}
$$
since $(3,1)$ and $(-5,4)$ must be of the form $(x,y(x))$ for the desired line. Solve this system to get the coefficients $a$ and $b$.
Answer: The mechanical way to find the parametric equation for any lines going through two points $A$ and $B$ is to write it in vector form, for some constant $\mu\in\mathbb{R}$:
$$\vec{l}=\overrightarrow{OA}+\mu\overrightarrow{AB}$$
For instance, in your case, for the first line, we have: $A(3,1)$ and $B(-5,4)$, therefore the equation of our line is:
$$\vec{l_{1}}=\begin{pmatrix}3 \\ 1\end{pmatrix}+\mu\begin{pmatrix}-5-3 \\ 4-1\end{pmatrix}=\begin{pmatrix}3 \\ 1\end{pmatrix}+\mu\begin{pmatrix}-8 \\ 3\end{pmatrix}$$
If you want the non-vector parametric equations you simply take the $x$ and $y$ components separately, i.e.:
$$\begin{align}x&=3-8\mu \\ y&= 1+3\mu\end{align}$$
Answer: The equation of the first line $$\frac{y-1}{x-3}=\frac{1-4}{3-(-5)}\iff \frac{y-1}{-3}=\frac{x-3}8=a\text{(say)}$$ where $a$ is any real number
$$\implies y=1-3a,x=3+8a$$
Answer: Let $p,q \in \mathbb{R}^2$ be points on the plane. The vector $v$ with starting point $p$ and ending point $q$ can be understood as a transport of points, in other words, the vector $v$ will be the subtraction of the points to give a kind of machine that when applied via the sum to the starting point gives the endinging point. Multiplying a vector by a number $k$ is equivalent to get a transport of point in the same direction if $k>0$ that is $k$ times the original transport. It'll reverse orientation if $k <0$.
Now, what's a line? A line can be understood as a curve that never changes it's direction. In other words, you take a point and transport it forever in the same direction forward and backward and you'll get a line in euclidean plane. Now one can describe a line by the following function $\alpha : \mathbb{R} \to \mathbb{R}$
$$\alpha(t) = p + tv$$
So this function says that you take any point on the line and transport it always on the same direction (that of $v$) all the way forever (this aims to allowing $t$ to run all the reals). Of course $p$ can be any point on the line and $v$ can be any transport from one point on the line to any other point on the line. A segment of $\alpha$ is obtained by restricting the domain to some closed subinterval of the reals (so that the transport gets bounded).
Now with this theory let's tackle the exercise. Since we want a line through $(3,1)$ and $(-5,4)$ we know that both points are on the line. So $(-5, 4) - (3,1) = (-8, 3)$ is the vector that transports one point of the line to the other one. So by the preceding discussion the line is parametrized by $\alpha : \mathbb{R} \to \mathbb{R}^2$ given by the following:
$$\alpha(t) = (-5,4)+t(-8,3)=(-5-8t, 4-3t)$$
Now the segment joining $(1,1)$ and $(2,3)$ can be obtained in analogous way. However the domain must be a closed subinterval. The natural choice is $[0,1]$, so that for $0$ we get $(1,1)$ and for $1$ we get $(2,3)$. Again the vector responsible for transporting the initial to the final point is $(2,3) - (1,1) = (1,2)$. So the parametrization is $\alpha : [0,1] \to \mathbb{R}^2$ given by:
$$\alpha(t) = (1,1) + t(1,2) = (1+t, 1+2t)$$
Answer: 1) The point-slope form for the equation of a line: $y-y_0=m(x-x_0)$. So an equation for the line is $y=\frac{4-1}{-5-3}(x-3)+1$. A parametric equation here would be $$y=\frac{4-1}{-5-3}(t-3)+1$$$$x=t$$
2) You could use the same technique and restrict $t$, or you could restrict $t$ using another method. First, an equation for the line is $y=2(x-1)+1$. We want $1\le x\le2$, so we need a bounded function that goes from $1$ at $-\infty$ to 2 at $\infty$. One function that is similar is the tanh (hyperbolic tangent: $\displaystyle\frac{e^x-e^{-x}}{e^{-x}+e^x}$. The tanh function goes from $-1$ at $-\infty$ to $1$ at $\infty$, so $\frac12\tanh x + \frac32$ goes from $1$ to $2$, so this is something we can use.
The unrestricted parametric plot is:$$y=2(t-1)+1$$$$x=t$$
After substituting $\frac12\tanh t + \frac32$ for $t$, we get what we want:
$$y = 2(\frac12\tanh t + \frac32-1)+1$$
$$x = \frac12\tanh t + \frac32$$

Parametric equations for given line


Error: "Cannot start process, the working directory does not exist." in IntelliJ

Question: When I move a whole project from one computer to another, and I try to start the project in IDEA on the other computer, the following error occurred when I start my application itself: "Cannot start process, the working directory does not exist."
There's no context for me to put this message in. I checked all my settings and everything seems to be all right. What have I done wrong?
Comment: I'm willing to bet that you copied over things like the .idea folder and various IDE-centric files.  If you purge those configs and recreate your project from scratch, do you still get the error?
Comment: Check the `idea.log` for possible hints (`Help | Show Log in XXX`)
Answer: For IntelliJ all I had to do was create a directory called modules in the project's .idea folder. This solved the issue. But my specific error said the working directory does not exist and it had my project path and ended in project/.idea/modules.
Note that doing rm -r .idea/ in the project folder did not solve my issue.
Comment: weird that creating an empty folder fixed this... thank you!
Answer: I was also facing the same issues which has been fixed and working fine.
Solution: Go to FOlder where your project resides. Search for ".idea" folder --> delete that folder and then open the code and go to "settings.gradle(Project Setting)" file -- >
cut the line "include ':app'" -- > Sync Now --> now paste the same "include ':app'" and Sync now again --> Issues resolved -- > Last Clean & Revuild the project
Answer: See here :
https://stackoverflow.com/a/25922840/5334435
You need to set a value "." for the working directory. And remember to set it as Default, in order no to reset it every time.
Answer: Invalidate Caches / Restart Worked in my case


Não consigo executar uma query com jdbc java

Question: public List<Sistema> buscarUsuarioSistemaPor(Long cpf) throws SQLException {
    List<Sistema> listSistemas = new ArrayList<>();

    String sql = "select s.* from sistema as s\r\n" +
            "inner join usuariosistema as u on (u.idsistema = s.idsistema)\r\n" +
            "where u.usuario_cpf = @cpf";
    connect();

    PreparedStatement prepareStatement = jdbcConnection.prepareStatement(sql);
    prepareStatement.setLong(1, cpf);

    ResultSet resultSet = prepareStatement.executeQuery(sql);

    while (resultSet.next()) {
        Long idSistema = resultSet.getLong("idSistema");
        String nome = resultSet.getString("Nome");

        Sistema Sistema = new Sistema(idSistema, nome);

        listSistemas.add(Sistema);
    }

    resultSet.close();
    prepareStatement.close();

    disconnect();

    return listSistemas;
}

O seguinte erro está ocorrendo:
Parameter index out of range (1 > number of parameters, which is 0).
Parameter index out of range (1 > number of parameters, which is 0).
Parameter index out of range (1 > number of parameters, which is 0).
Parameter index out of range (1 > number of parameters, which is 0).
Parameter index out of range (1 > number of parameters, which is 0).
estou usando a versão do conector mysql:

Citação

<dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.17</version>
    </dependency>

Fazendo com o parametro na query dessa outra forma:
public List<Sistema> buscarUsuarioSistemaPor(Long cpf) throws SQLException {
    List<Sistema> listSistemas = new ArrayList<>();

    String sql = "select s.* from sistema as s\r\n" +
            "inner join usuariosistema as u on (u.idsistema = s.idsistema)\r\n" +
            "where u.usuario_cpf = ?";
    connect();

    PreparedStatement prepareStatement = jdbcConnection.prepareStatement(sql);
    prepareStatement.setLong(1, cpf);

    ResultSet resultSet = prepareStatement.executeQuery(sql);

    while (resultSet.next()) {
        Long idSistema = resultSet.getLong("idSistema");
        String nome = resultSet.getString("Nome");

        Sistema Sistema = new Sistema(idSistema, nome);

        listSistemas.add(Sistema);
    }

    resultSet.close();
    prepareStatement.close();

    disconnect();

    return listSistemas;
}

Ocorre o seguinte erro:

java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?' at line 3
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:120)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97)
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
at com.mysql.cj.jdbc.StatementImpl.executeQuery(StatementImpl.java:1218)
at br.com.sefaz.dao.Usuario_SistemaDAO.buscarUsuarioSistemaPor(Usuario_SistemaDAO.java:101)
at br.com.sefaz.controller.Usuario_SistemaController.buscarUsuarioSistemaPor(Usuario_SistemaController.java:37)
at br.com.sefaz.dao.UsuarioDAO.listAllUsuarios(UsuarioDAO.java:100)
at br.com.sefaz.controller.UsuarioController.listAllUsuarios(UsuarioController.java:52)
at br.com.sefaz.main.Teste.main(Teste.java:35)

Já não sei mais o que fazer, alguém me ajude por favor?
Comment: Não tem muito sentido estes \r\n em sua sentença SQL.
Answer: Amigo altere seu código
ResultSet resultSet = prepareStatement.executeQuery(sql);

Para
ResultSet resultSet = prepareStatement.executeQuery();

Não precisa passar a query como parâmetro do executeQuery quando se esta chamando ele pela PrepareStatement. Na sua preparestatement você já informou o select, não precisa passar novamente.
[Editado]
Encontrei a documentação onde fala disso: https://docs.oracle.com/javase/7/docs/api/java/sql/Statement.html#executeQuery(java.lang.String)
Comment: Obrigado cara, tava tão bitolado no problema que não vi que tinha colocado 2x o sql. Sua recomendação resolveu meu problema.
Comment: Que bom, fico feliz que tenha resolvido. Se deu certo, por favor marque a resposta como correta para ajudar outras pessoas que procurarem por este erro.
Comment: Ja tinha marcado.
Comment: Verdade, me desculpe na hora que escrevi o comentário  não tinha percebido. Mas acho que foi tentar marcar de novo e agora desmarcou a resposta como correta rssrs
Answer: select s.* from sistema as      <--- você precisa  colocar a mesma referência aonde vc colocou ( s.* ) Revise os espaços da SQL.
String sql = "select s.* from sistema as s\r\n" +
        "inner join usuariosistema as u on (u.idsistema = s.idsistema)\r\n" +
        "where u.usuario_cpf = @cpf";

Tenta fazer separado que irá lhe ajudar muito usei
StringBuilder sql = new StringBuilder();
sql.append(" SELECT * FROM TABELA "):
sql.append(" WHERE ID = ?");

sql.toString;


Sticky/fixed dropdown menu doesn't scroll with page

Question: So i have been trying to fix this issue for some hours now. There is a double level submenu. If the content of the sub menu goes out of viewport, when you scroll the submenu items doesn't scroll too.

click here to view the site
Comment: Thanks for your response. The site is on wordpress. I added the link to the site.
Comment: can you add your minimised html and css code?
Answer: Try this
<code>#menu-main-menu ul li{
    height: 400px;
    overflow: scroll;
}
</code>
Answer: on the submenu ul that doesn't scroll, try adding a fixed height and overflow: scroll
Comment: this did work partially, but messed up the look of the menu. And besides with the static height, i am sure i wouldn't know the heights of all the devices viewing the site.


Rack:cors gem not setting cors header for GET requests

Question: I am trying to use Rack-cors gem to enable cors. The issue is that for non-get requests the header is coming bur for GET requests the header is not present.
In application.rb
    config.middleware.insert_before ActionDispatch::Static, Rack::Cors do
      allow do
        origins '*.example.com'
        resource '*', :headers => :any, :methods => [:get, :post, :options]
      end
    end

Searched rack:cors issue but not able to found any solution .

Any idea what is wrong here?
Answer: Its working for me. Having following configuration in application.rb
config.middleware.insert_before 0, "Rack::Cors" do
  allow do
    origins *Rails.application.secrets.cors_origins
    resource '/posts', headers: :any, methods: [:get, :post, :options]
    resource '/post', headers: :any, methods: [:post, :options]
  end
end

Comment: Not sure why this is not working for me.. I am using Rails 3.2.13 and not using rails-api.
Comment: What version of rails and rails-api are you using?
Comment: rails (4.2.6) , rails-api (0.4.0)


How Specify the class name of our columns in Responsive Grid View?

Question: I'm trying to build a responsive Views grid using views responsive grid module. But added fields in the view is not visible.
I'm confused in adding grid class.Please anybody guide me to set class name, so that fields can be seen in the grid?I have attached screenshot of my settings below.
Answer: For Wrapper do not use
 you need to use a name. Ex: magazine_grid_wrapper
Comment: I didn't understand explanation given in the module.                                              "How to Use"  section in https://www.drupal.org/project/views_responsive_grid
Comment: I updated with class name ,still fields are not displaying.
Comment: umm humm, try this [tutorial](https://www.drupal.org/node/2390355)


Notating Augmented Chords

Question: When writing an Augmented chord, which inversion of the chord should I use?
The problem came up while I was composing (piano). I came to an augmented chord and couldn't think of which version to use due to the accidentals.
The key I was writing for here is C# Minor. 'n' reperesents a natural:

G#+ Root: G♯ - B♯ - D♯♯
C+ 2nd Inv: G♯ - C♮ - E
E+ 1st Inv: G♯ - B# - E

I remember from my music theory that an inverted augmented chord creates another augmented chord. But I have no clue how I should write it. If I had to guess, I would say that you chose based off the key that you're writing in.
Comment: Those chord spellings are weird, I suppose that you count on us to add the key signature of C# minor. It would all be more clear if it called G# G#, whatever if the sharp is an accidental or in the key signature.
Answer: Really you're talking about augmented triads, specifically, and yes, all augmented triad inversions create another augmented triad.
You already know which augmented triad you want, so this is more a question of accidental notation--this can come up in many other circumstances as well, especially if you're working in a neotonal context or are very far away from your key center.
If you're writing traditional harmony, the answer is probably going to be whichever notes fit your key signature the best. #2 and b1 (xD and nC in your key of C# minor) are rare, so the notation you're looking for is probably G# - B# - E. This is also really the same as finding one of the chords diatonic to your key signature. In C# harmonic minor, the only diatonic augmented triad is indeed rooted on b3 (E - G# - B#).
If this is not the case, then in order to answer the question properly, we'd have to know how you got to that chord and where you're going. i.e. how does the augmented triad function in the chord progression you've written. You would then choose an inversion that most clearly describes the root movement of the bass, or how you're planing something, or a weird deceptive cadence, or any number of other compositional techniques.
One last thing worth noting is that the first method I mentioned (look in the key signature when writing traditional harmony) is really exactly the same as the last one (do what makes logical sense): when you're writing traditional harmony, the logical progressions generally all fall on the diatonic notes, or not far from them in the case of secondary dominants.
Comment: I know the question is about triads, but what about this: try to find which aug7 chord that fits best, and this will give what the best root of the aug triad is. It's nothing I have tried for composing, but I do often play the seventh on aug chords even if not noted. Your opinion?
Comment: @Gauthier The Aug7 chord is only going to "fit" if it is functioning as a Maj7+5 chord; that is, it would go where a Maj7 chord would go, but the fifth is altered for effect.  Yes, this chord has a defined root, but depending on the harmonic language in use, the augmented triad may not be functioning in a similar manner.  The notation of these "divide-the-octave-equally" chords (the other notable one being the fully diminished seventh chord) depends on context, and even then it is not always an exact science, since some music uses the chord's ambiguity to resolve to an unexpected harmony.
Comment: @Andrew: I was thinking of a minor 7th. As in: `G#+7 - C#m`. I am not sure what you mean with that only a Maj7 would work. I hear you about the "divide-the-octave-equally" though, our scales and theory are not really made for that...
Comment: @Gauthier I misunderstood what you were doing when you said that you played the seventh on augmented chords.  It looks like you are instead using an altered dominant (altered to include ♯̂2).  In that case, yes, you could just be treating the augmented chord as a dominant-functioning sonority.  It occurs to me that it should be possible also to resolve the V7+5 as a non-traditional augmented sixth chord, which would make a progression like `G♯7+5 - E♯7 (F7) - B♭`.  I don't have a keyboard handy to hear how that progression would sound, but I think it would sound pretty unusual.
Answer: I assume here that you are looking for the way to name the chord, rather than to spell it in notes.
You seem to know that you want the G# at the bass. I would probably write the chord that does not call for an inversion, for the sake of simplicity. G#+ is much easier to read than B#+/G# or E+/G#.
In the general case, if one of the tones forming the augmented chord is not in the current tonality, you could put that as the augmented 5th. For example in C major, I would use G+ rather than other inversions because D# is the accidental.
However in your example, all tones of G#+ are in C# minor harmonic (B# is really in the scale although it does look like an accidental. That's an annoying shortcoming of our notation system).
One way to decide which of the inversions to use could also be to test the associated aug7 chord. Test G#+7, B#+7, and E+7, see which one fits best. That could give you your answer.
Answer: I notate the chord by the key signature (in C# minor: G# B# E) but name and analyze the chord as an altered V (G#+) if it contains the 5 scale degree.
Two reasons for the former: (1) Clarity is always a goal of sheet music and writing Dx when E is in the key signature is confusing, and (2) the E note is often just a suspension that releases to D# before the chord resolves to C#m, so you want to be able to read that E - D# melody clearly. There's an argument that theory should call this chord a 6th suspension but we just don't.
For the latter, well, G# B# E in C# minor sounds like a V and is likely decorated with extensions considering G# to be the root. That is, F# is added as the dom7, and perhaps b9 (A).
Answer: Your list of chords is not just changing inversion, it changes roots. If you make a first inversion G#aug triad, it is simply B# Dx G#. Your first inversion example uses the same enharmonic pitches, but it changes the root. In the end you need to know which root and inversion of the chord you want. You would make those choices, like other such choices, based on harmonic function and melodic aspects.
Answer: Considering that E belongs in C# minor (unlike Dx), and B# belongs in the harmonic minor (unlike C♮), I'd go with option 3 and call it an Eaug.

Notating Augmented Chords


$\mathcal{B}(H)^+$ is closed and generated by $id$

Question: Let $H$ be a Hilbert space. Define its positive cone by
$$\mathcal{B}(H) = \{A \in \mathcal{B}(H) : \langle v, A(v)\rangle \geq 0, \forall v \in H\}.$$
Show that $\mathcal{B}(H)^+$ is closed with respect to the operator norm and it is generated by $id \in \mathcal{B}(H)$.
1) $\mathcal{B}(H)^+$ is closed.
Let $(A_n)_{n \in \mathbb{N}}$ be a sequence of positive elements of $\mathcal{B}(H)$ and $A = \lim_{n \in \mathbb{N}} A_n$, ie, $\vert\vert A_n - A \vert\vert_{op} \rightarrow 0$. This means that $ \sup_{v \in H, ||v|| = 1} |A_n(v) - A(v)| \rightarrow 0$.
As $A_n \in \mathcal{B}(H)$, for all $n \in \mathbb{N}$, we have that for all $v \in H$ and for all $n \in \mathbb{N}$, $\langle v, A_n(v) \rangle \geq 0$.  In order to show that $\mathcal{B}(H)^+$ is closed, we need to show that for all $v \in H$, $\langle v, A(v) \rangle \geq 0$.
Suppose that $v \in H$ is such that $||v|| = 1$ (otherwise we can divide and multiply by the norm and do some similar calculation). Then,
$\langle v, A(v) \rangle = \langle v, A(v) - A_n(v) \rangle + \langle v, A_n(v) \rangle \geq 0$, because the first term goes to $0$ and $\vert \vert A_n - A \vert\vert_{op} \rightarrow 0$ and the second term is positive.
Problem: I think this argument is not totally precise. Could someone help me here?
And I am struggling to show that $\mathcal{B}(H)^+$ is generated by $id$. I would appreciate very much some hint :)
Thanks in advance!
Comment: Can you define "generated by"?
Comment: We say that a positive cone $V^+$ is generated by some element $v$ if $V^+ = \cup_{\alpha \in \mathbb{R}^+_{0} }$ $[0, \alpha v] $.
Answer: 1) The argument is not written very clearly, but it's essentially ok. If $A_n\to A$ is operator norm, then $A_n v\to A v$ for all $v\in H$ (this you already used) and thus also $\langle A_n v,v\rangle\to \langle A v,v\rangle$. The latter follows directly from the continuity of the inner product. Since every sequence member is nonnegative, so is the limit.
2) You have to show that for every $A\in B(H)^+$ there exists $\alpha>0$ such that $A\leq \alpha\,\mathrm{id}$. The canoncial candidate for any bound on $A$ is $\lVert A\rVert$, and indeed it works:
$$
\langle Av,v\rangle\leq \lVert Av\rVert \lVert v\rVert \leq \lVert A\rVert \lVert v\rVert^2=\lVert A\rVert \langle\mathrm{id}\,v,v\rangle.
$$
Hence $A\leq \lVert A\rVert\,\mathrm{id}$.


Should we always eliminate calculated attributes, even when it is a critical and complicated calculation?

Question: The "third normal form" of database design asks you to remove functional dependencies. It  seeks to eliminate redundancy, removing from a table any attributes (fields) that can be calculated from the other fields. For instance, when you make a reference to another entity, you only store its key. You don't store replicas of attributes from these referred entities, because that would mean having to update them every time you change the referred entity.
Another situation is an attribute such as height. You want to know the height of a person, but in your application you may like to know it in different units: meters, feet, astronomical units. But you don't store all of these values, you should remove calculated fields, so you only leave one of them (meters, of course), and you calculate the transformed values "on the fly", when you need it.
You also don't store something like age, you calculate them from date of birth. In this case the fact that age changes with time also plays a role. If you don't do this your data will soon be incorrect, unless you keep updating it constantly.
Now suppose you have a social network that displays the astrological sign of each user. For each user we display his or her sign, which is calculated from the date and time of birth, and also from the astrological tradition of the user's choice (e.g. Western or Chinese). Calculating someone's sign is a pretty specialized and involved calculation, but is nevertheless something you can just call from an astrological library and calculate. How would you design this database, would you remove this functionally dependent attribute, or would you calculate the user's sign once, or every time she updates her date of birth, then store it in the database and forget about the possibility of calculating a sign in the rest of your system, or would you enforce the "3NF" rule with an iron fist? And how do you see the potential benefit of being able to tweak a user's sign if she insists that her sign should be different from the one that your algorithm is calculating?
Now suppose a new application. You are building a system for the Army, that chooses possible occupations for new conscripts. Part of your system is a huge bad-ass pattern recognition machine, developed at ORNL, that tells you what occupations will be allowed for the conscripts, based on a whole lot of data that comes from your database. This pattern recognition method looks at each person's height, date of birth, medical records, school transcript, and it also looks at a long list of answers the person gave to one of two questionnaires. It also takes in consideration evaluation questionnaires filled by higher-rank officers, and the analysis that is made looks at all of the conscripts from each year at the same time, to come up with a bunch of parameters for, say, a feed-forward neural network. This neural network is simpler than the whole of the pattern recognition system, but it is still a pretty involved calculation, not just a temperature unit conversion. Nevertheless, you can see it as a "black box", and it can tell you the fate from each of your conscripts when you pull his record form the database.
At a specific date in the Army's calendar, the analysis is made, the ANN parameters are found, and now you can run the black box and tell each conscript what he will be doing for the next one year or two. It's a pretty important thing. You will be deciding people's occupations, you will be sending some people to operate ovens at the kitchen, and other to drive tanks. Everyone will be logging in the Army's network to check out their occupations, and see the result in their personal webpages.
Now, the little black box is there, and it outputs this important value based on the attributes pulled from your database. The attributes and parameters will probably never change, and the calculation of the conscript's destiny will probably be always correct, always the same value form the first day. But would you really leave that outside the database, just to follow the "remove calculated attributes" rule?
This is not just some calculation of age, astrological sign or temperature conversion. The pattern recognition system is indeed a path to calculate an attribute. But would you really like to keep that inside your system forever, re-calculating this hugely important thing over and over again? Or would you consider it better to calculate everything once, and forget that this magical black box exists? I mean, just run all of this crazy pattern recognition code once some day, then pick the results, and record them in the database. When someone logs in to see the output from his analysis, make it so the query is just a boring data-fetching procedure, and leave all the pettern recognition "excitement" for another time.
Another more palpable situation: You run a web store like Amazon. You have a pattern recognition method to recommend books to people, that is fed from a user's record in your DB. Would you keep running the thing all the time you need the current recommendations, or would you treat the pattern recognition box as something separate from the rest of the system, just feeding its results to the database from where it can be read by other programs? Wouldn't it be nice to have a control, for example, to make sure that you are not switching recommendations at an awkward moment?... Don't worry too much about computational burden, assume excellent memory and computational resources.
TL;DR -- Do you think the rule of removing calculated attributes should never be broken, or would you say it is OK to store in the database the results from very important attributes, that are calculated by very complex and delicate pattern recognition methods? Aren't there situations where we should just pretend that you actually cannot perform the calculation "on demand", and just leave recorded there these results, that won't be updated anyway?
Answer: Deliberate, judicial denormalization is "allowed" for caching the results of an expensive calculation. Converting units or calculating age would be examples of inexpensive operations that should probably not be cached, but other examples you cited look appropriate.
Depending on the DBMS, you may be able leave the tables normalized, and implement caching "on top" of them:

Some DBMSes support materialized views - like a regular VIEW but persisted so it doesn't need to be recalculated every time it's queried.
Some DBMSes that support calculated fields (aka. computed columns), also support persisting them (one example is the PERSISTED keyword under MS SQL Server).


TFS REST API System.IterationPath returns error

Question: I am passing the Iteration path to the field in REST API Query using python requests library.
>>> payload = {"name": "Audit Work Items","wiql": ("SELECT [System.Id],[System.WorkItemType],[System.Title],[System.AssignedTo],[System.State],[System.Tags],[System.IterationPath] FROM workitems WHERE [System.WorkItemType] = 'User Story' OR [System.WorkItemType] = 'Bug' AND [System.IterationPath] = '\2CES\Backlog\2020\20.1\20.1.5' ORDER BY [System.Id]")}
>>> response  = requests.post(organization_url, auth=HTTPBasicAuth(username, password), verify=False, json=payload)
>>> response.text
'{"$id":"1","innerException":null,"message":"TF51011: The specified iteration path does not exist. The error is caused by «\'\\u0002CES\\\\Backlog\x820\\u0010.1\\u0010.1.5\'».","typeName":"Microsoft.TeamFoundation.WorkItemTracking.Client.Wiql.SyntaxException, Microsoft.TeamFoundation.WorkItemTracking.Client.QueryLanguage","typeKey":"SyntaxException","errorCode":0,"eventId":0}'
>>>

I am unable to understand the innerException returned by the REST API and why is the path showing some binary characters in the error message ?
Can anyone please help me fix this issue, thanks in advance.
Comment: Did you try escaping the backslash character?
Answer: The backslashes need to be escaped. \2CES is being interpreted as a Unicode character. Try \\2CES
Comment: The solution worked. I took an ID for a work item and executed it through requests GET call from python interpreter which returned the result set as dictionary. I found the System.IterationPath has been escaped with back slash in the response output.


How to print multi-value link image CCK field in template?

Question: I have a multi-value CCK field set up using the Link Image Field module, and I need to print all of the images (linked) on the content page. I used the code below to print the images themselves, but cannot figure out how to wrap each image's link around each image.
                <?php if ($node->field_day_option_buttons[0]['filepath']): ?>
             <?php
                foreach($node->field_day_option_buttons as $image) {
                 if (file_exists($image['filepath'])) {
                     print theme_imagecache('my image cache preset name', $image['filepath']);
                    }
                  }
              ?>
            <?php endif; ?>

Can anyone provide input on how to accomplish that?
Thanks!
EDIT
Here is the info placed on the page when I run a print(r) on that cck field:
Array (
  [0] => Array (
    [fid] => 347
    [uid] => 1
    [filename] => days-5.png
    [filepath] => sites/default/files/days-5_0.png
    [filemime] => image/png
    [filesize] => 440
    [status] => 1
    [timestamp] => 1366038083
    [list] => 1
    [data] => Array (
       [alt] => Alt Text
       [title] => Title Text
       [url] => http://www.mysite.com
       [target] => _self
    )
    [nid] => 18
  )
  [1] => Array (
    [fid] => 348
    [uid] => 1
    [filename] => days-20.png
    [filepath] => sites/default/files/days-20_0.png
    [filemime] => image/png
    [filesize] => 506
    [status] => 1
    [timestamp] => 1366038108
    [list] => 1
    [data] => Array (
       [alt] => Alt Text
       [title] => Title Text
       [url] => http://www.mysite.com
       [target] => _self
     )
    [nid] => 18
  )
)

Comment: what else is available inside `$image` besides 'filepath', eg can you give us a print_r() or equivalent of the rest of the data you have to work with.  I am assuming somewhere in there is the link/url you need to grab.
Comment: @Jimajamma I added the info from the print(r) to my question above. Does that show what you are looking for?
Comment: some editing shows me you are probably wanting to grab the `$image['data']['url']` info and then use that with  @Boriana's answer below.
Answer: You should be able to use the l() function (link function) to print out your link.
Typically, l() is used with the arguments l("My link text", $path), however, the first argument doesn't have to be text and can be just html.  You just have to specify that with the optional $options array argument at the end if you're including html.  :-)
Here is more documentation on using l(): http://api.drupal.org/api/drupal/includes!common.inc/function/l/7  The 6 & 7 versions should work similarly.
In your case, you can build your link like this:

Your first argument will be an image, rather than text as the link
Your second argument will be the path you want the image to link to, which should be $image['filepath']
Your third argument should specify that the first argument is html, and not just text

So, try something like:
<?php
print l(
    theme_imagecache('my image cache preset name', $image['filepath']),
    $image['data']['url'],
    array(
          'attributes' => array(   // Sample attributes you can apply to your anchor tag
            'id' => 'your-link-id',
            'class' => 'your-link-class',
            'target' => '_blank',  // open link in new window.
          ),
        'html' => true,
    )
);
?>

I haven't tested this yet, as I don't have a Drupal 6 site handy, but this should work.  Let us know if it works or if it needs some tweaking...
Comment: Why not?  :-)  Done.
Comment: in this, using `$image['data']['url']` as the second argument or `$path` is probably what the OP is asking about.
Comment: Hmmm.  @Jimajamma, I'm just wondering whether to edit my response, but it seems your edit would result in each image to the site's homepage?  Is that how how you understood the question?  Am I missing something?
Comment: I understood the question to be how to print the images wrapped in the link that is set in the field, and the only link I see there is the url one (wherever it happens to point)
Comment: OK, you're probably right. That's the whole point of the link image module, after all.  I misread to mean the image's URL too literally.  I'm going to edit my response.  Thank you!
Comment: Feel free to add in the `'attributes' => array ('target' => $image['data']['target'])` stuff if we all want to be super fancy, too :)


How to get maximum possible score for a query in elasticsearch?

Question: I have a large document set stored in elasticsearch index and I need to find similar ones to exlude duplicates.
Unfortunately, these documents can have different values, so I can not fully rely on filters. Instead, I am trying to evaluate how much the difference is between two documents using multiple fields and different boost values.
If the difference is too big then document doesn't count as a duplicate.
The problem is - I do not know how to evaluate the difference, because _score in search response tells nothing about how big the difference is.
It would be perfect to have maximum possible score for each particular query. How can I achieve this?
Edit:
For example, if I execute a query like this it returns a JSON with _score, more than 1.00
Request:
GET /documents/sometype/_search
{
    "query": {
        "bool": {
            "should": [
                {"match": {
                    "title": {
                        "query": "some title"
                    }
               }}
            ]
        }
    }
}

Example response:

{    "took": 1,    "timed_out": false,    "_shards": ...,    "hits": {
        "total": 100,
        "max_score": 1.7588379,
      } }

As documentation says, _score - is just a floating number, saying nothing about its range.
Comment: The maximum possible score for any query will be 1.00, I'm not exactly sure what you're looking for could you provide an example? Is it the max score for a query among the documents? In which case a simple search gives you the list.
Comment: Updated a post.
@VishalRao
As far as I know, the "max score" field means "max score in a matched result set". It is not max possible score for a query.
Answer: That's an interesting question. Since the Practical Scoring Function(PSF) in general uses the inverse-document-frequency (IDF) the question "What is the maximum document score given a query" is not well-posed. The scoring result will depend on all documents, i.e. the index, and even the number of shards in your ES configuration.
My guess would be that by modifying the index it is possible to show that the maximum score of a query is unbounded if IDF is used.
In special cases though, if you deactivate the IDF part of the PSF by using e.g. constant_score, the maximum score should be bounded since it only depends on the doc itself, not the index.
That being said, I would also love to see an _max_score endpoint returning inf in case of IDF is used somewhere in the query and the actual maximum document score if not.
Answer: Here's a python snippet to get the current max score by adding a non-existent term (and deleting it afterwards).
This assumes that 25 random lower case characters have ~0 chance of appearing as a term in your index (otherwise change the way the unique string is generated).
import elasticsearch
import string
import random

es = elasticsearch.Elasticsearch()

unique = ''.join(random.choice(string.ascii_lowercase) for i in range(25))

index = "your_index"
doc_type = "your_doctype"
key = "your_key"

es.index(index=index, doc_type=doc_type, body={key: unique}, id=unique, params={"refresh": "true"})

body = {
        "doc": {index: unique},
        "term_statistics": True,
        "field_statistics": True,
        "positions": False,
        "offsets": False,
        "filter": {
            "min_term_freq": 0,
            "min_doc_freq": 0
        }
    }

result = es.termvectors(index=index, doc_type=doc_type, body=body)

max_es_term_score[index] = result["term_vectors"][index]["terms"][unique]

es.delete(index=index, doc_type=doc_type, id=unique)

Comment: I actually had to put this in a function and retry several times (re-generating the `unique` string every time) until succeeding since `termvectors` didn't always return a score for `unique`. I attribute this to the frail 6.* ES Python API (i had many problems), which i hope was fixed in later versions. If anyone have any insight into why this happens please share.


What is the difference between period prevalence and incidence rate?

Question: I am confused about the difference between period prevalence and incidence rate. Following are from Wikipedia:

The incidence rate is the number of new cases per population in a
  given time period.
Period prevalence is the proportion of the population with a given
  disease or condition over a specific period of time.

Thanks!
Comment: First one is NEW, second one is ALL as I understand. So, first is a derivative of second by time.
Answer: Incidence refers to new cases of a disease, while prevalence refers to all existing cases.
The two are related (Prevalence = Incidence x Disease Duration), but aren't the same thing. For example, for an incurable disease like HIV, the incidence rate could be decreasing as prevention measures improve, but the period prevalence can still rise (due perhaps to increased survival rates).
Answer: a)prevalence is the amount or the number of cases they have in a specified time(in other word the total number of cases divided by the number of individuals).example,300 players have participated in Ethiopia volleyball premier league in 2014 season,in that season 180 injuries were registered.Therefore,the prevalence of injuries are 180/300=0.6 .
b)incidence is the frequency of cases in a specified period of time.example:-in the 2014 Ethiopian volleyball premier league players spend 12345hrs in one season during game and training,in that period 180 injuries were registered. therefore the incidence of injury will be 180/12345*1000= 14.58


Re-charmar função php, porem está retornando null na segunda chamada

Question: O que está acontecendo tenho  essa função no  pgp que verifica se já existe a url no banco de dados se já existe simplesmente adiciona um numero na frente, para isso  eu  chamo a função até ela achar uma que não existe exemplo
se meu-nome existe ele vai tentar meu-nome1, meu-nome2 e retornar quando der certo, porem o return só está funcionando na primeira vez, já verifique se o valor existe está ok, somente não está retornando.
<code>public function checkUrl($nome,$tabela,$coluna,$cont){
    global $mysql,$fottic; // vairaveis globais
    if($cont > 0){ // veirifca se a função foi chamada novamente
        $url = $nome."-".$cont; // adiciona um numero na url
    }else{ se tiver sido chamada pela prmeiravez normaliza a url
        $url = $fottic->NormalizaURL($nome);
    }
    $qr = mysqli_query($mysql,"SELECT * FROM $tabela WHERE $coluna='$url'") or die(mysql_error()); // verifica no db se existe
    if(mysqli_num_rows($qr) == '0'){
        return $url; // se não existe retorna o valor

    }else{
        $cont++;
        $fottic->checkUrl($url,$tabela,$coluna,$cont);
        //se já existe, faz toda função novamente
    }
}
</code>
Answer: Consegui achar o que deu de errado, tinha que retornar a função novamente
<code>}else{
    $cont++;
    return  $fottic->checkUrl($url,$tabela,$coluna,$cont);
    //se já existe, faz toda função novamente
}
</code>


Putting a steel string on a classical guitar? (classical guitar with truss rods)

Question: I know that putting a steel string on a classical guitar is not advisable as it can damage the bridge or the neck. And based on my research classical guitars doesn't have truss rods because nylon strings does not put heavy tensions ..
But i was surprised on the classical guitar that i bought because it has a truss rod in it. So i was wandering if i can put a steel string on it, because i think that the neck can handle the tension. And what about the bridge? I think that classical guitar's bridges is different from acoustic guitar's bridges.
So, is it safe?
Comment: Why do people keep wanting to do this? _"It's a bad idea"_, we say. *"But this time it's different!"*, they say.
Comment: I've got to say, I agree with @VarLogRant here. If you want to put steel strings on an acoustic guitar, you're best putting them on a steel-string acoustic guitar.
Comment: possible duplicate of [Can I use nylon with steel string guitar?](http://music.stackexchange.com/questions/2997/can-i-use-nylon-with-steel-string-guitar)
Comment: I've voted to leave this open. Although these questions are related, the consequences of the actions described are very different.
Comment: Agree too. Why would you _want_ steel strings... though allright, if you want a brighter sound, extended bending range and/or magnetic pickups, then you _can_ actually put steel strings on any classical guitar – just, definitely not the standard western-guitar kind, but specially designed low-tension rope strings, like the [Thomastik Classic S](http://www.thomastik-infeld.com/family-detail/Classic%20S%20rope%20core).
Answer: This is not only about the neck. The pattern of bracing under the top, and the bridge plate under the top of your classical guitar, are designed to vibrate with and counteract the tension of nylon strings. Steel strings have twice the tension, so steel strings would cause the top of the guitar to warp upward, or "belly up" and eventually the bridge would rip loose from the top. This would destroy your guitar.
Comment: I understand that the frets are generally of softer material and will tend to get tore up by metal strings.
Answer: Classical guitar truss rods are not designed for steel strings - I learnt this as a child when my classical (with a truss rod) ended up with a bent rod and cracked neck.
Comment: I've never seen a classical guitar with a truss rod.
Answer: I did this once back in my younger years.  The guitar did sound awesome, but over time it destroyed the structure and integrity of the instrument.  I would not advise steel strings on classical guitar, unless you don't care about the instrument.  Try some hard tension nylon strings instead.
Answer: Another problem with adding steel strings to nylon string guitars comes in the form of "how far from the neck the string is." A steel string guitar has the string very close to the neck so that it is playable, whilst a nylon string guitar has it a fair way from the neck so that it plays louder. There is quite a bit of theory involved here, but in simple terms, the nylon string guitar that has steel strings on it, if it was able to cope with the forces, would be very hard to play and not sound great at all.
Comment: Or (what I do), you lower the fret 0 and the bridge. You reduce the tension all of you speak about (actually, you reduce the tension momentum, but that's it, no?) and the guitar survives for ages. Many Czech people do it because during the communist era, you didn't have many western guitars in the shops and people still wanted to play steel strings.
Answer: The key is the string tension being similar to nylon strings. This will mean that you will have to do some calculations to determine the proper gauge strings to produce the notes at the tension that is safe. This D'addarion web site should help you in your endeavor...
http://stringtensionpro.com/
Comment: Could you maybe explain how to use that website for this task?  This post was flagged as spam, and we generally discourage answers that primarily rely on a link.
Answer: The answer I have found works well is to use Newtone Heritage strings .010 to .043 gauge. These are  "normal" steel and  phosphor bronze  - low tension -
acoustic guitar strings and are hand wound in England. They have almost equal tension and although ultra-light gauge their total load is 94 lbs and therefore only slightly more than a set of low tension nylon strings. I have them on a lovely modern handmade Spanish guitar (Antonio Picado Model 49 2004) with a cedar top and Indian rosewood back and sides and the resulting sound is crisp and resonant -  lovely for fingerpicking and arpeggios and very loud - certainly louder than my Martin D18 GE though without the woody bass from the Mahogany back. Lots more finger room and works well with an LR Baggs classical under saddle pickup. A good classical guitar can be very loud even with nylon strings and is more so picked with just bare finger pads.
Of course I agree that this is something that should not be tried on a very old or valuable or treasured classical guitar or one with repairs and that there are risks but Newtone Heritage strings are designed for those older Martins without truss rods that re often heavily repaired  and they are loud and easy on these old fingers to.   If you don't mind accepting the slight risk of a 12% overload (surely within design limits of a modern classical guitar?) then this produces awesome sound and playability in my opinion. I would not however put them on my treasured 1970 Taurus (also made by Senor Picado I believe)  as it has already been driven over in its youth while on loan to my sister-in-law!
By the way, I have no connection with Antonio Picado or  Newtone Strings other than being a very satisfied customer of their Materclass, Heritage and Mandolin family strings!  They can be difficult to track down in the right gauges, presumably because they are different (being on round wound cores) and popular.
Ian Kirkland
Answer: As others have pointed out, this is probably a bad idea. If you still want to consider it, mind the string tension. A typical nylon strings set has a total tension of around 80 pounds. You definitely don't want to replace that with a typical acoustic steel set, which is almost double that.
Some electric guitar strings, e.g. D'Addario EXL130 or EXL120, are in a safer range (70-85 pounds). Still not sure how well they might work.
Answer: My workplace has a guitar I just used today - it has steel strings although it is a classical guitar. I noticed a couple of tuning pins already "loose" (spinning with no increase in tension on the string) and has very little volume or tone to the strings. Very hard on the fingers because of the height of the string. I would not recommend a normal set of steel strings on a classical, as people have already mentioned. It was tough to play and not particularly enjoyable either.
Not sure how long the strings have been on for - am thinking the problems suggest there is some damage to the guitar's structure. Now I'm wondering if putting nylon strings back on it will work? Will I break the neck taking the steel string off? I always replace one at a time, but the difference in tension will be very different. Any ideas?
Thank you and hope I answered, and am able to ask at the same time??
Comment: @K Morris if you want to ask a question, you can do it by clicking on the 'Ask Question' on the top right of the site. This space is for the answers to this question
Answer: I put some higher tension strings on my classical guitar, a Córdoba, and they were on for maybe less than a year and the bridge snapped off. There could have been other factors to this, but I imagine steel strings would be worse.
Answer: To answer the OP - the short answer (as others have aptly stated) is a big fat NO.   Don't do this.  You will ruin the guitar.
As do why you would want to do this - if you are looking for a wider neck than a standard acoustic (or electric) guitar you could look into acoustic models that have a wider neck.  This allows for the steel-string tonality while allowing for fingerings more like a classical.
Answer: Yes you can just put steel strings on a classical guitar if you really want to. They will of course create some structural and playing issues though.
The far greater string pressure on the classical guitar's plastic machine-head winder barrels will probably crack some of them fairly quickly, but they will still work.
The classical guitar's body, being constructed of much lighter/thinner woods and lighter wood bracing on the inside of the soundboard wont help either.
The soundboard top behind the bridge will rise to some degree ("bellying"), depending on the guitar. That will raise the height of the strings above the fretboard making it even harder to play and the string height will already be quite high.
The best thing to do would be to only tune the steel strings to a whole tone down from concert pitch "C", which would really lower the strain on the guitar's body. Put a capo just behind the second fret if you wish to play in concert pitch.


Determine all $ α \in \mathbb{R} $ for which every solution of $ y'' − (2 α − 1) y' + α (α − 1) y = 0 $ tends to $ 0 $ as $ t \to \infty $.

Question:
Problem. Determine all values of $ \alpha \in \mathbb{R} $ for which every
    solution of
    $$
  y'' − (2 \alpha − 1) y' + \alpha (\alpha − 1) y = 0
  $$
    tends to $ 0 $ as $ t \to \infty $.
Comment: all solutions are given by $$c_1 e^{(\alpha -1) t}+c_2 e^{\alpha  t}$$
Answer: To solve:
$$\text{y}''\left(t\right)−\left(2\cdot\alpha−1\right)\cdot\text{y}'\left(t\right)+\alpha\cdot\left(\alpha−1\right)\cdot\text{y}\left(t\right)=0$$
Use Laplace transform:
$$\mathcal{L}_t\left[\text{y}''\left(t\right)\right]_{\left(\text{s}\right)}−\mathcal{L}_t\left[\left(2\cdot\alpha−1\right)\cdot\text{y}'\left(t\right)\right]_{\left(\text{s}\right)}+\mathcal{L}_t\left[\alpha\cdot\left(\alpha−1\right)\cdot\text{y}\left(t\right)\right]_{\left(\text{s}\right)}=\mathcal{L}_t\left[0\right]_{\left(\text{s}\right)}$$
Now, use:

$$\mathcal{L}_t\left[\text{y}''\left(t\right)\right]_{\left(\text{s}\right)}=\text{s}^2\cdot\text{Y}\left(\text{s}\right)-\text{s}\cdot\text{y}\left(0\right)-\text{y}'\left(0\right)$$
$$\mathcal{L}_t\left[\left(2\cdot\alpha−1\right)\cdot\text{y}'\left(t\right)\right]_{\left(\text{s}\right)}=\left(2\cdot\alpha−1\right)\cdot\mathcal{L}_t\left[\text{y}'\left(t\right)\right]_{\left(\text{s}\right)}=\left(2\cdot\alpha−1\right)\cdot\left(\text{s}\cdot\text{Y}\left(\text{s}\right)-\text{y}\left(0\right)\right)$$
$$\mathcal{L}_t\left[\alpha\cdot\left(\alpha−1\right)\cdot\text{y}\left(t\right)\right]_{\left(\text{s}\right)}=\alpha\cdot\left(\alpha−1\right)\cdot\mathcal{L}_t\left[\text{y}\left(t\right)\right]_{\left(\text{s}\right)}=\alpha\cdot\left(\alpha−1\right)\cdot\text{Y}\left(\text{s}\right)$$
$$\mathcal{L}_t\left[0\right]_{\left(\text{s}\right)}=0$$

So, we get:
$$\text{s}^2\cdot\text{Y}\left(\text{s}\right)-\text{s}\cdot\text{y}\left(0\right)-\text{y}'\left(0\right)-\left(2\cdot\alpha−1\right)\cdot\left(\text{s}\cdot\text{Y}\left(\text{s}\right)-\text{y}\left(0\right)\right)+\alpha\cdot\left(\alpha−1\right)\cdot\text{Y}\left(\text{s}\right)=0$$
Solving $\text{Y}\left(\text{s}\right)$:
$$\text{Y}\left(\text{s}\right)=\frac{\text{y}'\left(0\right)+\text{y}\left(0\right)\cdot\left(1-2\cdot\alpha+\text{s}\right)}{\left(\alpha-\text{s}\right)\cdot\left(\alpha-1-\text{s}\right)}$$
Using inverse Laplace transform, gives us:
$$\text{y}\left(t\right)=e^{t\cdot\left(\alpha-1\right)}\cdot\left(e^t\cdot\left(\text{y}\left(0\right)+\text{y}'\left(0\right)\right)-\alpha\cdot\text{y}\left(0\right)\cdot\left(e^t-1\right)-\text{y}'\left(0\right)\right)$$
Comment: we did not cover Laplace


Load image from server on a UIImageView in phone

Question: I'm having a problem loading a remote image into a UIImageVIew...
It just doesn't show the image, may be i'm missing something...
I also use the described here but with the same results
How to load image from remote server on the UIImageView in iphone?
Can someone help me?
This is the code i'm using
Im getting the data from a xml and on the image element I have the full path
[[detailViewController detailImage] setImage:[UIImage imageWithData: [NSData dataWithContentsOfURL: [NSURL URLWithString: [NSString stringWithFormat:@"%@", [[promoList objectAtIndex: promoIndex] objectForKey: @"image"]] ]]] ];

With this code the image are displayed correctly
[[detailViewController detailImage] setImage:[UIImage imageWithData: [NSData dataWithContentsOfURL: [NSURL URLWithString: @"http://localhost/promos/preview/1.jpeg"]] ]];

Answer: Since the bottom example works as expected and besides the url string the example looks the same the problem should be with getting the url string. The problem is also that the code looks the same but it is quite hard to see. I would refactor the code to something like:
NSObject *urlObject = [[promoList objectAtIndex:promoIndex] objectForKey:@"image"];
NSString *urlString = [NSString stringWithFormat:@"%@", urlObject];
NSURL *url = [NSURL URLWithString:urlString];
NSData *imageData = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:imageData];

[[detailViewController detailImage] setImage:image];

Then you can debug the statement properly and make sure that you get what you expect after each step.
Update
To remove newline and tabs you can:
NSString *urlString = [NSString stringWithFormat:@"%@", urlObject];
urlString = [urlString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

If urlObject already is a string, which it should be, then you can do:
NSString *urlString = [urlObject stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

which would make it a bit cleaner.
Comment: I try it and get this on the summary column on the debugger at the urlObject and urlString at the end of the path "\n\t\n\n\t"
Answer: UIImage *img = [[UIImage imageWithData: [NSData dataWithContentsOfURL: [NSURL URLWithString:@"http://...."]]] retain];
if (img != nil)
{
    [imageViewName setImage:img];
    [img release];
}


Diagonal set definition

Question: Consider surjection
$f: N \rightarrow P,$ where $P$ is the power set of $N$.  Define set $D$, subset of $N,$ such that for all $n,$ $n$ is element of $D$ iff $n$ is not element of $f(n).$  Questions:

Is D a "legal" set within the restrictions of set theory?
What is an example of D?

Many thanks for any help, Agapito
Comment: Please use [MathJax](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference).
Comment: It's perfectly legal. Related: https://math.stackexchange.com/questions/2391576/a-function-that-maps-from-a-to-its-power-set/
Comment: By the way, this is on the way to proving that $f$ cannot be a surjection.
Answer: The definition
$$ D = \{ n\in N \mid n \notin f(n) \} $$
is perfectly valid in standard set theory -- that is, set theory based on the ZFC axioms. The Axiom of Separation (also known as the axiom of Specification or Subsets) guarantees that this expression describes a set that exists, whenever $N$ and $f$ exist.
There are non-mainstream set theories where this is not allowed -- in particular in NF set theory, the formula $n\notin f(n)$ is not allowed to appear inside a set builder, because it is not "stratified" (even though the formula is considered to be meaningful in itself).
But this is not something you need to worry about in ordinary mathematics, since that is always supposed to be formalizable in ZFC, rather than NF.

Examples: If $f$ is the function that maps every $n$ to $\{n\}$ then $D$ becomes the empty set. On the other hand, if $f$ is the function that maps everything to $\varnothing$, then $D$ becomes all of $N$.
Comment: Thank you very much for your help.  AM

Diagonal set definition


Finding all repeating points in a large set

Question: This is a programming question, but I believe there should be a related mathematical theorem, so sorry if it is not broad enough.
Given a large set of points $(X,Y)$ where $1 \le X \le 2000000$ and $1 \le Y \le 2000000$. How to find point or points that repeat $>2$ times. Without writing down every point in the set to mark down occurrences.
All set points are randomly distributed, except points that repeat, those occur multiple times in the set.
Normally it would be easy to spot those points putting each of them on the graph. However, since the set is very large and no visualization can be done I'm looking for a way to approximate a number of occurrences with some sort of reduction algorithm. So any related mathematical problem would be helpful.
Simplified question: Given a very list of integers $N$ where $1 \le N \le 2000000$ how to find one or more integers that are probably (with a confidence of $\ge90$%) most dominant in the list, without counting all occurrences of every number.
Suggested solution: if anyone stumbles onto similar problem - you can lookup probabilistic data structures for information how to deal with problems like this. Also this problem can be solved in naive way by the answer below.
Comment: What do you mean exactly by "without writing down every point"? If you don't look at every point in the list at least once, how can you be sure you have found all repeated ones?
Comment: There seems to be some important context for the problem that you are reluctant to share .  If you explained why "all repeating points" need to be found in fixed space memory, we might be able to advise you a little better.
Comment: The point is that random sampling will not tell you "what those points are." It will identify a _few_ of the repeating points and will completely miss most of them. Perhaps you are merely using words badly and not expressing the things you really want to say, but the things you _are_ saying are self-contradictory.
Comment: Pickiness about terminology:  The definition of a "set" is that there are no repetitions.  If you have a "list" or some other kind of collection that allows for repetitions, you should not call it a set.  This sounds like a problem motivated by programming since in a purely mathematical setting, knowing the collection means knowing how many repetitions of each point there are.
Comment: @hardmath - thanks, I will keep that in mind. The question is there any way to calculate repetitions without doing it manually (for example - taking a smaller list, calculating all repetitions and than approximating other repetitions by probability).
Comment: Your Question lacks precision.  From what you describe, there might be a set of points (no repetitions), or there could be one point repeated a thousand times (but all other points appear once), or every point might appear twice.  In most programming contexts one sorts the points (or whatever objects are given) and this reveals exactly how many points are repetitions.
Comment: @DavidK - I can look at every point at least once, but I cannot hold/write the state of each number. I'l put it another way - there is a book, I want to find words that repeats the most, I want to find an algorithm that would allow me to find those words by only writing small amount of information and reading the book. Or technically speaking - data set is way to big to put into RAM and I think some combinatorics can help me.
Comment: @hardmath - yes, I know, but this is exactly my problem - data lacks precision as well. In simple programming approach it would work exactly as you described, however I have never seen approach where memory required is < O(1). In this case I' trying to find an algorithm that would work without sorting entire data set. So I was thinking that there might be a way to approximate which points repeats usually (with degree of confidence based on statistics) and then scan list again to count only those points.
Comment: Why don't you 'hash' them by putting them in '$(x,y)$' buckets (round $x,y$ to 3 decimal places, for example). If you hit a bucket twice, keep track of it. Hashing is a fairly standard technique for looking for canonical forms.
Comment: @hardmath - sorry for being so vague. I do not want to make it too technical since this is a math forum. Maybe I should update my question. Problem I'm trying to solve is related to memory - standard machine has 8-16GB or RAM memory, now imagine that you need to process data in magnitudes of 1TB or more and there is no way to do in memory sort (because it would require $(2000000*4)^2*2$ bytes to store each value and number of repeats), performance is important and I do not want to write it back to disk. I want to determine probable repeating numbers and just count them in a second pass.
Comment: If there are _many_ repeated points, a random sample might give you a reasonable estimate of how many; I would not call this "finding all repeating points," however, since this does not tell you _which_ points repeat, so you have not "found" them. If the "words that repeat the most" repeat a very large number of times each, random sampling might give you a good list of candidates for "most repeated" word, but again this is not _all_ the repeated words, just the most-often repeated.
Comment: If you want to actually _identify_ all points that occur 2 or more times, you will somehow have to compare each point to most of the others, and with 1TB of data that will take a long time or a lot of memory or both.
Comment: @DavidK - thanks, I'm moving towards what you have described - random sampling. It is easy to know how many points there are, if I know what those points are. What I need is to find a way to determine abnormalities in the noise. After I know points that are abnormal I can just scan data again and count those points. Problem being is that abnormalities are too few to easily find them just by picking random region.
Comment: @copper.hat I thought about that already, unfortunately hash would not be balanced. Let's take for example $P(5,5)$ repeating 100 times in range $1..10000$, however in range $10000..20000$ there are more pairs of the same point or just more points in that region in general, so hash for $10000..20000$ will be hit more often.
Comment: There are not that many points, why not just code something up and try. You have a somewhat vague problem, but very specific objections to suggestions.
Comment: @DavidK - sorry if I'm not making sense. I've simplified question to better represent what I want. I do not see any contradictions. I think it is confusing, because I do not want exact precision, I'm looking for a way to prove with some confidence that a set of numbers statistically dominant in the list just by looking at a small part of that list.
Comment: @copper.hat I have updated question. There is no way to do that using hashes and I can explain in more details why if you want me to. This is the first thing I've tried when started looking into this. Simple programming solutions are not working here, that's why I'm hoping that there is some kind of statistical/combinatorical way of dealing with this.
Comment: The "contradiction" is that in your original question you refer to points that "repeat $> 2$ times," but in the "simplified" question you look for points that are "most dominant in the list." You have not defined what you mean by "dominant," but it does not seem consistent with points that merely occur $3$ times each. If "dominant" is really what you want, and if "dominant" means the point occurs in a significant percentage of all entries in the list, _not_ just "$> 2$," then you might be able to identify dominant points by sampling. What exactly makes a point "dominant"?
Comment: It's OK if the thing you first asked for is not what you really wanted, as long as in the end we're able to see unambiguously what it is you want.
Comment: Suppose your set consists of a whole lot of items, each occurring three times. Then all the input points will be output points, and you'll have to "write down all the points in the set", or at least a third of them (and the remaining 2/3 will all be points in the list you output as well, of course). If that kind of input isn't possible, you need to explain why. If it *is* possible, then it's clear your problem, as stated, has no solution. Help us help you by writing a clear and unambiguous problem statement. Here's one question: are the coordinates of your points all **integers**?
Comment: I'm voting to close, because the "simplified question" is even more vague than the original.
Comment: @DavidK - if all numbers in the list are unique and only one number repeats, then that number is dominant, even if that number repeats only two times. Imagine scattering numbers in the way that each integer value is a point on $X$ axis, now each time that specific integer repeats we put it it on $Y$ axis. Creating a function $f(n)=timesRepeats(n)$. Looking at such plot it would be very easy to tell which numbers are dominant. After that I would need to pick $MAX(Y)$ value and find $X$ for that.
Comment: @JohnHughes - it seems hardmath understand the question pretty well
Comment: "if all numbers in the list are unique and only one number repeats, then that number is dominant, even if that number repeats only two times." Well, then, you are out of luck, my friend. Is it not obvious that there is no way to find that number (and to know that there's no other that has 3 repetitions) without looking at every number in the list (or at least a large majority of them)? Look for ways to process lots of data fast. hardmath's answer is a good start.
Comment: @JohnHughes to answer your question above (if you still interested) - output should not be the points, output should be reduced only to points that repeat. so for $[(1,1), (2,9), (5,2), (1,1), (9,6),(2,9)]$ output would be $[(1,1), (2,9)]$. I was not clear what does it mean *most dominant*, because there is no specific threshold, I'm interested in divergence from normal, so if all points repeats two times and one point repeat 3 times - that's the point I need, to put is simply point that repeats in data stream more often then all others. And yes, all numbers are integers.
Answer: I think the best you can do (with two or three passes) is to create a number of "bins" that cover your set of points.  For example, we might think in terms of the original universe $[1,\ldots,20000000]\times [1,\ldots,20000000]$ being subdivided into subsets of a convenient form.
Ideally your 1Tbyte of data would be partitioned into (say) one hundred 10Gbyte subsets.  If the subsets are defined by (say) cartesian bounds $S_{i,j} = [x_i,x_{i+1})\times [y_j,y_{j+1})$, then any repetitions that occur will necessarily occur within one of these subsets.
Now each subset is constructed to fit within your PC's memory, where an efficient sorting algorithm can identify all the repeated elements.
If the points are known to be distributed more or less uniformly throught the "universe", something like the optimal partition of the universe will be easily precomputed.  If the distribution is not uniform and not much information is available apriori about the distribution, then an approach in which we adaptively define the partition might be attractive.
Many ways of partitioning the universe will serve our purpose, as the only real requirement is that repeated points will be assigned to the same bin.
Comment: If the memory size is large enough to store $k$ points, and the original input has $n$ points, and $s = \lceil \frac{n}{k} \rceil$, then this will require approximately $s^2$ passes over the input points, one to extract each subsquare, so the runtime looks like $s^2 k \ln k$, which is still $O(n^2)$, which is hardly suprising. (Esp. since, per my comment on the question, the output might have size that's $O(n^2)$.)
Comment: @JohnHughes:  The Question doesn't ask us to compare each pair of points and report the result of those comparisons.  Instead we are asked to identify all repeated items (and if later requirements are credited, to report the number of such repeats).  Perhaps you can give an example of how the output could be much larger than the input?
Comment: @JohnHughes:  Perhaps I failed to clearly state that each bin into which points are placed will by construction contain any duplicates of points in that bin.  We can place points in their assigned bins with a single pass once the boundaries are set.  These "hundred bins" in the case I sketched can be files on disk.  So there is no comparison between pairs of bins, as your Comment outlines.
Comment: Suppose the set contains 1,1,1, 2,2,2, 3, 3, 3, ..., 1000, 1000, 1000 etc. Then we have to report repeats at $1, 2, 3 ... 1000$, i.e., at 1/3 of the points. (I'm showing the example in 1D, but it clearly works in 2D as well).  I don't know what I was thinking when I wrote $O(n^2)$ -- sorry about that. I was assuming that the dataset was *very* large (think of the old days: the dataset lives on tape, for instance), and on a medium so slow that random-access writing to it isn't feasible (again, tape). Then to extract each subsquare requires re-reading the input tape.
Comment: Hence there are $s^2$ passes over the data, one to extract each bin. Sorting the bin of size $k$ takes time $k \ln k$, and from that you can find all duplicates (in that bin; as you observe, any duplicate pair must lie in one bin). BTW, I like your algorithm, and think it's completely reasonable -- I was just pointing out to OP that the runtime analysis still has an $n^2$ if your storage medium either isn't large enough for two copies of the data, or doesn't have a constant time random access.
Comment: @JohnHughes:  All the bins are extracted in a single pass.  To give a simple example, the highest order digit of $X$ and the highest  order digit of $Y$ are used to determine a file `BINxy.DAT` that each point is written to as it is read.  This would work okay if the data is fairly uniformly distributed, but problems will arise if the distribution is lopsided.  Lowest order digit would also work.
Comment: Thanks @hardmath - I think this is not a math question. I'm pretty sure now that problems like these should be solved using *probabilistic data structures* (I will update my question to reference other people). Although you answered in the way that would work (I think) but not necessarily using the best approach for this problem, I still will mark your response as an answer since it more or less provides working solution for this problem.
Comment: Sure, and you could also use something like a universal hashing scheme to avoid dependence on the input distribution. I understood that, **given enough memory**, you could extract all bins in one pass; if memory is limited, then you're in multipass land. As David K observes, the problem turns out to be "find the most frequently occurring value(s)," and I suspect, like David K, that this cannot be done "fast" (certainly not in sublinear time) for inputs where there are only one or two repetitions. Hashing and looking for fullest buckets does it in linear time, of course, but OP dislikes that.


Python hangs when running in a conda env on git bash

Question: I want to use my conda environment in gitbash.
I have add my conda.sh path in my ~/.bashrc. This is correctly recognized as I can now run conda activate and the base environment will be activated. Now I can run command such as pip install jupyterlab and it will correctly run. However, when I type python the terminal just hangs indefinitely. which python correctly returns /c/Users/valer/anaconda3/python. Similarly, the Anaconda Prompt returns to where python: C:\Users\valer\anaconda3\python.exe
If I type python through the Anaconda Prompt it works normally.
Any idea?
Answer: I have the same problem. In addition to your story, I'm able to run scripts.
So, this hangs:
$ python

But this works:
$ python script.py

Comment: Hi, I did find a workaround in the meantime. Try running `winpty python.exe`. That works for me. Of course you can alias it in the `.bashrc`. Let me know!
Comment: Could you tell us why the second one works?
Comment: I guess that the second one works, because it doesn't use the python shell. I think the python shell doesn't support Git Bash and using winpty fixes that. However, I'm not an expert on this matter.
Answer: As @Vaaal88 suggest, add alias python='winpty python.exe' to your ~/.bash_profile (or ~/.bashrc in older versions of git bash)
My ~/.bash_profile looks like:
alias python='winpty python.exe'

# >>> conda initialize >>>
# !! Contents within this block are managed by 'conda init' !!
if [ -f '/c/Users/hugo/miniconda3/Scripts/conda.exe' ]; then
    eval "$('/c/Users/hugo/miniconda3/Scripts/conda.exe' 'shell.bash' 'hook')"
fi
# <<< conda initialize <<<


Entity Framework Update Key

Question: <code>[Table("tblClients")]
public class ClientsTbl
{
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int ClientID { get; set; }
    [Key]
    public int userid { get; set; }
}
</code>
If i have old data (from unknown source) to import which has userid that related with other tables for example invoice etc without using Foreign Key, how can i design my DB model?  If i would design like that insert must be like that :
<code>Random a = new Random();
ClientsTbl c = new ClientsTbl()
{
    userid = a.Next(-1000, -1),
}
dataContext.Clients.Add(c);
dataContext.SaveChanges();
var client = dataContext.Clients.FirstOrDefault(x => x.userid == c.userid);
if(client!=null)
{
    client.userid = c.ClientID;
}
dataContext.SaveChanges();
</code>
after inserting a record I need to update "userid" : ``  And it gives an error

The property 'userid' is part of the object's key information and cannot be modified.

If i would change all operations to Stored Procedure's (insert and update) everything is ok.
Why Entity Framework doesn't allow to update Key ? (Sql server does)
Answer: This is due to the fact that you're referencing the same object. This has been asked before and answered here:
The property 'Id' is part of the object's key information and cannot be modified
I hope this helps you.
Comment: There is no Foreign Key in my problem. And your link doesn't include reliable solution to this problem.
Only way to pass this , using stored procedure. (I think, because i solved by this way)
Answer: OO paradigm has this thing about "object identity".  RM does not have this (not in the sense that every identifier of a thing MUST MANDATORILY remain unchanged during the whole lifetime of the thing it identifies).
Tools that attempt to bridge the gap between the two are therefore inevitably faced with a kind of mismatch, and must do one of two things to address it : (a) break the OO paradigm of cast-in-concrete-immutable identity, or (b) enforce the OO paradigm and rule out perfectly legitimate RM operations.
Most if not all of them opt for (b) because that is the easiest way out, at least for the developers.
Comment: I think there isn't any philosofic problem. Very simple. EF is an object and it's rule to respect. Stored procedure is very good solutions. In fact i dont like to use EF but some security limitations force us to use EF.
I just wonder ıs there a eficient solutions.
Anyway many thanks your great answer.

Entity Framework Update Key


Combining modular congruencies

Question: I'm trying to work through the PuMaC 2016 a-division algebra contest, but I'm having trouble understanding the solution for #4.
The solution shows that there is an integer $N$ where

$N = 2 \pmod{2015}$
$N = 3 \pmod{2014}$
$N = 3 \pmod{2013}$

Then it skips to
$N = 3 + 1007 \times 2013 \times 2014 \pmod{2013 \times 2014 \times 2015}$
I'm just a bit confused how they got to that step? If I didn't add enough detail to my question, here's the contest archive I got it from: https://jason-shi-f9dm.squarespace.com/archives/#2016
Thanks in advance!
Answer: $N=3+\lambda\times2013\times2014$ clearly satisfies two of the equations. You then need $$2=3+\lambda\times2013\times2014\pmod{2015}$$$$2014=\lambda\times(-2)\times(-1)\pmod{2015}$$
Therefore $\lambda=1007$ is a solution.

Combining modular congruencies


Kalman Filter alternative derivation

Question: Take a state space model of the form
$y_t=\alpha_t+\epsilon_t$ where $\epsilon_t\sim NID(0,\sigma_{\epsilon}^2)$
$\alpha_{t+1}=\alpha_t+\eta_t$ where $\eta\sim NID(0,\sigma_{\eta}^2)$
Futhermore, it is assumed that $E(\epsilon_t\eta_s) = 0$, for all $t,s$, that is, the error terms are independent. More, error tersma re also independent of $\alpha_1$, the initial state.
I do not get why we would apply this restrictive assumption for the Kalman Filter when we could easily estimate other parameters via MLE. For instance, suppose that $\mathbb{C}ov(\epsilon\eta) = I\sigma_{\eta,\epsilon}$ so that $E(\epsilon_t\eta_s) = 0$ for all $t\neq s$ and $E(\epsilon_t\eta_s) = \sigma_{\eta,\epsilon} \neq 0$.
We are interested in estimating $a_{t+1}=\mathbb{E}(\alpha_{t+1}|Y_t)$ and $P_{t+1}=\mathbb{V}ar(\alpha_{t+1}|Y_t)$, where $Y_{t}=(y_1,y_2,...,y_t)'$. Furthermore, I follow Durbin and Koopman textbook in that $a_{t|t}=\mathbb{E}(\alpha_{t}|Y_t)$ and $P_{t|t}=\mathbb{V}ar(\alpha_{t}|Y_t)$.
Now, $a_{t+1}=\mathbb{E}(\alpha_{t+1}|Y_t) =\mathbb{E}(\alpha_{t}+\eta_t|Y_t)=\mathbb{E}(\alpha_{t}|Y_t)=a_{t|t}$ and $P_{t+1}=\mathbb{V}ar(\alpha_{t+1}|Y_t)=\mathbb{V}ar(\alpha_{t}+\eta_t|Y_t)=\mathbb{V}ar(\alpha_{t}|Y_t) + \mathbb{V}ar(\eta_{t}|Y_t) + 2 \mathbb{C}ov(\eta_t,\alpha_t|Y_t)=P_{t|t}+\sigma_{\eta}^2+2 \mathbb{C}ov(\eta_t,\alpha_t|Y_t)$.
Under independence, $\mathbb{C}ov(\eta_t,\alpha_t)=0$. However, under my assumption, $\mathbb{C}ov(\eta_t,\alpha_{t-1}+\eta_{t-1})=\mathbb{C}ov(\eta_t,y_t-\epsilon_t)=\mathbb{C}ov(\eta_t,-\epsilon_t)=-\sigma_{\eta,\epsilon}$, leading to:
$P_{t+1}= P_{t|t}+\sigma_{\eta}^2-2\sigma_{\eta,\epsilon}$.
Now, since all distributions are normal, $P_{t+1}$ and $a_{t+1}$ are easily found if we find the expression for the pdf of $\alpha_{t}|Y_t$ - name it $f(\alpha_{t}|Y_t)$. Then,$f(\alpha_{t}|Y_t)=f(\alpha_{t}|Y_{t-1},y_t)=\frac{f(\alpha_{t},y_t|Y_{t-1})}{f(y_t|Y_{t-1})}=\frac{f(\alpha_{t}|Y_{t-1})f(y_t|Y_{t-1},\alpha_{t})}{f(y_t|Y_{t-1})}$.
Since these pdf's are fully defined by their 1st and 2nd moments, we just need to compute those as:
$\mathbb{E}(y_t|Y_{t-1})=\mathbb{E}(\alpha_t+\epsilon_t|Y_t)=a_t+0=a_t$
$\mathbb{V}ar(y_t|Y_{t-1})=\mathbb{V}ar(\alpha_t+\epsilon_t|Y_t)=\sigma_{\epsilon}+P_{t|t}$
$\mathbb{E}(y_t|Y_{t-1},\alpha_t) = \alpha_t$
$\mathbb{V}ar(y_t|Y_{t-1},\alpha_t) = \sigma_{\epsilon}$.
Substituting in the pdf's above and computing yields:
$f(\alpha_t|Y_t)=N(a_t+\frac{P_t}{P_t+\sigma_{\epsilon}^2}v_t,\frac{P_t\sigma_{\epsilon}^2}{P_t+\sigma_{\epsilon}^2})=N(a_{t|t},P_{t|t})$, where I define $v_t=y_t-a_t$, from which it follows that:
$a_{t+1}=a_{t|t}=a_t+\frac{P_t}{P_t+\sigma_{\epsilon}^2}v_t$
and
$P_{t+1}=P_{t|t}+\sigma_{\eta}^2-2\sigma_{\eta\epsilon}=\frac{P_t\sigma_{\epsilon}^2}{P_t+\sigma_{\epsilon}^2}+\sigma_{\eta}^2-2\sigma_{\eta\epsilon}$
Then, the Kalman Filter becomes,
$v_t = y_t-a_t$
$F_t = \mathbb{V}ar(v_t|Y_{t-1})=P_t+\sigma_{\epsilon}^2$
$a_{t|t}=a_t+K_t v_t$
$P_{t|t}=P_t(1-K_t)$
$a_{t+1} = a_{t|t}$
$P_{t+1} = \frac{P_t\sigma_{\epsilon}^2}{P_t+\sigma_{\epsilon}^2}+\sigma_{\eta}^2-2\sigma_{\eta\epsilon}$ for $t=1,...,n$ and $K_t = P_t/F_t$ denotes the Kalman Gain. Then $\sigma_{\eta\epsilon}$ could be estimated via MLE together with the other hyperparameters $\sigma_{\eta}$ and $\sigma_{\epsilon}$.
Does this make sense or am I missing something here? Assuming the derivation is correct, would there be any disadvantage of estimating $\sigma_{\eta\epsilon}$ via MLE?
Thanks
Comment: If you take the trouble to write $\mathbb{V}ar$, then $\text{Var}$ or $\mathbb{V}\text{ar}$ (where "ar" is nonitalicized) would be another step ahead.
Comment: I thought that would not be confusing. I will be more careful next time.
Comment: No, it is not confusing at all, it is just a matter of consistency of mathematical typing.
Answer: You are right in that the covariance parameter could be estimated by maximum likelihood. However, care is needed because including this additional parameter may lead to a problem of identification of the parameters.
For example, let's take the local level model defined as follows:
\begin{align}
&y_t = m_t + \epsilon_t \,, &\epsilon_t \sim NID(0, \sigma^2_\epsilon) \\
&m_t = \mu + m_{t-1} + \eta_t \,, &\eta_t \sim NID(0, \sigma^2_\eta) \\
&E(\epsilon_t \eta_s) = \sigma_{\epsilon\eta} &\hbox{ if } t = s \hbox{ and } 0 \hbox{ otherwise} \,.
\end{align}
It can be checked that the autocovariances of this model are:
\begin{align}
\gamma(0) &=  2\sigma^2_\epsilon + \sigma^2_\eta + 2\sigma_{\epsilon\eta} \\
\gamma(1) &= -\sigma^2_\epsilon - \sigma_{\epsilon\eta} \\
\gamma(k) &= 0 \,, \quad \hbox{for } k > 1 \,.
\end{align}
Given the sample autocovariances $\gamma(k)$, there is no unique solution to the system of equations, since we have two equations to be solved and three parameters ($\sigma^2_\epsilon$, $\sigma^2_\eta$ and $\sigma_{\epsilon\eta}$).
The common restriction $\sigma_{\epsilon\eta} = 0$ can therefore be interpreted as an identifying restriction.

Morley et al. (2003) [1] is an interesting discussion on this issue in the field of economics. The authors fit a model consisting of a trend and a stationary cycle with and without the zero-correlation restriction between the components.
[1] James C. Morley, Charles R. Nelson and Eric Zivot (2003).
"Why Are the Beveridge-Nelson and Unobserved-Components Decompositions of GDP so Different?". The Review of Economics and Statistics. Vol. 85, No. 2.
URL http://research.economics.unsw.edu.au/jmorley/mnz03.pdf.
Comment: Thank you javlacalle! Very useful. Other question, is the derivation of the Kalman filter above correct?
Comment: I would say that the Kalman filter does not require any modification.
You could define a relatively large value for the covariance matrix of the initial state vector (instead of setting zeros outside the diagonal). Apart from this, the standard Kalman filter could be used.
Comment: I don't get your point.  As I see it, we do not need to set the covariance matrix of the initial state vector to zeros outside the diagonal. Under the assumptions of the model, they happen to be zero. But I can run a KF for this simple local level model without ever computing the non-diagonal terms. It looks just like the KF I wrote above but in the last expression for P_{t+1} the \sigma_{\eta\epsilon}^2 drops.
Comment: In other words, either we assume that the state and measurement disturbances are independent or not. If not, I argue that the expression for P_{t+1} used in the recursion (and therefore the confidence intervals around the state estimates will change). Would you then say that this is wrong?
Comment: That's what I said, *instead of setting zeros*, you will need to decide
how to initialise the values outside the diagonal (for example, by setting
a large value to them, reflecting the uncertainty in the covariance matrix). Apart from that, I would say that the standard equations of the Kalman filter would apply.
Comment: But anyway, I did not look deep into it, you may be right. I just wanted to point out the reason why the covariance parameter is usually restricted to zero.

Kalman Filter alternative derivation