Definition of Willmore energy in higher dimensions

Question: The Willmore energy is a well-known and studied quantity typically defined for surfaces immersed in a 3-dimensional manifold as the integral of the square of the mean curvature (see https://en.wikipedia.org/wiki/Willmore_energy).
I was wondering if there is any standard notion of Willmore energy  for a $n$-dimensional submanifold of a $(n+1)$-dimensional Riemannian manifold. I couldn't find much material online, so I thought that this was the right place where to ask.
Any help will be very appreciated! Thanks a lot!
Comment: This is a perfectly valid question with a rich history and a lot of amazing results to mention. I am really disappointed with the poor judgment of the members who put it on hold without even making comments or trying to improve it. This is not in the spirit of this community to repel the users by pushing them off the topics that you don't care about. Very disappointed...
Comment: I started writing a little survey on this question [here](https://anglesmatter.wordpress.com/2018/06/23/the-willmore-functional-in-higher-dimensions/). Provided there is an interest to this topic, I am happy to post updates and answer further questions.
Comment: @YuriVyatkin I am also surprised! I don't really understand why the question was put on hold.. I couldn't find much material online about a possible definition of the Willmore energy in higher dimension and I thought that this was the natural place where to ask. Thanks a lot for caring about my question and thanks for writing that nice note! :)
Comment: You are welcome. Anyway, the community here decides what is worthy, so I would suggest you to follow the guidelines above and edit your question, so that the folks change their mind and add more votes for reopening it. Add your definition of the Willmore energy and some motivation for your question.
Comment: Anyway, you are right, I made a mistake in the note. Please see the updated version there. Sorry, I have not been thinking on this topic for quite a while and need to recapitulate it for myself.
Comment: @YuriVyatkin I have a question about your note. If I have well understood, you say that $\mathcal{W}$ is invariant under conformal transformation of the ambient space. But I think I am missing something. Take for instance a minimal surface in $\mathbb{S}^3$, for instance an equatorial sphere. This will have 0 Willmore energy in  $\mathbb{S}^3$. But its image in $\mathbb{R}^3$ under the stereographic projection can't have 0 Willmore energy..
Comment: I appreciate your interest but the comments here is not an appropriate place for continuing the discussion. Please either 1) create a question on this site with a specific topic and concerns; or 2) leave comments under my [post](https://anglesmatter.wordpress.com/2018/06/23/the-willmore-functional-in-higher-dimensions/), or 3) contact me directly. Cheers!
Answer: Let us consider an embedding $\Sigma \to M$ where $\dim \Sigma = n$ and $M$ is a Riemannian manifold, with all the additional assumptions made when needed in order to the following could make sense.
Already Willmore [1] mentions (p.282) the integrals (for the case $M = \mathbb{R}^{n+1}$)
$$
W(\Sigma) = \int_{\Sigma} |H|^n \mathrm{d}\Sigma \tag{1}
$$
and the related work of B.-Y. Chen on computing their Euler-Lagrange equations. He notices that these integrals are not conformally invariant except when $n = 2$. Here $\mathrm{d}\Sigma$ is the Riemannian volume form induced on $\Sigma$.
In [2] Guo constructs a series of functionals $W_r, 2 \le r \le n,$ where the integrands are certain powers of polynomials of the principal curvatures of $\Sigma$. The functionals $W_r$ generalize the Willmore functional to higher dimensions ($W = C\cdot W_2$, where $C$ is a constant). Moreover, $W_r$ are conformally invariant (with respect to rescalings of the metric in $M$). Explicitly,
$$
W_2(\Sigma) = \int_M (\sigma^2_1 - \sigma_2)^{n/2} \mathrm{d} \Sigma \tag{2}
$$
The integrand in (2) is $n$-th power of the length of the trace-free part of the second fundamental form (the quantity, that I prefer to call the umbilicity tensor, for the sake of brevity).
The umbilicity tensor is a classical example of a hypersurface conformal invariant (these are the central topic of my PhD thesis, by the way). Then notation for this tensor is not widely adopted, so instead of writing something like $\overset{\circ}{L}$ (that I usually do), let me just denote it here by $U$, so that we can consider
$$
\mathcal{W} = \int_{\Sigma} |U|^2 \mathrm{d}\Sigma \tag{3}
$$
for the case $n = 2$. This is obviously a global conformal invariant of $\Sigma$ (Global conformal invariants in general have been studied in detail by Spyros Alexakis, but this one is rather special one, intimately related to the hypersurface structure).
The integrand in (3) is a nice Riemannian quantity: it arises as a polynomial expression in partial derivatives of the metric and transforms naturally under coordinate changes (in other words, this is a natural Riemannian ir curvature invariant of $\Sigma$).
If we require that the Willmore energy generalizes to the case of a Riemannian background and higher dimensions so that this generalizations satisfies the following conditions:

the integrand is a natural Riemannian invariant (possibly, of a higher
order, that is we can consider covariant derivatives of the curvature
and the second fundamental form);
the integral is a global conformal invariant of the hypersurface $\Sigma$;

then the problem of generalizing the Willmore energy becomes very non-trivial.
J.Guven in [3] found a $4$-dimensional analogue of $W$ in a Euclidean background:
$$
H_2 = \frac{1}{2} \int \Big( (\nabla K)^2 - \frac{7}{8} K^4 + 2 K^2 \mathrm{tr} K^2 \Big) \mathrm{d}\Sigma
$$
where by $K$ he denoted the shape tensor (essentially, the second fundamental form).
During my PhD study under supervision by A.Rod Gover, we discovered a quantity closely related to the so called $Q$-curvature, which also generalizes the Willmore functional to the case of $4$-dimensional hypersurfaces. Actually, I only scratched the surface gently...
The problem as stated above was completely solved by A.Rod Gover and Andrew Waldron using a set of powerful techniques, including so-called boundary calculus.
Some additional remarks and curious links you can find in my post here.
References:

T.J. Willmore, Riemannian Geometry (OUP, 1993)
Zhen Guo, Generalized Willmore functionals and related variational problems, Diff.Geom.and its App. 25 (2007) 543-551
Jemal Guven, Conformally invariant bending energy for hypersurfaces,  J. Phys. A: Math. Gen. (2005), Vol.38, Num.37.
A. Rod Gover, Andrew Waldron, Generalising the Willmore equation: submanifold conformal invariants from a boundary Yamabe problem, (2014)    arXiv:1407.6742 [hep-th]


How to use Media Segmenter for split video?

Question: I have read many documents still very confused about HTTP Live Streaming.
But i am still trying for solution.. and i have convert my video in .ts format with ffmpeg.
Now i know that i have to split my video and have to create playlist with the use of mediasegmenter.
But i don't know where is mediasegmenter and how to use it to split video.
I am very new to this so sorry for this silly Question..
Any help would be appreciated..!!
Thanks in advance..!!
Comment: Just curious, you said ...in mac but you don't tags in iphone and iOS but no mac or OSX
Comment: That was my mistake.. corrected it..
Answer: Here: 35703_streamingtools_beta.dmg or go to http://connect.apple.com/ and search for "HTTP Live Streaming", or download from https://developer.apple.com/streaming/. Usage:
mediafilesegmenter -t 10 myvideo-iphone.ts

This will generate one .ts file for each 10 seconds of the video plus a .m3u8 file pointing to all of them.
Comment: i downloaded `HTTP Live Streaming Tool` and installed it. now i have  `sample.mp4` video on desktop. so i have to wright this code `mediafilesegmenter -t 10 sample.mp4` in terminal?? Am i right or doing something wrong..???
Comment: Yes, it should be on your path. Just type mediafilesegmenter. It is installed in /usr/bin/mediafilesegmenter.
Comment: Actually i can't see mediafilesegmenter in use/bin/..  Do you think it would be hidden..?? and i wright `mediafilesegmenter -t 10 sample.mp4` in terminal but it shows some options like `-b   | --base-url=    : base url (omit for relative URLs)
 -t   | --target-duration= : target duration for each segment ` and some other options...
Comment: Try downloading from: http://developer.apple.com/resources/http-streaming/ It should show on console if you type `ls -la /usr/bin/mediafilesegmenter`. If you type `mediafilesegmenter -t 10 sample.ts` it shouldn't show the usage screen, even if the video file sample.ts is missing.
Comment: i've downloaded from the same link.. if i type `ls -la /usr/bin/mediafilesegmenter` then i got `-rwxr-xr-x  1 jigar  wheel  1852172 Oct 28 03:07 /usr/bin/mediafilesegmenter` and if i type `mediafilesegmenter -t 10 Desktop/sample.mp4` then i get `Nov  2 2011 18:21:00.352: Finalized fileSequence0.ts
Nov  2 2011 18:21:00.357: segment bitrate 464285 is new max
Nov  2 2011 18:21:00.392: Finalized fileSequence1.ts
Nov  2 2011 18:21:00.404: segment bitrate 873824 is new max
Nov  2 2011 18:21:00.411: Finalized fileSequence2.ts` up to `Nov  2 2011 18:21:00.420: Finalized fileSequence74.ts`
Comment: That looks right, now you have to move the .ts files and m3u8 file to a web server.
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/4684/discussion-between-jano-and-snhl)
Answer: If you use FFMpeg, it's very easy to split files with it.
Don't use Media Segmenter.
Simply write something like this:
ffmpeg.exe -i YourFile.mp4 -ss 00:10:00 -t 00:05:00 OutFile.mp4

where -ss 00:10:00 is time offset , -t 00:05:00 is duration of OutFile.mp4.
This will create OutFile.mp4 which contains 5 minute video(-t 00:05:00) of YourFile.mp4
(from 00:10:00 to 00:15:00 of YourFile.mp4).
Useful ?)
And also you can create .ASX playlist which is able to cast streams and is very simple.


fancybox and onfocus

Question: I need to load fancybox with inside php file, when I will click on textarea.
My code:

<textarea rows="4" cols="50" onfocus="#mypop" ></textarea>

Why this is not working ?
Answer: You need to change your textarea tag: remove onfocus="#mypop" and add id="mypop". The $("#mypop") function-call will search for an element with id="mypop", and the click(function(){...}) function will add the event-listener. This function-call also makes the onfocus=-attribute unnecessary.
Comment: Thank you I forgot to add before $("#mypop").click(function() to add $(document).ready(function() :) now it works!
Comment: Ok but what will be with Submit button ? What will I need to write in input onclick ?
Comment: I don't actually know anything about fancybox, so I can't give you any specific advise. But if it has an element on the page it displays when needed (as opposed to creating it using Javascript). Then you can look up the id of the submit-button and add your send-function as an event-listener to it.
Answer:
<textarea rows="4" cols="50" id="mypop" ></textarea>
By: Jose ALfredo Cocom Chan

fancybox and onfocus


How to handle MapView touch event

Question: How do you handle the touch of a MapView so it allows me to insert a marker by touching a point on the map?
I would also like the coordinates of that point.
Answer: You can set an OnMapClickListener directly on the GoogleMap object.
For example
 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);

        MapFragment mapFragment = (MapFragment) getFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

    }

    @Override
    public void onMapReady(GoogleMap map)
    {
        googleMap = map;

        googleMap.setOnMapClickListener(new OnMapClickListener(){
            void onMapClick(LatLng point){
                Toast.makeText(Activity.this,
                        point.latitude + ", " + point.longitude,
                        Toast.LENGTH_SHORT).show();
            }
        });

    }

Reference
Comment: I gets me off the following error, even if I initialized the object type googleMap..                                                                                'Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.maps.GoogleMap.setOnMapClickListener(com.google.android.gms.maps.GoogleMap$OnMapClickListener)' on a null object reference'
Comment: Put the setOnMapClickListener into onMapReady() method

How to handle MapView touch event


On an equation satisfied by the irreducible characters of a finite group

Question: I have the following question:
Let $G$ be a finite group, $\hat{G}$ the set of irreducible characters of $G$ (up to equivalence), and $n = |G|$. Given $x,g \in G,$ show
\begin{equation*}
\frac{1}{n}\sum_{\chi \in \hat{G}}\mathrm{deg}(\pi)\chi_{\pi}(gx^{-1})=\delta_{g,x}.
\end{equation*}
I can prove that the sum is equal to $1$ when $g=x$, but I haven't been able to make progress for the other case.
I have tried rearranging the sum, and also introducing a factor of $\chi'(gx^{-1})$ for a suitable $\chi'$ in the hopes of showing it doesn't change the sum, however, with $\hat{G}$ not being abelian this wasn't fruitful.
All answers are appreciated, hints are preferred.
Answer: It is well known that the regular representation $(\rho, V)$ of $G$ decomposes as
$$\rho\sim\oplus_{\pi}\deg(\pi)\pi,$$
where the direct sum is taken over a complete set of inequivalent irreducible representations of $G$
(for instance, see here).
Therefore, we can write $\chi_\rho=\sum_\pi\deg(\pi)\chi_\pi$. In other words,
$$\chi_\rho(g)=\sum_\pi\deg(\pi)\chi_{\pi}(g)$$ for all $g\in G$.
We have $$\chi_{\rho}(g)=\begin{cases}n,&g=1\\0,&g\neq 1\end{cases}$$ by direct calculations. Thus
$$\sum_\pi\deg(\pi)\chi_{\pi}(gx^{-1})=\chi_\rho(gx^{-1})=\begin{cases}n,&g=x\\0,&g\neq x\end{cases}.$$
Comment: Can you briefly elaborate on the direct calculations mentioned to compute $\chi_{\rho}(g)$?
Comment: @carraig: Given $g\in G$, $\rho_g$ takes a basis element $h$ to $gh$. If $g\neq 1$, then $h\neq gh$. This implies that the diagonal entries of the matrix corresponding to $\rho_g$ are zero.


Proving the "extended version" of Markov's inequality

Question: I am trying to prove the "extended version" of Markov's inequality:

Suppose $(X, \mathcal S, \mu)$ is a measure space and $h: X \to \mathbb R$ is an $\mathcal S$-measurable function. Prove that
\begin{align}
    \mu\left(\left\{ x\in X: \left|h(x) \right|\ge c
    \right\}\right) \le
    \frac{1}{c^p} \left(\int |h|^p \; d\mu \right)
\end{align}
for any positive numbers $c, p$.

I have the proof for the $p=1$ case. I want to use induction to prove this for any positive number $p$. Of course, the first step in the induction process would be assuming that
\begin{align}
    \mu\left(\left\{ x\in X: \left|h(x)\right|\ge c
    \right\}\right) \le
    \frac{1}{c^p} \left(\int |h|^p \; d\mu \right)
\end{align}
is true. Then, we would need to show that
\begin{align}
    \mu\left(\left\{ x\in X: \left|h(x)\right|\ge c
    \right\}\right) \le
    \frac{1}{c^{p+1}} \left(\int |h|^{p+1} \; d\mu \right)
\end{align}
How can the last inequality be proven given the induction hypothesis? Should I even use induction here?
Comment: Why is there the subtraction of the expected value?
Comment: @Snoop Because it was a typo. :) Gone now.
Answer: No need for induction (you also need any $p>0$). Because
$$\mu(|f|\geq c )=\mu(|f|^p\geq c^p )=\frac{1}{c^p}\int c^p \mathbb{I}_{\{|f|^p \geq c^p\}}\,d\mu$$
So (because $\mathbb{I}_{\{|f|^p \geq c^p\}} \leq \mathbb{I}_\Omega$)
$$\frac{1}{c^p}\int c^p \mathbb{I}_{\{|f|^p \geq c^p\}} \, d\mu \leq \frac{1}{c^p}\int |f|^pd\mu$$
Therefore
$$\mu(|f|\geq c ) \leq \frac{1}{c^p}\int |f|^pd\mu$$
$$$$
Answer: If you have the $p=1$ case, then you can handle the other cases immediately by noting
$$\{x \in X: |h(x)| \ge c\} = \{x \in X : |h(x)|^p \ge c^p\}.$$


Reporting results of fixed effect MA alongside results of random effects MA

Question: I have conducted meta-analyses for a Cochrane systematic review. I was comfortable pre-specifying and justifying whether a fixed effect or random effects approach will be used in the MA. Having completed the meta-analyses and used random effects models in some instances my co-author is requesting that I include results from fixed effect models alongside the random effects results.
Given that I pre-stated the analysis approach (although this is an update so there is no registered protocol per-se), then reporting both RE and FE results seems to undermine the purpose of pre-stating the analysis approach.
Should I simply include the FE results, and be clear that they come under sensitivity analysis or stick to my guns and only report what I said would be done? My co-author's view is that FE is more reliable when there is no heterogeneity or there is suspected publication bias.
Comment: In my opinion, there is nothing wrong with including the results of FE as sensitivity analysis. It gives indeed more information about the meta-analysis at hand. I would not say that FE is more reliable when there is no heterogeneity in true effect size. The RE model actually reduces to the FE model if there is no heterogeneity. FE assigns less weight to smaller studies if there is heterogeneity, so comparing the results of FE and RE can indeed be insightful if publication bias is present.
Answer: The debate over FE vs. RE often reflects around the lack of understanding of the concepts behind the models. To make matters worse, the Cochrane handbook only briefly touches on this (9.4.2  Principles of meta-analysis) and provides some guidance on whether or not the posthoc decision to use the FE or the RE was the correct one (10.4.4.1  Comparing fixed and random-effects estimates). From the Handbook: "The combination of intervention effect estimates across studies may optionally incorporate an assumption that the studies are not all estimating the same intervention effect, but estimate intervention effects that follow a distribution across studies. This is the basis of a random-effects meta-analysis (see Section 9.5.4). Alternatively, if it is assumed that each study is estimating exactly the same quantity a fixed-effect meta-analysis is performed."
In only the rarest types of meta-analyses (e.g. same trial repeated multiple times with the same exact protocol) could we assume that the studies are all estimating the same intervention effect, with between-study differences in results attributed to random error. On the other hand, we typically combine studies that use similar populations, similar interventions, similar comparisons, similar doses, etc. assuming that the studies have a reasonable amount of clinical homogeneity allowing their data to be pooled together.
Therefore, IMHO, the decision to use the FE or RE model should be performed at the protocol stage since the actual results do not play a factor in the model choice. Having said that, as noted in section 10.4.4.1 of the Handbook, this choice may need to be reversed after seeing the results of the meta-analysis; if there is suspicion of small-study effect skewing the pooled results.
So, in closing, unless there is justification for the use of FE model, the RE model should be the default choice when conducting a meta-analysis from different study results. Of course, that doesn't mean you can't test test the robustness of the analyses in a sensitivity analysis (FE model). Actually a lot of Cochrane groups request this.
Comment: This to me is the key point "...the decision to use the FE or RE model should be performed at the protocol stage", but with the pragmatic inclusion of sensitivity analysis involving FE as appropriate. I think this trumps the Cochrane Handbook's recommendation to revise the analysis approach if small-study effects are suspected.
Answer: To answer this question, one must first consider when the meta analytic estimates from a RE model differ from a FE model. If there is zero between-study heterogeneity, but one uses the RE model, the estimate and interval will be equivalent to a FE model. This is because the FE is assuming 0 heterogeneity. Now, when the estimates differ, this is because there is some degree of variability in the individual effects.
With this in mind, you can ALWAYS assume a RE model, and if there happens to be zero heterogeneity, then your estimates will accurately reflect that fact. The opposite is not true, however, as fixing tau to zero with a FE model "forces" upon your data what is likely an untenable assumption.
With this in mind, if your estimates differ by some amount, this is because there IS between-study variability.
In regards to another answer posted here, I do not see a FE model as a sensitivity analysis. If anything, you will be more likely to reach significance (narrower interval due to possibly underestimating tau). The RE could be considered a sensitivity analysis, but should really just be the default for the above stated reasons.
Comment: I'm not sure I agree that RE can always be assumed. If FE models are indeed less affected by the biases of small studies, then in this instance it's conceivable that, while both RE and FE are inaccurate, FE may be less inaccurate (although CIs will probably be too narrow). I imagine there is a simulation study which addresses this, but I haven't been able to find one.
Comment: I'd be interested to see a paper on this topic investigating your notion. It would not be too difficult to simulate yourself. Simply generate some biased effects selected for significance, then answer your question comparing the performance of RE or FE models over the long run. Also, one could take the position they are will to sacrifice some accuracy of the point estimate to ensure they don't erroneously reject the null. I'd be more worried about the ratio of estimate to standard error. Furthermore, if the interval is to narrower, this can increase type one error rate.
Answer: The distinction here has been ably set out by @abousetta but it is perhaps wrth stressing that neither approach can be regarded as completely satisfactory. The RE estimate is very affected by the smaller studies which are often considered less reliable whereas the FE estimate of the confidence interval is too narrow. The proble has been addressed by Henmi and Copas in an article here entitled "Confidence intervals for random effects meta--analysis and robustness to publication bias". They use the central estimate from the FE model but with a confidence interval which accounts for $\tau^2>0$. The method is available in the metafor package in R. Disclaimer 1: I corrected a few typos in the code and made it available for the package author. Disclaimer 2: I am not claiming that this method is going to solve all the problems of meta-analysis but it is an intriguing option.


Greens function of the equation $(\alpha^2 \Delta^2 - \Delta + \beta^2)u = 0$

Question: Consider the equation
$(\alpha^2 \Delta^2 - \Delta + \beta^2)u = 0$,
where $\Delta = \partial/\partial x^2 + \partial/\partial ^2$ and $u(x,y) \in \mathbb{R}^2$. Is anyone aware of the greens function of the above equation? For the case $\alpha =0$, above equation reduces to the Helmholtz equation with $\frac{1}{2 \pi} K_0(\beta r)$ being the Greens function ($r = \sqrt{x^2 + y^2}$ and $K_0$ is the modified Bessel function of the second kind). But I am interested in the case $\alpha \neq 0$. Can some one help in calculating the Greens function of the equation?
Comment: Do you maybe know the Greens function of $\Delta^2$? Usually you can construct a full Greens function if you know the Greens function of the summands.
Comment: The Greens function of $\Delta^2 u = 0$ is $\frac{1}{8 \pi} r^2 \ln r$. However, is it true that : "Usually you can construct a full Greens function if you know the Greens function of the summands". Could you point me to some specific references?  Thanks.
Answer: You can write your equation for $\alpha \neq 0$ as
\begin{equation*}
Lu=\{(\Delta -\frac{1}{2\alpha ^{2}})^{2}+\beta ^{2}-\frac{1}{4\alpha ^{4}}%
\}u=0
\end{equation*}
and your Green's function is proportional to the imaginary part of
\begin{equation*}
<\mathbf{x}|\frac{1}{-i\varepsilon -\beta ^{2}+\frac{1}{4\alpha ^{2}}-(k^{2}+%
\frac{1}{2\alpha ^{2}})^{2}}|\mathbf{y}>\\=\frac{1}{(2\pi )^{2}}\int_{\mathbb{R%
}^{2}}d\mathbf{k}\exp [i\mathbf{k\cdot }(\mathbf{x-y)}]\frac{1}{%
-i\varepsilon -\beta ^{2}+\frac{1}{4\alpha ^{2}}-(k^{2}+\frac{1}{2\alpha ^{2}
})^{2}}
\end{equation*}
The integral seems to be doable since there are only pole contributions.


How to extend link field type in D8?

Question: It's good to see the Link field type in D8. It takes a URL and (optionally) link text.
I'm adding a multiple links field to a content type and would like users to be able to provide some styling clues as well: e.g. this link is the primary one, this one needs a download icon. Basically let the user add CSS classes to each of the links in the same way they can add urls, text to each link they enter.
Is there a way to adding a new part to the field type?
(EDIT: I've put the answer into a custom module)
Comment: Just create new field formatter plugin and extend the \Drupal\link\Plugin\Field\FieldFormatter\LinkFormatter
Comment: Thanks for the hint. The field formatter seems the third thing I'd need to create. First I need somewhere to store the classes data, then I need a widget enabling user to specify classes, then I need a formatter to apply them to the HTML.
Comment: I think the formatter is a good idea, but it probably doesn't fit @artfulrobot's use case of having users save arbitrary styling clues for link data. You can extend the link class and give it a different annotation and change the schema method (similar to Drupal 7). This creates a new field type plugin. File and Image field type plugins work similarly. This won't do anything about your current data though and you'll need to migrate.
Comment: So there's not a sort of "alter" option where I can alter an existing field (link) to add the extra part?
Comment: No, there is no field schema alter hook in either Drupal 7 or Drupal 8.  Edit: Actually, I guess you could alter the plugin definition, provided your own class, implement schema method, and then all link fields will have that schema from then on. This seems like a lot of behavior to change for something like a custom menu system.
Comment: OK, thanks for clarifying. So I need to make a new field type, or use [field_group](https://www.drupal.org/project/field_group) to group a link and a text/select field for the classes.
Comment: I meant [field_collection](https://www.drupal.org/project/field_collection)
Comment: Yeah sorry, I mean field widget in my first comment :D
Answer: If you check \Drupal\link\Plugin\Field\FieldType\LinkItem, you see that it supports an array of options.
LinkFormatter then passes those to the URL.
So the only thing that you need is a custom widget that allows you to select/configure classes within the options somehow.
Comment: I'm not sure if this answers the use case of users saving arbitrary class/style data with the link content when it's created. This would be for a site builder to configure all link field content for a specific link field to have that style/class data.
Comment: Not sure I understand your point. the link field can store any classes. It's just a question of how you expose it in the UI, you could make a textfield so anything is allowed or you could make a select/checkboxes to only allow specific classes. It was explicitly decided to offer the storage but not provide any advanced widgets and leave that to contrib/custom modules.
Comment: Check out my [Segue - classy links module](https://www.drupal.org/sandbox/artfulrobot/2687501) (sandbox) that does as you suggest :-)

How to extend link field type in D8?


Building rails Form and Form_Fields on the fly

Question: On a Rails3 project , I have a requirement where i have to build the form based on the fields & labels that are already saved in the database and i want to save the values  in to other tables with other associated records with FORM_FIELD id.
I have a table FORM_FIELDS( name , label  ,field_type ) with name of the field , label and its type like text_area ,text_field , integer etc.
I want to build the FORM with fields that will have name , label and type based on the records i choose from the FORM_FIELDS table.
How do i build this form Syntactically correct? ,  Can anyone please help me out with this design?
Answer: Use formtastic gem for doing this on the fly.
Comment: but fortastic works only with For_for and not form_tag . Or is it not the case?? thats the reason i didnt research further on it!
and the form data collected from this form will be saved over two tables.


two text coming on same label in UITableViewCell

Question: What I am trying to do is taking the static data and show the data in UITableView. Below is what I have.
Note: : I am adding label and imageView in cell programatically as I have english and arabic version app.
//
//  ListViewController.m
//  Demo
//
//  Created by  on 1/20/13.
//  Copyright (c) 2013 . All rights reserved.
//

#import "ListViewController.h"
#import "ListOfProperty.h"
#import "Localization.h"
#import <QuartzCore/QuartzCore.h>

@interface ListViewController ()

@end

@implementation ListViewController {
    NSMutableArray *propListFinal;
}

@synthesize headerLabel, secondImage, myTableView;

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

-(void) viewWillAppear:(BOOL)animated {

    NSLog(@"in viewWillAppear");

    secondImage.alpha = 0.4f;

    propListFinal = [[NSMutableArray alloc] initWithCapacity:2];

    ListOfProperty *listOfProperty;

    listOfProperty = [[ListOfProperty alloc] init];
    listOfProperty.refIDOfFlat = @"8756342";
    listOfProperty.addressOfFlat = @"Al Salam, Hawalli, Kuwait";
    listOfProperty.amountOfFlat = @"2500";
    listOfProperty.typeOfFlat = @"Villa";
    listOfProperty.areaOfFlat = @"300";
    listOfProperty.imageName = @"home0.jpg";
    [propListFinal addObject:listOfProperty];

    listOfProperty = [[ListOfProperty alloc] init];
    listOfProperty.refIDOfFlat = @"6342875";
    listOfProperty.addressOfFlat = @"Al Salam, Khaitan, Kuwait";
    listOfProperty.amountOfFlat = @"2300";
    listOfProperty.typeOfFlat = @"Villa";
    listOfProperty.areaOfFlat = @"400";
    listOfProperty.imageName = @"home1.jpg";
    [propListFinal addObject:listOfProperty];

    listOfProperty = [[ListOfProperty alloc] init];
    listOfProperty.refIDOfFlat = @"8573624";
    listOfProperty.addressOfFlat = @"Hateen, Hawalli, Kuwait";
    listOfProperty.amountOfFlat = @"1500";
    listOfProperty.typeOfFlat = @"House";
    listOfProperty.areaOfFlat = @"415";
    listOfProperty.imageName = @"home2.jpg";
    [propListFinal addObject:listOfProperty];

    listOfProperty = [[ListOfProperty alloc] init];
    listOfProperty.refIDOfFlat = @"8634752";
    listOfProperty.addressOfFlat = @"Hateen, Salmiya, Kuwait";
    listOfProperty.amountOfFlat = @"1300";
    listOfProperty.typeOfFlat = @"Flat";
    listOfProperty.areaOfFlat = @"325";
    listOfProperty.imageName = @"home3.jpg";
    [propListFinal addObject:listOfProperty];

    listOfProperty = [[ListOfProperty alloc] init];
    listOfProperty.refIDOfFlat = @"8427563";
    listOfProperty.addressOfFlat = @"Al Salam, Jaleeb, Kuwait";
    listOfProperty.amountOfFlat = @"2500";
    listOfProperty.typeOfFlat = @"Small Flat";
    listOfProperty.areaOfFlat = @"100";
    listOfProperty.imageName = @"home4.jpg";
    [propListFinal addObject:listOfProperty];

    listOfProperty = [[ListOfProperty alloc] init];
    listOfProperty.refIDOfFlat = @"8427561";
    listOfProperty.addressOfFlat = @"Al Salam, Mallya, Kuwait";
    listOfProperty.amountOfFlat = @"2500";
    listOfProperty.typeOfFlat = @"Small Flat";
    listOfProperty.areaOfFlat = @"100";
    listOfProperty.imageName = @"home5.jpg";
    [propListFinal addObject:listOfProperty];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (int)numberOfSectionsInTableView:(UITableView *) tableView {
    return 1;
}

- (int) tableView:(UITableView *) tableView numberOfRowsInSection:(NSInteger)section {
    return [propListFinal count];
}

-(UITableViewCell *) tableView:(UITableView *) tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MainCell"];
    if (cell==nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"MainCell"];
    }

    NSString *commString;

    NSString *myLanguage = localize(@"myLanguage");

    ListOfProperty *propList = [propListFinal objectAtIndex:indexPath.row];

    UIImageView *myImageview;
    UILabel *addressLabel;
    UILabel *typeLabel;
    UILabel *areaLabel;
    UILabel *priceLabel;

    if ([myLanguage isEqualToString:@"en"]) {
        myImageview = [[UIImageView alloc] initWithFrame:CGRectMake(4, 4, 75, 65)];
        addressLabel = [[UILabel alloc] initWithFrame:CGRectMake(87, 9, 223, 21)];
        typeLabel = [[UILabel alloc] initWithFrame:CGRectMake(87, 32, 223, 21)];
        areaLabel = [[UILabel alloc] initWithFrame:CGRectMake(87, 55, 223, 21)];
        priceLabel = [[UILabel alloc] initWithFrame:CGRectMake(4, 74, 110, 21)];
    } else {
        myImageview = [[UIImageView alloc] initWithFrame:CGRectMake(240, 004, 75, 65)];
        addressLabel = [[UILabel alloc] initWithFrame:CGRectMake(11, 9, 223, 21)];
        typeLabel = [[UILabel alloc] initWithFrame:CGRectMake(11, 32, 223, 21)];
        areaLabel = [[UILabel alloc] initWithFrame:CGRectMake(11, 55, 223, 21)];
        priceLabel = [[UILabel alloc] initWithFrame:CGRectMake(200, 74, 110, 21)];
        addressLabel.textAlignment = NSTextAlignmentRight;
        typeLabel.textAlignment = NSTextAlignmentRight;
        areaLabel.textAlignment = NSTextAlignmentRight;
        priceLabel.textAlignment = NSTextAlignmentRight;
    }

    [addressLabel setFont:[UIFont fontWithName:localize(@"myFont") size: 13.0]];
    [typeLabel setFont:[UIFont fontWithName:localize(@"myFont") size: 13.0]];
    [areaLabel setFont:[UIFont fontWithName:localize(@"myFont") size: 13.0]];
    [priceLabel setFont:[UIFont fontWithName:localize(@"myFont") size: 15.0]];
    [priceLabel setFont:[UIFont boldSystemFontOfSize:15.0]];

    addressLabel.backgroundColor = [UIColor clearColor];
    typeLabel.backgroundColor = [UIColor clearColor];
    areaLabel.backgroundColor = [UIColor clearColor];
    priceLabel.backgroundColor = [UIColor clearColor];

    addressLabel.textColor = [UIColor colorWithRed:(246/255.0) green:(230/255.0) blue:(74/255.0) alpha:1.0f];
    typeLabel.textColor = [UIColor colorWithRed:(246/255.0) green:(230/255.0) blue:(74/255.0) alpha:1.0f];
    areaLabel.textColor = [UIColor colorWithRed:(246/255.0) green:(230/255.0) blue:(74/255.0) alpha:1.0f];
    priceLabel.textColor = [UIColor colorWithRed:(26/255.0) green:(169/255.0) blue:(213/255.0) alpha:1.0f];

    commString = [NSString stringWithFormat:@"Ref. ID : %@", propList.refIDOfFlat];
    addressLabel.text = propList.addressOfFlat;
    NSLog(@"data is %@", propList.addressOfFlat);
    typeLabel.text = propList.typeOfFlat;
    commString = [NSString stringWithFormat:@"%@ Sq. Meter.", propList.areaOfFlat];
    areaLabel.text = commString;
    commString = [NSString stringWithFormat:@"%@ KWD", propList.amountOfFlat];
    priceLabel.text = commString;

    myImageview.image = [UIImage imageNamed:propList.imageName];

    [cell.contentView  addSubview:myImageview];
    [myImageview release];

    [cell.contentView  addSubview:addressLabel];
    [addressLabel release];

    [cell.contentView  addSubview:typeLabel];
    [typeLabel release];

    [cell.contentView  addSubview:areaLabel];
    [areaLabel release];

    [cell.contentView  addSubview:priceLabel];
    [priceLabel release];

    return cell;
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return NO;
}

- (void)dealloc {
    [headerLabel release];
    [secondImage release];
    [myTableView release];
    [super dealloc];
}
@end

Now when I run the app, I have below screen which is fine.
as I don't have right to upload image, I am providing link
Image 1
Now when I scroll down, I have this screen.
Image 2
When you look at last row, the text are mixed. :( I don't get why this is happening?
Now when I scroll up, again the text is mixed as shown in below image.
Image 3
i.e. on one label I see two text
Now I added one more entry of building and below is what I get after scrolling the tableView up and down.
Image 4
i.e. on one label I see two text
My question would be, why this is happening in this case?
Comment: another images are [Image 3](http://i47.tinypic.com/esnn7b.png), [Image 4](http://i47.tinypic.com/wmbb5x.png)
Answer: just comment as follows in your code:
//if (cell==nil) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"MainCell"];
//}

Check whether problem is resolved.
Comment: this way its working... but all background images are gone now.. is that means I have to add background images programatically?
Comment: I tried adding `cell.backgroundColor = [UIColor redColor];` just before `return cell`, but still I see white background
Comment: @user1996238 this is not the best approach, please see my answer for further details.
Comment: Commenting //if (cell==nil) or // [tableView dequeueReusableCellWithIdentifier:nil] is not good approach . You should make custom cell. See my answer below
Answer: From what i see from your code, you are reusing the previous cell but alloc/initing all labels and image views every time, which is not a good approach and causing all this problem.
You shouldn't create these subviews every time just create two cells with different identifiers and later just assign them updated values like this:
-(UITableViewCell *) tableView:(UITableView *) tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

NSString *commString;

NSString *myLanguage = localize(@"myLanguage");

UIImageView *myImageview;
UILabel *addressLabel;
UILabel *typeLabel;
UILabel *areaLabel;
UILabel *priceLabel;

NSString *cellIdentifier = [myLanguage isEqualToString:@"en"]?@"EngCell":@"ARCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell==nil) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];

    if ([myLanguage isEqualToString:@"en"]) {
        myImageview = [[UIImageView alloc] initWithFrame:CGRectMake(4, 4, 75, 65)];
        addressLabel = [[UILabel alloc] initWithFrame:CGRectMake(87, 9, 223, 21)];
        typeLabel = [[UILabel alloc] initWithFrame:CGRectMake(87, 32, 223, 21)];
        areaLabel = [[UILabel alloc] initWithFrame:CGRectMake(87, 55, 223, 21)];
        priceLabel = [[UILabel alloc] initWithFrame:CGRectMake(4, 74, 110, 21)];
    } else {
        myImageview = [[UIImageView alloc] initWithFrame:CGRectMake(240, 004, 75, 65)];
        addressLabel = [[UILabel alloc] initWithFrame:CGRectMake(11, 9, 223, 21)];
        typeLabel = [[UILabel alloc] initWithFrame:CGRectMake(11, 32, 223, 21)];
        areaLabel = [[UILabel alloc] initWithFrame:CGRectMake(11, 55, 223, 21)];
        priceLabel = [[UILabel alloc] initWithFrame:CGRectMake(200, 74, 110, 21)];
        addressLabel.textAlignment = NSTextAlignmentRight;
        typeLabel.textAlignment = NSTextAlignmentRight;
        areaLabel.textAlignment = NSTextAlignmentRight;
        priceLabel.textAlignment = NSTextAlignmentRight;
    }

    [addressLabel setFont:[UIFont fontWithName:localize(@"myFont") size: 13.0]];
    [typeLabel setFont:[UIFont fontWithName:localize(@"myFont") size: 13.0]];
    [areaLabel setFont:[UIFont fontWithName:localize(@"myFont") size: 13.0]];
    [priceLabel setFont:[UIFont fontWithName:localize(@"myFont") size: 15.0]];
    [priceLabel setFont:[UIFont boldSystemFontOfSize:15.0]];

    addressLabel.backgroundColor = [UIColor clearColor];
    typeLabel.backgroundColor = [UIColor clearColor];
    areaLabel.backgroundColor = [UIColor clearColor];
    priceLabel.backgroundColor = [UIColor clearColor];

    myImageview.tag = 10;
    addressLabel.tag = 11;
    typeLabel.tag = 12;
    areaLabel.tag = 13;
    priceLabel.tag = 14;

    addressLabel.textColor = [UIColor colorWithRed:(246/255.0) green:(230/255.0) blue:(74/255.0) alpha:1.0f];
    typeLabel.textColor = [UIColor colorWithRed:(246/255.0) green:(230/255.0) blue:(74/255.0) alpha:1.0f];
    areaLabel.textColor = [UIColor colorWithRed:(246/255.0) green:(230/255.0) blue:(74/255.0) alpha:1.0f];
    priceLabel.textColor = [UIColor colorWithRed:(26/255.0) green:(169/255.0) blue:(213/255.0) alpha:1.0f];

    [cell.contentView  addSubview:myImageview];
    [myImageview release];

    [cell.contentView  addSubview:addressLabel];
    [addressLabel release];

    [cell.contentView  addSubview:typeLabel];
    [typeLabel release];

    [cell.contentView  addSubview:areaLabel];
    [areaLabel release];

    [cell.contentView  addSubview:priceLabel];
    [priceLabel release];
}

myImageview = [cell viewWithTag:10];
addressLabel = [cell viewWithTag:11];
typeLabel = [cell viewWithTag:12];
areaLabel = [cell viewWithTag:13];
priceLabel = [cell viewWithTag:14];

ListOfProperty *propList = [propListFinal objectAtIndex:indexPath.row];

commString = [NSString stringWithFormat:@"Ref. ID : %@", propList.refIDOfFlat];
addressLabel.text = propList.addressOfFlat;
NSLog(@"data is %@", propList.addressOfFlat);
typeLabel.text = propList.typeOfFlat;
commString = [NSString stringWithFormat:@"%@ Sq. Meter.", propList.areaOfFlat];
areaLabel.text = commString;
commString = [NSString stringWithFormat:@"%@ KWD", propList.amountOfFlat];
priceLabel.text = commString;

myImageview.image = [UIImage imageNamed:propList.imageName];

return cell;

}
Regards,
Comment: @user1996238 please see my updated answer to see the changes!
Comment: thanks for the detailed answer. I shall check and get back to you incase of any queries.
Comment: @user1996238 sure, and please don't forget to mark this one as the right answer, in case it helps You :)
Answer: Use following code.
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:nil];
    if (cell==nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:nil];
    }

Answer: Its reusability problem.I faced many  times in my code also.So i prefer Custom cells.It always resolve reusability problem. So try with making custom tableview Cell.And then modify Layout subviews.
Comment: I meant in Style, I have choosed Custom.
Comment: No , i meant for  Custom Cell (whole tableViewCell) read this article for customizing cell. http://www.appcoda.com/customize-table-view-cells-for-uitableview/
Comment: Yes, It will, in my case it does all time. Its good Practice also. Just learn and try.
Comment: can you take a look at my question http://stackoverflow.com/questions/14435261/uilabel-text-not-changing-however-xx-title-is-working
Comment: Hey i have answered there, check it


Step function is integrable

Question:
Show that step function is integrable

I think my logic is correct but wanted to check if I'm missing anything as the logic is too simple..
Step function is piecewise continuous as constant is continuous. If $f$ is piecewise continuous then $f$ is integrable.
I used theorems I studied recently and came up with that. Is there any logical issue?
*I assume that $f:[a,b] \to \mathbb{R}$ and $f$ is bounded
Thanks!
Comment: How do you define "piecewise continuous"?
Comment: This is not true, the constant function $f(x)=1$ is a step function which is not integrable on $\mathbb{R}$.
Comment: @JoséCarlosSantos I used the definition: If $f$ is uniformly continuous on $(t_{k-1}, t_k)$ for all $k$, then we say that $f$ is piecewise continuous.
Comment: @TheSilverDoe Then.. step function is not piecewise continuous? Is this the part where my logic breaks?
Comment: It helps to know the precise statement and the context of your question. If you're working in a context where the integral is built up through step functions, the worst logical issue you could be having by using general statements on the integrability of continous functions is circularity!
Comment: @befunctored Thanks for pointing that out. I added some context. Thanks!
Comment: @TheSilverDoe  Oh. if $f:[a,b] \to \mathbb{R}$, then $f$ is integrable on $\mathbb{R}$, right? I added some conditions. Sorry!
Comment: In fact, every non-negative measurable function is the limit of a sequence of  [simple functions](https://en.wikipedia.org/wiki/Simple_function), for which the step functions are building blocks.
Answer: Yes, the step function is integrable, but specifically on any interval $[a,b]$ where $a<b,a,b \in \mathbb{R}$, not on the entire real line. For example in $[-n,n]$ we have
$$\int_{-n}^n\mathbb{I}_{[0,\infty)}(x)dx=\int_{0}^ndx=n$$
and clearly as we extend $n \to \infty$ we get that
$$\lim_{n\to \infty}\int_{-n}^n\mathbb{I}_{[0,\infty)}(x)dx=\infty$$
If you are using $[a,b]$, we know that bounded functions (the step is non-negative and bounded by $1$) are integrable if and only if the set of points of discontinuity has measure zero, which is the case here because we have one point of discontinuity.

Step function is integrable


Why does a rotation transformation have 3 degrees of freedom?

Question: I'm learning about computer vision and came across this point that my instructor made in the material regarding image transformations.
He claimed that rotation has 3 degrees of freedom, but I'm having trouble wrapping my head around how that is. As far as I know, the rotation matrix is:
$$\mathbf{R} = \begin{bmatrix}\cos{(\theta)} & -\sin{(\theta)} \\ \sin{(\theta)} & \phantom{-}\cos{(\theta)}\end{bmatrix}$$
Doesn't this mean that we only have 1 degree of freedom, namely $\theta$?
I understand that a rigid (Euclidean) transformation (which is basically rotation + translation) has 3 degrees of freedom, but how does rotation have that?
I've also checked the Wikipedia page for rotation but it seems that rotation has 3 degrees of freedom when in $\mathbb{R}^3$. I also checked the Wikipedia page for the rotation matrix but it doesn't mention anything about degrees of freedom.
Comment: You can also pick the origin about which to rotate (should be 2 coordinates)
Comment: Wouldn't that also be a $\mathbb{R}^3$ case though?
Answer: Rotation in 2d about a fixed point has only 1 degree of freedom, while in 3d has 3 degrees of freedom. In general, in n dimensions you have $\frac{1}{2}n(n−1)$ degrees of freedom. I think the important point here is that when usually talking, we assume the origin point is fixed. You should clear this up with your instructor.


Como mapear uma imagem usando Areas e Coordenadas do Google.Cloud.Vision.Api

Question: Ola, amigos!
Estou tentando mapear uma imagem, usando a tag do html5 "Area" que trabalha com poligonos, eu quero mapear um retangulo ou varios retangulos em cima de uma imagem "img".
Minha duvida é, eu tenho um Mapeamento que rebecebo ou tabem coordenadas desta forma:
[X:166 - Y:64] [X:245 - Y:64] [X:245 - Y:81] [X:166 - Y:81]

São coordenadas de uma área de uma imagem. o que quero e pegar essas coordenadas e mapeá-las usando a tag Area do HTML5 mas essa tag so aceita 4 tipos de coordenadas, como proceder ?

<map name = "shape"> <area shape = "rect" alt="parte 1" coords = "0, 0, 100, 100" href="parte1.html"/> <area shape = "circle" alt="parte 2" coords = "100, 100, 25" href="parte2.html"/> <area shape = "poly" alt="parte 3" coords = "116, 207, 186, 299, 49, 296" href="parte3.html"/></map>

Pelo que vi "Area" só aceita 4 coordenadas e agora.
Comment: Tem como vc explicar melhor qual tipo de forma q essas coordenadas precisam criar?? Pq a ordem delas está um pouco confuso para mim, já que todos os pontos se repetem duas vezes cada em ordem diferente.
Comment: Entao, a API da Google.Cloud.Vision me retorna essa informacao
[X:166 - Y:64] [X:245 - Y:64] [X:245 - Y:81] [X:166 - Y:81] ou seja essa informacao e a Horizontal de Vertical de cada Coordenada perceba que sao 4 coordenadas cada um com horizontal e vertial formando um retangulo ou quadrado (poligono). ok.

Minha duvida e como eu uso a tag Area do HTML5 sendo esta para atributo Shape dela aceita domente 4 coordenadas eu nao entendi direito a essa parte demarcacao que a tag Area usa entende!?
Answer: Tem q ver se essas coordenadas são para duas áreas do tipo rect para formar dois quadrados, ou se são para uma unica área num polígono.
Pq se for um polígono pelas coordenadas que está ai, não vai aparecer dois quadrados, vai aparecer outro shape com pontos misturados.
Numa área estilo rect vc pode por somente 4 coordenadas, sendo x1, y1 que é o ponto de partida e x2, y2 que é o ponto final.
Se for nesse esquema suas coordenadas deveria ter duas áreas rect mais ou menos assim?
<area shape = "rect" alt="parte 1" coords = "x1, y1, x2, y2" href="parte1.html"/>
<area shape = "rect" alt="parte 1" coords = "x3, y3, x4, y4" href="parte1.html"/>

Num polígono vc pode por quantas coordenadas em pares desejar, e cada uma será equivalente a um ponto no estilo x1, y1, x2, y2, x3, y3, x4, y4 e etc....
E então seguindo o seu código seria algo assim:
<area shape = "poly" alt="parte 3" coords = "x1, y1, x2, y2, x3, y3, x4, y4" href="parte3.html"/>

E dessa forma vc poderia colocar todas suas 4 coordenadas numa mesma área.
Agora só fique atento pela ordem, pq a imagem vem primeiro e o mapa depois.
No seu código vc está colocando a tag da imagem depois da tag do mapa, e é o contrário.
Qualquer coisa nesse link vc pode encontrar mais informações:
https://www.html-5-tutorial.com/map-and-area-elements.htm


When in Adaptive LASSO process does it make sense to constrain control variable lambdas to 0?

Question: Lets take this example for how to conduct an adaptive LASSO. Essentially an initial model is fit using ridge regression. Then, a LASSO is fit, in which the value of lambda is tuned individually for each predictor based on its coefficient in the ridge regression.
Suppose I would like to include a control variable.
I know I can alter the model such that lambda doesn't get applied to a certain variable by setting the penalty factor to be 0 for those variables (i.e., the candidate control variables).
My question is: Does it make more sense to do this in both the initial ridge model and the rescale model (i.e., ride1_cv and alasso1_cv in the example). Or just in the rescale model?

Code for setting lambdas to 0:
For example, in ridge1_cv I would:
#create a vector of 0 for my control variable and 1s everywhere else, and add a penalty factor term to the model:

penf <- c(0, rep(1, times = (ncol(d)-1))

ridge1_cv <- cv.glmnet(x = x_cont, y = y_cont,
                       type.measure = "mse",
                       nfold = 10,
                       alpha = 0,
                       penalty.facotr = penf
)

In alasso1_cv I would do something similar, but just replace 1s with the calculated lambda:
penf <- 1 / abs(best_ridge_coef)
penf[1] <- 0

alasso1_cv <- glmnet(x = x_cont, y = y_cont,
              alpha = 1,
              penalty.factor = penf)

Comment: Is your goal to build a predictive model, or to understand the relationship between your predictors and the outcome? If you're interested in prediction, could you please explain the distinction between "control" and "non-control" variables - isn't everything just a predictor? If you're interested in understanding, why use lasso?
Comment: To understand the relationship. Using lasso because it is conservative and is happy to deal with correlated predictors. I'm also using adaptive lasso which I understand to be better for understanding.
Comment: I think it's fair to say that this is an extremely convoluted way of trying to understand a linear relationship. There are sensible Bayesian interpretations of both ridge regression (a Gaussian prior) and lasso (MAP with Laplace prior). Adaptive lasso is useful, particularly for data-mining, but I have no idea how you could interpret its estimates scientifically, let alone publish them.
Basically, my advice is to forget about adaptive lasso, and just use Bayesian linear regression if you want conservative parameter estimates.
Comment: @Dave, LASSO is not happy to deal with correlated predictors; it is the opposite. Ridge is better suited for dealing with correlated predictors.
Comment: @Eoin Thanks, I appreciate the advice! Could you give me a bit more detail on the methods you would suggest using instead?
Comment: @RichardHardy What about an Adaptive LASSO based on the output of Ridge Regression?
Comment: Just a side note: controlling ``penalty.factor`` in ``glmnet`` is **not** Adaptive LASSO. It can be seen from the fact that penalty factor weights are internally normalized. Whereas the goal of Adaptive LASSO is to give _diverging_ weights for insignificant variables. See, e.g., [this](https://www.r-bloggers.com/a-deep-dive-into-glmnet-penalty-factor/).
Comment: (cont.) [this would be a proper example of](https://stats.stackexchange.com/a/389137/87362) Adaptive LASSO, just switch initial estimates to ridge estimates to be used as weights.
Comment: @Nutle I followed this code: https://rpubs.com/kaz_yos/alasso Is it incorrect?
Comment: (cont.2) alternatively, you could try reusing [this snippet](https://pastebin.com/Di3WFXDB), here we additionally cross-validate different powers $\gamma$ for the weights $w_j$, as per [the original article](http://users.stat.umn.edu/~zouxx019/Papers/adalasso.pdf), though it's not bad to just fix to some power like $\gamma=1$.  With power $\gamma$ closer to $0$, the solution is in essence the classic LASSO.
Comment: @Dave in my experience, normalizing through penalty.factor alone is much less strict than using the weights straightforwardly as in the original article. Depending on the final goal and the results, your method may actually be better suited for your problem. I would suggest testing both approaches, though.
Comment: @Nutle Thanks for the feedback! I wonder if you have any thoughts on this question: https://stats.stackexchange.com/questions/484982/if-there-are-40-candidate-predictors-and-i-want-to-know-which-ones-predict-the ?
Answer: Prediction versus Understanding
Broadly speaking, your goal when fitting a model is either to be able to make predictions, or to understand the relationships between your variables. All kinds of models can be used for both purposes, but some are better suited to prediction (but are hard to understand or interpret), while others are better for understanding (but may make inferior predictions).
Prediction
If your goal is prediction, the distinction between control and non-control variables doesn't make sense. All of your variables are potential predictors, and your goal is to make the best (for a given value of "best") predictions you can with them.
Including a penalty (ridge or lasso) on the terms in your model is usually a good idea because it reduces overfitting, improving your ability to make predictions.
That's why penalised regression is mostly used by people interested in prediction.
Does it make sense to include a penalty on some terms but not others? It might, based on the problem at hand, and any prior knowledge you might have. However, the only way to know is to test whether doing so improves the accuracy of your out-of-sample predictions. This is true of all regularisation methods, not just adaptive lasso.
Understanding
If your goal is understanding (as you've said), things are a little different.
First, since your goal is no longer to make predictions,
it's not clear what the advantage of using adaptive lasso is,
since it's a complex procedure, and not easy to interpret.
In fact, standard lasso and ridge regression are both  easier to interpret,
since they have straightforward Bayesian interpretations,
while adaptive lasso doesn't, to my knowledge.
Let's say you use the adaptive lasso, with or without setting some penalty terms to zero, and find that it uses one of your variables as a predictor. What can you conclude from this?
There are a few alternative approaches. The simplest is just to use linear regression, and see what predictors are statistically significant (note that correlated predictors pose a problem for all regression models, so that's a parallel issue). Since you're interested in being "conservative", you have a few options. You could use a stricter threshold for significance, for instance only concluding there is an effect if $p < .001$ (see Lakens et al, 2008).
Alternatively, you could fit a Bayesian regression model, setting conservative priors on the parameters for variables you believe should have small effects. In this case, it absolutely makes sense to set a uniform prior on some control variables (equivalent to setting the penalty to 0), but using a more conservative prior for other predictors. You get to use your own judgement for this!
On a practical level, you can use the brms package for R for this (this is a good tutorial on linear models in brms), standardise your predictors and your outcome variable to have a standard deviation of 1, and set, for instance, a $\text{Normal}(0, 1)$ prior (set_prior("normal(0, 1)", class = "b")) to indicate that you're 95% certain the standardised regression weights (change in standard deviations of the outcome per one standard deviation change of the predictor) should be between $-2$ and $+2$.
Obviously, there's a lot of details I'm skipping here. I would suggest Richard McElreath's excellent Statistical Rethinking book as a starting point.


addEventListener is not working in plnkr editor while executing script in external file

Question: Here is my first [link][1] where I have used script tag internally and addEventListener is working fine.
Here is my second [link][2] where I have used script externally and addEventListener is not working.
  [1]: https://plnkr.co/edit/f8vd7pGijNFxghz56Aze?p=preview
  [2]: https://plnkr.co/edit/i1pKKwdSC0O2o3FvhoD4?p=preview

Comment: You've misidentified the problem. As well as moving the source code from inside the script element to a URL with a `src` attribute … you **moved the entire script element** to a different part of the HTML.
Answer: Move your script to the end of body or add the listerners in window.onload handler.
https://plnkr.co/edit/KvKLCC2QOFdTTEHcmiCl?p=preview
https://plnkr.co/edit/6skW5rucm73my9pK6cGw?p=preview
Comment: What I have to do if I want to add it externally in js
Comment: Have you read the answer?


ansible task generating weird syntax for logrotate definition file

Question: I am using ansible logrotate definition for logrotate in ubuntu 14.04 which is having definition as below
<code>---

- name: dependencies
  apt: pkg={{item}} state=latest
  with_items:
    - unzip
    - jq

- name: check if already downloaded
  stat: path={{nomad_download_folder}}/{{nomad_archive}}
  register: nomad_archive_stat

- name: download
  get_url: >
    url={{nomad_download}}
    dest={{nomad_download_folder}}
    sha256sum={{nomad_checksum}}
  register: nomad_downloaded
  when: nomad_archive_stat.stat.exists == false

- name: group
  group: >
    name={{nomad_group}}
    state=present
  register: nomad_group_created

# On Nomad schedulers
- name: user
  user: >
    home={{nomad_home}}
    name={{nomad_user}}
    system=yes
    groups={{nomad_group}}
    append=yes
  when: (nomad_group_created | changed) and (nomad_is_server == true)

# On Nomad runners
- name: user
  user: >
    home={{nomad_home}}
    name={{nomad_user}}
    system=yes
    groups={{nomad_group}},docker
    append=yes
  when: (nomad_group_created | changed) and (nomad_is_server == false)

- name: directories
  file: >
    state=directory
    path={{item}}
    owner={{nomad_user}}
    group={{nomad_group}}
  with_items:
    - "{{nomad_home}}"
    - "{{nomad_home}}/bin"
    - "{{nomad_config_dir}}"

- name: check for log directory
  stat: path={{nomad_log_file | dirname}}
  register: nomad_log_directory_stat

- name: create log directory
  file: >
    state=directory
    path={{nomad_log_file | dirname}}
    owner={{nomad_user}}
    group={{nomad_group}}
  when: not nomad_log_directory_stat.stat.exists

- name: touch log file
  file: >
    state=touch
    path={{nomad_log_file}}
    owner={{nomad_user}}
    group={{nomad_group}}
  changed_when: false

- name: install
  unarchive: >
    src={{nomad_download_folder}}/{{nomad_archive}}
    dest={{nomad_home}}/bin
    copy=no
  when: nomad_downloaded | changed

- name: link executable in PATH
  file: >
    state=link
    src={{nomad_home}}/bin/nomad
    dest=/usr/local/bin/nomad

- name: set ownership
  file: >
    state=directory
    path={{nomad_home}}
    owner={{nomad_user}}
    group={{nomad_group}}
    recurse=yes
  when: nomad_downloaded | changed

- name: nomad config file
  template: >
    src=nomad.conf.j2
    dest={{nomad_config_file}}
    owner={{nomad_user}}
    group={{nomad_group}}
    mode=0755
  notify:
    - restart nomad

- name: copy nomad upstart script
  template: >
    src=nomad.upstart.conf.j2
    dest=/etc/init/nomad.conf
    owner={{nomad_user}}
    group={{nomad_group}}
    mode=0755
  notify:
    - restart nomad

- name: rotate log file
  logrotate: name=nomad path={{nomad_log_file}}
  args:
    options:
      - daily
      - missingok
      - rotate 3
      - compress
      - delaycompress
      - copytruncate
      - notifempty
</code>
Which causes to generate file with weird syntax which is below.
<code>sudo cat /etc/logrotate.d/nomad

# Generated by Ansible.
# Local modifications will be overwritten.

/var/log/nomad.log {
  [
  '
  d
  a
  i
  l
  y
  '
  ,

  '
  m
  i
  s
  s
  i
  n
  g
  o
  k
  '
  ,

  '
  r
  o
  t
  a
  t
  e

  3
  '
  ,

  '
  c
  o
  m
  p
  r
  e
  s
  s
  '
  ,

  '
  d
  e
  l
  a
  y
  c
  o
  m
  p
  r
  e
  s
  s
  '
  ,

  '
  c
  o
  p
  y
  t
  r
  u
  n
  c
  a
  t
  e
  '
  ,

  '
  n
  o
  t
  i
  f
  e
  m
  p
  t
  y
  '
  ]
}
</code>
Due to this syntax error I am getting so many emails every morning. Below are more details about server.
<code>$sudo ansible --version
ansible 126.96.36.199
  config file = /etc/ansible/ansible.cfg
  configured module search path = Default w/o overrides
$lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 14.04.4 LTS
Release:    14.04
Codename:   trusty
</code>
Comment: There is no `logrotate` module in core Ansible.  There are several available from third parties, and you haven't specified which one you are using.
Comment: I am using the one by john dewey https://github.com/retr0h/ansible-logrotate
Comment: @larsks could you please check above
Answer: If I clone that module from github and create a playbook like this:
<code>- hosts: localhost
  roles:
    - logrotate
  tasks:
    - logrotate: name=myapp path=/tmp/myapp.log
      args:
        options:
          - daily
          - rotate 8
          - postrotate
          - exec script
          - endscript
</code>
It runs just fine, and results in a logrotate configuration file that looks like:
<code># Generated by Ansible.
# Local modifications will be overwritten.
/tmp/myapp.log {
  daily
  rotate 8
  postrotate
  exec script
  endscript
}
</code>
If you're seeing different behavior using an identical playbook, would you update your question to indicate which version of ansible you're using (and on what platform you're running it)?
Incidentally, the syntax you're using is a little odd; you're mixing the legacy key=value syntax with the preferred YAML dictionary syntax.  It doesn't have an operational impact (the playbook works the same either way), but in general you would write it like this:
<code>- hosts: localhost
  roles:
    - logrotate
  tasks:
    - logrotate:
        name: myapp
        path: /tmp/myapp.log
        options:
          - daily
          - rotate 8
          - postrotate
          - exec script
          - endscript
</code>
Comment: @ShaileshSutar you will need to update your question with an example that  clearly reproduces the problem.  Trying to put that together may actually lead you to the source of your problem.
Comment: What is the `logrotate` role from your example? Why did you include it?
Comment: That is the logrotate role referenced by Shailesh Sutar in the question, and I included it because that's how you use a role. In this case, that ensures that logrotate is installed via the role's `tasks/main.yml` and also activates the roles `library` directory.
Comment: @larsks It works for me when I run ansible-playbook the way you did however It doesn't work for me in production where it is deployed.


How can I use aptitude to remove old versions of a package?

Question:
I want to remove the 0.9.8o versions. Does anyone know how without breaking and destroy it's dependents.
Answer: <code>Figure 2.9. Values of the "current state" flag

i   -    the package is installed and all its dependencies are satisfied.
p   -    the package and all its configuration files were removed, or the package was never installed.
</code>
For more information, check out the documentation relating to accessing package information in aptitude.
Basically, those old versions are just available options from your package database. They don't exist on your system, and possibly never were there.
Comment: Oh I see. I asked, because my `phpinfo` says I am using 0.9.8o, so I am quite dazzled on what's going on with my system
Comment: @Doug: The `openssl` package is not the package that PHP uses.  You probably are looking for `libssl0.9.8`, which you can't remove as long as something's linked to it, which PHP probably is.  Rebuild/upgrade PHP and it'll automatically link against -- and depend on -- the correct version of libssl.
Comment: I rebuilt PHP dozens of times today trying different options. Couldn't figure it out. Could you please give me a hand? (I also have libssl1.0.0 installed already)
Comment: @Doug That's way too much to go over in comments and a strong change from the current topic. You should open a new question asking that.
Answer: Aptitude will automatically remove old versions when you install a new version.  Dependencies are also automatically handled.
The screen shot you are showing indicates the versions you are asking about are fully removed, or have never been installed.  The versions show up on the list because they are available.  Likely the oldest version was likely included in the initial distribution.  The other two versions likely come from update and/or backports repositories.


Given $\left(x + \sqrt{1+y^2}\right)\left(y + \sqrt{1+x^2}\right) = 1$, prove $\left(x + \sqrt{1+x^2}\right)\left(y + \sqrt{1+y^2}\right) = 1$.

Question:
Let $x$ and $y$ be real numbers such that
  $$\left(x + \sqrt{1+y^2}\right)\left(y + \sqrt{1+x^2}\right) = 1$$
  Prove that
  $$\left(x + \sqrt{1+x^2}\right)\left(y + \sqrt{1+y^2}\right) = 1$$
Comment: Welcome to Math.SE! You'll find that the community tends to respond more favorably to questions that include some sense of what you know about a problem, and/or where you got stuck. Such information helps answerers target their responses to your skill level, without wasting anyone's time telling you things you already know. (Plus, it helps convince people that you aren't simply trying to get them to do your homework for you.)
Answer: Hint :
By the hypothesis of the problem, do some algebra and show that :
$$\left(x + \sqrt{1+y^2}\right)\left(y + \sqrt{1+x^2}\right) = 1 \Leftrightarrow \dots \Leftrightarrow y = -x$$
Now, substitute $y=-x$ on the expression $\left(x + \sqrt{1+x^2}\right)\left(y + \sqrt{1+y^2}\right)$ and see what happens.
Comment: How to prove $(x + \sqrt{1+x^2})(y + \sqrt{1+y^2}) = (x + \sqrt{1+y^2})(y + \sqrt{1+x^2})$?
Comment: @Success I updated my answer to a more straightforward one.
Answer: Write $x=\tan a$ and $y = \tan b$ for some (angles) $a,b$. They exsist since $\tan $ is surjective function. Pluging in starting equation we get:
$$ {\sin a+1\over \cos a}\cdot {\sin b+1\over \cos b}=1$$
and after rearranging we get $$\sin(a)+ \sin(b) = \cos (a+b) - \cos 0$$
which is equivalent to $$2\sin{a+b\over 2}\cos{a-b\over 2} = -2\sin {a+b\over 2}\sin{a+b\over 2}$$
Case 1. $\sin {a+b\over 2}=0$ then $a+b = 2\pi k$ so $$x=\tan a = \tan (2\pi k-b) = -\tan b = -y$$
Case 2. $\sin {a+b\over 2}\ne 0$, then $$\cos {a-b\over 2}+\sin{a+b\over 2}=0$$
Factorising this we get:
$$2\cos ({\pi\over 4}-{b\over 2})\cdot \cos({a\over 2}-{\pi\over 4})=0$$
Now we have to choises again.
1.st: $${\pi\over 4}-{b\over 2} = {\pi\over 2}+\pi k\implies b =-{\pi\over 2}+2\pi k $$
so $y$ does not exist.
2.nd case... we get $x$ does not exsist.
So $x=-y$ and thus second expresins is also $1$.
Comment: Actually, $\sqrt{1+\tan^2a}\neq\frac{1}{\cos{a}}.$
Comment: @MichaelRozenberg We can restrict $-\pi/2 < a < \pi/2$, so $x=\tan a$ is one-to-one
Comment: @Dylan Yes, of course!
Answer: We'll replace $y$ an $-y$.
Thus, the given it's $$\left(\sqrt{y^2+1}+x\right)\left(\sqrt{x^2+1}-y\right)=1$$ and we need to prove that:
$$\left(\sqrt{x^2+1}+x\right)\left(\sqrt{y^2+1}-y\right)=1.$$
Now, the condition gives
$$\left(\sqrt{y^2+1}+x\right)\left(\sqrt{x^2+1}-y\right)=\left(\sqrt{x^2+1}+x\right)\left(\sqrt{x^2+1}-x\right)$$ or
$$\left(\sqrt{y^2+1}+x\right)\left(\sqrt{x^2+1}-y\right)-\left(\sqrt{y^2+1}+x\right)\left(\sqrt{x^2+1}-x\right)+$$
$$+\left(\sqrt{y^2+1}+x\right)\left(\sqrt{x^2+1}-x\right)-\left(\sqrt{x^2+1}+x\right)\left(\sqrt{x^2+1}-x\right)=0.$$ or
$$(x-y)\left(\sqrt{y^2+1}+x\right)-\left(\sqrt{x^2+1}-x\right)\left(\sqrt{x^2+1}-\sqrt{y^2+1}\right)=0$$ or
$$(x-y)\left(\sqrt{y^2+1}+x-\frac{(x+y)\left(\sqrt{x^2+1}-x\right)}{\sqrt{x^2+1}+\sqrt{y^2+1}}\right)=0,$$ which gives $x=y$ because the second factor it's
$$\left(\sqrt{x^2+1}+x\right)\left(\sqrt{y^2+1}-y\right)+(x+y)^2+1>0.$$
Id est, $$\left(\sqrt{x^2+1}+x\right)\left(\sqrt{y^2+1}-y\right)=\left(\sqrt{x^2+1}+x\right)\left(\sqrt{x^2+1}-x\right)=1$$ and we are done!
Answer: Hint:
Like greedoid, WLOG let $x=\cot2A,y=\cot2B,0<2A,2B<\pi$ (Reference )
$$1=(x+\sqrt{1+x^2})(y+\sqrt{1+y^2})=\cot A\cot B$$
$\implies\tan A=\cot B$
$x=\cot2A=\dfrac{1-\tan^2A}{2\tan A}=\dfrac{1-\cot^2B}{2\cot B}=\cdots=-\cot2B=-y$


Como desativar o Pop-UP do Google Chrome para salvar senhas?

Question: Como seria um método para desativar o Pop-Up:

Deseja que o Google Chrome atualize sua senha para este site?

Fique a vontade para escolher a linguagem, mas a resposta com JavaScript será a resposta aceita.
Nota: AutoComplete='Off' indica ao navegador que não é necessário exibir opções com base em valores anteriores, então não é isso que desejo.
Comment: Relacionado em inglês: https://stackoverflow.com/questions/23177225/how-do-i-disable-the-save-password-bubble-in-chrome-using-javascript
Comment: @WallaceMaxters através do link consegui chegar a resposta! Vlw :)
Comment: já entendi. Deve ser porque você mesmo respondeu, porém a galera não sabe que o sistema do site incentiva isso :p
Comment: Quem negativou poderia explicar o porque? Assim eu poderia melhorar a pergunta.
Comment: Agora são dois negativos. Parece que tem uma galerinha que não gostou da pergunta, mas não pode explicar bem o que houve.
Comment: Parece que sim, vai entender =D;
Comment: Posso perguntar por quê você deseja fazer isso? Não consigo visualizar um ambiente em que a filosofia do navegador de armazenar senhas possa entrar em conflito com a aplicação.
Comment: @AndersonCarlosWoss pode sim. Estou criando criando um `Redefinir Senha` e sempre que o formulário é submetido o `Crome` está fazendo este tipo de pergunta.
Comment: @Marconi mas não é interessante que ele faça isso para não manter a senha antiga armazenada ao invés da nova?
Comment: @AndersonCarlosWoss no meu caso não, até porque este usuário que está no print não é o que estou alterando a senha.
Comment: @AndersonCarlosWoss isso gerou uma certa confusão no tester aqui, e ela achou melhor retirar.
Answer: Pelo comentário do @Wallace Maxters, descobri que em nenhum local diz exatamente como desativar este Pop-UP(por maneiras corretas), mas existem meios de burlar isto.
Porque isso acontece?
Sempre que um formulário com <input  type="password"> é enviado o Chrome irá fazer a pergunta do Pop-UP.
E qual a solução para isso?
Adicione 2 campos falsos ao lado do seu campo de senha.
<input type="password" class="stealthy" tabindex="-1">
<input type="password" " id="user_password" autocomplete="off">
<input type="password" class="stealthy" tabindex="-1">

E use o seguinte CSS
.stealthy {
  left: 0;
  margin: 0;
  max-height: 1px;
  max-width: 1px;
  opacity: 0;
  outline: none;
  overflow: hidden;
  pointer-events: none;
  position: absolute;
  top: 0;
  z-index: -1;
}

O motivo da classe CSS é torna os campos  invisíveis e desclassificados.
Comment: Essa resposta ainda não é definitiva. Os desenvolvedores dos principais [tomaram a decisão de forçar o armazenamento local de senhas](https://developer.mozilla.org/pt-BR/docs/Web/Security/Securing_your_site/Turning_off_form_autocompletion) e técnicas como essa irão eventualmente parar de funcionar em alguma atualização futura. A solução que você colocou aqui não é a primeira e nem será a última forma de se evitar que o Chrome salve senhas, é apenas a forma que funciona hoje.
Comment: Isso não faz com que os caracteres do campo fiquem visíveis?
Comment: @Renan editada, essa resposta resolveu o meu problema. Obrigado por mencionar aqui ;)
Answer: Não podemos desabilitar essa função diretamente via Javascript, pois isto é uma configuaração do próprio navegador.
Mas podemos utilizar um código para "burlar" isto ...
Você pode tentar copiar a senha para um campo 'hidden' e remover do input 'original', antes de enviar o 'submit';
Exemplo :
function executeAdjustment(){
    $("#vPassword").val($("#txtPassword").val());
    $(":password").remove();
    var myForm = document.getElementById("createServerForm");
    myForm.action = "executeCreditAdjustment.do";
    myForm.submit();
}

Ref. Stack


Existence of a linear form sending a non zero vector to non zero scalar.

Question: Let $E$ be a real $n-$dimensional space. Let $x$ be a non zero vector of $E$. I want to show that there exists a linear fomr $f:E\to \mathbb{R}$ such that $f(x)\not = 0$.
My try is to take a basis $(e_1,\cdots,e_n)$ of $E$. Then $x=a_1e_1+\cdots+a_ne_n$ for some scalars $a_1,\cdots,a_n$. Now since $x$ is not zero then there exists at least one of the $a_i$ that is not zero. I thought about $f(x)=a_1+\cdots + a_n$ but this can be zero.
Answer: Just take $f= x_i$, the linear map which maps every vector to its $i$th coordinate in that basis.
Comment: What? You chose $i$ so that the $i$th coordinate of $x$ in that basis was not zero...
Comment: Oh i see, how i missed that !! thank you very much..
Comment: you mean $f(x)=a_i$ ? this can be zero of course.
Comment: Choose $i$ such that $a_i\neq 0$, then take $f=x_i$, simple as that.


How to use reflection to get a constructor where you are passing in a super class as a paremeter

Question: Today while coding I began a deep dive into the world of reflection.  I have messed with it in small bits and pieces before but never to this extent and no matter where I look I can find no answer to my question and so here I am!  Currently what I am trying to do is use reflection with a class whose constructor requests a parameter but for ease of use I wish to use the super class of the parameter.
Here is the code causing problems with some explanations:
this.listener = (MyListener) listenerClass.getConstructor(MyAppState.class).newInstance(this);

The thing is that MyAppState is the class that all of my appstates extend from and each listener takes in its own specific AppState that extends MyAppState but has extra features different from each other.  What I need to know is what I can put in my .getConstructor() to specify that the class I am passing in is the super of the parameter it wants.
Here is a theoretical example of the code:
this.listener = (MyListener) listenerClass.getConstructor(Class extends MyAppState.class).newInstance(this);

So is this possible or should I just work with my code to have a second constructor that accepts the MyAppState class, or something else along those lines.
Also, sorry if this is off topic but to prevent problems in the future, I am being told this question is subjective.  Is there any way to word future questions to not be as subjective or is the method to figure out whether the question is subjective just a bit flawed?
[EDIT] As requested, a few more examples related to the question:
    public MyAppState(Node screen, Class listenerClass)
    {
        this.screen = screen;

        try
        {
            this.listener = (MyListener) listenerClass.getConstructor(MyAppState.class).newInstance(this);
        }
        catch (Exception e)
        {
            Logger.getLogger(MyAppState.class.getName()).log(Level.SEVERE, "The listener for the {0} appstate could not be created using reflection.", new Object[]{this.getClass().getName()});
            System.exit(-1);
        }
    }

Above is the full parent class's constructor, the said class extends one more class but it contains no constructor and so I am not sure if it is needed.  If it is please feel free to ask for it.
public class OptionsMenuState extends MyAppState
{
    public OptionsMenuState()
    {
        super(new Node("Options Screen"), OptionsMenuStateListener.class);
    }

That is one class and its constructor with pieces cut off to keep it short.
public class MainMenuState extends MyAppState
{
    public MainMenuState()
    {
        super(new Node("Start Screen"), MainMenuStateListener.class);
    }

Here is another class and its constructor.
[EDIT] As suggested, I created a program that roughly mimics what I am attempting to do.
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        //This is what I want to do but I don't know how to have java allow me to pass in Greeting.
        createObject(SimpleSentence.class);
        createObject(DifferentSentence.class);
    }

    public static void createObject(Class theClass)
    {
        theClass.getConstructor(Greeting.class).newInstance(new Hello());
    }

    class SimpleSentence
    {
        Hello firstWord;

        public SimpleSentence(Hello word)
        {
            firstWord = word;
        }
    }

    class DifferentSentence
    {
        Howdy firstWord;

        public DifferentSentence(Howdy word)
        {
            firstWord = word;
        }
    }

    class Greeting
    {

    }

    class Hello extends Greeting
    {

    }

    class Howdy extends Greeting
    {

    }
}

Comment: Please give an example of a constructor, of its parameter, and the inheritance hierarchy you are describing.
Comment: Just edited the question with the information about halfway down.
Comment: Your question is still unclear. Your question includes 5 types, without describing the type hierarchy. I'm sure you could demonstrate the problem with a short but complete program which would be significantly clearer.
Comment: And what is `listenerClass`? Is there an inheritance hierarchy with that type too?
Comment: Adding an example that is much simpler I hope and that poses a similar problem.  Sorry for the lack of constructors and body to the example but it is late by me but don't want to leave this question overnight if it is not complete but I also need to get some sleep.
Comment: I hope you see how your example will fail since you will invoke a constructor that expects a `Howdy` by providing a `Hello`.
Comment: I do see how my example will fail.  I can't really figure out a way to make the example work the way I wrote it and I think it will become complicated to rewrite it.  The real question is how to get the .getConstructor(Greeting.class) part to work as I would never even get to the problem of passing a Hello when it expects a Howdy as there is no constructor that has a Greeting parameter but only parameters that extend greeting.  I need some way, if it exists, to specify that I want a constructor that allows passing in of a parameter that extends Greeting.
Answer: Short answer is you can't. getConstructor(Class<?>...parametertypes) is very explicit because it needs to match exactly zero or one constructor only.
You will need to go through all the constructors to find one, that has a parameter that is assignable from MyAppState
e.g. outline:
    final Constructor<?>[] ctrs = listenerClass.getConstructors();
    for (Constructor<?> constructor : ctrs) {
        if (constructor.getParameterTypes()[0].isAssignableFrom(MyAppState.class)) {
            // use this one?
        }
    }

Comment: I think this may be the answer I need.  Thank you for understanding my seemingly complicated question.  As long as there is no easier way to do what I want I think you figured it out!
Comment: Just beware that you potentially may find many constructors that could match your criteria, so make sure your documentation is very specific in your requirements. Anything you can do to make it more explicit would be good (such as requiring a certain constructor annotation or something)


Extração de dados de um calendário com Python e Beautifulsoup (em Linux Ubuntu-like)

Question: Amigos,
Gostaria de pegar dados em um calendário:
http://www.purebhakti.com/component/panjika
O primeiro passo seria fazer o programa escolher a time zone ( -3:00 Buenos Aires) e clicar em Submit Time Zone.
Após clicar em Submit Time Zone, selecionar a cidade (Rio de Janeiro) e clicar em Get Calendar.
Só após essas etapas, terei acesso ao calendário efetivamente para pensar em extrair as informações.
Gostaria de, pegar o evento do dia:
Por exemplo, hoje é dia 22, então imprimiria:
22 Apr 2017  : Ekādaśī, K, 06:09, Śatabhiṣā
+ŚUDDHA EKĀDAŚĪ VRATA: FASTING FOR Varūthinī EKADASI
Pensei em utilizar o Python e beautifulsoap mas aceito sugestões.
Pergunta: Como fazer o programa chegar até o calendário (após fazer a seleção do time zone e cidade automaticamente)?
Não consegui sair de:
from bs4 import BeautifulSoup
import requests

url = 'http://www.purebhakti.com/component/panjika'
header = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) '
                        'AppleWebKit/537.36 (KHTML, like Gecko) '
                        'Chrome/51.0.2704.103 Safari/537.36'}

req = requests.get(url,headers= header)

html = req.text

soup = BeautifulSoup(html,'html.parser')

Comment: Tem algum código inicial ?
Comment: só este. tinha esquecido de postar
Comment: Já é um começo, se naum pode soar "faz para mim" saca ? Quia apouco aparece um manjador de phyton...
Comment: Desculpe, foi erro meu.
Comment: Não acho que seja complexo, mas eu realmente não sei! Obrigado pela contribuição!
Answer: Tenta isto:
import requests, time
from bs4 import BeautifulSoup as bs

url_post = 'http://www.purebhakti.com/component/panjika'
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)'}
payload = {'action': 2, 'timezone': 23, 'location': 'Rio de Janeiro, Brazil        043W15 22S54     -3.00'}

req = requests.post(url_post, headers=headers, data=payload)
soup = bs(req.text, 'html.parser')
eles = soup.select('tr td')
dates = (' '.join(d.select('b')[0].text.strip().split()) for d in eles if d.has_attr('class'))
events = (' '.join(d.text.split()) for d in eles if not d.has_attr('class'))
calendar = dict(zip(dates, events))

data_hoje = time.strftime("%d %b %Y", time.gmtime())
calendar[data_hoje] = calendar.setdefault(data_hoje, 'nenhum evento para hoje')
print(calendar[data_hoje])

Output do ultimo print (dia de hoje, 22 Feb 2017):

Ekādaśī, K, 05:46, Purvāṣāḍhā +ŚUDDHA EKĀDAŚĪ VRATA: FASTING FOR Vijaya EKADASI

Há que ter muita atenção aos elementos HTML que queremos, neste caso queremos os , se tiverem a class date é uma data (chave do dicionário) senão é o evento (valor correspondente)
Neste caso as keys do nosso dicionário vão ser o texto que está dentro de  que por sua vez este está dentro de um td que tenha o atributo class
Comment: Muito obrigado. Como passar para o print, imprimir print (calendar['data de hoje']) ? Tentei com from datetime import datetime mas nao deu certo!
Comment: Ha vou ver isso @EdS , só um sec
Comment: Muito obrigado. Desculpe o trabalho.
Comment: Sem problema eu devia ter lido esse pormenor na pergunta @EdS, mas enganou-se porque hoje é dia 22 Feb, e não 22 Abr :P
Comment: Muito bom. Obrigado. Vou estudar o codigo e depois marco como resolvido.
Comment: Ok @EdS, sem problema. Ainda bem que resolveste. O importante é mesmo perceber os elementos html que queres e como retirar informação
Comment: @EdS, editei a ultima por achar que assim fica melhor... com defaultDict: https://www.tutorialspoint.com/python/dictionary_setdefault.htm
Comment: DIa 10 Apr 2017 ocorrem varios eventos, como imprimir cada um em uma linha diferente?
Comment: @EdS em vez de `' '.join(d.text.split())`, deixa só `d.text`
Comment: Estou tentando modificar o seguinte: imagine que desejo imprimir o evento que ocorrerá daqui a X dias, por exemplo, 4 dias.  futuro = date.fromordinal(hj.toordinal()+4). O problema é que este codigo gera data assim: 2017-02-26. O que fazer?
Comment: @EdS isso é uma pergunta à parte. Agora não consigo ajudar porque não estou no computador. Mas tenta, `time.strftime("%d %b %Y", time.gmtime(time.time() + (3600 * 24 * 4)))`, para mais 4 dias a partir de hoje


Comparing logistic coefficients on models with different dependent variables?

Question: This is a follow up question from the one I asked a couple of days ago. I feel it puts a different slant on the issue, so listed a new question.
The question is: can I compare the magnitude of coefficients across models with different dependent variables? For example, on a single sample say I want to know whether the economy is a stronger predictor of votes in the House of Representatives or for President. In this case, my two dependent variables would be the vote in the House (coded 1 for Democrat and 0 for Republican) and vote for President (1 for Democrat and 0 for Republican) and my independent variable is the economy. I'd expect a statistically significant result in both offices, but how do I assess whether it has a 'bigger' effect in one more than the other? This might not be a particularly interesting example, but i'm curious about whether there is a way to compare. I know one can't just look at the 'size' of the coefficient. So, is comparing coefficients on models with different dependent variables possible? And, if so, how can it be done?
If any of this doesn't make sense, let me know. All advice and comments are appreciated.
Comment: Starting a bounty - seems like an important question with three very different answers, none of which has *a single vote*.  We can do better.  Andy W's [paper link](http://dx.doi.org/10.1093/esr/jcp006) on [this related question](http://stats.stackexchange.com/questions/8718/comparing-logistic-regression-coefficients-across-models/) seems pertinent.
Comment: How do you know one can't just look at the 'size' of the coefficient?
Comment: I merged your two accounts. You'll still need to register, as indicated on the [FAQ](http://stats.stackexchange.com/faq). (@onestop Thx for pointing to the duplicate.)
Comment: I assumed that I couldn't compare 'effect' of predictors across models by looking at the coefficients from the answers to my previous question. Are things different for my example above?
Answer: The short answer is "yes you can" - but you should compare the Maximum Likelihood Estimates (MLEs) of the "big model" with all co variates in either model fitted to both.
This is a "quasi-formal" way to get probability theory to answer your question
In the example, $Y_{1}$ and $Y_{2}$ are the same type of variables (fractions/percentages) so they are comparable.  I will assume that you fit the same model to both.  So we have two models:
$$M_{1}:Y_{1i}\sim Bin(n_{1i},p_{1i})$$
$$log\left(\frac{p_{1i}}{1-p_{1i}}\right)=\alpha_{1}+\beta_{1}X_{i}$$
$$M_{2}:Y_{2i}\sim Bin(n_{2i},p_{2i})$$
$$log\left(\frac{p_{2i}}{1-p_{2i}}\right)=\alpha_{2}+\beta_{2}X_{i}$$
So you have the hypothesis you want to assess:
$$H_{0}:\beta_{1}>\beta_{2}$$
And you have some data $\{Y_{1i},Y_{2i},X_{i}\}_{i=1}^{n}$, and some prior information (such as the use of logistic model). So you calculate the probability:
$$P=Pr(H_0|\{Y_{1i},Y_{2i},X_{i}\}_{i=1}^{n},I)$$
Now $H_0$ doesn't depend on the actual value of any of the regression parameters, so they must have be removed by marginalising.
$$P=\int_{-\infty}^{\infty} \int_{-\infty}^{\infty} \int_{-\infty}^{\infty} \int_{-\infty}^{\infty} Pr(H_0,\alpha_{1},\alpha_{2},\beta_{1},\beta_{2}|\{Y_{1i},Y_{2i},X_{i}\}_{i=1}^{n},I) d\alpha_{1}d\alpha_{2}d\beta_{1}d\beta_{2}$$
The hypothesis simply restricts the range of integration, so we have:
$$P=\int_{-\infty}^{\infty} \int_{\beta_{2}}^{\infty} \int_{-\infty}^{\infty} \int_{-\infty}^{\infty} Pr(\alpha_{1},\alpha_{2},\beta_{1},\beta_{2}|\{Y_{1i},Y_{2i},X_{i}\}_{i=1}^{n},I) d\alpha_{1}d\alpha_{2}d\beta_{1}d\beta_{2}$$
Because the probability is conditional on the data, it will factor into the two separate posteriors for each model
$$Pr(\alpha_{1},\beta_{1}|\{Y_{1i},X_{i},Y_{2i}\}_{i=1}^{n},I)Pr(\alpha_{2},\beta_{2}|\{Y_{2i},X_{i},Y_{1i}\}_{i=1}^{n},I)$$
Now because there is no direct links between $Y_{1i}$ and $\alpha_{2},\beta_{2}$, only indirect links through $X_{i}$, which is known, it will drop out of the conditioning in the second posterior. same for $Y_{2i}$ in the first posterior.
From standard logistic regression theory, and assuming uniform prior probabilities, the posterior for the parameters is approximately bi-variate normal with mean equal to the MLEs, and variance equal to the information matrix, denoted by $V_{1}$ and $V_{2}$ - which do not depend on the parameters, only the MLEs.  so you have straight-forward normal integrals with known variance matrix. $\alpha_{j}$ marginalises out with no contribution (as would any other "common variable") and we are left with the usual result (I can post the details of the derivation if you want, but its pretty "standard" stuff):
$$P=\Phi\left(\frac{\hat{\beta}_{2,MLE}-\hat{\beta}_{1,MLE}}{\sqrt{V_{1:\beta,\beta}+V_{2:\beta,\beta}}}\right)
$$
Where $\Phi()$ is just the standard normal CDF.  This is the usual comparison of normal means test.  But note that this approach requires the use of the same set of regression variables in each.  In the multivariate case with many predictors, if you have different regression variables, the integrals will become effectively equal to the above test, but from the MLEs of the two betas from the "big model" which includes all covariates from both models.
Answer: Why not? The models are estimating how much 1 unit of change in any model predictor will influence the probability of "1" for the outcome variable. I'll assume the models are the same-- that they have the same predictors in them. The most informative way to compare the relative magnitudes of any given predictor in the 2 models is to use the models to calculate (either deterministically or better by simulation) how much some meaningful increment of change (e.g., +/- 1 SD) in the predictor affects the probabilities of the respective outcome variables--& compare them! You'll want to determine confidence intervals for the two estimates as well as so you can satisfy yourself that the difference is "significant," practically & statistically.
Comment: Consult the King. He will not disappoint.  King, G., Tomz, M., & Wittenberg., J. (2000). Making the Most of Statistical Analyses: Improving Interpretation and Presentation. Am. J. Pol. Sci, 44(2), 347-361.
Comment: Thanks dmk8, very useful. Some follow-up points/questions: is this what is often meant when referring to varying the variable of interest (the economy from bad to good for example) while holding all control variables at their means? What do you mean by deterministically? How do I determine the confidence intervals around the probabilities?
Answer: I assume that by "my independent variable is the economy" you're using shorthand for some specific predictor.
At one level, I see nothing wrong with making a statement such as

X predicts Y1 with an odds ratio of _ and a 95% confidence interval of [ _ , _ ]
   while
  X predicts Y2 with an odds ratio of _ and a 95% confidence interval of [ _ , _ ].

@dmk38's recent suggestions look very helpful in this regard.
You might also want to standardize the coefficients to facilitate comparison.
At another level, beware of taking inferential statistics (standard errors, p-values, CIs) literally when your sample constitutes a nonrandom sample of the population of years to which you might want to generalize.
Comment: Yes, 'the economy' is shorthand for perceptions of national economic conditions. Does the same advice apply when other predictors (controls) are included in the model?
Comment: @Ejs - I'm afraid there's no short answer to your last question.  You're getting into what it means to assess relationships when using statistical control - a fabulously intricate topic worthy of extensive study.  You're also probably getting into the topic of variable selection, which is a big one as well.  Imho the best source for the committed student of these topics is Pedhazur's http://www.amazon.com/Multiple-regression-behavioral-research-Pedhazur/product-reviews/0030728312
Answer: Let us say the interest lies in comparing two groups of people: those with $X_{1} = 1$ and those with $X_{1} = 0$.
The exponential of $\beta_{1}$, the corresponding coefficient, is interpreted as the ratio of the odds of success for those with $X_{1} = 1$ over the odds of success for those with $X_{1} = 0$, conditional on the other variables in the model.
So, if you have two models with different dependend variables then the interpretation of $\beta_{1}$ changes since it is not conditioned upon the same set of variables. As a consequence, the comparison is not direct...
Comment: Does this have any implications for roland2's suggestion?
Comment: @Ejs. Do you refer to the standardisation step? By the way, does my answer help ? Have I misunderstood the question ?


Como popular Gráfico ChartJS com VueJs e Axios?

Question: não estou conseguindo popular meu gráfico com dados vintos de uma api, podem me ajudar, não sei o que estou fazendo de errado!
<template>

Site Traffic Overview

                    <canvas ref="chart"></canvas>

Comment: a saída console.log(dados) ta imprimindo corretamente? eu acredito que vc deveria usar this.dados = resposta.data
Comment: Sim, está, no console, tenho todos os dados mostrados, e o gráfico chega a ser montado, mas não carrega as labels e datasets | data, parece ser uma questão de ordem de carregamento que não estou sabendo resolver! Se puder ajudar, grata!
Answer: Aconselho usar um pacote chama vue-chartjs https://vue-chartjs.org/ e criar wrappers em cima dele, caso você não queira usar, você pode criar uma variável booleana em data, chamada hasData: false e adicionar um v-if na div do gráfico, v-if="hasData". Assim essa div não existirá até os dados serem populados na resposta do serviço, ou seja, dentro do then você seta o this.hasData = true após popular a variável dados, creio que com isso você resolva o problema.


How to render a taxonomy field in a Views' PHP code field?

Question: In Views PHP code, I could render a field by :-
<?php
  print drupal_render($data->field_field_my_text);
?>

But this only seems to work field with type Text. I have a field which is Taxonomy (Term Reference) and I am trying to output that through the above code but it's not working.
This is what I wrote:-
<?php
      print drupal_render($data->field_field_my_category);
    ?>

Unfortunately, this is not working. Any idea what I should do here?
Thanks.
Comment: Instead of adding PHP code in database I would suggest write a template file for it and write your code there.
Answer: I can't comment because of rep..
Use devel module and use the dpm() function in your php for some debugging, drill down and find the value you are looking for then double click the value in the debug widget and it should tell you your field value.
here's my guess:
$data->field_field_my_category[0]['raw']['value'];
Might be slightly different if it's a tax term but devel is your best friend and you should use it quite frequently. Stop guessing and start debuging (best advice i've ever gotten).