Random nonegative solution of multivariate linear Diophantine equation

Question: Consider a diophantine equation in n variables:  $a_1x_1+a_2x_2+...+a_nx_n=k$
All $a_i$'s, $x_i$'s and $k$ are restricted to non-negative integers $\mathbb{Z^+}$. (note that because of domain restrictions the number if solutions is guaranteed to be finite)
I need to generate a random solution to this equation and i do not know how to approach it. In other words i need an algorithm which is equally likely to generate any one of the possible solutions.Any help would be welcome.
Comment: Do you just need *a* solution, or do you need an algorithm which is equally likely to produce any of the solutions?
Comment: yes, i need an algorithm which is equally likely to produce any of the solutions. sorry if i was unclear.
Answer: Let $f(a_1, a_2, \ldots, a_n, k)$ be the number of solutions.  This is the coefficient of
$x^k$ in the Maclaurin series $\prod_{j=1}^n (1 - x^{a_i})^{-1}$.  The number of solutions with $x_1 = t$ is $f(a_2, \ldots, a_n, k - a_1 t)$ for $t = 0$ to $\lfloor k/a_1 \rfloor$.
So choose $x_1$ with the probabilities $P(x_1 = t) = f(a_2,\ldots,a_n, k - a_1 t)/f(a_1,a_2,\ldots,a_n,k)$.  Proceed recursively.


Android - AppWidget AppWidgetManager.updateAppWidget() not being called instantly

Question: I am developing an appwidget that uses the RemoteViews to display a ListView. For simplicity's sake, I will give an analogy of the appwidget's functionality:

The user will select to add the appwidget to the home screen. Upon selecting the widget, a configuration activity is launched and the user selects from one recipe from a list of recipes.
Upon selecting the recipe from the configuration activity, the configuration activity broadcasts the AppWidgetManager.ACTION_APPWIDGET_UPDATE intent. This intent received and handled in the onReceive method of my AppWidgetProvider class. From here the RemoteView is instantiated and passed into the AppWidgetManager.updateAppWidget() method. This proceeds to fill in the ListView of ingredients.

This all works as expected, except when I attempt to manually update the ListView from the appwidget. I have set a PendingIntent to re-launch the configuration activity, which also works. Unfortunately, the call to AppWidgetManager.updateAppWidget() does not get called instantly as it did when being launched upon adding it to the home screen and the ListView does not get updated. The update does get called, however, after scrolling down the list a ways (until it gets passed the number of rows it has loaded in its cache, I reckon). This fires off my FlightBoardAppWidgetService and ViewsFactory as it should. It is almost as if the updateAppWidget is getting put into some lazily-loaded queue. I tried to look at the Android source code to see how AppWidgetManager.updateAppWidget() is coded, but it appears to be hidden.
tl;dr: AppWidgetManager.updateAppWidget() does not always get called instantly, what gives?
Is there any way to get the ListView to update when it is actually called? What am I doing wrong? Thanks!
Answer: Well, I ended up solving the problem finally. It is somewhat of a hack, but I ended up solving the problem  by declaring a refresh broadcast and an update broadcast. Each time I want to update the widget I call updateAppWidget(), and then from the function that receives and handles this broadcast, I launch another broadcast that calls notifyChanged. This works all of the time!


How can I import fields into Drupal 8.4 user profile from a csv file that has identical values in the key row?

Question: I'm using Migrate Tools, Migrate Plus and Migrate Source CSV. My CSV file looks like that:
"Stg";"Color";"Fruit"
"user1";"red";"apple"
"user1";"blue";"pear"
"user2";"green";"banana"
"user2";"black";"rotten banana"

I'm using the Profile Module (https://www.drupal.org/project/profile)
I have a migration within my migration group that looks like this (migrate_plus.migration.user_vorlesungen.yml):
id: user_vorlesungen
langcode: de
status: true
dependencies:
    enforced:
        module:
            - user_migrate
migration_group: hoevwa
label: 'HoeVWA Vorlesungen Import'
source:
    plugin: csv
    track_changes: true
    path: /config/Vorlesungsverzeichnis.csv
    # Column delimiter. Comma (,) by default.
    delimiter: ';'
    # Field enclosure. Double quotation marks (") by default.
    enclosure: '"'
    header_row_count: 1
    keys:
        - Stg
destination:
    plugin: entity:profile
process:
    type:
        plugin: default_value
        default_value: 'vorlesungen'
    uid:
        plugin: migration_lookup
        no_stub: true
        # previous user migration
        migration: user__hoerer
        # property in the source data
        source: Stg
    # These field have multiple values in D8
    field_color: Color
    field_fruit: Fruit

migration_dependencies:
    required: {  }
    optional: {  }

In my YAML file the content is printed like that:
...

    {{ content.field_color }}
    {{ content.field_fruit }}

...

When I run drush mim --group=hoevwa only the last values of user1 (blue, pear) are imported. How can I get running a process plugin to loop through the CSV and get all values imported. And finally how can I loop through all values in my TWIG Template?
Answer: The solution will be to create a custom Migration Source Plugin and do some magic in the fetchNextRow() method. Depending on the source of your data, you might also use some other approach.


Implementing a Query Using @NamedQuery with a 'SELECT OBJECt(var) FROM EntityName var

Question: I have started  to learn JPA and I have searched on many sites and I couldn't find an explanation regarding this example :
Implementing a Query Using @NamedQuery:
   @Entity
   @NamedQuery(
    name="findAllEmployeesByFirstName",
    queryString="SELECT OBJECT(emp) FROM Employee emp WHERE emp.firstName = 'John'"
)
public class Employee implements Serializable {
...
}

I just can't understand why the author is selecting an Object(emp)..why doesn't he use something like this SELECT emp FROM Employee emp WHERE emp.firstName = 'John'
Is there a difference ? Do I miss something ?
Answer: SELECT OBJECT(emp) FROM Employee emp

is the exact same as
SELECT emp FROM Employee emp

See the JPA spec.
[69] Note that the keyword OBJECT is not required. It is preferred that it be omitted for new queries.
The origin of "OBJECT" is in EJBs (now outdated).
Comment: Thank you for your time to answer @Neil!
Answer: They are synonym expressions when selecting entities.
It's the same thing when in Java you declare interface, you could declare abstract interface but it is longer and it brings nothing, so nobody does it.
Answer: The difference is that even though path expressions can resolve to an entity type, the syntax of the OBJECT keyword is limited to identification variables.
You can safely remove OBJECT from the query.
To make an example, if Employee has a relationship with a Department entity, this query would be illegal using object:
SELECT OBJECT(emp.department) FROM Employee emp WHERE emp.firstName = 'John'  // Not valid
SELECT emp.department FROM Employee emp WHERE emp.firstName = 'John' // Valid

Comment: explanation a little complicated but you are right.
Good example. +1


setTimeout not working after update to jquery version 1.8.1

Question: hello i was using my long polling code from a long time it was working fine with jquery verison 1.8 but since i upgraded it to verison 1.8.1 it stopped working and its giving me the error

Error: NS_ERROR_XPC_BAD_CONVERT_JS: Could not convert JavaScript
  argument arg 0 [nsIDOMWindow.getComputedStyle]

this is my code
<code>  (function pollfrnd() { setTimeout(function() {
        var demon=$('.frndnotimore').val();
        var page="notirequest";
        var a=$('.gvpgvpxgvp').val();
        $.ajax({ url: 'modules/notifications/beast.php?nid='+demon+'&id='+a+'&page='+page,
        success: function(html) {
        if ($.trim(html) == 'no')
        {

        }
        else
        {

        $('.frndnotimore').remove();
        $('.notiloadfriend').prepend($(html).fadeIn('slow'));
        counter(a,page);
        }
        }, dataType: "html", complete: pollfrnd }); }, 60000); })();

    });
