Help with arguing against symmetry proofs.

Question: I am asking for the help of mathematicians here to show my colleague that her arguments are wrong. I tried my best to explain that inequalities and equations can be solved like that, but maybe my arguments were not good enough.
Some of the examples of her solutions:
Example 1. Over the real numbers, if $x+y=2$, what is the maximum value of $xy$?
Solution: By symmetry, there must be a maximum or minimum when $x=y$ so $x=y=1$ and $xy=1$. This is clearly a maximum, since if say $x=0$ and $y=2$, you get a lower value.
Example 2. Let $x, y$ and $z$ be positive real numbers such that $x + y + z = 1$. Prove that $\frac{1}{x^2}+\frac{1}{y^2}+\frac{1}{z^2} \geq 27$.
Solution: By symmetry, there is a minimum at x=y=z hance all = 1/3 and the expression equals 27.
Example 3. For positive numbers $a,b,c$ prove that $\sqrt{\frac{a}{a+b}}+\sqrt{\frac{b}{b+c}}+\sqrt{\frac{c}{c+a}} \leq \frac{3\sqrt{2}}{2}$?
Solution: Another of those symmetry arguments.  The LHS is a maximum for $a=b=c$ and then equals the RHS.

It is very clear, that these are not even close to be called solutions. When I (or my other collegaues) try to explain that it not that simple to show that extreme points will be at $x=y=z$ we get answers like

It's a symmetry thing.  If you imagine that say $a$ tends to 0 or infinity you see that the LHS is going to decrease.

have repeatedly said that symmetry arguments do not always work.  However, it must be obvious to any bright 18 year old that the argument does work in this particular case.

Much to my amazement, many people in this group do not understand how to solve problems using symmetry. In England, this is taught in schools.

I am not sure what will help us to explain that it does not work like that. If we will get many reponces here, I believe it will help to convince my colleagues. Also, if you are from UK or have degree from prestigous college it will be helpfull to mention that.
Comment: It suffices to find a counterexample, doesn't it?
Comment: Instead of arguing with your collegue, you might together investigate *under what conditions* the symmetry argument works or fails.
Comment: @Servaes that makes sense, but I think the goal is not to show that it is it wrong in general, since she says: "have repeatedly said that symmetry arguments do not always work". I think the goal is to show that it is not that easy as "use symmetry then everything solved"
Comment: Some people use killer arguments like "it must be obvious to any bright 18 year old" or "in England, this is taught in schools" or even "as every pre-school child knows". Don't worry, the only intention is to make you feel like a fool because you are not able to understand such a "really obvious" thing. And if it should not work always, then at least in this particular case ... only you simpleton cannot to see that.
Comment: But taken seriously, the point is that symmetry arguments are in fact often useful, but you cannot a priori be sure that symmetric solutions are optimal in the given situation. If somebody can see that at first glance, he must have a lot of experience or says it ex post (after he has verified it the quite chamber).
Answer: The issue is that your colleague seems to be confusing a useful heuristic with a proof.   If the principle of why something 'must be true' by symmetry cannot be articulated and only applied ex post, then that's a red flag that it's not a proof.  One approach is to suppose your colleague is right in 2 simple separate cases, then combine them (via multiplication in this case) and show that the 'principle' breaks.
A better way to view 'symmetry arguments' when looking at inequalities involving symmetric functions like example 1, is through majorization.  The deeper reason example 1 holds is that $x_1\cdot x_2$ is symmetric and in fact a Schur concave function and the constraint $x_1+x_2=2$  ensures that $\mathbf x =\mathbf 1$ is majorized by any other candidate.  By Schur concavity this is a maximum.
Alternatively consider $\mathbf x \in \mathbb R^2_{\geq 0}$ and $\mathbf x\mapsto x_1^4 + x_2^4$ with the constraint $x_1+x_2=2$.  This is symmetric and in fact a Schur convex function.  The candidate $\mathbf x =\mathbf 1$ is a minimum since it is majorized by all other allowed choices of $\mathbf x$ and Schur convexity ensures that is a minimum.
Finally consider consider $\mathbf x \in \mathbb R^2_{\geq 0}$ and $\mathbf x\mapsto  (x_1\cdot x_2)\cdot(x_1^4 + x_2^4)$ with the constraint $x_1+x_2=2$.   This is a symmetric function but neither (Schur) concave nor convex. Being majorized by all choices of $\mathbf x$ (what your colleague calls the symmetric solution) doesn't tell you anything definitive.  Hence applying a heuristic like "It's a symmetry thing. If you imagine that say  tends to 0 or infinity you see that the LHS is going to decrease" misleads you despite the fact that this is a symmetric function.  And $\mathbf x =\mathbf 1$ is neither a maximum or a minimum, as $0$ is a clear minimum e.g. as $x_1\to 0$ but e.g. $x_1=1.5, x_2=0.5$ is much larger than the constant solution.
conclusion: your colleague's heuristic is true when dealing with symmetric functions that are Schur convex (concave). But not all functions are Shur convex (concave); understanding this is vital.  The theory of majorization is a well developed mathematical theory quite distinct from declaring things are obvious.
Answer: Example 1 does not seem so bad at first sight. It is true that by symmetry (and smoothness of the functions) $x=y$ is a stationary point, hence it probably forms a local maximum or minimum.
Anyway, exhibiting a lower point is not enough to prove that we have a global maximum.
If we absorb the constraint with $x=1-t,y=1+t$, we only have to maximize $1-t^2$ and it turns out that the unique stationary point is a maximum, which favors your colleague.
Now, on the opposite, the function $t^2-t^4$, corresponding to the maximization of
$$(4xy+1)(x^2+y^2)-x^4-y^4-6x^2y^2-2xy$$ under $x+y=2$, induces an asymmetric solution.


ASP.net MVC with Ajax

Question: Does anybody know of an up to date tutorial on using Ajax with ASP.net MVC?  Most of what I can find seems to talk about older versions of MVC and I suspect that this is an area where there has been a lot of change of late.
Answer: Stephen Walter just blogged about this:
http://weblogs.asp.net/stephenwalther/archive/2008/09/22/asp-net-mvc-application-building-forums-6-ajax.aspx
Answer: Stephen Walter's post "ASP.NET MVC Application Building: Forums #6 – Ajax" seems to be focused on Microsoft ASP.NET AJAX.
A quick search on google for "ASP.NET MVC jquery" brings up several resources on non-MS javascript.
I lean towards the non-MS AJAX demos & tutorials as they show platform-agnostic patterns and practices.
Comment: ASP.NET AJAX libraries are platform agnostic... they are just javascript.
Comment: just javascript, true, but with a .NET flavor of syntax and structure to their API.  One of the stated goals of ASP.NET AJAX is to provide .NET developers with familiar method signatures and behavior, where reasonable, to ease their transition to client-side development.
Answer: If you're looking for form-releated Ajax support in MVC, check out Scott Hanselman's post:
http://www.hanselman.com/blog/ASPNETMVCPreview4UsingAjaxAndAjaxForm.aspx
It seems there isn't currently good support for end-to-end validation with Ajax forms. Most articles I've read use a combination of a client-side library and server-side data annotations. I'm hoping the full beta release of MVC will include better support.
Also, be sure to note that Microsoft will be including jQuery as an officially supported library for Ajax development. Scott Guthrie annoinced this at:
http://weblogs.asp.net/scottgu/archive/2008/09/28/jquery-and-microsoft.aspx

ASP.net MVC with Ajax


Unexpected token, expected "}" Error while passing object from FetchMovie to MovieList component at line 7 of MovieList.js

Question: This is MovieList.js and I passed a react object as prop to this component from FetchMovie.js which I gave below. I tried but it's still there . Pls help
MovieList.js
import React from "react";
function MovieList(props) {
  console.log(props.newFilm)
  return (

{props.newFilm.film_name}

      //line 7

  );
}

export default MovieList

FetchMovie.js
This is the FetchMovie.js file and through this component I passed users object as a prop to MovieList.js and that error occured. Pls help.
I have given the users object below the FetchMOvies.js.
import React, { useState } from "react";
import MovieList from "./MovieList";
import users from "./MovieView";
let s = users.films;
function FetchMovies() {
  return (

      {s.map((film) => (
        <MovieList key={film.film_id} newFilm={film} />
      ))}

  );
}

export default FetchMovies;

This is the users object:
users={
  films: [
    {
      film_id: 258136,
      imdb_id: 2119543,
      imdb_title_id: "tt2119543",
      film_name: "The House With A Clock In Its Walls",
      other_titles: {
        EN: "The House With A Clock In Its Walls"
      },
      release_dates: [
        {
          release_date: "2018-09-21",
          notes: "GBR"
        }
      ],
      age_rating: [
        {
          rating: "12A ",
          age_rating_image:
            "https://d2z9fe5yu2p0av.cloudfront.net/age_rating_logos/uk/12a.png",
          age_advisory: "moderate threat, scary scenes"
        }
      ],
      film_trailer: "https://dzm1iom8kpoas.cloudfront.net/258136_uk_high.mp4",
      synopsis_long:
        "In the tradition of Amblin classics where fantastical events occur in the most unexpected places, Jack Black and two-time Academy Award® winner Cate Blanchett star in THE HOUSE WITH A CLOCK IN ITS WALLS, from Amblin Entertainment.  The magical adventure tells the spine-tingling tale of 10-year-old Lewis (Owen Vaccaro) who goes to live with his uncle in a creaky old house with a mysterious tick-tocking heart.  But his new town's sleepy façade jolts to life with a secret world of warlocks and witches when Lewis accidentally awakens the dead.",
      images: {
        poster: {
          "1": {
            image_orientation: "portrait",
            region: "US",
            medium: {
              film_image:
                "https://d3ltpb4h29tx4j.cloudfront.net/258136/258136h1.jpg",
              width: 200,
              height: 300
            }
          }
        },
        still: {
          "2": {
            image_orientation: "landscape",
            medium: {
              film_image:
                "https://d3ltpb4h29tx4j.cloudfront.net/258136/258136h2.jpg",
              width: 300,
              height: 199
            }
          }
        }
      }
    }
  ],
  status: {
    count: 1,
    state: "OK",
    method: "filmsComingSoon",
    message: null,
    request_method: "GET",
    version: "ZUPIv200",
    territory: "UK",
    device_datetime_sent: "2018-09-14T09:26:34.793Z",
    device_datetime_used: "2018-09-14 09:26:34"
  }
};

Answer: The key of an object has to be a string. You did it right in the object itself. But when you attempt to access it, the issue reappears.
If you insist on using it as it (maybe you do not have the choice), you have to use the square bracket notation:
props.newFilm.images.still["2"].medium.film_image

Why that error: JavaScript stopped looking in the object when it encountered the number and was about to return props.newFilm.images.still The rest not being understood, the error thrown was "expecting a }"
Answer: While using the numbered key, use bracket notation instead of dot notation

