Isomorphism from a subset of $\mathbb{R}^n$ to the space $\mathbb{R}^{n-1}$

Question: Let $I \subset \mathbb{R}^n$ be non-empty such that $I$ is in general not a vector subspace of $\mathbb{R}^n$, i.e. it is not necessarily closed under addition and multiplication by a scalar. We define a projection from $I$ to $\mathbb{R}^{n-1}$ by $\alpha(\boldsymbol{x}) = (x_1, \ldots, x_{n-1})$, where $\boldsymbol{x} = (x_1, \ldots, x_n), \ \boldsymbol{x} \in I$.
We know that the following property holds for $\alpha$, which follows from the properties of $I$: for $\boldsymbol{x}, \boldsymbol{y} \in I$, if $\alpha(\boldsymbol{x}) = \alpha(\boldsymbol{y})$, then $\boldsymbol{x} = \boldsymbol{y}$.
The paper I read shows that $\dim(I) = n-1$ and thus the Lebesgue measure of $I$ in $\mathbb{R}^n$ is $0$. Its reasoning is that $\alpha$ is an epimorphism since it is a projection and a monomorphism by the aforementioned property, so it is an isomorphism.
My questions are:

Which definition of an isomorphism is used here at all? (I am mostly familiar with the definition of an isomorphism between two vector spaces).
Is it true to state that $\alpha$ is an isomorphism because it is a bijection (i.e. leaving out the notions of  epimorphism and monomorphism)?
If no, which definitions of epimorphism and monomorphism are used here and why these two properties imply that $\alpha$ is an isomorphism?

References to definitions and theorems in books are also appreciated very much. Thank you!
Answer: You can think of $I$ as the graph of a function $$f:\mathbb{R}^{n-1}\to \mathbb{R},\: (x_1,\ldots,x_{n-1})\to f(x_1,\ldots,x_{n-1}).$$ That is,
$$I=\{(x_1,\ldots,x_n)\in \mathbb{R}^n:x_n=f(x_1,\ldots,x_{n-1})\}.$$ Assuming $f$ is continuous then isomorphism should mean homeomorphism. If $f$ is not continuous, then isomorphism would be just bijection.
Comment: Thank you for you comment. Would it help knowing that $I$ is a level set of a function $F: \mathbb{R}^n \to \mathbb{R}$ which is strictly increasing in each component (i.e., $I = \{ \boldsymbol{x} \in \mathbb{R}^n: F(\boldsymbol{x}) = q \}$, where $q \in F(\mathbb{R}^n))$? This is the only assumption made in the paper.
Comment: What is the paper you are reading?
Comment: It is in Italian...
Comment: Is it available online?
Comment: I only have a scanned version from the author: https://www.dropbox.com/s/2w95ixtoklrn00c/Insiemi%201990.pdf?dl=0. The corresponding proposition is named Property 3 ("Proprieta 3").
Comment: To me it is talking of *morphism of sets, that is: monomorphism means injective, epimorphism means surjective and isomorphism means bijective. There is no additional structure on the proof.
Comment: This is what puzzles me. If they are talking about isomorphism of sets, then it does not imply anything about the dimension of $I$ (does it?). And they are certainly not talking about isomorphism of vector spaces, since $I$ is not a vector space. So I don't get what they are talking about...
Comment: I agree with you. The dimension is used later when assume that $I_q$ is convex. In this case it makes sense, because it is an affine space. But, to me, it is unnecessary in Propieta 3.


Custom exposed filter for year in date field with ajax

Question: I am trying to create a custom exposed filter which would be a select field with years (2015-2025).
This would filter the result with the year of the date they are created.
I followed this tutorial https://www.flocondetoile.fr/blog/filter-content-year-views-drupal-8
But here there is no solution for ajax submission, so the page does not refresh and the filter does not apply.
Currently I have this year as a contextual filter and the form field in the hook_form_views_exposed_form_alter():
$options = [
    'all' => t('- All -'),
    '2015' => '2015',
    '2016' => '2016',
    '2017' => '2017',
    '2018' => '2018',
    '2019' => '2019',
    '2020' => '2020',
    '2021' => '2021',
    '2022' => '2022',
    '2023' => '2023',
    '2024' => '2024',
    '2025' => '2025',
  ];

  $form['year'] = [
    '#title' => t('By year'),
    '#type' => 'select',
    '#options' => $options,
    '#size' => NULL,
    '#default_value' => 'all',
  ];

Is there a possibility for the filter to work with ajax submission?
Comment: You can try create views custom filter https://www.webomelette.com/creating-custom-views-filter-drupal-8
Answer: You can use this custom filter to filter by year:
https://github.com/DarkteK/d8-views-custom-filter/tree/master/d8_filters
Just change the years you want to use in the file 'ViewsYearsFilter.php'
This will work with Ajax
Answer: I believe Views Better Exposed Filters can achieve this: What else can I do with BEF?: Provide instant feedback by updating the View using AJAX whenever an exposed filter is changed


Overriding destination directory from ROBOCOPY Job file?

Question: I am using Robocopy for backing up my project directories to an external disk, and it works like a charm.
Except for one little issue: sometimes, I wish I could override the destination directory which I specify in my Robocopy Job file (myproject.rcj) to send the files somewhere else.
So if I have this in my myprojects.rcj:
:: Robocopy Job MYPROJECT.RCJ

:: Source Directory :
 /SD:d:\MyProject :: Source Directory.

:: Destination Directory :
 /DD:f:\MyDefaultDestination :: Destination Directory.

is there any way I can instruct Robocopy to use a different destination when executing it using a job?
So I execute Robocopy like this:
robocopy /job:myproject.rcj

and I wish I could override the default destination directory by using:
robocopy /job:myproject.rcj /DD:X:\OtherDestination

but that doesn't seem to work.....

ERROR : Invalid Parameter #2 :
  "/DD:X:\OtherDestination"

Any ideas??
Comment: Do you need this to use just the .rcj options?  You could always make a .bat that takes an argument for `$destinationDIR` and passes it to robocopy.
Answer: I was able to do this with the /LOG parameter by simply removing it from the job file. I didn't try it with /SD and /DD, but I'd be willing to throw a fish back that it'd work.
Comment: I confirm that @InteXX is right.
If you remove the /SD and /DD sections from the job file you will be able to specify them on the command line, which means you can change any of them according to your heart's desire. Of course, this means that you will always need to specify the source and the destination on the command line, instead of the job file.


Can a subset of a group, which does not contain the identity element, be a group

Question: Let $G$ be a group. Let $1 \in G$ be the identity element of $G$. Let $S \subset G$, with $1 \notin S$. Is it possible for $S$ to be a group, with some other element playing the role of the identity in $S$?
Comment: Well, $xy = x$ in a group implies $y = 1$. So it seems like the answer is no.
Comment: Indeed, the identity is the only idempotent in a group (idempotent$\Leftrightarrow g^2=g$) but here you'd need two.
Answer: A subset $S$ of $G$ can not be a subgroup with respect to the multiplication
in $G$ since the element $1$ is unique and is not in $S$. (I think Dylan explained this well in his comment).
If you are asking if $S$ can be a group with different multiplication
than the multiplication in $G$ then take for example $S=\{g\}$ for
some $g\in G$ and define $g\bigstar g=g$.


Cordova 6.0.0 Android: INSTALL_FAILED_VERSION_DOWNGRADE

Question: This is just an answer to my own question
iOS runs fine, but when I tried running Android I get the following error:
ERROR running one or more of the platforms: Failed to install apk to emulator: pkg: /data/local/tmp/android-debug.apk
Failure [INSTALL_FAILED_VERSION_DOWNGRADE]

You may not have the required environment or OS to run this project

I've tried removing and re adding the Android platform; doesn't work.
When I tried downgrading to Cordova 5.1.1 with:
sudo npm install -g email@example.com

it works.
Answer: INSTALL_FAILED_VERSION_DOWNGRADE is an ADB error that means you're trying to install an older version than what's already on the device. So check your app versions in your AndroidManifest.xml or gradle files, that's what it's checking - package version. Your new package needs to be either the same, or a newer (larger) version code.
You could also just delete the existing app off the emulator before you deploy again.
Comment: (BTW this is a general Android thing, nothing to do with Cordova per se.)
Comment: Thanks, that also worked!  I thought they were referring to downgrading to a previous version of cordova because I made the project when 5.1.x was the latest.
Comment: No problem! If it helped, an answer vote is always appreciated :)


Commandline method to switch network connection on and off in OSX

Question: I frequently tether using my iPhone using a Wifi Hotspot and every once in a while the connection stops working. To fix this, I have to enable and disable the hotspot and then enable/disable the Wifi on the MBP (OSX 10.8.3).
I was hoping to automate this on the MBP. Would you know of a command line way to do this ? The command should switch the wifi off (if it's on) and then switch it back on (slightly different from simply toggling the Wifi connection).
Thanks !!
Answer: You can do this with ifconfig:
$ sudo ifconfig en1 down    # take network interface down
$ sudo ifconfig en1 up      # bring it back up again

This assumes that your WiFi network is on en1 - obviously change this to en1 or en2 or whatever, as needed.
Comment: Awesome, this totally works : `sudo ifconfig en1 down && sudo ifconfig en1 up`. Thanks !!


Creating an object that has all the properties of two other objects?

Question: Consider a sports club situation.
A club can have a Club manager and 1 or more Coaches (1 coach per team)
So, here is an example of the Manager and Coach classes.
Class ClubManager
{
    public void RegisterMember()
    {
        // code for registering a member..
    }
}

Class Coach
{
    public void DeviceTeamFormation()
    {
        // code for making a team formation..
    }
}

My issue is, how can I have a Club manager who is also a Coach? because there are sports clubs with this situation.
Appreciate any and all help.
Thanks guys.
Comment: You seem to be wanting multiple inheritance, which is not supported in C#.
Answer: No, you cannot do this with classes. Interfaces however get you in that direction.
On the other hand, you may want to add another level of indirection and separate the manager and coach roles from persons, so that you can assign each role to a person (which may also be the same person).
Comment: +1 This is the correct solution; Coach and Manager are ROLES that people play, not kinds of people. More details below.
Answer: Lucero's second paragraph is the correct approach. Coach and Manager are not kinds of people, they are roles that people play. Theoretically the same person could be a TeamPlayer, TeamCaptain, Coach, Manager, and WaterBoy!
So what you want is composition, not inheritance. For example:
SportsClub myClub = new SportsClub();
Person Bill = new Person();
myClub.Manager = new Manager(Bill);
myClub.Coach = new Coach(Bill);

Answer: Being a Coach and being a ClubManager are not inherent attributes of this person.  They are roles that the person has taken on.  As such I would say that the person object (or whatever it is you want to call it) should be assigned roles.  Those role/ability objects would then delegate those methods.
So it might look like this:
Person joe = new Person("joe");
joe.setClubManager(true);

joe.getManagerAbilities().RegisterMember();

Hard to know what is right without a lot more information about your problem, but maybe this will get you thinking along some different line.
Comment: Your suggestion makes logical sense but I am very new to this concept of roles and this technique i.e. I have never used it in my life.

Are you able to give me some suggestions as to where to start on understanding how to use this technique to solve the problem?appreciate it, ty.
Comment: Yeah... it's kind of something I pulled out of my ass.  Basically I was thinking of mix-in's from Ruby and composition like Robert Davis mentions in here.  Roles/abilities seemed like a good way to divide up your problem and fake our way to mix-ins.

Basically my thought process was that the people in your system aren't 'coaches'.  They are people who sometimes have coaching responsibilities (that is they may not be a coach in the future, then you have to create a whole new object).  From that it seems logical that these people have some attribute that makes them a coach.
Comment: continued... So from there we have a couple of options:  1) make new objects that contain a person like Steven A. Lowe mentions or 2) make new role/ability/responsibility objects that are attributes of the person.  The second seemed to mimic reality a bit more closely so I went with that one.
Answer: Multiple Inheritance is what you are looking for. Unfortunately, this is not currently supported in C#. I did not see it come up in the 2010 version either.
You can implement multiple interfaces, but you cannot inherit from multiple classes.
Comment: It isn't something that is ever likely to be added to C# because of all of the pitfalls it creates. http://en.wikipedia.org/wiki/Multiple_inheritance#Criticisms
Answer: As Chinmay Kanchi noted, C# does not support multiple inheritance; however, you can inherit from a type and implement as many interfaces as you like.
public interface ICoach {
}

