Looping over lenses, and using each with view and set

Question: This is a version of some code I have been working on, with the specifics removed. Hopefully it's clear what I'm trying to do, but if not I can clarify. I'm quite new to using lenses, and the complicated types involved often make them seem more trouble than they're worth.
-- some data type
type AType = ...

data Thing = Th { _v, _w, _x :: AType, _otherStuff :: ... }

makeLenses ''Thing

-- some operation that can be performed on corresponding x or w or v values in two Things.
f :: AType -> AType -> AType
f = ...

-- apply f to the corresponding v, and w, and x values in a and b; then store each result in the respective field of a, leaving other fields untouched.
transform :: Thing -> Thing -> Thing
transform a b =
    let transformVorWorX :: Lens' Thing AType -> AType
        transformVorWorX lens =
            let vwx  = view lens a
                vwx' = view lens b
            in  f vwx vwx'

    in  foldl (\a' lens -> set lens (transformVorWorX lens) a') a [v,w,x]

When I compile, ghc spits out
Could not deduce (f ~ Identity)
from the context (Functor f)
  bound by a type expected by the context:
             Functor f => (AType -> f AType) -> Thing -> f Thing
  at ...
  'f' is a rigid type variable bound by
      a type expected by the context:
        Functor f => (AType -> f AType) -> Thing -> f Thing
      at ...
Expected type: (AType -> f AType) -> Thing -> f Thing
  Actual type: ASetter Thing Thing AType AType
In the first argument of 'transformVorWorX', namely 'lens'
In the second argument of 'set', namely '(transformVorWorX lens)'

Why doesn't this code work? I found that replacing lens with cloneLens lens lets it compile, but I'm not sure why, and this feels very ugly - is there a more elegant way to do what I want, that is perhaps more general?
Many thanks
Answer: Lens' is under the hood universally quantified
type Lens' s a = ∀ f . Functor f => (a -> f a) -> s -> f s

So the type of [v,w,x] would have to be
[∀ f . Functor f => (AType -> f AType) -> Thing -> f Thing]

– with a quantor inside the list. Such types are called impredicative types, and Haskell doesn't support them. (A GHC extension with that name has been around for a while, but it doesn't work.) [Edit: work on impredicatives is ongoing as of 2021.]
There's a relatively easy way that always works to get around this: hide the quantor in a newtype. In the lens library, this is ReifiedLens. With it you can write
transform a b =
    let transformVorWorX :: ReifiedLens' Thing AType -> AType
        transformVorWorX (Lens lens) =
            let vwx  = view lens a
                vwx' = view lens b
            in  f vwx vwx'
    in  foldl (\a' lens -> set (runLens lens) (transformVorWorX lens) a') a
            [Lens v, Lens w, Lens x]

This code has exactly the runtime behaviour of the one you envisioned, but it's clearly pretty ugly.
The alternative solution you've discovered yourself does effectively the same thing too but is rather nicer. To see what's actually going on there, I'll put the cloneLens within transformVorWorX:
transform a b =
    let transformVorWorX :: ALens' Thing AType -> AType
        transformVorWorX lens =
            let vwx  = view (cloneLens lens) a
                vwx' = view (cloneLens lens) b
            in  f vwx vwx'
    in  foldl (\a' lens -> set (cloneLens lens) (transformVorWorX lens) a') a [v,w,x]