to


Custom php to handle url based on taxanomy terms

Question: Our site uses taxanomy to maintain a blog page. And for now we use views to render the contents. Now we are planning to get rid of views and use templates. What we need is to have custom tpl.php only for request containing vocabulary. So for any request to my site of a pattern path/*,

I need my custom tpl.php to be used only when the path is valid vocabulary.
Let the default flow get executed when the path is not a valid vocabulary.

What would be right way to handle this?
Answer: In views use TID converted to Name filter then use TID in url as a parameter and when the url is hit check the tid is valid or not and write behavior accordingly.
Comment: sorry.. forgot to add that we are planning to get rid of views. Updated the question now.
Answer: You can use template_preprocess_page() to check the specific path and add your custom template.
<code>function template_preprocess_page(&$vars, $hook) {
  $path = current_path();
  if ($path == 'your_path') {
    $vars['theme_hook_suggestions'][] = 'page__custom';
  }
}
</code>
So your template file should have the name page--custom.tpl.php


Unity3d Admob Reward Based Video error

Question: having problem showing rewarded ads using ad-mob SDK for Unity3d.
i successfully showing banner and interstitial ads, but when trying to show
rewarded ads i get the fallowing error (logcat):

Starting ad request.
  06-20 13:35:17.278 1188-1211/com.dice.master W/Ads: There was a problem getting an ad response. ErrorCode: 0
  06-20 13:35:17.279 1188-1188/com.dice.master W/Ads: Failed to load ad: 0
  06-20 13:35:17.319 1188-1188/com.dice.master I/Unity: HandleRewardBasedVideoFailedToLoad event received with message: Internal error
                                                        UnityEngine.DebugLogHandler:Internal_Log(LogType, String, Object)
                                                        UnityEngine.DebugLogHandler:LogFormat(LogType, Object, String, Object[])
                                                        UnityEngine.Logger:Log(LogType, Object)
                                                        UnityEngine.Debug:Log(Object)
                                                        UnityEngine.MonoBehaviour:print(Object) (at /Users/builduser/buildslave/unity/build/artifacts/generated/common/runtime/UnityEngineMonoBehaviourBindings.gen.cs:106)
                                                        AdController:HandleRewardBasedVideoFailedToLoad(Object, AdFailedToLoadEventArgs) (at D:\Private\Dice master 3D\Assets\Scripts\Admob\AdController.cs:133)
                                                        GoogleMobileAds.Api.RewardBasedVideoAd:m__1E(Object, AdFailedToLoadEventArgs) (at D:\Private\Dice master 3D\Assets\GoogleMobileAds\Api\RewardBasedVideoAd.cs:60)
                                                        GoogleMobileAds.Android.RewardBasedVideoAdClient:onAdFailedToLoad(String) (at D:\Private\Dice master 3D\Assets\GoogleMobileAds\Platforms\Android\RewardBasedVideoAdClient.cs:84)
                                                        System.Reflection.MonoMethod:InternalInvoke(Object, Object[]

i have an account in Chartboost ,set app with basic settings.
added the Mediation in the admob account to the add unit.....
the implementing is pretty straightforward so....
Answer: Error code 0 means there is no fill. I've never worked with charboost but there should be one of these: if charboost has test ads - enable them, if you just finished setting up charboost dashboard it may take some time to start working. But if these don't work than probably you are from 3rd world country like me and have very low fill. In this case download a free VPN app, start it and test again.
Comment: Hi Nika,so any recommended Reward Based Video network for 3rd country (for Unity)?
Comment: not really, I don't know any. Thing is, Developed countries have more financial potential, so better chances of buying new game/app. Thus ADVERTISERS chose to direct 9 ads out of 10 to developed countries. Ad PROVIDERS (like charboost) just implement this behavior. And this is the way absolute majority of ad networks work, not only rewarded video providers. I test my ads with BetterNet VPN, it's free, but there are a lot of other free VPNs out there.
Answer: Internal error !try late again.
if continue not able to load ,you can download https://github.com/unity-plugins/Unity-Admob and run it on device to test if your device and admob id is right.
Answer: You can try switch between Wi-fi network and 4G. Also you can try to use the google app id and reward id to test in a real device.

Unity3d Admob Reward Based Video error


do-while condition without declaring a separate variable

Question: I have a do-while loop inside a function that resembles something like this:
do
{
    // a bunch of stuff
    if (something < something else)
    {
        return true;
    }
    else if (stuff > other stuff)
    {
        if (something != other stuff)
        {
             return false;
        }
        else
        {
              return true;
         }
     }
} while (condition);

My issue here is with the condition at the end. The only way I can thing of to keep track of this would be to declare a boolean variable before the loop, and have it's value set to match the return value and have the while() check for that after each iteration. While this would work, it's seems rather inelegant to me and I was wondering if there was a way I could have the while() tap into the return value instead.
Comment: Is this loop intended to run until it returns true or false inside?  Or is there a return statement farther down?
Comment: It appears that nobody understands your issue, could you be clear?
Answer: It's not clear how your condition looks like. Anyway, you probably want an infinite loop:
for (; ;) {
    … your code here …
}

or:
while (true) {
    … your code here …
}

This loop will never stop by itself … but since you exit it using return this isn't a problem.
Answer: Assuming your code is incorrect due to you trying to paraphrase it, this is what you should be doing to meet your needs of the return being the same as the while();
To others, this code below is incorrect logic, but I am trying to keep it in the similar pseudo code he utilized. Basically if you want the while to mimic the return value, you need the ! of the return in order for the condition to exit.
do
{
    // a bunch of stuff
    if (something < something else)
    {
        return !condition;
    }
    else if (stuff > other stuff)
    {
        if (something != other stuff)
        {
             return condition;
        }
        else
        {
              return !condition;
        }
    }
} while (condition);

Answer: You could just say
 do
{
    // a bunch of stuff
    if (something < something else)
    {
        return true;
    }
    else if (stuff > other stuff)
    {
        if (something != other stuff)
        {
             return false;
        }
        else
        {
              return true;
         }
     }
     else if(exit_condition)
      break;
} while (1);


How to implement google plus login into my Iphone application?

Question: I am trying to implement google+ login in to my application, like facebook login.For fetching their contact details.I have gdata API.But i don't know what are the procedures to implement that in to my class.Is there any sample application ? Any help will be greatly appreciated.
Answer: This question is a bit broad - what have you tried already? The easiest way to use google+ login API call should be inside a UIWebView. Write up an html page using the API sample code then load it up inside your app. Check google for a good tutorial.


How to make polygons with moving vertices?

Question: I'm trying to make a 2D wave simulation similar to what's done in this tutorial. The problem is, I'm not sure of the best way to do it. I was thinking of using a CAShapeLayer and a UIBeizerPath since most guides say to do something like that, but the problem with that is I can't find a way to move the individual vertices of a UIBeizerPath without recreating the path entirely, which seems a bit performance-intensive to me.
Is there a better way than this?
Also, I don't need help with the actual wave part, I've already tried coding it before in an app called Codea with success. I just need to know the best way to draw the polygon.
Any answers will help!
Answer: You can't change the vertices in a CGPathor CGMutablePath. Thus you must recreate the complete path. But if you want animate the change, you need not to compute the path for every intermediate step. Core Animation can interpolate this change automatically.
Comment: Alright, that's what I figured, but is it performance intensive to recreate the path every time? Whatever Codea does seems to work incredibly fast, so is it perhaps using a different method?
Comment: I think creating a path costs not so much time. You can use `CGMutablePath` instead of `UIBezierPath`, which could be a little bit faster. But this is all POITROAE ;)

You should try it. If this is too slow for you, you can implement your own layer class, which is doing drawing and animation directly. But I think this is too much to start with.


Characteristic Function of a Compound Poisson Process

Question: The definition of a compound Poisson process and its characteristic function I have are the following:

Let $\lambda>0$ and $N\sim\text{Poisson}(\lambda T)$. Also, $\{X_i\}_{i=1}^N$ are i.i.d. and independent of $N$. And $\{U_i\}_{i=1}^N$ are i.i.d., $U_i\sim\text{Uniform}([0,T])$, and independent from $X_i,N$. Define:
  $$
Y_t\equiv\sum_{i=1}^N\mathbb{1}_{\{U_i\leq t\}}X_i, 0\leq t\leq T
$$
  Then $Y_t$ is a compound Poisson process with intensity parameter $\lambda$ and jump pdf $f(x)$.
The characteristic function of $Y_1$ is:
  $$
\mathbb{E}(e^{iuY_1})=e^{\lambda\int(e^{ix}-1)f(x)dx}
$$

Note that the characteristic function I quoted above is for $Y_1$, not $Y_t$. I am trying to show the equality above. I currently have:
$$
\begin{align}
\mathbb{E}(e^{iuY_1})&=\sum_nP(N=n)\mathbb{E}(e^{iuY_1}\mid N=n)\\
&=\sum_nP(N=n)\prod_{j=1}^n\mathbb{E}(e^{iu\mathbb{1}_{\{U_j\leq 1\}}X_j})\quad\text{(by independence)}\\
&=\sum_n P(N=n)\prod_{j=1}\int e^{iux}f(x)dx\quad\text{(by uniform)}
\end{align}
$$
I am not sure how to proceed. Any tips?
Thanks for helping! :D
Comment: As a hint, it looks like you can combine the Poisson and Uniform parts of your overall process into one Poisson process.  That will greatly simplify things, as you will then just have a sum of i.i.d. random variates with the number of elements of the sum distributed Poisson...
Comment: @jbowman thank you for the tip, I will try to combine them!
Comment: If you don't see how to do it, I'll help out more later, here's a followup hint.  Look carefully at the definition of $Y_t$ and how $U_i$ is used.  The question is really very well done, the essential fact that makes it simple is not immediately obvious.
Comment: @jbowman ok! I'm trying to solve it by myself, so the tip helps a lot. I already found something new using that. I will update it when I understand it better. Thank you very much! :D
Comment: @jbowman I have been trying to solve it for the past few hours, but I think I got very stuck, and I feel like I am wasting time. I found [this](http://www.maths.qmul.ac.uk/~ig/MAS338/PP%20and%20uniform%20d-n.pdf) on combining poisson and uniform. It seemed related to your hint, but I couldn't prove the theorem, even for the case $n=1$. I then proceeded to trying to find the pdf of $Y_1$, but it involves a bunch of convolutions, so I don't think that's the way you intended me to follow.
Comment: If you look at the expression for $Y_t$, which $X_i$ are *actually* being summed up?  How many of them are there?  Label that $n$.  What is the distribution of $n$?
Comment: @jbowman I managed to find the answer using the exponential series. If you know another way to obtain this result, could you please share? Thanks for helping! :D
Answer: I was missing the knowledge of the exponential series:
$$
e^x=1+x+\frac{x^2}{2!}+\frac{x^3}{3!}+\frac{x^4}{4!}+\cdots
$$
I also made a mistake when I separated the uniform in the expectation. Fixing these problems:
$$
\begin{align}
\mathbb{E}(e^{iuY_1})&=\sum_nP(N=n)\mathbb{E}(e^{iuY_1}\mid N=n)\\
&=\sum_nP(N=n)\prod_{j=1}^n\mathbb{E}(e^{iu\mathbb{1}_{\{U_j\leq 1\}}X_j})\quad\text{(by independence)}\\
&=\sum_n P(N=n)\left(\mathbb{E}(e^{iu\mathbb{1}_{\{U_1\leq 1\}}X_1})\right)^n\quad\text{(by i.i.d.)}\\
&=\sum_{n=0}^\infty\frac{(\lambda T)^n e^{-(\lambda T)}}{n!}\left(\mathbb{E}(e^{iu\mathbb{1}_{\{U_1\leq 1\}}X_1})\right)^n\quad\text{(by Poisson)}\\
&=e^{-(\lambda T)}\cdot e^{(\lambda T)\mathbb{E}(e^{iu\mathbb{1}_{\{U_1\leq 1\}}X_1})}\quad\text{(by the exponential series)}
\end{align}
$$
We can calculate the expectation by conditioning on the uniform:
$$
\mathbb{E}(e^{iu\mathbb{1}_{\{U_1\leq 1\}}X_1})=\frac{T-1}{T}+\frac{1}{T}\int e^{iux}f(x)dx
$$
Substituting and doing some algebra we get the answer:
$$
\begin{align}
\mathbb{E}(e^{iuY_1})&=e^{\lambda \int (e^{iux}-1)f(x)dx}
\end{align}
$$
Answer: Here's another approach that uses a common trick with characteristic functions to avoid having to work out the sums / integrals.
I'll set $\lambda = 1$ without loss of generality, it simplifies notation and can be put back in in obvious ways in what follows.  This means all the "$\lambda$"s below are not related to the $\lambda$ in the problem statement, until the very end where I include it again.
First, note that the definition of $Y_t$ involves the sum of $X_i$ corresponding to $U_i \leq t$.  This can be thought of as summing "observed" $X_i$, where an $X_i$ is "observed" with a probability $p = t/T$ that is the same across all $i$..  The number of "observed" $X_i$, label it $n$, is therefore distributed Poisson$(pT)$, which is the same as Poisson$(t)$.
The proof of this is straightforward.  The number of observed $X_i$, label it $n$, conditional upon $N$ is clearly distributed Binomial$(N, t/T)$.  Now, let's look at the characteristic function (ch.f.) of the Binomial distribution:
$\phi_{n|N}(i\theta) = (1-p+p\text{e}^{i\theta})^N$
We will want to integrate out $N$ w.r.t. the Poisson distribution to get the ch.f. of $n$.  The simple way to do this is to note that:
$\phi_{n|N}(i\theta) = \exp(N*\log(1-p+p\text{e}^{i\theta}))$
Writing out the integration (summation) gives us:
$\phi_n(i\theta) = \sum_N \exp(N*\log(1-p+p\text{e}^{i\theta})) p(N|\lambda)$
Looking at this, we can see this will have the same form as the ch.f. of a Poisson distribution ($\exp(\lambda(\text{e}^{i\theta}-1))$), just with $\log(1-p+p\text{e}^{i\theta})$ substituted in wherever $i\theta$ appears in the ch.f.  Making this substitution gives us:
$\phi_n(i\theta) = \exp(\lambda \text{e}^{\log(1-p+p\text{e}^{i\theta})} - \lambda)$
which quickly reduces to:
$\phi_n(i\theta) = \exp(\lambda(1-p+p\text{e}^{i\theta}) - \lambda)$
which can be rearranged to:
$\phi_n(i\theta) = \exp(p\lambda(\text{e}^{i\theta}-1))$
which is the ch.f. of a Poisson variate with mean $p\lambda$.  Substituting $t/T$ for $p$ and $T$ for $\lambda$ gives us the result.
On to step 2.  Now we have the ch.f. of the number of elements in the sum $n$. Let's define $\phi_Y(i\theta)$ as the ch.f. of $Y_t$, $\phi_\Sigma(i\theta)$ as the ch.f. of the sum of $n$ $X_i$ and $\phi_X(i\theta)$ as the ch.f. of a single $X_i$.  Since the elements are i.i.d., we know that, conditional upon $n$,
$\phi_\Sigma(i\theta) = \phi_X^n(i\theta) = \exp\{n \log \phi_X(i\theta)\}$
We can apply exactly the same approach as above to integrate out $n$:
$\phi_Y(i\theta) = \sum_n \exp\{n \log \phi_X(i\theta)\} p(n | t)$
where we know that $p(n|t)$ is a Poisson distribution.  This will be the ch.f. of a Poisson$(t)$ distribution with $\log \phi_X(i\theta)$ substituted for $i\theta$:
$\phi_Y(i\theta) = \exp\{t(\phi_x(i\theta)-1)\}$
Adding the $\lambda$ from the original problem statement gives the answer:
$\phi_Y(i\theta) = \exp\{t\lambda(\phi_x(i\theta)-1)\}$


Making a JSX syntax for a MockComponent and have it typed with typescript

Question: Wondering if anybody has some good suggestions on how to crack this. Got this test helper utils I have added some types to:
import { jest } from '@jest/globals'
import React from 'react'

// https://learn.reactnativeschool.com/courses/781007/lectures/14173979
export function mockComponent(moduleName: string, propOverrideFn = (props: Record<string, any>) => ({})) {
  const RealComponent = jest.requireActual(moduleName) as React.ComponentType<any>
  const CustomizedComponent = (props: Record<string, any>) => {
    return React.createElement(
      'CustomizedComponent',
      {
        ...props,
        ...propOverrideFn(props),
      },
      props.children
    )
  }
  CustomizedComponent.propTypes = RealComponent.propTypes

  return CustomizedComponent
}

So currently I can call it like this
jest.mock('react-native/Libraries/Components/Touchable/TouchableOpacity', () => {
  return mockComponent('react-native/Libraries/Components/Touchable/TouchableOpacity', (props) => {
    return {
      onPress: props.disabled ? () => {} : props.onPress
    }
  })
})

But I would like to be able to call it more like

jest.mock('react-native/Libraries/Components/Touchable/TouchableOpacity', () => {
  return <MockComponent
          module='TouchableOpacity'
          onPress={props => props.disabled ? () => {} : props.onPress}
         />
})

or
jest.mock('react-native/Libraries/Components/Touchable/TouchableOpacity', () => {
 return <MockComponent
          module='TouchableOpacity'
          propOverride={props => ({onPress: props.disabled ? () => {} : props.onPress, ...props})}
        />
})

Answer: If you look at React without JSX, you'll see that the XML-inspired syntax (<MockComponent />) is just short for React.createElement('MockComponent').
Right now, if you renamed mockComponent to MockComponent and tried using the angle bracket syntax, the first issue is that your function receives two arguments. React components are either class components that take one constructor argument (props) or functional components that take one argument (again, props). The second issue is that your function returns a React functional component, when it needs to return a rendered React element.
One way to fix this issue is to convert mockComponent into a React functional component and make module and propOverride props of the FC.
// https://learn.reactnativeschool.com/courses/781007/lectures/14173979
export function MockComponent(props) {
  const { moduleName, propOverrideFn, ...customComponentProps } = props;

  const RealComponent = jest.requireActual(moduleName) as React.ComponentType<any>
  const CustomizedComponent = (props: Record<string, any>) => {
    return React.createElement(
      'CustomizedComponent',
      {
        ...props,
        ...propOverrideFn(props),
      },
      props.children
    )
  }
  CustomizedComponent.propTypes = RealComponent.propTypes

  return <CustomizedComponent {...customComponentProps} />
}

The differences are subtle but important. Here I modified MockComponent to take in a singular prop argument to be compatible with React.createElement(). This leads to the issue of how to differentiate props that are meant for the CustomizedComponent and what used to be arguments for mockComponent(). Here, I use the JavaScript destructuring and spread operators to separate module and propOverride from the props intended from CustomizedComponent.
Lastly, I use the JSX spread syntax to pass the arbitrary props intended for CustomizedComponent into CustomizedComponent, and I use angle brackets to render it (instead of returning a function).
I'll leave as an exercise for you to come up with the appropriate TypeScript definition for MockComponent's props. You can simply define it as the union of Record<string, any> and module and propOverride. However, you can get fancy and use a template definition so MockComponent<Toolbar> is a union of module and propOverride and Toolbar's props.
Oh, and I almost forgot. Your Jest call would look like
jest.mock('react-native/Libraries/Components/Touchable/TouchableOpacity', () => {
    (props) => {
        return <MockComponent
            module='TouchableOpacity'
            onPress={props => props.disabled ? () => {} : props.onPress}
            {...props}
        />
   }
})

Comment: Thank you very much Vincent for the throughout explanation and code suggestion


Conditional Gaussian

Question: Suppose I have
$$
\begin{align}
p(x_1) &= N(x_1; 0, 1) \\
p(x_2 \mid x_1) &= N(x_2; x_1, 1)
\end{align}
$$
How do I compute $p(x_1 \mid x_2)$? I know how to compute their product, giving $N\left(\frac{x_1}{2}, \frac{1}{2}\right)$. The answer of the exercise is $N\left(\frac{x_2}{2}, \frac{1}{2}\right)$, so with $x_2$ rather than $x_1$ in the mean.
Answer: When one Marginal is Normal, and one Conditional is Normal, then the joint bivariate distribution is Normal. Then the other marginal is also Normal, and the second Conditional is also Normal. Using Baye's Law for densities
$$f(x_1 \mid x_2) = \frac{f(x_2 \mid x_1)\cdot f(x_1)}{f(x_2)}$$
we can solve for the left-hand-side. Determining the marginal parameters of $f(x_2)$ as well as the correlation coefficient can be done using the expressions for conditional Normal densities between two variables.
UPDATE responding to OP comments
As mentioned earlier, one marginal and one conditional Normal imply a bivariate Normal distribution, and so both the other conditional and the other Normal will be also Normal. So
$$X_2 \sim N\left(\mu_2, \sigma^2_2\right) , \quad X_1 \mid X_2 \sim N\left (\mu_1+\frac{\sigma_1}{\sigma_2} \rho(x_2 - \mu_2),\,(1-\rho^2)\sigma^2_1\right)$$
and we also have from the premises
$$X_2 \mid X_1 \sim N\left(\mu_2+\frac{\sigma_2}{\sigma_1} \rho(x_1 - \mu_1) =x_1,\,(1-\rho^2)\sigma^2_2 =1\right),$$
$$X_1 \sim N\left(\mu_1=0, \sigma^2_1=1\right) , $$
which gives us
$$\mu_2 = 0, \;\;\; \sigma_2\rho = 1 \implies \sigma_2 = \sqrt{2} , \rho=1/\sqrt{2}.$$
Since
$$X_1 \mid X_2 \sim N\left(\mu_1+\frac{\sigma_1}{\sigma_2} \rho(x_2 - \mu_2) ,\,(1-\rho^2)\sigma^2_1 \right)$$
we get
$$X_1 \mid X_2 \sim N\left(\frac{1}{2}x_2,\,\frac{1}{2}\right),\qquad X_2 \sim N\left(\mu_2 = 0, \sigma^2_2 =2 \right)$$
Comment: Thank you, that's very helpful!

Conditional Gaussian


How can I make a footer's height expand to take up the remainder of the screen?

Question: I'm looking to do something like:

Where I have a footer at the bottom of the page which has a height that expands to take up the remainder of the screen.
Is it possible to do this in CSS?
Answer: I've looked at doing this before and wasn't able to find a way to do it using strictly CSS.  However, I have seen it done successfully using Javascript (the jQuery CSS height function).
Answer: if your target is to make the footer at bottom.
you can make the footer (DIV) set to

.footer{position: absolute; bottom:
  10}

the bottom you need to change the value as needed.


Test for one coefficient doubled another one?

Question: I want to run a regression in order to test ( thinking of the $t$-test ) the null hypothesis that one coefficient ($b_2$) is twice another coefficient ($b_3$), so $b_2= 2 b_3$, The variable for $b_3$ is a dummy variable. The $t$-test is $(b_2-2b_3)/se(b_2-2b_3)$. How can I find $se(b_2-2b_3)$?
Comment: You can just report likelihood ratio of your hypothesis to alternative.
Comment: What are you using to do your stats?
Answer: Most any statistics package will report, somewhere, the covariance matrix of your estimators. Let $S$ denote this covariance matrix.
Let $w = \left[ \begin{array}{c}1\\-2\end{array} \right]$ and $b = \left[ \begin{array}{c}b_1\\b_2\end{array} \right]$
$\mathrm{Var}(w'b) = w'\mathrm{Var}(b)w = w'Sw$. The standard error of $w'b$ would then be $\sqrt{w'Sw}$.
Answer: The answer by MatthewGunn applies more generally. If you are working under the framework of linear regression (or generalized linear regression), then
$$se(b_2 - 2b_3) = \sqrt{\dfrac{Var(b_2 - 2b_3)}{n}},$$
where $n$ is the number of observations. The covariance matrix of regression coefficients is $\sigma^2 (X^TX)^{-1}$, which can be calculates for every problem.
$$Var(b_2 - 2b_3) = Var(b_2) + 4Var(b_3) - 4Cov(b_2, b_3).$$
These values can be picked from the estimate of $\sigma^2 (X^TX)^{-1}$. For example, in R you can use the vcov function on the lm object. I present the example on the dataset cars below.
> fit <- lm(cars)
> vcov(fit)
            (Intercept)          dist
(Intercept)  0.76454824 -0.0131543211
dist        -0.01315432  0.0003060568

Here $Var(dist - 2Intercept)$ = .0003 + 4(.76454) - 4(-.01315).
Comment: (+1) Perhaps worth noting that the likelihood-ratio test may be preferable for generalized linear models: compare the model having $b_1x_1 + b_2x_2$ with the restricted one having $b(x_1+2x_2)$.


Convert silverlight to flash

Question: How can i convert silverlight app to flash?
Comment: The same way you convert COBOL to Lolcode.  Lots of alcohol, lots of work, lots of pain...
Answer: The platforms are different enough that a "conversion" of code is out of the question.
Instead take the running Silverlight app as a prototype and build the Flash from scratch.
You might be able to re-use some assets such as images.
Answer: I imagine both platforms are turing complete.
Maybe you could embed a simple PC emulator from http://bellard.org/jslinux/ into one (or the other) of these, and install the opposing platform into it, and run it in that fashion.
Performance might suffer a bit.

Convert silverlight to flash


Proof union of two disjoint perfect matchings in a bipartite graph is covering all vertices of G with disjoint cycles

Question: I am trying to prove that the union of two disjoint perfect matchings in a bipartite graph is covering all vertices of G with disjoint cycles.
I would appreciate if anyone knew the proof or had ideas about it
Answer: Let $(V_1,V_2)$ be the bipartition sets, $M_1$, $M_2$ the two matchings, and $G'$ the graph with vertex set $V_1\cup V_2$ and edge set $M_1\cup M_2$. Since $G$ is bipartite, each edge in a matching is incident on a vertex $u\in V_1$ and a vertex in $V_2$, so $|M_1|\leqslant|V_1|,|V_2|$. But $M_1$ is a perfect matching, so $|M_1|\geqslant|V_1|,|V_2|$, and so $|M_1|=|V_1|=|V_2|$ (and similarly $|M_2|=|M_1|$).
Since $M_1\cap M_2=\varnothing$, each vertex in $u\in G'$ is incident with an edge $uv\in M_1$ and some $uw\in M_2$. It follows that $G'$ is $2$-regular, and so is the union of disjoint cycles.
Comment: What is the first paragraph for? Doesn't the second paragraph do the job all by itself? And what does "bipartite" have to do with it? The union of two disjoint perfect matchings in any graph is going to be a $2$-regular subgraph, isn't it?


How do I implement a javascript clock?

Question: This code is taken from a Udemy course to make projects. I have seen this code work perfectly before and now it shows nothing. All it does is reflect the local time. It remains blank.
I have run it through a couple of browsers and ran it on codepen and it all looks the same, which is blank. I had codepen analyze the code for errors and it came clean on the html, css, and javascript portions.
https://codepen.io/Laurax/pen/gVwGYo
here is the javascript portion by itself:
 setInterval(function (){
    var currentTime = new Date();
    var hours = currentTime.getHours();
    var minutes = currentTime.getMinutes();
    var seconds = cuttentTime.getSeconds();
    var period = "AM";

     if(hours >= 12){
     period = "PM";
    }
    if(hours > 12){
    hours = hours -12;
    }
    if(seconds < 10){
    seconds = "0" + seconds;
    }
    if(minutes < 10){
    minutes = "0" + minutes;
    }

   var clockTime = hours + ":" + minutes + ":" + seconds + " " + period;
   var clock = document.getElementById('clock');
   clock.innerText = clockTime;

   }, 1000 );

I expect the output to show hours, minutes, and seconds. It should be white numbers over a black background.
Comment: Yes typo error ! Should be close
Comment: cuttentTime is not defined.
Answer: There's a typo in this line:
var seconds = cuttentTime.getSeconds();
Your date variable is called currentTime and not cuttentTime.

How do I implement a javascript clock?


Mostrar e esconder de acordo com outro evento

Question: Tenho 2 botões de mostrar/esconder de 2 grupos: grupo1 e grupo2.Quando clico para abrir o do grupo1,por exemplo, ele abre um card com informações desse grupo e quando clico em esconder ele esconde.
Até aí tudo bem!
O que eu quero é que quando clique no outro grupo(grupo2), ao invés dele abrir o grupo2 embaixo do que ja estava aberto(grupo1), quero que ao clicar ele feche o do grupo1 para abrir o novo.
<button type="button" class=" grupo1 btn-toggle btn waves-effect waves-light green" data-element="#grupo1">
                            Mostrar / Esconder
                        </button>

<button type="button" class=" grupo2 btn-toggle btn waves-effect waves-light green" data-element="#grupo2">
                            Mostrar / Esconder
                        </button>

// Função do button Mostrar/Esconder do card
    $(function(){
        $(".btn-toggle").click(function(e){
            e.preventDefault();
            el = $(this).data('element');
            $(el).toggle();

        });

    });

Answer: Adicionei uma classe aos elementos que você mostra/esconde. Ao clicar no botão eu oculto todos elementos com .hide() e depois só exibo o que foi clicado:

// Função do button Mostrar/Esconder do card
$(function(){
  $(".btn-toggle").click(function(e){
      e.preventDefault();
      $(".grupo").hide(); //Oculta todos elemento com classe grupo

      el = $(this).data('element');
      $(el).toggle(); //Exibe o elemento clicado.
  });
});

<button type="button" class="grupo1 btn-toggle btn waves-effect waves-light green" data-element="#grupo1">
    Mostrar / Esconder
</button>

<button type="button" class="btn-toggle btn waves-effect waves-light green" data-element="#grupo2">
    Mostrar / Esconder
</button>

      Grupo 1

      Grupo 2

Comment: Obrigada Caique! Era exatamente o que eu precisava!!
Answer:

   $(document).ready(function(){
        var bt1 = $('#bt1'), //seleciona botão 1
            bt2 = $('#bt2'); //seleciona botão 2
       bt1.click(function(){  //define o display de acordo com o botão clicado
         $('#grupo1').css('display','block');
         $('#grupo2').css('display','none');

       })
       bt2.click(function(){ //define o display de acordo com o botao clicado
         $('#grupo2').css('display','block');
         $('#grupo1').css('display','none');

       })
  });
<button type="button" id="bt1" class=" grupo1 btn-toggle btn waves-effect waves-light green" data-element="#grupo1">
                            Mostrar / Esconder
                        </button>

<button type="button" id="bt2" class=" grupo2 btn-toggle btn waves-effect waves-light green" data-element="#grupo2">
                            Mostrar / Esconder
                        </button>

            Botão 1 pressionado e conteúdo do grupo 2 oculto!

             Botão 2 pressionado e conteúdo do grupo 1 oculto!

Teste e vê se é o que precisa!
Comment: Olá Jorge! Obrigada pelo comentário, porém eu dei o exemplo com 2 botões mas tenho 5 aqui e por isso fazendo do modo como você fez seria muita verificação! Mas já foi resolvido com o comentário abaixo
Comment: @BiancaC. que bom que resolveu! Por nada!


Ordering CSS properties

Question: I have the following CSS:
body
{
    margin-left:0px;
    margin-right:0px;
    margin-bottom:0px;
    margin-top:0px;
    background-image: url("../images/tile.png");
    background-repeat: repeat;
    background-attachment: fixed;
}

#mbody
{
    width:80%;
    border-style:solid;
    border-width:2px;
    margin-left:10%;
    margin-top:50px;
    margin-bottom:10%;
    background-color:white;
 }

Is there a generally accepted method to order the properties?  Alphabetical?  Grouped by purpose?  Currently I kind of just add them onto the end when I think to add them.  I feel like a bad person by doing this.
Comment: Duplicate of: http://stackoverflow.com/questions/2064498/how-to-order-properties-in-a-declaration-block
Answer: I prefer alphabetical. The other thing you should do it to add vendor specific attributes before the standard ones so that if available your elements get styled according to the standard. Also, consider combining compatible properties together.
Use margin:none instead of:
margin-left:0px;
margin-right:0px;
margin-bottom:0px;
margin-top:0px;

And the same goes for the background properties.
Answer: The order of properties does not matter, but you generally should order them by purpose. Also, feel free to use short forms like margin: 50px 0 10% 10% instead of 4 margin-* rules.
If you're thinking about ordering properties alphabetically, it is probably time to split up your classes, and define properties common in multiple classes in one class or rule.
Answer: It doesn't matter in the least. Just remember to run the file through a YUI compressor before you put it into production.
Answer: Think of a clock...
Start at 12:00, then 3:00, 6:00, 9:00. Up, right, bottom, left is usually how I list properties.
I believe using some of the new CSS3 properties like border-radius, you have to list them in that order.

Ordering CSS properties


Why do a density plot and a rug plot seem to disagree?

Question: The second peak of the density plot is large in this example.  Why does the rug representation of the data--which seems to show few high values--not appear to match the much higher density estimated there?
How can one make rug plots less misleading?

Here's its R code:
plot(density(Boston$tax))
rug(Boston$tax, col=2, lwd=3.5)

Comment: The "problem" with the rug plot is just that one tick and several ticks in the same place look the same. You could use a spike for each distinct value whose length was proportional to number of values, i.e. a histogram with bins the distinct values.
Comment: You are using subjective terms like "so high" and "inadequate"...why is the second peak "too high" and why is the rug function not acceptable? What is it doing that you don't like.
Comment: How many data points are above the level of 600?
Comment: This question appears to be relying on unjustified premises (at least in general). Are these questions someone else has set for you to do?
Answer: The way to make a rug plot less misleading is often to use something different instead. Rug plots necessarily are relatively good at showing distinct values and very poor at indicating their relative frequency.
Here is a spike representation of the frequency distribution of the data used in the original post. The principle is that often used to show discrete distributions, a spike proportional in height to the frequency of each distinct value. The Boston data as available and documented here were read into Stata and the spikeplot command used. Something similar should be trivial in all good statistical software. If you like, this is a hybrid of a histogram and a rug plot, although historically graphs of this kind may long predate rug plots.

Stata documentation for spikeplot, including, more to the point of this question, further examples of such graphs, is accessible here
EDIT 3 August 2022 See also this paper for examples of marginal spike histograms as inspired by Harrell, F.E. 2001/2015. Regression Modeling Strategies. Springer.
The Boston housing data are often used as an example. Many researchers follow in the path of the original authors, who did not show any plots of the raw data in their paper. Here are four of the more unusual distributions for predictors in that dataset, as shown by quantile plots, plots of the ordered values versus an estimate of cumulative probability. The vertical axis labels are minimum, lower quartile, median, upper quartile and maximum, which in some instances coincide. A quantile plot is good for showing marked spikes and gaps in the data. Naturally an unusual (e.g. spiky) distribution doesn't stop a variable being useful as a predictor, as exemplified also by indicator or dummy variables, but it is a good idea to look at your data before modelling.
In some problems, there may be real doubts about data quality, or at least puzzles about definitions and measurements that need to inform the interpretation.
Answer: From the R package MASS, of the $506$ total observations in Boston, $369$ have a value for tax below 470 and $137$ have a value for tax above 665.  In fact 666 is by far the most common value in the data set, appearing $132$ times.
So if the area of the density plot to the left is about twice the area to the right, then that could reasonably be taken as representing the distribution.  Visual inspection suggests this might be what is happening.
A more accurate representation would have the right peak much higher and narrower, and this could be achieved by adjusting the parameters.
Added for comments:
For example with a much narrower bandwidth for the density function and some manual jitter:
library(MASS)
plot(density(Boston$tax, bw=5))
rug(Boston$tax + rnorm(length(Boston$tax), sd=5), col=2, lwd=3.5)

you would get something like this
Comment: Yeah, I used jitter for modifying the rug.
Comment: @RickHenderson: I added a chart with a narrower bandwidth and manual jitter
Comment: You have hit upon the reason for the discrepancy.  But upon adjusting the parameters of the density estimate, the *area* of the right peak should not change and so there will still be a strong visual discrepancy between what the rug plot displays and the density plot displays. Effective solutions will--as the O.P. suggests and as @Nick Cox hints in a comment--modify the rug plot rather than the density plot.
Comment: @MonaJalal could you post what the chart looks like after you made your changes? I'd be interested in seeing it.
Comment: Jitter on a rug plot defeats the very purpose of indicating that **these values** are the distinct values that occur in the sample. NB distinct, not unique, which is the pivot of the question.


The fundamental form is real of type $(1,1)$

Question: Given a real vector space $V$ with an almost complex structure $I$, and an inner product $\langle, \rangle$. Can define a fundamental form $(,):= \langle I(),() \rangle$. The claim is that is real of type $(1,1)$, i.e. $(,) \in \wedge^2 V^{\ast} \cap \wedge^{(1,1)}V^{\ast}$.
Why should it be real? It does not make sense at all, since if I take for instance $iv \in V_{\mathbb C}$, $v, w \in V$, then $(w, iv) = i(I(w), v)$ which is complex.
Also, why is it denoted by $\wedge^2 V^{\ast} \cap \wedge^{(1,1)}V^{\ast}$? Isn't $\wedge^{(1,1)}V^{\ast}$ a subspace of $\wedge^{2}V^{\ast}$?
This statement is taken from  Introduction to Complex Geometry Lemma1.2.24, can someone clarify what it means by saying that the form is real?
Comment: Dear Vanstar, you may take a look at Chern's book "Complex Manifolds without Potential Theory". You are mixing some definitions.
Comment: @user90189 Can you point out which definitions I am missing out?
Comment: https://www.math.uh.edu/~shanyuji/Complex/Complexgeometry.pdf There is a good discussion here starting at page 25
Comment: @Alan Muniz That is actually where I am taking this from, so I am still confused.
Comment: I think the proof in Lemma 1.2.14  is clear. Check the definitions of each space involved.
Comment: @Alan Muniz Yes, but it does not explain why it is real. Maybe I am interpreting it wrong. May you at least clarify what it means for $w$ to be real? I am also confused why he has to denote the space by intersecting them since he pointed out in proposition 1.2.8 the latter is the subspace of the former.
Comment: Actually, $\Lambda^{1,1}V^* \subset \Lambda^2(V\otimes\Bbb C)^*$, no?
Comment: Formally no, but it can be identified with a subspace of the latter.@TedShifrin
Comment: @Vanstar  $\Lambda^{1,1}V^* \subset \Lambda^2(V\otimes\Bbb C)^*$ by definition!  Actually, $\Lambda^2V^*$ that is identified with the subspace of $\Lambda^2(V\otimes\Bbb C)^*$ given by the elements invariant by complex conjugation.
Comment: @AlanMuniz, I do not think that is true. Just take a look at the first statement of proposition 1.2.8. The issue is that the former object is defined as the tensor product of two subspaces of $(V_{\mathbb C})^{\ast}$ which is not a subspace of the wedge product to begin with. But it can certainly be identified as its subspace.
Answer: This matter has also puzzled me for a long time.
$ V^*_{\mathbb{C}} $, the complexification of the dual space of $ V $, has a direct sum decomposition
$$V^*_\mathbb{C}=W^{1,0}\oplus W^{0,1}$$
since on $ V^* $ there is a natural complex structure induced by $ I $. Then we have
$$ \bigwedge^2 V^*_\mathbb{C}=\bigwedge^2 W^{1,0}\oplus W^{1,1}\oplus \bigwedge^2W^{0,1}, $$
where $ W^{1,1} $ is the image of
$$ \varphi\colon W^{1,0}\otimes W^{0,1}\longrightarrow \bigwedge^2 V^*_\mathbb{C},\quad f\otimes g\longmapsto f\wedge g. $$
Besides, for every $ \omega\in \bigwedge^2 V^* $, which can be regarded as an alternating function
$$ \omega\colon V\times V\longrightarrow \mathbb{R}, $$
can be extended by linear to (still denoted by $ \omega $)
$$ \omega\colon V_\mathbb{C}\times V_\mathbb{C}\longrightarrow \mathbb{C}. $$
In this way we embed $ \bigwedge^2 V^* $ into $ \bigwedge^2 V^*_{\mathbb{C}} $. Now we can talk about the intersection
$$ W^{1,1}_\mathbb{R}:=W^{1,1}\cap \bigwedge^2V^*\subset \bigwedge^2 V^*_{\mathbb{C}}. $$
We say elements of $ W^{1,1}_\mathbb{R} $ are alternating real form of type $ (1,1) $. Now it is clear how the name "real" and " type $ (1,1) $ " come from.
My references

Huybrechts - Complex Geometry
https://people.brandeis.edu/~igusa/Math250b/Notes2020C.pdf
Exterior power "commutes" with direct sum

Warnning: The notation in this answer such as $ W^{1,1}_\mathbb{R} $ may not be standard.


Solve $x^{15} \equiv 7$ (mod $19$)

Question: Using the brute force approach, I found that $5$, $16$ and $17$ satisfied the congruence. How to find all possible solutions?
Comment: Consider $2$ as the primitive root modulo $19$. You would have $15\operatorname{ind} x\equiv \operatorname{ind} 7\pmod{18}$. We can easily get $\operatorname{ind} 7=6$. Therefore you are looking for the solutions to $3y\equiv -6\pmod{18}$. This gives you $\operatorname{ind} x\equiv 4, 10, 16$, meaning $x=2^4,2^{10}\equiv 17, 2^{16}\equiv5$.
Answer: First, let us use Fermat's little theorem.  Since $x^{18}\equiv 1 \pmod{19}$ for any $x\not \equiv 0 \pmod{19}$, we can rewrite the equation as $x^{-3}\equiv 7\pmod{19}$, and since $7^{-1}\equiv 11\pmod{19}$, the problem is equivalent to solving
$$ x^{3}\equiv 11 \pmod{19}$$
Since this is a 3rd degree polynomial equation an $19$ is prime, there are at most $3$ solutions, all of which have been found.
However, if you only had one solution, here is a way you could generate the others.  Suppose that $\omega^{3}\equiv 1 \pmod{19}$.  If $x^{3}\equiv 11$, then $(\omega x)^{3}\equiv \omega^{3}x^{3}\equiv x^{3}\equiv 11$, and similarly with $\omega^2 x$.  Therefore, if you have one solution, finding such an $\omega$ will give you the rest.
But how do you find such an $\omega$? If you have a generator $g$, then set $\omega=g^{18/3}=g^6$.  If you don't have a generator, but you do have $h$ such that $h\neq 0, h^2\neq 1$, then either $h^6=1$, in which case we can take $\omega = h^2$, or else we can take $\omega=h^6$.

Solve $x^{15} \equiv 7$ (mod $19$)


Determining the position of a vertex of a triangle

Question:
A triangle has a vertex $A$ at $(0,3)$, vertex $B$ at $(4,0)$, and vertex $C$ at $(x,5)$. If the area of the triangle is $8$, what is the value of $x$?

I did this problem out by using the formula of the given coordinates of the vertices. My answer was 2.66.
Comment: Good for you.  Do you have a question?  Your answer is not exactly correct.
Comment: @Briana791: If the question asked for the *positive* $x$ that works, you have found it. More precisely, $x=8/3$.  But, as a picture may persuade you, there is also a negative $x$ that gives area $8$.
Comment: Is there a question here?
Comment: Please put the problem **in the body of the question**, not in the title!
Comment: @Arturo: True but I presume she wanted to know how to proceed.
Comment: or may be even check the answer with us.
Comment: @Chandru: I'm not criticising you, so I don't see why the need to defend yourself. But since you bring it up, why did you assume "she wanted to know how to proceed", if she said she had already finished?
Comment: @Arturo: Don't know. Can't really justify that.
Answer: Good work, in arriving at one of the correct solutions, Briana..
I would just like to clarify what others mean by there being two solutions: there are two triangles, each sharing vertices at $(0,3)$ and $(4,0)$ (and hence they share a side).  But there are two values for the unknown $x$ in the vertex $(x, 5)$ that yield a triangle with area $8: x = \frac {8}{3} = (2.66$ repeating), and $x = -8.$
In other words, the area of the triangle with third vertex $( \frac {8}{3}, 5)$ and the area of triangle with third vertex $(-8, 5)$ both equal $8$.
Answer: The area of the triangle with vertices $(x_{i},y_{i})$, $i=1,2,3$ is given by $$\Delta = \frac{1}{2} \cdot \left| \begin{array}{cc} x_{1} & y_{1} & 1 \\ x_{2} & y_{2} & 1 \\\ x_{3} & y_{3} & 1 \end{array}\right| = \frac{1}{2}\left|\begin{array}{cc} 0 & 3 & 1 \\  4 & 0 & 1 \\ x & 5 & 1 \end{array}\right|$$
Now substitute $\Delta=8$, and the corresponding values for $(x_{i},y_{i})$ and solve for $x$. Solving you get $16 = -3(4-x) + 1 \times 20 = -12 + 3x +20$. Therefore you have $3x=8$ which says $x=\frac{\pm{8}}{3}$. You get the minus sign if you interchange the vertices. (Thanks to Arturo for pointing out the error.)
Comment: Last I checked, $\frac{8}{3}\neq\frac{133}{50}$.
Comment: Sigh. $\frac{8}{3}\neq \frac{133}{50} = \frac{266}{100} = 2.66$. If you are giving approximations, don't use the equal sign. If you use the equal sign, both sides should be **equal**.
Comment: The formula cannot be correct as given, because if you exchange the first two rows (if you take the vertices in a different order), then the value of the determinant is multiplied by $-1$, yielding a "negative area". So you are missing an absolute value sign, which also means that there is more than one solution.
Comment: @Briana: Does this clarify your doubts.
Comment: @Arturo: Where have i gone wrong. Don't know. Checked calculation and it seems correct.
Comment: @Arturo: Thanks. I have edited.
Comment: @Chandru: As Arturo points out as well, the area is the magnitude of the determinant and hence you will get $x = -8$ as well.


Gerar options de um select (anos) de acordo com outro campo selecionado

Question: Tenho um formulario para cadastro de dependentes de um plano, onde pode escolher filho, marido, sogro, etc.. e depois o ano de nascimento
Queria que, ao selecionar qual o grau de parentesco, ele vá alterando os options do select, ex:
Selecionar filho: Máximo ano atual | Mínimo - 35 anos (1982 a 2017)
Pai/mãe:  Máximo ano atual - 12 | Mínimo ano atual - 100 (1917 a 2005)
Outros: Máximo ano atual | Mínimo ano atual - 100 (1917 a 2017)

Pode usar php, javascript, jquery, qq um.
Consegui apenas criar uma regra, não sei como atrelar ao outro select:
<select id="grau_parentesco">
<option value="filho">Filho(a)</option>
<option value="pai">Pai</option>
<option value="mae">Mãe</option>
<option value="outros">Outros</option>
</select>
<select id="ano"></option>
<?
$ano_inicial = date("Y");
$qtd = 35;
for($i=0; $i <= $qtd; $i++){
    $ano = $ano_inicial-$i;
    $ano = sprintf("%02s",$ano);
    echo "<option value=\"".$ano."\">".$ano."</option>\n";
}
?>
</select>

Comment: Você quer dizer [dessa forma](https://pt.stackoverflow.com/questions/162062/valida%c3%a7%c3%a3o-de-dois-selects/162066#162066)?
Comment: Ou esta: https://pt.stackoverflow.com/a/14668/43731
Comment: exato, mas a diferença é que preciso que gere os anos automaticamente, pra que independente do ano que a gente esteja, ele gere todos os anos, para que eu não precise alterar o código todo ano
Answer: Segue um exemplo utilizado JQuery e uma lógica simples, deixei as regras em um switch para facilitar, caso queria adicionar outras.

$("#grau_parentesco").on('change', function () {

        //Selecionar
        //filho: Máximo ano atual | Mínimo - 35 anos (1982 a 2017)
        //Pai / mãe:  Máximo ano atual - 12 | Mínimo ano atual - 100(1917 a 2005)
        //Outros: Máximo ano atual | Mínimo ano atual - 100(1917 a 2017)

        var maxValue = (new Date()).getFullYear();
        var minValue = maxValue - 100;

        switch ($(this).val()) {
            case "pai":
            case "mae":
                maxValue -= 12;
                break;
            case "filho":
                minValue = maxValue - 35;
                break;
            default:
                break;
        }

        //limpa
        $("#ano").find("option").remove();

        //popula
        for (var ano = minValue; ano <= maxValue; ano++) {
           $('#ano').append($('<option>', {
                value: ano,
                text: ano
            }));
        }

    });

<select id="grau_parentesco">
  <option value="">Selecione</option>
  <option value="filho">Filho(a)</option>
  <option value="pai">Pai</option>
  <option value="mae">Mãe</option>
  <option value="outros">Outros</option>
</select>

<select id="ano">
</select>
Comment: perfeito, isso mesmo. só mais uma frecurite..rs, como faço para aparecer os anos invertido, o primeiro option de cima do filho por exemplo ser 2017
Comment: é só inverter a população, (var ano = maxValue; ano >= minValue ; ano--)
Comment: Perfeito, obrigado!


Should I remove stopwords before generating n-grams?

Question: I'm wondering if the stopwords are useful in n-gram or it should be removed before generating n-gram.
I would like to know best practices on extract features of text. I'm currently using nltk.
Comment: The correct answer is 'no'. Stop words have an important function in language, and should not be ignored.
Answer: Should you generally remove stopwords?
Depends on what you use the n-grams for but generally yes, I would recommend to remove them, otherwise a lot of the results highest in your list of occuring n-grams are going to contain them.
When within your code should you remove the stopwords?
Depending on your intended use you can either:

calculate common n-grams and then remove those which contain stopwords OR
remove stopwords and then calculate common n-grams from the remaining text

Usually of those the first approach is better since this gives you n-grams which actually occur exactly as listed in the original corpus.
A tweaked approach I like to use:
First calculate the n-grams, then remove n-grams containing stopwords, but only remove n-grams which begin and/or end with a stopword.
So the quadgram/4-gram end of the month would not be removed since it does not contain stopwords in the first or last position.


Probability of segments connecting six points

Question: Question: You can draw edges between any two vertices of an empty graph with $6$ vertices and you have the same chance of drawing each edge. Find the probability that "there exists three vertices that any two of them are connected or any two of them are not connected".
What I tried:
index the vertices and there are 15 different segments so there are $2^{15}$cases in total.
Cases for existence of three connected vertices: connect arbitrary three vertices and then decide the 12 edges left. ${6\choose 3} * 2^{12}$.
Cases for existence of three not connected vertices: choose arbitrary three vertices and not connect them and then decide the 12 edges left. ${6\choose 3} * 2^{12}$.
Cases for both: connect arbitrary three vertices and not connect the three left . And there are $3 * 3 = 9$ edges between  connected vertices and disconnected vertices.  ${6\choose 3} * 2^9$
The problem is that $\frac{{6\choose 3} * 2^{12} + {6\choose 3} * 2^{12} - {6\choose 3} * 2^{9}}{2^{15}} > 1$.
Could you tell me where I went wrong?
Thanks in advance.
Comment: How many segments are you to draw?
Comment: Hi! Welcome to MSE! It seems that your question is about random graphs. Could you explain, please, what random graph model are you using? Without knowing that, we will not be able to answer your question...
Comment: @L.ScottJohnson 0 to 15.
Comment: @YaniorWeg    I have not learned any graph theory yet . What information is missing?
Comment: @Adwin1033, there are different ways of drawing random edges. And the probability of an outcome usualy depends on which of them you are using. You can find several most commonly used random graph models under this link: https://en.m.wikipedia.org/wiki/Random_graph And if you want more information, there is a book on random graphs, written by A.M. Raigorodskiy
Comment: Ah, that information needs to be included in the question.
Answer: A quick look suggests you forgot the case where one of the points is a member of both the connected and disconnected groups.
Edit: in fact, you are double counting a ton of the graphs, for example the completely connected graph gets counted 20 times. My suggestion on how to approach this problem would be to instead consider the graphs where neither the 3-clique of connected vertices nor the 3-clique of disconnected vertices exist. Do such graphs really exist?
Comment: Oh, I did count repeatedly.   Such graph does not exist.  I wanted to prove it by showing probability of its opposite is 1.
Answer: Actually, despite what I claimed in the comment, your question does not depend on the random graph model you are using. By Ramsey's Theorem any graph with 6 vertices contains either a full 3-vertice subgraph or an empty 3-vertice subgraph, so your probability is 1 in any case.
You can find more information about Ramsey's theorem and Ramsey Numbers under this link: https://en.m.wikipedia.org/wiki/Ramsey%27s_theorem
Answer: This is Ramsey's Theorem. Here the "colors" are either "in the graph" or "not in the graph". So just color every edge red or blue at random. The odds of getting a monochromatic triangle are 1.

Suppose the edges of a complete graph on 6 vertices are coloured red
  and blue. Pick a vertex, v. There are 5 edges incident to v and so (by
  the pigeonhole principle) at least 3 of them must be the same colour.
  Without loss of generality we can assume at least 3 of these edges,
  connecting the vertex, v, to vertices, r, s and t, are blue. (If not,
  exchange red and blue in what follows.) If any of the edges, (r, s),
  (r, t), (s, t), are also blue then we have an entirely blue triangle.
  If not, then those three edges are all red and we have an entirely red
  triangle. Since this argument works for any colouring, any K6 contains
  a monochromatic K3, and therefore R(3, 3) ≤ 6.

Wiki


Is it wise to bifurcate guitar mastery into a procedural component and a creative component?

Question: In math education, there are two (not necessarily dichotomous) camps:
(a) people who advocate drill and kill (which is a form of rote learning)
(b) people who advocate constructive learning
Now, I see benefits to both forms of learning, and in fact, there's quite a bit that is complementary between them, and I can see how the drill-and-kill method would help with other kinds of reflective or constructive learning.
I came across this app called Yousician, which helps with the drill-and-kill aspect of learning guitar, allowing users to focus on extended periods of deliberate practice. I have heard some reviewers belittle this app due to the fact that it doesn't really teach you the elements of music that have to do with forming some kind of creative output. It just helps you with the mechanics of playing guitar.
This got me wondering if it is possible to bifurcate guitar playing into the mechanical or procedural aspects, like fretting the right notes when sight-reading, playing scales and arpeggios well, etc., and the creative aspects like forming melody lines and licks, etc. Drawing a parallel to math education, I don't see how you can become proficient at higher levels of creative playing without nailing down the mechanical/procedural elements first.
So, an app like Yousician would be a great first step as long as it is followed up by regular guitar classes to bring the student up from the end of beginner level to advanced.
Am I right in my analysis?
Comment: Totally, utterly, and completely off topic: What a horrible app name.
Comment: By "forming melody lines and licks", "creative output", and "creative playing", do you mean expressive playing and interpretation of the sheet music, or do you mean composition and/or improvisation? I am incapable of playing some of my most advanced solo piano compositions and arrangements at full speed, even after 6 months of practice, so I strongly believe that you can become proficient at higher levels of composition and arrangement without nailing down the mechanical/procedural elements first.
Comment: @Dekkadeci: I meant composition and improvisation, mainly.
Comment: @Joebevo, no one is an advocate for "drill and kill." No one advocates killing a student's interest.
Comment: Is it wise? I don't know, but I have an opinion. Ask Mr. Owl.
Answer: I wouldn't compare rote learning in math with rote learning in music, because music is a temporal art and math isn't. For music you want to train reflexive movements so you can play without hesitation. Being in time is everything. But math doesn't really have that requirement. Certainly not with the split second timing of music.

...I don't see how you can become proficient at higher levels of creative playing without nailing down the mechanical/procedural elements first.

I disagree. Especially about setting up a dichotomy between creative/mechanical and higher/lower. Plenty of musical creativity is procedural. It's very pattern driven. The axiom of repetition with variation is basically a procedure statement. Mechanical performance matters are not all low level. Plenty of etudes are specifically about mechanical challenges and are for high level players.
I think performance (mechanical) and improvisation (creative) aspects should be studied hand in hand at the level appropriate for the player. Composition should be a third aspect of musical learning, which I think is distinctly different than the other two, and that throws out the notion of a bifurcation.
He is an example to illustrate what I mean. Playing DO RE MI surely is something to learn at the most basic level. Playing it mechanically is a matter of finger coordination and dealing with the instrument itself, keys, frets, valves, etc. As you develop the ability play DO RE MI in various positions and keys, with a few basic rhythms, you can add in some improvisation to turn rote patterns into a musical phrase. The path to doing that will by necessity introduce some compositional ideas like repetition to continue a line, repetition with variation to add variety, function of scale degrees, and structuring phrases with cadences. A lot of that could be first taught by example and then later learned more deeply in music theory study...

...start with a basic DO RE MI that the earliest student can play, repeat it to extend the phrase, vary it with a modified rhythm using some neighboring non-chord tones, vary the order of tones in the last bar to end on RE for a half cadence. Stuff like this should be improvised regularly from rote material through application of rhythm patterns and rudimentary harmony (essentially cadences which should be practiced in rote exercises as well.)
Depending on what the rote material is other improvisational exercises could be devised. But the point is the mechanical and creative are complimentary. They don't need to be separated into two apposed domains. Exercise both at an appropriate level.
Answer: This is a classic either or red herring of a question.  Do we do A or B, the two cannot be done together.  In fact this is not true at all.  One can combine both methods and take what is useful from both.
Mastering any musical instrument involves mastering your own body movements, the physics of the instrument, and your connection with the instrument.  You cannot effectively make up creative licks or learn songs if you do not have any physical connection to the instrument, if you cannot make a good sound from it.  Learning songs and being creative is the motive and if you don't do anything creative most students quit.  This is why I think the approach my teacher used was a good mix of both.  From day one there was introduction to reading and learning correct technique through exercises.  But he also said "what song do you want to learn" and created exercises from one or two simple riffs or licks from that song (it was a Kiss tune, and I was 7 or 8 years old).
If you look at the classical approach, refer to Pepe Romero's book or Carcassi, you will see a mix of "mechanical" exercises for both right and left hands in dependently, and performance pieces that uses the techniques taught in each section progressing in difficulty.
I would say the your "bifurcating" suggestion is exactly how the guitar is taught and has been for over 150 years.
Comment: Your teacher had the right approach in my opinion.  Teaching based around helping you learn to play something that interested you specifically gave you a more meaningful short term goal and allowed for you to experience a meaningful reward - learning to play something that you liked.  It is important for any student learning any instrument to receive some gratification early in the process by learning to play something that interests them.  You can learn the mechanics in the process of learning to play something that you actually want to be able to play.
Answer: This seems to be a long-winded way of saying "Should I practice my scales and other technical exercises aiming mainly for fluency, then practice 'pieces' thinking more of the artistic result?"   To which the answer, of course, is 'Yes'.
Answer: Why restrict this to guitar? It's appropriate for any muscal instrument. Let's face it, each one has different ways which are used in note production, so initally, at very least, each needs to be studied from a practical point of view - how to get some noise out of the darned thing!
That's at a very basic level, after which making music come from it is the next step. Scales, arpeggios, chords are all the musical basics - not particularly entwined with producing those sounds, but a by-product of that.
There are many players who don't know scales, etc., but something intrinsic in them  makes them natural players, who can and do produce great music, without relying on theory to do so. It may well cost them extra time working out what notes to use, but they get there. Maybe that's the trade-off - time spent learning scales, etc., versus time spent 'experimenting'?
So, there's no neccessity to split into one direction rather than the other, maybe for some that happens naturally, but - even being absolutely brilliant playing the technicals - scales, etc., does not guarantee the other part happens automatically. It may help, but doesn't do more than open the doorway to playing creatively. Rather like most of us can string a sentence together, but does that mean we could all be poet laureates?


ReactJS: passing function to child component results in TypeError

Question: I'm trying to pass a callback function from parent->child, but when the child component is rendered I get the error: TypeError: this.props.setCurrentWindow is not a function.
Parent component where I am trying to pass the function setCurrentWindow
class Parent extends Component {
constructor(props){
  super(props);
  this.setCurrentWindow = this.setCurrentWindow.bind(this);
}

setCurrentWindow(){
  console.log("called")
}

render(){
  return(
      <Child
        setCurrentWindow={this.setCurrentWindow}
      />)}
    }

child component where I am trying to call setCurrentWindow
class Child extends Component{
  constructor(props){
    super(props)
  }

  render(){
    return(

{this.props.setCurrentWindow()}}>
          {this.props.children}

    )}
  }

Why is setCurrentWindow not being recognized as a function here?
Comment: Perhaps you meant `{this.props.setCurrentWindow}` instead of `{this.props.setCurrentWindow()}`.
Comment: when I do that I get a compile error: `Expected an assignment or function call and instead saw an expression`
Comment: `onClick={this.props.setCurrentWindow}>`
Comment: If you update the code, you should explain that its not the same code giving you the error in question. Its very confusing to have to look through the questions edit history to see whats actually causing the error..
Comment: Ah that seems to work! I realize the error was in wrapping it in an anonymous function. In my full code I have multiple functions that are called on this onClick event, is there a way to call this within an anonymous arrow function ()=>{} , such that `onClick={()=>{this.props.setCurrentWindow(); this.setState({...}); this.myLocalFunction()}}`?
Comment: Why do you prefer to use the inline function? Its technically less performant and adds complexity to the JSX. But yes you can do that all inline
Comment: @BrianThompson my apologies with the edit, that was my mistake when copying the code over. My error was still the same however. Is there an easier way to do this as not an inline function?
Comment: @MuratYıldız I tried it and helped me discover what was really going on (see my answer to this thread). A very silly error that took up the better half of my day... thanks for the responses all
Answer: Please check this example where I only found the difference is to have child element like

Hello

 that was not in your code. other than this everything is working fine. When I click on the div, it writes called in console
export default class Parent extends Component {
    constructor(props) {
        super(props);
        this.setCurrentWindow = this.setCurrentWindow.bind(this);
    }

    setCurrentWindow() {
        console.log("called")
    }

    render() {
        return (
            <Child
                setCurrentWindow={this.setCurrentWindow}
            >

Hello

                </Child>
            )
    }
}

class Child extends Component {
    constructor(props) {
        super(props)
    }

    render() {
        return (

 {
                this.props.setCurrentWindow()
            }}>
                {this.props.children}

        );
    }
}

Answer: Try this:
parent.jsx:
class Parent extends Component {
  // code omitted for brevity

  handleSetWindow = () => {
    //
  };

  render() {
    return (

        <Child onSetWindow={this.handleSetWindow}
          />

    );
  }
}

child.jsx:
class Child extends Component {

  render() {
    return (

        <button onClick={() => this.props.onSetWindow()} >
          Set
        </button>

    );
  }
}

Comment: No explanation as to what your code does different from the problem code? A code block and "try this" is generally not viewed as a quality answer.
Answer: A stupid answer but the final solution here is that not all instances of my child components were being passed this.setCurrentWindow hence the undefined error. Durrr! Thanks for the responses!


Security implications of having less permission restrictions on a group than owner in Unix?

Question: I have an Ubuntu server that's currently hosting a WordPress site using an Apache web server, MySQL and PHP etc. Additionally I have configured VSFTPD and SSH to handle FTPS (implicit FTPS) and SFTP and I have created two accounts foo and bar for example. My web server is running under the www-data Unix user/group which I can see using the following command: sudo apachectl -S
User: name="www-data" id=33
Group: name="www-data" id=33

sudo ps -aux | egrep apache2 '(httpd|apache2|apache)' confirms this too.
The two user accounts foo and bar, foo is part of the sudo group and bar is a standard user.
Following WordPress' hardening guide Changing file permissions found here
"Typically, all files should be owned by your user (ftp) account on your web server, and should be writable by that account. On shared hosts, files should never be owned by the webserver process itself (sometimes this is www, or apache, or nobody user).
Any file that needs write access from WordPress should be owned or group-owned by the user account used by WordPress (which may be different than the server account). For example, you may have a user account that lets you FTP files back and forth to your server, but your server itself may run using a separate user, in a separate usergroup, such as dhapache or nobody. If WordPress is running as the FTP account, that account needs to have write access, i.e., be the owner of the files, or belong to a group that has write access. In the latter case, that would mean permissions are set more permissively than default (for example, 775 rather than 755 for folders, and 664 instead of 644)."
With that in mind, I have added foo as the owner and www-data as the group owner of the web root directory at /var/www/example.com using the following command:
sudo chown -R foo:www-data /var/www/example.com

I then set the file and directory permissions as detailed in the WordPress permissions guide using the following commands:
# Set permissions for directories
find "/var/www/example.com/" -type d -exec chmod 775 {} \;

# Set permissions for files
find "/var/www/example.com/" -type f -exec chmod 664 {} \;

# Set permission for 'wp-config.php' file
sudo chmod 440 "var/www/example.com/wp-config.php"

# Set all permissions on all 'htaccess' files
sudo chmod 664 "/var/www/example.com/.htaccess" "var/www/example.com/wp-admin/.htaccess"

When the foo user is accessing /var/www/example.com via SFTP or FTPS they are able to delete files, make new files and change permissions as expected being the owner.
This is fine if you only need one user to be able to edit files via FTP. However, in my case I need to enable full permissions to bar so they can fully edit files/directories too. From my understanding of Unix permissions, the way for multiple users to have full permissions on files/directories would be to add both users to a group and set the group owner to that group. For example:
sudo usermod -a -G www-data foo
sudo usermod -a -G www-data bar

# Re-set permissions on web root directory
find /var/www/example.com/ -type d -exec chmod 775 {} \;
find /var/www/example.com/ -type f -exec chmod 664 {} \;

However, to be able to give full permissions to foo and bar in the www-data group they would require their file permissions to be updated to 674 find /var/www/example.com/ -type f -exec chmod 674 {} \;?
This however breaks away from the recommended secure permissions WordPress have defined for files and directories. What I'm trying to understand and the questions I'm trying to ask are:-

Can I set owner to www-data and set foo as the group owner?
Can I lower the permissions for the new owner and heighten the
permissions for the new group owner?

In other words I'm swapping the owner and group owners around. Essentially the process in which the Apache web server is running (www-data) and the new owner of the web root directory would become the same account. What are the security implications of having the owner of the web root directories files/directories the same as the web server user it's running under?
Answer: It sounds like you've got a pretty good understanding of what the implications are. The goal of security recommandations is to give the lowest amount of permissions that allow your system to be maintained so that no data is needlessly exposed to reads or updates. The recommandations you're referring to try to give you a configuration that is best in most cases but might not be ideal in yours.
In this specific case, I'd advise against using group permissions to handle file accesses: it would also mean changing the umask used by vsftpd (-> might have side-effects if other users connect to other folders on your server) as well as default groups for your users and will be a pain to handle in the long run if you have to add an other user for example.
What you probably want to do instead is set-up user-specific (or global if they are your only ftp users) configuration in vsftpd to map both users to a third one when they access the server. By doing this, you can handle the permissions in your folder as if there is only one user accessing it (the new user).
Take a look at user_config_dir in VSFTD's MAN pages to set-up the directory as well as guest_username for the user mapping
Comment: Does OpenSSH have anything similar to this? SFTP is FTP over SSH and I primarily use SFTP over VSFTPD where I can.
Comment: I have never had to set-up such a thing for SSH. There might be a way with tunneling, but I would probably just grant the specific users I want to be able to access and the user with permissions on the directory a common group with a known common folder where they could share files and grant members of the group permission to execute `sudo su ` :/

It's clunky, but I don't know how to set-up something similar with SSH (or if it's possible) ; maybe wait for someone else to come.


How to use jQuery selector to filter jQuery isotope items case-insensitive (search)

Question: I'm playing around with jQuery Isotope and want to implement an element search.  When the user types into a text box, I change the filter option like this:
var newFilter = '[data-myAttr*="' + $('#mySearchBox').val() + '"]';
$('#myIsotopeContainer').isotope({filter: newFilter});

I'm using jQuery's attribute contains selector.  But it's case-sensitive, and I want to be case-insensitive.  How can I accomplish this?
I've looked at other questions and Google results that suggest using .filter(fn), but I don't have that much control with isotope.  I just give it a selector.
Comment: not sure where myAttr values come from but making them all lowercase and changing search value to lowercase seems to make sense
Comment: This is totally the easiest solution.  Post it as an answer and I'll at least upvote it.
Answer: From looking at Isotope's source, you should be able to pass a function, like this:
$('#myIsotopeContainer').isotope({ filter: function() {
        // case-insensitive pattern match:
        var pattern=new RegExp($('#mySearchBox').val(),'i');

        // test against 'data-myAttr':
        return pattern.test(this.attr('data-myAttr'));
    }
});

Isotope simply makes a .filter() call to do it's own filtering.  Give it a try and see what happens.
Comment: +1 Adding a function for a filter works great.  I needed to filter based on an attribute of child.
Answer: use lower case as protocol for all attributes and then change user input to lowercase
Answer: I want to give an answer that is related to this question for people like me who are doing this a little bit differently. I wanted to search any text in the whole element (or any children of the element), and not just an attribute. If you are using the :contains selector and want it to be case-insensitive, you should extend JQuery as outlined in this bug report. I'm posting the code below for convenience:
$.extend($.expr[':'], {
  'containsi': function(elem, i, match, array)
  {
    return (elem.textContent || elem.innerText || '').toLowerCase()
    .indexOf((match[3] || "").toLowerCase()) >= 0;
  }
});

Now you can use the JQuery like you would have using :contains('SomeString') but now use your new extended :containsi('SomeString')


Meeting Schedule Variant Advice

Question: I have a specific scheduling problem I am interested in. I wish to schedule n meetings (hereafter 2 for simplicity) that maximizes the number of people able to attend, with j time slots and m people. In trying to format this as an optimization problem I came up with the following:
$$argmin_{x} \frac{1}{2} \sum^m (1 - \sum^j c_{l,i} x_i )(2 - \sum^j c_{l,i} x_i )$$
$$st \sum^j x_i = 2$$
The vector c represents the availability of each person l for the time slot i, and is 1 if available for that spot and 0 otherwise. X is the current assignment of meetings to slots, and should some to n (here 2). Therefore, $\sum^j c_{l,i} x_i$ represents the number of scheduled meetings that individual l will be able to attend. The polynomial in the cost ensures that the cost for individuals able to attend one or both of the meetings have cost 0 and those who can attend 0 meetings have cost 2.
My question is whether there is a more efficient representation of this problem, and if not is there a practical advice for implementing a solution to this optimization problem?
Comment: http://or.stackexchange.com
Answer: You can model the problem linearly.  Let binary variable $y_l$ indicate whether person $l$ can attend.  Then the problem is to maximize $\sum_{l=1}^m y_l$ subject to:
\begin{align}
\sum_{i=1}^j x_i &= n \\
y_l &\le \sum_{i=1}^j c_{l,i} x_i &&\text{for all $l$} \\
x_i &\in \{0,1\} &&\text{for all $i$}\\
y_l &\in \{0,1\} &&\text{for all $l$}
\end{align}

Meeting Schedule Variant Advice


Finding all matches of a certain pattern in a string using regex

Question: So Im pretty new to regex, I already use it in my project succefully, but only to find one specific match.
Now im trying to find all matches of a certain url pattern inside an html source code.
The urls are like this:
Link example 1: https://clips.twitch.tv/KindYummyCarrotPeteZaroll?tt_content=video_thumbnail
Link example 2: https://clips.twitch.tv/AmericanOilyMeerkatSaltBae?tt_content=video_thumbnail
I have this code searching for the links:
       MatchCollection matches = Regex.Matches(source, @"^(https://clips.twitch.tv/)+(.*?)+(video_thumbnail)$");

        if (matches.Count <= 0)
        {
            MessageBox.Show(matches.Count.ToString() + " urls found");
        }
        else
        {
            MessageBox.Show(matches.Count.ToString() + " urls");
        }

My first instinc was that the source string was somehow wrong, so I tried this regex in this string:
string source = (" adsfgsdfg adsfg assdfg https://clips.twitch.tv/KindYummyCarrotPeteZaroll?tt_content=video_thumbnail dfgsdfgszdfg asdfg https://clips.twitch.tv/AmericanOilyMeerkatSaltBae?tt_content=video_thumbnailsadfgdf g");

I have tried also this regex:
Regex.Matches(source, @"^(https://clips.twitch.tv/)+([a-z0-9A-Z]{1,100})+(\?)+(tt_content=video_thumbnail)$");

But the result is always 0 urls found.
What im doing wrong?
Comment: Try taking out the `^` and `$`, and wrapping the entire pattern in parenthesis.
Comment: @gunr2171 Why do you suggest *wrapping the entire pattern in parenthesis*? There is no need here, as OP is *extracting* the text. Unless you are splitting, but it is not the case.
Comment: @WiktorStribiżew, you're right. I'm used to using a capture group for the text I want to extra, which in this case would be the entire pattern. But the resulting object will give you that information without the need for the capture group.
Comment: @gunr2171 Thanks a lot, I didnt know ^ and $ where so the string matched the regex perfectly.
Answer: Your regex pattern had unescaped characters in it. The . has a special regex uses, so to indicate that you just mean an actual period they must have a backslash before them. Try this:
(https://clips\.twitch\.tv/)(?:(?!http).)*?(video_thumbnail)

Note also that the ^ and $ are gone; if you include those, it will only match if the entire string matches.
Comment: `/` should not be escaped in .NET regex, it is not a special character in any regex, BTW. It may be used as a delimiter, but .NET regex do not use delimiters.
Comment: @WiktorStribiżew The regex parser I use (regex101.com) throws an error if `/` is not escaped. I should double check to see if C# requires this.
Comment: regex101.com does not support .NET regex, why mention it? And it [supports unescaped `/`](https://regex101.com/r/iH8GCx/1).
Comment: @WiktorStribiżew you are right. I used the site out of habit and forgot about the difference. I have edited the post.
Comment: Well, mind that `(...)+` repeats the whole grouping construct pattern 1 or more times, and `(.*?)+` makes too little sense. Note that `.` matches any char but a newline, so the pattern may overmatch, (i.e. match several `https` links on a line starting with the first, and ending with the one that has `video_thumbnail` matching all other URLs on its way. You might at least change `(.*?)+` into `(?:(?!http).)*?`. But it is not really clear here.
Comment: @WiktorStribiżew thank you for the suggestion, you raise a lot of good points here and I've added your change. My testing shows that it's made it less likely to put two links together, as you suspected.
Comment: Taking out the ^ and $ worked, I didnt know it was so the regex match the entire string!