Which group homomorphisms induce the action of the fundamental group on the fiber?

Question: Given topological spaces $X$ and $Y$ and a covering map $p: X \rightarrow Y$, we know that the group $\pi_1(Y,y_0)$, where $y_0\in Y$, acts on the fiber $F=p^{-1}(y_0)$.
Also, we know that the set of all action $G\times M \rightarrow M$ of a group $G$ on a set $M$ is in a bijective correspondence with the set of all group homomorphisms $G\rightarrow \text{Sym}(M)$. Here $\text{Sym}(M)$ is the symmetric group on the elements of $M$.
In particulat, the action of the fundamental group of $X$, as any action of a group on a set, by the above, induces the group homomorphism $\pi_1(Y,y_0)\rightarrow \text{Sym}(F)$. Similarly, by the above, any group homomorphism $\pi_1(Y,y_0)\rightarrow \text{Sym}(F)$ must induce the action of $\pi_1(Y,y_0)$ on the fiber $F$. But I was told that this is not true. The question is why? In such a case, what additional requirements one must impose on the homomorphism $\pi_1(Y,y_0)\rightarrow \text{Sym}(F)$ in order that it induce the action on the fiber? Is it true that the homomorphism must be transitive? Does it have something to do with the Riemann Existence theorem? (If you refer to this theorem, please use its statement presented here.)
Comment: if $X$ for instance is connected, locally path-connected (and so is also $Y$) then this action is always free. If it is transitive (like the case where the covering is universal) then we call the cover regular.
Comment: with all due respect. I am not sure about your question. if you have for instance a universal cover then the $\pi_1(Y)$ is the group of deck transformations and so permutes the fibers. But I can't understand at the moment what's your problem, excuse me. Can you help me?
Comment: @mayer_vietoris It seems to me that it is always transitive. Regular transformations are such that some deck transformation (acting on $Y$) takes a point on $F$ to another point on $F$. But if you just choose two points on $F$ to be connected by a $\pi_1$-action, you only need $Y$ to be connected.
Comment: @PeterFranek as far as I know the transitivity of an action is a special property among the covers. For instance, for sufficiently "nice" topological spaces regular covering spaces are in an one-to-one correspondence with the normal subgroups of its fundamental group. If you choose one space whose fundamental group is a simple group, then the above fails.
Comment: Just choose a path in $Y$ connecting these two points $x,y\in F$ and project it to $X$: this gives you the element of $\pi_1$ that sends $x$ to $y$. (Not every action of $\pi_1$ on $F$ extends to a deck transformation)
Comment: @PeterFranek it's a standard theorem Peter, which states that for a connected and locally path connected space $X$ and assume $x_{0} \in X$ is an arbitrary point, then $(X',p)$ is a regular covering space of it if-f $Deck(X'/X)$  acts transitively on $p^{-1}(x_{0})$.
Comment: @mayer_vietoris I agree, but as far as I understood the question, he asked about the action of $\pi_1$ on $F$, not about deck transformations. Or am I missing something subtle?
Comment: @PeterFranek no Peter, I guess you are right, the followed-up comments that I did was on the case where the covering map is universal and in that case deck transformations are isomorphic with the fundamental group of the space.
Answer: The first problem is that the homomorphism $\pi_1(Y, y_0) \rightarrow \mathrm{Sym}(F)$ could be too small.  For instance, it could be the trivial homomorphism in a setting where the action of $\pi_1(Y,y_0)$ on $F$ is not always the identity permutation.
A minimal example of this is the (helical) double-cover of $S^1$.  Here, $F$ is two points and both the identity and "swap" actions are induced by $\pi_1(Y, y_0)$.  However, there are two homomorphisms $\pi_1(Y, y_0) \rightarrow \mathrm{Sym}(F)$.  The faithful one (the one with trivial kernel) does induce the action.  The trivial one does not.
Even more exciting, $\mathrm{Sym}(F)$ might be large enough to contain two copies of the action of $\pi_1(Y, y_0)$, only intersecting at the identity.  Then the homomorphism $\pi_1(Y, y_0) \rightarrow \mathrm{Sym}(F)$ can have trivial kernel and still map $\pi_1(Y, y_0)$ to a bunch of elements of $\mathrm{Sym}(F)$ that have no relation to the permutations induced by the action.  (This happens pretty quickly.  Symmetric groups tend to have lots of conjugate, nearly disjoint (, small) subgroups.)
I haven't thought about conditions which would restrict the image of the homomorphism $\pi_1(Y, y_0) \rightarrow \mathrm{Sym}(F)$ to the subset of $\mathrm{Sym}(F)$ induced by the action of $\pi_1(Y, y_0)$, but I'm not convinced it can be much different than "the image of the homomorphism is exactly the set of permutations induced by the action".


If $x≥0$ and $0≤x<ϵ$, for all $ϵ>0$, then $x=0$?

Question: I tried to let ϵ=0.5x, but find ϵ might be zero in this way, which is contradict to for all ϵ>0. Is this statement false?
Comment: Suppose $x>0$. What can you conclude?
Comment: The statement says that the conclusion follows if the inequality is true for all $\epsilon > 0$. Fixing $\epsilon$ at a particular value is not meaningful, especially if that value is possibly outside of the range of $\epsilon$ that you are allowed to consider.
Answer: Prove it by contradiction.
Suppose $x \ge 0$ but $ x \ne 0$. So, $x > 0$
Then for $\epsilon = x/ 2 \gt 0$ we have $ x \not \lt \epsilon$.
Answer: Your statement means that x is non negative yet it is strictly smaller than every positive real number. Hence x=0 is the only possible solution
Answer: Argue by contradiction. Assume $x>0.$ Then consider $\epsilon=\dfrac x2>0.$ By assumption we have that $$0\le x<\epsilon =\dfrac x2,$$ from where it must be $x=0.$ This gives a contradiction with the assumption $x>0.$
So, we have shown that $x=0.$
Answer: $$(\forall \epsilon>0)\; \;0\leq x\leq \epsilon$$
$$\implies (\forall n>0)\;\; 0\leq x\leq \frac{1}{n}$$
$$\implies 0\leq x \leq \lim_{n\to+\infty}\frac{1}{n}$$
$$\implies x=0.$$
Answer: You can either take the limit of $\epsilon \to 0$ or suppose that $x \not= 0$ and try to find a contradiction.


Draw another chart/or series on mouse hover in HighStock

Question: I have an indicator which is a function of x, y.
How can i draw this indicator on top of chart?
Lets say here https://jsfiddle.net/yv3pehj8/
plotOptions: {
        series: {
            point: {
                events: {
                    mouseOver: function () {
                        var chart = this.series.chart;
                        if (!chart.lbl) {
                            chart.lbl = chart.renderer.label('')
                                .attr({
                                    padding: 10,
                                    r: 10,
                                    fill: Highcharts.getOptions().colors[1]
                                })
                                .css({
                                    color: '#FFFFFF'
                                })
                                .add();
                        }
                        chart.lbl
                            .show()
                            .attr({
                                text: 'x: ' + this.x + ', y: ' + this.y
                            });
                    }
                }
            }

Instead of printing x,y value on the corner, I wanted to draw a line at an angle of 45 degrees to the hover point ranging from [x-10, x+10]. How could I do it in the most performant way?
TIA
EDIT
Many thanks for the solution. To make it a bit more complicated. i want to reach the following effect as seen in this image []
i want to draw the blue/red curves as you see in the image on mouse hover.. Would you happen to have a solution for this @ppotaczek??
Answer: Instead of rendering the label, you can render a path:
plotOptions: {
    series: {
        point: {
            events: {
                mouseOver: function() {
                    var chart = this.series.chart,
                        path = [
                            'M',
                            chart.plotLeft + this.plotX - 10,
                            chart.plotTop + this.plotY - 10,
                            'L',
                            chart.plotLeft + this.plotX + 10,
                            chart.plotTop + this.plotY + 10
                        ];

                    if (!chart.lbl) {
                        chart.lbl = chart.renderer.path(path)
                            .attr({
                                'stroke-width': 2,
                                stroke: 'red'
                            })
                            .add();
                    }
                    chart.lbl
                        .show()
                        .attr({
                            d: path
                        });
                }
            }
        },
        ...
    }
}

Live demo: https://jsfiddle.net/BlackLabel/zo46fuxb/
API Reference: https://api.highcharts.com/class-reference/Highcharts.SVGRenderer#path
Comment: many thanks @ppotaczek could you please suggest how to reach the desired effect as in the image  added by me in the edit ??
Comment: Hi @user4772933, I am glad I could help. Sure, I will help you in your second thread: https://stackoverflow.com/questions/57458149/draw-multiple-series-upon-mouse-hover-in-highstock


Showing representation of centralizer is irreducible.

Question: $G$ is a finite group with a subgroup $H$. Let $\rho_1:G \to GL(V)$ and $\rho_2:H \to GL(U)$ be representations. $Z=\mathbb{C}[G]^H$, i.e., $Z$ is the centralizer of $H$ in $\mathbb{C}[G]$.
How do I show the representation $$\phi:Z \to End(Hom_H(U,V))$$ given by $\phi_g:f \to \rho_1(g) \circ f$ is irreducible?
If I am not mistaken, $Z$ might be infinite and $Hom_H(U,V)$ might be infinite dimensional.
Comment: I am sorry. I fixed the notation.
Answer: The claim isn't true. Maybe you can clarify the claim after this post.
There is a natural isomorphism $\hom(\Bbb C,V)\cong V$. Every vector $v\in V$ can be identified canonically with the linear map $\lambda\mapsto \lambda v$ (this is $\Bbb C\to V$). Moreover, it is a natural isomorphism of representations of $G$ if $G$ acts trivially on $\Bbb C$.
So suppose that $H=1$ is the trivial subgroup of $G$. Then $Z=\Bbb C[G]^H=\Bbb C[G]$. Furthermore we may note that $\hom_H(U,V)\cong V$ naturally if $U=\Bbb C$ is the trivial representation. Therefore the map
$$Z\to{\rm End}(\hom_H(U,V))$$
is just the already-in-place action of $\Bbb C[G]\to{\rm End}(V)$. If we choose $V$ to be reducible, then the above representation must also be reducible, since it's equivalent.


How to guess the size of a set?

Question: Assume we have a set of unique words and draw a number $n$ of them using simple-random-sampling without replacement independently in each round. We have several rounds and try to guess the set size after each round. The words are drawn from the same set in each round, but are drawn without replacement in each round (all words are distinct in each round). How could this be achieved and how big would the error be?
For example if the set size is smaller than $n$, then we would only need one round.  If the set size is close to $n$, in the second round the number of words that were drawn in the first round would be close to $n$.  So I know that we get some information, but I don't understand how we could efficiently guess the set size.
Comment: OP: The abbreviation should be spelled out and the replacement issue made explicit in the question. Please edit. One possibly related topic is the capture-recapture method (aka mark-and-recapture), depending on the clarifications.
Comment: @utobi *u.a.r* is probably "uniformly at random" - it is not stated whether this is with or without replacement but I would guess without replacement in each round and then replaced for the next round
Comment: If the words are replaced between rounds (or, better, if they were replaced before the subsequent draw) then the system is an analog of the 'catch and release' approach to estimation of populations or, for example, fish.
Comment: Rasmus Baath has a fascinating take on a similar problem on YouTube. It's not the answer to your question but close enough to recommend watching for this: https://youtu.be/nKCT-Cdk0xY The video is called "Tiny data, Approximate Bayesian Computationand the Socks of Karl Broman".
Comment: what is w.a.r.?
Comment: I updated the question. Yes u.a.r. meant uniformly at random. And @Henry was right with his assumptions about the replacements.
Comment: Based on the comments here, I have taken the liberty to edit the question to more clearly specify the sampling method.
Comment: Count-min sketch? Or some sort of hash-and-sketch algorithm like that?
Answer: Using the following notation:
$s_i$: the number of samples for the $i^{th}$ round
$k_i$: the number of words sampled in the $i^{th}$ round that had not been previously sampled
$m_i=\sum_{j=1}^ik_j$
$\pi_1(n)$: the prior distribution of $n$
We'll also assume $n\geq{s}$; otherwise we can determine $n$ after the first round of sampling. We can update $\pi(n)$ beginning with the second round of sampling:
$$\pi_i(n)\propto\frac{\binom{m_{i-1}}{s_i-k_i}\binom{n-m_{i-1}}{k_i}}{\binom{n}{s_i}}\pi_{i-1}(n)$$
$$\propto\pi_1(n)\prod_{j=2}^i\frac{(n-m_{j-1})!(n-s_j)!}{n!(n-m_{j-1}-k_j)!}$$
Implemented as an R function:
pn <- function(s, k, prior) {
  l <- length(s)
  m <- cumsum(k[-l])
  s <- s[-1]
  k <- k[-1]
  function(n) pmax(prior(n)*exp(colSums(lgamma(outer(1 - m, n, "+")) + lgamma(outer(1 - s, n, "+")) - lgamma(outer(1 - m - k, n, "+"))) - (l - 1)*lgamma(n + 1)), 0, na.rm = TRUE)
}

For example, say $\pi_1(n)\sim{U(8,30)}$, $k=5,3,1$, and $s=5,5,5$.
k <- c(5, 3, 1)
s <- rep(5, 3)

post <- pn(s, k, function(n) 1)
like <- post(8:30)
plot(8:30, like/sum(like), xlab = "n", ylab = "p(n)", col = "blue", pch = 3)

We can verify the results with simulation:
library(parallel)
set.seed(724526144)
nreps <- tabulate(sample(23, 23e6, TRUE), 23)
clust <- makeCluster(detectCores() - 1)
clusterExport(clust, c("nreps", "s", "k"))
sim <- unlist(parLapply(clust, 1:23, function(i) sum(replicate(nreps[i], all(cumsum(!duplicated(c(replicate(3, sample(i + 7, 5)))))[cumsum(s)] == cumsum(k))))))
stopCluster(clust)
points(8:30, sim/sum(sim), col = "orange")
legend("topright", legend = c("Posterior likelihood", "Simulation"), col = c("blue", "orange"), pch = c(3, 1))

If we had observed $k=5,4,2$ instead of $k=5,3,1$, we can see the posterior distribution shift toward larger values of $n$.
k <- c(5, 4, 2)

post <- pn(s, k, function(n) 1)
like <- post(8:30)
plot(8:30, like/sum(like), xlab = "n", ylab = "p(n)", col = "blue", pch = 3)

Again verifying the results with simulation:
set.seed(353678169)
nreps <- tabulate(sample(23, 23e6, TRUE), 23)
clust <- makeCluster(detectCores() - 1)
clusterExport(clust, c("nreps", "s", "k"))
sim <- unlist(parLapply(clust, 1:23, function(i) sum(replicate(nreps[i], all(cumsum(!duplicated(c(replicate(3, sample(i + 7, 5)))))[cumsum(s)] == cumsum(k))))))
stopCluster(clust)
points(8:30, sim/sum(sim), col = "orange")
legend("topright", legend = c("Posterior likelihood", "Simulation"), col = c("blue", "orange"), pch = c(3, 1))

Answer: First some notation: Assume $N$ unique words, sampled with the same probability. We are doing $R$ (independent) rounds of simple random sampling without replacement, each round the sample size is $n \le N$ (generalization to unequal sample sizes should be straightforward).
Define indicator random variables
$$ X_{ij} =\begin{cases} 1 & \text{word $j$ sampled in round $i$} \\
                         0 & \text{otherwise} \end{cases} $$
Note that we have
\begin{align}
  \sum_j X_{ij} &= n ~(\text{for all $i$}) \\
  \sum_i X_{ij} &\sim \mathcal{Binom}(R, n/N)
\end{align}
but all these binomial random variables are not independent, since they have a fixed, constant sum $nR$. But if $N$ is large and $n/N$ small the dependence would be slight.
Define $Y_j = \sum_i X_{ij}$ each having the binomial distribution defined above. The exact likelihood function for this problem will be intractable, so I will not write it out. But based on this binomials $Y_j$ we can construct a composite likelihood function, see the references at Parameter Estimation for intractable Likelihoods / Alternatives to approximate Bayesian computation.
But before going into the details, we can also define pair statistics
$$ Y_{jl} = \sum_{i=1}^R X_{ij} X_{il} \quad \text{for $j\not=l$}
$$
which will also have binomial distributions: $\mathcal{Binom}(R,\frac{n}{N}\cdot\frac{n-1}{N-1})$.
The idea with composite likelihood (a specific form of pseudo-likelihood) is to construct individual likelihood functions from parts of the data, and then just multiply them together, as would be correct if they where independent ... even if they are not independent. See the linked page above for details.
First, we find the composite likelihood only based on the $Y_j$. First, suppose the total number of unique words sampled in the $R$ rounds are $M \le N$. Then the composite likelihood for the one unknown parameter $N$ becomes
$$ \prod_{j=1}^M \binom{R}{y_j}(n/N)^{y_j} (1-n/N)^{R-y_j} \cdot \left[ (1-n/N)^R \right]^{(N-M)}
$$ the last factor coming from the $N-M$ unobserved words.
(sorry, now it is late night here, so I will continue this answer tomorrow)
Answer: This is known as the Mark and Recapture problem, because the people who most often encounter it are ecologists estimating population size. There are many methods available, which you can find by searching for "Mark and Recapture".

How to guess the size of a set?


Using Drupal 6's form ahah to have one dropdown field update the values of a second dropdown field

Question: I am working on a pair of form fields the directly effect one another. Specifically the problem I am dealing with is that we have thousands of groups users can join on this website that I have been working on. We are creating some administrative analytics forms for the site. Part of those forms is filtering by group.
The problem is that most of the people don't know the name of a group off the top of their heads, only what it starts with. So instead of using auto-complete we came up with two dropdowns. The first contains the options A through Z, letters of the alphabet which the group names begin with. The second dropdown contains all of the groups beginning with the selected letter.
The concept is simple enough and we were able to implement the AJAX pretty easy with jQuery. But this causes validation errors. After some research I found that this has to do with Drupal form caching. The solution is to use the ahah functions.
The problem with that is that all the instructions I have found so far deal with ahah actions for the specified field updating itself, not another field. So I am trying to figure out how to get the list of letters to update the group list using ahah and registering the new values with the form cache.
One solution I found was to simply load all the values on the page in a hidden dropdown and then just load up those in the set in the visible one as needed. But that creates a bunch of problems because the client uses almost exclusively IE and we have seen IE choke when given huge lists like that. Especially with the lists stored in JavaScript. So we need a light-weight solution.
Any thoughts? Ideas?
Answer: There's comprehensive example code in the Examples module that shows how to do this.
In the dependant_dropdown.inc file of the ahah_example module, you'll find an example form that does exactly what you're looking for. It's very well commented and should guide you through the process pretty well.
There's also a companion tutorial for the ahah_example module which would be worth looking it as it has more code examples.
Comment: Thanks, I will take a look at that. If it works out, then you win.


Volume Shell Integration of $\int_{0}^{1} 2\pi\frac{x}{e^{x^2}}\,dx$

Question: I have a question on the integration of the below integral. It is part of a larger problem about using shell integration to find the volume generated by rotating the region bounded by the given curves about the y-axis, where
$$y = e^{-x^2}, y=0, x=0, x=1 $$
Let $u = e^{x^2}, du = 2xe^{x^2}$
$$\begin{align}
I &= \int_{0}^{1} 2\pi\frac{x}{e^{x^2}} = 2\pi \int_{0}^{1} \frac{1}{2} \frac{du}{u^2} \\
&= \pi \bigg[ -\frac{1}{u^1} \bigg]_{0}^{1} = \pi \bigg[ -\frac{1}{e^{2^x}} \bigg]_{0}^{1} \\
& = -\pi \frac{1}{e}
\end{align}$$
However the textbook says the answer is $\pi(1-\frac{1}{e})$. Not really sure if I set the problem up wrong, or if I did some illegal u-substitution moves (I don't feel the best about getting the $\frac{1}{u^2}$ part).
Comment: $e^0=1{}{}{}{}$
Comment: Correct; as @quarague points out, you have a few typos, but the only major mistake you have is assuming that plugging in $0$ produces $0$.
Comment: Thank you Clayton. So that is the issue and not my u-substitution?
Comment: You have a few typos in your math code but the extra $1$ comes from plugging in $x=0$.
Answer: The setup for the shell method looks fine, but the antiderivative for $\displaystyle\int xe^{-x^2}\,dx$ that you came up with doesn't seem to be correct. Just use the u-substitution $u=-x^2$:
$$
\int xe^{-x^2}\,dx=
-\frac{1}{2}\int e^{-x^2}\frac{d}{dx}\left(-x^2\right)\,dx=
-\frac{1}{2}\int e^u\,du=\\
-\frac{1}{2}e^u+C=
-\frac{1}{2}e^{-x^2}+C.
$$
$$
V=2\pi\int_{0}^{1} xe^{-x^2}\,dx=
-\pi\frac{1}{e^{x^2}}\bigg|_{0}^{1}=
-\pi\left(\frac{1}{e^{1^2}}-\frac{1}{e^{0^2}}\right)=\\
-\pi\left(\frac{1}{e}-\frac{1}{1}\right)=
-\pi\left(\frac{1}{e}-1\right)=
\pi\left(1-\frac{1}{e}\right)\ cubic\ units.
$$


embed any web page

Question: i would like to embed the public view of my Google Scholar page into my personal webpage. I used the iframe tags, however the resulting box is just empty. What are the general rule where iframe tag applies?
Comment: can you put some code
Answer: Short answer: you cannot, because google refuses to allow other sites to embed its pages. Actually, if you are using a debugger, it should warn you that Google is using the same origin policy on its response:
Refused to display 'http://scholar.google.fr/...' in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'.
Answer: Want to know all about ? Follow the link below.
http://www.w3schools.com/tags/tag_iframe.asp
My opinion is to avoid iframes because of bookmarking and navigation.
Here are some alternatives
Alternatives to Iframe
http://icant.co.uk/articles/crossdomain-ajax-with-jquery/index.html
Comment: If you're going to link to a resource to find out more about certain HTML elements you should link to the [W3 HTML specification](http://www.w3.org/TR/html5/embedded-content-0.html#the-iframe-element). W3Schools is generally frowned upon.
Comment: A link to a solution is welcome, but please ensure your answer is useful without it: [add context around the link](//meta.stackexchange.com/a/8259) so your fellow users will have some idea what it is and why it's there, then quote the most relevant part of the page you're linking to in case the target page is unavailable. [Answers that are little more than a link may be deleted.](//stackoverflow.com/help/deleted-answers)
Answer: The way I solved this is by exporting all my publications from Google Scholar to a bib file then use bibbase.org to create a publications page using the generated bib file. You can embed the generated page into your website. Works fine and looks good.

embed any web page


Como escrever esse bean xml usando java?

Question: <bean id="templateEngine" class="org.thymeleaf.spring4.SpringTemplateEngine">
          ...
          <property name="additionalDialects">
            <set>

              <bean class="org.thymeleaf.extras.springsecurity4.dialect.SpringSecurityDialect"/>
            </set>
          </property>
          ...
        </bean>

Não estou usando o Spring-boot.
Gostaria de saber como encaixar o treixo acima no formato java em umas das classes abaixo:
@Configuration
public class ThymeleafConfig {

    @Autowired
    private ApplicationContext applicationContext;

    @Bean
    public ViewResolver thymeleafViewResolver(ITemplateEngine templateEngine) {
        ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();

        viewResolver.setOrder(1);
        viewResolver.setTemplateEngine(templateEngine);
        viewResolver.setCharacterEncoding("UTF-8");
        viewResolver.setViewNames(new String[]{"*.html"});

        return viewResolver;
    }

    @Bean
    public ITemplateEngine templateEngine(ITemplateResolver templateResolver) {
        SpringTemplateEngine templateEngine = new SpringTemplateEngine();

        templateEngine.setTemplateResolver(templateResolver);
        templateEngine.setEnableSpringELCompiler(true);
        templateEngine.addDialect(new Java8TimeDialect());//adicionado para trabalhar com data do java8
        templateEngine.addDialect(new SpringSecurityDialect());

        return templateEngine;
    }

    @Bean
    public ITemplateResolver templateResolver() {
        SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();

        templateResolver.setApplicationContext(this.applicationContext);
        templateResolver.setTemplateMode(TemplateMode.HTML);
        templateResolver.setPrefix("/WEB-INF/templates/");
        templateResolver.setCharacterEncoding("UTF-8");
        templateResolver.setCacheable(false);

        return templateResolver;
    }

}

e
public class SpringWebInitializer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {

            AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext();

        applicationContext.scan(SpringWebInitializer.class.getPackage().getName());

        servletContext.addListener(new ContextLoaderListener(applicationContext));
        servletContext.addListener(new RequestContextListener());

        ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcher", dispatcherServlet(applicationContext));
        dispatcher.setLoadOnStartup(1);
        dispatcher.addMapping("/");

        FilterRegistration.Dynamic characterEncodingFilter = servletContext.addFilter("characterEncodingFilter", characterEncodingFilter());
        characterEncodingFilter.setAsyncSupported(true);
        characterEncodingFilter.addMappingForServletNames(dispatcherTypes(true), false, "dispatcher");

        FilterRegistration.Dynamic inViewSession =
                servletContext.addFilter(
                        "Spring OpenEntityManagerInViewFilter",
                        new OpenEntityManagerInViewFilter());
        inViewSession.setAsyncSupported(Boolean.TRUE);
        inViewSession.addMappingForUrlPatterns(null, true, "/*");

        FilterRegistration.Dynamic securityFilter =
                                servletContext.addFilter("springSecurityFilterChain", new DelegatingFilterProxy());
                securityFilter.setAsyncSupported(Boolean.TRUE);
                securityFilter.addMappingForUrlPatterns(null, true, "/*");
    }

    private DispatcherServlet dispatcherServlet(WebApplicationContext applicationContext) {
          DispatcherServlet dispatcherServlet = new DispatcherServlet(applicationContext);

        dispatcherServlet.setThrowExceptionIfNoHandlerFound(true);
        return dispatcherServlet;
    }

    private CharacterEncodingFilter characterEncodingFilter() {
        CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();

        characterEncodingFilter.setEncoding("UTF-8");
        characterEncodingFilter.setForceEncoding(true);

        return characterEncodingFilter;
    }

    private EnumSet<DispatcherType> dispatcherTypes(boolean asyncSupported) {
        return (asyncSupported ?
                EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.INCLUDE, DispatcherType.ASYNC) :
                EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.INCLUDE));
    }
}

e
@EnableWebMvc
@Configuration
@ComponentScan("com.aplicacao.thymeleaf")
public class WebConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}

@Bean
public MultipartResolver multipartResolver() {
    CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
    multipartResolver.setMaxUploadSize(100000);// 100k
    return multipartResolver;
}

@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {

    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.registerModule(new Hibernate4Module());

    Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
    builder.dateFormat(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"));

    MappingJackson2HttpMessageConverter converter
            = new MappingJackson2HttpMessageConverter(builder.build());

    converter.setObjectMapper(objectMapper);

    converters.add(new ByteArrayHttpMessageConverter());
        converters.add(converter);

    }
}

e
@Configuration
@EnableJpaRepositories("com.aplicacao.thymeleaf.repository")
@EnableTransactionManagement
@PropertySource("classpath:/application.properties")
public class SpringDataConfig {

    @Autowired
    private Environment env;

    @Bean
    public PlatformTransactionManager transactionManager(EntityManagerFactory factory) {
        JpaTransactionManager manager = new JpaTransactionManager();
        manager.setEntityManagerFactory(factory);
        manager.setJpaDialect(new HibernateJpaDialect());
        return manager;
    }

    @Bean
    public HibernateJpaVendorAdapter jpaVendorAdapter() {
        HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
        adapter.setShowSql(env.getProperty("hibernate.show.sql", Boolean.class));
        adapter.setGenerateDdl(env.getProperty("hibernate.ddl", Boolean.class));
        return adapter;
    }

    @Bean
    public EntityManagerFactory entityManagerFactory() {
        LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
        factory.setJpaVendorAdapter(jpaVendorAdapter());
        factory.setPackagesToScan(
                env.getProperty("hibernate.package.scan"),
                env.getProperty("java.time.jpa.converter")
        );
        factory.setDataSource(dataSource());
        factory.afterPropertiesSet();
        return factory.getObject();
    }

    @Bean(name = "dataSource")
    public DataSource dataSource() {
        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setUsername(env.getProperty("jdbc.user"));
        dataSource.setPassword(env.getProperty("jdbc.pass"));
        dataSource.setDriverClassName(env.getProperty("jdbc.driverClass"));
        dataSource.setUrl(env.getProperty("jdbc.url"));
        return dataSource;
    }

Answer: Uma maneira de escrever este bean é da seguinte maneira:
@Configuration
public class ThymeleafEngineConfiguration {

    @Bean
    @ConditionalOnMissingBean(SpringTemplateEngine.class)
    public SpringTemplateEngine templateEngine() {
        SpringTemplateEngine engine = new SpringTemplateEngine();
        engine.setAdditionalDialects(additionalDialects());
        return engine;
    }

    @Bean
    public Set<IDialect> additionalDialects() {
        Set<IDialect> dialects = new HashSet<>();
        IDialect dialect = new SpringSecurityDialect();
        dialects.add(dialect);
        return dialects;
    }

}

neste link você encontra um exemplo mais detalhado
Comment: Obrigado mas não estou usando o spring-boot !! Poderia me ajudar?
Comment: A sim, neste caso tente colocar os dois métodos `templateEngine()` e `additionalDialects()` dentro de sua classe `ThymeleafConfig`
Comment: Pelo que vì no seu código vc tem um método chamado `templateEngine()` tente colocar neste método o seguinte trecho `templateEngine.setAdditionalDialects(additionalDialects())` ai vc precisa só copiar o método `additionalDialects()` para o seu código


Web Service NFE Prefeitura de São Paulo Erro 1402

Question: boa tarde.
Estou criando um código para acesso ao Web Service de NFE da Prefeitura de São Paulo, chamando o método de Pedido de Consulta de NF-e Emitidas.
Criei todo o código de integração, inclusive gerando o XML assinado pelo certificado digital e aparentemente está tudo correto com o código, mas ao fazer uso recebo um XML de retorno com o erro 1402 O CPF/CNPJ da assinatura da mensagem XML não tem acesso ao Tomador de Serviços
informado..
Alguém sabe qual a causa desse erro?
Answer: Poste mais um pouco do código que faz a consulta.
Esta fazendo o download através de qual WebService? Bom se for o servidor da Sefaz no caso você muito provavelmente estará fazendo uma manifestação destinatário e depois uma Distribuição
Bom Se for isso o conceito e:
Você vai colocar o CNPJ do destinatário que na maioria dos casos e você mesmo. Utilizando seu certificado digital (Do destinatário que no caso e você mesmo) irá fazer o processo citado acima. Manifestação e Distribuição.
Porque e preciso de manifestação e distribuição?
manifestação: você confirma que a NFe foi realmente emitida para você. Em outras palavras você diz para a sefaz: Sefaz essa NF-e realmente foi emitida para min, ok? (Manifestação de confirmar "Ciência da Operação")
Distribuição: faz uma distribuição pela chave da nf-e ou pelo nsu depende do caso.
Obs: A prefeitura de são paulo disponibiliza um download custom de NF-e? Ou e servidor da Sefaz de São paulo?


Mass and center of mass using double integrals

Question: Disclaimer: This was given as a homework from college but the teacher didn't teach us anything about density or mass or anything related.
A lamina has the form of the region limited by the parabola $ y = x^2 $ and the straight line $ y = x $. The density varies as the distance from the $ X $ axis.
Find the mass and center of mass.
what i could find however is that the formula of mass is the following
$$M = \int\int_R \rho(x,y)dA $$
so i tried doing something like this
$$ \int_0^1\int_y^{\sqrt(y)} ? dxdy $$
the thing is that they say the density varies as the distance from the x axis, so i don't know what to replace for the density.. is it $ x + y $?
Comment: No, it would just be $ky$, where $k$ is some constant of proportionality that won't matter for the center of mass, but will (naturally) matter for the mass itself.
Comment: (Since $y$ is the distance from the $x$-axis.  Just making sure you see this correction.)
Answer: The mass density varies as the distance from the x-axis implies that $\rho =Ky$ where $K$ is a constant.
Now, the total mass is given by
$$M=\int_0^1 \int_y^{\sqrt{y}} (Ky) dx dy$$
The moment about x is
$$\frac{\int_0^1 \int_y^{\sqrt{y}} x(Ky) dx dy}{M}$$
$$\frac{\int_0^1 \int_y^{\sqrt{y}} y(Ky) dx dy}{M}$$
Can you complete?  Notice that the moments are independent of $K$.
Comment: i think i understand you but i have a couple of questions so everything comes clear: 1) why K? i mean is it part of a formula or something or what's the reason for the constant?. 2) if it were that the density varies as the distance from the y-axis, it would be $ \rho = Kx $? and 3) are the integration boundaries right?
Comment: Great!  On $1$, $K$ is a proportionality constant.  Keep in mind dimensional analysis.  If $M$ is mass in, say kilograms (kg), and $y$ is the distance from the $x$-axis in, say meters (m), then $K$ is a constant in kg/m.  The greater $K$, the greater the mass density.  On $2$, if you are at $(x,y)$ you are $x$ units away from the $x$-axis, and $y$ units away from the $x$-axis.  On $3$, the integration limits that you used are indeed correct!
Comment: Well thanks, it solved my questions and i learned a little more.
Comment: You're welcome.  My pleasure.  I'm glad that this really helped!!
Answer: Mass of lamina is K/15
(Density=KY)
On the vertical strip on the region of integration-
Y varies from parabola to straight line i.e. x^2 to x
And X varies from 0 to 1
Thus after double integration by the mass formula, we get mass of lamina=K/15


Return a value from a userform

Question: I am trying to return a value from a userform to another macro.
Here is an example of a piece of code that I want to return the value intMonth:
sub comparison()
    UserForm1.Show
end sub

then I have the userform code:
Private Sub initialize()
    OptionButton1 = False
End Sub

Private Sub OptionButton1_Click()
    intMonth = 1
    Me.Hide
End Sub

How do I get the intMonth value of 1 back to my original comparison() function?
Comment: You could make `intMonth` public, or create a `Public Property`, and then refer to those back in your calling code.
Comment: https://stackoverflow.com/questions/2722146/how-do-i-declare-a-global-variable-in-vba
Answer: This is a minimal example, but should help.

In the UserForm:
Option Explicit
Option Base 0

Public intMonth As Long    ' <-- the variable that will hold your output

Private Sub initialize()
    OptionButton1 = False
    intMonth = 0
End Sub

Private Sub CommandButton1_Click()  ' OK button
    Me.Hide
End Sub

Private Sub OptionButton1_Click()
    intMonth = 1    '<-- set the value corresponding to the selected radio button
End Sub

Private Sub OptionButton2_Click()
    intMonth = 2
End Sub

In a module or ThisWorkbook:
Option Explicit
Option Base 0

Sub comparison()
    UserForm1.Show
    MsgBox CStr(UserForm1.intMonth)   ' <-- retrieve the value
End Sub

Comment: @MathieuGuindon Yep - the code as is also doesn't reset the radio buttons if `comparison` is called repeatedly without an editor reset between them :) .  I was trying to keep the answer focused on the OP's stated issue, but agree with your point.  My personal style is `Dim f as UserForm: set f = New UserForm` &c.
Comment: Thank you, i see what i was doing wrong now, i didnt have a variable declared in the userform code for it to return. Can i just confirm, you are saying rather than using UserForm1.Show, i should create an instance of the UserForm in my comparison () sub?
Comment: @MikeHill good news!  Yes, `UserForm1. Show` can cause you problems later, so `comparison` should create an instance.  The second code sample in the article linked above by @MathieuGuindon shows an example.  Happy hacking!
Comment: Yep, i read through it, and i think i actually understand it. Thanks for your help cxw
Answer: Another useful way to achieve what you need is to wrap the code in a public function in the userform.
In the UserForm:
Option Explicit
Option Base 0

Private intMonth As Long

Public Function Choose_Option()
    OptionButton1 = False
    intMonth = 0
    Me.show()

    Choose_Option = intMonth
End sub

Private Sub CommandButton1_Click()  ' OK button
    Me.Hide
End Sub

Private Sub OptionButton1_Click()
    intMonth = 1
End Sub

Private Sub OptionButton2_Click()
    intMonth = 2
End Sub

Then in module, it is simple as this:
Option Explicit
Option Base 0

Sub comparison()
    MsgBox Userform1.Choose_Option()
End Sub

This way, the function is in charge of showing the userform, prompting the user and returning the value.
If you debug this function, you will see that after Me.Show() is called, the function halts and continue only when the userform is hidden, which is done in the OK button.

Return a value from a userform


distinguishable arrangements using combinations

Question:
Please have a look at question 1 first.
Can any one please tell me how to understand the method used in the second question?
Many thanks.
Comment: Choose $3$ out of $10$ places for the letter A, choose $4$ out of the remaining $7$ places for the letter B, choose $3$ out of the remaining $3$ places for the letter C.
Comment: possible duplicate of [How many different words can be formed using all the letters of the word GOOGOLPLEX?](http://math.stackexchange.com/questions/483277/how-many-different-words-can-be-formed-using-all-the-letters-of-the-word-googolp)
Comment: thanks barak, you have been most helpful. that is exactly what I need to know.
Answer: There are 10 positions and you can think of this question in 3 stages and multiply the number of choices at each stage to get the final answer.
Stage 1: choose where to place the 3 letters A: $\binom{10}{3}$ choices (10 places, 3 indistinguishable objects).
Stage 2: choose where to place the 4 letters B: $\binom{7}{4}$ choices (7 places left, 4 indistinguishable objects)
Stage 3: choose where to place the 3 letters C: $\binom{3}{3}$ choices (3 places left, 3 indistinguishable objects, no choice actually).
You can observe that your answer is independent of the order of choices you make about the stages, by writing out the binomial coefficients and seeing the cancellations. So $\binom{10}{4}\binom{7}{3}\binom{3}{3}$ as well as $\binom{10}{3}\binom{7}{3}\binom{4}{4}$ give the same numerical answer.
As an exercise, you can write a general expression for $n$ total slots for $v$ distinct letters,  and $k_i$ instances of each letter, where $k_1+k_2+...+k_v=n$ and simplify it.


Saving controls (UIElements) in list in IsolatedStorage

Question: I'm writing an app where I have create a few controls of my own. One of these controls are being added to a ListBox dynamically after the user's wish.
This controls contains 4 TextBoxes, and each of these TextBoxes get their data from the user when he/she enters them. But the thing i cannot get to work, is how to save them. I tried to save the list as a normal list - which didn't work. See my code:
Declarations:
List<scheduleControl> scheduleList;
IsolatedStorageSettings settings;

Initialization of settings:
settings = IsolatedStorageSettings.ApplicationSettings;

Add the control dynamically to the list:
        private void addscheduleitemButton_Click(object sender, RoutedEventArgs e)
    {
        // addscheduleitemButton was tapped, add an item to the list holding the information the user entered

        scheduleControl control = new scheduleControl();
        control.fromTextBlock.Text = "From: " + fromTextBox.Text.ToString();
        control.toTextBlock.Text = "To: " + toTextBox.Text.ToString();
        control.detailsTextBlock.Text = "Details: " + detailsTextBox.Text.ToString();
        control.dateTextBlock.Text = "Date: " + dateTextBox.Text.ToString();

        // Create Thickness
        Thickness stackpanelThickness = new Thickness();
        stackpanelThickness.Bottom = 20;
        stackpanelThickness.Top = 0;
        stackpanelThickness.Right = 0;
        stackpanelThickness.Left = 0;

        // Assign the thickness
        control.Margin = stackpanelThickness;

        // Add the control
        scheduleListBox.Items.Add(control);
        scheduleList.Add(control);
    }

Control xaml:
<UserControl x:Class="App_Name.scheduleControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}" Height="132" Width="359">

<Grid x:Name="LayoutRoot" Background="{StaticResource PhoneChromeBrush}">
    <TextBlock x:Name="dateTextBlock" HorizontalAlignment="Left" Margin="10,0,0,0" TextWrapping="Wrap" Text="Date" VerticalAlignment="Top" FontSize="22" Height="32" Width="152"/>
    <TextBlock x:Name="fromTextBlock" HorizontalAlignment="Left" Margin="10,47,0,0" TextWrapping="Wrap" Text="From:" VerticalAlignment="Top" FontSize="22" Height="28" Width="152"/>
    <TextBlock x:Name="toTextBlock" HorizontalAlignment="Left" Margin="10,93,0,0" TextWrapping="Wrap" Text="To:" VerticalAlignment="Top" FontSize="22" Width="152"/>
    <TextBlock x:Name="detailsTextBlock" Margin="167,0,0,0" TextWrapping="Wrap" Text="Details:" FontSize="22" HorizontalAlignment="Left" Width="192"/>

</Grid>
</UserControl>

Saving the list when done:
                // Save the scheduleList
            settings.Add(projectnameTextBox.Text.ToString() + "-scheduleList", scheduleList);
settings.Save();

I get an InvalidDataControlException, which is think is due to this since the log said something about UIElement being serialized.
Please help!:)
Answer: Save content of your controls, not the controls.
IsolatedStorageSettings.ApplicationSettings can save Lists of your own objects, but it's require additional code at your side. Here is a good example.
Comment: Hmm, okay - that'll add a little bit more work - what would be the best approach for this?
Comment: Store your controls in classes and serialize them(classes) into files. You can use [XMLserializer](http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer(v=vs.110).aspx) for this task. You can [try this code](http://stackoverflow.com/questions/5073925/problem-storing-a-list-of-objects-in-isolated-storage) if you want to save lists into IsolatedStorage. I have edited original answer, because isolatedstorage.settings can save lists of objects, but not directly.


pegar dados de uma determinada linha

Question: Tenho uma tabela. Em cada linha possui um botão. Na hota que o usuário clicar, preciso pegar todos os dados dessa linha.
É uma tabela comum, onde os dados são inseridos dinamicamente, juntamente com o botão.
Esse botão tem um evento onclick que chama uma função.
Já tentei os seguintes comandos (sem sucesso)
function test() { // tblInfracoes
    console.log($(this).closest('tr'))
}

que retorna
w.fn.init [prevObject: w.fn.init(1)]
length: 0
prevObject: w.fn.init [Window]
__proto__: Object(0)

function test() {
     var tableData = $(this).children("td").map(function() {
        return $(this).text();
    }).get();

    console.log(tableData);
}

que retorna um vetor vazio

HTML:

            nome
            idade
            Período de atividade
            Período de exclusão
            Opções

Função que popula a tabela: (quero que copie os dados quando clicar em edit)
function insertRow(nome, idade, periodoValido, periodoInvalido) {
   var html = `

            ${nome}
            ${idade}
            ${periodoValido}
            ${periodoInvalido}

   `;

    $("#tblInfracoes").append(html)
}

Comment: Você consegue colocar o código HTML de sua tabela? Pelo menos umas duas linhas é o suficiente.
Comment: `function test() {var trParent = $(this).parents("tr")[0]; console.log(trParent)}`
Answer: Pode fazer desta forma, excluindo a última coluna onde possui o botão. Você precisa passar na função o this do botão para poder achar a linha e suas colunas:

function test(botao) {

   var tableData = $(botao).closest("tr").find("td:not(:last-child)").map(function(){
      return $(this).text().trim();
   }).get();

   console.log(tableData);

}

         A1

         B1

         C1

         <button onClick="test(this)">pegar linha</button>

         A2

         B2

         C2

         <button onClick="test(this)">pegar linha</button>

Explicação:
$(botao) // seleciona o botão clicado
.closest("tr") // busca a linha onde está o botão clicado
.find("td:not(:last-child)") // busca na linha as colunas, menos a última

Comment: Entendi qual foi meu erro! muito obrigada! agora consegui corrigir aqui.

pegar dados de uma determinada linha


Falha ao arquivar projeto Xamarin.forms

Question: Seguinte, estou terminando meu projeto e como ultimo passo estou tentando "arquivar" meu projeto android, porem ao tentar arquiva-lo ele gera o seguinte erro:
    Erro        Falha inesperada da tarefa "LinkAssemblies".
Mono.Linker.MarkException: Error processing method: 'System.Void Xamarin.Forms.Pages.BaseDataSource/<Initialize>d__22::MoveNext()' in assembly: 'Xamarin.Forms.Pages.dll' ---> Mono.Cecil.ResolutionException: Failed to resolve System.Void Xamarin.Forms.Log::Warning(System.String,System.String)
   em Mono.Linker.Steps.MarkStep.HandleUnresolvedMethod(MethodReference reference)
   em Mono.Linker.Steps.MarkStep.MarkMethod(MethodReference reference)
   em Mono.Linker.Steps.MarkStep.MarkInstruction(Instruction instruction)
   em Mono.Linker.Steps.MarkStep.MarkMethodBody(MethodBody body)
   em Mono.Linker.Steps.MarkStep.ProcessMethod(MethodDefinition method)
   em Mono.Linker.Steps.MarkStep.ProcessQueue()
   --- Fim do rastreamento de pilha de exceções internas ---
   em Mono.Linker.Steps.MarkStep.ProcessQueue()
   em Mono.Linker.Steps.MarkStep.ProcessEntireQueue()
   em Mono.Linker.Steps.MarkStep.Process()
   em Mono.Linker.Steps.MarkStep.Process(LinkContext context)
   em Mono.Linker.Pipeline.Process(LinkContext context)
   em MonoDroid.Tuner.Linker.Process(LinkerOptions options, ILogger logger, LinkContext& context)
   em Xamarin.Android.Tasks.LinkAssemblies.Execute(DirectoryAssemblyResolver res)
   em Xamarin.Android.Tasks.LinkAssemblies.Execute()
   em Microsoft.Build.BackEnd.TaskExecutionHost.Microsoft.Build.BackEnd.ITaskExecutionHost.Execute()
   em Microsoft.Build.BackEnd.TaskBuilder.<ExecuteInstantiatedTask>d__26.MoveNext() AppRDVAUX.Android   C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\Xamarin\Android\Xamarin.Android.Common.targets   1748

Após muita procura verifiquei que esse erro esta relacionado a uma opção marcada no Android.Manifest chamada de Linker(vinculação), nela voce tem a opção de "compactar" seu aplicativo de forma ao não ficar muito grande. Sem essa opção marcada o meu projeto gera o apk, porem fica muito grande(70mb). Então resumindo, alguem sabe como fazer para que essa opção de vinculação funcione ou se tem algum outro meio de fazer o apk gerado ficar menor? Desde já agradeço a quem puder responder.
Answer: O mecanismo do Linker não é baseado em uma compactação, mas sim em remoção de recursos não utilizados (basicamente métodos e classes) no seu aplicativo. É assim que ele reduz o tamanho do app - "capando" as bibliotecas referenciadas para manter somente o que for utilizado.
A questão é que, para isso, o linker identifica o que está ou não sendo utilizado através de uma análise estática, e algumas vezes ele pode remover métodos que estão sendo utilizados em tempo de execução (como métodoso invocados via reflexão, por exemplo).
Em uma tradução livre, a documentação da microsoft diz que

Aplicações Xamarin.Android usam o linker para reduzir o tamanho do aplicativo. O linker aplica uma análise estátiva da sua aplicação para determinar que bibliotecas, tipos e membros estão sendo de fato utilizados. Ele se comporta como um garbage collector, buscando recursivamente por bibliotecas, tipos e membro que são referenciados até determinar o escopo de utilização da biblioteca. A partir daí, tudo foroa desse escopo é descartado.

Confesso que usar o Linker total não é uma tarefa trivial quando já se tem um projeto construido: é um processo lento identificar e corrigir as remoções indevidas. Esse assunto, inclusive, está sendo ministrado como um tópico avançado na Maratona Xamarin que está em curso.
Em geral, o pessoal indica usar o a opção intermédiaria (passar o Linker nas bibliotecas do SDK somente) e desde o início do projeto, pois assim fica mais fácil identificar caso algo que não devia tenha diso removido . Isso já dá uma boa reduzida no tamanho do app.
Como aplicar o linker no projeto
Você pode começar entendendo o comportamento do Linker, usando a opção "Bibliotecas do SDK" inicialmente e ir fazendo as configurações dos elementos que são utilizados em tempo de execução após identificá-los um a um.
A configuração para isso resume-se a três opções:
1. A estratégia LinkerPleaseInclude ou FalseFlag
Consiste em fazer uma referência para os membros e/ou classes que foram descartados.
Um exemplo da própria documentação da microsoft:

[Activity (Label="Linker Example", MainLauncher=true)]
class MyActivity
{
    static bool falseflag = false;
    static MyActivity ()
    {
        if (falseflag)
            var ignore = new Example ();
    }
    // ...
}

Na prática esse código nunca será executado, mas como força uam referência para o tipo Example, esse construtor não será removido pelo Linker.
2. Atributo Preserve
Outra maneira de fazer o mesmo mostrado acima seria usar o atributo Preserve:

public class Example
{
    [Android.Runtime.Preserve]
    public Example ()
    {
        // ...
    }
}

3. Arquivo de configuração personalizado
A outra alternativa seria usar um arquivo xml com a configuração. Esse arquivo precisa ter sua ação de build definida como LinkDescription.
Eis um exemplo do arquivo da mesma fonte:

<linker>
        <assembly fullname="mscorlib">
                <type fullname="System.Environment">
                        <field name="mono_corlib_version" />
                        <method name="get_StackTrace" />
                </type>
        </assembly>
        <assembly fullname="My.Own.Assembly">
                <type fullname="Foo" preserve="fields">
                        <method name=".ctor" />
                </type>
                <type fullname="Bar">
                        <method signature="System.Void .ctor(System.String)" />
                        <field signature="System.String _blah" />
                </type>
                <namespace fullname="My.Own.Namespace" />
                <type fullname="My.Other*" />
        </assembly>
</linker>

Esta última, entretanto, exige um aprofundamento maior no estudo do formato do arquivo esperado, sintaxe, caracteres coringa e por aí vai.
E para identificar os membros, tipos e classes que foram removidas?
Essa é a parte difícil. Quando o projeto já está desenvolvido essa etapa deve consumir um tempo considerável. Para executála, você pode ativar o linker em modo debug, e ir colocando breakpoints na cadeia de execução do aplicativo e vai tratando caso a caso. Tem também a possibilidade de usar o BitDiffer, comparando uma compilação sem e uma com o linker. Assim você vai conseguir identificar todos membros, tipos e bibliotecas que foram removidos e tratar diretamente os casos.
Detalhes nesse procedimento seria mais um tutorial e eu não acredito que seria um conteúdo on aqui no SOpt. Novamente recomendo o conteúdo do Módulo 8 da Maratona Xamarin Avançada que trata desse assunto.
Finalmente...
Não dá para ajudar no seu caso específico, como você pode imaginar, pois em se tratando de Linker, cada caso é um caso. A sua solução precisa ser avaliada juntamente com a mensagem de erro do processo de linker ou de execução para irmos corrigindo.
Espero que isso ajude.
Comment: Olá Diego, obrigado por responder, eu retirei algumas bibliotecas do meu projeto que acredito terem sido as responsáveis pelo não arquivamento do meu projeto (no meu caso em especifico eram Xamarin.Theme.Base, Xamarin.Theme.Ligth, Xamarin.Theme.Dark ), ajustei o projeto e selecionei a opção de vincular "Somente Assemblies de SDK" ele conseguiu arquivar, gerou o apk e para minha surpresa o tamanho não foi reduzido em nada, continua um arquivo de tamanho gigante para um apk. Enfim, isso já problema para um outro tópico e estou pesquisando mais sobre o assunto. Agradeço novamente sua ajuda.
Comment: Oi Diego, obrigado pela ajuda, eu consegui gerar um apk com 15mb (já foi uma diferença tremenda), consegui isso refazendo todo o projeto, iniciei um projeto novo atualizei tudo, todas as bibliotecas, arquivos, importei as classes do meu projeto habilitei as opções e funcionou, não sei exatamente o que estava errado, mas funcionou. Não vou deixar de olhar o BitDiffer que você indicou, é uma ferramenta que com toda certeza vai me ajudar muito. Obrigado novamente.
Comment: @Q.Wesley se o linker não fez diferença no tamanho do apk, temos duas opções: ou alguma biblioteca que vocÊ está utilizando é muito grande ou praticamente todo o conteúdo do app está sendo preservado e o linker não está tendo efeito. [Um projeto _hello world_ simples já teria uma redução de 70 a 87%](https://docs.microsoft.com/pt-br/xamarin/android/deploy-test/linker) no tamanho do apk. Dá uma conferida no BitDiffer
Comment: Show de bola. 15 mb já torna as coisas mais fáceis. =)

Falha ao arquivar projeto Xamarin.forms


Distance calculation on variables that cannot be represented in the Euclidean space

Question: Given a variable such as number of events attended together, which is more of a multi-dimensional data how can you calculate a sort of distance between people (i.e. a similarity score)?
Context:
For simplicity, lets say there are two types of data available

Customer_id and their purchases across brands (a.k.a. Buying Patterns)
Customer_id and the events attended (a.k.a. Socializing Patterns), where a customer may attend multiple events

The idea is to process the data and get a weighted (Based on business priorities) average similarity score that can identify customers who are similar to each other.

Buying Patterns: Here because it is continuous data that can be rolled up at customer_id level we can simply take a distance measure.
Socializing Patterns: If we roll up the data to a customer_id level with the number of events attended we lose information about which customer attended the same event as the other. This is valuable info lost as they might have met each other, may have mutual friends attending the event or simply means that they have similar tastes.

I was thinking of simply taking the number of events attended together itself as a distance between them after reversing the values (i.e. Maximum value - value), assuming that people who have attended more number of events together are similar to each other.
Is there a better approach to this? A better way to handle a variable that is more of a network variable (if that is the right word)
Note: there are 100s of events, and when I mean the distance cannot be represented in the Euclidean space I mean you cannot simply calculate the distance on the events data.
For example given an input with customer_id, event_id how can you measure the similarities between customers? You can't simply count the number of events attended and then calculate the distance because of the problem I've mentioned above.
One idea is to try out Gower's measure but I'm still trying to understand what that does exactly.
Comment: How about an indicator variable for each event? Customers get a 1 on the variable if they attended the event, a 0 if they did not. You can then use a mixed similarty measure (since you will have both continuous and binary variables) like Gower.
Comment: You mean a 1/0 flag for each and every event right?. Well that's an idea, but to be honest with 100s of events I'm not a big fan of that
Comment: Can you just _show_ how your data look like? What do you mean by "roll up"? Do you want a (dis)similarity measure on both your types of data at once or only on events data? What are "similar" individuals for you in your case, intuitively?
Comment: ...and why do you think the variables cannot be represented in Euclidean space? Just your question is not enough clear, I think.
Comment: When I say rolled up I mean aggregated. For example data at customer, date item level can be aggregated to the customer level by summing up all the items bought. I actually want it on both types of data, but lets say I just want it for the events data. In my case intuitively people who have attended the same event are similar because they have similar preferences.
Comment: So, your event data are just binary variables? n respondents by p events with 1=attended, 0=not attended?
Comment: Yes, its like that for events
Comment: or was the event data binary _prior_ date aggregation (that is, a respondent could attend the same type of event several times)?
Comment: Gower could be one of ways to go (find threads on Gower on this site, to read). If all variables are of binary type it is essentially Jaccard.
Answer: I assume you store your customers in any form similar to this:

(customer_1, {event_1, event_5, event_7, event_8}) (customer_2,
  {event_2, event_3, event_5, event_8, event_13})
  ...

Then you can measure how similar a given pair of customers are to each other, by measuring a similarity score for the respective sets of attended events.
Measuring similarity of sets with a notion of overlap can be done with Jaccard coefficient or Dice coefficient (among others). These are related, and can be derived from each other. You should check which one works best for your data, empirically.
Let A, B be the sets of events attended by customer 1, and customer 2, respectively.
Jaccard measures the number of commonly attended events, normalized by the number of events attended by either person:
$$
J(A,B) = {{|A \cap B|}\over{|A \cup B|}} = {{|A \cap B|}\over{|A| + |B| - |A \cap B|}}
$$
Dice measures the number of commonly attended events (times 2), normalized by the number of events attended by either person with repetition:
$$
D(A,B) =  \frac{2 |A \cap B|}{|A|+ |B|}
$$
In the above example, the coefficients are: $J(A,B)=2/7$ and $D(A,B)=4/9$
Implementations are widely available (e.g., scikitlearn, Java Apache commons for Jaccard), but can also be done very easily on your own for any general programming language.
Comment: What do mean saying Jaccard and Dice are "related and can be derived from each other"? So, knowing value of one you could get the value of the other without knowing their formula terms? This will make either one of the two theoretically redundant. Actually, that is not so, and both are usable. Dice coef. is most often applied for binary data representing nominal attributes https://stats.stackexchange.com/a/61910/3277
Comment: Yes, knowing one will give you the other, as explained here: [link](https://en.wikipedia.org/wiki/S%C3%B8rensen%E2%80%93Dice_coefficient#Difference_from_Jaccard). In that sense, they are redundant. However, dependent on how you use them downstream, one might be favourable over the other. To the binarization of nominal attributes: Would that same mapping to dummy binary variables (mentioned in your link) be possible, if you want to apply Jaccard afterwards?
Comment: Oops, you are completely right. I've entirely forgotten about that they are curvilinearly related (I myself had an answer observing the [relationships of some binary measures with Dice](https://stats.stackexchange.com/a/55802/3277)). So, I take my comment remark back. +1 for your answer.
Comment: Thank you for the answer I learnt quite a bit from these two answers. But in the end I guess I will go for a Gowers measure as there are a few continuous variables as well.
Comment: Can you also elaborate on what you should look for in your data to choose one method over the other
Answer: I would suggest using the sample Mahalanobis distance for the vectors of indicator variables for the events.  Suppose that you have $n$ customers and $m$ social events, so that you can represent event attendance in an $n \times m$ matrix:
$$\mathbf{M} = \begin{bmatrix}
\boldsymbol{m}_1^\text{T} \\
\boldsymbol{m}_2^\text{T} \\
\vdots \\
\boldsymbol{m}_n^\text{T}
\end{bmatrix} = \begin{bmatrix}
m_{1,1} & m_{1,2} & \cdots & m_{1,m} \\
m_{2,1} & m_{2,2} & \cdots & m_{2,m} \\
\vdots & \vdots & \ddots & \vdots \\
m_{n,1} & m_{n,2} & \cdots & m_{n,m} \\
\end{bmatrix}.$$
The elements of this matrix would be indicator variables, but this is not actually necessary for the proceeding calculation of the distances.  The matrix of squared Mahalanobis distances between the customeres is an $n \times n$ matrix given by:
$$\mathbf{D}^2 = \frac{\mathbf{c} \mathbf{M} (\mathbf{M}^\text{T} \mathbf{c} \mathbf{M})^{-1} \mathbf{M}^\text{T} \mathbf{c}}{n-1} \quad \quad \quad \mathbf{c} = \mathbf{I}_n - \tfrac{1}{n} \mathbf{1}_{n \times n}.$$
(Note that the matrix $\mathbf{c}$ is the centering matrix.)  The square roots of the values in this matrix give the distances between the customers in terms of their event attendance.
Implementation in R: The above squared-distance matrix $\mathbf{D}^2$ can be calculated in R using the mahalanobis function in the stats package.  This is done as follows (this code assumes that you have already entered the data as an $n \times m$ matrix of indicators assigned as M):
library(stats);
D2 <- mahalanobis(M, colMeans(M), cov(M));

Comment: Why are you suggesting Mahalanobis distance (and not, for example, euclidean or Manhattan)? In particular, what are resons to compute it on binary variables?
Comment: Thanks for the reply, so effectively what you are saying is that factors should be created (aka dummy code the variables) based on which the distance can be calculated but isn't that a problem for high dimentionality (~4k customers and ~1k events). The distance calculation might not have much meaning in such a case as far as I have read https://stats.stackexchange.com/a/122118/164939
Comment: Not sure if that level of computation will present a problem.  I would think it that would still be within the scope of what could be computed, so I wouldn't anticipate a problem.  There is no reason it would not be meaningful - customers with more events in common will have closer distance than those with less, taking account of the number they attended.


Which modules should be listed as dependency of my module?

Question: If my module calls a function of another module, that other module should be listed as a dependency of my module.
Now my module only provides some field handlers for the Views module. On the one hand, my module is useless without the Views module. On the other hand, my module does not call any functions or methods provided by the Views module.
Should I add Views to the list of dependencies for that module? If yes, would that change if my module provides other functionality unrelated to views (like custom pages)?
Note that I used Views only as an example. The question applies to all optional modules, that define hooks.
Answer: The Drupal.org .info file documentation does not define a dependency in itself other than stating a module cannot be enabled if a dependency is not present.
I guess you have to decide for yourself what you would consider a dependency. Personally, if a user needs to use Views in order to use your module than you would want to make sure it is installed.
If you don't want to make a module a dependency because it only supports secondary functionality in your module, you can use module_exists() to make sure your module doesn't die if the function it is calling is not there.
Answer: As I see it, you only need to list a module as a dependency if it's possible for your module to cause errors or bugs if the other module (Views in your example) is not enabled.
That said, if your module really doesn't do much without Views as you say, it seems to make sense to list it as a dependency. At this point it's mostly about user experience. You want it to be clear to users that Views is essentially required in order to use your module.
Note that there are other options in the middle also: you could use hook_enable to check whether module_exists('views') when your module is enabled, and if it's not you can use drupal_set_message() to tell the user that it's probably a good idea to install Views.
Answer: If your module implements any views API hooks, then you should declare views as a dependency.
Also, consider that at some point in the future, if you don't declare views as a dependency, there will be a user who will send you an email asking you why your module doesn't do anything. :-)


Exponent of group

Question:
Suppose that $G$ is an abelian group and that I want to prove that a certain subgroup $K$ of $G$ has limited exponent and that there exists a normal subgroup $N$ of $G$ with limited exponent. Can I suppose without loss of generality that $N=\{1\}$ and to try to prove that $K$ has limited exponent?

Remark:It is not in my hypothesis that KN/N has exponent.
Comment: This is a bit strange... there is always a normal subgroup with bounded exponent (the identity); and since $G$ is abelian, if $K$ is nontrivial and has bounded exponent then *of course* $G$ has a *nontrivial* normal subgroup that has bounded exponent: $K$ itself. I think you are trying to abstract form the situation you actually have, but the question as phrased is rather strange....
Comment: It is not in my hypothesis that KN/N has exponent.
Comment: Yes, but in assuming that $N=1$, you are passing to the quotient group. Hence, it now *suffices* to show that the image of $K$, which is $KN/N$, has finite exponent.
Comment: New question:Suppose Let be G a group (no abelian) . I want to prove that a certain subgroup K of G has limited exponent. Suppose that there exists a normal subgroup N (possibly different of K) of G with limited exponent. Can I suppose without loss of generality that N={1} to show that K has limited exponent?
Comment: Ops!Remove the word it supposes in begin of the text.
Answer: What Arturo was pointing out in his comment was that every subgroup of an abelian group is normal, so if you can prove that $K$ has bounded exponent, then you've found a non-trivial normal subgroup with bounded exponent.  You can just let $N = K$.
Answer: Yes, you can, if I am understanding your question correctly. If $N$ has exponent $n$ and $KN/N$ has exponent $m$, then for any $k\in K$, $k^m\in N$, so $k^{mn}=(k^m)^n=1$

Exponent of group


Is there a requirement for using WS2_32.dll instead of wsock32.dll when building with MSVC9.0

Question: I'm in the middle of porting some code to be compiled with MSVC 9.0, and one of my coworkers mentioned that we would need to link against WS2_32.dll because now only Winsock 2 was supported. Is there any truth to this? Our code is pretty old and heavily dependent on wsock32.dll, so this requirement could be a huge obstacle for the project.
Thanks
Answer: As long as you're not using any Winsock 2 specific features, you should be just fine linking against wsock32.dll.  The old Winsock 1.1 API is not deprecated.  Winsock 2 is an extension to Winsock 1, not a replacement for it.
Because Winsock 2 is purely an extension, a program that currently works against wsock32.dll should still work fine when relinked against ws2_32.dll.  The best reason not to do that is if you still have to support stock Windows 95 systems, since Winsock 2 is a downloadable add-on for those systems.  Winsock 2 was introduced with Windows 98 and Windows NT 4.
There are degrees to Winsock 2 support.  A program using all the newest features available under Windows 7 may not work with Windows 95 even with the Winsock 2 add-on.  Sometimes the reverse is true, too: the newer Winsock stacks have removed some raw sockets support available in Windows 2000 and XP, for instance.
Bottom line, test on all platforms you have to support.


Question on Limits from Spivak Calculus {Ch 5 Question 31}

Question: Question goes as follows:
Suppose that $\lim_{x\to {a-}}f(x)<\lim_{x\to {a+}}f(x)$. Prove that there is some $m \gt0$ such that $f(x)\lt f(y)$ whenever $x \lt a \lt y$ and $|x-a|\lt m$ and $|y-a|\lt m$. Is the converse true?
What I tried:
I could picture this situation on graph and prove it but i do not know how to prove it rigorously. Also, I don't understand how to find answer to the second question. All I did is try to think of a function which does not satisfy the converse but could not come up with one, so I concluded the converse is also true. I'm sure this method is not right for finding the answer. Can anyone please provide me the correct solution to the problem?
Answer: Denote $l = \lim\limits_{x \to a^-} f(x)$, $L = \lim\limits_{x \to a^+} f(x)$ and $k = \frac{l+L}{2}$. By hypothesis, we have $l < k < L$.
By definition of the limits, it exists $\delta^-$ such that for $x- \delta^- < x < a$ you have $f(x) < k$. And $\delta^+$ such that for $a < y < a + \delta^+$ we have $k < f(y)$. Denote $\delta = \min (\delta^-, \delta^+)$
Now for $x < a < y$, $\vert x-a \vert, \vert y -a \vert < \delta$ we have indeed $f(x)<k < f(y)$.
The converse is not true.
Obviously we'll have $l \le L$. However, we can have the equality $l = L$ for example for continuous maps at $a$.


Configuring values of combobox in a tablelist using tablelist wrapper in python

Question: Basically my problem is in configuring a combobox in a tablelist written in python (not tcl directly). I have prepared an example that could demonstrate the problem, but before that lets see the required steps to run it:

Copy the tablelist wrapper from here and save it as 'tablelist.py', then put it at the example code directory.
Download "tklib-0.5" from here and copy "tablelist" directory from "modules" directory to the directory of example code.

Here it is the code:
from tkinter import *
from tkinter import ttk
from tablelist import TableList

class Window (Frame):
    def __init__(self):
#       frame
        Frame.__init__(self)
        self.grid()
#       tablelist
        self.tableList = TableList(self,
                                    columns = (0, "Parity"),
                                    editstartcommand=self.editStartCmd
                                    )
        self.tableList.grid()
#       configure column #0
        self.tableList.columnconfigure(0, editable="yes", editwindow="ttk::combobox")
#       insert an item
        self.tableList.insert(END,('Even'))

    def editStartCmd(self, table, row, col, text):
#
#       must configure "values" option of Combobox here!
#
        return

def main():
    Window().mainloop()

if __name__ == '__main__':
    main()

As you would see it results in a single column/cell window with an initial value (Even). By clicking on the cell the combobox will appear (because of using "editstartcommand") and it doesn't have any values (None). I know for editing cell's widgets one has to use "editwinpath" command to get pathname of temporary widget, but the method just returns a string of the address referring to combobox widget that is not callable.
I'd appreciate any help or possible solutions.
Answer: I know it's a bit weird that I'm responding to my own question, but I'm hopeful that it could be useful to others in the future. After reading tablelist scripts and examples in TCL, I was able to find my answer. The answer has two different parts, one is related to the wrapper (tablelist wrapper in python that you can find it here), and the other one resides in my example code. First of all the wrapper needs to be modified to include widgets' pathnames in its "configure" method of "TableList" class. Here it is the modified version:
def configure(self, pathname, cnf={}, **kw):
    """Queries or modifies the configuration options of the
    widget.

    If no option is specified, the command returns a list
    describing all of the available options for def (see
    Tk_ConfigureInfo for information on the format of this list).
    If option is specified with no value, then the command
    returns a list describing the one named option (this list
    will be identical to the corresponding sublist of the value
    returned if no option is specified).  If one or more
    option-value pairs are specified, then the command modifies
    the given widget option(s) to have the given value(s); in
    this case the return value is an empty string.  option may
    have any of the values accepted by the tablelist::tablelist
    command.
    """
    return self.tk.call((pathname, "configure") +
                 self._options(cnf, kw))

Second and last part is the obligation that the "editstartcommand" (in case of my example code "editStartCmd" method) has to return its "text" variable at the end of it. This trick would prevent entries from turning to "None" as you click on them. The correct form of example code is:
from tkinter import *
from tkinter import ttk
from tablelist import TableList

class Window (Frame):
    def __init__(self):
#       frame
        Frame.__init__(self)
        self.grid()
#       tablelist
        self.tableList = TableList(self,
                                    columns = (0, "Parity"),
                                    editstartcommand=self.editStartCmd
                                    )
        self.tableList.grid()
#       configure column #0
        self.tableList.columnconfigure(0, editable="yes", editwindow="ttk::combobox")
#       insert an item
        self.tableList.insert(END,('Even'))

    def editStartCmd(self, table, row, col, text):
#
#       must configure "values" option of Combobox here!
#
        pathname = self.tableList.editwinpath()
        self.tableList.configure(pathname, values=('Even','Odd'))
        return text

def main():
    Window().mainloop()

if __name__ == '__main__':
    main()

That's it and I hope it was clear enough.


Clarification in non-homogeneous linear system in matrix

Question: The following augmented matrix is in row echelon form and belongs to some
non-homogeneous linear system:
\begin{bmatrix}a&b&c&|d\\0&e&f&|g\\0&0&h&|i\end{bmatrix}
(The entries a, e, h need not be leading entries of the row echelon form.)
Given that the matrix above is a non-homogenoeus system, am I right in assuming that d,g,i≠0? or as long as either one d,g,i is non zero, then the matrix is considered non-homogeneous system?
Answer: The second statement is correct: if at least one of $d,g,i$ is non-zero, then the associated system of linear equations is a non-homogeneous system.


R Shiny: Create a button that updates a data.frame

Question: I have a randomly generated data.frame. The user can modify a slider to choose the number of points. Then I plot this data.frame.
I want to add a button than when clicked, it performs a modification in the previous randomly generated data.frame (but without regenerating the data.frame). The modification is a voronoid relaxation, and it should be performed once per each time the button is clicked and the graph generated.
Until now, I have not achieved anything similar...
ui.R
library(shiny)

# Define UI for application that draws a histogram
shinyUI(fluidPage(

  # Application title
  titlePanel("Map Generator:"),

  # Sidebar with a slider input for the number of bins
  sidebarLayout(
    sidebarPanel(
      p("Select the power p to generate 2^p points."),
      sliderInput("NumPoints",
                  "Number of points:",
                  min = 1,
                  max = 10,
                  value = 9),
      actionButton("GenPoints", "Generate"),
      actionButton("LloydAlg", "Relaxe")
    ),

    # Show a plot of the generated distribution
    mainPanel(

      plotOutput("distPlot",height = 700, width = "auto")
    )
  )
))

server.R
library(shiny)
library(deldir)

shinyServer(function(input, output) {

  observeEvent(input$NumPoints,{

    x = data.frame(X = runif(2^input$NumPoints,1,1E6),
                   Y = runif(2^input$NumPoints,1,1E6))

    observeEvent(input$LloydAlg, {
        x = tile.centroids(tile.list(deldir(x)))
    })

    output$distPlot <- renderPlot({
        plot(x,pch = 20,asp=1,xlim=c(0,1E6),ylim = c(0,1E6))
  })

  })
})

Of course there is something that I must be doing wrong, but I am quite new into shiny I can't figure it out what I am doing wrong...
Answer: This should work (even though I am pretty sure this could be improved):
shinyServer(function(input, output) {
  library(deldir)

  data = data.frame(
    X = runif(2^9, 1, 1E6),
    Y = runif(2^9, 1, 1E6)
  )

  rv <- reactiveValues(x = data)

  observeEvent(input$GenPoints, {
    rv$x <- data.frame(
      X = runif(2^input$NumPoints,1,1E6),
      Y = runif(2^input$NumPoints,1,1E6)
    )
  })
  observeEvent(input$LloydAlg, {
    rv$x = tile.centroids(tile.list(deldir(rv$x)))
  })

  output$distPlot <- renderPlot({
    plot(rv$x,pch = 20,asp=1,xlim=c(0,1E6),ylim = c(0,1E6))
  })
})

So first I initialize the points to plot. I use runif(2^9, 1, 1E6) because the starting value of the sliderInput is 9 all the time.
I also removed the observeEvent from the sliderInput and moved it to the GenPoints actionButton.


Using WM_Close in c#

Question: I am using the below code to close the window, by searching the window name in taskbar.
But i one case, my window will not appear in the taskbar. In that case, WM_Close could not close the window. Whats the other way to do it using WM_Close ???
    void DaemonTerminamtionHook_KeyPressed(object sender, KeyPressedEventArgs e)
    {
        DaemonResult = MessageBox.Show("Are you sure, you want to Terminate Daemon?", "Terminate Daemon", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation);

        if (DaemonResult == DialogResult.Yes)
        {
            //Free the resources of ShellBasics and terminate Daemon here.
            IntPtr hWnd = FindWindowByCaption(IntPtr.Zero, "DAEMON TAB BAR");
            bool ret = CloseWindow(hWnd);
        }
    }

    //WM_Close
    [DllImport("user32.dll", EntryPoint = "FindWindow", SetLastError = true)]
    static extern IntPtr FindWindowByCaption(IntPtr ZeroOnly, string lpWindowName);

    [DllImport("user32.dll", CharSet = CharSet.Auto)]
    static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);

    static uint WM_CLOSE = 0x10;

    static bool CloseWindow(IntPtr hWnd)
    {
        SendMessage(hWnd, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
        return true;
    }

Now using the below code...But getting error in
"IntPtr hWnd = PostMessage(IntPtr.Zero, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);"
where to provide the window name in order to close that ???

 void DaemonTerminamtionHook_KeyPressed(object sender, KeyPressedEventArgs e)
    {
        DaemonResult = MessageBox.Show("Are you sure, you want to Terminate Daemon?", "Terminate Daemon", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation);

        if (DaemonResult == DialogResult.Yes)
        {

            IntPtr hWnd = PostMessage(IntPtr.Zero, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
            bool ret = CloseWindow(hWnd);
        }
    }

    static uint WM_CLOSE = 0x10;
    [return: MarshalAs(UnmanagedType.Bool)]
    [DllImport("user32.dll", SetLastError = true)]
    static extern bool PostMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);

    static bool CloseWindow(IntPtr hWnd)
    {
        bool returnValue = PostMessage(hWnd, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
        if (!returnValue)
            throw new Win32Exception(Marshal.GetLastWin32Error());
        return true;
    }

Answer: Edit: Sorry misread your question.
Use FindWindow/FindWindowEx instead.
Comment: @Preet, Thanks for your support. Can u tell me how to pass the parameter for :

 void PostMessageSafe( HandleRef hWnd, uint msg, IntPtr wParam, IntPtr lParam )
Comment: @Preet, where to pass the window name here ?
Comment: @Preet, please refer to the updated code on top, it is giving some errors as the paramerters does not match and please tell me where to provide the windows name inorder to close it.
Comment: I suggest reading http://msdn.microsoft.com/en-us/library/ms633499(VS.85).aspx to set up your window with a classname so findwindow can find it. Or use SPY++ to find this value in dev

Using WM_Close in c#


Join pmf of 2 dependent random variables

Question:
Let $X_1$, $X_2$, $X_3$ be independent Binomial($3, p$) random variables.
Let $Y_1 = X_1 + X_3$, $Y_2 = X_2 + X_3$
Let $Z_1 =
\begin{cases}
 1 & \text{if $ Y_1 = 0$} \\
 0 & \text{Otherwise}
 \end{cases}
$
$Z_2 =
\begin{cases}
 1 & \text{if $ Y_2 = 0$} \\
 0 & \text{Otherwise}
 \end{cases}
$

I'm trying to find the joint pmf of $(Z_1, Z_2)$
$Y_1$ and $Y_2$ are Binimoial($6, p$) as the X's are independent
The probabilities of $Y_1 = 0$, $Y_2 = 0$ are $(1-p)^6$ I believe.
The issue is $Y_1$ and $Y_2$ are not independent as they both contain $X_3$, meaning I don't think I can just multiply the pmf of $Z_1$ with the pmf of $Z_2$. How would I find the joint pmf in this case?
Answer: Hint:
Observe that: $$Y_1=Y_2=0\iff X_1=X_2=X_3=0$$

addendum:
Let $q:=1-p$.
$\{Z_1=1,Z_2=1\}=\{X_1+X_2+X_3=0\}$ so that:$$P(Z_1=1,Z_2=1)=P(X_1+X_2+X_3=0)=q^9$$
$\{Z_1=1,Z_2=0\}=\{Y_1>0,Y_2=0\}=\{X_1>0,X_2+X_3=0\}$ so that:$$P(Z_1=1,Z_2=0)=P(X_1>0,X_2+X_3=0)=P(X_1>0)P(X_2+X_3=0)=$$$$\left(1-P(X_1=0)\right)P(X_2+X_3=0)=(1-q^3)q^6$$
Similarly we find $P(Z_1=1,Z_2=0)=(1-q^3)q^6$.
We find $P(Z_1=0,Z_2=0)$ on base of:$$P(Z_1=0,Z_2=0)=1-P(Z_1=1,Z_2=0)-P(Z_1=0,Z_2=1)-P(Z_1=1,Z_2=1)$$
Observe that we do not have $P(Z_1=1,Z_2=1)=P(Z_1=1)P(Z_2=1)$ so $Z_1,Z_2$ are not independent.
Comment: $Z_1$ and $Z_2$ are *not* independent. Right now I have not the opportunity to explain further. I will do that later.
Comment: Just to make sure I have understood this correct, I can assume that $Z_1$ and $Z_2$ are independent and so the joint pmf is just $P(Z_1, Z_2) = P(Z_1)*P(Z_2) =  ((1-p)^6)^{Z_1 +Z_2} (1-(1-p)^6)^{2-Z_1-Z_2}$, correct?
Comment: Alright, thanks
Comment: I thought they were because $X_1 = X_2 = X_3$ are $0$ when $Y_1 = Y_2 = 0$ and when they are $0$, they are independent?
Comment: I have added something.
Comment: That makes a lot of sense, thank you.


Facebook SDK 3.1 for iOS login issues

Question: I have used Facebook sdk 3.1 in my ios  app for sharing link on friends wall. I try to open a new session in the applicationDidFinishLaunching method as below
<code>- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

myAppDelegate = self;

AudioViewController *viewController = [[AudioViewController alloc] init];
self.navController = [[UINavigationController alloc] initWithRootViewController:viewController];
[self.navController setNavigationBarHidden:YES];
viewController = nil;

self.window.rootViewController = self.navController;
[self.window makeKeyAndVisible];

if (![self openSessionWithAllowLoginUI:NO]) {
    // No? Display the login page.
    [self performSelector:@selector(login) withObject:nil afterDelay:0.5];
}

return YES;
}

- (void)login{
[self openSessionWithAllowLoginUI:YES];
}

- (BOOL)openSessionWithAllowLoginUI:(BOOL)allowLoginUI {
return [FBSession openActiveSessionWithReadPermissions:nil
                                          allowLoginUI:allowLoginUI
                                     completionHandler:^(FBSession *session, FBSessionState state, NSError *error) {
                                         [self sessionStateChanged:session state:state error:error];
                                     }];
}

- (void)sessionStateChanged:(FBSession *)session
                  state:(FBSessionState)state
                  error:(NSError *)error{

switch (state) {
    case FBSessionStateOpen: {
        DLOG(@"session open");
    }
        break;
    case FBSessionStateClosed: {

        DLOG(@"session closed");

        [FBSession.activeSession closeAndClearTokenInformation];

    }
        break;
    case FBSessionStateClosedLoginFailed: {

         DLOG(@"session Failed");

    }
        break;
    default:
        break;
}

[[NSNotificationCenter defaultCenter] postNotificationName:WVSessionStateChangedNotification
                                                    object:session];

if (error) {
    DLOG(@"error = %@",error);
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:@"Error: %@",
                                                                 [AppDelegate FBErrorCodeDescription:error.code]]
                                                        message:error.localizedDescription
                                                       delegate:nil
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
    [alertView show];
}
}
</code>
With some of the Facebook accounts it returns error "The operation could not be completed" com.facebook.sdk error 2. and so further cannot post on Facebook.
Am I doing something wrong here ?Any help would be appreciated.!
Comment: Do you get this error during the login?
Comment: did u add facebook methods in view where you are login to facebook
Comment: Off-topic, but posting to friends' walls via the API is deprecated and will be unavailable after February 6th, 2013.
Answer: I had same issue, and i have solved it by calling openSessionWithAllowLoginUI:TRUE via NSTimer.
<code>if (![self openSessionWithAllowLoginUI:NO]) {
    // No? Display the login page.
    [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(login) userInfo:nil repeats:NO];
}
</code>
The reason is, we can't get FB session on different threads, either we use main thread or another(background) thread. In your code, when you check session availability, you use main thread and for login, you use different thread via performSelector function.
Hope, it will help you.
thanks

Facebook SDK 3.1 for iOS login issues


Unable to shadow Windows 10 VDI session from 2012 R2 Virtualisation Host

Question: I have deployed a test VDI setup on 2012 R2 remote desktop services, and when I attempt to shadow a session on one of our Windows 10 virtual desktops, I get a message that says;
"The computer name is invalid"
I found this article, but even after enabling network discovery, the same error persisted when attempting to shadow the session.
Is there anything else I need to do to get this working?
Comment: how are you shadowing the session? GUI tool or commandline and are you using FQDN, short name, or IP
Comment: Through server manager GUI
Answer:
I would check DNS to make sure its working correctly
try to shadow via commandline and use the IP address
<code>Mstsc.exe [/shadow:sessionID [/v:Servername] [/u:[Username]] [/control] [/noConsentPrompt]]
</code>
/shadow:ID Starts shadow with the specified sessionID.
/v:servername If not specified, will use the current server as the default.
/u:username If not specified, the currently logged on user is used.
/control If not specified, will only view the session.
/noConsentPrompt Attempts to shadow without prompting the shadowee to grant permission.
check your GPO settings

[Computer Configuration | User Configuration]\Administrative Templates\Windows Components\Remote Desktop Services\Remote Desktop Session Host\Connections\Set rules for remote control of Remote Desktop Services user sessions

make sure your an admin of that VDI desktop
make sure your VDI is talking to the domain correcly

More infomation can be found at https://blogs.technet.microsoft.com/askperf/2013/10/22/windows-8-1-windows-server-2012-r2-rds-shadowing-is-back/
Update:
This ps1 might help until the GUI is working correctly
<code>$selected = Get-RDUserSession | Select-Object -Property Username,HostServer,UnifiedSessionID |Out-GridView -PassThru
mstsc /shadow: $selected.UnifiedSessionId /control /v: $selected.HostServer
</code>
Comment: DNS is fine, and I can ping that Virtual Desktop from the server I am trying to connect from. Trying via the command line I get a message that states "The specified session is not connected". After I log into the Virtual Desktop, in task manager my session is RDP-Tcp#0, so I am using session 0, and the computer name of the virtual desktop. We don't specify any of those settings via GPO, and shadowing on our session hosts is working fine. I am a domain admin, so will be an admin on the virtual desktop. Domain connectivity seems fine too.
Comment: For complete clarity, the command I am running is:  mstsc /shadow:0 /v:FLX-VDI-2 /control
Comment: Ok so as it turns out the session is not 0, it is 2. I had to run the query session command at the command line to determine the session ID. Now, when I do it via the CLI, it works correctly. This to me indicates an issue within server manager? Any thoughts why it works via CLI but not SM? Kind of makes life a bit awkward when trying to shadow users if we deploy this in a live environment!
Comment: @JamesEdmonds it might be some issues with server manager and shortname vs FQDN. Could also be a bug from MS
Comment: I did find it odd that when it attempts to shadow the virtual desktop, is says "Connecting to...The". Rather than giving me the computer name, it just says "The". I have created a post in the technet forum too, but seems like a pretty massive bug!
Comment: @JamesEdmonds I edited my answer to include a script I found yesterday that might help you with this issue until the GUI is working.
Comment: Silly how broken it is, as I can send a message and log off etc, just not shadow
Comment: Just tried your script my friend, but I get told a deployment doesn't exist on this server. Odd, as this server runs all the roles, Connection broker, Web access and virtualisation host :S
Comment: I would see if Get-RDUserSession will show anything run in powershell by itself on that server.
Comment: Unfortunately it does not, as complains in the same way stating there is no deployment on that server.
Comment: Works flawlessly when I redeployed on 2016 (same Windows 10 template), so I suspect this is a bug with 2012 R2.
Answer: Believe this is a bug in 2012 R2, as when I redeployed on 2016, it worked perfectly first time using the same VM template for my VDI.


Uploading images using Form Collections and Doctrine in ZF2

Question: How to upload with form collection, ZF2 and Doctrine2?
When I upload an image file, entity Image method setFileName($value) receives input array $_FILE('name'=>'image.jpg', 'tmp_name'=>....).
This is my code:
Entity Image
namespace Application\Entity;

class Image
{
    /**
     * @var int
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @var string
     * @ORM\Column(type="string")
     */
    protected $filename;

    /**
     * @ORM\ManyToOne(targetEntity="Application\Entity\Product", inversedBy="images")
     * @ORM\JoinColumn(name="product_id", referencedColumnName="id", onDelete="CASCADE")
     */
    protected $product;
...

    public function getFileName()
    {
        return $this->filename;
    }

    public function setFileName($name)
    {

        $this->filename = $name;

    }

    public function setProduct(Product $product = null)
    {
        $this->product = $product;
    }

    public function getProduct()
    {
        return $this->product;
    }

}

Entity Product
namespace Application\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection as Collection;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="product")
 */