The reason this works is that, like ReifiedLens – but unlike Lens – ALens' has no quantor. It is just a concrete instantiation of the Functor f, thus it doesn't require impredicativity but you can directly use v, w and x in a [ALens' Thing AType] list. The functor instance is cleverly chosen to not lose any of the generality, hence cloneLens is able to give you back a full, universally-quantised lens.
Rather than cloning it, you can also use the ^# operator, which directly views an ALens, and storing instead of set:
transform a b =
    let transformVorWorX :: ALens' Thing AType -> AType
        transformVorWorX lens =
            let vwx  = a^#lens
                vwx' = b^#lens
            in  f vwx vwx'
    in  foldl (\a' lens -> storing lens (transformVorWorX lens) a') a [v,w,x]

If we condense that to a less verbose form, it looks quite good IMO:
transform a b = foldl updater a [v,w,x]
 where updater a' lens = a' & lens #~ f (a^#lens) (b^#lens)

Let me also suggest an entirely different solution: you define a single optic that accesses all the values of interest, namely
vwx :: Traversal' Thing AType
vwx f (Thing в ш к otherVals)
    = (\в' ш' к' -> Thing в' ш' к' otherVals)
      <$> f в <*> f ш <*> f к

Instead than defining this yourself, you can also let the Template Haskell helper do it for you:
makeLensesFor [("_v", "vwx"), ("_w", "vwx"), ("_x", "vwx")] ''Thing

Now, a traversal can be used as a simple fold, and thus to get a list of all the values. You can then use a standard zip to perform the transformation of the elements:
transform a b = ...
 where tfmedVals = zipWith f (a^..vwx) (b^..vwx)

To put that list of modified values back in a container, the library has also a function: partsOf. And with that, your entire transformation boils down to
transform a b = a & partsOf vwx .~ zipWith f (a^..vwx) (b^..vwx)

Comment: It appears that I missed your answer back in 2017. But thank you. I hope it has helped someone else. I must admit Lenses are still mysterious to me, these days I am on the dark side doing C++...


Is a power of an inverse gamma random variable itself inverse gamma?

Question: If $X$ is an inverse gamma distributed random variable, then would $X^p$ also be distributed as inverse gamma?
I found someone asked about the square root of inverse gamma, but I didn't find a direct answer to that question.
Answer: The short answer is no, in general a power of an inverse gamma random variable is not itself distributed as inverse gamma.
This can be seen by directly computing the distribution of the transformed random variable.
In what follows, I'll assume $p>0$.
With the transformation $Y = X^p$ we have $f_Y(y)= f_X(y^{1/p}) \left|\frac{d y^{1/p}}{dy}\right|$.
If
$$f_X(x) \propto x^{-(\alpha+1)} \exp(-\beta/x); \quad x>0, \alpha,\beta>0\,,$$
then (if I didn't make a mistake somewhere)
$$f_Y(y) \propto y^{-(\alpha/p) -1} \exp(-\beta/y^{1/p}) ; \quad y>0, \alpha,\beta>0\,.$$
As you see, because of the power of $y$ in the $\exp$ term, the result isn't inverse-gamma. Indeed, at least for some values of $p$, it looks like it's a particular case of what Mathematica calls the Generalized Inverse Gamma (see here, scroll down 2/3 of the page), with shift-parameter $\mu=0$ and second shape parameter $\gamma$ related to $p$.


How to retrieve information of autocovariance from autocovariance generating function?

Question: My lecturer introduced the concept autocovariance generating function (ACGF) of a stationary process in class.
$G(L) = \sum_{k = -\infty}^{+\infty} \gamma_kL^k$ [1]
$\gamma_k$ is autocovariance at k-th lag.
She also mentioned that we can retrieve information of $\gamma_k$ from this by differentiating this polynomial k times then evaluate the derivative at $L = 0$. Finally, divide the result by $k!$.
However, I think it is mathematically wrong as it is not possible to evaluate the derivative at $L = 0$ at any term $L^k$ where k is negative. It is possible that she mentioned another kind of ACGF which is $G(L) = \sum_{k =
 0}^{+\infty} \gamma_kL^k$. Am I correct?
Furthermore, I want to know how I can retrieve information about autocovariance from the first ACGF. I can do it by deriving the spectral density function from ACGF. However, I want to know if there is another way to do it.
Answer: Turning comment to answer.

If $ \langle\gamma_j\rangle_{j =-\infty}^\infty$ is absolutely summable, then the autocovariances can be summarized using a scalar-valued function, the acv generating function $$g_Y(z) := \sum_{j =-\infty}^\infty \gamma_jz^j.$$
If the linear process is $Y_t = \psi(B) \varepsilon_t,$ then acv generating function can be shown to be
\begin{align} g_Y(z) &= \sum_{j =-\infty}^\infty \gamma_jB^j\\ &= \sigma^2\psi(B) \psi(B^{-1}) ;\end{align} $\gamma_j$ can be found out by observing the coefficient of $B^j$ (also $B^{-j}$) .
Since the process is absolutely summable, one can also resort to population spectrum $$ s_Y(\omega) = \frac{1}{2\pi} \sum_{j =-\infty}^\infty \gamma_j\exp(-i\omega j) $$  to retrieve the acv s.

Reference:
Time Series Analysis, James D. Hamilton, Princeton University Press, 1994.
Comment: Derivation for the auto covariance generating function https://stats.stackexchange.com/questions/636494/the-logic-behind-the-derivation-of-the-autocovariance-generating-function?noredirect=1&lq=1


function which is Riemann integrable

Question: Consider $f:[-1,1]\to\mathbb{R}$, $x\mapsto \begin{cases}
  1,  & \text{if } x=0 \\
  0 & \text{else }
\end{cases}$ I want to know why f is Riemann integrable and I tried something. First of all we had the definition in lecture: $\int_{-1}^{1^*} f(x)\,dx=inf\{\int_{-1}^1 \phi(x)\,dx;\phi:[-1,1]\to\mathbb{R} \;\text{step function}, f\le\phi \}$ and $\int_{-1^*}^{1} f(x)\,dx=inf\{\int_{-1}^1 \phi(x)\,dx;\phi:[-1,1]\to\mathbb{R} \;\text{step function}, \phi\le f \}$. Now the bounded function f is Riemann integrable, if $\int_{-1}^{1^*} f(x)\,dx=\int_{-1^*}^{1} f(x)\,dx$.
My first try: consider the step function $\phi:[-1,1]\setminus\{0\}\to\mathbb{R},\; x\mapsto 0$. It is $f=\phi$ everywhere on $[-1,1]\setminus \{0\}$. Therefore it is
$\int_{-1}^{1^*} f(x)\,dx=inf\{\int_{-1}^1 \phi(x)\,dx;\phi:[-1,1]\to\mathbb{R} \;\text{step function}, f\le\phi \}=\int_{-1}^{1} \phi(x)\,dx=0$ and $\int_{-1^*}^{1} f(x)\,dx=\int_{-1}^{1} \phi(x)\,dx=0$. Therefore f is Riemann-integrable and $\int_{-1}^{1} f(x)\,dx=0$. Could you help me, to correct my solution?
I'm not sure if it is ok, because my step function isn't defined in $x=0$. But we say that $\phi:[-1,1]\to\mathbb{R}$ is a step function if you have a partition of the interval $[-1,1]$, $x_0=-1<x_1<..<x_n=1$, such that $\phi_{|(x_{i-1},x_i)}=c_i\in\mathbb{R}$ for $i=1,..,n$.
Maybe I have to define $\phi$ in $x=0$ too but take $x=0$ as one of the $x_i's$.
I will try next to do this with Riemann Sums. Regards
Comment: instead of doing this with your hands, you can prove that the Riemann Integral does not change it's  value if you change the function in one point (in fact you can do this for countably many point's)  and then you can see that your $f$ is the constant function zero, with the changing one point at zero.
Comment: Well a function $f: [a,b] \to \mathbb{R}$ is Riemann integrable iff it is bounded and the set of discontinuity points is a zero set (Riemann-Lebesgue Theorem).
Comment: yes, thanks. but I don't know the theorem from lecture and I want to know if it is correct what I have tried
Answer: Fix $1> \epsilon > 0$, and consider the step function
$$
\varphi(x) = \begin{cases}
1 &: -\epsilon \leq x \leq \epsilon \\
0 &: \text{ otherwise}
\end{cases}
$$
Then
$$
\int_{-1}^1 \varphi(x)dx = 2\epsilon
$$
Hence
$$
\int_{-1}^{1^{\ast}} f(x)dx = 0
$$
Now for any step function $\psi \leq f$, then choose a partition $-1 < x_1 < x_2 < \ldots < x_n = 1$ and constants $c_i$ such that $\psi = c_i$ on $(x_{i-1},x_i)$. Now consider the two cases

$0 = x_i$ for some $i$ or
$0 \in (x_{i-1},x_i)$ for some $i$

In either case, prove that
$$
\int_{-1}^1 \psi(x)dx \leq 0
$$
Since the constant function $0 \leq f$ is a step function, it follows that
$$
\int_{-1^{\ast}}^{1} f(x)dx = 0
$$
and so $f$ is Riemann integrable.
Answer: A piecewise constant function lies below $f$ if and only if it is nonpositive everywhere. So the supremum of the lower sums of $f$ is zero. Among piecewise constant functions lying above $f$, for any $\delta>0$ we have a function which is $1$ on $[-\delta,\delta]$ and zero elsewhere. The integral of this function is $2 \delta$, which can be made arbitrarily small, so the infimum of the upper sums of $f$ is also zero. We have checked the Darboux criterion for integrability.
What might be left to prove is that the Darboux definition is equivalent to your original definition of Riemann integrability.
Comment: thank you! If I compare, it wasn't enough what I have done. Thanks

function which is Riemann integrable


Protecting post routes NodeJS

Question: I am working on a nodeJS application. So far i've learned you can protect routes with JWT and i've implemented this. The problem is, I am not sure how to protect a route where the user is allowed to post to.
Let's take a register route for example, this route will be used for user registration. I want users to be able to post to this, BUT only from my application. I dont want anyone to just be able to connect to it via postman and post whatever. How do you protect these kind of routes.
Thanks in advance.
Answer: You can use CORS middleware to allow only specific clients to access your server https://expressjs.com/en/resources/middleware/cors.html
Example:
<code>var express = require('express')
var cors = require('cors')
var app = express()

var corsOptions = {
  origin: 'http://example.com',
}

app.get('/products/:id', cors(corsOptions), function (req, res, next) {
  res.json({msg: 'This is CORS-enabled for only example.com.'})
})

app.listen(80, function () {
  console.log('CORS-enabled web server listening on port 80')
})
</code>

Protecting post routes NodeJS


GROUP BY with MAX()

Question: I am new to sql and I have a problem to resolve so i need some help please
For example, during the week 04/2019, 720 mutations are missing compared to the real information
In fact the problem comes from query . Indeed in this one a group by CODE_COMMUNE and NOM_SITE is made and the value MAX of the fields is returned for this commune and this site. This means that when there are several mutations on the same site of the same commune, only one mutation is returned, which explains the missing mutations.
So i would like to return all the mutation on the same site of the same commune.
How can i do that ?
<code>`select IPO_VILLE.CODE_COMMUNE,
   IPO_SITE.NOM_SITE,
     MAX(IPO_AT.DATE_MUTATION) DATE_MUTATION,
     MAX(IPO_AT.IAR_NDFICTIF) IAR_NDFICTIF,
     MAX(IPO_AT.MUTATION_REALISEE_PAR) MUTATION_REALISEE_PAR,
     MAX(IPO_AT.CAUSE_MUTATION) CAUSE_MUTATION,
     MAX(IPO_AT.CODE_BASICAT) CODE_BASICAT,
     MAX(IPO_AT.PIGTAIL_FIBRE_CONN_COURANT) FIBRE_COURANT,
     MAX(IPO_AT.PIGTAIL_FIBRE_CONN_CIBLE) FIBRE_CIBLE,
     MAX(IPO_AT.NOM_PB_COURANT) NOM_PB_COURANT,
     MAX(IPO_AT.NOM_PB) NOM_PB_CIBLE,
     MAX(IPO_AT.NOM_PM_COURANT) NOM_PM_COURANT,
     MAX(IPO_AT.NOM_PM) NOM_PM_CIBLE,
     MAX(IPO_AT.INTERVENTION_NUMBER) INTERVENTION_NUMBER,
     MAX(IPO_AT.GPC_BASE) GPC_BASE
from EDRPRE.IPO_AT IPO_AT
left join EDRPRE.IPO_LOGEMENT IPO_LOGEMENT ON IPO_AT.OBJECTID_LOGEMENT = IPO_LOGEMENT.OBJECTID_LOGEMENT
left join EDRPRE.IPO_SITE IPO_SITE ON IPO_LOGEMENT.OBJECTID_IMMEUBLE = IPO_SITE.OBJECTID_SITE
left join EDRPRE.IPO_RUE IPO_RUE ON IPO_SITE.OBJECTID_RUE = IPO_RUE.OBJECTID_RUE
left join EDRPRE.IPO_VILLE IPO_VILLE ON IPO_RUE.OBJECTID_COMMUNE  = IPO_VILLE.OBJECTID_COMMUNE
where IPO_AT.DATE_MUTATION is not null and IPO_AT.DATE_MUTATION >= TRUNC(sysdate-5, 'DD')
and IPO_VILLE.CODE_COMMUNE is not null and IPO_SITE.NOM_SITE is not null
group by IPO_VILLE.CODE_COMMUNE,IPO_SITE.NOM_SITE
order by IPO_VILLE.CODE_COMMUNE,IPO_SITE.NOM_SITE;`
</code>
Comment: remove the max and the group by clauses, then you will return all records.
Answer: try this to get all records:
<code>select IPO_VILLE.CODE_COMMUNE,
   IPO_SITE.NOM_SITE,
     IPO_AT.DATE_MUTATION ,
     IPO_AT.IAR_NDFICTIF ,
     IPO_AT.MUTATION_REALISEE_PAR ,
     IPO_AT.CAUSE_MUTATION ,
     IPO_AT.CODE_BASICAT ,
     IPO_AT.PIGTAIL_FIBRE_CONN_COURANT ,
     IPO_AT.PIGTAIL_FIBRE_CONN_CIBLE ,
     IPO_AT.NOM_PB_COURANT ,
     IPO_AT.NOM_PB ,
     IPO_AT.NOM_PM_COURANT ,
     IPO_AT.NOM_PM ,
     IPO_AT.INTERVENTION_NUMBER ,
     IPO_AT.GPC_BASE
from EDRPRE.IPO_AT IPO_AT
left join EDRPRE.IPO_LOGEMENT IPO_LOGEMENT ON IPO_AT.OBJECTID_LOGEMENT = IPO_LOGEMENT.OBJECTID_LOGEMENT
left join EDRPRE.IPO_SITE IPO_SITE ON IPO_LOGEMENT.OBJECTID_IMMEUBLE = IPO_SITE.OBJECTID_SITE
left join EDRPRE.IPO_RUE IPO_RUE ON IPO_SITE.OBJECTID_RUE = IPO_RUE.OBJECTID_RUE
left join EDRPRE.IPO_VILLE IPO_VILLE ON IPO_RUE.OBJECTID_COMMUNE  = IPO_VILLE.OBJECTID_COMMUNE
where IPO_AT.DATE_MUTATION is not null and IPO_AT.DATE_MUTATION >= TRUNC(sysdate-5, 'DD')
and IPO_VILLE.CODE_COMMUNE is not null and IPO_SITE.NOM_SITE is not null
order by IPO_VILLE.CODE_COMMUNE,IPO_SITE.NOM_SITE;
</code>

GROUP BY with MAX()


Creating A Function For The Following:

Question: In trying to manipulate a function arrived at in a prior post, I've arrived at this (as a goal):
$$\begin{array}{c|c}
x & y \\ \hline
0.3^{-1} & -1 \\
0.3^{-1}+0.3^{0} & 0 \\
0.3^{-1}+0.3^{0}+0.3^{1}& 1 \\
0.3^{-1}+0.3^{0}+0.3^{1}+0.3^{2} & 2 \\
0.3^{-1}+0.3^{0}+0.3^{1}+0.3^{2}+0.3^{3} & 3 \\
\end{array}$$
But, I'm having issues creating the right function. I'd be very thankful if someone could give me a hand with it!
Comment: @zwim Could you expand the hint ever so slightly? Thank you!
Comment: https://math.stackexchange.com/questions/3378076/evaluating-0-3-10-300-310-32-cdots0-3n/3378146#3378146 Sorry, I did not understand your question until I saw your other post. So you want to find $y$ given the sum $x$. Is that right ?
Comment: Yes, @zwim, thank you!
Answer: I think this fulfills what you are asking for.
$$\DeclareMathOperator*{\argmax}{arg\,max}$$
\begin{equation}y={\argmax_{\sum_{i=-1}^{a}{0.3^i}\le x
}}a
\end{equation}
Achieving a smooth function may not be is possible (look at zwim's answer).
Comment: This fulfills the vague question without mindreading. zwim's answer probably fulfills the asker's intent, and is not a step function.
Comment: Not what I intended, but still a really clever thought!
Answer: In your other post you were given the formula (where $a=0.3$)
$$x=\dfrac{1-a^{y+2}}{(1-a)a}$$
So isolating $y$ we get $\quad a^{y+2}=1-x(1-a)a\iff y+2=\log_a(1-xa+xa^2)$
The formula you seek is thus $$y=\dfrac{\ln(1-xa+xa^2)}{\ln(a)}-2$$
Comment: Sorry for my comment; I made an error when solving for x. Your work is perfect and awesome!

Creating A Function For The Following:


How to associate model in CakePHP by fields not named by convention?

Question: I have two tables with field username in both. How i can specify field name for both local and foreign table?
I want CakePHP will do something like
ON (`T1`.`username` = `T2`.`username`)`

in result.
Without any changes tables will be joined with following condition:
ON (`T1`.`id` = `T2`.`t1_id`)`

Setting 'foreign_key' = 'username' property is not enough because it will produce query like this:
ON (`t1`.`id` = `t2`.`username`)`

I have two solutions.
First one is use 'join' property and join table on the fly. In such case i can set both local and foreign field. But if i need to join more tables to that one, joined manually, i can't use contain anymore i need to write following joins manually even if that associations was set correctly.
So i need to write long join definitions every time instead just use 'contain' => array('T1', 'T2', 'T3')
Second is to set 'primary_key' of table to corresponding field. It can be done in model file or in runtime. In my case it can not be done in model because that table also have "correct" association by its 'id' field.
Setup it runtime is the case but i dislike it because it's not obvious and looks like a hack.
When i ask this question i thought i missing something obvious but now i understand that CakePHP just can't do that. So i started a bounty hoping that somebody share solution. If not i will try to read cake sources and redefine model some of method to add ability to define local field near the 'foreign_key' in association definition.
Comment: Why are you not happy with that answer. Change your question to be more specific about what you do want and what behaviour you don't. Maybe your problems comes from a bad design descision where better sollutions for exists
Comment: It is possible to change "primary key" of model and force CakePHP to use that field in join condition. But i'm not happy with such solution.
Comment: Jeroen, thanks for you interest. I'm not happy because it's something like i try to cheat CakePHP and i dislike such solutions. There are nothing about design, i just want to join two tables by custom fields in both tables. And i want to write that condition once in my model file to use everywhere in my app. May be you right, i will try to rewrite my question.
Answer: ForeignKey false
To have an association which does not use the primary key of the related model in join conditions - the standard way to do that would be to use 'foreignKey' => false.
I.e. whereas this association:
class Comment extends AppModel {
    public $belongsTo = array(
        'Profile' => array(
        )
    );
}

Will generate this sql:
SELECT ... LEFT JOIN profiles on ON (Profile.id = Comment.profile_id)

Specifying that a foreignKey isn't to be used like so:
class Comment extends AppModel {
    public $belongsTo = array(
        'Profile' => array(
            'foreignKey' => false
        )
    );
}

Will produce this (invalid) sql:
SELECT ... LEFT JOIN profiles on ON ()

From this point, the desired conditions can be specified using the conditions array key:
class Comment extends AppModel {
    public $belongsTo = array(
        'Profile' => array(
            'foreignKey' => false,
             'conditions' => array(
                 'Comment.username = Profile.username'
             ),
        )
    );
}

(Note that the conditions are defined as a string) resulting in:
 SELECT ... LEFT JOIN profiles on ON (Comment.username = Profile.username)

Comment: I'm perfectly happy for dave to get the accept (and bounty if that's possible) if the answer is updated appropriately.
Answer: Update:
Just specify that you don't want to use a foreignKey, then specify the conditions (all within the association:
'foreignKey' => false and 'conditions' => 'Comment.username = User.username'
PS - probably a good idea moving forward to try not to be rude to the people helping you.

This is very clearly defined in the CakePHP book:  http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#hasmany
class User extends AppModel {
    public $hasMany = array(
        'Comment' => array(
            'className' => 'Comment',
            'foreignKey' => 'user_id', // <---- THIS HERE you can define the foreign_key
            'conditions' => array('Comment.status' => '1'),
            'order' => 'Comment.created DESC',
            'limit' => '5',
            'dependent' => true
        )
    );
}

What is a Foreign Key?:

In the context of relational databases, a foreign key is
  a field in one table that uniquely identifies a row of another table.
Comment: Do you really want me to go to the link for you, and copy/paste out the answer into stackoverflow?
Comment: I'm not interested in a work-around, as I believe my answer solves the problem within normal CakePHP options.
Comment: @Yaroslav Dave is right and I've checked your answer, your DB is simply awkward. Besides that even this awkward design can be used the way Dave describes with CakePHP why do you create such a DB design at all?
Comment: Please quote that part where my question is answered.
Comment: I just read that part of manual again and still can't find answer. So if you can point me directly i will be grateful. Also please look my answer above.
Comment: OK, foreign key. I know that already. And now: how to define field name not in ANOTHER table, but in current table to which i want to join to? Because my question is actually about that part. And as i say earlier if i do that it changes only foreign field and take `id` from current table. But i need to use another field, not an `id`.
Comment: I sounds like you just need to spend a few minutes clarifying your question.
Comment: Dave, it sounds like you need to spend few minutes to read question again. I have two tables with field username in both. And need to join for that field in BOTH tables. Not only in foreign table. That's it.
Comment: Sorry, you got a down vote because not even try to read my question carefully and continue arguing. I fount a solution but i don't like it. See my answer if you interested.
Comment: So please try your solution with my schema and debug 2 and see the query. I believe you're wrong. Because i have huge experience with CakePHP and know about foreign key.
Comment: I will simplify task: please see my update to my own answer. There are sample CakePHP app with my schema and your solution. And that solution doesn't work. So please take your downvote back because you're totally wrong but continue arguing without even try to understand my question.
Comment: @burzum, Dave isn't right. See my screenshot above there you can see actual query produced by CakePHP. See that it use values `1` and `2` in `'username'` condition but in need to be `'firstusername'` instead.
Please treat that "awkward design" just like example. It isn't actual schema of my application. I have complicated DB schema. But still it's question not about DB optimization.
Answer: Just a workaround that should work for your hasMany relationship when you want to retrieve a User and all his Comments
class User extends AppModel {
    public $hasMany = array(
        'Comment' => array(
            'finderQuery' => 'SELECT * FROM comments Comment
                              LEFT JOIN users User
                              ON Comment.username = User.username
                              WHERE User.id = {__CakeID__}'
        )
    );
}

Hope it helps
Comment: Thanks, it will work for totally esoteric join conditions, but in my case it's enough `'foreignKey' => false, 'conditions' => array()` solution.
Answer: I struggled with this exact problem for days and the solution that I found (not clearly addressed above) is: The hasMany must have 'foreignKey' => false while the belongsTo MUST ALSO have the 'foreignKey' => false and have the 'conditions' => 'Comment.username = User.username'. With the conditions as a string not assoc array. Like so:
// Profile
public $hasMany = array(
    'Comment' => array(
        'foreignKey' => false,
    )
);

// Comment
public $belongsTo = array(
    'Profile' => array(
        'foreignKey' => false,
        'conditions' => array('Profile.username = Comment.username')
    )
);

Answer: public $hasMany = array(
    'Comment' => array(
        'className' => 'T1',
        'foreignKey' => 'username',
        'dependent' => true
    )
);

Note that dependent true would delete all the T1's when T2's were deleted from within cake.
Comment: Speaking about Cake manual: in this case query would be something like `ON (`Comment`.`username` = `User`.`id`)` but i need `username` for both tables.
Comment: It is like i need to join comments not by user id but by login:

`Select * from users as User LEFT JOIN comment as Comment ON (User.login = Comment.login)`

I hope it is more clear explanation.


Rule on doubling the second rather than the fourth when using ligatures

Question: I was going through the ligatures in 4 parts exercises from Fux's Gradus. On page 133, Aloys says, "Finally, in the sixth measure of the same example the fourth is doubled, although as a rule one doubles the second rather than the fourth":

When Josephus asks for clarification, Aloys presents the answer as a matter of complete harmony (a third, fifth, and octave) in the second half of the measure. However, his correction (below) does not double any note. Instead, he understandably opts to use a C so that it leads up to D, forming a complete harmony in the second half:

I'm still a bit confused about the reasoning for doubling the second over the fourth since Fux did not provide any other detail.

Why is doubling the second much more preferable than doubling the fourth? I know that when the bass descends by step a fourth will become a fifth and a second will become a third. This means that doubling the second would result in doubled thirds, which could be problematic if the thirds are major. Or does this rule only apply when the resulting thirds are minor?
Are there any instances/examples where you would need to double the second?

Thanks in advance and sorry for the long question.
-Allen
Edit:
After doing more research, I have found this section about 4-part ligatures in Louis Van Beethoven's Studies in Thorough-bass, Counterpoint and the Art of Scientific Composition:

From this I can assume that (correct me if I am wrong):
-Minor thirds on the upbeat (meaning second on the downbeat) can be doubled.
-Major thirds can be doubled only if

The third is a third tone
The doubled notes are are in the middle parts
The third is not a leading tone

What is a third tone in this case? I don't think it is a tritone since that would mean it is a leading tone, which is forbidden.
Comment: Welcome to Music.SE, and congrats one heck of a great first question!
Comment: It appears that by "the third tone" they mean the third __iterval__ up from the bass note harmonically
Answer: As regards the edited question re. Beethoven: as far as I can see from the original German language version, the topic is being discussed specifically in the context of dissonances arising from suspensions and their resolution (the examples at the bottom of p. 99 are clear enough even if you don't speak German). As to the specific sentence here

Die kleine Terz kann gut verdoppelt werden; die grosse jedoch [bloß] in der Mitte, als dritter Ton; niemals als siebenter (semitonium modi).

[The minor third can be doubled advantageously, the major however only in the middle as a third tone, never as the seventh (leading tone).]

"dritter Ton", by analogy with the "siebenter [Ton]" here most likely refers to scale degrees, as in the modern German compound "Tonstufe" (which does not appear in Beethoven's text; and which in any case does not appear to have been used much if at all before the 19th century, Grimm's dictionary giving as example only Heinr. Christoph Koch's Handbuch bey dem Studium der Harmonie, published in 1811; other sources give me similar results)
However, if you look slightly further up the page, the heading is "On the fourth species of simple three-part counterpoint"... (the musical example above does, however, show the third above the bass being doubled, FWIW, though it is 3rd species), so I'm not sure how relevant this is to four-part writing.
As regards the original question: doubling the fourth will lead to a doubling of the fifth in the following chord. This is of course not ideal for voice leading as fifths are trickier to deal with (and thus might require judgement in determining which rules are ok to break in the context, as Fux does in his example), while parallel thirds are perfectly ok so long you don't abuse them. In any case, the previous page makes clear that this is just general advice and that "it is not so much a matter of the second or the fourth as it is a matter of the complete harmony [following the resolution of the suspension]".
As to an example of "needing" to double the second, and I'm not sure this is the kind of progression you would expect in Fux, the best I could come up with is a cadential progression with the bass descending to the leading tone, where the fourth would "resolve" to the tritone, in which case you are however best just not putting any fourth (and, yes, doubling the second which becomes the third):


Como encontrar strings dentro de um array

Question: Bom dia!
Eu tenho o seguinte array:
const keys = ["idCard1", "idCard2", "idCard3",  "oi", "idCard4"]
Eu preciso guardar em outro array apenas o que começa com a palavra "idCard", seria possível?
Tentativa do usuário:
let keys = [idCard1, idCard2, idCard3,  oi, idCard4]
let filtro = keys.filter(item => item.includes("idCard"));
console.log(filtro);

Essa tentativa havia sido colocada no campo de respostas.
Comment: Eu não apresentei uma tenteativa, eu não dou chutes. Eu estou alertando que isso que você colocou na pergunta `const keys = [idCard1, idCard2, idCard3,  oi, idCard4]` não é um array de strings é um array de variáveis.
Comment: Um array de strings seria assim `const keys = ["idCard1", "idCard2", "idCard3",  "oi", "idCard4"]`. Então pergunto você tem certeza que a primeira forma apresentada está correta?
Comment: function isBigEnough(value) {
  return value >= 10;
}

var filtered = [12, 5, 8, 130, 44].filter(isBigEnough);
// filtrado é [12, 130, 44]
Comment: Mas eu quero pegar tudo que começa com a palavra "idCard", essa função serviria?
Comment: Isto responde à sua pergunta? [Filtrar array de strings](https://pt.stackoverflow.com/questions/292455/filtrar-array-de-strings)
Comment: let nomes = ["Thiago Carvalho", "Renata Carvalho", "Alexandre Otoni", "Guilherme Otoni de Carvalho"];
let filtro = nomes.filter(item => item.includes("Carvalho"));
console.log(filtro);
Comment: Muita calma nessa hora, isso aqui `const keys = [idCard1, idCard2, idCard3,  oi, idCard4]` não é um array de strings, é um array composto pelo valor de várias variáveis que podem ou não ser strings.
Comment: Postei o teste do código, o qual não funcionou
Comment: Voce esta correto, a minha forma de enviar aqui realmente foi errada. O meu array é de strings, mas eu o trouxe aqui como variável. Mesmo assim, teria como eu procurar o que preciso?
Comment: Edite a pergunta e deixe da maneira correta e me marque num comentário depois da edição que ao voltar do almoço o dou uma resposta. Isso se alguém já não tiver o respondido após a edição.
Comment: Pronto, Augusto. Já editei. Agradeceria muito se conseguisse me ajudar. Desde já, obrigado
Answer: Use o método Array.prototype.filter() para cria um novo array com todos os elementos que passaram no teste fornecido em uma função passado como parâmetro para filter().
Para implementar o teste use a o método String.prototype.startsWith() que determina se uma string começa com os caracteres especificados retornando true ou false.

const keys = ["idCard1", "idCard2", "idCard3", "oi", "idCard4"]

let result = keys.filter((e) => e.startsWith("idCard"));

console.log(result)
Answer: Uma outra maneira de resolver este problema é utilizando uma estrutura de laço for em conjunto com o método startsWith do javascript.
Segue um exemplo:
const chave = ['idCard1', 'idCard2', 'idCard3',  'oi', 'idCard4']
const result = []
for (let k = 0; k < chave.length;k++) {
    if  (chave[k].startsWith('idCard')) {
        result.push(chave[k])
    }
}
console.log(result)


Does $x=\frac{1}{2^n-3}$ converge in both directions in $\Bbb{Z}_2$ for $n$ an integer?

Question:
Does $x=\dfrac{1}{2^n-3}$ converge in both directions in $\Bbb{Z}_2$ for $n$ is integer?

Solving $x=\dfrac{1}{2^n-3}$ for $x$ where $n$ is integer.
We get that the only the solutions in $\Bbb{Z}$ are $x\in\{-1,1\}$ and of course there is a countable set of solutions in $\Bbb{Q}$ given by:
$x\in\left\{\ldots,-\frac{4}{11},-\frac{2}{5},-\frac{1}{2},-1,1,\frac{1}{5},\frac{1}{13},\ldots\right\}$
Does this sequence $x_n$ converge in both directions in $\Bbb{Z}_2$?
To the right (i.e. $n\to\infty$) we have $x\to \dfrac{1}{2^{m}-3}$
To the left (i.e. $n\to-\infty$) we have $x\to \dfrac{-2^m}{2^m+2^{m-1}-1}=2^{2m}\cdot\dfrac{-1}{1+2^{2m-1}-2^m}$
I have no doubt that to the right it converges to $-\frac{1}{3}$.  Is that correct?
To the left I'm not so sure.  I think all but the $1$ in the denominator  converges to $0$ leaving me with $0\cdot \frac{-1}{1}=0$.  Is that correct?
Comment: Let's prove that it converges to $-1/3$ when $n\to\infty$: We have that $|1/(2^n-3)+1/3|=|2^n/(2^n-3)|=2^{-n}\to0$ as $n\to\infty$.
Comment: For $n\to-\infty$ it converges to $0$: Since $|1/(2^n-3)|=|2^{-n}/(1-3\cdot 2^{-n})|=2^n\to0$ as $n\to-\infty$.
Comment: No `\dfrac` in titles please.
Comment: I'm utterly baffled as to why this question would be downvoted and voted to close.
Comment: @totoro thanks. Much appreciated.
Answer: To put this into a bit of perspective, I figure I will post this as an answer to a broader case. In general, if we look at the expression $\dfrac{1}{x^{-1} + a^{-1}}$ it tends towards $a$ as $x$ gets larger in magnitude and tends towards $0$ as $x$ gets smaller in magnitude, regardless of what field you're in, real or p-adic.
Specifically here we can let x play the role of $p^n$ and $a$ play the role of $\dfrac{-1}{3}$.


finding the value pair that has the highest affinity in Java?

Question: Hi I am current working on a algorithm problem set.
Given the below file in a file.txt file,
<code>yahoo,ap42
google,ap42
twitter,thl76
google,aa314
google,aa314
google,thl76
twitter,aa314
twitter,ap42
yahoo,aa314
</code>
A web server logs page views in a log file. The log file consists of one line per page view. A page view consists of page id and a user id, separated by a comma. The affinity of a pair of pages is the number of distinct users who viewed both pages. For example in the quoted log file, the affinity of yahoo and google is 2 (because ap42 viewed both and aa314 viewed both).
My requirement is to create an algorithm which will return the pair of pages with highest affinity.
Currently, I have written below code, however, right now it is not returning the pair of pages with highest affinity, any suggest of how I am modify the code to make it work? thanks. :
<code>    Scanner in = new Scanner(new File("./file.txt"));
    ArrayList<String[]> logList = new ArrayList<String[]>();
    while (in.hasNextLine()) {
        logList.add(in.nextLine().split(","));
    }
    String currentPage;
    String currentUser;

    int highestCount =0;

    for (int i = 0; i < logList.size()-1; i++) {
        int affinityCount =0;
        currentPage = logList.get(i)[0];
        currentUser = logList.get(i)[1];
        for (int j = logList.size()-1; j > 0; j--) {
            if (i != j) {
                if (!currentPage.equals(logList.get(j)[0])
                        && currentUser.equals(logList.get(j)[1])) {
                    affinityCount++;
                    System.out.println("currentPage: "+currentPage+" currentUser: "+ currentUser);
                    System.out.println("logList.get(j)[0]: "+logList.get(j)[0]+" logList.get(j)[1]): "+ logList.get(j)[1]);
                    System.out.println(affinityCount);
                }
            }
        }
    }
</code>
Comment: Do you need only top 2 pages with highest affinity or more?
Comment: yes, I was hoping to find the top 2 pages pair that have the highest affinity. Thank you.
Comment: Do u know the size of the number of distinct webpages and user names?
Comment: Also If there is a tie, which one you output?
Answer: Am going to write the algorithm here . You can convert that into the code.

Traverse the file and create a hashMap of .
After this traversal, you shall get the pages viewed by each user.
Now traverse this dataset. For each user, take out the list of pages he viewed. Make all possible combinations of pair of pages and put it in a max heap with value set to 1. If the combination exists in heap, increment the value.
Make sure you treat - yahoo,google same as google,yahoo while comparing.
At the end of this, the element at top of the heap is your output.


HTML borders not the same length

Question: I have this list of salons and each has a dotted border on the right hand side. Some of these borders stop before others, is there any way to make them all the same length? (ideally so they reach the footer)
All salons are in this HTML (the information is just different):

Urban Bliss

 15 Headingly Lane,
    LS6 1BL.
    0113 278 1572

and the CSS is as follows:
.salons {
font-family:"Century Gothic";
width:248.5px;
max-height:inherit;
float:left;
padding-left:5px;
border-right:1px dotted #FFB6D7;
padding-bottom:5px;
}

Comment: You need to set a fixed height or `100%`.
Comment: I would say have a fixed height. Also @JoshPowell will `100%` work?
Comment: i added height: 100%; into my css but it hasnt solved the problem unfortunately
Comment: @JoshPowell Im clearly high it would work.
Comment: lol :] It just needs a height on it's parent to have `height: 100%;` work.
Answer: Okay you need to give it's parent a fixed size, of the longest one, and then add height: 100%; to the children.
.parent {
    width: 100%;
    height: 190px;
}

.salons{
    font-family:"Century Gothic";
    width:248.5px;
    height:100%;
    float:left; /* the reason the parent needs a fixed height is due to the float */
    padding-left:5px;
    border-right:1px dotted #FFB6D7;
    padding-bottom:5px;
}

JSFIDDLE
Comment: thank you! can you explain what a parent is though? sorry very new to all of this!
Comment: No need to be sorry! A parent is an html element that contains other tags. The class name does not need to be parent, what this does is the `parent` is containing the class `.salons` which therefor are a child of that parent. Since the parent has those styles the children can now inheret what 100% would be of the parent. Without a parent the 100% would not work since there is nothing to compare 100% to.
Comment: @user3095683 I made this fiddle to show you how 100% height works with it's parent. In this http://jsfiddle.net/5xtB4/ the `div` has no parent with styles so the height 100% does nothing. In this http://jsfiddle.net/5xtB4/1/ I added height and width to be 100% on the `html, body` which contain that `div`. Now you can see how the `div` is inheriting it's parents size. Hope this helps, if this was the answer you can always mark it as the accepted answer. :]
Answer: The reason this is happening is because some of the box heights are less than the tallest. To fix this, just add a fixed height to all of the divs in the css.
For example:
height:200px;

Answer: It's Because they have different height (based on it's content)...
You can try giving a fixed height to the .salons class
or...
a 100% and a fixed height to the container.
Answer: You need to set the height, min-height and max-height
.salons {
  /* other style */
  height: 200px;
  min-height: 200px;
  max-height: 200px;
}

Answer: You Don't need to fix any height I think just make the parent display:table; and make the class salons display:table-cell;
To check how this thing work try the below given HTML and CSS
HTML

1

2
2

1

1

CSS
ul { display:table; list-style:none; }
ul li { display:table-cell; padding:10px; border-right:1px solid red }

HTML borders not the same length


Existence of solutions for the following PDE

Question: We have that $a:\mathbb{R}^+\times \mathbb{R}\to \mathbb{R}$ be a given function such that $|a(t,x)|+|\partial_x a(t,x)|\leq M$. $\rho_0$ is the initial data where $$\rho_{|t=0} = \rho_0 \in L^1\cap L^{\infty}(\mathbb{R}),\quad \rho_0\geq 0.$$

Show that the iterative scheme
$$ \left\{ \begin{array}{lcc}
             \rho^{(0)}\in L^2((0,T)\times \mathbb{R}),\quad \partial_x \rho^{(0)}\in L^2((0,T)\times \mathbb{R}) \\
             \\ \partial_t \rho^{(n+1)} - \partial_{xx}^2 \rho^{(n+1)} = -\partial_x (a\rho^{(n)}) =   -\rho^{(n)}\partial_x a - a \partial_x \rho^{(n)}\\
             \\ \rho^{(n+1)}_{|t=0} = \rho_0
             \end{array}
   \right.$$
is well defined.
Show that it is contracting on $C^0 ([0; T]; L^2 (\mathbb{R}))$ endowed with norm
$$N(u)^2 = \sup_{0\leq t\leq T< \infty}\left(e^{-\gamma t}\int_\mathbb{R}|u(t,x)|^2 dx\right)$$
for a well chosen value of $\gamma> 0$.

My fisrt question is, what is the meaning of iterative schema well defined? and how to test it?
For the second item, I have the following idea:
I worked with
$$\small \partial_t (\rho^{(n+1)}-\rho^{(n)}) - \partial_{xx}^2( \rho^{(n+1)} - \rho^{(n)}) = -(\rho^{(n)}-\rho^{(n-1)})\partial_x a - a \partial_x (\rho^{(n)}-\rho^{(n-1)})$$
then, multiplying by $(\rho^{(n+1)}-\rho^{(n)})$ and integrating with respect to $x$ we have that
$$\scriptsize \frac{d}{dt}\int_\mathbb{R}\frac{|\rho^{(n+1)}-\rho^{(n)}|^2}{2}dx + \int_\mathbb{R}|\nabla(\rho^{(n+1)}-\rho^{(n)})|^2 dx = -\int_\mathbb{R} (\rho^{(n+1)}-\rho^{(n)})(\rho^{(n)}-\rho^{(n-1)})\partial_x a dx -\int_\mathbb{R} a(\rho^{(n+1)}-\rho^{(n)})\partial_x(\rho^{(n)}-\rho^{(n-1)}) dx$$
and from this expression, we will find majorities for the expression on the right until we can express a Gronwall lemma inequality.
Comment: What are the assumptions on $\rho_{0}$?
Comment: @PeterMorfe Could you help me?
Answer: Concerning (1), I think the question is asking you to check that if $\rho^{(n)} \in L^{2}((0,T) \times \mathbb{R})$ and $\partial_{x} \rho^{(n)} \in L^{2}((0,T) \times \mathbb{R})$, then $\rho^{(n + 1)}$ is well-defined (i.e. there's a solution of the equation) and has the same property.  (I won't give the details, but it looks correct to me.)
Concerning (2), notice that, given $u \in C([0,T]; L^{2}(\mathbb{R}))$, $N_{\gamma}(u)$ can be written as
\begin{equation*}
N_{\gamma}(u)^{2} = \sup \left\{ \int_{-\infty}^{\infty} |u_{\gamma}(t)|^{2} \, dx \, \mid \, t \in [0,T] \right\}.
\end{equation*}
Here $u_{\gamma}$ is defined by $u_{\gamma}(t) = e^{-\gamma t/2} u(t)$.  Hence one way to proceed is to study $\rho_{\gamma}$ instead of $\rho$.
Rather than the scheme, let's show that the solution map $S : \mathcal{S} \to \mathcal{S}$ is a contraction.  Here $\mathcal{S}$ is the space of possible solutions
\begin{equation*}
\mathcal{S} = \{\rho \in C([0,T]; L^{2}(\mathbb{R})) \, \mid \, \rho \restriction_{t = 0} = \rho_{0}\}
\end{equation*}
and, given $\eta \in C([0,T];L^{2}(\mathbb{R}))$, we define $\rho = S\eta$ as the solution of the equation
\begin{equation*}
\left\{ \begin{array}{r l}
\partial_{t} \rho - \partial^{2}_{xx} \rho = - \partial_{x}(a \eta) & \text{in} \, \, (0,T) \times \mathbb{R} \\
\rho \restriction_{t = 0} = \rho_{0} & \text{on} \, \, \{0\} \times \mathbb{R}
\end{array} \right.
\end{equation*}
We want to show that, for an appropriate choice of $\gamma > 0$, there is an $\alpha_{\gamma} \in (0,1)$ such that $N_{\gamma}(S\eta - S\beta) \leq \alpha_{\gamma} N_{\gamma}(\eta - \beta)$.
Fix $\eta, \beta \in \mathcal{S}$.  Let $\rho^{\eta} = S\eta$ and $\rho^{\beta} = S \beta$ and let $\mu = \rho^{\eta} - \rho^{\beta}$ be the error.  If we set $\gamma > 0$, then $\mu_{\gamma}(t) = e^{-\gamma t/2} \mu(t)$ solves the equation
\begin{equation*}
\left\{ \begin{array}{r l}
\partial_{t} \mu_{\gamma} - \partial^{2}_{xx} \mu_{\gamma} + \frac{\gamma}{2} \mu_{\gamma} = - e^{-\gamma t/2} \partial_{x}(a (\eta - \beta)) & \text{in} \, \, (0,T) \times \mathbb{R} \\
\mu \restriction_{t = 0} = 0 & \text{on} \, \, \{0\} \times \mathbb{R}
\end{array} \right.
\end{equation*}
If we multiply the equation by $\mu_{\gamma}$ and integrate-by-parts in the right-hand side, we find
\begin{equation*}
\frac{1}{2} \frac{d}{dt} \left\{ \int_{-\infty}^{\infty} |u_{\gamma}(t)|^{2} \, dx \right\} + \int_{-\infty}^{\infty} |\partial_{x} u_{\gamma}(t)|^{2} \, dx = e^{-\gamma t/2} \int_{-\infty}^{\infty} a (\eta - \beta) \partial_{x} \mu_{\gamma} \, dx - \frac{\gamma}{2} \int_{-\infty}^{\infty} |u_{\gamma}(t)|^{2} \, dx
\end{equation*}
By Young's inequality, given $\nu> 1/2$, we have
\begin{equation*}
e^{-\gamma t/2} \int_{-\infty}^{\infty} a (\eta - \beta) \partial_{x} \mu_{\gamma} \, dx \leq \frac{1}{2 \nu} \int_{-\infty}^{\infty} |\partial_{x} \mu_{\gamma}|^{2} \, dx + \frac{\nu}{2} e^{-\gamma t} \int_{-\infty}^{\infty} a^{2} |\eta - \beta|^{2} \, dx
\end{equation*}
and, thus, the function $F_{\gamma}(t) = \int_{-\infty}^{\infty} |u_{\gamma}(t)|^{2} \, dx$ satisfies
\begin{equation*}
F_{\gamma}'(t) \leq - \gamma F_{\gamma}(t) + \frac{\nu M}{2} e^{-\gamma t} \int_{-\infty}^{\infty} |\eta(t) - \beta(t)|^{2} \, dx.
\end{equation*}
Therefore, we can apply Gronwall's Lemma to find
\begin{equation*}
F_{\gamma}(t) \leq \frac{\nu M}{2} \int_{0}^{t} e^{- \gamma(t - s)} \cdot e^{-\gamma s} \int_{-\infty}^{\infty} |\eta(s) - \beta(s)|^{2} \, dx \, ds \leq \frac{\nu M}{2} \int_{0}^{t} e^{-\gamma (t - s)} \, ds \cdot N_{\gamma}(\eta - \beta)^{2}.
\end{equation*}
which gives
\begin{equation*}
N_{\gamma}(S\eta - S \beta)^{2} = \sup \left\{ F_{\gamma}(t) \, \mid \, t \in [0,T] \right\} \leq \frac{\nu M}{2 \gamma} N_{\gamma}(\eta - \beta)^{2}.
\end{equation*}
Hence we get $\alpha_{\gamma}^{2} = \frac{\nu M}{2 \gamma} < 1$ as soon as $\gamma > \frac{2}{\nu M}$.
Given the above, notice that $N_{\gamma}(\rho^{(n + 1)} - \rho^{(n)}) \leq \alpha_{\gamma} N_{\gamma}(\rho^{(n)} - \rho^{(n - 1)})$ and, thus, $N_{\gamma} (\rho^{(n + 1)} - \rho^{(n)}) \leq \alpha_{\gamma}^{n} N_{\gamma}(\rho^{(1)} - \rho^{(0)})$.  This implies $\{\rho^{(n)}\}_{n \in \mathbb{N}}$ is a Cauchy sequence in $\mathcal{S}$ and it approaches its limit exponentially fast.


ASP.NET Insert <% =i %> into

Question: How can I append this
<% =i %>

variable onto this.
<asp:DropDownList ID="AdTitle" runat="server">

Cant have this for some reason.
<asp:DropDownList ID="AdTitle<% =i %>" runat="server">

Answer: Where does your "i" come from?

If it's part of a fixed or hard-coded loop, you really should just list out each control.  If there are enough of these to make that very cumbersome, you should make this data driven somehow.
If it's data driven, you probably want a repeater control.
If it's pulled from a config file, put a place holder on the form and create the controls dynamically in your code-behind.
Comment: I probably should use a repeater control for this. Im an absolute beginner, how do I databind to the repeater control?
Comment: It depends on what your data looks like.  At this point you'll likely do better starting a new question with that in mind.  Don't forget to include all the relevant details, namely how you get your data, where your keeping it, and what it looks like.
Answer: You shouldn't need to dynamically generate ids in this way.
Use a repeater (or any other repeating control with item templates):
<asp:Repeater ID="forEachItem" runat="server">
    <ItemTemplate>
        <asp:DropDownList ID="AdTitle" runat="server" />
        <%!-- any other content per item --%>
    </ItemTemplate>
</asp:Repeater>

Or generate your controls server side:
<asp:PlaceHolder ID="ph" runat="server" />

<%
    //...
    ph.Controls.Add( new DropDownList { Id = "AdTitle" + i } );
    //...
%>

If you use the repeater make sure you use databindings (<%#) rather than literals (<%=).
Comment: Brilliant. Thanks Keith. How can I bind data on the codefile?
Comment: Something like: forEachItem.DataSource = myDataTable; forEachItem.DataBind();
Comment: Then in your item template you can use bindings:
Answer: Is there more than one DropDownList? Do you know ahead of time how many there are? If so, you can set the id's ahead of time. If not, you can create the controls on the fly and give them whatever iD you want.
Answer: <asp:DropDownList ID="AdTitle<% =i %>" runat="server">

and
<asp:DropDownList ID='<= "AddTitle" + i %>' runat="server">

will not work because of the order in which asp.net processes and renders html.  you can do this with a simple <select id='AddTitle<%=id%>'>
but you can't do it with asp.net controls
you are not allowed to dynamically set IDs of user and server control objects anyway because they are used to identify the controls to the code behind page on the server
Answer: If you really need to do something like this, you'll need to use an Expression Builder because of the way that the ASP.net engine parses the markup. I wrote a blog posting about them a while ago and there's some good links at the top. Possibly the most useful of them is the one going to 4GuysFromRolla.com.
I would add that the other suggestions here are almost certainly better ways of doing what you want to do, unless you have a very very specific reason for wanting to do it this way, which you've said you don't =)

ASP.NET Insert <% =i %> into


Algorithms for regression analysis which can handle large scale datasets

Question: I am a CS undergraduate student and for my final project i developed a regression algorithm that is suited for large-scale datasets (i wouldn't say 'Big Data', but still large scale).
For the final results, i'm looking for regression algorithms that are known to successfully work on such large datasets, so i can use them as a baseline for my algorithm.
I dont have limits to some particular proerties of the dataset, so the algorithm should be general.
Does anybody have an idea for regression models i can use?
EDIT:
To clarify: the best thing for me is to find a paper which shows one (or more) regression models, and their performances on large-scale datasets.
If anybody could also point me out to a known public dataset (that is big of course) it will be very helpfull.
Thanks for helping,
Nir
Comment: Nir, it looks like you have created more than one account. If this is the case, you should merge them.
Comment: How can i check if i have another account?
Comment: If you didn't make another one recently, then you probably don't. I thought I saw a recent new account under the name 'nir' rather than 'ni6go' in the last few days, which was asking about a similar topic. It's possible I was mistaken. If you may have made an account in the past, go to the [USERS](http://stats.stackexchange.com/users) page and type a name in the search bar at the top left.
Comment: No, this is my only account :)
Answer: The biglm package in R is designed for fitting linear models and generalized linear models to very large data sets.
http://cran.r-project.org/web/packages/biglm/index.html


Why are only 16 GB of memory usable on our server?

Question: We've recently upgraded the RAM on a Windows Storage Server 2008 R2 Standard to 32 GB.
When I open the System panel, it indicates Installed memory: 32.0 GB (16.0 GB usable). Why is that?
I've been trying to dig up documentation that would indicate that this is a limit of the operating system version, but I've come up short. Looking at the version comparison on Wikipedia shows no version with 16 GB, but Storage Server isn't listed and Memory Limits for Windows and Windows Server Releases doesn't list Storage Serer 2008 R2.
I've since found an infographic in the blog post titled Windows Storage Server 2008 R2 is now available!, which indicates that the limit would be 32 GB.
As suggested by @Nico, opening perfmon shows that 16 GB of memory are "reserved for hardware".
The board of the server is an Intel S3420GPLX set up with an Intel Xeon SP X3430, both of which are supposed to support 32 GB of memory.
The installed RAM modules are 4 x 8 GB Hynix HMT31GR7CFR8A-H9 RDIMM.
Support advised us to perform a firmware upgrade of the mainboard. We performed the firmware upgrade, but it had no effect on the issue
Comment: http://technet.microsoft.com/en-us/library/gg214172(v=ws.10).aspx lists the memory limits for the different editions of Storage Server 2008 R2 (none of them are limited to 16GB).
Comment: You sure the problem isn't hardware?
Comment: @Zoredache No, I'm not sure. But I basically asked our supplier, who we bought the server from, to send us the max amount of memory that the board could handle and they looked up the 32 GB in their database and sent them over. I'll check back with them though.
Comment: Maybe check firmware versions and so on?
Comment: @Zoredache I'm trying to get in touch with their support, but it's still pretty early in the morning here. Will update when I get more info.
Comment: Check in `msconfig` if there is no limit on memory (should be in the Boot tab under Advanced options… or something like this).
Answer: High end servers have options for pairing memory modules, like raid arrays for hard disks. You must view the BIOS option for that.
Comment: This was my thought as well. It's typically labeled as "Memory Mirroring"
Comment: While it sounded promising, no feature like that seems to be available in the boards BIOS.
Answer: Have you see this link ?
Running a Perfom /res would show you this "bug". Cause the missing RAM might be hardware reserved.
Also, have a look at this Microsoft's KB : http://support.microsoft.com/kb/978610
(I apologize, I cannot add any comment due to reputation)
Comment: Yeah, it shows 16 as reserved for hardware. The KB article didn't provide anything I deemed helpful. I'm currently trying to gather information for tech support so that they can determine possible hardware issues. Thanks
Comment: Ok. (Agree that the KB isn't probably the best one) On Google, seems like this is a motherboard issue. But wait for support feedbacks and update your question with their answer if possible. That must help.
Answer: It would be useful to know the exact configuration of RAM. i.e. the number of dimms, whether they're all udimm (unbuffered) or rdimm (registered). You can't mix udimms and rdimms on the board, and if you're using udimms you can only use 4/6 of the dimms and can only use up to 16GB of RAM - this sounds a likely cause for your issue.
Reference - https://communities.intel.com/thread/21622
It looks like, in order to get 32GB of RAM working on the board, you need a very specific configuration.
Comment: The modules are 4x8 Hynix HMT31GR7CFR8A-H9 RDIMM
Comment: OK - the specs of the RAM look to match the requirements for the board, from the link I sent you people have had issues with RAM that is supposedly supported and have had to change it, but their issues are different to yours ( they can't post ). Have you perhaps tried a linux live cd or similar, to see if another OS will actually boot with all 32GB available?
Comment: I'm actually not on site, but I will do that if necessary. We actually had a set of 4x8GB Samsung Rx4 RAM before and couldn't POST either. :P
Answer: In the BIOS, 2 of the modules were marked as "failed".
Support advised us to test every module individually. The tech on-site tested different configurations, then put all the modules back in as they were and now the full 32 GB are usable.
Not really sure what to make of it.
Comment: memtest86+, Linux bootable CD, ...
Comment: You should have tested with some software other than Windows to determine if it was a software problem or a hardware/BIOS problem. That would have saved you some time and allowed us to rule out Windows immediately.
Comment: Care to name a software?
Comment: As I explained already, I wasn't on site, otherwise I would have.
Comment: Surely the person who performed the firmware upgrade could have. But whatever.
Comment: Right, he could have. He just would have needed a PDF document full of screenshots for every single step of the way to perform it, just like he had for the firmware upgrade. But whatever
Comment: Maybe he populated the wrong slots?  and then when he reinserted them he populated the correct slots but didn't own up to his mistake.
Answer: Many servers have separate RAM for each Processor, so if you have only 1 processor, then you either have to 1) install the 2nd processor or 2) install the RAM in the correct memory channel.
(what hardware server do you have?)
update:
the manual says:
32 GB max with x8 ECC RDIMM (2 Gb DRAM) and 16 GB max with x8 ECC UDIMM (2 Gb DRAM)
the model that you say youhave are RDIMM as far as I can see, but they do not seem to appear on the approved list of RAM modules here
but not sure if that has any effect...  looks like it is a BIOS or Windows thing then.
Comment: The board is a single-socket. Besides, if it was installed on the wrong side of a dual-socket board, the OS wouldn't even see it.
Comment: Interesting theory as this server has only 1 CPU installed. Not sure if it's a dual-CPU board though. Still waiting on feedback from the client.
Comment: guess we will find out when your client replies :)
Comment: ok, I did not know the board is single-socket, and also I did not know how windows would react to RAM in the wrong place. (thanks)
Comment: I've run in to this with another Intel board. Since the motherboard only supports 2 GB of RAM per slot, that's all the OS will get to use. However, the RAM will still report that it is 4 GB when asked via SPI.
Answer: I agree with some of the answers listed already in particular with Mirrored Mode RAM.
Also, according to the official Intel site, your particular memory is not supported for the board chipset.
First thing I'd do is return the RAM back and get certified modules supported by the vendor.
Then check if it requires the memory to be matched on each side of the banks i.e. two modules in the correct slots per side. There could be every chance the BIOS is also out of date.


Different results with "same" code

Question: I am asking a simple question. Why are these two code fragments not the same?
pNl <- {}

for(i in length(x):length(x)-250) {
    temp <-x[i] - x[i-1]
    pNl <-append(pNl, temp, length(pNl))
}

pNl

and
PnL <- {}

for(i in length(x):(length(x)-250)) {
    temp <- x[i] - x[i-1]
    PnL <- append(PnL, temp, length(PnL))
}

PnL

I get different results when I execute them...
I really appreciate your answer!!!
Comment: Please make your question reproducible, i.e. provide us with `x`.
Comment: Obvious error is nonobvious :-) -- this question will no doubt make Mr. Burns happy, as he loves to point out how erroneous code can run w/o errors and produce nothing like what you wanted.
Comment: Operator precedence. (Yet again.)
Answer: The problem is in the for loop definition. In the first loop statement you have left off brackets, i.e.
#length(x):length(x)-250
R> 2:5-1
[1] 1 2 3 4

In the second loop you have brackets, so:
#length(x):(length(x)-250)
R> 2:(5-1)
[1] 2 3 4

These two statements are not the same and so you are not looping over the same thing.

Different results with "same" code


Scala - error: value max is not a member of my custom class

Question: I've got my own class
class Foo {
 MyCustomClass value;
 ...
}

which consists of MyCustomClass which is java enum with the following signature:
enum MyCustomClass{
   ONE(1),
   TWO(2),
   THREE(3)

   private int nominal;

   MyCustomClass(int nominal) {
       this.nominal = nominal;
   }

   public int nominal() {
       return nominal;
   }
}

for which i define ordering as:
implicit val myCustomClassOrdering = new Ordering[Foo] {
    override def compare(c1: Foo, c2:Foo): Int = {
        c1.value.nominal.compareTo(c2.value.nominal)
    }
}
import myCustomClassOrdering ._

and then i'm able to use function max for sequence of objects ofMyCustomClass type. But i got an error trying to use max fucntion in reduceOption function
val l = List[Foo](...)
l.reduceOption(_ max _)

got error message: value max is not a member of ...
What should i do to be able to use it in reduceOption with max function?
Answer: max method delegated for MyCustomClass. Either add ordering for Foo or add another method which returns Foo object according to result of max method call on MyCustomClass values.
def op(x: Foo,y: Foo):Foo = {
    if( (x.value max y.value) == x.value) x
    else y
  }

  val b = l.reduceOption( op(_,_) )

Comment: fixed his typos, please delete
Comment: oh, yes sorry, i tried to simplify but the exact case is more complex, i've made some changes in question.
Answer: object FooExtension {
    implicit class RichFoo(c:Foo) {
        def max(c2:Foo) = {
            if(c.value.nominal > c2.value.nominal) c else c2
        }
    }
}

import FooExtension._

Now it works but i'm wondering if there is more clear solution where i can rely on built in max and ordering features.


Let $a_{n}$ be a sequence as $|a_{n+1}-a_{n}|\leq\frac{\ln(n+1)}{n^{2}}$ for every $n\in\mathbb{N}$. Prove that $a_{n}$ converges.

Question: Let $a_{n}$ be a sequence as $|a_{n+1}-a_{n}|\leq\frac{\ln(n+1)}{n^{2}}$ for every $n\in\mathbb{N}$.
Prove that $a_{n}$ converges.
I was given a hint: prove that $\sum_{n=1}^{\infty}\frac{\ln(n+1)}{n^{2}}$ converges.
I tried to prove it using Cauchy condensation test. I got that it converges if and only if $$\sum_{n=1}^{\infty}\frac{2^{n}\ln(2^{n}+1)}{2^{2n}} = \sum_{n=1}^{\infty}\frac{\ln(2^{n}+1)}{2^{n}}$$ converges, which isn't very helpful. (I know it converges, but I can't prove it.)
Comment: For $\ln(n)$, e.g, simply use `\ln(n)`.
Comment: For that point, show that $\ln(n+1)\leq \sqrt{n}$ (either for all, or for all large $n$), then comparison.
Answer: Note that
$$
a_{n}=a_{0}+\sum_{k=0}^{n-1}(a_{k+1}-a_{k}).
$$
Let $n\to \infty$. The sequence of partial sums on the right converge, and thus the sequence $(a_{n})$ also converges, since
$$
\sum_{n=0}^\infty|a_{n+1}-a_{n}|\leq \sum_{n=0}^\infty \frac{\ln (n+1)}{n^{2}}<\infty\tag{1}
$$
Indeed $\dfrac{\ln (n+1)}{\sqrt{n}}\to 0.\;$ In particular $\ln (n+1)\leq \sqrt{n}$ for sufficiently large $n$ and thus by comparison to the series $\sum n^{-3/2}$, we have the result in (1).
Comment: I don't understand how did you conclude that $\sum\frac{ln(n+1)}{\sqrt{n}}\leq\sum\frac{1}{n\sqrt{n}}$
Comment: @Jneven He doesn't. He compares $\sum_n \frac{\ln(n+1)}{n^2}$ to $\sum_n\frac{1}{n\sqrt{n}}$ (via the [limit test](https://en.wikipedia.org/wiki/Limit_comparison_test)), using that $$\frac{\frac{\ln(n+1)}{n^2}}{\frac{1}{n\sqrt{n}}} = \frac{\ln(n+1)}{\sqrt{n}}\xrightarrow[n\to\infty]{} 0$$
Answer: You can also do it using the Cauchy condensation test like you tried:
$$\frac{\ln(2^n+1)}{2^n} \le \frac{\ln(2^n+2^n)}{2^n} = \frac{\ln(2^{n+1})}{2^n} = \frac{n+1}{2^n}\ln 2$$
Now prove that for $n \ge 6$ we have $n+1 \le (\sqrt{2})^n$ so
$$\sum_{n=1}^\infty \frac{\ln(2^n+1)}{2^n} \le \sum_{n=1}^5 \frac{\ln(2^n+1)}{2^n} + (\ln 2)\sum_{n=6}^\infty \frac1{(\sqrt{2})^n} < +\infty$$
because the latter is a geometric series.
Hence $\sum_{n=1}^\infty \frac{\ln(n+1)}{n^2}$ converges so $(a_n)_n$ is a Cauchy sequence.


How to find out the real part of this expression in term of k.

Question: $$A=\frac{e^{i \pi k}-1}{e^{i \pi k h}-1}$$
Where
$k=p+q$, $p$ and $q$ natural numbers
$h\in]0,1[$  real number
We can consider that the denominator is never $0$.
The result may be someway like this:
if $k$ is even then $Re(A)= 0$ (or $1$, I dont know but it should be $0$ or $1$ or $-1$)
if $k$ is odd then...
Comment: Do I miss something here? If we multiply both numerator and denominator by $e^{i \pi k}+1$ the numerator becomes $e^{i 2 \pi k}-1=\cos 2 \pi k + i \sin 2 \pi k -1 = 1-1=0$?
Comment: Personally I'd multiply by $\frac zz$ where $z$ is the complex conjugate of the denominator. Then identify the real part of the numerator.
Comment: I used this http://math.stackexchange.com/questions/707053/real-part-of-a-quotient post , and the result is if $k=2n$ then $Re(A)= 0$ and if $k=2n+1$ then $Re(A)=1$. I think it is correct, If someone can confirm this answering this post will be great, thank you!
Comment: Usage of these rules should help:

(I): $Re\left(a\cdot b\right)=Re\left(a\right)\cdot Re\left(b\right)-Im\left(a\right)\cdot Im\left(b\right), Im\left(a\cdot b\right)=Re\left(a\right)\cdot Im\left(b\right)+Im\left(a\right)\cdot Re\left(b\right)$
(II) $Re\left(z\right)=\frac{z+\bar{z}}{2}, Im\left(z\right)=\frac{z-\bar{z}}{2i}$
(III)for $z=Ae^{ib}$ holds $Re\left(z\right)=A cos\left(b\right)$ and $Im\left(z\right)=A sin\left(b\right)$

then start with $A=Re\left(A\right)+iIm\left(A\right)$ and get the denominator on the other side.
Comment: @Alex since $e^{i\pi}=-1$ you could be dividing by zero. On the other hand the numerator is $0$ or $-2$
Comment: @MarkBennet: I'm talking about the numerator, the denominator is not $0$
Comment: @Alex - if you multiply by $\frac 00$ you are dividing by $0$
Comment: @MarkBennet: oops sorry, I understand now: I didn't realize first $e^{i \pi k} +1$ is also $0$
Answer: $$A = { (e^{i\pi k} -1) (e^{-i\pi kh} -1) \over (e^{i\pi kh} -1) (e^{-i\pi kh} -1) } = { e^{-i\pi k(h-1)} - e^{-i\pi kh} - e^{i\pi k} + 1 \over 2(1-\cos (kh \pi)) }$$
From which we obtain:
$$
\operatorname{re}A = { \cos({\pi k(h-1)}) - \cos({\pi kh}) - \cos({\pi k}) + 1 \over 2(1-\cos (kh \pi)) }
$$
As Robjohn mentioned, the basic idea here is that if $z \neq 0$, then ${ w \over z} = { w \bar{z} \over z \bar{z}} = { w \bar{z} \over |z|^2}$.
Comment: It is worth mentioning that in general, the idea is to multiply both the numerator and the denominator by the conjugate of the denominator. (+1)
Comment: @robjohn: Good suggestion.


jQuery UI tabs and external links

Question: I am having a problem with getting my jQuery ui tabs to link to an external HTML document, also does the external HTML document have to be in the same format or should it just be body content?
The problem I saw on firefox console was that tags were mismatched and those tags were  and  which made no sense at all.
Here is what the HTML looks like.

Policy Details

Edit Policy

Personal Details

...

This is what my jQuery looks like at the moment.
$(function() {
            $("#tabs").tabs();
});

In summary: I don't know how to link a tab to an external webpage. I have tried the AJAX example posted on the jQueryUI website.
Comment: I think we're going need a few more clues to work with...
Comment: please post more relevant code and describe the problem further so we can help ...
Comment: @PerryW is this enough information now?
Comment: I am not sure you can use href="$tag" in jqueryUI tabs
Answer: I don't know why you getting error. are you sure you have correct file mentioned in the href ? it exists ?  JqueryUI Ajax tab

Policy Details

Edit Policy

Personal Details

asdf

asdf

Jquery.
$(function() {
    $( "#tabs" ).tabs({
      beforeLoad: function( event, ui ) {
        ui.jqXHR.error(function() {
          ui.panel.html(
            "Couldn't load this tab. We'll try to fix this as soon as possible. " +
            "If this wouldn't be a demo." );
        });
      }
    });
  });

if you got any error ? then may be your href location is not valid.
Comment: Yeah the page does exist, although like I mentioned earlier there was a tag mismatch. does the external page have to have the whole skeleton or just the body tags?
Comment: @SnakeEater External file should have whole skeletone.

jQuery UI tabs and external links


Apache SSL configuration testing

Question: When I run configtest on our Apache server, I get the following:
`Syntax error on line 1023 of /www/conf/httpd.conf:
Invalid command 'SSLEnable', perhaps mis-spelled or defined by a module not included in the server configuration`

I know this part of the configuration works. Is there a trick to make configtest mod_ssl aware?
EDIT:
RHEL4, nonstandard Apache 1.3 install? I just wanted to fix the ssl access log format to where Webalizer can give a clearer picture on who's still using this thing before we take the thing down. Since it's going away, no point upgrading apache just for this side project.
Answer: You get this error when mod_ssl is not loaded, because of this Apache doesn't know about the SSLEnable configuration directive. Make sure mod_ssl is installed and enabled in your configuration, you can get a list of modules by running httpd -M. If ssl_module is not listed you can install mod_ssl by running yum install mod_ssl (assuming RedHat EL is using yum as a package manager like CentOS).
Comment: With Apache 1.3 `-M` doesn't exist.  You can still run `-l` to list compiled-in modules.
Answer: If I understand correctly, you have mod_ssl installed and operational with the configuration but still receive an error when running configtest.
Are you using the apachectl appropriate to your installation?  If you have a package installed and it compiled from source as well, you may be running apachectl with a binary that isn't mod_ssl aware.

Apache SSL configuration testing


Add CSS just to the main content and not to include comments

Question: I'm theming using the Omega HTML5 starterkit theme on Drupal 7, and I want to add CSS just to the main content region in nodes but not to the comments.
How do I do that? What is the class (or ID) for that?
Comment: Why can't you just use Firebug and look for yourself?
Answer: In my own Omega subtheme, which is quite standard, page content with comments has this structure (closing tags omitted for brevity):

   (node body)

    (another node field I'm displaying)

So a CSS selector of:
node > content

would get you all the fields in the content, but not the comments. Or if you just want to style the body, you could choose it specifically.
Note that the content class is used a number of different places in a page. Alternatively you might want to set up  some default CSS for most of the node and style the #comments or .comment-wrapper separately.
This is not profound: I just poked around with Firebug to figure it out.


Envio de e-mail com Arduino

Question: Não estou conseguindo me conectar corretamente com o servidor smtp do gmail, diz "Username and Password not accepted", mas meu email e senha está correto, não estou sabendo exatamente onde está o erro.
<code>#include <SPI.h>
#include <Ethernet.h>
#include <Thermistor.h>
#include <Ultrasonic.h>

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
byte ip[] = { 192, 168, 100, 95 };
//EthernetClient client;

Thermistor temp(0);

EthernetServer server(5560);
char msg;

//Inicializa o sensor nos pinos definidos acima
#define pino_trigger 4
#define pino_echo 5
Ultrasonic ultrasonic(pino_trigger, pino_echo);

//Servidor Email
EthernetClient clientEmail;
char serverEmail[] = "smtp.gmail.com"; // Colocar o ip do servidor SMTP 220.127.116.11
int portaEmail = 587;
bool enviaEmail = false;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  Ethernet.begin(mac, ip);
  server.begin();
}

void loop() {
    Ultrasonico();
    delay(500);
}

void Ultrasonico(){
  //Le as informacoes do sensor, em cm e pol
  float cmMsec, inMsec;
  long microsec = ultrasonic.timing();
  cmMsec = ultrasonic.convert(microsec, Ultrasonic::CM);
  //Exibe informacoes no serial monitor
  //Serial.print("Distancia em cm: ");
  //Serial.print(cmMsec);
  //Serial.print("\n");
  if(cmMsec>9){
    if(!enviaEmail){
      if(EnviaEmail()){
        Serial.println(F("Email sent"));
      }
      else {
        Serial.println(F("Email failed"));
        delay(2000);
        enviaEmail = true;
      }
    }
  }
  else{
    //Serial.print("Fechado!\n");
  }
}

byte EnviaEmail() {
  byte thisByte = 0;
  byte respCode;
  Serial.println(F("conectando..."));
  if(clientEmail.connect(serverEmail,portaEmail) == 1) {
  Serial.println(F("connected"));
  } else {
  Serial.println(F("connection failed"));
  return 0;
  }

  if(!eRcv()) return 0;

  Serial.println(F("Sending hello"));
  // replace 126.96.36.199 with your Arduino's ip

  clientEmail.println("HELO 188.8.131.52\r\n");
  if(!eRcv()) return 0;

  clientEmail.println("STARTTLS oAuth2\r\n");

  Serial.println(F("Sending auth login"));
  clientEmail.println("auth login \r\n");
  if(!eRcv()) return 0;

  Serial.println("Sending User");
  // Change to your base64 encoded user
  clientEmail.println("Y2pyLnByb2pldG9maW5hbHRjY0BnbWFpbC5jb20=\r\n");

  if(!eRcv()) return 0;

  Serial.println("Sending Password");
  // change to your base64 encoded password
  clientEmail.println("xxxxxxxxx\r\n");

  if(!eRcv()) return 0;

  // change to your email address (sender)
  Serial.println(F("Sending From"));
  clientEmail.println("MAIL From: <firstname.lastname@example.com>\r\n");
  if(!eRcv()) return 0;

  // change to recipient address
  Serial.println(F("Sending To"));
  clientEmail.println("RCPT To: <email@example.com>\r\n");
  if(!eRcv()) return 0;

  Serial.println(F("Sending DATA"));
  clientEmail.println("DATA\r\n");
  if(!eRcv()) return 0;

  Serial.println(F("Sending email"));

  // change to recipient address
  clientEmail.println("To: Rodolfo Souza <firstname.lastname@example.com>\r\n");

  // change to your address
  clientEmail.println("From: Projeto TCC <email@example.com>\r\n");

  clientEmail.println("Subject: RoomX\r\n");

  clientEmail.println("Ola, a central foi aberta!\r\n");

  clientEmail.println(".");

  if(!eRcv()) return 0;

  Serial.println(F("Sending QUIT"));
  clientEmail.println("QUIT\r\n");
  if(!eRcv()) return 0;

  clientEmail.stop();

  Serial.println(F("disconnected"));
  enviaEmail = true;
  return 1;
}

byte eRcv()
{
  byte respCode;
  byte thisByte;
  int loopCount = 0;

  while(!clientEmail.available()) {
    delay(1);
    loopCount++;

    // if nothing received for 10 seconds, timeout
    if(loopCount > 10000) {
        clientEmail.stop();
        Serial.println(F("\r\nTimeout"));
        return 0;
      }
    }

    respCode = clientEmail.peek();

    while(clientEmail.available())
    {
      thisByte = clientEmail.read();
      Serial.write(thisByte);
    }

    if(respCode >= '4')
    {
      efail();
      return 0;
   }

  return 1;
}

void efail()
{
  byte thisByte = 0;
  int loopCount = 0;

  clientEmail.println(F("QUIT"));

  while(!clientEmail.available()) {
    delay(1);
    loopCount++;

    // if nothing received for 10 seconds, timeout
    if(loopCount > 10000) {
        clientEmail.stop();
        Serial.println(F("\r\nTimeout"));
        return;
      }
  }

  while(clientEmail.available())
  {
    thisByte = clientEmail.read();
    Serial.write(thisByte);
  }

  clientEmail.stop();

  Serial.println(F("disconnected"));
}
</code>
Após compilar, meu serial diz:

Se existir outra maneira de enviar e-mail pelo arduino, meu intuito é apenas que o arduino me envie um email.
Comment: veja se o seu gmail está habilitado para aplicativos menos seguros, você pode ver se está habilitado aqui http://www.google.com/settings/security/lesssecureapps estando logado com a sua conta do gmail
Comment: Ele está já esta ativado pois usava esse email para outros fins tbm.
Answer: Resolvi utilizando o email BOL
<code>#include <SPI.h>
#include <Ethernet.h>
#include <Thermistor.h>
#include <Ultrasonic.h>

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
byte ip[] = { 192, 168, 100, 95 };
//EthernetClient client;

Thermistor temp(0);

EthernetServer server(5560);
char msg;

//Inicializa o sensor nos pinos definidos acima
#define pino_trigger 4
#define pino_echo 5
Ultrasonic ultrasonic(pino_trigger, pino_echo);

//Servidor Email
EthernetClient clientEmail;
byte serverEmail[] = {200,147,99,132}; // Colocar o ip bol
int portaEmail = 587;
bool enviaEmail = false;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  Ethernet.begin(mac, ip);
  server.begin();
  Serial.println(F("Setup"));
}

void loop() {
    Ultrasonico();
    delay(500);
}

void Ultrasonico(){
  //Le as informacoes do sensor, em cm e pol
  float cmMsec, inMsec;
  long microsec = ultrasonic.timing();
  cmMsec = ultrasonic.convert(microsec, Ultrasonic::CM);
  //Exibe informacoes no serial monitor
  //Serial.print("Distancia em cm: ");
  //Serial.print(cmMsec);
  //Serial.print("\n");
  if(cmMsec>9){
    if(!enviaEmail){
      if(EnviaEmail()){
        Serial.println(F("Email sent"));
      }
      else {
        Serial.println(F("Email failed"));
        delay(2000);
        enviaEmail = true;
      }
    }
  }
  else{
    enviaEmail = false;
  }
}

byte EnviaEmail() {
  byte thisByte = 0;
  byte respCode;
  Serial.println(F("conectando..."));
  if(clientEmail.connect(serverEmail,portaEmail)) {
  Serial.println(F("connected"));
  } else {
  Serial.println(F("connection failed"));
  return 0;
  }

  if(!eRcv()) return 0;

  Serial.println(F("Sending hello"));
  // replace 188.8.131.52 with your Arduino's ip

  clientEmail.println("HELO 192.168.100.95");
  if(!eRcv()) return 0;

  //clientEmail.println("STARTTLS oAuth2\r\n");

  Serial.println(F("Sending auth login"));
  clientEmail.println("auth login");
  if(!eRcv()) return 0;

  Serial.println("Sending User");
  // Change to your base64 encoded user
  clientEmail.println("cm9vbXhAYm9sLmNvbS5icg==");

  if(!eRcv()) return 0;

  Serial.println("Sending Password");
  // change to your base64 encoded password
  clientEmail.println("xxxxxxxxxxxx");

  if(!eRcv()) return 0;

  // change to your email address (sender)
  Serial.println(F("Sending From"));
  clientEmail.println("MAIL From: <firstname.lastname@example.com>");
  if(!eRcv()) return 0;

  // change to recipient address
  Serial.println(F("Sending To"));
  clientEmail.println("RCPT To: <firstname.lastname@example.com>");
  if(!eRcv()) return 0;

  Serial.println(F("Sending DATA"));
  clientEmail.println("DATA");
  if(!eRcv()) return 0;

  Serial.println(F("Sending email"));

  // change to recipient address
  clientEmail.println("To: Rodolfo Souza <email@example.com>");

  // change to your address
  clientEmail.println("From: Roomx AI <firstname.lastname@example.com>");

  clientEmail.println("Subject: RoomX");

  clientEmail.println("Ola, a central foi aberta!");

  clientEmail.println(".");

  if(!eRcv()) return 0;

  Serial.println(F("Sending QUIT"));
  clientEmail.println("QUIT");
  if(!eRcv()) return 0;

  clientEmail.stop();

  Serial.println(F("disconnected"));
  enviaEmail = true;
  return 1;
}

byte eRcv()
{
  byte respCode;
  byte thisByte;
  int loopCount = 0;

  while(!clientEmail.available()) {
    delay(1);
    loopCount++;

    // if nothing received for 10 seconds, timeout
    if(loopCount > 10000) {
        clientEmail.stop();
        Serial.println(F("\r\nTimeout"));
        return 0;
      }
    }

    respCode = clientEmail.peek();

    while(clientEmail.available())
    {
      thisByte = clientEmail.read();
      Serial.write(thisByte);
    }

    if(respCode >= '4')
    {
      efail();
      return 0;
   }

  return 1;
}

void efail()
{
  byte thisByte = 0;
  int loopCount = 0;

  clientEmail.println(F("QUIT"));

  while(!clientEmail.available()) {
    delay(1);
    loopCount++;

    // if nothing received for 10 seconds, timeout
    if(loopCount > 10000) {
        clientEmail.stop();
        Serial.println(F("\r\nTimeout"));
        return;
      }
  }

  while(clientEmail.available())
  {
    thisByte = clientEmail.read();
    Serial.write(thisByte);
  }

  clientEmail.stop();

  Serial.println(F("disconnected"));
}
</code>
Answer: Para enviar email usando o SMTP do Gmail, Live ou Yahoo tu precisas usar SSL, Porém ...
no caso do Gmail será necessário acessar as configurações da tua conta google e "Permitir aplicativos menos seguros", link direto ->  https://myaccount.google.com/lesssecureapps

Envio de e-mail com Arduino


Eclipse maven | lambda | use -source 8 or higher to enable lambda expressions

Question: Projeto Java Maven no Eclipse neon (4.6.0), simplesmente não compila ao utilizar lambda.
O erro:

use lambda expressions are not supported in -source 1.5 (use -source 8
  or higher to enable lambda expressions)

O detalhe é que estou usando o JDK 8:

java version "1.8.0_101" Java(TM) SE Runtime Environment (build 1.8.0_101-b13) Java HotSpot(TM) 64-Bit Server VM (build 25.101-b13, mixed mode)

O Eclipse também está configurado corretamente conforme imagens abaixo:

Alguma ideia do motivo de estar dando erro de lambda?
Answer: O código do seu pom.xml também deve referenciar o java8. Ficaria da seguinte forma:
<build>
    <plugins>
        <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.0</version>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
            </configuration>
        </plugin>
    </plugins>
</build>

Comment: Funcionou, mas eu nunca tinha precisado fazer isso, sabe o motivo? Obrigado.
Comment: Sim, toda vez que você faz build do projeto maven ele troca a versão do java que você tinha selecionado. Por isso você precisa sempre informar isso no pom.


Quotient of scalar products

Question: Given fixed $x$ and $y$. Is it possible to extend the quotient $\frac{<x,1>}{<y,1>}?=?\frac{<x,a>}{<y,a>}$ where $<,>$ is the common dot product,$a$ is any vector and $1$ is a vector of $1's$.
Where extend means $\frac{a}{b}\cdot 1=\frac{a}{b}\cdot \frac{c}{c}=\frac{ac}{bc} $
Comment: What does it mean to extend a quotient?
Comment: It's easy enough to make up some examples where your two fractions aren't equal. I think you get equality only when $a$ is a scalar multiple of a vector with all $1$s. But as @lulu pointed out, I'm also not sure what it means to extend a quotient.
Comment: @lulu $\frac{a}{b}\cdot 1=\frac{a}{b}\cdot \frac{c}{c} $
Comment: What on earth does that mean?
Comment: I don't think  you have thought through your question.  Take a look at the usual inner product on $\mathbb R^2$.  In that context you should be able to write out whatever you meant explicitly.
Comment: $\frac{a}{b}\cdot 1=\frac{ac}{bc}$? is that more clear?
Answer: With $1 = (1, \ldots, 1)$ it's not true that $\frac{\langle x, 1 \rangle}{\langle y, 1 \rangle} = \frac{\langle x, a \rangle}{\langle y, a \rangle}$ for any vector $a$. For example, take $x=(1, -1),\ y=(1,1),\ a=(1,0).$ Then,
$$\begin{align}
\langle x, 1 \rangle &= 1\cdot 1 + (-1)\cdot 1 = 0, \\
\langle y, 1 \rangle &= 1\cdot 1 + 1 \cdot 1 = 2, \\
\langle x, a \rangle &= 1\cdot 1 + (-1) \cdot 0 = 1, \\
\langle y, a \rangle &= 1\cdot 1 + 1 \cdot 0 = 1, \\
\end{align}$$
so
$\frac{\langle x, 1 \rangle}{\langle y, 1 \rangle} = \frac{0}{2} = 0$
but
$\frac{\langle x, a \rangle}{\langle y, a \rangle} = \frac{1}{1} = 1.$

Quotient of scalar products


Excel - Disabel ability to manually change sheets (but don't hide them)

Question: Apologies if this is a really stupid question but I've not been able to find a solution.
I've got a main page on my Excel workbook with a number of filter options and some buttons linked to vba code. When clicking the button it takes you another tab with a load of data filtered appropritately. There is a button there that removes the filters and takes you back.
This all works fine but what I want to do is stop people being able to manually change sheets but clicking on the tabs at the bottom of the screen. So far the only method I've found is hiding them, but this obviously doesn't work as you then can't see that data.
Comment: go to excel option > Advanced > Display options  and Uncheck 'Show sheet tabs'. This will hide the sheet tabs, so visually to a user it will show only main page. Make sure you have navigation link intact. However this will not disable changing sheet by Ctrl + PgDn.
Comment: what is the point of being able to see the data on the sheets, but not being able to navigate them? In other words, if you don't want people to be able to navigate to the sheets but you want the data to be seen... it's not making sense. Do you want only certain people (like you as the developer) to see the sheets?
Comment: Disabling the sheet tabs is exactly what I was after. Seems like such a simple solution. Thanks.
Answer: You can disable the editing of the sheet tab names by turning them off on the excel options as mentioned in the comment above. The downside to this approach is the user won't be able to see what sheet they are on (which I find incredibly frustrating).
The better method in my mind is to set up an event listener for when the user changes the name of the tab. You can then send a pop up box that appears when the user attempts to change the tab name.


A question about the definition of $\overline{\nabla}_X \langle Y,Z\rangle$

Question: Lee's "Riemannian Manifolds" has the following theorem:

The Euclidean connection on $\Bbb{R}^n$ has one very nice property with respect to the Euclidean metric: it satisfies the product rule
  $$\overline{\nabla}_X \langle Y,Z\rangle=\langle \overline{\nabla}_XY,Z\rangle + \langle Y,\overline{\nabla}_XZ\rangle$$

But $\langle Y,Z\rangle$ is not a vector field. How does $\overline{\nabla}_X \langle Y,Z\rangle$ make sense?
Answer: Yes, $\langle Y, Z \rangle$ is a scalar, not a vector, field.  $\overline \nabla_X \langle Y, Z \rangle$ make sense by virtue of the fact that, for scalar fields $f$, we define
$\overline \nabla_X f = X[f] = \dfrac{\partial f}{\partial t}, \tag 1$
where $t$ is a parameter along the integral curves of $X$:
$X = \dfrac{\partial}{\partial t}; \tag 2$
then the formula
$\overline \nabla_X \langle Y, Z \rangle = \langle \overline \nabla_X Y, Z \rangle + \langle Y, \overline \nabla_X Z \rangle \tag 3$
expresses
$\overline \nabla_X \langle Y, Z \rangle = X[\langle Y, Z \rangle] \tag 4$
as the sum of the two inner products $\langle \overline \nabla_X Y, Z \rangle$ and $\langle Y, \overline \nabla _X Z \rangle$.
This is all of course just a generalization of the well-known formula in Euclidean spaces:
$\dfrac{d}{dt} (\vec v(t) \cdot \vec y(t)) = \dot {\vec v}(t) \cdot \vec y(t) + \vec v(t) \cdot \dot {\vec y}(t), \tag 5$
where $t$ is the parameter along some curve on which $\vec v(t)$, $\vec y(t)$ are defined.
Comment: This is exactly right. See Lemma 4.6(b) in my book for the definition of covariant derivatives of scalar functions (i.e., $0$-tensor fields).
Comment: The only online version currently available (legally, anyway) is a PDF e-book that can be [purchased from Springer](https://www.springer.com/us/book/9780387982717). But I would advise against buying it right now, because the much-improved [second edition](https://www.springer.com/us/book/9783319917542) should be available within a month or two. If you're connected with a university that has a subscription to Springer's GTM series, you'll be able to read the second edition online for free.
Comment: @JackLee:  is your book available online?  and thanks for the kind words!
Comment: @JackLee:  OK, thanks.  I may be able to access it through my university.


Como fazer para um textbox receber apenas números

Question: Como eu faço para um textbox receber apenas número, mas apenas para o WPF. Com winform eu consigo fazer, mas com WPF não consegui ainda.
Answer: Você pode usar o evento PreviewTextInput do TextBox.
1. Layout (XAML)
Adicione o evento PreviewTextInput no seu TextBox:
<TextBox HorizontalAlignment="Left" Height="23" Margin="10,181,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120" PreviewTextInput="TextBox_PreviewTextInput"/>

2. Code Behind (.cs)
Adicione o seguinte using:
using System.Text.RegularExpressions;

Adicione o método para o evento PreviewTextInput:
private void TextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
    var textBox = sender as TextBox;
    e.Handled = Regex.IsMatch(e.Text, "[^0-9]+");
}


Solving the Laplace transform

Question: I need to find transformation $F(s)$ for:
$f(t)=tsin(ωt)$
Could somebody please help me?
Answer: First of all, use the property:
$$\mathcal{L}_x\left[x\text{y}\left(x\right)\right]_{\left(\text{s}\right)}=-\frac{\text{d}}{\text{ds}}\left(\mathcal{L}_x\left[\text{y}\left(x\right)\right]_{\left(\text{s}\right)}\right)\tag1$$
Now, use:
$$\mathcal{L}_x\left[\sin\left(\omega x\right)\right]_{\left(\text{s}\right)}=\frac{\omega}{\text{s}^2+\omega^2}\tag2$$
So, you will get:
$$\mathcal{L}_x\left[x\sin\left(\omega x\right)\right]_{\left(\text{s}\right)}=-\frac{\partial}{\partial\text{s}}\left(\frac{\omega}{\text{s}^2+\omega^2}\right)\tag3$$
Comment: Thank you, but it is still complex to me. Are you able to show me step by step how to solve this? I think the biggest problem I have is to use the property because i get a different result
Comment: @DominikMazur show us what you've tried
Comment: I have no idea how to add equation here
Comment: @DominikMazur exactly as you did in your question.
Comment: So I make it alternate form: f(t) = 1/2 ite (escalating -itw) - 1/2 (esclating itw)
Comment: Then i tried to derivative: a/at(tsin(tω)) = sin (tω)+tωcos(tω
Comment: I tried to do it in different ways but i don't even understand what i do. I need someone who will explain it to me step by step how to do this transformation beacuse at the end i have always different results than my colleagues
Comment: @DominikMazur If you don't want to use the properties, try it find: $$\int_0^\infty t\sin(\omega t)\exp(-\text{s}t)\space\text{d}t$$
Comment: ok, but how? I don't understand this at all
Comment: @DominikMazur What is your background in calculus? Because if you have talked about Laplace transform your calculus class has to be taught beforehand.

Solving the Laplace transform


For syndetic set $S\subseteq G$, is there $e\neq g\in G$ such that $gS\cap S$ is a syndetic set?

Question: Let $G$ be a topological group, $S\subseteq G$ is a syndetic set if there is a compact set $K\subseteq G$ with $G=KS$.
Let $\mathcal{P}$ be family of all syndetic sets in $G$,
Question. For every $S\in \mathcal{P}$, Is there $e\neq g\in G$ with $gS\cap S\in \mathcal{P}$?
Answer: In general, no. Indeed, let $G$ be the group of reals with the standard topology. Let $S$ be any dense subset of $\Bbb R$ consisting of real numbers linearly independent over $\Bbb Q$. Such a set $S$ can be constructed inductively as follows. Fix a countable base $\{U_n\}$ of the space $G$ (consisting of non-empty sets) and for each $n$ pick any element $s_n\in U_n\setminus\langle s_1,\dots, s_{n-1}\rangle\Bbb Q$ (we recall that $\langle A\rangle$ denotes the subgroup generated by a subset $A$ of $G$). Since the group $G$ is locally compact and $S$ is a dense subset of $G$, $S$ is syndetic in $G$. On the other hand, suppose that there exists a non-zero element $g$ of $G$ such that $|(g+S)\cup S|\ge 2$. Then there exist elements $x_1, x_2, y_1, y_2\in G$ such that $x_1\ne x_2$, $x_1+g=y_1$, and $x_2+g=y_2$. Thus $g=y_1-x_1=y_2-x_2$. If $x_1$ is different from each of $x_2$,
$y_1$, and $y_2$ then we obtain a contradiction with the linear independence of the set $S$. Since $x_1\ne x_2$ and $x_1\ne x_1+g=y_1$, the only remaining possibility is $x_1=y_2$. But then $2x_1=y_1+x_2$ and we again obtain a contradiction with the linear independence of the set $S$.
Comment: Dear Prof. Alex Ravsky.  Thanks a lot for your reply. If $G$ is a locally compact and $S$ is a dense subset of $G$, Is it true that $S$ is syndetic?(in general)
Comment: @AliBarzanouni Yes.


Set view header full width (css child conflict)

Question: I created a drupal website using the foundation theme.
At the page level the content is put inside a container.
Now I created a view and I want the header of this view (using an entity rendered entity) to be full width.
But the page layout is inside a container so the child (views template) cannot exceed it's width. How can I set the header to full width without breaking the page layout?
Comment: I haven't downvoted but I must admit this does seem like an HTML/CSS issue. The short answer would be to restructure your theme's HTML/CSS as necessary to accommodate your design. I don't think there's much Drupal core or a module could do to do that restructuring for you, unless maybe you do something drastic like moving to Panels. If you can tell us in basic HTML/CSS terms how you would make that `` appear as full width (which is the crux of the issue), we can probably tell you how to make that happen in Drupal.
Comment: Why is this getting downvotes? It's not per se a css question. It's about page to node structure
Answer: Create header content as a seperate block and place it in the desired region. Set block visibility as views content.
Comment: But it should be kept dynamic. Different headers for different views. Is that possible using your solution?
Comment: Yes. It will be. you should set visibility of block as view page path only.
Comment: I guess I should use the block views visibility module?
Answer: change the page layout in page.tpl.php:
move the container up the DOM structure until you get 100% width,
this will result in closing the parent(s) of the container,
having the container, and opening the parent(s) again.
or create a new region that will be in 100% width scope, and place the block there
Answer: best thing to do is just comment/hide of most of the html/php in page.tpl and then go from there.
First way to solve issues relating to css is go in views and go through all format/field and make sure there is no extra html/css markup.
Second best thing is to get CSS formatter class module and go in manage displays of that view and set a new css class and update the .css with a wrapper.
Answer: 1 - Create a sub-theme based on your current theme and make the page.tpl to full width.
2 - Install theme-key module.
3 - Create a rule to switch theme based on the view you want.