</code>
Comment: Do none of the [results which come up for a search for that error](https://www.google.co.uk/search?q=NS_ERROR_XPC_BAD_CONVERT_JS) lead you to a solution?
Comment: nope , i first tried it on google but still no help so i asked for help here
Comment: when you get data back from `beast.php` what does the HTML look like? Also, what does `counter(a,page)` do? any further DOM manipulations?
Comment: yes , the counter is for count of notifications . and html is like a normal html
Comment: the code works (albeit 404 errors) even if not connected to the internet, I am pretty sure his code is not the issue actually.
Comment: its not working with jquery 1.8.1 in firefox but its working with jquery 1.7 in firefox why?
Comment: Param just a wild guess (since I don't know what your code is really doing after you get the ajax) - in your code success callback you call $('.frndnotimore').remove(); but then it is needed again next time for $('.frndnotimore').val(); but it is not 100% clear if it is put back in DOM from your ajax response or not - is Firefox + New Jqueryversion choking on perhaps on this .frndnotimore element being missing from DOM while other browsers don't? dunno... I mean check if for some reason Firefox + neWJquery hates it if you are missing DOM elements or something like that
Comment: there is a `frndnotimore` present which is removed and ajax introduces new one
Comment: yes, and weird thing is - even in MY Firefox just now, with new Jquery 1.8.1, and even considering that I am not connected to internet (so my ajax doesn;t put it back) it STILL works with "undefined" and 404 error anyway - I still don't get nsiDOMERROR - so your code is OK anyway even on my test, with new Firefox, and new Jquery 1.8.1 - whats going on!!!! Try reinstall your firefox??? Whats your FFox version?
Comment: my firefox version is latest 14.0.1
Answer: When I run your code exactly as below, I get no error at all actually(jquery 1.7.2 AND jquery 1.8.1 AND EVEN Firefox 14) and it even tries to poll something:
<code>function pollfrnd() { setTimeout(function() {
        var demon=$('.frndnotimore').val();
        var page="notirequest";
        var a=$('.gvpgvpxgvp').val();
        $.ajax({ url: 'modules/notifications/beast.php?nid='+demon+'&id='+a+'&page='+page,
        success: function(html) {
        if ($.trim(html) == 'no')
        {

        }
        else
        {

        $('.frndnotimore').remove();

        $('.notiloadfriend').prepend(html);
        //This code below was your problem in Firefox
        //$('.notiloadfriend').prepend($(html).fadeIn('slow'));
        counter(a,page);
        }
        }, dataType: "html", complete: pollfrnd }); }, 60000); }

 pollfrnd();
</code>
Comment: Remember, use $('.notiloadfriend').prepend(html); not the animation one you had that said $('.notiloadfriend').prepend($(html).fadeIn('slow')); to avoid that strange error you described in your question that only happens in Firefox


Format date in validation message with Laravel 5

Question: In my database i have date field in format Y-m-d H:i:s. What I want is, that this date is always bigger then this moment, when adding new item in database. I check this with laravel's validator:
Validator::make->($request->all(), [
     'date'=>'date|after:'.date(Y-m-d H:i:s)
]);
The problem is, that my page is in different languages, and each language has different date formats. Sometimes I want default format, sometimes i want d.m.Y H:i:s, and so on..
I made translations for different languages in resources/lang directory. For validation, I translated existing validation.php file, but the problem is, I don't know how to format date, if that is even possible with this approach. For now, my date is always in default format, the one I compare my input with. My validation.php file looks like this:
<?php

return [
   'after' => 'The :attribute must be a date after :date.'
];

My question now is, how to format :date attribute. Any help would be appreciated.
I tried already:
'after' => 'The :attribute must be date after'.date(format, strtotime(':date'))

But it doesn't do anything.
Answer: I'm not sure if it solves your problem, but I tested this:
$dateFormat = 'j.n.Y';
$this->validate($request, [
  'date' => 'date_format:'.$dateFormat.'|after:' . now()->format($dateFormat)
]);

and it seems to work.
Changing the $dateFormat, it displays errors correctly.
Answer: The dates will be always passed into the PHP strtotime function.
To make date always bigger than this moment you can simply use the term now.
Laravel make it pretty simple as below.
Validator::make->($request->all(), [
 'date'=>'date|after:now'
]);

Comment: Thank you for your answer, but this is not actually what i am looking for. My validation works correctly, the problem I am having is with formatting date in validation message. Even if I use your approach, and put now in attributes and translate it, validation message still returns :date as now.
Comment: I would be satisfied if "now" would be translated, but I still prefer acutal date.


How do I get a date selector field in a content entity?

Question: I have a content entity in Drupal 8 that generates form for datetime. I just want to show only the date selector in the form, but it shows date and time selectors.
     $fields['start_date'] = BaseFieldDefinition::create('datetime')
            ->setLabel(t('Start date'))
            ->setDescription(t('The date that the survey is started.'))
            ->setRequired(true)
            ->setDisplayOptions('view', array(
                'label' => 'above',
                'type' => 'string',
                'weight' => -4,
            ))
            ->setDisplayOptions('form', array(
                'type' => 'date',
                'weight' => -4,
            ))
            ->setDisplayConfigurable('form', TRUE)
            ->setDisplayConfigurable('view', TRUE);

How do I show only the date selector?
Answer: Your problem is that you are setting the option on the form and not the field.  The datatime field has an option, datetime_type which can be two strings 'date' or 'datetime' (see DateTimeItem), and it defaults to 'datetime'.
So, when you are creating your field, you need to update this setting.  The following should work for you:
$fields['start_date'] = BaseFieldDefinition::create('datetime')
  ->setLabel(t('Start date'))
  ->setDescription(t('The date that the survey is started.'))
  ->setSetting('datetime_type', 'date')
  ->setRequired(true)
  ->setDisplayOptions('view', array(
    'label' => 'above',
    'type' => 'string',
    'weight' => -4,
  ))
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE);

As a side note, when you are having problems like this, the first place to look is at the class implementing the field that you are using, and then look at the tests that cover that field.  Often, you will find the example code that you need.  In this case, you would look at DateTimeFieldTest and see what that integration test is doing.
Comment: @Kevin this creates it as a datetime field, so you get all of the stuff that goes along with it (eg, the formatters).  Datetime fields are stored as (mostly) ISO8601 strings which are sortable easily (they are always UTC in storage), indexable, and also easily manipulated in SQL to extract parts.  Date/time manipulation is not standardized between MySQL PostgreSQL, and SQLite, so this last bit can important.  Also, picking nits, but they aren't varchar, they have a hard limit of 20 (will be bumped to 25 soon).
Comment: i am not sure about that, that ll create a varchar type field in mysql... if you want sort on date it's not really the best way


Error while migrate wordpress to drupal

Question: I want to migrate a wordpress blog to drupal. I create an "Article blog" content type with three fields: body, tags and categories (plus default title field). I am trying to import with Wordpress migrate (version 7.x-2.2) via url or file, both solution return same error while importing for each article:

Illegal string offset 'translatable' File drupal_root/modules/field/field.multilingual.inc, line 176

I am using drupal 7.22 with commons profile 7.x-3.2.
All other imports (tag, categories and attachments) works fine.
Do you have an idea about how to solve my problem?
Answer: If you can export the content to a csv format. Then use Feeds to import the csv file to the mapped fields.
Comment: doesn't work... I have a to old wordpress version... and can't do anything for that at this point. Not a problem, I have another solution... thanks for your help

Error while migrate wordpress to drupal


Removing Exchange 2010 and SBS2011 gracefully after migration to Server 2008 Std R2

Question: We have recently completed a server replacement for a customer. They had SBS2011 using Exchange 2010. They now have Server 2008 Std R2 and Google Apps email. We have migrated the DHCP, DNS, Filserver and all 5 FSMO roles to the new 2008 R2 server (today). During the grace period for SBS2011 we intend to decomission the old server completely.
Previous experience would suggest uninstalling Exchange 2010 then demote SBS2011 then remove from the domain and switch off. Can I simply demote SBS2011 without removing Exchange?
Can't really find any walkthroughs on this.
My concern is that if we simply turn off SBS2011 the AD is left in a mess with legacy Exchange objects making any potential reintroduction of Exchange difficult in future, plus I want to do it the right way!
Answer: I'm not sure there is a 'correct' way to do this...
Demoting a DC Exchange Server usually indicates that a new DC running Exchange will be taking over immediately.
You are probably best following through instructions on removing SBS as that will include Exchange. But check after demoting your server that the Exchange Objects also are removed cleanly.
As this is an old question - how did you proceed and what results (+problems) did you experience?
Comment: Thanks Haydn, I uninstalled Exchange 2010 as part of the SBS removal process which leaves the AD in a sane state. I didn't encounter any issues with the Exchange uninstall.

After another 2 exchange 2003 to 2010 migrations since this question I am now satisfied with my understanding of AD objects removed and necessity to uninstall Exchange to keep AD tidy.
Comment: Thanks for the feedback and update, you certainly did things the right way - keeping AD working (and tidy) should be the main object of any changes! I'm stuck in a situation which may require a similar resolution - SBS2011 on an underspecced server. Solution looks like introducing a second server for the workloads as virtualisation/cloud is off the cards.
Answer: Did you join the new DC to the existing SBS domain, or create a new Active Directory forest? My understanding is that an SBS server must be at the root of its own forest, and while additional domain controllers can be added, the original server cannot be removed. This is why Microsoft's instructions on migrating from SBS to another server dictate that the new server create a new Active Directory Forest and Domain.


Is a parabola really a conic section?

Question: A parabola is supposed to be a conic section, obtained by slicing through a cone with a plane, like this from Wikipedia:

But if you do this, what you get is just part of an elipse, since if the cone and the plane were bigger, eventually you'd end up with an elipse. And a section of an elipse is not a parabola - there is no possible focal point that satisfies the condition that all points on the curve are equidistant from the focal point and the directrix - at least not when I try to construct this in my CAD software
Answered by JonathanZ, the key thing was the parabola needs the slicing plane parallel to the slope of the cone (not illustrated or explained clearly in either Wikipedia or Wolfram IMHO). Here's what it looks like in my construction:
Comment: The axis of the parabola must be parallel to a generatrix of the cone.
Comment: The cone is also infinite in both directions (imagine another cone at the apex of this one but going in the other direction).
Comment: @HopefulWhitepiller - When the OP says "... if the cone and the plane were bigger, eventually ...", it sounds like they they are in fact _relying_ on the infinite size of the cone.
Comment: If the "other part" of the ellipse is at infinity (since the plane is parallel to the cone side) then you have a parabola. The corollary to this if you sketch a parabola on the ground to infinity and view it in perspective from above the ground it will appear as an ellipse
Answer: It's not clear what you're saying about "not being able to find a focal point and directrix", but if you are trying to create this construction with CAD software, it seems worth mentioning that "being a parabola" exists at a "critical point", i.e.

if you've got an ellipse and jiggle parameters a small bit, you still get an ellipse,

if you've got a hyperbola and jiggle parameters a small bit, you still get a hyperbola

if you've got a parabola and jiggle parameters a small bit, jiggle one direction and you get an ellipse, jiggle in the other direction and you get a hyperbola.

Phenomena like this, which are perched on the transition line between two areas, are very hard to render with finite precision math. I wonder if that's the problem you're running into?
Also, as to your comment "if the cone and the plane were bigger, eventually you'd end up with an elipse" - in order to get a parabola, the slicing plane has to be exactly "parallel" to the edge of the cone opposite to it, i.e. never intersect it. (It looks a little off in your image, possibly due to the angle of view.) This is again something very hard to do with finite precision math: Draw some random line, then try to come up with a plane that never intersects it. If you're the least bit off there's going to be some intersection, probably way off in the distance, but intersection none the less - even though we can mathematically show such a plane exists, and give an equation for it.
Comment: Excellent! As someone who used to write CAD code, I'm still not 100% sure your model won't close up into an ellipse at the gigameter scale, but we often relied on the user not zooming out that far. :-) And BTW, if you think this is the best answer, you can check the check mark on the left hand side, so the question is marked "solved", and I get some rep points.
Comment: Thank you Jonathan - that's cleared that up. The bit I was missing was that the slicing plane has to be parallel to the slope of the cone... and therefore never becomes an ellipse. This works perfectly in CAD now (no issues with mathematical precision for this type of problem, CAD can happily model something at meter scale to nanometer precision). I'll update the question to illustrate your answer... since I can't attach an image here...
Answer: Let us work out the equation of the intersection of a cone and plane in terms of some plane coordinates $(u,v)$ and see if it is a parabola indeed. Place a coordinate system on the apex of the cone.
Place the axis of the cone along the $\hat{j}$ direction, and slice it with a plane rotated an angle half of the cone angle $\psi$