public class ClubManager : SomeType, ICoach {
}

Answer: I would use delegation rather than inheritance and use the Composite Pattern instead. (http://en.wikipedia.org/wiki/Composite_pattern)
Answer: you can do this but with following procedure as C# does not support Inheritance through classes
Interface IClubManager
{
  public void RegisterMember();
}

Interface ICoach
{
   // code for making a team formation..
}
class SomeDesignation : ICoach, IClubManager
{
}

Answer: As others have noted, you can't do that with classes, although you can do it with interfaces, which has the disadvantage that you have reimplement the interface each time. One way around that is with mixins: Is it possible to implement mixins in C#?.
Answer: You can not have exactly what you want - multiple inheritance is not supported in C#.
Along with the other proposals about using interfaces (with their limitations), you can possibly re-think the object model at all.
If you separate your data structure (classes), so the Coach class and the ClubManager class has property Person, they you will not "duplicate" the person's data. And you can have factory methods to create Coach out of person, and/or ClubManager out of person.
Another option would be to have "InRole" functionality, which says what role a person can have, and the Person class will have both methods you require, but each one of them may throw an exception if the person is not in the right role to perform the operation.
Or, you can inject "roles", and use some form of indirection to access the specific role's functionality.
Answer: Here's the first idea that popped into my head:

Create a ClubManagerCoach class, or something to that effect that has logic for both managers and coaches.
Create interfaces for IClubManager and ICoach.  Use those interfaces in place of ClubManager and Coach.
Make ClubManagerCoach implement IClubManager and ICoach.
Answer: I think the best compromise you'll get in this case (and this is a debated topic, of course) is to create something along the lines of a ClubManagerCoach class that exposes ClubManager and Coach properties.


Git commit with SSH asking for email

Question: I am trying to commit to my github repository but I keep getting an error message asking me to identify myself by logging in through email and name. I'm using ssh for the commit, my sshconfig and keys are correctly configured. I have also checked the gitconfig file and they seem to be correct as well.. Any ideas?
###Gitconfig file
[core]
    repositoryformatversion = 0
    filemode = false
    bare = false
    logallrefupdates = true
    symlinks = false
    ignorecase = true
[remote "origin"]
    url = email@example.com:imran1005/testhomere.git
    fetch = +refs/heads/*:ref
[branch "master"]
    remote = origin
    merge = refs/heads/master

###Error msg on console win7 cmd while executing git commit:

*** Please tell me who you are.
Run
    git config --global user.email "email@example.com"
    git config --global user.name "Your Name"
to set your account's default identity.
Omit --global to set the identity only in this repository.
fatal: unable to auto-detect email address (got 'TestUser@Asus.(none)')

Comment: Just follow the instructions in the error. Apart from being logged in to Github, your git commits should tell who you are. So, fill in those two lines starting `git config` with your details.
Comment: That means your credentials are not set in git config. You need to set email, name & password for your git config.
Comment: git config --global user.email

What output do you get?
Comment: I get an empty output
Comment: I'm using SSH, authentification with RSA keys. I don't have to set email name and password while using commit with ssh
Comment: verify that your URL is set to SSH.

git remote -v
Answer: As the error message states, you need to set user.email and user.name git configs. This information is stored in the commit, git does not work without them.

my sshconfig and keys are correctly configured

This is irrelevant, ssh keys are used when you are pushing existing commits to some remote, not when creating new commits.
Comment: Thank you. Indeed you're right, even with SSH commit, email should be configured!

Git commit with SSH asking for email


Analytic Geometry: Distance between a point and a line.

Question: Get the equations of both lines going through $0$ which have a distance of 5 from the point $(1,7)$.
How to handle this problem? We have this formula:
If line $l$ is $ax+by=c$, distance $ P(x,y) $ to line $l$:
$ \dfrac{|ax+by-c|}{\sqrt{a^2+b^2}}$
Answer: Find the circle with radius $5$ and center $(1,7)$ and then find the lines passing through the origin and which is a tangent to the circle by using the formula $y = mx+r\cdot\sqrt{m^2+ 1}$ and as it passes through tho origin $r.\sqrt{m^2+1}=0$  so your line now becomes $y=mx$ if distance of this line from $(1,7)$ is $5$, then you get a quadratic in $m$.
Solving this you can find out the values of $m$ and substituting in the line equation, we get the required equation.
Comment: @Amzoti .... This is an answer. no tags needed because the question is already tagged.
Answer: First find the equation of the circle of radius 5 around the point. Then the lines you are looking for are the tangents of this circle which pass through 0.
Answer: Here the lines pass through the origin $(0,0),$ so $c=0$
$$\frac{|a\cdot 1+b \cdot 7|}{\sqrt{a^2+b^2}}=5$$
Squaring, $(a+7b)^2=25(a^2+b^2)$
$\implies 24a^2-14ab-24b^2=0$
Solving for $a, a=\frac{4b}3$ or $-\frac{3b}4$
If $a=\frac{4b}3, \frac{4b}3x+by=0\implies 3y+4x=0$  as $b\ne 0$
If $a=-\frac{3b}4, -\frac{3b}4x+by=0\implies -3x+4y=0$  as $b\ne 0$

Here the lines pass through the origin $(0,0),$
the equation of the required line can be $y=mx$ where the gradient $m$ is finite, as the line is not the Y-axis.
So the distance of $(1,7)$ from $mx-y=0$ is $$\frac{|m\cdot 1-1\cdot 7|}{\sqrt{m^2+1}}=5$$
Squaring we get, $(m-7)^2=25(m^2+1)$
$24m^2+14m-24=0\implies m=-\frac  4 3$  or $\frac 3 4$
Comment: I understand what you're doing up until 'solving for a'.. how did you do that?
Comment: @ZafarS, it's a quadratic equation of $a$. You can put $a=b\cdot c$ and eliminate $b$ as $b\ne 0$
Comment: Might be easier to work with $y=mx$. Note that the line cannot be vertical, thus you can work with the slope formula... Then it is easier to work with only 1 variable...
Comment: My plan was originally to find the line through the points $(0,0)$ and $(1,7)$..
Comment: @N.S., I just wanted to keep the solution generic. Clearly, the line is not the Y-axis, so we can go with $y=mx$
Comment: I wonder why both answers had a $-1$, they are both very good ideas....
Comment: @N.S., should down-voting not mandate the explanation?
Comment: @labbhattacharjee Well it would definitely be nice (and proper) if whoever downvoted explains why.
Comment: How do you get to the equation $$\frac{|m.1-7|}{\sqrt{m^2+1}}=5$$? I literally haven't got a clue what you've done..
Comment: @ZafarS Well he just used the formula YOU posted ;) Note that there are TWO solutions in there, don't read them as one...
Comment: Yes but why the -7? Why the 1xm? why the root of 1?
Comment: @ZafarS The equation of a line of slope $m$ through the origin is $y=mx$. This means $mx-y=0$. So your $a$ is $m$ and your $b=-1$.
Answer: Here is another approach, but I think this is more geometric than analytic geometry.
Let $Q(x,y)$ be the leg of the perpendicular from $P$ onto $l$.
Then, $PQ=5$ thus
$$(x-1)^2+(y-7)^2=25$$
Also, by the Pytagorean Theorem we have
$$PQ^2 +QO^2=PO^2$$
or
$$25+x^2+y^2=50$$
The two equations yield
$$x^2+y^2=25$$
$$2x+7y=50$$
solving for $x$ in the second equation and plugging in the first gives a quadratic, so the rest is easy.


Matrices - Find the rank and determine if its invertible

Question: Find the rank of $A = \begin{bmatrix}2&1&-4\\-4&-1&-6\\-2&2&-2\end{bmatrix}$ and explain why $A$ is not invertible.
What I have done is:
Guass-Jordan Elimination: $$\begin{bmatrix}1&0&-1\\0&1&-2\\0&0&0\end{bmatrix}$$
Therefore, I found the $rank(A) = 2$
Explanation why $A$ is invertible:
A matrix i invertible if and only if it does not have $0$ as any number such that a given matrix minus that number times the identity matrix has a $0$ dominant. Since this does not satisfy $A$, $A$ is not invertible.
Am I right with both answers? My explanation on whether or not $A$ is invertible is not strong, I feel.
Answer: In particular for matrices 3x3, given
$$A=\begin{bmatrix}a&b&c\\d&e&f\\g&h&i\end{bmatrix}$$
The inverse is
$$A^{-1}=\frac{1}{det(A)}\begin{bmatrix}ei-fh&ch-bi&bf-ce\\fg-di&ai-cg&cd-af\\dh-ge&bg-ah&ae-bd\end{bmatrix}$$
and since the determinant of a matrix without full rank is $0$ you have that $\frac{1}{det(A)}"=" "\frac{1}{0}"$ and thus the inverse does not exist :-)
Answer: You are right about the rank. I do not know what a dominant is. For the second point I would say that a square matrix is invertible if and only if the determinant is nonzero or, equivalently, if and only if it is of maximal rank. Since your matrix is not of maximal rank it is not invertible. Otherwise, after you have reduced the matrix to upper triangular form via Gauss elimination, you can compute the determinant multiplying the elements on the diagonal: from this you see that the determinant is zero.
Answer: you're right, you can use that a matrix is invertible iff it's rank is full.


Cordova/Phonegap iOS: no access rights for Facebook Connect plugin

Question: I'm trying to set up Facebook login for my app using this plugin:
https://github.com/Wizcorp/phonegap-facebook-plugin/tree/master/platforms/ios
I follow the steps and get error messages every time.
Here's a ss of the whole process:
http://xu.cooljon.com/pic/terminal.png
What am I doing wrong to get these errors and what can I do to fix them?
I want to build profiles off of the Facebook authoization.
Comment: what error message you got my friend?
Comment: it's in the screenshot I attached (by link)
http://xu.cooljon.com/pic/terminal.png
Answer: Try install like this one.
<code>cordova plugin add https://github.com/Wizcorp/phonegap-facebook-plugin --variable APP_ID="XXXXXXXXXXXXXXX" --variable APP_NAME="cordovasocial"
</code>
Comment: I had to install with sudo. that seemed to do it.


Como posso transformar uma variável(0-10) em 3 categorias?

Question: A variável GLEASON da base de dados está de 0 a 10. E eu queria transformar esta variável em 3 categorias, por exemplo: 0-4: pouco agressivo, 5-7: agressivo intermedio e 8-10: muito agressivo. Em programação R.
Obrigada
Answer: Outra opção é usar a função cut. Utilizando o data.frame criado pelo @Daniel:
dados <- data.frame(GLEASON = sample(0:10, 50, replace = TRUE))
dados$categorias <- cut(dados$GLEASON, c(0,4,7,10),
   include.lowest = T, labels = c("pouco agressivo",
   "agressivo intermedio","muito agressivo"))

O primeiro argumento é o vetor numérico, o segundo é o vetor de cortes, o terceiro é para indicar se inclui o valor mais baixo, 0, e último são as categorias que você quer.
Comment: A vantagem aqui é que nesse o tipo da coluna `categorias` será  [*Factor*](https://www.stat.berkeley.edu/classes/s133/factors.html) ao invés de `Character`. Factors são mais econômicos em termos de memória.
Comment: Você também pode adicionar o argumento ordered_result=TRUE para ordernar as categorias, dependendo da análise que quer fazer.
Answer: Uma forma simples e de fácil compreensão é utilizando os vetores lógicos de análise de dados. Os vetores geram valores TRUE/FALSE que validam a execução seguinte. Neste exemplo, os dados estão num data.frame e ao fazer a primeira verificação automaticamente criamos a variável categoria.
dados <- data.frame(GLEASON = sample(0:10, 50, replace = TRUE))

dados$categorias[dados$GLEASON <= 4] <- 'pouco agressivo'
dados$categorias[dados$GLEASON >= 5 & dados$GLEASON <= 7] <- 'agressivo intermedio'
dados$categorias[dados$GLEASON >= 8] <- 'muito agressivo'

head(dados)
 GLEASON           categorias
       9      muito agressivo
       1      pouco agressivo
       8      muito agressivo
      10      muito agressivo
      10      muito agressivo
       6 agressivo intermedio

Comment: Obrigada, eu tentei fazer "e" com "&" mas estava a fazer de maneira errada. :)


Examples of groups satisfying that its number of conjugacy classes is less that the number of conjugacy classes of centain subgroup

Question: If $G$ is a group define $r(G)$ to be the number of conjugacy classes of $G$. I'm trying to construct simple examples of groups $G$ with at least one subgroup $H$ such that $r(H)>r(G)$. I won't find simple examples of this, so I'd appreciate some hints.
Answer: Let $D_n$ denote the dihedral group of order $2n$ (I'm specifying, since the notation is never consistent); the subgroup of rotations $C_n \subset D_n$ has $n$ conjugacy classes, so we count the conjugacy classes of $D_n$.
If $n$ is odd, then reflections form a single conjugacy class, and the rotations pair up, excepting the identity, so there are $\frac{n+3}{2}$ conjugacy classes. This is less than $n$ when $n \ge 5$.
If $n$ is even, then reflections form two conjugacy classes, and the rotations pair up, excepting the identity and $180^\circ$ rotation, so there are $\frac{n+6}{2}$ conjugacy classes. This is less than $n$ when $n \ge 8$.
Answer: If you can find "large" abelian subgroups, this will work -- they just need to have more elements than the full group has conjugacy classes.
It turns out this is kind of hard for symmetric groups, at least if I'm being lazy. The symmetric group $S_{n^2}$ of degree $n^2$ has an abelian subgroup of order $n^n$ ($n$ copies of the cyclic group of order $n$). Consulting OEIS, it turns out $S_{16}$ has only $231$ conjugacy classes, while $4^4 = 256$, yielding an example. A similar thing happens with $S_{25}$, which has $1958$ conjugacy classes and an abelian subgroup of order $5^5 = 3125$. It would be interesting to know whether this happens for all $S_{n^2}$ where $n \geq 4$, and I suspect it does, but I have no idea.
Comment: Thanks! This is a nice mine of examples. I think the general case for $n \geq 4$ could be worked out by using the asymptotic results of Hardy about the partition function. Still, I'm not sure.


Using SMOTE with grouped, paneled, or categorical data?

Question: Let's say that I am building a classifier on imbalanced data. A sample of the data set looks like:
Person   Time1    Time2    Time3    Injury
A        3        2        3        0
A        3        3.4      1.2      0
A        2        2.1      2.1      1
B        0        2        2        0

etc. I want to use Person, Time1, Time2, and Time3 as features to classify Injury (this is just an example I'm making up). Now let's say that in my target Injury I have value counts of:
Label    Count
0        9000
1        50

I want to use SMOTE to both under-sample the majority class and over-sample the minority class. This is easy enough if I'm only using the numerical variables, but what do I do in this case where I have a grouping variable?
It theoretically is OK to have multiple positive Injury cases within any given Person. But how do I setup the SMOTE algorithm such that when it finds the kNN's and then generates the synthetic points between the kNN's and itself, that it retains the particular Person label of that data point?
Comment: Are you sure you need to use SMOTE at all? It's really hard to recommend the best way to do something [when there's a strong argument that you shouldn't be doing it in the first place.](https://stats.stackexchange.com/q/357466/247274)
Comment: I strongly suspect one has to customise the original SMOTE algorithm to do this. Notice that distances are not well-defined between categorical variables so the concept of nearest-neighbours is murky. You could start having custom distance metrics (say some hybrid of Mahalanobis and Hamming but that a horrible exercise) My first approach would be not to use resampling to balance the dataset but actually focus on proper metrics that would adequately penalise the misclassification of minority class examples as well as classifier who do not do strong parametric assumptions. (Good basic question.)
Answer: It's very late but SMOTENC() is the correct method to do the oversampling for the mixture of categorical and numerical variables.
imblearn.over_sampling.SMOTENC


Getting number of bytes of a bitmap

Question: Goal is to show progress of jpeg encoding from bitmap. I have couple of bitmaps that need to be encoded. So I get the total number of bytes as was suggested here:
for (var i:int = 0; i < bitmaps.length; i++)
{
    bmp = bitmaps[i];

    total_bytes += bmp.getPixels(bmp.rect).length;
}

Then I'm trying to show progress when doing asychronous encoding. I get a ProgressEvent which gives me bytesLoaded. So I calculate the progress like so:
total_loaded_bytes += event.bytesLoaded;

var percentage:int = ((total_loaded_bytes / total_bytes) * 100);

However, total_bytes does not add up to total_loaded_bytes. Total bytes loaded is way highter.
Comment: Why don't you use the `event.bytesTotal` instead of `total_bytes`?
Comment: `event.bytesTotal` is just for specific image that is getting encoded at the moment. I have couple of images. So I need to get total size of images, add up total loaded and divide whatever is loaded by total.
Answer: A wrong approach to use bytesLoaded property. This is not to be blandly added up, as this contains the total of already loaded bytes bu the Loader object that issued the event. And a wrong approach on getting total bytes too, you need to use event.bytesTotal from within the progress event listener, since you are loading bytes, not pixels. Even if you are uploading. Also, the exact progress may be totally unavailable for asynchronous encoding, you are only displaying the uploading/downloading progress.
Update: to receive an accumulated progress, do something like this:
var loaders:Array=[]; // array of loaders. Fill manually
var progress:Array=[]; // fill with zeroes alongside loaders, should be same size
function updateProgress(e:ProgressEvent):void {
    var loader:Loader=e.target as Loader;
    if (!loader) return; // or skip type coercion, we just need the reference
    var i:int=loaders.indexOf(loader); // now get an index from array
    if (i<0) return; // not found, drop it
    progress[i]=e.bytesLoaded; // and update progress array with new value
    // now sum up progress array and divide by aggregated bytesTotal
    // this one is up to you
}

Comment: First, say you are uploading a something that's 1024 kilobytes long, but the channel is too small so the throughput is 1 kilobyte per frame. You will receive 1024 events with 1024*i bytes in `bytesLoaded` for each, and if you add these values up, you'll end up with 512 megabytes instead of one. And second, yes it's the right way to get **raw** bitmap weight, but if you encode it via say `PNGEncoder`, the resultant ByteArray will be way smaller. Also raw bitmaps can only be assigned within Flash, you will have to do tricks to read raw data outside Flash.
Comment: `event.bytesTotal` is just for specific image that is getting encoded at the moment. I have couple of images. So I need to get total size of images, add up total loaded and divide whatever is loaded by total.
Comment: Yeah, right, for this you have to track all the loader objects, record their `bytesLoaded` in an array of ints corresponding to loaders, and sum that up. See update.
Comment: I was summing up `e.bytesLoaded` for every load object `total_loaded_bytes += event.bytesLoaded`. Why do I need to put the bytesLoaded into a `progress` array?
Comment: Also, is this `total_bytes += bmp.getPixels(bmp.rect).length` a wrong way to get total bytes of bitmaps? If not, what is the right way?

Getting number of bytes of a bitmap


Payment methods not showing

Question: I've installed - drupal commerce +  paypal + payment + commerce payment- modules.
Commerce seems to be working fine with regards adding and displaying products.
But in 'configuration', there is no list item there that says 'payment methods'.
I've enabled all related modules, so 'paypal wpp' and '..wps' etc.
Also installed and enabled 'payment' and payment commerce'.
What am I missing?
Any help would be great,thanks
Jon
Answer: Drupal Commerce payment  methods can usually be found at      /admin/commerce/config/payment-methods. They are rules in fact. If for any reason that menu doesn't exist, check your rules.
To get that menu you need ro enable Payment UI module.
You also need to properly enable and setup your checkout panes at admin/commerce/config/checkout
Comment: Thanks for your help, paypal WPS was diasbled in rules. I have just enabled it. Also reviewed the checkout settings and everything looks alright-the payment pane is enabled and under the payment part of the checkout. Still no menu item for payment methods though. I'm stumped on this one!
Comment: That's the one! Thanks a lot! I have spent hours scratching my head about this:)

Payment methods not showing


Interpreting the residuals vs. fitted values plot for logit GLMM?

Question: What I have is a generalized linear mixed model of the log OR of a rater (random effect)  giving a response above a certain level on an ordinal scale, given a specification of what the rater was presented with (acoustic parameters of the stimulus). Now, the residuals look fine, but I cat wrap my head around the residuals v.s. fitted values plot. Presumably, heteroscedasticity should to should not be a huge problem for in a logit model, and the results are more or less equidistant across the range of predicted values, but why the odd shape?

Is this what you usually see (this is my first logit GLMM)? Is this due to the link function,or what could it be?
You can download the model here (R save format) https://www.dropbox.com/s/rkygt5a8eat8qpc/gv.glmer02.rda?dl=0
if you want to play with it.
Comment: Just want to add to the correct answer of @Sophologist that the DHARMa R package can transform the residuals back to a standardized space, see examples in https://cran.r-project.org/web/packages/DHARMa/vignettes/DHARMa.html
Answer: This is what you usually see in a logit model.
In general, the strange shape is because the outcome is an integer. As a result, you see curves corresponding to the continuous input (smooth) minus the discrete output (not smooth), with one curve for each possible output (this top curve for the positive examples, bottom for the negative ones).
Interpreting these plots is difficult and I'm pretty sure has many posts that I can't search because I'm on my phone, sorry.
I'm not sure why the residuals have the scale they do (-2, 2) but I assume that's some party of your model that I can't see.


Incremental compilation in Chapel

Question: I have been learning Chapel with small programs and they are working great. But as a program becomes longer, the compilation time also becomes longer. So I looked for the way to compile multiple files one by one, but not with success yet. By searching the internet, I found this and this pages, and the latter says

All of these incremental compilation features are enabled with the new --incremental flag in the Chapel compiler, which will be made available in Chapel 1.14.0 release.

Although the Chapel compiler on my computer accepts this option, it does not seem to generate any *.o (or *.a?) when compiling a file containing only a procedure (i.e. no main()). Is this because the above project is experimental...? In that case, can we expect this feature to be included in some future version of Chapel?
(Or, the word "incremental compilation" above is not what I'm expecting for usual compilers like GCC?)
My environment: Chapel-1.14.0 installed via homebrew on Mac OSX 10.11.6.
Answer: The Chapel implementation only fully compiles code that is used through the execution of the main() routine.  As a starting foray, the incremental compilation project tried to minimize the executable difference between code compiled through normal compilation and code compiled with the --incremental flag.  This was to ensure that the user would not encounter a different set of errors when developing in one mode than they would the other.  As a consequence, a file containing only a procedure would not be compiled until a compilation attempt when that file/procedure was used.
The project you reference was an excellent first start but exposed many considerations to the team which we had not previously considered (including the one you have raised).  We're still discussing the future direction of this feature, so it isn't entirely clear what that would entail.  One possible expansion is "separate compilation", where code could be compiled into a .o or .a which could be linked to other programs.  Again, though, this is still under discussion.
If you have thoughts on how this feature should develop, we would love to hear them via an issue on our Github page, or via our developers or users mailing lists.

Incremental compilation in Chapel


"\Drupal::$container is not initialized yet. \Drupal::setContainer() must be called with a real container."

Question: I am attempting to write a PHPUnit test for a service of mine.
My test looks like the following.
class CustomServiceTest extends UnitTestCase {

  public function testDefaultBehavior() {
    $service = new CustomService(\Drupal::service('custom_utils.some_resolver'), \Drupal::configFactory());
    $service->execute();
  }
}

However, it raises the following exception.
Drupal\Core\DependencyInjection\ContainerNotInitializedException:
\Drupal::$container is not initialized yet. \Drupal::setContainer() must be called with a real container.

What am I doing wrong?
Answer: You need to mock the services you will be using in your test, so that they return values. You can do that as follows:
public function testDefaultBehavior() {
  $some_resolver = $this->getMockBuilder('Drupal\namespace\for\custom_utils\someresolver')
    ->disableOriginalConstructor()
    ->getMock();
  $config_factory = $this->getMockBuilder('Drupal\Core\Config\ConfigFactory')
    ->disableOriginalConstructor()
    ->getMock();
    $service = new CustomService($some_resolver, $config_factory);

}
Note that you should use the actual interface (or class if you have no interface) instead of Drupal\namespace\for\custom_utils\someresolver
You'll need to set up expectations to return the values from the services you mocked. You can read more on that here:
https://www.drupal.org/docs/8/phpunit/understanding-phpunit-expectations


HTML scaled down 50 % in iPhone

Question: We have a client site which uses below html. When I open the URL in safari browser on desktop the URL page renders correctly fitting completely. When the similar page is opened in iPhone the page shrinks to 50% height.
First i thought the issue is because of our code but when we check in iPhone the code at our end works as expected.
Below is the HTML. Requesting help on this. Thanks

  <title>Test.com</title>

 <frameset>
    <frame name="test.com" src="http://www.google.com" marginwidth="0" marginheight="0"    scrolling="auto" frameborder="0"></frame>
</frameset>

Comment: Does the client's iPhone have a different pixel density than the one you tested on?
Comment: No we even checked on our iphones and still same result. What is he missing in the HTML?
Answer: The problem is in the default viewport of the page.

Safari on iOS sets the size and scale of the viewport to reasonable
  defaults that work well for most webpages. The default width is 980
  pixels.
  (source)

You will need to setup your own viewport. By setting a viewport the browser recognises how the content should fit on the device's screen.
Simply adding the following meta tag to your  should fix your problem.
<meta name="viewport" content="initial-scale=1.0">

For more options and information on configuring the viewport visit  http://developer.apple.com/library/ios/documentation/AppleApplications/Reference/SafariWebContent/UsingtheViewport/UsingtheViewport.html

HTML scaled down 50 % in iPhone


Count the number of users in roles

Question: In my D7 installation I'd like to have a view where all roles are listed followed by the number of users that have that particular role.
i.e. of my expected result:

role 1: 2
role 2: 5
role 3: 1
role 4: 8

In addition to this, when I can exclude a role (the admin role) from this view, it would make my day...
Thanks for your support!
Comment: Is custom PHP-code an option? It's easily done with it.
Answer: Create a User View. Then add a "Contextual Filter" for the field "User: Roles". Set the "When the filter value is NOT available" option to "Display Summary" and leave all the other settings. Now you should get the list you want ...
Check the other settings for any customization of the list.

Count the number of users in roles


How to map localhost:8009 to external firiendly URL?

Question: I've installed Atlassian Confluence to my dedicated server (hosted on softlayer.com). I use Windows 2008R2 with IIS7. By default, Atlassian Confluence is installed and works fine on localhost:8009 (not port 80). But I want it to get accessible from some friendly URL such as http://docs.mysite.com
How can I do it? Where can it be configured? Some DNS? CNAME?
Answer: If you want to have this installation externally visible then there are two things you'll want to do:

Create a DNS record to point to the IP of the server - this will allow your visitors to access the server via http://docs.example.com/
Configure your webserver such that you don't need to use the external port.

If you were using Apache I'd suggest you look at mod_proxy, for IIS I'm hazier on what would be required.
Answer: You can use Application Request Routing and URL Rewrite to automatically redirect the users to port 8009 without them having to type it - and without them seeing what port they are actually connected to - the article below gives you the basic idea of how to do this.
http://www.iis.net/learn/extensions/url-rewrite-module/reverse-proxy-with-url-rewrite-v2-and-application-request-routing


Erro ao criar Banco de Dados pelo Visual Studio 2015

Question: Estou com problemas, quando tento criar um Banco de Dados pelo Visual Studio aparece essa mensagem:
Answer: Conforme a própria mensagem de erro diz: você precisa ter o LocalDB ou SQL Server Express instalado e em execução no computador local, ou seja, na sua máquina. Acredito que você não tenha o(s) programa(s) instalado(s) e/ou em execução.
Para solucionar o problema faça o que a mensagem instrui, vá para o link fornecido na mensagem de erro, selecione Microsoft SQL Server Data Tools, e instale a versão mais recente.
Comment: Ok, vou tentar, muito obrigado.
Comment: Qualquer coisa pode me procurar pelos comentários que vamos encontrar uma solução =D
Answer: Você também pode configurar seu banco de forma local através do web.config. Geralmente ao criar o projeto o arquivo web.config já vem pré-configurado, basta ajustar. Verifique se possui o seguinte trecho de código.
Exemplo:
<code><connectionStrings>
<add name="Nome do Banco" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-Vidly-20170823094631.mdf;Initial Catalog=aspnet-Vidly-20170823094631;Integrated Security=True" providerName="System.Data.SqlClient" />
</code>

Segue link da configuração do meu web.config onde está com o banco configurado.
GitHub


If $K\lhd G$ and $(|K|,[G:K])=1$ then $K$ is characteristic.

Question: Here is my Idea I think I am somehow supposed to use the fact that $K$ is a unique subgroup of order $|K|$. To prove this. I think the proof is that for every automorphism of G ($\varphi$), $|\varphi(K)|=|K|$. But I am not sure if that is true, or if it is how to prove that it is true.
Answer: Suppose $K\triangleleft G$, $(|K|,[G:K])=1$ and $H$ is a subgroup of order $|H|=|K|$.  Let $h\in H\setminus K$.
Since $h$ is not the identity, $|h|>1$ and divides $|K|=|H|$.  Now, consider the image of $h$ in $G/K$ by the natural surjection $\phi:G\rightarrow G/K$ (since $K$ is normal).  The image is not the identity since $h\not\in K$, so $|\phi(h)|>1$.  Moreover, $|\phi(h)|$ must divide $|h|$ (which divides $|K|$) as well as $|G/K|=[G:K]$.
This is impossible, because the only positive common divisor of $|K|$ and $[G:K]$ is $1$, which cannot be the order of $\phi(h)$.
Answer: The claim that for every automorphism $\varphi$ of $G$, $|\varphi(L)| = |L|$ is true for every subgroup $L$, because $\varphi$ is injective. That doesn't mean in general that $\varphi(L) = L$ though.
To show $K$ is the unique subgroup of order $|K|$ with the given assumptions, let $H$ be another subgroup of $G$ with order $|K|$. Since $K$ is normal, $HK$ is a subgroup and $|HK| = \frac{|H||K|}{|H \cap K|} = \frac{|K|^2}{|H \cap K|}$. Thus $|HK|$ divides $|K|^2$. But $|HK|$ also divides $|G| = |K| |G:K|$. Since $(|K|,|G:K|) = 1$, $|HK|$ must divide $|K|$ (why?). But $K$ is contained in $HK$, so $HK = K$, which means $H \subseteq K$. But $|H| = |K|$, so $H = K$.
Now you can deduce that since $\varphi(K)$ is also a subgroup of order $|K|$, we must have $\varphi(K) = K$; thus $K$ is characteristic.
Comment: Beautiful. So elegant.
Answer: I think I just got it. Let $\phi: G\to G$ be an automoprhism, and let $\varphi:G\to G/K$ be the natural map. Then it follows that $|\phi(K)|$ divides $|K|$ so $\varphi (\phi(K))=\{e^*\}$ so it follows that $\phi (K)\subset K$.
Comment: Although, I would be careful about writing $\varphi(\phi(K))=e^\ast$ since the LHS is a set and the RHS is an element.


Integração Cielo Woocommerce

Question: Uso Woocommerce e estou tentando implementar o pagamento através da Cielo usando o plugin do Gabriel Reguly.
https://github.com/greguly/cielo-woocommerce/
Porém, quando estou na página de checkout e seleciono a opção da cielo não aparece nenhuma opção de cartão nem parcelamento. Quando clico em Finalizar Compra, é retornado um JSON de erro, porém não consigo identificar de onde vem esse JSON.
<code>{"result":"failure","messages":"","refresh":"false","reload":"false"}
</code>
Não consigo identificar se o erro é do Woocommerce ou do Plugin.
Estou usando a versão 3.0.0 do plugin. E Wordpress 3.9.1.
Desde já, obrigado!
Answer: Simples, a versão 3.0.0 não esta pronta ainda, esta em desenvolvimento e vai demorar alguns dias ainda para ficar pronta.
Se quer usar o plugin, baixe a versão de produção que esta disponível em http://wordpress.org/plugins/cielo-woocommerce/
Comment: Provavelmente, a *Development Version* no `trunk`: http://wordpress.org/plugins/cielo-woocommerce/developers/
Comment: @brasofilo o que esta no `trunk` é a versão 2.0.10. Estamos mantendo o desenvolvimento apenas pelo Github, justamente que assim é mais simples para outras pessoas contribuem com o código e o no WordPress.org usamos apenas para servir as versões.
Comment: Ah, sorry, me confundi ao ler aqui "versão de produção" :)
Comment: Versão 3.0.0 já esta disponível para produção em http://wordpress.org/plugins/cielo-woocommerce/

Integração Cielo Woocommerce


Using ansible cli to restart servers return an error (while still restarting the servers)

Question: I can successfully connect to my server with ssh. Nevertheless, when I try to execute a command through Ansible cli, it fails:
ansible en2 -a "/sbin/reboot" -vvv
Using /etc/ansible/ansible.cfg as config file
<en2> ESTABLISH SSH CONNECTION FOR USER: None
<en2> SSH: EXEC ssh -C -q -o ControlMaster=auto -o ControlPersist=60s -o KbdInteractiveAuthentication=no -o PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o ConnectTimeout=10 -o ControlPath=/home/buzut/.ansible/cp/ansible-ssh-%h-%p-%r en2 '/bin/sh -c '"'"'( umask 77 && mkdir -p "` echo $HOME/.ansible/tmp/ansible-tmp-1470744750.87-182962282383475 `" && echo ansible-tmp-1470744750.87-182962282383475="` echo $HOME/.ansible/tmp/ansible-tmp-1470744750.87-182962282383475 `" ) && sleep 0'"'"''
<en2> PUT /tmp/tmpampMBF TO /root/.ansible/tmp/ansible-tmp-1470744750.87-182962282383475/command
<en2> SSH: EXEC sftp -b - -C -o ControlMaster=auto -o ControlPersist=60s -o KbdInteractiveAuthentication=no -o PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o ConnectTimeout=10 -o ControlPath=/home/buzut/.ansible/cp/ansible-ssh-%h-%p-%r '[en2]'
<en2> ESTABLISH SSH CONNECTION FOR USER: None
<en2> SSH: EXEC ssh -C -q -o ControlMaster=auto -o ControlPersist=60s -o KbdInteractiveAuthentication=no -o PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o ConnectTimeout=10 -o ControlPath=/home/buzut/.ansible/cp/ansible-ssh-%h-%p-%r -tt en2 '/bin/sh -c '"'"'LANG=fr_FR.UTF-8 LC_ALL=fr_FR.UTF-8 LC_MESSAGES=fr_FR.UTF-8 /usr/bin/python /root/.ansible/tmp/ansible-tmp-1470744750.87-182962282383475/command; rm -rf "/root/.ansible/tmp/ansible-tmp-1470744750.87-182962282383475/" > /dev/null 2>&1 && sleep 0'"'"''
en2 | UNREACHABLE! => {
    "changed": false,
    "msg": "Failed to connect to the host via ssh.",
    "unreachable": true
}

Comment: Hint: it's not the user as `USER: None` defaults to root and that's how it' supposed to connect.
Answer: Everything in your output looks correct.
Ansible establishes an SSH connection, runs its script (containing your command) and waits for its exit code.
However you order it to issue an /sbin/reboot command which reboots the server. The SSH connection is thus broken before the exit code is returned to the Ansible and Ansible reports the error.
The error message is actually a bit misleading, but it means the connection was broken.
Comment: You can confirm that by checking of the server restarted.
Comment: Yes, I don't really understand why some servers error and others not. As they're all the same config: Ubuntu 16.04 set up with ansible of course and same ssh conf for all. It might be hardware bound then? I also confirm that the servers restarted!
Comment: What's weird is that it just works as expected on some servers and not others. Nevertheless, it worked on a server doing `ansible -m ping`. So you must just be right!
Comment: Definitely! That's what I'll do.
Comment: SSH doesn't really keep the session packets constantly flowing, depending on the configuration it might poll the server at several-minute intervals and renegotiate the session.  I'm not sure if it can survive daemon (server) restart. That would explain why sometimes you don't get the error. You made me curious about that.


Is there a way to have a method accept blocks with different signatures?

Question: I have this:
typedef void (^resultMail)(MFMailComposeViewController *controller, MFMailComposeResult result);
typedef void (^resultMessage)(MFMessageComposeViewController *controller, MessageComposeResult result);

and I have this:
- (void)shareMailWithImage:(UIImage *)image
     onCompletion:(resultMail)result;

and
- (void)shareMessageWithImage:(UIImage *)image
     onCompletion:(resultMessage)result;

I would like to unify both methods with something like this
- (void)shareType:(typeShare)type withImage:(UIImage*)image onCompletion:...

typeShare will be a typedef like this:
typedef NS_ENUM(NSInteger, typeShare)
{
  kTypeMail = 100,
  kTypeMessage,
};

My problem is the onCompletion block. Each of the previous methods had one specific block signature.
Is it possible to unify that? I mean to create one method that can use any signature for that block as parameter?
Answer: What about changing your block to accept parameters of the respective superclasses?
typedef void (^result)(UINavigationController *controller, NSInteger result);

Answer: Couldn't you just make the parameters more generic..
typedef void (^newResult)(id controller, NSInteger result);

- (void)shareType:(typeShare)type withImage:(UIImage*)image onCompletion:(newResult)result;

This way you can do with result block whatever you want. Both of your blocks pass in a controller and a typedef integer as a result.


Update user when node is created

Question: I'm new in Drupal 8 and I need to update the user when a node of a specific content type is created or updated.
I did some searching and I find hook_entity_create but this hook Act when creating a new entity
Comment: node is an entity...
Comment: Yes I know that, but I need to update the user after the entity(node) is created - thank you for help
Answer: /*
 * Implements hook_ENTITY_TYPE_insert()
 */
function MYMODULE_node_insert(Drupal\node\NodeInterface $node) {

  if($node->bundle() == 'article') { //check for a content type, ex: article
    $user = \Drupal\user\Entity\User::load($uid); // load the user
    $user->set('field_name', $some_value); // set a value for a particular field
    $user->save();
  }

}

Originally I wrote:
MYMODULE_node_create(Drupal\node\NodeInterface $node) {
Changed it as per the comment below.
Comment: I wouldn't save anything to the database in this hook because you don't know if the entity form will be submitted. Use hook_ENTITY_TYPE_insert() (new) or hook_ENTITY_TYPE_update() (update).
Answer: You can use Rules module (in alpha) to perform some actions after new content or updated content is saved.
Answer: I'm not sure that I clearly understand your needs, but the hook_node_presave lets you the option to take a different action if it's a new or an updated node. Of course, it is always a good idea to wrap it in a try catch.
/**
 * Implements hook_node_presave().
 *
 * Acts on an node before it is created or updated.
 *
 * This hook is invoked from $node->save() before the node is saved to the
 * database.
 *
 * @param \Drupal\Core\Entity\EntityInterface $node
 *   The node that is being inserted or updated.
 *
 */
function MYMODULE_node_presave($node) {
  // If it is the wanted content type ...
  if($node->getType() === 'my_wanted_type') {
    // ... and if what you need is the current user ...
    $user = \Drupal::currentUser();
    // ... check if it is a new or an updated node
    $operation = $node->isNew() ? 'create' : 'update';
    // ... and call the function that will handle your needs.
    updateUserOnNodeSave($user, $operation);
  }
}

function updateUserOnNodeSave($user, $operation) {
  if(null != $user) {
    if($operation === 'create') {
      // do something meaningful with $user
    }
    elseif($operation === 'update') {
      // do something meaningful with $user
    }
    $user->save();
  }
}

Update user when node is created


Feeling the beat in the wrong place

Question: This question is related to Basic Punk Rhythm Guitar--Snare Feels Like Down Beat, but essentially different.
I have been playing the drums for quite a long time. When I started drumming I practiced quite a lot. I noticed that some songs try to 'deceive' the listener into feeling the (down)beat at the wrong place by placing a big accent that is offbeat.
The example where I notice this effect in the most obvious way is 'rope' by the foo fighters:

or listen to it (I skipped through most of the intro):

Notice the rest on the one, and the accent on the offbeat. A similar thing happens in 'elephants' by them crooked vultures (although I'm not even sure if I'm feeling the count wrong, or if the beat is actually where I feel it).
Is it 'wrong' to feel the downbeat in the wrong place (or count in the wrong way, if you prefer)? It certainly makes the beat from rope harder to play, but it is not very hard to just learn the patterns shifted by half a count.
Can you do exercises to avoid this? I tried playing rope quite often but never really got used to counting it the right way (although I did seem like I made a little bit of progress, in that I could feel the downbeat at the right space for a couple of bars. It seems like the little rest 'resets' my counting.
I hope my issue is clear. I am also curious how other people (more experienced musicians) interpret the downbeat in rope. If you do count it in the right way, is this by stubbornly counting or does it happen naturally?
Answer: Although it may seem easier to learn that pattern shifted, what happens when you get to the chorus? I contend that it's pretty awkward to add an eighth note and then take it away between sections, especially if you want to add a fill. You'll also have to memorize such shifts for any other song, instead of just feeling 4/4, which is what most of our practicing already fits into.
Getting used to the awkward accents is not only a much more flexible habit, but it allows you to keep more consistent time at higher tempos, since your brain gets used to using more of the counts as reference points.
I recommend using Audacity to slow the song way down, to like half-speed. Then, you can easily sit and clap the downbeats, making absolutely sure that your brain is putting not only the "1" in the right spot, but the rhythms of all of the other instruments as well. Then, you can slowly speed the tempo back up to the original.
Here is an exercise that you can do with a metronome. Here is the hard-mode for this type of ear training. Like Rope, it accents the "&" of "4" and skips the "1", but instead of ~140bpm it's ~200bpm and the beat is double-time. Make sure you pay attention to how the drummer counts in on the hi-hat and the beats that the vocalist emphasizes. Took me a few weeks of listening to this at varying speeds to get it right. Here is a version that includes a click track.
Comment: Thanks for your answer! I was also thinking about using Audacity to remove the first accent. It is indeed very helpful to listen to the other instruments. I think when I first tried to play this song as a novice, I spent so much time listening to the drums with the wrong feel that it's hard to unhear the wrong timing.
Comment: I've found that two things help for me: 1. Filtering out the main guitar (either by turning up the bass or just listening to the drums on https://www.youtube.com/watch?v=k0TLFbpsL7M ). 2. Playing the missing downbeat. This helps me to keep track of time (so that I don't feel the accent as the downbeat).
Answer: There's nothing wrong with placing accents anywhere. The rhythm in Rope is similar to swing (in a way) so that the off-beat is accented. Don't think of it as wrong or odd.
You may have an issue separating your right hand from the right foot (if you're right-handed). One exercise I'd recommend for inter- or in-dependence would be to play quarter- or eight- notes in succession: right hand, right foot.
It will feel perfectly natural after a while. And the result will be this somewhat reggae-like accenting.

Feeling the beat in the wrong place


What is the PDF of a Normal convolved with a Laplace

Question: I'd like to see if using Stan or similar I can successfully model Laplace noise added to data through the use of a convolved Normal-Laplace distribution and MCMC sampling. In the literature I can only find this https://www.tandfonline.com/doi/full/10.1080/03610926.2015.1040510 which concerns an asymmetric Laplace distribution. I was wondering if anyone knows of a simpler expression I could use for a Normal convolved with a symmetric Laplace. And further to this, whether this is even the correct approach to modelling noise added to data (provided I know the scale of the Laplace noise added). Here is the corrected PDF in the linked article which is unfortunately behind a paywall:
$$
\begin{aligned}
f(y)=& \frac{\alpha \beta}{2(\alpha+\beta)}\left[e^{\frac{1}{2} \alpha\left(-2 y+2 \mu+\alpha \sigma^{2}\right)} \operatorname{erf} c\left(\frac{\alpha \sigma}{\sqrt{2}}-\frac{y-\mu}{\sqrt{2} \sigma}\right)\right.\\
&\left.+e^{\frac{1}{2} \beta\left(2 y-2 \mu+\beta \sigma^{2}\right)} \operatorname{erf} c\left(\frac{\beta \sigma}{\sqrt{2}}+\frac{y-\mu}{\sqrt{2} \sigma}\right)\right]
\end{aligned}
$$
And for further reference, the original:
$$
\begin{array}{c}
\phi(x)=\frac{e^{-\frac{1}{2} x^{2}}}{\sqrt{2 \pi}} \\
\left.\Phi(x)=\frac{1}{\sqrt{2 \pi}} \int_{-\infty}^{x} e^{-\frac{t^{2}}{2}} d t=\frac{1}{2}\left[1+\operatorname{erf}\left(\frac{x}{\sqrt{2}}\right)\right]\right] \\
R(z)=\frac{1-\Phi(z)}{\phi(z)}=\frac{\sqrt{2 \pi}\left[\operatorname{erfc}\left(\frac{z}{\sqrt{2}}\right)-\frac{1}{2}\right]}{e^{-\frac{z^{2}}{2}}} \\
f(y)=\frac{\alpha \beta}{\alpha+\beta} \phi\left(\frac{y-\mu}{\sigma}\right)\left[R\left(\alpha \sigma-\frac{y-\mu}{\sigma}\right)+R\left(\beta \sigma+\frac{y-\mu}{\sigma}\right)\right]
\end{array}$$
Here is the PDF I get by setting $\alpha = \beta$ in the referenced article. I am presuming that the asymmetric Laplace here is centred, meaning this would only work for a $Laplace(0, \lambda)$. This results in extremely large PDF values in some cases, so I believe I have done something wrong.
$$\frac{λ}{4} \text{erfc} \left(\frac{λσ}{\sqrt{2}} - \frac{y - μ}{\sigma \sqrt{2}} \right) \left(
        \exp\left(\frac{\lambda}{2} \left(-2y + 2μ + λσ^2\right)\right) +
        \exp\left(\frac{\lambda}{2} \left(2y - 2μ + λσ^2\right)\right)\right)$$
function pdf_NL(μ, σ, λ, y)
    return (λ / 4) * erfc((λ * σ) / √2 - (y - μ) / (√2 * σ)) * (
        exp(0.5λ * (-2y + 2μ + λ * abs2(σ))) +
        exp(0.5λ * (2y - 2μ + λ * abs2(σ)))
    )
end

Comment: Your reference explicitly answers the question in the title by providing expressions for the pdf and cdf of this convolution.  Just set $\alpha=\beta.$ It's clear nothing will cancel or disappear from the formulas, so little simplification will occur.
Comment: @whuber Yes, this was my initial attempt too, the PDF that results through setting $\alpha = \beta = \lambda$ doesn't seem right when I pass it values though. I will edit the question to include it and some Julia code to go alongside. I am presuming here that the asymmetric Laplace is always centred, but perhaps this is where I am misunderstanding?
Comment: Could you please rephrase your question by (a) avoiding the connection with DP which is irrelevant for the question and (b) formally and rigorously defining the convolution you are interested in? Note that the density of the convolution is NOT the sum of the two densities involved. Further, convolutions are well-suited to MCMC algorithms as they naturally invoke a latent variable. Enjoying a closed form density is thus less important.
Comment: The link is to a paper behind a paywall.
Comment: Your formula does not seem to agree with that of the paper: you are neglecting terms in the denominator.  See the formula for $R.$
Comment: @whuber which terms are you referring to? The LHS becomes $\frac{\lambda ^ 2}{2(2\lambda)}$ no? Note I am looking at the correct pdf not the original, I can't actually comment on the correctness but looking at the appendix convinced me the corrections were valid
Comment: @Xi'an unfortunately I cannot find another source for the article, I can copy out the PDF's defined within it though, part of the confusion stems from the fact this is a correction to an older paper. Would you mind expanding a bit more on what you'd suggest if a closed form is not important?
Comment: @Xi'an Right, I see what you're saying, I have tried to do this in modelling the noise itself   yes. I was interested in looking at a comparison between this and the use of the NL convolution as well though
Comment: I signed up to post this: convolving with a normal pdf is the same as multiplying the Fourier transform by a normal pdf. The Fourier transform of a Laplace pdf is a Cauchy pdf. I haven't checked that this gives the same answer, but it might be simpler.
Answer: Let's work it out from first principles, beginning with the hard work of computing a convolution.
As an auxiliary calculation, consider the distribution of $W=X+Y$ where $Y$ has an Exponential distribution with pdf $$f_Y(y) = e^{-y}\,\mathcal{I}(y\gt 0)$$ and $X$ has a Normal$(\mu,\sigma^2)$ distribution with pdf $f_X(x;\mu,\sigma) = \phi((x-\mu)/\sigma)/\sigma$ where $$\phi(z) = \frac{1}{\sqrt{2\pi}}\,e^{-z^2/2}$$ is the standard Normal pdf.  The PDF of the sum is the convolution
$$f_W(w;\mu,\sigma) = \int_{-\infty}^\infty f_Y(y) f_X(w-y;\mu,\sigma)\,\mathrm{d}y = \int_0^\infty e^{-y} f_X(w-y;\mu,\sigma)\,\mathrm{d}y.$$
Substituting $\sigma z = w - y - \mu$ expresses this integral as

$$\eqalign{f_W(w;\mu,\sigma) &= e^{\mu-w}\,e^{\sigma^2/2}\int_{-\infty}^{(w-\mu)/\sigma} \phi(z-\sigma)\,\mathrm{d}z \\
&= e^{\mu-w+\sigma^2/2}\, \Phi\left(\frac{w-\mu}{\sigma}-\sigma\right)}\tag{1}$$

where $\Phi$ is the standard normal CDF,
$$\Phi(z) = \int_{-\infty}^z \phi(z)\,\mathrm{d}z.$$

The rest builds on this work and is relatively easy.
An asymmetric Laplace random variable $U$ is based on a mixture of a scaled exponential distribution and the negative of a scaled exponential distribution (potentially with a different scale, thereby making the mixture asymmetric). This mixture is then shifted by a specified amount.  The amount of mixing is established to give the Laplace pdf a unique value at its peak--but this is unimportant.
One component of $U$ therefore can be expressed as $$U_+ = \alpha Y + \lambda$$ with a positive scale $\alpha$ and the other component as $$U_- = -\beta Y + \lambda$$ with a positive scale $\beta.$  (I apologize: I worked this out before realizing that my $\alpha$ is $1/\alpha$ in the paper and my $\beta$ is $1/\beta$ in the paper: in the end, after setting $\alpha=\beta,$ this won't matter.)
When we add $X = \sigma Z + \mu$ we obtain two components, of which the first is $$W_+ = U_+ + X = \alpha Y + \lambda + \sigma Z + \mu = \alpha\left(Y + \left[\frac{\sigma}{\alpha} Z + \frac{\lambda + \mu}{\alpha}\right]\right)$$ and the second is similarly written.  To obtain its pdf, all we need to do is scale formula $(1)$ by $\alpha,$ giving

$$f_{W_+}(w;\mu,\sigma,\lambda,\alpha) = \frac{1}{\alpha}\,f_W\left(\frac{w}{\alpha};\frac{\lambda+\mu}{\alpha}, \frac{\sigma}{\alpha}\right).\tag{2}$$

Likewise, because
$$W_- = U_- + X = -\beta Y + \lambda + \sigma Z + \mu = -\beta \left(Y + \left[-\frac{\sigma}{\beta } Z + \frac{\lambda + \mu}{\beta }\right]\right)$$
and $-Z$ has the same distribution as $Z$, formula $(1)$ yields

$$\eqalign{f_{W_-}(w;\mu,\sigma,\lambda,\beta) &= \frac{1}{\beta }\,f_W\left(-\frac{w}{\beta };-\frac{\lambda+\mu}{\beta }, \frac{\sigma}{\beta }\right) \\
&= f_{W_+}(-w;-\lambda,\beta,-\mu,\sigma).}\tag{3}$$

The mixture pdf is

$$f_W(w;\mu,\sigma,\lambda,\alpha,\beta,p) = pf_{W_+}(w;\mu,\sigma,\lambda,\alpha) + (1-p) f_{W_-}(w;\mu,\sigma,\lambda,\beta).\tag{4}$$

Comments
For the Laplace-Normal distribution, use $p = \alpha / (\alpha + \beta).$  In your case $\alpha=\beta,$ which evidently "simplifies" $(4)$ a tiny bit--but a quick look at its component formulas $(2)$ and $(3)$ suggests there's not much one can do algebraically to reduce the amount of computation, so why bother?
Each of the components of the final formula $(4),$ as embodied in formulas $(1),$ $(2),$ and $(3)$ can be separately and flexibly implemented and separately tested.  This makes for an easier and more reliable software implementation than attempting to combine them all into one monster combination of $\phi$ and $\Phi,$ as done in the referenced paper.  As a bonus, important numerical improvements in the calculation can be implemented exactly where they are needed, making the code relatively easy to maintain.  As an example, see how $f_W$ is implemented using logarithms (as f.1) in the code below.

Illustration
This plot compares a histogram of one million iid draws from an asymmetric Laplace-Normal distribution with pdf $f_W(w;4,0.5,-3,2,1,2/3)$ to a calculation based directly on formulas $(1) - (4):$

The agreement is a pretty good test.

Code
Here's the R code that generated this simulation and this plot.
n <- 1e6      # Size of simulation
mu <- 4
sigma <- 1/2
alpha <- 2
lambda <- -3
beta <- 1
#
# Generate data.
# set.seed(17)
X <- rnorm(n, mu, sigma)
Y <- ifelse(runif(n, 0, alpha + beta) < alpha, alpha, -beta) * rexp(n) + lambda
W <- X + Y
#
# Plot their histogram.
#
hist(W, freq=FALSE, breaks=200, cex.main=1)
#
# Overplot the PDF.
#
f.1 <- function(w, mu=0, sigma=1) {
  exp(mu - w + sigma^2/2 + pnorm((w - mu)/sigma - sigma, log=TRUE))
}
f.plus <- function(w, mu=0, sigma=1, lambda=0, alpha=1) {
  f.1(w / alpha, (lambda + mu) / alpha, sigma / alpha) / alpha
}
f.minus <- function(w, mu=0, sigma=1, lambda=0, beta=1) {
  f.plus(-w, -mu, sigma, -lambda, beta)
}
f <- function(w, mu=0, sigma=1, lambda=0, alpha=1, beta=1, p=1/2) {
  p * f.plus(w, mu, sigma, lambda, alpha) + (1-p) * f.minus(w, mu, sigma, lambda, beta)
}
f.asymmetric <- function(y, mu=0, sigma=1, lambda=0, alpha=1, beta=1) {
  f(y, mu, sigma, lambda, alpha, beta, alpha / (alpha + beta))
}
curve(f.asymmetric(x, mu, sigma, lambda, alpha, beta), add=TRUE, lwd=2, col="Red")


SSIS - Continue Package Flow even after inner task in a Foreach Loop Container fails

Question: In the figure below, why is the Foreach Loop Container failing despite the fail path (of the DFT that failed) being handled correctly?
How can I get the loop to continue after handling fail path?

If it helps to know what's going on in the package, here's the gist:

We have a requirement where data from Excel files must be loaded into
  a DB. The package we have splits each Excel file into constituent CSV
  files (one CSV per sheet), and loads the CSVs into the DB. It is
  possible that some of the sheets have issues (missing columns, data
  type mismatch etc), and such erroneous CSVs are captured by the fail
  path of the DFT. Ideally the package must resume processing the rest
  of the CSVs, and the rest of the Excel files, and exit successfully.
Answer: Do you have any OnError EventHandlers defined for that Data Flow Task? If yes, you could as well set the System Variable, Propogate (type Boolean), for that Error Handler scope to 'False'.
Also please go through Gracefully Handing Task Error in SSIS Package
Comment: Thanks! That's what I ended up doing, thanks to [SSIS Foreach Loop Container: Continue on Error](http://sqlserverselect.blogspot.in/2010/12/ssis-foreach-loop-container-continue-on.html). I was going to answer my own question with a screenshot, but you beat me to it! Cheers!
Answer: There is a property on every SSIS component that is called MaximumErrorCount which defines the number of errors that this particular component can accept before failing the whole package.
You have to increase this value for each and every component that you want to continue executing before failing.


JavaScript eval verificar se é seguro

Question: Gostaria de criar objetos sequenciados e para setar o nome do objeto, apenas consegui fazer pela função eval(), não achei outras alternativas.
Dizem que é ineseguro, e sujeito a ataques. Gostaria de saber , se o código abaixo oferece alguma insegurança ao site.
var obj1 = { but1: { Label: "button1" }, but2: { Label: "button2" }, but3: { Label: "button3" } };

for (i=4;i<=6;i++)
   x = eval("obj1.but" + i + " = {Label:'button"+i+"'};");

Caso afirmativo, qual a maneira segura de escrever esse código ?
Obrigado.
Comment: **Relacionado:** [Eval é mocinho ou bandido?](http://pt.stackoverflow.com/q/128845/3635)
Answer: Você não precisa usar eval nesse caso. Você pode acessar um campo determinado por uma string usando o operador []
for (var i=4;i<=6;i++){
    obj1["but"+i] = { Label: "button"+i };
}

Mas na minha opinião o melhor mesmo seria botar os botões num vetor ou em uma tabela hash:
var obj1 = {
    buttons: [
        { Label: "button0" },
        { Label: "button1" },
        { Label: "button2" }
    ]
};

for (var i=3;i<=5;i++) {
   obj1.buttons[i] = { Label: "button"+i };
}

Quanto à segurança, esse exemplo em particular que você usou não é inseguro pois você pode garantir que todas as strings que são passadas para o eval são bem comportadas. O problema de segurança surgiria se você passasse algum valor determinado por um usuário do seu website para dentro do eval.
Mas apesar da versão atual não ser insegura eu ainda não recomendaria o uso do eval. Ele é bem mais complicado do que as alternativas, se houver um erro durante o eval a mensagem de erro e o stack trace são difíceis de debugar, e o eval bloqueia diversas otimizações do compilador, o que faz seu programa rodar mais lentamente. Além disso é bem fácil introduzir um problema de segurança fazendo apenas uma pequena modificação acidental no código.
Answer: Esta resposta é um adendo a resposta do @hugomg, resumindo o problema do eval é que tipos de dados que serão executados, na pergunta o exemplo não é tecnicamente inseguro, todavia ainda existe o problema da performance, neste exemplo eu fiz mais semelhante ao código original, apesar de concordar com a abordagem de arrays do @hugomg, eu mantive assim para comparar a performance, veja por você mesmo:

Função testObject pega ou seta os objetos assim obj1['but' + i]
Função testEval é o seu código original eval("obj1.but" + i);

O exemplo:

var obj1 = { but1: { Label: "button1" }, but2: { Label: "button2" }, but3: { Label: "button3" } };

function testEval() {
   for (var i=4;i<=6;i++) {
      x = eval("obj1.but" + i + " = {Label:'button"+i+"'};");
   }
}

function testObject() {
   for (var i=4;i<=6;i++) {
      x = obj1['but' + i] = {Label:'button' + i };
   }
}

var d = new Date().getTime();

for (var i=0;i<100000;i++) {
   testEval();
}

console.log("eval:", (new Date().getTime() - d) + "ms");

d = new Date().getTime();

for (var i=0;i<1000;i++) {
   testObject();
}

console.log("object:", (new Date().getTime() - d) + "ms");

Resultados no Chrome:

testEval levou ~477ms para concluir
testObject levou ~2ms para concluir

Ou seja usar assim obj1['but' + i] é muito mais eficiente que eval
No firefox o resultado é bem pior com eval, leva 6741ms para executar o exemplo:

eval: 6741ms
object: 3ms
Answer:
Gostaria de saber , se o código abaixo oferece alguma insegurança ao site.
  ...
  Caso afirmativo, qual a maneira segura de escrever esse código ?

Você já sabe que o eval faz com que o navegador interprete/execute um código no mesmo escopo onde foi chamado: então, "não". O código executando ao lado do cliente não é capaz de modificar o servidor, mas tem acesso à declarações locais, já o contexto global qualquer um pode modificar rapidamente (agora isso é caso você queira avaliar uma string que veio de outro lugar).
Eu preocuparia de usar eval nesse caso, já que pode abalar a performance de um jogo (por exemplo), de tanto fazer o navegador re-avaliar e executar um código.
Do jeito que você usou o eval não foi muito vantagioso, tipo, você queria obter uma propriedade de obj1 de forma de forma mais customizada. Os assignments também funcionam com (exp)[expParaONomeDaPropriedade] ao invés de (exp).identificador:
obj1['0']; // o mesmo que obj1[0]
obj1['but1']; // o mesmo que obj1.but1

A diferença de usar o . é porque você é obrigado à usar um identificador, de várias maneiras atualmente:
({ 'a': 2 }).\u{61} // 2
({ 'a': 2 }).\u0061 // 2

({ 'B': 5 }).\u0042 // 5
({ 'B': 5 }).B // 5

Lembrando que o nome de todas propriedades são forçados para serem strings, exceto uma propriedade com o nome do tipo 'symbol'...
Comment: muito obrigado pelos esclarecimentos.. irei fazer os testes da maneira que propos. Minha precaução era em realação a segurança, porém como posso melhorar também a perfomance. acho viavel modificar. grato..

JavaScript eval verificar se é seguro


How to use Flow with React.createRef()?

Question: Since React 16.3 it is possible to use React.createRef() to access a DOM element. I am also using Flow in my project, but the documentation still uses the old way.
The below code unfortunately fails:
/* @flow */
import * as React from 'react';

export class TestComponent extends React.Component<{}> {
  myRef: React.Ref<HTMLDivElement>

  constructor(props: any) {
    super(props)
    this.myRef = React.createRef()
  }

  render() {
    return (

    )
  }
}

with the following error:
Cannot instantiate `Ref` because in type argument `ElementType`:
 - Either a callable signature is missing in `HTMLDivElement` [1] but exists in
   `React.StatelessFunctionalComponent` [2].
 - Or `HTMLDivElement` [1] is incompatible with statics of `React.Component` [3].

How do I type it correctly?
Comment: https://devdocs.io/flow/react/types#toc-react-ref
Answer: Looking at the flow type definition for React.createRef():
declare export function createRef<ElementType: React$ElementType>(
): {current: null | React$ElementRef<ElementType>};

I was able to do something like this:
/* @flow */
import * as React from 'react';

export class TestComponent extends React.Component<{}> {
  myRef: { current: null | HTMLDivElement }

  constructor(props: any) {
    super(props)
    this.myRef = React.createRef()
  }

  render() {
    return (

    )
  }
}

Comment: You can create your own generic type to make declarations shorter: type RefType = {
  current: null | T
};
 Then you can use it like this in your class: myRef: ReactRef
Answer: There is a related github issue.
If it's not fixed yet you can type it yourself:
type RefObject = {|
  current: any,
|};

This is how it is typed internally in react library type definitions.
Comment: When trying to use the self defined RefObject I get the error `Cannot assign React.createRef() to this.myRef because inexact object type [1] is incompatible with exact
RefObject [2].`  Any idea? (I am quite new to flow).
Comment: @Zardoz try like this: `type RefObject = { current: any };`
Answer: If you are using "class properties", you may createRef() in the following way:
// @flow
import * as React from 'react';

export class TestComponent extends React.Component<{}> {
  myRef = React.createRef<HTMLElement>();

  render() {
    return (

    )
  }
}

Answer: In my case I was using formik reference
// @flow
import React from 'react';
import { Formik } from "formik"

export class TestComponent extends React.Component<Props> {
   formikRef = React.createRef<Formik>();

  render() {
     return (
         <Formik
            ...,
            ref={this.formikRef}
         />
     )
  }
}

Comment: Yes, the type arrows here fixed it: `const formRef = React.useRef(null);`

How to use Flow with React.createRef()?


Forecasting: Linear vs. Exponential vs. ARIMA

Question: I have tried forecasting next 13 years data point by using past 20 years data (1998-2010) available in the following graphs. I used three models to compare- linear regression, exponential regression, and ARIMA. In the first image ARIMA tend to fit the data well and prediction is clearly better than other two models. In the second image though ARIMA fits the data well, but none seems to have a good prediction. I think as in the final year, data had a sharp fall, ARIMA showing a sharp decrease in the next years as well! However, it had a increasing trend in the previous 18 years! Any idea?
My second question is- is there any situation where Linear or Exponential regression can better predict than ARIMA model?
dput(

data<-c(1796.0, 1737.0, 1745.0, 1829.0, 1857.0, 1885.0, 2088.0, 2112.0, 2137.0, 2150.0, 2168.0, 2219.0, 2233.0, 2249.3, 2291.5, 2307.3, 2325.4,
2379.7, 2385.3, 2407.0)

data<-ts(data,start=1998)

fit.arima<-auto.arima(data)

fcast.arima<- forecast(fit.arima)

autoplot(data) +
   autolayer(fitted(fit.arima), series = "arima") +
   autolayer(fcast.arima, series="arima", PI=FALSE) +
   xlab("Year") + ylab("Employment") +
   ggtitle("") +
   guides(colour = guide_legend(title = " "))

)

dput(

data<-c(1090.0,1118.0, 1135.0,1218.0,1255.0,1275.0,1391.0,1424.0,1432.0,1430.0,
1447.0,1468.0,1471.0,1507.2,1520.5,1526.4,1524.4,1545.6,1539.0,1466.4)

data<-ts(data,start=1998)

fit.arima<-auto.arima(data)

fcast.arima<- forecast(fit.arima)

autoplot(data) +
   autolayer(fitted(fit.arima), series = "arima") +
   autolayer(fcast.arima, series="arima", PI=FALSE) +
   xlab("Year") + ylab("Employment") +
   ggtitle("") +
   guides(colour = guide_legend(title = " "))

)

Comment: How did you select the orders of your ARIMA model? Can you edit your post to include your data?
Comment: I used auto.arima function in R, for the first one it used ARIMA(0,1,0) with drift, and for the 2nd one ARIMA(0,2,1). I am adding data in my post.
Comment: @StephanKolassa I also used NNAR, which seems to underestimates to a large extent!
Comment: Ah. I don't quite understand your data. Can you please post them in a way we can use them without having to type them down again? Best to use `dput()` on whatever you submit to `auto.arima()`.
Comment: @StephanKolassa now see!
Answer: First, forecasting 13 years ahead from 20 years of historical data is very bold.
Second, the reason why you get a decline with ARIMA is probably because of the sudden sharp decrease in the data in the second plot.
Third, it doesn't seem like there is really any pattern to your data, which is probably why the models are struggling to find any sensible results.
In general, ARIMA should perform better than regression for forecasting time series data.
Comment: @MahmudulHasan Sure, something is better than nothing, however you still need a sensible something. For the second part, that depends on the data. If you really think that the previous data comes from a different process, then you can exclude it, since you are not really interested in. However, if this is about a period when something different happened, you can still keep it in the data and process it appropriately, such as using a dummy variable for war.
Comment: @MahmudulHasan Personally I don't see clear patterns in the data, the first plot looks like it might keep increasing, but the second looks like it could go either way. You may be better off using some simple predictions, such as the naive method.
Comment: Don't you think it's better to have something than nothing in hand if you want to get a picture about future! May be it can be adjusted with expert's opinion.

Another point is I had 36 years historical data, which represents some country employment. However, it faced war from 1985-1997 and data was very unusual that time. Before 1997 pattern and after 1997 pattern was very different. So, isn't it logical not use that part of data in forecasting?
Comment: So, what if I want to forecast this data, do you suggest I should solely rely on expert's opinion. On more thing, does 1st image looks have no trend as well?
Comment: You say "In general, ARIMA should perform better than regression for forecasting time series data." I say https://autobox.com/pdfs/regvsbox-old.pdf
Answer: Modelling is not about selecting a priori a specific type of equation BUT rather extracting the model specifics from the data in an iterative manner as presented here https://autobox.com/pdfs/ARIMA%20FLOW%20CHART.pdf
 in order to optimally/opportunistically combine linear, exponential smoothing and arima components while dealing with latent deterministic structure such as pulses , level/step shifts,local time trends and/or seasonal pulses AND possible transience in either model parameters or model error variance through time.
The whole idea is to use Exploratory Data Analysis tools (EDA) to evolve/deterimine the underlying model in order to separate signal and noise via an iterative self-checking approach as originally presented by Box & Jenkins and improved since.
In your first example the deterministic structure required is a level shift (intercept change) and a few pulses with an arima (1,0,0) nearly (0,1,0)  while the second example it is simply two pulses with an arima (0,1,0) .
first example:
There is a very clear pattern in the data as shown here  . Your 20 values are adequately described by a hybrid model using an AR(1) and a step/level shift along with 3 pulses .  and here  and here
The tools (approaches) that you were considering are presumptive in form whereas your data has it's own message. This data has not only a strong memory but has been affected by external activity causing the step.level shift and the 3 pulses.
here are the forecasts for the next 13 periods
The method used here to form the model is called Intervention Detection as detailed here and everywhere else http://docplayer.net/12080848-Outliers-level-shifts-and-variance-changes-in-time-series.html . Search SE for "INTERVENTION DETECTION" . It might behoove you to investigate the true cause of the level/step shift in order to more intelligently forecast this series.
Here is the Actual and Cleansed plot
The reason that arima (memory) doesn't work (alone) is that there is determinstic structure in the data .
second example:
This is also a hybrid model arima (1,1,0) with two pulses reflecting external deterministic inputs. The Actual/Fit and Forecast is here  with equation here  and here  with statistical summary here  and forecasts here . The Actual and cleansed graph is here
It is critical to assess whether the anomaly (pulse) downwards at the last point is "real and to be believed" or "a temporary change" . If it is temporary then the forecasts given are to be used , however if it is permanent then subtract 69.4 for each forecast period.
I used AUTOBOX an integrated piece of software that I have helped to develop but there a number of alternative software tools that can be cobbled together to give similar results as to the ideas that I have presented.


Drupal 7 on new Linode stack, POST/GETS 404ing but pages still loading?

Question: I'm trying to migrate a site to a new linode environment, and my website has made the journey with the exception(s) that:
I cannot login at /user/login, console shows 404s when submitting credentials and the page simply refreshes. Note: ?q=user DOES work.
When logged in (through ?q=user method), every page i request shows a 404, but then still loads the page. For example, when going to mysite.com/t-shirts, console shows 404 on that address, even though the page loads fine.
Trying to login via colorbox returns (in the modal): Request unsuccessful: error.
All the elements in my pages that use ajax fail, showing 404s in console.
Short URLs SEEM to work, i.e. /catalog returns the proper page (despite 404 in console). I can also get to admin pages with /admin paths, but cannot seem to change anything on those pages because submitting the changes always fails.
What am I missing in migrating this drupal install? Drupal install status whines about GD and cURL missing, but I don't believe this has anything to do with it..
base URL is set to the proper address in settings.php (http://dev.skinnyboyswagclub.com)
Answer: The reason for this is most likely that clean url's are disabled. Make sure that mod_rewrite is enabled in Apache.
Fetching pages still works, because the 404 triggers Drupal, which is then able to return the correct page. That does, as you found out, not work for form submits, because the submitted data is lost when doing the redirect.
Comment: I assumed rewrite was on because the clean urls seemed to be working despite the errors, however apache reported it as not being enabled.

I enabled it with a2enmod, restarted apache, and when I do this the site comes down completely. After disabling rewrite, the site comes back up (after like 10 minutes)

any additional pointers would be appreciated! going to look at logs for the time when the sites down of course..
Comment: i also noticed that the module is called rewrite and not mod_rewrite, in /mods-available/, yet htaccess rules use the condition: if mod_rewrite, does this matter?
Comment: mod_rewrite/rewrite: that's ok. Please elaborate on "comes down". server error 500? That probably indicates a error/permission problem somewhere. Check your apache error log, it should have more details.
Comment: /etc/apache2/error.log has only the starting/stopping notices for apache. The error log for the virtual host this site is run in shows a bunch of "file does not exist" messages for every short-url page request. And in the browser, requesting pages after enabling the rewrite module returns 404, not 500. In fact it seems like it cant resolve dev.skinnyboyswagclub.com and so it quickly adds a www before the dev, which of course also fails.. Where else should I be looking to troubleshoot this?
Comment: everything works fine when using the ip address (http://126.96.36.199), including login and short urls, the ajax stuff, etc.
Comment: sounds like you have non-www => www redirect enabled somewhere with mod_rewrite, probably in the .htaccess file. No browser does that automatically. You should be able to see that you get a redirect in firebug/web developer or the access log. Either find and disable it, or add the URL with the www. to your hosts file and as a ServerAlias.
Comment: Note that browsers cache a redirect, that's why the site is "down" for 5 minutes. You will need to clear the caches to debug it.
Answer: I would suggest the following:

Check all your logs. These include D7, webserver and syslogs.
Get a vanilla D7 site up & running and iron out all dependency issues.
Make sure that clean URLs and caching are working correctly.
On the migrated site, turn off clean URLs and caching, caching modules etc.
Try commenting out the <code>$base_url</code> option.
Check all your logs. These include D7, webserver and syslogs.

I would also get drush installed (if not already) to both check the status and keep an eye on the watchdog logs.
Comment: Thanks for the tips. First thing I notice in D7 logs are pages of these errors:

 Warning: unlink(/var/sbscdev/public/sites/default/files/js/js_kf6wmju1CCF0N1cebzbc350wT3UQyPKXcqOwtn3rgvY.js.gz): Permission denied in drupal_unlink() (line 2151 of /var/sbscdev/public/includes/file.inc).

does this narrow the scope of troubleshooting?
Comment: Looks like the files directory (and sub-directory) permissions were incorrectly transferred/reset on the new host. These files are _aggregated_ JavaScript files and might be unrelated to your issue. But it's worth fixing nonetheless. You should also turn off aggregation and other forms of optimisation and caching when debugging such errors.
Comment: I migrated from GoDaddy so the username and group names are all off... I suspect the permissions are how I want them, but need to change the usernames and groups who are assigned those permissions, without changing the permissions themselves..

edit: figured out the proper chown -R cmd a few seconds later ;D thx for your help


For which values of the parameter p does it hold that the vectors are independent?

Question: Let $ u, v$  and $ w$  be linearly independent vectors in $ \mathbb{R^n} $
. For which values
of the parameter p does it hold that the vectors $ a = u − v, b = u + w, c = u + v − w$
and $ d = p · u + v + w $ are linearly independent as well?
What is the easy way to solve this kind of problem? Can we say 4 vectors in $ \mathbb{R^3}$  are always dependent?
Comment: Tip: Use $\mathbb{R}$ to denote the real numbers. Code is ```\mathbb{R}```.
Comment: thank you edited! what about my question?
Comment: Yes, 4 vectors in $\mathbb{R}^3$ are always linearly dependent. See [here](https://math.stackexchange.com/questions/3171064/prove-that-if-a-vector-space-has-dimension-n-then-any-n-1-of-its-vectors-are-l)
Comment: what about if we have 3 vectors but question is same.How can I figure it out?
Comment: Which three vectors out of a,b,c, and d?
Comment: For example a b and d
Answer: So, just to restate:
$$\mathbf{a}=\mathbf{u}-\mathbf{v}$$
$$\mathbf{b}=\mathbf{u}+\mathbf{w}$$
$$\mathbf{d}=p \mathbf{u}+\mathbf{v}+\mathbf{w}$$
Given $\mathbf{u}, \mathbf{v}, \mathbf{w}$ are linearly independent vectors in $\mathbb{R}^3$.
They are linearly dependent if $\exists k_1,k_2,k_3 \in \mathbb{R}\backslash\{0\}$ such that
$$k_1 \mathbf{a} + k_2 \mathbf{b} + k_3 \mathbf{d}=0$$
Or
$$k_1(\mathbf{u}-\mathbf{v})+k_2(\mathbf{u}+\mathbf{w})+k_3(p \mathbf{u}+\mathbf{v}+\mathbf{w})=0$$
$$(k_1+k_2+pk_3)\mathbf{u}+(-k_1+k_3)\mathbf{v}+(k_2+k_3)\mathbf{w}=0$$
Since we know that $\mathbf{u}, \mathbf{v}, \mathbf{w}$ are linearly independent, this can only be true if
$$\begin{bmatrix}
k_{1} +k_{2} +pk_{3}\\
-k_{1} +k_{3}\\
k_{2} +k_{3}
\end{bmatrix} =\begin{bmatrix}
0\\
0\\
0
\end{bmatrix}$$
Thus we want to know if there are any non trivial solutions to the matrix equation
$$\begin{bmatrix}
1 & 1 & p\\
-1 & 0 & 1\\
0 & 1 & 1
\end{bmatrix}\begin{bmatrix}
k_{1}\\
k_{2}\\
k_{3}
\end{bmatrix} =\begin{bmatrix}
0\\
0\\
0
\end{bmatrix}$$
As if there are non trivial solutions, it means we have found $k_1, k_2, k_3 \neq 0$ such that $k_1 \mathbf{a} + k_2 \mathbf{b} + k_3 \mathbf{d} = 0$. Therefore, as long as the determinant of the above matrix is nonzero (i.e, we can invert the matrix, multiply both sides by the inverse), $k_1 =k_2=k_3=0$ is the only solution. It can be easily verified that
$$\det\left(\begin{bmatrix}
1 & 1 & p\\
-1 & 0 & 1\\
0 & 1 & 1
\end{bmatrix}\right) =-p$$
Therefore $\mathbf{a}, \mathbf{b}$, and $\mathbf{d}$ are only linearly independent if $p \neq 0$.
Comment: Now everything is clear!
Comment: @subhanceo Sorry for the late reply. Please ask if anything is unclear!
Comment: Thank you for explanation. One thing is unclear I learnt that if determinant is 0 then the vectors are dependent but in this case you say they are independent.
Comment: @subhanceo You are correct! Goodness, what was I thinking? I'll correct it.


Criar um video pelo javascript

Question: Eu tentei criar um vídeo na minha página que é gerado pelo clique do botão através do javascript, como segue no código:

function tocar_video(mysrc){
 var video = document.createElement('video');

 video.src = mysrc;
 video.autoplay = true;
}
.bt202{
 background-image:url("https://image.freepik.com/icones-gratis/botao-de-play_318-42541.jpg");
 background-size:100% 100%;
 background-repeat:no-repeat;
 width:50px;
 height:50px;
}
<!DOCTYPE html>

<input class="bt202" id="00202" type="button" onclick="tocar_video('http://somesite.com/somevideo.mp4');"></input>

Mas não tive êxito para fazer o vídeo aparecer, alguém saberia apontar o problema?
Comment: Vc quer por o vídeo dentro do input?
Comment: https://videojs.com/
Answer: Creio que você quer adicionar ele a algum lugar, se for isto então tem que usar appendChild para adicionar a um local desejado da página, por exemplo:

var lastVideo;

function tocar_video(mysrc){
    if (lastVideo && lastVideo.stop) {
         lastVideo.stop(); //Para o video anterior
    }

    var video = document.createElement('video');

    video.src = mysrc;
    video.autoplay = true;

    var videoContainer = document.querySelector("#video-container");

    videoContainer.innerHTML = ""; //Limpa elementos dentro do container ou video anterior

    videoContainer.appendChild(video);

    lastVideo = video; //Define para poder ser parado se trocar de video
}
.bt202{
 background-image:url("https://image.freepik.com/icones-gratis/botao-de-play_318-42541.jpg");
 background-size:100% 100%;
 background-repeat:no-repeat;
 width:50px;
 height:50px;
}
<input class="bt202" id="00202" type="button" onclick="tocar_video('https://www.w3schools.com/html/mov_bbb.mp4')">

<input class="bt202" id="00203" type="button" onclick="tocar_video('https://upload.wikimedia.org/wikipedia/commons/9/96/Video_animation_gyroscope_precession.ogv');">

<input class="bt202" id="00204" type="button" onclick="tocar_video('https://upload.wikimedia.org/wikipedia/commons/9/99/Animation_of_Rotating_Earth_at_Night.webm')">

<input class="bt202" id="00205" type="button" onclick="tocar_video('https://upload.wikimedia.org/wikipedia/commons/b/bb/Animation.ogv');">

Comment: Sim, obrigado, resolveu o problema. Mas desse modo é possível manipular as medidas, controls e outras funções ?
Eu tentei algo como `videoContainer.setAttribute("width","400");` e não funcionou
Comment: @Dr.G adicione no `video` o `setAttirbute` e não no `videoContainer`

Criar um video pelo javascript