class Product
{
    /**
     * @var int
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     *
     */
    protected $id;

    /**
     * @var string
     * @ORM\Column(type="string", length=255, unique=true, nullable=true)
     */
    protected $name;

    /**
     * @ORM\OneToMany(targetEntity="Application\Entity\Image",
                      mappedBy="product", cascade={"persist"})
     */
    protected $images;

    public function __construct()
    {
        $this->images = new ArrayCollection();
    }

    /**
     * Get id.
     *
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set id.
     *
     * @param int $id
     *
     * @return void
     */
    public function setId($id)
    {
        $this->id = (int) $id;
    }

    ....

    /**
     * Add images
     *
     * @param Collection $image
     */
    public function addImages($images)
    {
        foreach ($images as $image)
        {
            $tag->setProduct($this);
            $this->images->add($image);
        }
    }

    /**
     * Remove images
     *
     * @param \Application\Entity\Image $images
     */
    public function removeImages($images)
    {
        foreach ($images as $image)
        {
            $tag->setProduct(null);
            $this->images->removeElement($image);
        }
    }

    /**
     * Get images
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getImages()
    {
        return $this->images;
    }

}

Fieldset Image
class ImageFieldset extends Fieldset implements InputFilterProviderInterface
{

    public function __construct(ObjectManager $objectManager)
    {
        parent::__construct('product-image');

        $this->setHydrator(new DoctrineHydrator($objectManager,
                                                'Application\Entity\Image'))
             ->setObject(new Image());

        $this->add(array(
                    'name' => 'filename',
                    'type' => 'Zend\Form\Element\File',
                    'options' => array(
                        'label' => 'Photo Upload',
                        'label_attributes' => array(
                            'class' => 'form-label'
                        ),
                        'multiple' => true,
                        'id' => 'filename'
                    )
                )
        );

    }

Form Product
class ProductForm extends Form
{

    public function __construct(ObjectManager $objectManager, $name)
    {
        parent::__construct($name);

        $this->setAttribute('enctype', 'multipart/form-data');
        $this->setAttribute('method', 'post')
                ->setHydrator(new DoctrineHydrator($objectManager,
                                                  'Application\Entity\Product'));

        $imageFieldset = new ImageFieldset($objectManager);
        $imageFieldset->setName("images");
        $this->add(array(
            'type' => 'Zend\Form\Element\Collection',
            'name' => 'images',
            'options' => array(
                'allow_add' => true,
                'allow_remove' => false,
                'count' => 1,
                'target_element' => $imageFieldset
            )
        ));

      $this->setValidationGroup(array(
            'name',
            'images',
            ...
        ));
}

Product Controller
class ProductController extends AbstractActionController
{
    public function addAction()
    {
       $em = $this->getEntityManager();
       $request = $this->getRequest();

       $form = new ProductForm($em, 'product');
       $product = new Product();

       $form->bind($product);

       if ($request->isPost()):
          $dataForm = array_merge_recursive(
                $request->getPost()->toArray(),
                $request->getFiles()->toArray()
            );
          $form->setData($dataForm);
          if ($form->isValid()):
              $em->persist($product);
              $em->flush();
          endif;
       endif;
    }
}

The closest thing I've found has been in Symfony2:
Uploading images using Form Collections and Doctrine in Symfony2
Comment: Hello! What is the problem and did you try to write some code?
Answer: Usually I do something like that:
public function setFileName($filename)
{
    if (is_array($filename) && isset($filename['tmp_name'])) {
        $filename = $filename['tmp_name'];
    }

    $this->fileName = $filename;
}

Comment: That's the solution I had thought, is not there another way?
Comment: @Alex Savchenko, it works, thanks! But maybe you found some other solution?