The plane exists at a fixed distance $d$ from the origin, along the direction
$$ \hat{n} = \pmatrix{ \text{-}\cos \frac{\psi}{2} \\ \;\sin \frac{\psi}{2} \\ 0} $$
This defines the out of plane direction and also the two in-plane directions of $$ \hat{e} = \pmatrix{ \sin \frac{\psi}{2} \\ \cos \frac{\psi}{2} \\ 0} $$ and $\hat{k}$ which is common between the global coordinates and the plane coordinates.
We define a point in space $\boldsymbol{r}$ to be on the plane if it expressed as
$$ \boldsymbol{r} = d\,\hat{n} + u\,\hat{k} + v\,\hat{e}  \tag{1}$$
where $(u,v)$ are the in-plane coordinates of the point. You can prove the above as it obeys the vector plane equation of $\boldsymbol{r} \cdot \hat{n} = d$ given a plane unit normal vector $\hat{n}$ and distance $d$ from the origin ($\cdot$ is the vector dot product).
Now these points must also obey the equation of a cone, which in this case can be written as
$$ \boldsymbol{r} \cdot \hat{j} = \| \boldsymbol{r} \| \cos \tfrac{\psi}{2} \tag{2}$$
The above states that the angle between the vector $\boldsymbol{r}$ and $\hat{n}$ should equal to $\psi/2$ for all $\boldsymbol{r}$.
The we can use the plane points from (1) in the cone equation (2) to get
$$ \begin{gathered}\left(d\,\hat{n}+u\,\hat{k}+v\,\hat{n}\right)\cdot\hat{j}=\|d\,\hat{n}+u\,\hat{k}+v\,\hat{n}\|\,\cos\tfrac{\psi}{2}\\
d\,\left(\hat{n}\cdot\hat{j}\right)+u\,\left(\hat{k}\cdot\hat{j}\right)+v\,\left(\hat{n}\cdot\hat{j}\right)=\sqrt{d^{2}+u^{2}+v^{2}}\,\cos\tfrac{\psi}{2}\\
v\cos\tfrac{\psi}{2}+d\sin\tfrac{\psi}{2}=\sqrt{d^{2}+u^{2}+v^{2}}\,\cos\tfrac{\psi}{2}\\
v+d\,\tan\tfrac{\psi}{2}=\sqrt{d^{2}+u^{2}+v^{2}}\\
\left(v+d\,\tan\tfrac{\psi}{2}\right)^{2}=d^{2}+u^{2}+v^{2}\\
\left(d\,\tan\tfrac{\psi}{2}\right)^{2}+2\left(d\,\tan\tfrac{\psi}{2}\right)\,v=u^{2}+d^{2}\\
v=\frac{u^{2}+d^{2}-\left(d\,\tan\tfrac{\psi}{2}\right)^{2}}{2\left(d\,\tan\tfrac{\psi}{2}\right)}
\end{gathered}$$
which is clearly a parabola since it is of the form $v = a u^2 + b$ with coefficients $a = \tfrac{1}{2 d} \cot \tfrac{\psi}{2}$ and $b = d \cot \psi$ which are constants derived from the geometry of the problem.
Comment: Well, this is overkill, but I admire it. +1.
Comment: Hmm, I meant "overkill" as a compliment. I mean, i wrote an extended answer about the perils of finite precision arithmetic, and the OP's reply was "ah, plane parallel to generatrix, got it." So I thought you went above and beyond what the OP wanted, but nailed down down all the details very nicely.
Comment: How is it overkill what is a mathematical proof of the question at hand? This is still [Math.SE] the last time I checked. It uses geometry, vector algebra and function analysis to bring the point home.
Answer: If the plane is parallel to the slope of the cone, then no matter how big the plane and the cone are, it will never close into an elipse.
Take the vertex of the parabola in your image, now draw a line perpendicular to the parabola (i.e., along the axis of symmetry, in the image it is the dotted straight line). If the intersection was an elipse, this line should eventually intersect again the cone. But since it is parallel to the slope of the cone, it will never cut it again.

Is a parabola really a conic section?


Non-constant continuous map from $\mathbb{R}P^2$ to $\mathbb{R}$

Question: Give an example of non-constant continuous map from $\mathbb{R}P^2$ to $\mathbb{R}$.
My attempt: Since $\mathbb{R}P^2$ is closed unit disc with antipodal points of the boundary identified. I will restrict the projection map from $\mathbb{R}^2$ to $\mathbb{R}$ to closed unit disc. then can i use this to get the required map.
Comment: If you have a metric $d$ on a set $X$, then $f(x)=d(x_0,x)$ is always a continuous map $X\to\mathbb R$, for any $x_0\in X$.
Comment: why is d a metric??
Comment: Why is what a metric?
Comment: @ThomasAndrews is RP2 metrizable?
Comment: It is, but you'd need to show it is. And it depends on how you define $\mathbb RP^2$ how you'd define a metric. Probably easiest if $\mathbb RP^2$ is defined as the sphere with anti-podal points identified.
Comment: Embed in $\mathbb{RP}^2$ in some $\mathbb{R}^n$ and take a coordinate map.
Answer: Try $[x : y : z] \mapsto \frac{x^2}{x^2+y^2+z^2}.$
Comment: I wanted something with polynomials that is well defined on $RP^2$, so something like $p/q$ where $p$ and $q$ are homogenous would work. Then I needed to ensure $q$ never vanishes(on the specified domain), and for this the sum of squares works.
Comment: Why did u think about this map
Comment: since RP2 is a topological manifold and this map is continuous in the standard coordinate charts of RP2 I believe it follows it is continous. it looks pretty continuous anyway. you can also check it is nonconstant by plugging in some values
Answer: Let $\overline{\mathbb{D}}$ denote the closed unit disc in $\mathbb{C}$ and consider the map $f : \overline{\mathbb{D}} \to \overline{\mathbb{D}}$ given by $f(z) = z^2$. If $z, w \in \partial\overline{\mathbb{D}}$ are antipodal points, then $f(z) = f(w)$ so the map descends to a map $\hat{f} : \mathbb{RP}^2 \to \overline{\mathbb{D}}$ satisfying $\hat{f}([z]) = f(z)$. The map $|\hat{f}|$ is then a continuous non-constant map $\mathbb{RP}^2 \to \mathbb{R}$.
Answer: The following works for any manifold: Let $U \subset M$ be an open set homeomorphic to the unit disk $B$ in $\mathbb R^n$ via a homeomorphism $\varphi : U\to B$. Then define $f : M\to \mathbb R$,
$$f(x) = \begin{cases} \max\{-|\varphi (x)|+1/2, 0\} & \text{if }x\in U, \\ 0 &\text{if } x\notin U.\end{cases}$$
(That is, find a continuous nonconstant function on $B$ with compact support and then extend the function on $M$ and setting other points to be zero)
Answer: Indentify $\mathbb{R}^2$ by $\mathbb{C}$ and consider the map $\nu\colon \mathbb{C}\longrightarrow \mathbb{R}$ which takes $z$ to its norm $\nu(z)=|z|$.
Comment: This gives you a map $\mathbb{R}^2 \to \mathbb{R}$, not $\mathbb{RP}^2 \to \mathbb{R}$.


Mathematical Probability Problem

Question: Some friends and I were having an odd discussion about a hypothetical scenario. We couldn't come to a conclusion and as I believe the answer is based on mathematical probability I found this community hoping for a proven solution. I hope I have come to the right community for help.
The scenario is as follows (it is somewhat odd):
A person is having a shower and washing their hair with shampoo. This particular shampoo is somewhat deadly. The shampoo is running down your face and there is a 75% chance some will go in your eyes, and a 25% chance some will go in your mouth.
If the shampoo gets into your eyes, there is a 25% chance you will go blind. If the shampoo gets into your mouth, there is a 75% chance you will die.
You only have time to stop it from getting into either your eyes or mouth. Which would you choose to stop.
So our question is, of the 2 final outcomes, which, if either, is more likely?
In summary:
25% chance of A. If A, 75% chance of B.
75% chance of X. If X, 25% chance of Y.
Is either B or Y more likely overall?
I hope I have made the question clear enough. Thanks in advance for any help.
Answer: The odds are exactly the same. Probabilities multiply. There is a
$$\frac{1}{4}\ast\frac{3}{4}=\frac{3}{16}$$
chance of both outcomes. Avoid death.
Comment: Thank you very much.
Comment: This is correct, assuming your events are independent (which it seems they are).

Mathematical Probability Problem


Converting a string of numbers to correpsonding letters

Question: For a project I am working on, I need to be able to convert a string of numbers into letters to form the correct words.  For example, I would need to convert 2626 into BFBF, but how would I make sure it does not turn into ZZ instead or vice versa.
I am extremely confused because I cannot think of any way to make this possible, and I need this program to convert the numbers into their original letters.
Any help would be greatly appreciated, since I am not really sure what to do anymore…
Thanks you!
EDIT:  It seems as though this is impossible without using a list of numbers, so now I need to find a way to replace my strings with lists.  The problem is that I am making a public key cryptography encryptor/decryptor and I do not know how to do math on numbers without them being a string. (It wouldn't work for a list, for example if I had to square a number, 1212, I can easily do so with 1212^2.  However if the list was [12,1,2], I do not know how to square it to get the same answer as 1212^2.)
Any help would be great, Thanks Again!
Comment: Use a list, e.g. [2, 6, 2, 6], otherwise there is no way to reliably differentiate between combination of digits such as [26, 26] vs. [2, 6, 2, 6].
Comment: Once you use a list, use `chr()` to convert. `chr(65) = 'A'` and `chr(90) = 'Z'`
Comment: So there's no way of doing it using integers?
My project is a public key encrypted and decrypted, but on a very small level.  First, the user enters their secret code.  I then convert their code into numbers using (a=1,b=2, etc…) and then raise it to a power with a mod base etc. with the other steps to public key.  Then, with the encrypted message, the code continues public key to undo the message, and finding the number representation of the letters, which I have done.  The final step is converting these numbers into their original numbers, which I cannot find out how to do.
Comment: If you can use a delimiter between integers yes, otherwise you'll have problems.
Comment: @Alexander I understand what you're saying, but please check out my most recent edit.
Answer: Using chr() you can convert an int to a letter, ex. print chr(97) prints a.
If you can use some symbol to identify groups, maybe '-', between numbers, then this is a simple problem.  If not you will run into ambiguous mappings as you mentioned.
For example you could create a number to letter dictionary:
alphabet_dict = {}
for abet in range(1, 27):
    alphabet_dict[abet] = chr(96+abet)

print alphabet_dict

prints:
{1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e', 6: 'f', 7: 'g', 8: 'h', 9: 'i', 10: 'j', 11: 'k', 12: 'l', 13: 'm', 14: 'n', 15: 'o', 16: 'p', 17: 'q', 18: 'r', 19: 's', 20: 't', 21: 'u', 22: 'v', 23: 'w', 24: 'x', 25: 'y', 26: 'z'}

Now if we decide we can use a symbol delimiter, then we can use built in split() to break up our string into a list and then map those values (numbers) into the alphabet using the dictionary above:
s = '2-6-2-6'
def convert_num_to_alpha(num_string):
    num_list = num_string.split('-')
    abet_string = ''
    for num in num_list:
        abet_string = abet_string+alphabet_dict[int(num)]
    return abet_string

print convert_num_to_alpha(s) # prints: bfbf
print convert_num_to_alpha('26-26') # prints: zz

EDIT: How to convert the string of number-number (e.g. '2-6-2-6') to int:
This is hackish but if you need to do arithmetic on the number, which I have stored as a string you can do something like:
print int('2-6-2-6'.replace('-', ''))  # prints: 2626

Comment: Thanks for your help.  I will most likely post another post that goes into more depth about my problem.
As for your edit, I see how you converted the list into an integer, but after you do the arithmetic, it would be impossible to revert it into the correct integers, but correct me if I'm wrong.
Comment: I see how that works, but like I said in my most recent edit:
(It wouldn't work for a list, for example if I had to square a number, 1212, I can easily do so with 1212^2. However if the list was [12,1,2], I do not know how to square it to get the same answer as 1212^2.)
Comment: @Flo my example only uses a list as an intermediate step to manipulate each individual number between `-`.  In my edit I show how you could get the integer from such a string.
Comment: @Flo in general it seems like this approach (your encrypt/decrypt) may need another look.  Perhaps you should post, in another question, your full problem, how you are currently approaching it, list the pitfalls, and how to fix them.  Be aware, don't ask too many questions in one post and steer clear of asking for advise.  State what is broken and ask how to fix it.
Comment: @Flo My pleasure to help (or try).  Just to be clear, the edit is converting a **string** to an integer, not a list.  As far as modular arithmetic and finding the 'correct' integers after, you're using a many to one function so there is no way to distinguish between any numbers mapped to a particular equivalence class, so you're right.
Comment: In case you are curious, I found a way to fix it using a method similar to the one you proposed.
Comment: @Flo Definitely, what did you do?
Comment: I used str.zfill(2) so that all the letters would be represented by 2 number; a = 01, b = 02, etc…
Then, instead of doing the arithmetic to all the numbers in one string, I kept it as a list and did the same math to each element of the list.  From that I could easily make it into one string to get the "encrypted message", or just continue decrypting it as a list, which would be able to differentiate between letters because each one is represented by 2 unique numbers.  Seems so obvious now, but that is how coding is!
Comment: @Flo Nice idea.  It does seem as though things are so much easier once you figure them out...By the way, it is perfectly acceptable to post an answer to your own question and then accept it.  Of course your solution will still be open to scrutiny from others.
Comment: By the way, I just asked another question regarding another problem I encountered with the same program.. Mind checking it out?
Comment: @Flo Looks like someone already got to it.  By the way, if you look at how I made the dictionary above `for abet in range(1, 27):
    alphabet_dict[abet] = chr(96+abet)` this is exactly what you need.  I made that dictionary to serve as a look up 'table' to map between integer (1 through 26) to alphabet letters (a through z).


Best practices for Inversion of Control in libraries?

Question: I've been tasked with establishing code patterns to use for new applications that we'll be building. An early decision was made to build our applications and libraries using Prism & MEF with the intent of simplifying testing & reuse of functionality across applications.
As our code base has grown I've run into a problem.
Suppose we have some base library that needs access to some system - let's say a user management system:
<code>public interface IUserManagementSystem
{
    IUser AuthenticateUser(string username, string password);
}
// ...
public class SomeClass
{
   [ImportingConstructor]
   public SomeClass(IUserManagementSystem userSystem){ }
}
</code>
We can now create an object of type SomeClass using the ServiceLocator, but ONLY if an implementation of IUserManagementSystem has been registered. There is no way to know (at compile-time) whether creation will succeed or fail, what implementations are needed or other critical information.
This problem becomes even more complicated if we use the ServiceLocator in the library.
Finding the now-hidden dependencies has become a bigger problem than hard-coded dependencies were in legacy applications. The IoC and Dependency Injection patterns aren't new, how are we supposed to manage dependencies once we take that job away from the compiler? Should we avoid using ServiceLocator (or other IoC containers) in library code entirely?
EDIT: I'm specifically wondering how to handle cross-cutting concerns (such as logging, communication and configuration). I've seen some recommendations for building a CCC project (presumably making heavy use of singletons). In other cases (Is the dependency injection a cross-cutting concern?) the recommendation is to use the DI framework throughout the library leading back to the original problem of tracking dependencies.
Dependency Inject (DI) "friendly" library is somewhat relevant in that it explains how to structure code in a manner that can be used with or without a DI framework, but it doesn't address whether or not it makes sense to use DI within a library or how to determine the dependencies a given library requires. The marked answers there provide solid architectural advice about interacting with a DI framework but it doesn't address my question.
Answer: You should not be using ServiceLocator or any other DI-framework-specific pieces in your core library. That couples your code to the specific DI framework, and makes it so anyone consuming your library must also add that DI framework as a dependency for their product. Instead, use constructor injection and the various techniques mentioned by Mark Seeman in his excellent answer here.
Then, to help users of your library to get bootstrapped more easily, you can provide separate DI-Container-specific libraries with some basic utility classes that handle most of the standard DI bindings you're expecting people to use, so in many cases they can get started with a single line of code.
The problem of missing dependencies until run-time is a common one when using DI frameworks. The only real way around it is to use "poor-man's DI", where you have a class that actually defines how each type of object gets constructed, so you get a compile-time error if a dependency is introduced that you haven't dealt with.
However, you can often mitigate the problem by checking things as early in the runtime as possible. For example, SimpleInjector has a Validate() method that you can call after all the bindings have been set up, and it'll throw an exception if it can tell that it won't know how to construct dependencies for any of the types that have been registered to it. I also like adding a simple integration test to my testing suite that sets up all the bindings and then tries to construct all of the top-level types in my application (Web API Controllers, e.g.), and fails if it can't do so.
Comment: Also, DO NOT use MEF with Prism.  MEF is not a DI container, and Prism is dropping support for MEF for a number of reasons.
Comment: This is extremely valuable. One of the benefits of DI is that it helps us to write testable code. But the DI registration is itself complex code that needs to be tested.


How to install a text filter for plain_text input format

Question: The users at my Drupal 7 website discuss a card game in plain_text comments and I'd like to format the hearts and diamonds characters by red color.
Based on the Examples module recommended to me here at "Drupal Answers" site I've added the following code to my custom module sites/default/modules/pref/pref.module:
function pref_block_view($block_name = '') {
       ... this other part of my custom module works well ...
}

function pref_filter_info() {
  $filters['plain_text'] = array(
    'title' => t('Pref filter'),
    'description' => t('Replace the ♠ ♣ ♦ ♥ characters'),
    'process callback' => '_pref_filter_process',
  );
  return $filters;
}

function _pref_filter_process($text, $filter) {
  $text = str_replace('♦', '♦', $text);
  $text = str_replace('♥', '♥', $text);
  return $text;
}

However still nothing is highlighted in comments.
The rest of my custom module works fine (it generates few blocks - for the Flash game and player rating).
How to register my filter for the plain_text please? I suspect that
 $filters['plain_text'] = array( ... );

is a wrong way.
Answer: Do it in GUI. http://example.org/admin/config/content/formats/plain_text
Check it in Enabled filters section and then make sure it's the last one in Filter processing order section. If you'll put it before Display any HTML as plain text, your tags will get added and then in the very next step removed.
Also,  tag may be removed by HTML cleaning modules. Modern way is to make it like  and then style it in CSS. Actually, it might be a wise idea to add  as well, and maybe "card" class for both, and respective classes for clubs, spades, hearts and diamonds. That way you will be able to style them differently or even use image substitution, if you wish - all in CSS.
You can provide default CSS in your module. In mymodule.info add line:
stylesheets[all][] = css/cards.css

Create that file in mymodule/css directory and place all styles there. That way they will be there, and themes will be able to override them in their own CSS files.
Comment: "if it works, do not touch" ;) I would change key from 'plain_text' to 'card_colors' and title to something like t('Card symbols coloring'). But that's me. These strings have nothing to do with how things works. 'plain_text' name is misleading as it does not cause your filter to appear in plain text format. It's just coincidence, bad one.
Comment: Awesome this actually works, thank you. Do you think my code above is sufficient? And should `$filters['plain_text'] = array(...);` be used there? (Yes, I will switch to CSS later).


Interpretation of values of survival analysis

Question: I am looking for some input regarding the interpretation of a survival analysis with the survfit()-function.
A bit about my data:
I am interested in analyzing in R whether people with a specific level of a blood parameter have a higher risk for developing a specific disease. I have a closed cohort in that sense that a certain amount of people got included and are then followed-up until a certain date. The inclusion dates stretch over three years and therefore the baseline date differs. Therefore, I decided to take age as the timeline for survival. Furthermore, I had death as competing risk to the disease of interest.
The analysis:
I used surfit() to analyze the survival with age at event as the time value and either censored, death or disease as event. Because of this competing risk, I used type = "mstate"in the Surv() part of the function.
survfit(formula = Surv(time = survival_years, event = event_indicator, type = "mstate") ~ cat, id = id)
The results:

Framed in orange are the cases and in green the deaths.
I know wonder, why rmean is so small in cases and deaths and does not represent a mean age of event. Should I change something in my analysis or do I need to interpret this values differently?
I also plotted a histogram of the age until event (called survival_years here):

There is no survival age below 40. So, how can the values from the survfit() function be so small?
A few weeks ago, I posted another question on how to conduct the survival analysis here. Based on the answers there I decided for this kind of survival analysis.
Survival analysis vs Cumulative incidence vc Incidence rate for cohort with varying baseline dates
Answer: Two points.
First, if you are going to use age since birth as the time scale, you need to account for the inherent left truncation. If someone enters the study at age 70, then that individual provides no information about individuals who couldn't enter the study before age 70. The information about event times is thus left truncated. You can handle that with the counting-process data format also used for time-varying covariate values: Surv(startTime, stopTime, event), where startTime is age at study entry and stopTime is age at the event. In practice, you might need to specify some minimal startTime. See Sections 3.4 and 4.6 of Klein and Moeschberger.
Second, the restricted-mean survival times for your multi-state model represent durations within those states: "restricted mean time in state" according to your printout (emphasis added). So the values for state 1 and state 2 aren't on your age time scale, but on an age-difference scale.
Comment: @Canicash first, you can't readily compare means of uncensored observations against model predictions, as the model takes censoring into account. Second, if I understand your model correctly, the restricted mean survival in `state1` might represent an estimate for the time between the "disease" event and death, not between age at inclusion and the "disease" event. Restricted mean survival in `state2` might represent an estimate of time between death and 86.46 years; the model doesn't know that `state2` is a final absorbing state. See https://www.ncbi.nlm.nih.gov/pmc/articles/PMC6133743/ .
Comment: @Canicash I find plots of probability of state versus time are more generally useful in this situation than restricted mean survival. Your situation is similar to that in Section 2.2 of the R survival [competing-risks vignette](https://cran.r-project.org/web/packages/survival/vignettes/compete.pdf); see the plot at the end of that section for an example. I don't often do multi-state models, so refer to that vignette for guidance and the correct interpretation of model coefficients and other results.
Comment: Thank you very much for the answer. I now wrote the function with `startTime`and `stopTime`.
I still have troubles with the interpretation of the restricted-mean survival time. The rmean for diseases is now between 0.4 and 0.6 years while the average for the difference between age at inclusion and age at event for this group is 6 years.


PSQL Dynamic Key value for json_agg

Question: I have this table structure:

I'm grouping every element into an array based on the name column:
SELECT json_agg(json_build_object(
  'id', id,
  'time', time,
  'version', version,
  'desc1', 'desc1',
  'desc2', 'desc2',
 ))
FROM my_table
GROUP BY name

which gives me this result:
[ { json_agg: [ [Object] ] }, { json_agg: [ [Object] ] } ]

how ever I want the json_agg key to be the same as the name column value.
like this:
[ { test1: [ [Object] ] }, { test2: [ [Object] ] } ]

How do I achieve this? Using an AS name doesn't work.
Comment: `json_agg` is the column name of the resulting row(s). You cannot make that dynamic. And your desired output doesn't really make sense - aren't you rather looking for something like a single `{"test1": [{…}, {…}], "test2": [{…}]}` object?
Comment: It might help you understand what's going on when you look at the output of `SELECT name AS key, json_agg(json_build_obect(…)) AS values FROM my_table GROUP BY name`
Comment: Please make one part of your example match the other part of your example.
Answer: For each grouping, you to build a new object using name and the aggregated array result in a subquery. Then aggregate the objects created in that subquery into a single array.
SELECT
  json_agg(elem) arr
FROM

(
SELECT
    json_build_object(
      name,
      json_agg(json_build_object(
        'id', id,
        'time', time,
        'version', version,
        'desc1', 'desc1',
        'desc2', 'desc2',
      ))
    ) elem

FROM
 my_table

GROUP BY
  name
) elem

PSQL Dynamic Key value for json_agg


Are A/B testing problems intrinsically a multiple testing problem?

Question: Can we convert any A/B testing problem into a multiple testing problem?
Comment: @FransRodenburg, why not make that an official answer? Although this question is rather sparse, it could be answered, & that would be it, AFAICT.
Comment: What is the context? If you change one button and check for its effect, then you are performing one test. So no, A/B testing is not intrinsically a multiple testing problem.
Comment: Thank you for the suggestion, I was not sure it would be sufficient information for an answer.
Answer: That depends on the context of using A/B testing:
If you change one button and check for its effect, then you are performing one test. So A/B testing is not intrinsically a multiple testing problem.
Comment: Ok. If we were to perform multiple A/B testing, potentially with a large number of features, would that be intrinsically a multiple testing problem?
Comment: Or in the case where companies run a sequence of A/B tests over time.
Comment: If you test $p$ features from a single experiment for significance, then you need to correct for $p$ tests. You could think of Bonferroni, or FDR if the former is too conservative. If you perform a new A/B test with new observations, then no correction is applied for having performed one previously on a different dataset.
Comment: Thanks. I'm currently working on a online FDR control paper, that's why I'm thinking of a multiple A/B testing application.


Non-normal univariate distribution -- how to define "low" to "high" subsets of values?

Question: Sorry for the dumb question: it's been a million years since I took basic stats.
I have a set of 48, non-normally distributed values ranging from 1 to 100.  I'd like to be able to apply a (valid) descriptive scale to these values, grouping values into sets along the lines of these are "low", these are "below avg", "avg" "above avg" & "high". Is this possible with a non-normal distribution (and a small value set like this -- this set is the full population I'm interested in)?
I was thinking in terms of quartiles and using the median rather than the mean -- but then would I have to stick to "low" "medium" and "high", using <Q1 as my "low" and>Q3 as my "high"?
Given that this is essentially a qualitative, descriptive objective, how wrong would it be to call values < Q1 as "low", Q1 to Q2 as "below avg", Q2 to mean as "average", mean to Q3 as "above average" and> Q3 as "high"?
[If it helps, Q1=22.4, Q2=30.8, Q3=47.2, Q4=100; mean is 35.3; mode=33.33 ... so a lot of my values do centre in the median-mean range there, it's just that I have a long tail toward 100 and it does not make sense to dump the values.]
The full set of values is:
0.0 0.0 10.5    11.1    11.5    13.3    14.3    16.7    17.1    20.0    20.0    22.2    22.5    23.1    23.1    23.5    23.7    24.7    25.0    26.7    27.1    29.5    30.0    30.4    31.3    33.0    33.3    33.3    33.3    34.8    35.0    38.3    41.2    42.9    46.2    46.5    49.2    50.0    50.0    52.8    55.6    55.6    58.1    60.0    66.7    80.0    100.0   100.0
Comment: There is no obvious merit in any of these labels. Who are they for? Why you do think they will add to the results of quantitative analysis, which you can keep as simple as you like?  With 48 values, you can easily plot all the values, the mean and median and the quartiles too. Then you can see which values are low, and so forth, and especially if they bunch. More specifically, mixing intervals based on the median and those based on the mean is at best messy and at worst will bite sooner or later. It's entirely possible for the mean to be above the upper quartile or below the lower quartile.
Comment: Are you trying to create "bins" or are you looking for outliers?
Comment: Thank you. I'm really just trying to ascertain whether it is permissible to use qualitative descriptors as I described in this scenario, and if so, what the appropriate way to break up the full set of values would be. ... But based on your question: would it be appropriate to use 5 bins? i.e. values from 0<20 are "low", <80 "high" etc.?
Comment: (Edit: Label-wise, my bin proposal doesn't actually make sense, so nevermind.) Basically: I'm talking to Joe People. I'm hoping I can say "These cases use a really low number of x; These others are below average; these others are above avg, and these ones are high." But I don't want to be inaccurate or misrepresent what these values actually mean.
Comment: if you can explain why not, you should post it as an answer to your own question. It might be helpful to someone in the future
Comment: I just edited my last comment to try to clarify, if that's oK. I appreciate your responsiveness.
Comment: Show us the 48 values and we can suggest graphical displays and/or comment concretely.
Comment: Thanks for your responses. You may be right that what I'm trying to do is pointless. That's why I'm posting the question. Let's imagine that I have a group of kids who come from a small set of neighbourhoods, who can each take as many books as they want off the shelf. I want to know whether any categorical patterns are evident in terms of who is taking more science books, who is taking fewer, and whether there's a typical amount of these science books taken off the shelf. The 48 values each represent the proportion of science books each one takes. (not real--just an e.g.)
Answer: You should be reassured that "keep it simple" is the advice just as much as it is your inclination.
What follows may be more detailed or complicated than you want or need, but if it's along the right lines you can simplify too.
All the 48 points are shown below at right. The rising scale corresponds to increasing cumulative probability and serves to shake them apart.
The red reference line shows the mean.
A box plot is shown at left, with median and quartiles (conventionally) and 5% and 95% points (less conventionally) defining the whiskers.
The numbers shown as text (with some rounding to 1 d.p.) give the numeric story:
The minimum and maximum are 0 and 100 and so forth.
You can make qualitative comments too: there are two values a little detached at 0 and two values similarly detached at 100. The value at 80 is also notably high. Perhaps you can add substantive flesh. It's a matter of taste and judgment and experience whether to be dramatic and call them outliers. That judgment should depend on how surprising or exceptional they seem to you. For example, if these were exam scores as percents, two people were perfect and two flunked completely, and look at that!
Meta-prejudices:

Dividing into bins arbitrarily based on mean or median, etc., at best imposes a framework arbitrarily. Feel free to use the mean, median, etc., as summary, but let the data show themselves.
Using cluster analysis (K-means etc.) on data like this is unduly technical here.
Comment: Thank you for your time and input, I appreciate it. I had no idea what to expect when I posted here and I'm amazed by the helpful, prompt responses.
Answer: In this case, quartiles or quintiles would be just fine. They're easy to understand and they automatically give you roughly equal group sizes.
There are also a number of more complicated approaches you could take. This paper studies a few of them and name-drops a whole bunch more. Of all the algorithms mentioned there, "k means" (and possibly its cousins "k medians" and "k medoids" or "partitioning around medoids") is the most widely used, most readily available, and easiest to understand and explain.
Comment: Thanks for your help and the reference. I will definitely take a look when I have the time. I think Nick is probably right that for my particular scenario keeping it simple and trying to present the data visually will be most useful. But "big picture" it would be nice to understand more.
Answer: I would use either standard deviation or quartiles. If the distribution is not skewed, then whatever is less/more than one standard deviation would be low/high, and those within would be average/typical.
If the distribution is skewed, then Q1 is low, Q2-Q3 are average and Q4 is high.


jQuery grabbing value of a dynamic data-* attribute

Question: Inside of a jQuery click event listener I have some code like this:
function (evt) {
  evt.preventDefault();

  var reportbox = $(this).closest('.activityItem');
  var id = reportbox.data('questionId');
  ...
}

This works fine for data-question-id attributes, but I'm generalizing the function now and I need to grab the value from any of the following:
data-question-id
data-answer-id
data-comment-id
data-user-id
data-company-id

What's the best way to do this?
Comment: I don't quite understand the question, why can you not use the `data()` method for those too?
Comment: But that will just arbitrarily get the first data attribute on the element, in no guaranteed order - it may not be any of those you've listed. Although, if that works for you then all the better :)
Comment: Use a partial match on the end `-id`?
Comment: @RoryMcCrossan I just need a one-liner that can grab the value from any of those regardless. The `.activityItem` element has exclusively one of these but I won't know which one before-hand.
Comment: I'm afraid that's not possible. You would need to retrieve all of those data attributes and then perform some logic to check those which have values and proceed from there.
Comment: @RoryMcCrossan `var id = reportbox.data(Object.keys(reportbox.data())[0]);` Here's my one-liner. Just took a little time to think of it.
Comment: @RoryMcCrossan I _did_ say that the element would have exclusively only one of these, so this does work for my use-case.
Answer: If you know only one of those attributes will be present and you want to retrieve that single value you can use this:
var element = $(el);
var dataAttrs = ['question-id', 'answer-id', 'comment-id', 'user-id', 'company-id'];
var data = getUnknownAttr(element, dataAttrs);

function getUnknownAttr(element, potentialAttrs) {
    var $element = element instanceof $ ? element : $(element);
    var result = null;

    potentialAttrs.forEach(function (attr) {
        var temp = $element.data(attr);
        if (typeof temp !== 'undefined') {
            result = temp;
        }
    });

    return result;
}

Comment: I like this but I actually just came up with a much simpler way.
Comment: @PatrickRoberts please post it! I've got a couple use cases for it. I actually just came up with what I wrote without even implementing it but I was about to. EDIT: I just saw you posted it, thanks
Answer: As Brian points out, you could access the dataset property to retrieve all the element's data-* attributes:
$('.activityItem').each(function () {
  var dataAttributes = this.dataset;

  Object.keys(dataAttributes).forEach(function (key) {
    console.log(key, dataAttributes[key]); // key, value
  });
});

Since you only want the first data attribute, you could simply use:
var dataAttributes = this.dataset;
var id = dataAttributes[Object.keys(dataAttributes)[0]];

It's important to note that the dataset property returns the attribute names in camel case without the data prefix. In other words, data-question-id would be questionId.
If you want to retrieve all of an element's attributes, access the attributes property and check which attributes start with data-* and end with -id. It's definitely more verbose, but it may work better in other scenarios.
$('.activityItem').each(function () {
  var attributes = this.attributes;

  Object.keys(attributes).forEach(function (key) {
    var attribute = attributes[key];

    if (/^data-.*-id$/.test(attribute.name)) {
      console.log(attribute.name, attribute.value);
    }
  })
});

Comment: Having a regex inside a for-loop isn't exactly the "simple" solution I was looking for, but I appreciate the attempt.
Comment: @PatrickRoberts You're right--1+ to your answer. I was under the impression that it had to end with `*-id`.
Comment: Your impression was correct, but see my comment to Rory.
Comment: Using `this.dataset` would be more targeted for this use case. The `attributes` object contains all of the elements attributes, not just data-* attributes. Your regex takes care of the others but you could eliminate it completely using `dataset` if (like in this case) you knew there was only one data-* attribute.
Answer: I just thought of what I was looking for. I guess my question confused you, but here's what I wanted:

$('#test').children().each(function () {
  var reportbox = $(this);

  var id = reportbox.data(Object.keys(reportbox.data())[0]);

  reportbox.text(id);
});

The line of focus being:
var id = reportbox.data(Object.keys(reportbox.data())[0]);

Edit
Alternatively thanks to @Brian's comment I can rewrite this to:
var id = this.dataset(Object.keys(this.dataset)[0]);


Programmatically building a Quicktabs instance

Question: What I need to do is merge the usermenu ( user tasks ) with a Quicktabs menu I have on the same page.
So what I'm trying to do at the minute is to programmatically build a Quicktabs instance.
Based on the infomation at https://www.drupal.org/node/2119625  I have created a module 'userquicktabs'  heres the .module . Ive enabled the module, and I take it after this I should be able to see a new instance with the others instances I've created in the Quicktabs UI.  Do I need to make a block for the instance?
<code><?php

function userquicktabs() {
$tabs = array(
$tabs[] = array(
  'title'   => t('Node 1'),
  'type'    => 'node',
  'nid'     => '1',
  'weight'  => 0,
),
$tabs[] = array(
  'title'   => t('Node 2'),
  'type'    => 'node',
  'nid'     => '2',
  'weight'  => 1,
),
);

 // Configure the QuickTabs options
 $quicktabs_options = array(
'style'   => 'commons',
'ajax'    => FALSE,
'renderer'    => 'quicktabs',
);

$quicktabs_name = 'newinstance';

 print drupal_render(quicktabs_build_quicktabs($quicktabs_name, $quicktabs_options, $tabs));

}
</code>
Answer: Yes, programmatically created instances are not registered with those created trough the UI, but at least they are more flexible.


Why the linear numerator for fractions with irreducible denominators and constant numerators for reducible denominators?

Question: For example:
$\Large{\frac{2x^3+5x+1}{(x^2+4)(x^2+x+2)}}$ breaks down to $\Large{\frac{ax+b}{x^2+4}+\frac{cx+d}{x^2+x+2}}$
I have been told that since the denominators are irreducible, the numerators will be either linear or constant.
Now my question is for something like $\Large{\frac{2x^3+5x+1}{x^2-4}}$ you would make it equal $\Large{\frac{A}{x+2}+\frac{B}{x-2}}$, why do we assume that the numerators are constant? Why couldn't they be linear??
Answer: First you divide the denominator into the numerator, getting a remainder.  So, for your example, $$\frac{2x^3+5x+1}{x^2-4}=2x+\frac{13x+1}{x^2-4}$$ and expand the last fraction in partial fractions.  As the denominator now has a higher degree than the numerator, the limit as $x \to \infty$ is $0$, so you don't want a constant term.  In fact, $$\frac{13x+1}{x^2-4}=\frac {25/4}{x+2}+\frac{27/4}{x-2}$$ and you don't want or need a linear term in the numerator.
Comment: It is the degree counting argument.  In the original the "degree of the fraction" is -1, so the terms need to be as well.  If you have a linear term in the numerator over a linear denominator, the degree is zero.  This is reflected in the limit at infinity.
Comment: I know we don't want a linear numerator but why?? I'm not getting why we let the numerator be linear for an irreducible denominator and make the numerator a constant when the denominator is reducible. Why is this?
Comment: @KingSquirrel: also, it is not "a linear numerator for an irreducible denominator" but rather "for irreducible denominator of degree $n$ the numerator has at most degree $n-1$."  Note that this works nicely all the way down to linear denominators, as a linear denominator may be treated as irreducible.
Answer: Because remainder of division is always smaller then the degree of the polynomial so we assume it's exactly 1 smaller,and find if the other terms are zero
$$\frac{2x^3+5x+1}{(x+2)(x-2)}=\frac{ax+b}{x+2}+\frac{cx+d}{x-2}=\frac{ax+b-a(x+2)}{x+2}+a+\frac{cx+d-c(x-2)}{x-2}+c=\frac{ax+b-ax-2a}{x+2}+\frac{cx+d-cx+2c}{x-2}+a+c=\frac{b-2a}{x+2}+\frac{2c+d}{x-2}+a+c$$
Answer: That is actually incorrect... you need to do polynomial long division first.


Does the integral $\int \frac{1}{1+x^{a+2}} \ dx$ converge?

Question: I am attempting to demonstrate the convergence of the integral $\int_{0}^{1} \frac{1}{1+x^{a+2}} \, dx$. My approach involves showing that for every positive value of $a$, the integral is definite and can be solved using partial fractions. However, I'm uncertain about the correctness of my approach.
If anyone has insights into whether this method is valid or if there are alternative approaches to establish the convergence of this integral, I would greatly appreciate any assistance or guidance. Thank you!
Comment: For any $a>0$ the function integrated is continuous, so it is integrable, or I didn't get your question
Comment: For $a>0$, the integrand is a continuous function in the interval $[0,1]$ with range $[1/2,1]$. What does this imply for the integral?
Answer: The only problem you could have would be at $x = 0$. Let's see
If $a > -2$
$$
\lim_{x \to 0^{+}} \frac{1}{1+x^{2+a}} = 1
$$
If $a = -2$
$$
\lim_{x \to 0^{+}} \frac{1}{1+x^{2+-2}} = 1/2
$$
If $a < -2$
$$
\lim_{x \to 0^{+}} \frac{1}{1+x^{2+a}} = 0
$$
Since the improper integral is of type 2, it converges. So the integral converges for any $a \in \mathbb{R}$


Set the "from" header in the email to be in the format "Full Name"

Question: How can I change the from header in the email sent from Drupal to be in the format "Fullname" <email@example.com>?
I managed to do it on a Drupal 6 site at one point in the past, but I no longer have access to that site, and I don't remember how to do it.
Answer: You can use hook_mail_alter() to change the "from" email address of any email sent out from your site. The email address used needs to conform to the RFC standard, which it does is your question's title. But user names can be tricky and might contain illegal characters. There's a comment on the D6 docs that provides a code sample for properly formatting the email address. Your code would look something like...
function yourmodule_mail_alter(&$message) {
  $message['from'] = $message['headers']['From'] = '"Full Name" <firstname.lastname@example.com>';
}

Also, keep in mind that just setting the "from" address may not have the desired results in all email clients (see the discussion on the Drupal issue queue). You might also need to set "sender", "errors-to" and "reply-to" based on your requirements. Those values are in the "header" of the $message variable from the code sample above.
Comment: Thanks. For those who arrive at this answer in the future, definitely pay attention to the final paragraph. For example, just setting the $message['from'] did NOT work for me. I had to set the $message['headers']['From'] value.
Comment: Thanks @maxedison. You are right. I'm editting the answer and hope the modification will be accepted.
Comment: setting $message['from'] worked fine for me (5 years later), but watch that you do use the double quotes around from name
Answer: This is the method from Drupal 6 to add the the site name to the email.  Substitute  variable_get('site_name, Drupal') with The Site Full Name you want.
/**
* Implementation of hook_mail_alter().
* Here we allow the site name to be used as the senders name for outgoing email.
* see http://drupal.org/node/209672
*/
function mymodule_mail_alter(&$message){
  $default_from = variable_get('site_mail', ini_get('sendmail_from'));

  if($message['from'] == $default_from){
    $message['from'] = '"'. variable_get('site_name', 'Drupal') .'" <'. $default_from .'>';
    $message['headers']['From'] = $message['headers']['Sender'] = $message['headers']['Return-Path'] = $message['headers']['Errors-To'] = $message['headers']['Reply-To'] = $message['from'];
  }
}

the function for hook_mail_alter() has not change in Drupal 7, so this should work.
Comment: This is worked for me for `Gmail & outlook`. Thanks :)
Answer: Regarding the settings you have to change, this is still an issue in D7. If in doubt, use the following code in your hook_mail_alter :
$message['from'] = $from;
$message['headers']['From'] = $from;
$message['headers']['Sender'] = $from;
$message['headers']['Return-Path'] = $from;


Covering group of $\mathrm{PSL}(3,4)$.

Question: Let $G=\mathrm{PSL}(3,4)$. I have found the Schur multiplier of $G$ is $\mathbb{Z}_4\times\mathbb{Z}_{12}$ by looking up some books. Now I wonder the  universal covering group of $G$. Is there anyone who can tell me ? Or where can I find the information of it?
Comment: @DietrichBurde Isn't that section of the wikipedia article just referring to the real and complex numbers? I think ${\rm PSL}(3,4)$ is an exception to most general statements of that kind.
Comment: I find it difficult to know exactly what is being asked here. The covering group of $G$ is a perfect group $H$ with centre $ Z(H) \cong C_3 \times C_4^2$ and $H/Z(H) \cong {\rm PSL}(3,4)$. What specifically would  you like to know about it? The ATLAS of Finite Groups is the best general reference for properties of covering groups of finite simple groups, but it is not completely easy to read.
Comment: I wonder the generators and relations of it. Can I get it from the ATLAS? @DerekHolt
Comment: Unfortunately the only presentation given in the ATLAS is for $12_2.L_3(4)$, which has cyclic centre of order $12$. I will see if I can easily extend that to a presentation of the full covering group.
Answer: You can define the covering group of ${\rm PSL}(3,4)$ in GAP, either as a subgroup of $S_{511}$ or as a finite presentation (on the same generating sets) using one of the commands:
G := PerfectGroup(IsPermGroup,967680,4);
G := PerfectGroup(IsSubgroupFpGroup,967680,4);

You can do the same in Magma with
D := PerfectGroupDatabase();
G := PermutationGroup(D,967680,4);
G := Group(D,967680,4);

Comment: You can calculate the composition factors of each of the groups of that order until you hit the right one. With the GAP groups you can also tell from the name of the group.
Comment: Thanks a lot. But could you tell me how do you know the required group is the fourth group of order 967680 in the database?
Comment: Is GAP able to calculate and display the character table of G := PerfectGroup(IsPermGroup,967680,4); in a reasonable amount of time? Or do you know a place to find the character table for SchurCover(PSL(3,4))? I tried to display the table for SchurCover(PSL(3,4)) and got many "#I  Coset table calculation failed -- trying with bigger table limit" messages. But maybe the way you present the group here it will be quick to find the character table?
Comment: @IanGershonTeixeira That seems to be a new question, not a comment on my answer.
Comment: OK I asked a new question: https://math.stackexchange.com/questions/4582239/character-table-for-schur-cover-of-sz8

Covering group of $\mathrm{PSL}(3,4)$.


Erro no Visual Studio - Cannot find name 'Record'

Question: Estou trabalhando em um projeto ASP.NET com c# no Visual Studio 2015 e me deparei com erro no arquivo index.d.ts. As mensagens de erro são Cannot find name 'Record' e Cannot find name 'undefined'.Vi que seria algum erro relacionado ao TypeScript, mas não sei o que exatamente. Podem me dar um help? Já agradeço.
Answer: Atualiza o TypeScript para uma versão mais atualizada.
Nesse link tem o arquivo para o VS2015: https://www.microsoft.com/en-us/download/confirmation.aspx?id=48593


How can I change the whole look of a JTextField

Question: I want to change the look of the whole JTextField but still want it to be editable. The first picture shows a normal JTextField, the second picture shows, what I want it too look like. So basically it is just a blue horizontal line instead of a whole Box.

I tried to override the paintComponent() method of the JTextField and draw a blue line with the Graphics object, but it didn't show any effect. Thanks for any help and sorry if this question does not fit the rules of Stackoverflow.
Answer: Try setting a custom border on the JTextField or overriding paintBorder instead
Comment: Did work for me, painting only MatteBorder with bottom line. Thanks
Answer: You can override paintComponent(), just as you've said. Here's snippet for JTextField in simple JPanel:
<code>        JPanel panel = new JPanel();

        JTextField textField = new JTextField() {
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                g.setColor(Color.BLUE);
                g.drawLine(10, getHeight() - 10, getWidth() - 10, getHeight() - 10);
            }
        };

        panel.add(textField);
        textField.setPreferredSize(new Dimension(100, 50));
        textField.setForeground(Color.BLUE);
        textField.setHorizontalAlignment(JTextField.CENTER);

        add(panel);
        setSize(200, 200);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
</code>


How can you prove that a function has no closed form integral?

Question: In the past, I've come across statements  along the lines of "function $f(x)$ has no closed form integral", which I assume means that there is no combination of the operations:

addition/subtraction
multiplication/division
raising to powers and roots
trigonometric functions
exponential functions
logarithmic functions

which when differentiated gives the function $f(x)$. I've heard this said about the function $f(x) = x^x$, for example.
What sort of techniques are used to prove statements like this? What is this branch of mathematics called?

Merged with "How to prove that some functions don't have a primitive" by Ismael:
Sometimes we are told that some functions like $\dfrac{\sin(x)}{x}$ don't have an indefinite integral, or that it can't be expressed in term of other simple functions.
I wonder how we can prove that kind of assertion?
Comment: the branch of mathematics that studies this sort of thing is differential galois theory.
Comment: Fwiw, I think this question would also be ok at MO.
Comment: workmad3 - new operations do, of course, change what is representable in a closed form. For example, if we invent notation for a function whose value at t is \int_0^t x^x dx, many more things become representable! But for various mathematical, historical, and computational reasons, it is of interest what functions are expressible in terms of elementary functions as  they've already been defined - field operations (arithmetic), log, exp, and compositions of these.
Comment: It sounds like it would be part of Analysis, which deals with things like differentiability, continuous functions and the like. It's also worth noting that new operations can actually change what is representable in a closed form (for example, before logs were invented/discovered then functions involving them obviously couldn't be formulated in a closed form).
Comment: @Eric Not true for the functions typically considered in calculus. The theory of integration in finite terms doesn't employ any Galois theory at all. It plays a nontrivial role when one studies *higher-order* linear differential equations (see the comments on [this answer below](https://math.stackexchange.com/a/2329/242)).
Answer: It is a theorem of Liouville, reproven later with purely algebraic methods, that for rational functions $f$ and $g$, $g$ non-constant, the antiderivative of
$$f(x)\exp(g(x)) \, \mathrm dx$$
can be expressed in terms of elementary functions if and only if there exists some rational function $h$ such that it is a solution of
$$f = h' + hg'$$
$e^{x^2}$ is another classic example of such a function with no elementary antiderivative.
I don't know how much math you've had, but some of this paper might be comprehensible in its broad strokes:
https://ksda.ccny.cuny.edu/PostedPapers/liouv06.pdf
Liouville's original paper:

Liouville, J. "Suite du Mémoire sur la classification des Transcendantes, et sur l'impossibilité d'exprimer les racines de certaines équations en fonction finie explicite des coefficients." J. Math. Pure Appl. 3, 523-546, 1838.

Michael Spivak's book on Calculus also has a section with a discussion of this.
Comment: do you mean Spivak's elementary Calculus (and not on manifolds, *shudders*)? And if so, what page (or section)?
Comment: So, for the case of antidifferentiating $x^x$, one would take $f(x)=1$ and $\exp g(x) = \exp\ln(x^x)$ and hence look for a solution $1=h'+h\ln(x^x)$?
Comment: You mean $e^{x^2}$ antiderivative....
Comment: As I recall, Liouville's theorem uses a more general definition of "elementary function" ... not only "powers and roots" but also general "algebraic functions" are included.
Comment: I think it's $f = h' + hg'$.
Answer: Have you ever heard of Galois theory? It is a theory that studies the solutions of equations over fields.
As it turns out, there is a special type of Galois theory called Differential Galois theory, which studies fields with a differential operator on them:
http://en.wikipedia.org/wiki/Differential_galois_theory
Using this theory, one can prove that functions like $\frac{\sin(x)}{x}$ and $x^x$ don't have an indefinite integral.
Comment: This is a good proof sketch: http://www.math.niu.edu/~rusin/known-math/97/nonelem_integr2
Comment: In fact the theory of integration in finite terms doesn't employ any Galois theory at all. That only comes into play when one studies *higher-order* linear differential equations.
Comment: @Aryabhata Your link is dead. [Here](https://web.archive.org/web/20140325005636/http://www.math.niu.edu/~rusin/known-math/97/nonelem_integr2) is an archived version.
Comment: @BillDubuque is correct.  The Galois group of an integral is just the additive group of the constant subfield.  Why?  Well, the Galois group is the group of automorphisms that fix the base field and permute the solutions around amongst themselves.  For an integral, the solutions differ only by the constant of integration "C".  So, the integral's Galois group is the additive group of the real (or complex) numbers.  Actually that's one of two cases - the case when we need to extend the original field to construct the integral.  If we don't need to extend, then the Galois group is nil.
Answer: The techniques used for indefinite integration of elementary functions are actually quite simple in the transcendental (vs. algebraic) case, i.e. the case where the integrand lies in a purely transcendental extension of the field of rational functions $\rm\mathbb C(x)$. Informally this means that the integrand lies in some tower of fields $\rm\mathbb C(x) = F_0 < \cdots < F_n = \mathbb C(x,t_1,\ldots,t_n)$ which is built by adjoining an exponential or logarithm of an element from the prior field, i.e $\rm\  t_{i+1} =\: exp(f_i)\ $ or $\rm\ t_{i+1} =\: log(f_i)\ $ for $\rm\ f_i \in F_i$ where $\rm t_{i+1}$ is transcendental over $\rm F_i\:.\ $ For example $\rm\ exp(x),\ log(x)\ $ are transcendental over $\rm\mathbb C(x)$ but $\rm\ exp(2\ log(x)) = x^2\ $ is not. Now, because $\rm\ F_{i} = F_{i-1}(t_{i})$ is transcendental it has particularly simple structure, viz. it is isomorphic to the field of rational functions in one indeterminate $\rm\:t_i\:$ over $\rm\ F_{i-1}\ $. In particular, this means that one may employ well-known rational function integration, techniques such as expansions into partial fractions. This, combined with a simple analysis of the effect of differentiation on the degree of polynomials $\rm\  p(t_i)$, quickly leads to the fundamental result of Liouville on the structure of antiderivatives, namely they must lie in the same field $\rm F$ as the integrand except possibly for the addition of constant multiples of log's over $\rm F$. With this structure theorem in hand, the transcendental case reduces to elementary computations in rational function fields. This transcendental case of the algorithm is so simple that it may be  easily comprehended by anyone who has mastered a first course in abstract algebra.
On the other hand, the full-blown algebraic case of the algorithm requires nontrivial results from the theory of algebraic functions. Although there are some simple special case algorithms for sqrt's and cube-roots (Davenport, Trager) the general algorithm requires deep results about points of finite order on abelian varieties over finitely generated ground fields. This algebraic case of the integration algorithm was discovered by Robert Risch in 1969 - who did his Berkeley Ph.D. on this topic (under Max Rosenlicht).
For a very nice introduction to the theory see Max Rosenlicht's Monthly paper, available from JSTOR and also here. This exposition includes a complete proof of the Liouville structure theorem along with a derivation of Liouville's classic criterion for $\rm\int f(z)\: e^{g(z)}\: dz\ $ to be elementary, for $\rm\: f(z),\: g(z)\in \mathbb C(x)$. For algorithms see Barry Trager's 1984 MIT thesis and Manual Bronstein: Symbolic Integration I: Transcendental Functions.
Disclaimer: I implemented the integration algorithm in Macsyma (not the much older Maxima) so, perhaps due to this experience,  my judgment of simplicity might be slightly biased. However, the fact that the basic results are derived in a handful of pages in Rosenlicht's paper yields independent evidence for such claims.
Comment: I'm not sure if I agree with "easily comprehended".  There's quite a bit of differential algebra to learn to really understand what is going on, and the whole if it is pretty large and complex.  So "comprehended" yes, but "easily," maybe not.
Comment: @asm The amount of *differential* algebra required for the classical transcendental case is minimal. One could learn it in a few hours.
Comment: I'm not sure if I agree with that.  There are two whole chapters in Bronstein's book (chapters 3 and 4) dedicated to the differential algebra techniques required to prove the correctness of the algorithm.  And that doesn't even include the more advanced stuff you need to prove the structure theorems (chapter 9).  I suppose you don't really need all of this unless you are interested in understanding the proofs of the theorems, so I guess it depends on how define "comprehended".
Comment: @asm But the transcendental case can be presented much more succinctly, e.g. see the expositions by Rosenlicht and his student Risch.
Comment: @cla It's necessary if you wish to understand the algorithms. The gist is simple, e.g. a couple pages in the linked Rosenlicht  article, using nothing deeper than partial fractions (and it can be presented in more elementary language). We  can only go so far with ad-hoc methods. It's akin to attempting ts solve linear Diophantine equations without knowing the (extended) Euclidean algorithm (or equivalent). We can use ad-hoc methods for small problems, but there is no hope for less trivial instances, e.g. [Archimedes Cattle Problem](https://math.stackexchange.com/a/1742/242) (206545 digits)
Comment: A good introduction to the whole algorithm in Bronstein's paper, "Symbolic Integration Tutorial"
Comment: I'm not sure I'm going to spend "a couple of hours" learning differential algebra so I can understand one answer on MSE
Comment: The second (non-JSTOR) link for the Rosenlicht paper unfortunately appears to be dead.
Answer: Surprisingly, there is a procedure for determining this, called the Risch Algorithm. However, it is apparently very complicated to implement, and furthermore it is not a true algorithm: if the input does have an anti-derivative, it can find it in a finite amount of time, but demonstrating there is no anti-derivative requires solving the constant problem, which can fail to halt. (In that case, probabilistic methods can be used.)
Comment: It *is* an algorithm modulo the ability to compute effectively in the constant field. If the constant field is complex enough, e.g. involving transcendentals such as e, \pi, etc, then this leads to difficult problems in transcendental number theory - which are unsolvable in general. However, rarely if ever do such problems arise in practice. If they did they would not cause halting problems but instead might cause the algorithm to return an incorrect answer, e.g. declaring that no elementary closed form exists when one in fact does exist.
Comment: @Bill Dubuque: That's exactly correct. I've implemented the transcendental version of the Risch Algorithm in SymPy, and you can trick it into thinking something like `exp((sin(y)**2 + cos(y)**2 - 1)*x**2)` has no elementary integral with respect to `x` (when in fact it does, because it reduces to just 1).
Answer: A key result in this area is a theorem by Liouville. You'll find easy expositions of this result in the references below:

Antoine Chambert-Loir. A Field Guide to Algebra, last chapter, Springer, 2005.
M Rosenlicht. Integration in finite terms, Amer.    Math. Monthly,
    (1972), pp 963-972.
Toni Kasper. Integration in finite
terms: the Liouville theory. Math.
Mag.,  53(4):195–201, 1980.
D.    H. Potts. Elementary
integrals. Amer.    Math. Monthly,
63:545–554, 1956.
A. D. Fitt and G. T. Q. Hoare. The closed-form integration of arbitrary functions,
The Mathematical Gazette, Vol. 77, No. 479 (Jul., 1993), pp. 227-236
Elena Anne Marchisotto and Gholam-Ali Zakeri. An invitation to integration in finite terms, The College Mathematics Journal, Vol. 25, No. 4 (Sep., 1994), pp. 295-308
D. G. Mead. Integration, The American Mathematical Monthly, Vol. 68, No. 2 (Feb., 1961), pp. 152-156
Comment: See also [Impossibility theorems on integration in elementary terms](http://www.claymath.org/2005-academy-colloquium-series).
Answer: Brian Conrad explains this in the following:
Impossibility theorems on integration in elementary terms (archived PDF)
Comment: Works forever now, because I archived the pdf link :)
Comment: Works now, at least.
Comment: This sounds interesting but is currently *403 Forbidden*. On [Conrad's home page](http://math.stanford.edu/~conrad/) he notes: "These may be updated without warning. Links to files undergoing revision may be temporarily disabled." So hopefully it will return in new and improved form before too long.
Answer: The general pattern is always the same: (1). Study properties of derivatives of closed form functions. (2). If your function $f(x)$ fails one of those properties, then it has no closed form antiderivative.
Here is how to get started: First, consider derivatives of rational functions. Notice that their pole orders at finite points are never 1 (more generally: the residue is 0). If $f(x)$ fails this property, then you know that its antiderivative can not be a rational function. Sounds simple, but the surprising part is that this can be generalized quite easily to logarithmic extensions (handling exponential extensions in Risch algorithm is more involved, and handling algebraic extensions is more involved still).
Take for example a function $f(x) \in \mathbb{C}(x, \ln(x))$. For each irreducible factor $p \in \mathbb{C}(x)[ \ln(x) ]$ in the denominator of $f(x)$, you can define a corresponding residue (which will be algebraic over $\mathbb{C}(x)$). A necessary condition for $f(x)$ to have an elementary anti-derivative is for these residues to be constants  (in the more basic case, $f(x) \in \mathbb{C}(x)$, residues are always constants, and thus, rational functions always have an elementary antiderivative). See "Liouville's theorem (differential algebra)" on wikipedia for more.
Comment: Are you aware of the computational algorithms used to determine if there is an elementary function that can be differentiated to the integral?


$Cos^2(\varphi) = 1/2$? What is $\varphi$?

Question: Ok. I know this may sound silly but some reason, I am struggling to understand why the answer $\pi/4$.
Like what I did was take the square root of both sides to get cos($\varphi$) = 1/$\sqrt2$. Then I ask myself what value of phi would get me 1/$\sqrt2$. So, I start a 0 degrees at the top of the z-axis and find my way say the following:

$\pi$/6 => $\sqrt3$/2

$\pi$/4 => $\sqrt2$/2

$\pi$/3 => $\sqrt1$/2
So I said $\pi/3$
***I must confess that I think I basically rephrase this question by treating this like cos(x) = 1/2 and recreating this in the x-y plane like basic elementary work.
Comment: $1/\sqrt{2} \ne \sqrt{1}/2$, $1/\sqrt{2} = \sqrt{2}/2$.
Answer: You have noted that $\cos{\pi/3}=1/2$ This is correct, but it is not the answer you want. You want $\cos{\phi} = 1/\sqrt{2}$.
Hint: Rationalize $1/\sqrt{2}$ by multiplying the top and bottom by $\sqrt{2}$. What do you get?
Comment: Wow! How did I not see this? hahaha Thanks so much!!!


WebView não captura gestos

Question: WKWebView carrega o link porém não consigo realizar ação alguma no site
ViewController
import UIKit
import WebKit

class promoVC: UIViewController{

@IBOutlet weak var webView: WKWebView!

override func viewDidLoad() {
    super.viewDidLoad()

    webView.navigationDelegate = self
    webView.loadURL(strURL: "https://rh.mazza.tech/web/guest/webuser");
}

}
 extension promoVC : WKNavigationDelegate{

func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
    print(error.localizedDescription)
}

func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
    print("Webview is loading")
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
    print("")
}
}

Comment: Seu código compila? WKWebView não possui um método chamado loadURL(String). O método é load(URLRequest) https://developer.apple.com/documentation/webkit/wkwebview/1414954-load
Comment: Compila, ele abre o site, porém não consigo usar o site
Answer: O metodo da webView loadURL não compilala, voce precisar utilizar o método load
import UIKit
import WebKit

class ViewController: UIViewController {

@IBOutlet weak var webView: WKWebView!

override func viewDidLoad() {
    super.viewDidLoad()

    if let url = URL(string: "https://rh.mazza.tech/web/guest/webuser") {
        webView.load(URLRequest(url: url))
        webView.allowsBackForwardNavigationGestures = true
        webView.navigationDelegate = self
    }
}
}

extension ViewController: WKNavigationDelegate {
func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
     print(error.localizedDescription)
}

func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
     print("Webview is loading")
}

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
    print("")
}
}

WebView não captura gestos


Multiple Imputation: can I use same variables in my imputation model as in my substantive model?

Question: Let's say I were to impute values for a variable (using multiple imputation). Then I wanted to use that variable in a regression. Can I use the same variables I used to impute in my new regression?
So, for example, if I were to impute math test score with the variables race and income, could I then regress on GPA the variables math test score (imputed), race, and income?
Comment: Yes. That's what imputation is for. You don't have to use them, but you can. Also, you might want to edit your title.
Comment: Thanks for the response and patience! I am new to multiple imputation and am attempting to learn it on my own. How does this not violate multicollinearity?
Comment: How might it violate multicollinearity? I like the book "Missing Data" by Paul Allison - that will help you to get started.
Comment: There is a useful website http://missingdata.lshtm.ac.uk/ which may help.
Comment: I edited your title, fell free to roll it back if you do not like it.
Answer: There is inherently no reason that one cannot use the same variables in the imputation model and the analysis model. In fact, one will typically want to put as many or more information into the imputation.
The only possible concern I could see is that if your imputation model is insufficiently complex and you are imputing a considerable proportion of your data, then what you assumed int he imputation may turn up in your analysis again.
For example, the "standard" MI model might be seen as one, where multivariate normality is assumed with some means and covariance matrix to be estimated - this essentially corresponds to linear relationships between the variables you put in (unless you make sure that you do something else). If most of your data is imputed, you should then not be surprised if the relatioship between two variables looks pretty linear, if you did not allow the imputation model to consider a non-linear relationship.
Answer: Imputation does not create bias in regression but it does underestimate variability.  That is why multiple imputation is valuable.  It accounts for the variability that is missing from simple imputation.
Keep in mind that it rests on the assumption that the missing values are missing at random (MAR).  Read Rubin's book Multiple Imputation for Non response in Surveys and/or Little and Rubin's text Statistical Analysis with Missing Data.