Eager vs. lazy interpretation of recursive functions

Question: One of the ways of defining the set of recursive functions is to define first a language $L$ by induction in the following way:

$\mathsf{Z}^1 \in L$;
$\mathsf{S}^1 \in L$;
$\mathsf{P}^n_k \in L$ for all $n, k$ with $n \ge 1$, $1 \le k \le n$;
if $F^m, G_1^n, \dotsc, G_m^n \in L$, then $\mathsf{C}^n[F^m, G_1^n, \dotsc, G_m^n] \in L$;
if $F^n, G^{n+2} \in L$ then $\mathsf{R}^{n+1}[F^n, G^{n+2}] \in L$;
if $F^{n+1} \in L$, then $\mathsf{M}^n[F^{n+1}] \in L$.

Then one defines a function (we could call it interpretation) which associates to every $F^n \in L$ a partial function $i(F^n) : \mathbb{N}^n \rightarrow \mathbb{N}$. The interpretation is such that, intuitively, $\mathsf{Z}^1$ corresponds to the constant zero, $\mathsf{S}^1$ to the successor, $\mathsf{P}^n_k$ to the $k$-th projection, and then we have composition, primitive recursion and minimalization. One says that a partial function $f : \mathbb{N}^n \rightarrow \mathbb{N}$ is recursive if there is some $F^n \in L$ such that $f = i(F^n)$. (This way is particularly useful if one wants to deal precisely with intensional and extensional equalities.) Let's just call $i(L)$ the set of recursive functions in the sense of this definition.
My problem is that I can see at least two ways in which we could give the interpretation of $F^n$. The one I was taught corresponds to what I think computer scientists would call eager evaluation. But we could also define the interpretation in such a way that the evaluation is lazy. The definitions are quite long, but let me illustrate the key difference between the two: if $e$ stands for eager and $l$ stands for lazy, we would have for example that
$$ e(\mathsf{C}^1 [\mathsf{P}_1^2, F^1, G^1])(x) = \left\{\begin{array}{l l}
e(F^1)(x) & \text{if } e(G^1)(x) \text{ is defined,} \\
\text{undefined} & \text{otherwise.} \end{array}\right.$$
$$ l(\mathsf{C}^1 [\mathsf{P}_1^2, F^1, G^1])(x) = l(F^1)(x) \quad\text{for all } x $$
i.e., one can treat the projections in two ways, either requiring that all arguments be defined in order to return the $k$-th, or not – and consequently the same applies for other functions which don't really need all their arguments (this could be made precise, but it's very technical and not so interesting).
It is not obvious, to me, that the recursive functions defined using the eager evaluation are exactly the same as those defined using the lazy evaluation. I can't find any reference for this, because most texts adopt the eager evaluation without saying much about their choice (and some are not quite clear about the interpretation as well, maybe because they interchange functions and symbols for functions). So, my question is,

Why is $e(L) = l(L)$?

I think that $e(L) \subseteq l(L)$ should be simple, but of course we can't just say that if $f = e(F^n)$, then $f = l(F^n)$. On the contrary, the other inclusion seems quite complicated: in a sense, what is needed is a way to emulate parallel computation.
I know that in order to give a proof one needs to see the explicit definitions of $e$ and $l$, but I hope that this problem has already been dealt with somewhere, and that someone could point me to good references. Anyway, if it's really necessary I'll copy them here.
Answer: When the partial recursive functions a constructed in the way you sketch, one is always assuming the eager semantics. This easier to specify (and a somewhat carefully written text should define composition in sufficient detail that it is clear that it is eager) -- and more importantly it is easier to convince oneself that the computation of a function value in the eager semantics ought to be realizable as a mechanical process, given the usual assumptions of infinite resources, etc.
However, it is well known in computer science that lazy and eager functional languages have the same strength. What can be expressed in one can be expressed in the other.
The proof of this is by simulation: We can define a lazy semantics for the language, and then program an interpreter that implements this semantics in the eager language. Thus, if we have any specification of a function, what it will do in the lazy semantics is also realized by some program in the eager semantics, namely the interpeter, as combined with the function specification using the $s$-$m$-$n$ theorem.
Conversely we can use the lazy language to program an interpreter for the eager language. So the set of functions $\mathbb N\to\mathbb N$ that can be expressed in the two formalisms are the same.
With just a bit of ingenuity one can even make interpreters for the lazy and eager semantics whose behavior is independent on whether the interpreter itself is run under the eager or lazy semantics.
The classical reference is G.D. Plotkin, Call-by-name, call-by-value, and the $\lambda$-calculus, Theoretical Computer Science 1(2), 125-159 (1975). As the title says, it uses the lambda calculus rather than recursion equations as its formal setting. I can't offhand cite a source where this is done explicitly for recursion equations in a bare-bones foundational context like mathematicians like them, but actually doing it would be on the level of a small early project for a graduate student in theoretical CS.
(There are plenty of texts that discuss implementation techniques for lazy evaluation at a more abstract level. Implementing that in any desired programming language -- such as the recursion calculus you use here -- is just a matter of programming).

Added later: What I claim to be an early graduate-student project above is just writing the interpreter. Actually proving down to the gory details that it implements the lazy semantics is going to be a formidable project for the interpreter an average graduate student would produce. Doing so would certainly be possible and some "natural" interpreters have machine-verifiable correctness proofs. However, if the goal is to produce a concrete proof of lazy/eager equivalence, I would probably structure the interpreter with such a proof in mind.
For example, the interpretation could consist of a brute-force search for a proof that the lazy semantics entails that the result must be such-and-such. Such an interpreter would be hysterically inefficient, but verifying that it is correct would be comparable to verifying that the details in the proof of Gödel's incompleteness theorem work as the explanations claim they do.

On the contrary, the other inclusion seems quite complicated: in a sense, what is needed is a way to emulate parallel computation.

Note that the usual concept of "laziness" does not include parallel computation, only postponing the evaluation of function arguments until we know they're needed. Since this is sufficient to handle your example with composition of a projection function, I've assumed that is what you meant.
However, if you're more ambitious than that and want, for example
$$ l(\mathsf{C}^1 [H^2, F^1, \mathsf{P}^1_1])(x) = \begin{cases}
 y & \text{when }l(H^2)(z,x)=y\text{ for all } z\in\mathbb N \\
l(H^2)(l(F^1)(x), x) & \text{otherwise} \end{cases} $$
then this lazy semantics is strictly stronger than the eager semantics.
For example such a semantics would declare the halting predicate for Turing machines to be solvable: Let $H^2(n,x)$ be the function that decides if $x$ is a description of a Turing machine that halts in $n$ steps or less (this is primitive recursive), and let $F^1$ be a computation that doesn't terminate. Then the function above would terminate iff the Turing machine $x$ doesn't, so HALT and its complement would both be r.e.


What should I look for in the written estimate provided by the technician for musical instrument servicing?

Question: If the technician for musical instrument servicing provides with an estimate or explanation of the work that will be done, a written estimate will help understand what work is being done and how much it will cost.
What should I look for in the written estimate provided by the technician for musical instrument servicing?
Comment: Surely this will vary a lot from one sort of instrument to another. Compare guitar with saxophone, for example, not a lot of common ground.
Comment: Adding onto @Tim it's impossible to answer until we know what kind of instrument we are talking about.
Comment: I usually just establish that the technician is someone I can trust to do a good job and to accurately tell me what needs to be done. I do that partly by asking colleagues who they recommend. If I were to have any doubt, I might ask a competing technician for a second opinion.
Answer: An estimate for any kind of handwork, not just musical, needs to contain several things:

a complete listing of exactly what the technician intends to do
an estimate of the necessary time
the hourly rate for the technician
the costs for parts and other material
the time the servicing will take
depending on where you are, possibly any legal requirements

It's also important to discuss with the technician exactly why this work needs to be done.
Probably more important is some information that will not be on the estimate: the reputation of the person who is going to be doing the work.
Answer: In the absence of knowing even what kind of instrument this is, I can only be just so specific.  @PiedPiper has a good answer for things to look for on the estimate.  Beyond that, your best bet is to ask musicians for references/recommendations.  You might find, for example, one guitar "expert" online who will accidentally destroy your instrument, but five professional players may all suggest the same technician by word-of-mouth.  If it's a band instrument or orchestra instrument, you might contact a high school with an instrumental program and ask who they use.


jQuery ajax request with different types of responses to handle

Question: I am submitting a form through $.ajax() method. My request is like this:
       $.ajax(url, {
            type: "POST",
            contentType: "application/x-www-form-urlencoded; charset=UTF-8",
            dataType: "html json",
            data: formData,
            headers: {
                "X-Requested-With": "XMLHttpRequest"
            }
        }).done(function (result) {
                //handle correct json response or html response
        }).fail(function (jqXHR, textStatus, errorThrown) {
            console.log(jqXHR);
            console.log(textStatus);
            console.log(errorThrown.stack);
        });

When the server returns a JSON response, all works as excpected. But when the response is Html, the fail() callback is executed (status code of the response is 200 - OK) and errorThrown.stack as this value:
"SyntaxError: Unexpected token <
    at Object.parse (native)
    at jQuery.extend.parseJSON (http://localhost/Scripts/jquery-1.10.2.js:550:23)
    at ajaxConvert (http://localhost/Scripts/jquery-1.10.2.js:8429:19)
    at done (http://localhost/Scripts/jquery-1.10.2.js:8185:15)
    at XMLHttpRequest.jQuery.ajaxTransport.send.callback (http://localhost/Scripts/jquery-1.10.2.js:8778:8)"

So I think its is trying to parse JSON instead of html. I don't understand because I have set the dataType option to "html json"...
Following are some info about the request/response:
Request Headers
Accept:text/html, */*; q=0.01
Accept-Encoding:gzip,deflate
Accept-Language:pt-PT,pt;q=0.8,en-US;q=0.6,en;q=0.4
Connection:keep-alive
Content-Length:2386
Content-Type:application/x-www-form-urlencoded; charset=UTF-8
X-Requested-With:XMLHttpRequest

Response Headers
Cache-Control:private, s-maxage=0
Content-Length:56392
Content-Type:text/html; charset=utf-8
Date:Fri, 03 Oct 2014 09:52:13 GMT
Server:Microsoft-IIS/8.5
Vary:Accept-Encoding
X-AspNet-Version:4.0.30319
X-AspNetMvc-Version:4.0
X-Powered-By:ASP.NET

Why is this happening?
Solution (based on @Oscar Bout response)
        $.ajax(url, {
            type: "POST",
            contentType: "application/x-www-form-urlencoded; charset=UTF-8",
            dataType: "html",
            data: formData,
            headers: {
                "X-Requested-With": "XMLHttpRequest"
            }
        }).done(function (result) {
            try {
                var jsonResult = $.parseJSON(result);
                //handle json result
            } catch (e) {
                $("#myDiv").html(result); //handle html result
            }
        }).fail(function (jqXHR, textStatus, errorThrown) {
            console.log(jqXHR);
            console.log(textStatus);
            console.log(errorThrown.stack);
        });

I think using try/catch is not the best approach so I am listening other options.
Comment: Did you analyze the actual request and response (e.g. using the browser's Web Console) and check the actual return type of the response (`Content-Type`)?
Comment: @JanakaBandara I updated my question why the info.
Answer: What your are saying in the dataType is "treat the html response as JSON".
2 values in the dateType function does not mean it can handle 2 types.
It means "treat first one as second".
So the error is sadly correct. When html comes in, it is treated as JSON.
Parse that and well... since it is not JSON but in fact HTML it fails.
The function is meant for "syntax correct json but with a html header".
Your response probably is "syntax correct html with html header", hence the "<" in your output.
Maybe for you there is a way around using a try {} catch (e) {} function?
Here the dataType explanation:
http://api.jquery.com/jquery.ajax/
Comment: I misunderstood the use of `dataType`. I will update my question with the solution based on this response, but I think using `try/catch` is not the best approach, so I am listening for other solutions...


Delete a custom content type

Question: When my module is uninstalled, I want to delete the custom content type created by config files on module installation. On Drupal 7 there was a node_type_delete(node_machine_name). What is the equivalent method/function, in Drupal 8?
Answer: See How to delete a content type, programmatically? for the easiest way for your use case. This works for any config entity that doesn't already explicitly depend on your module (those are uninstalled anyway).
The nice thing about that approach is that the user will be informed on the uninstall confirm age that this stuff will be deleted.
To delete using the API, node types are entities, so you delete them like all others: NodeType::load('id')->delete()

Delete a custom content type


How can I insert an image into a Session variable in sql query?

Question: hello I'm trying to start a session in the sql login query
to save the image in a Session variable and display it. How can I insert an image into a Session variable in sql query?
Query:
<code>    function checkuser($conexionBd,$us,$pass){

            $sentence= $conexionBd->prepare("SELECT us_id, us_img FROM users where us_us=? AND us_pass=?");
            $img='us_img';
            session_start();
        $sentence->execute(array($us, $pass));
            if ($sentence->rowCount()==1) {

            $_SESSION['img']= $img;

            header("Location:img.php");
            exit();
            }else{

            echo 'user or password incorrect';
            }

            }
</code>
Comment: Is there a question in there somewhere?
Comment: You execute the query but never retrieve any results. Retrieve the results and you will have the `us_img` value from the database which you may store in the session.
Answer: You first need to load your image and convert it using base64.
<code>$path = 'myfolder/myimage.png';
$type = pathinfo($path, PATHINFO_EXTENSION);
$data = file_get_contents($path);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
</code>
Then you add $base64 variable to session
<code>session_start();
$_SESSION['product_number'.$base64 ] = true;
</code>


Size of data obtained from SQL query via ODBC API

Question: Does anybody know how I can get the number of the elements (rows*cols) returned after I do an SQL query?  If that can't be done, then is there something that's going to be relatively representative of the size of data I get back?
I'm trying to make a status bar that indicates how much of the returned data I have processed, so I want to be somewhere relatively close.  Any ideas?
Please note that SQLRowCount only returns returns the number of rows affected by an UPDATE, INSERT, or DELETE statement; not the number of rows returned from a SELECT statement (as far as I can tell). So I can't multiply that directly to the SQLColCount.
My last option is to have a status bar that goes back and forth, indicating that data is being processed.
Answer: That is frequently a problem when you wan to reserve dynamic memory to hold the entire result set.
One technique is to return the count as part of the result set.
WITH
data AS
(
    SELECT interesting-data
    FROM   interesting-table
    WHERE  some-condition
)
SELECT COUNT(*), data.*
from data

If you don't know beforehand what columns you are selecting
or use a *, like the example above,
then number of columns can be selected out of the USER_TAB_COLS table
SELECT COUNT(*)
FROM USER_TAB_COLS
WHERE TABLE_NAME = 'interesting-table'

Comment: In retrospect, I neglected to point out that USER_TAB_COLS is probably Oracle specific.
Answer: SQLRowCount can return the number of rows for SELECT queries if the driver supports it. Many drivers dont however, because it can be expensive for the server to compute this. If you want to guarantee you always have a count, you must use COUNT(*), thus forcing the server into doing the potentially time consuming calculation (or causing it to delay returning any results until the entire result is known).
My suggestion would be to attempt SQLRowCount, so that the server or driver can decide if the number of rows is easily computable. If it returns a value, then multiply by the result from SQLNumResultCols. Otherwise, if it returns -1, use the back and forth status bar. Sometimes this is better because you can appear more responsive to the user.


Natuite adding custom GL impact while creating a sales order via suitescript

Question: How to add custom GL impact while creating a sales order via suitescript 2.0?
Answer: According to documentation
Suite Answers

The Custom GL Lines plug-in does not currently support SuiteScript
2.0. Only SuiteScript 1.0 is supported.

The Plug-in is the only way how to generate customized GL impact lines.


On left and right inverses of functions

Question: Let $F: A \to B$ and $ G: B \to A $. Then
$ G = F^{-1}$ iff $G \circ F = I_A$ and $F \circ G = I_B$.
My Solution:
Now to prove if two functions are equal we have to show that both their domains are equal and all the elements in their domains have the same values in their co-domains.
(a) Let us take $G = F^{-1}$. Now domain of $(G \circ F = I_A) =$ Domain of $F$ = A = Domain of $ I_A$. Same could be done with the other statement. Now let us take an element $x$ to be an element of A. Then there exists a $y$ such that $f(x) = y$. So $g[f(x)]=g(y)$ is equal to $x$ because $(x,y)$ belongs to $f$ then $(y,x)$ belongs to $f^{-1}$. So $g[f(x)]=g(y) = x = I_A$ Same could be done with the other statement.
(b) Now let us take $G \circ F = I_A$ and $F \circ G = I_B$. As $I_A$ is one-to-one $F$ is one-to-one. And as $I_B$ is onto $B$, $F$ is onto $B$. Now this is where I get stuck. I don't know how will I be able to show $ G = F^{-1}$.
Comment: What is your definition of $F^{-1}$?
Comment: The Inverse Function of F.
Comment: Then what is your definition of inverse function of $F$?
Comment: Well F maps elements in its domain to its co domain. And $F^{-1}$ maps elements in the co domain of F back to its domain.
Comment: You probably mean to say that it is a function $G:B\rightarrow A$ that satisfies $G(F(x))=x$ for $x\in A$. Am I right?
Comment: ^Yes. That is what I meant. :)
Comment: Now suppose $A=\{a\}$ and $B$ is a set having more than one element. Then for functions $F:A\rightarrow B$ and $G:B\rightarrow A$ you will always have $G(F(x))=x$ for $x\in\{a\}$. Is $G$ the inverse of $F$ in this case?
Comment: No But F is one-to-one and onto. (I've stated this in the solution.)
Comment: The thing is that $G$ normally is *defined* to be the inverse function of $F$ if $G\circ F=1_A$ *and* $F\circ G=1_B$. So it seems that you are trying to prove something that is by definition the case. That's the reason why it was asked in comments what your definition of $F^{-1}$ was.
Comment: Okay But is my solution correct then. And how will I prove this if I wanted to.
Comment: If you take the definition of inverse of $F$ in my former comment then there is nothing to prove. If you take another definition then your solving can only be checked if you explicitly state this (alternative) definition in your question.
Answer: In this answer I put aside what your definition of inverse function is (see
the comments) and I presume in (a) it was shown that $F^{-1}\circ F=1_{A}$
and $F\circ F^{-1}=1_{B}$.
Now suppose that $G\circ F=1_{A}$ for some function $G:B\rightarrow A$.
Then $G=G\circ1_{B}=G\circ F\circ F^{-1}=1_{A}\circ F^{-1}=F^{-1}$.

On left and right inverses of functions


Which user related token(s) can be used to create a Rule for setting up a message type?

Question: I have created few activity logs using the Message module. All works ok, but when I try to create a message type for example "username started following you on github". When setting up the rules for this message type, I am not able to understand how to achieve this.
What should happen?
Message must be logged for the "User who 'Is flagged'" user and at the same time the username token must be replaced by the "User who 'Flagged it'" user. The problem is that this is not happening.
What is happening?
When the message is logged for "User who is flagged", the username is also replaced by "User who is flagged" user and vice versa. Obviously this is not what is required.
Export of "User Following" message type
{
  "name" : "user_following",
  "description" : "User following",
  "argument_keys" : [],
  "argument" : [],
  "category" : "message_type",
  "data" : {
    "token options" : { "clear" : 0 },
    "purge" : { "override" : 0, "enabled" : 0, "quota" : "", "days" : "" }
  },
  "language" : "",
  "arguments" : null,
  "message_text" : { "und" : [
      {
        "value" : "[message:user:name] started following you on [site:name]",
        "format" : "plain_text",
        "safe_value" : "[message:user:name] started following you on [site:name]"
      }
    ]
  },
  "rdf_mapping" : []
}

Rules for above message
{ "rules_started_following" : {
    "LABEL" : "Started_following",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "user" ],
    "REQUIRES" : [ "rules", "flag" ],
    "ON" : { "flag_flagged_follow" : [] },
    "DO" : [
      { "entity_create" : {
          "USING" : {
            "type" : "message",
            "param_type" : "user_following",
            "param_user" : [ "flagged-user" ]
          },
          "PROVIDE" : { "entity_created" : { "entity_created" : "Created entity" } }
        }
      }
    ]
  }
}

Note: It is about rules setup for message type when you select data-selectors in rules setup.
Another example is for "xyz mentioned you on github". Same problem goes here. Here username replaced by xyz and it was logged for xyz as well. It should not happen.
If abc user was mentioned by the xyz user, then the above message or notification must be received by the abc user and not the xyz user. Like normally you receive a notification on other websites when someone follows you or mentions you.
Export of "Mentions" message type
{
  "name" : "log_mentions",
  "description" : "Log mentions",
  "argument_keys" : [],
  "argument" : [],
  "category" : "message_type",
  "data" : {
    "token options" : { "clear" : 0 },
    "purge" : { "override" : 0, "enabled" : 0, "quota" : "", "days" : "" }
  },
  "language" : "",
  "arguments" : null,
  "message_text" : { "und" : [
      {
        "value" : "[message:user:name] mentioned you",
        "format" : "plain_text",
        "safe_value" : "[message:user:name] mentioned you"
      },
      {
        "value" : "\u003Cp\u003E[message:user:name]\u003C\/p\u003E\r\n",
        "format" : "full_html",
        "safe_value" : "\u003Cp\u003E[message:user:name]\u003C\/p\u003E\n"
      }
    ]
  },
  "rdf_mapping" : []
}

Export of Rules for above message
{ "rules_test_rule" : {
    "LABEL" : "test rule",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "statuses_tags" ],
    "ON" : { "statuses_tags_user_was_tagged" : [] },
    "IF" : [
      { "statuses_tags_has_specific_tag_condition" : { "status" : [ "status" ], "type" : "user", "tag" : "[account:name]" } }
    ],
    "DO" : [
      { "entity_create" : {
          "USING" : {
            "type" : "message",
            "param_type" : "log_mentions",
            "param_user" : [ "account" ]
          },
          "PROVIDE" : { "entity_created" : { "entity_created" : "Created entity" } }
        }
      },
      { "data_set" : {
          "data" : [ "entity-created:field-message-mentioning:name" ],
          "value" : "[status:sender]"
        }
      }
    ]
  }
}

Problem: When using it, if I mentioned Pierre in a post, the output is, "Pierre mentioned you" and the message is also logged for Pierre.
Statuses Sub-Modules: I am using all sub-module except following:
Statuses Domain Access, Statuses Mollom, Statuses Notifications and Statuses Userpoints. It is important to tell here that Flag 3 does not work with statuses module, Flag 2 does. Good thing is you do not want flag module to workout this problem. I am using flag 2 as I want the "like" button and follow functionality for status updates.
Note: I created the field of machine name "field_message_mentioning" Label: "mentioning" Type: "Entity Reference (User)" Widget: "Autocomplete". I have tried lot of things and spent hours, but I do not know what I am doing. I just read online and try to apply.
Hope you understood. Please read the whole explanation in the context of rules setup for message type. If there is any confusion, please ask me before answering.
Answer: Part 1: Rules tokens
Here is a sample of a rule (in Rules export format), for a flag which is used to flag an entity of type "user":
{ "rules_set_the_ever_flagged_with_flagx_flag" : {
    "LABEL" : "Set the ever flagged with FlagX flag",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "flag" ],
    "ON" : { "flag_flagged_flagx" : [] },
    "DO" : [
      { "flag_flaguser" : {
          "flag" : "ever_flagged_with_flagx ",
          "user" : [ "flagged-user" ],
          "flagging_user" : [ "flagging-user" ],
          "permission_check" : "1"
        }
      }
    ]
  }
}

The Rules Action of it, uses these 2 tokens:

flagged-user, which you should use for  User who 'Is flagged'.
flagging-user, which you should use for  User who 'Flagged it'.

Those 2 tokens should also be available for you to select in your custom rule.
You may also want to look at my answer to "Flag Module: "Never Flagged" Status", which provides more details about my example rule here.
However, the above technique is not going to work in your case, because your question has to do with tokens that you need to be available at the level of the Message module. And that is a completely different story ... Read on for more details on that (and a working solution) ...
Part 2: Message tokens
Your question is about messages created via Rules, but for 2 variations of message types:

Messages triggered by the Flag module (after a user got flagged).
Messages triggered by the Statuses (Social Microblog) module (and it's Tag related submodule).

But in both case (types of messages), you want to create a message that requires some token that is not provided by the Message module. And even though it seems that status:recipient token might be a possible fit, it is actually NOT what you're looking for (that token is about who the message is to be delivered to, not about who triggered that message to be delivered).
However, since you are using Rules to create your messages to be delivered, you can make the missing tokens available by using the Replacement patterns for each message type. Refer to the answer to What's the purpose of "Replacement tokens" of a Message type? for way more details on that (these Replacement tokens are really a hidden gem about how Rules integrates with Message!).
Part 3: Solution for "User following"
Step 1 - Define replacement tokens
Define a replacement token for this message type that is like so: @following_user (adapt to whatever fits, if you also adapt it in the steps below).
Step 2 - Custom message using these replacement tokens
Within the Message text, use something like so (note the tokens I'm using):

@following_user started following [message:user:name]

Step 3 - Custom rule
Here is how your adapted rule should look like (I mostly just added that extra Rules Action):
{ "rules_somebody_started_following_you" : {
    "LABEL" : "Somebody started following you",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "user" ],
    "REQUIRES" : [ "rules", "flag" ],
    "ON" : { "flag_flagged_follow" : [] },
    "DO" : [
      { "entity_create" : {
          "USING" : {
            "type" : "message",
            "param_type" : "user_following",
            "param_user" : [ "flagged-user" ]
          },
          "PROVIDE" : { "entity_created" : { "entity_created" : "Created entity" } }
        }
      },
      { "data_set" : {
          "data" : [ "entity-created:arguments:following-user" ],
          "value" : "[site:current-user]"
        }
      }
    ]
  }
}

Part 4: Solution for "Log mentions"
Step 1 - Define replacement tokens
Define 2 replacement tokens for this message type that is like so: @mentioning_user, %mentioning_statuses_text (adapt to whatever fits, if you also adapt it in the steps below).
Note the 2 (instead of just 1) tokens I used here, just to also show how to do that ...
Step 2 - Custom message using these replacement tokens
Within the Message text, use something like so (note the tokens I'm using):

@mentioning_user mentioned [message:user:name] in the statuses message "%mentioning_statuses_text" ...

Note the @ versus % I used in this message text, doesn't matter which one you use, just to show the difference ...
Step 3 - Custom rule
Here is how your adapted rule should look like (I mostly just added those 2 extra Rules Action, 1 for each replacement token):
{ "rules_somebody_mentioned_you" : {
    "LABEL" : "Somebody mentioned you",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "statuses_tags" ],
    "ON" : { "statuses_tags_user_was_tagged" : [] },
    "IF" : [
      { "statuses_tags_has_specific_tag_condition" : { "status" : [ "status" ], "type" : "user", "tag" : "[account:name]" } }
    ],
    "DO" : [
      { "entity_create" : {
          "USING" : {
            "type" : "message",
            "param_type" : "log_mentions",
            "param_user" : [ "account" ]
          },
          "PROVIDE" : { "entity_created" : { "entity_created" : "Created entity" } }
        }
      },
      { "data_set" : {
          "data" : [ "entity-created:arguments:mentioning-user" ],
          "value" : "[site:current-user]"
        }
      },
      { "data_set" : {
          "data" : [ "entity-created:arguments:mentioning-statuses-text" ],
          "value" : "[status:message-formatted]"
        }
      },
      { "data_set" : {
          "data" : [ "entity-created:field-message-mentioning:name" ],
          "value" : "[status:sender]"
        }
      }
    ]
  }
}

Note that I did not change anything to the (now) last Rules Action, though IMO you could savely remove that Rules Action (it's not needed to make it work, but maybe you need it for something else). Similarly: I'm not sure what the purpose of that extra "field" is for your message type (possibly obsolete now?).
Part 5: Fruit of your labor
If you make it this far, and implement the above rules and message types in your own site, you should be able to get results similar to my setup ...
Demo of "User following"

Scenario:
Hillary.Trump flags Donald.Clinton
Result:
Message delivered to Donald.Clinton:

11/09/2016 - 12:05 Hillary.Trump started following Donald.Clinton

Demo of "Log mention"

Scenario:
drupal.admin posts a statuses-msg like "Just saw the answer from [@Pierre.Vriens], and it works like a charm!!!"
Result:
Message delivered to Pierre.Vriens:

11/09/2016 - 12:22  drupal.admin mentioned Pierre.Vriens in the statuses message "Just saw the answer from [@Pierre.Vriens], and it works like a charm!!!" ...
Comment: Merci for all the effort. A detailed and good answer. I will try it and let you know as quickly as possible. In the last, you have mentioned that the extra field is obsolete, so should I remove following from the rules export? { "data_set" : {
          "data" : [ "entity-created:field-message-mentioning:name" ],
          "value" : "[status:sender]"
        }
Comment: one more question. I have to paste these replacement patterns (@mentioning_user, @mentioning_statuses_text) in the box given for optional replacement patterns in the message setup page? OR I can just directly use them in the message text in message setup?
Comment: Merci for the feedback @Umair . It doesn't hurt to leave that obsolete stuff in for now, so I'd rather first try without any deleting/cleanup (it works fine for me). After you succeed, you can always make a backup of what works (in export format), then do your cleanup to see it still works (and if not restore your backup via import). BTW: your question here intrigued me, also because I'm a huge fan of the (poorly documented but great) Message module. That's why I spend a lot of time documenting what I learned, via my new question/answer (also let me know if you "like" that, if so maybe +1?).
Comment: @Umair : you ***must*** " paste these replacement patterns (@mentioning_user, @mentioning_statuses_text)" ... that is like 50% of the clue to it all (take the time to digest my new question/answer, I bet you'll really like what you'll learn from it). So if you don't "paste" that, it can never work ... PS: I do not like "chat", so maybe remove some obsolete comments around here again if you can, ok?
Comment: Just tested "following" message type. Great it is working. I was stuck with @following_user replacement pattern because my message type machine name was "user_following". I changed it to "following"
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/48267/discussion-between-umair-and-pierre-vriens).
Comment: I wanted to show themed status so I used the token [status:status-themed] but it is showing the code instead of a status post. I am pasting part of the code here to explain `   `
Comment: @Umair : I have no idea what this may be related to. Why not post that as a new question?
Comment: I also tried the replacement token "mentioning_statuses_html" and in message settings I used "Full html" as text format.
Comment: ok no problem pierre


Analyzing multiple, within-subjects, non-independent ordinal rankings

Question: So I'm working with some previously collected data where participants (N=139) were asked to rank 3 types of events (1 being best, 3 being worst) for 6 separate scenarios. The question of interest is whether, across all 6 scenarios, the 3 types differ in their rankings. Is Type A ranked higher than Type B? Is Type A ranked higher than Type C? Is Type B ranked higher than Type C?
I'm not sure how best to conceptualize and analyze this data. Obviously, a participant's rankings for each event type for each scenario is non-independent, so how can I compare the rankings when they are dependent on one another? I'm mainly looking for an idea of what tests to look into. I've checked out Friedman's Test, but I'm not sure my data apply due to the non-independence of the rankings and the fact that the rankings are repeated across scenarios. I also can see how the data would fit into a multilevel model (rankings within scenarios within participants), but I'm not sure how to deal with the non-independence of the rankings.
As a note, the data is really easy to present DESCRIPTIVELY and leads to clear conclusions, but I'd like to be able to back-up these conclusions up with some inferential statistics if possible.
Average Rank Collapsed Across Scenario
Type 1: 1.55 (SD = .29)
Ranked 1st 57%. Ranked 2nd 33%. Ranked 3rd 9%.
Type 2: 1.75 (SD = .29)
Ranked 1st 38%. Ranked 2nd 53%. Ranked 3rd 10%.
Type 3: 2.70 (SD = .31)
Ranked 1st 5%. Ranked 2nd 14%. Ranked 3rd 81%.
Answer: I know this isn't your data, but as a side note, asking subjects for rankings is generally a poor way to ask a question (depending on what you're looking for) because you are putting yourself in a situation where your data fits with a repeated measures ANOVA, but you have a subject main effect of 0 (all subjects will have the same mean). That means that your error term (the subject by factor interaction) is as large as it can be. This is one of the few cases where within subjects designs have less power than between subjects designs. Asking for ratings would give you more power.
Anyway, you'll be fine with a repeated measures ANOVA. A) most nonparametric tests are the equivalent to doing an ANOVA/regression on rank transformations of the data. Instead of asking for ratings and then transforming them yourself, you implicitly asked your subjects to do it for you. B) Even if you asked for ratings instead of rankings, your data would still be dependent. You remove the dependence by analyzing within subjects. To test the hypothesis that A is ranked higher than B which is ranked higher than C, you just test the within subject contrast that would equate to that prediction.
Edit: When formulating the answer, I didn't consider that there are only 3 things that can be ranked. That is rather few and you could run into other problems besides dependence. However, I ran the following simulation, which revealed no effect on type I error rate.
<code>set.seed(555)
ps<-numeric()#initialize
for(i in 1:5000){
    a<-cbind(c(1,2,3),c(1,3,2),c(2,1,3),c(2,3,1),c(3,1,2),c(3,2,1))#all possible combinations
    b<-sample(c(1,2,3,4,5,6),100,T)#create a sample of 100 with equal probability
    dat<-stack(data.frame(a[,b]))#convert to one column
    dat$version<-rep(c("A","B","C"),100)#add version/type column
    ps[i]<-summary(aov(values~version+Error(ind/version),data=dat))[[2]][[1]][["Pr(>F)"]][[1]]#get p value
}
length(ps[ps<.05])/5000
#> .0494
</code>
Comment: Appreciate the response, and, yeah, I whole-heartedly agree with avoiding rankings in preference for ratings; most of my research focuses on ratings.

What are your thoughts on collapsing across the scenario variable vs. running a 3 (type) x 6 (scenario) model vs. using a multi-level model? I'm not expecting differences across scenario (other studies using the same scenarios haven't found consistent cross-scenario differences), but I should probably run it that way to be sure.
Comment: I'm a fan of multilevel models in that scenarios seem like a random effect (I don't know the context, though) and should be treated as such. There may be power issues with only six scenarios, however. If there is truly little variation between scenarios I imagine it won't matter though.


Access Control Lists & DHCP

Question: Please take a look at this image right here.
In the image above you can see a virtual netwerk simulation program (CISCO Packet Tracer 6.0) where I'm trying to setup a network and secure it.
However I've come to the point where I want to use Access Control Lists in combination with DHCP. However, I haven't managed to find a way to bind certain MAC addresses to specific IP addresses (If anyone would know how to do this in this program... please let me know).
So I figured out that that might bring me future problems. Where a lease would be released and a new IP is handed out. When a computer then tries to access certain parts of the network, the ACL might block them...
Would anyone be able to hand me some information on how to deal with this so that if I connected a "attacker" computer to this network, it gets blocked. But when a computer in the network receives a new IP adres, it doesn't block it?
You might be thinking: Use port-security...
However, for me to understand ACL's better I would like to find a way to use it in this network.
Thank you in advance!
Dempsey
Answer:
However, I haven't managed to find a way to bind certain MAC addresses
  to specific IP addresses (If anyone would know how to do this in this
  program... please let me know).

Yes, you can do that. Imagining you want client Gnouc, MAC address xxxx.yyyy.zzzz will have IP 192.168.1.100, then you do this in router:
<code>ip dhcp pool Gnouc
host 192.168.1.100
hardware-address xxxx.yyyy.zzzz ieee802
client-name Gnouc
</code>
Try and feedback.

Would anyone be able to hand me some information on how to deal with
  this so that if I connected a "attacker" computer to this network, it
  gets blocked. But when a computer in the network receives a new IP
  adres, it doesn't block it?

I think ACL can not do that, you must use mac access-list.
Comment: I presume this is based on using the router as a DHCP server?
Comment: Yes, it is not you want?
Comment: Sure that could work :) However, I've been told that if you have a server using DHCP, if a router is using DHCP it will disable the one running on a server.
Comment: Don't understand what you want? If you want ACL for DHCP, i.e MAC address, it is impossible, use `mac access-list` instead.
Comment: The idea you gave me is good, i'll test it out first thing in the morning. However, in my current setup i have a server dedicated for DHCP... long story short... i'll remove the dedicated DHCP to avoid conflicts. I will give you feedback on the outcome tommorrow.
Comment: I'm unable to use these commands in the routers that are provided in this network simulator. The routers available in this simulator are: 1841, 1941, 2620XM, 2621XM, 2811, 2901, 2911.. all cisco.
Comment: Refer this `http://www.uptimekeeper.net/2011/01/configuring-cisco-ios-dhcp-reservation/`

Access Control Lists & DHCP


Finding rows that do not have particular child rows

Question: I have two tables that pertain to images:
ImageInfo
---------
Id
Name
Photographer

Images
------
Id
ImageInfo_Id
Quality
URL

Images has a many-to-one foreign key relationship with ImageInfo, and can hold various qualities-- 600, 800 and other pixel resolutions, for a given ImageInfo entry.
What I'm after are all ImageInfo IDs that do not have a 600 pixel quality entry in the Images table.  How can I best do this?  I'm thinking of a left outer join or maybe where not exists statement but wanted to solicit opinions before going that route.
Answer: It sounds like not exists
select ii.*
from imageinfo ii
where not exists (select 1
                  from images i
                  where i.ImageInfo_Id = ii.id and
                        i.quality = '600 pixel' -- or whatever
                 );

You can also phrase this as a left join, but not exists is almost a direct translation of your question.


Assign PCollection back to global window

Question: I have a pipeline that takes a bounded PCollection, assigns timestamps to it and "windows" it into Sliding Windows. After a grouping transform, I want to assign the resulting PCollection back to the global window. I have not been able to figure out how to do this. See sample beam pseudo-code below:
import apache_beam as beam

with beam.Pipeline() as p:
    (
        p
        | beam.io.ReadFromText()
        | beam.ParDo(AddTimestampDoFn())
        | beam.WindowInto(beam.window.SlidingWindows(60, 60))
        | beam.GroupByKey()
        | beam.ParDo(SomethingElse()
        | beam.WindowInto(GlobalWindow()) # Here is where I want to bring back to global window
    )

Any ideas on how to go about it?
Answer: Using beam.WindowInto(window.GlobalWindows()) should work. For example, with this quick test:
data = [{'message': 'Hi', 'timestamp': time.time()}]

events = (p
  | 'Create Events' >> beam.Create(data) \
  | 'Add Timestamps' >> beam.Map(lambda x: beam.window.TimestampedValue(x, x['timestamp'])) \
  | 'Sliding Windows'   >> beam.WindowInto(beam.window.SlidingWindows(60, 60)) \
  | 'First window' >> beam.ParDo(DebugPrinterFn()) \
  | 'global Window'   >> beam.WindowInto(window.GlobalWindows()) \
  | 'Second window'   >> beam.ParDo(DebugPrinterFn()))

where DebugPrinterFn prints window information:
class DebugPrinterFn(beam.DoFn):
  """Just prints the element and window"""
  def process(self, element, window=beam.DoFn.WindowParam):
    logging.info("Received message %s in window=%s", element['message'], window)
    yield element

I get the following output:
INFO:root:Received message Hi in window=[1575565500.0, 1575565560.0)
INFO:root:Received message Hi in window=GlobalWindow

Tested with the DirectRunner and 2.16.0 SDK. If it does not work for you:

Do you get any error?
Which runner and SDK are you using?

Full code here


symfony security prod doesn't work

Question: I'm using symfony 3.2.3, and I want restrict access on same pages.
Ok, no problem! Configuring security.yml, all can be done, and actually it works in dev environment.
But, when I switch my symfony site in production mode, nothing works any more!
Switching to prod commands:

php bin\console cache:clear --env=prod --no-debug

I have 4 pages:

/homepage (can access everyone)
/lucky (can access everyone)
/auth_area (can access only logged users)
/backend (can access only ROLE_ADMIN users)

Here my security.yml
security:
encoders:
    FOS\UserBundle\Model\UserInterface: bcrypt

role_hierarchy:
    ROLE_USER_LOGGED: IS_AUTHENTICATED_FULLY
    ROLE_ADMIN:       ROLE_USER_LOGGED

providers:
    fos_userbundle:
        id: fos_user.user_provider.username

firewalls:
    dev:
        pattern: ^/(_(profiler|wdt)|css|images|js)/
        security: false

    default:
        anonymous: ~
        http_basic: ~
        form_login:
            provider: fos_userbundle
            csrf_token_generator: security.csrf.token_manager
        logout:
            path: /logout
            target: /

access_control:
    - { path: ^/, roles: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/login$, role: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/backend, roles: ROLE_ADMIN }
    - { path: ^/auth_area, roles: IS_AUTHENTICATED_FULLY }

Finally, all works fine on dev, nothing works in prod: anonymous user can access everywhere! ;(
Thanks in advance!
Comment: Looking at your access control these lines are useless if you have only 2 specific areas with limited access: `- { path: ^/, roles: IS_AUTHENTICATED_ANONYMOUSLY }` and - `{ path: ^/login$, role: IS_AUTHENTICATED_ANONYMOUSLY }`. Comment out these 2 directives, delete the cache and try. PS: I think the first directive is always matched and cause your problem.
Answer: As written by gp_sflover in a comment:

PS: I think the first directive is always matched and cause your problem.

and in the documentation:

For each incoming request, Symfony checks each access_control entry to find one that matches the current request. As soon as it finds a matching access_control entry, it stops - only the first matching access_control is used to enforce access.

So you have to change the order of your rules and put the rule that match every request (path: ^/) at the end:
access_control:
    - { path: ^/login$, role: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/backend, roles: ROLE_ADMIN }
    - { path: ^/auth_area, roles: IS_AUTHENTICATED_FULLY }
    - { path: ^/, roles: IS_AUTHENTICATED_ANONYMOUSLY }

Comment: @JaredFarrish in the case described in your question you need only the directives that prevents the access, because the users are already allowed to access any page of your site as `IS_AUTHENTICATED_ANONYMOUSLY` (this happens because each  firewall is enabled `security: true` by default).
Comment: Hi @mardif if this answer has solved your question please consider [accepting it](http://meta.stackexchange.com/a/5235/237701) by clicking the check-mark. This indicates to the wider community that you've found a solution and gives some reputation to both the answerer and yourself. There is no obligation to do this.
Comment: Is `^/login$` needed? It would seem to be covered under `^/` and the other two do not apply.
Comment: To wit: I'm not the OP.
Comment: @JaredFarrish Yes, you're right. It's not required but it's part of the [default configuration of FOSUserBundle](http://symfony.com/doc/current/bundles/FOSUserBundle/index.html#step-4-configure-your-application-s-security-yml). So it may be better to keep it, for example if later you change the roles of `path: ^/` you may have unexpected behaviours.

symfony security prod doesn't work


Confusion about how $A$ is equal to its successor when $A$ is a proper class

Question: In the set theory text I am reading, J. Donald Monk's Introduction to Set Theory, it is stated (p.20):

If $A$ is a proper class, then $\mathcal{S}(A) = A$

where $\mathcal{S}(A) := \{ x : x \in A \vee x = A \}$, and is called the successor of $A$.
The provided proof is essentially as follows.

Assume that $X$ is any class. If $X ∈ A$, then $X$ is a set and either:
  $X \in A$   or   $X = A$.  Hence, $X \in  \mathcal{S}(A)$.
If $X \in \mathcal{S}(A)$, then $X \in A$  or $X = A$, and $X$ is a set;
  since $A$ is not a set, the possibility $X = A$ is excluded, so that we
  always have $X \in A$.
Thus $(\forall X) [X \in \mathcal{S}(A) \Leftrightarrow  X \in A]$  and so that by the axiom of extensionality, $\mathcal{S}(A) = A$.

I am confused about step (1). Given a class $C$, if $x$ is an element
of $\mathcal{S}(C)$, must it be true that either

$x$ is an element of $C$  (this seems obvious), or
$x = C$  (this seems very non-obvious)?

On the other hand, when I consider that $A = \{A\}$  is legal for a class, but not a set, and then when I am given  the statement   $X \in A$, and I am also told $A$ is a proper class (which cannot be an element of any other set or class), then I guess I do understand that, in this case,  $X$ must be equal to $A$.
Given what I wrote on the last paragraph, maybe I actually do understand this?

Epilogue:
The Elvis Presley analogy (from Arthur's comment) turned on the light bulb for me.   First.. I checked and Elvis is indeed dead, so what Arthur did was point out  that the true/falseness of a statement 'S' is not changed if  we say
S OR something-known-to-be-false
The something-known-to-be-false in step 1  was X = A  (stated right after we said $X ∈ A$, which means that no way can X=A).  I understand (finally) why the known-not-to-be-true thing was tacked on.  It was tacked on so that we could state that  $X \in  \mathcal{S}(A)$ to feed in to the argument that follows.
Comment: The successor of a class is the collection of sets *belonging* to that class or *equal* to that class.  Since a proper class isn't a set, the second case can't happen: its successor is just the collection of sets *belonging* to it, i.e., the proper class itself.
Comment: Remember that "or" in mathematics is inclusive; if $x \in C$, then "$x \in C\text{ or Elvis Presley is still alive}$" is true.
Comment: Arthur - thanks a million... if you make your comment an answer i will happily accept ;^)
Answer: I agree with mjqxxxx. The reason is that the definition uses a naive but nevertheless set based class builder, i.e. the variable x is lower case and therefore stands for a set. But a proper class is not a set, so that x=A never succeeds, and then you have S(A)=A.
See also this theorem here:
A proper class is its own successor
http://at.metamath.org/mpegif/sucprc.html
If you would have classes of classes, and use a different class builder, you would also get a different successor of a class, with S(A)<>A. But this successor is not a class anymore, so I guess things would get pretty contrieved, at last not simply typed anymore.


How to read scientific notation output (numbers that include "e")?

Question: After running the lm regression model using R, sometime one is bound to get very small P values or values in the covariance matrix. Something of the sort: -1.861246e-04 for example in a covariance matrix. My question is how do you read this? how could I perform calculations on it manually? I needed to multiply this covariance matrix out with a vector but since I do not know how to manipulate those numbers, I am lost.
Comment: @Gordon Smyth Did O.P. really get : -1.861246e-04 for p-value? That is a negative number for p-value. Is that possible?
Comment: *minus one point eight six times ten to the [power of] minus four*
Answer: The "e" is a symbol for base-10 scientific notation. The "e" stands for $\times 10^{\rm exponent}$. So -1.861246e-04 means $-1.861246 \times 10^{-4}$. In fixed-point notation that would be -0.0001861246.
This notation is pretty standard. Even Microsoft Excel understands it, not just R.
Comment: @dc3rd You don't need to. Scientific notation was developed because it is useful. You should perform calculations with just the numbers, and multiply the powers of ten separately. For example, 2e-5 * 8e-3 = (2*8)e(-5-3) = 16e-8 = 1.6e-7
Comment: Thank you. Just means I'm going to have a lot of decimals in my manual calculation.
Comment: @Gordon As per your answer I have tried to verify if python 2.7.5 understand ->
-6.53842823889031e+18 vs -6538428238890310000 are the same value when equated using '==' it doesn't think so why?
>>> d
-6.53842823889031e+18
>>> e
-6538428238890310000
>>> d == e
False
Care to comment ? Am I understanding it wrong?
Answer: I cannot yet comment so this answer will be a response to @Mark L. Stone :  OP also stated that he's getting covariance matrix values in the scientific notation. Obviously the negative value must be one of the covariances.
To not be completely OT I will just add that working with scientific notation to me looks a bit clunky(especially if you are publishing the results). To supress the notation in R use the command options(scipen=alpha) where alpha is the maximum number of digits for the result to be still expressed in fixed notation.
Comment: Thanks. It appears that in response to my comment, the OP edited the question to add "in a covariance matrix"" to what is now "-1.861246e-04 for example in a covariance matrix"


Kaplan-Meier curves seem to say otherwise than the Cox regression

Question: In R, I am doing survival data analysis of cancer patients.
I have been reading very helpful stuff about survival analysis in CrossValidated and other places and think I understood how to interpret the Cox regression results. However, one result still bugs me...
I am comparing survival vs. gender. The Kaplan-Meier curves are in clear favour of female patients (I have checked several times that the legend I have added is correct, the patient with the maximum survival, 4856 days, is indeed a woman):

And the Cox regression is returning:
Call:
coxph(formula = survival ~ gender, data = Clinical)

  n= 348, number of events= 154

              coef exp(coef) se(coef)      z Pr(>|z|)
gendermale -0.3707    0.6903   0.1758 -2.109    0.035 *
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

           exp(coef) exp(-coef) lower .95 upper .95
gendermale    0.6903      1.449    0.4891    0.9742

Concordance= 0.555  (se = 0.019 )
Rsquare= 0.012   (max possible= 0.989 )
Likelihood ratio test= 4.23  on 1 df,   p=0.03982
Wald test            = 4.45  on 1 df,   p=0.03499
Score (logrank) test = 4.5  on 1 df,   p=0.03396

So Hazards Ratio (HR) for male patients (gendermale) is 0.6903. The way I would interpret that (without looking at the Kaplan-Meier curve) is: as the HR is <1, being a patient of male gender is protective. Or more precisely, a female patient is 1/0.6903 =  exp(-coef) = 1.449 more likely to die at any specific time than a male.
But that does not seem like what the Kaplan-Meier curves say! What's wrong with my interpretation?
Comment: NB It's the curves $\log -\log \hat S_i(t)$, where $\hat S_i(t)$ is the estimated survival function for group $i$, that should be parallel under proportional hazards. As @IWS points out, the confidence intervals will be very wide for the female group after about 3000 days (are there only two making it past that point?) so the PH assumption *may* not be too bad.
Comment: From your K-M curve, it seems PH assumption of Cox regression is not hold.
Comment: I see. I haven't look into that before! Graphically, it means my Kaplan-Meier curves should be parallel so I can safely use Cox, right? That seems more or less OK before ~2200 days. Is it alright to have a look at the Cox results for all data a bit before the intersection?
Comment: @DeepNorth: I don't really see strong evidence against proportional hazards. Yeah the curves technically overlap...but that's on the extreme tails.
Comment: To complement the other answers and comments, compare the median survival or five year survival for males and for females. There is a clear benefit for males in this data in agreement with the Cox PH analysis.
Answer: This is a very good example of non-proportional hazards OR the effect of 'depletion' in survival analysis. I will try to explain.
At first take a good look at your Kaplan-Meier (KM) curve: you can see in the first part (until around 3000 days) the proportion of males still alive in the population at risk at time t is larger than the proportion of females (i.e. the blue line is 'higher' than the red one). This means that indeed male gender is 'protective' for the event (death) studied. Accordingly the hazard ratio should be between 0 and 1 (and the coefficient should be negative).
However, after day 3000, the red line is higher! This would indeed suggest the opposite. Based on this KM graph alone, this would further suggest a non-proportional hazard. In this case 'non-proportional' means that the effect of your independent variable (gender) is not constant over time. In other words, the hazard ratio is viable to change as time progresses. As explained above, this seems the case. The regular proportional hazard Cox model does not accommodate such effects. Actually, one of the main assumptions is that the hazards are proportional! Now you can actually model non-proportional hazards as well, but that is beyond the scope of this answer.
There is one additional comment to make: this difference could be due to the true hazards being non-proportional or the fact that there is a lot of variance in the tail estimates of the KM curves. Note that at this point in time the total group of 348 patients will have declined to a very small population still at risk. As you can see, both gender groups have patients experiencing the event and patients being censored (the vertical lines). As the population at risk declines, the survival estimates will become less certain. If you would have plotted 95% confidence intervals around the KM lines, you would see the width of the confidence interval increasing. This is important for the estimation of hazards as well. Put simply, as the population at risk and amount of events in the final period of your study is low, this period will contribute less to the estimates in your initial cox model.
Finally, this would explain why the hazard (assumed constant over time) is more in line with the first part of your KM, instead of the final endpoint.
EDIT: see @Scrotchi's spot-on comment to the original question: As stated, the effect of low numbers in the final period of the study is that the estimates of the hazards at those points in time are uncertain. Consequently you are also less certain whether the apparent violation of the proportional hazards assumption isn't due to chance. As @ scrotchi's states, the PH assumption may not be that bad.
Comment: @CliffAB Thanks for the feedback Cliff AB. I am a bit confused though, as your remark is exactly what I was trying to say. I'll admit: it could have been a little shorter. The -1 is a tad bit harsh though :'(
Comment: perhaps it was a bit mean of me. My only point is that when I look at this, I don't see necessarily a good example of non proportional hazards, but rather little data on the tails. I see the first sentence has been revised (I think unless I missed this the first time?) to address though, so now the (-1) is definitely uncalled for.
Comment: (-1) The tails cross on the extreme ends, where we have extremely little data. In fact, the evidence for "non-proportional hazards" is based on only two observations (i.e. when t >2800, there were only two subjects left in the female cohort, and besides that, the last event before that in the group was around t = 2100)
Comment: Oops, it appears I did miss it the first time. Sorry!
Comment: No problem, at leest we agree on the answer :D
Answer: You are confused as to the nature of your output. These data say: If you are a male you are more likely to live longer than a female; Females have WORSE survival than males. This is reflected in the regression output as the effect for being MALE is to have a negative log hazard ratio, e.g. males have lower risk than females. At most event times (when the curves "step"), the male survival curve is greater than that of the females, the Cox model results and graph agree very well. The KM curves confirm this as do the regression model output. The "cross" is an inconsequential one.
KM curves behave poorly in the tails, especially when they near 0% and/or taper off flatly. The Y-axis is the proportion surviving. With relatively few who survive long into the study, and few who die at that time, the reliability of the estimates is intuitively and graphically terrible. I note, for instance, there are visibly fewer females in your cohort than males and that after 2,800 days, there are less than 10 females remaining in the cohort, as evidenced by the steps in the survival curve and lack of censored events.
As an interesting note, because survival analyses using KM curves, log rank tests, and Cox models use ranked survival time, the actual duration of survival is somewhat irrelevant. Your longest surviving female could, infact, have survived for another 100 years and it would have no impact on the analyses. This is because the baseline hazard function (not having observed any events for the past 13 years) would assume there was no risk of death for those next 87 years since nobody died then.
If you want a robust HR to obtain correct 95% CIs and p-values for this, specify robust=TRUE in the Cox-PH to obtain sandwich standard errors. In that case, the HR is a time-averaged HR comparing males to females at all failure times.
Comment: @HarveyMotulsky true but the tails of KMs are very unreliable
. If OP drew the CIs they would overlap strongly, so that inferentially we would say that the survival was probably equivocal after 2,700 days.
Comment: To clarify: In the KM plot, males have better survival up to about 2700 days. After that, women have better survival. But that tail isn't precise because there is so little data out there. You can see that two steps in the KM curve take female survival from about 35% to 0%, so that is most likely two people.It would be helpful to plot the KM curves with confidence bands. Then I'd guess that you'd see clear separation up to about 2000 days, and then overlap after that.
Comment: Exactly my point. The data clearly show that males (in this situation, whatever it is) have better survival at least for the first 2000+ days.


Problemas com Variáveis no JS

Question: Tenho algumas inputs que deverão se autopreencherem.

Funciona assim: preencho a input Código de Barras 1 e o JS preenche automaticamente a Descrição do Produto 1 e o Valor Unitário 1.
O problema que estou tendo é que que quando coloco o Código de Barras 1 ele preenche os dados do 2 do 3 do 4 e se eu preenche o Código de Barras 2 e o JS 'reeprenche' as inputs 1, 2, 3 ...
Segue meu script:

  $(document).ready(function(){
   $('.class_codbar input[id^=cod]').blur(function(){
    var $descricao_produto = $('.class_descricao input[id^=descricao]');
    var $preco_produto = $('.class_unit input[id^=valor_unitario]');
    $.getJSON('preenche_produto.php',{
     cod: $( this ).val()
    },function( json ){
     $descricao_produto.val( json.descricao_produto );
     $preco_produto.val( json.preco_produto );
    });
   });
  });

   Código de Barras "+iLoop+"
   <input type='text' class='form-control' id='cod"+iLoop+"' name='cod"+iLoop+"' >

   Descrição Produto "+iLoop+"
   <input type='text' class='form-control' id='descricao"+iLoop+"' name='descricao"+iLoop+"'>

   Valor Unitário "+iLoop+"
   <input type='text' class='selectall form-control' id='valor_unitario"+iLoop+"' name='valor_unitario"+iLoop+"' onkeyup='k(this);' value='0,00'>

   Quantidade "+iLoop+"
   <input type='text' class='selectall form-control' id='qnt"+iLoop+"' name='qnt"+iLoop+"' value='0'>

   Subtotal "+iLoop+"
   <input type='text' class='form-control' id='subtotal"+iLoop+"' name='subtotal"+iLoop+"' readonly>

   <input type='button' value='Remover' onclick='RemoverCampos(\""+iLoop+"\")' class='btn btn-sm btn-danger'>

Comment: Como está seu HTML?
Comment: Coloquei o HTML!
Answer: Tenta ajustar o js dessa forma:
$(document).ready(function(){
    $('.class_codbar input[id^=cod]').blur(function(){
        var parent = $(this).closest('[id^=linha]');
        var $descricao_produto = parent.find('.class_descricao input[id^=descricao]');
        var $preco_produto = parent.find('.class_unit input[id^=valor_unitario]');
        $.getJSON('preenche_produto.php',{
            cod: $( this ).val()
        },function( json ){
            $descricao_produto.val( json.descricao_produto );
            $preco_produto.val( json.preco_produto );
        });
    });
});

Assim, ele vai sempre procurar a linha "pai", salvá-la na var parent e atribuir os valores somente aos elementos filhos da respectiva linha.
Comment: Detalhe: acabei de editar a linha 5 da resposta acima, corrigindo (tinha esquecido de adicionar `.find` nessa linha) :D
Comment: Perfeito! Entendi o porque não estava passando a variável da id.
Answer: Supondo que iLoop seja um index que será incrementado e adicionado aos ids
O this.id.substr(3) pega o id do input do código de barras e retira os 3 primeiros caracteres (cod) e sobra o iLoop, então use ele para selecionar os elementos que fazem parte do conjunto

$(document).ready(function() {
  $('.class_codbar input[id^=cod]').blur(function() {
    var $descricao_produto = $('.class_descricao input#descricao'+this.id.substr(3));

    var $preco_produto = $('.class_unit input#valor_unitario'+this.id.substr(3));

    console.log($descricao_produto[0], $preco_produto[0])

    $.getJSON('preenche_produto.php',{
        cod: $( this ).val()
    },function( json ){
        $descricao_produto.val( json.descricao_produto );
        $preco_produto.val( json.preco_produto );
    });
  });
});

      Código de Barras 1
      <input type='text' class='form-control' id='cod1' name='cod1'>

      Descrição Produto 1
      <input type='text' class='form-control' id='descricao1' name='descricao1'>

      Valor Unitário 1
      <input type='text' class='selectall form-control' id='valor_unitario1' name='valor_unitario1' onkeyup='k(this);' value='0,00'>

      Quantidade 1
      <input type='text' class='selectall form-control' id='qnt1' name='qnt1' value='0'>

      Subtotal 1
      <input type='text' class='form-control' id='subtotal"+iLoop+"' name='subtotal1' readonly>

      <input type='button' value='Remover' onclick='RemoverCampos("1")' class='btn btn-sm btn-danger'>

Comment: Do mesmo jeito, a única coisa que muda é como selecionar os elementos que receberão os dados. Atualizei a resposta completando
Comment: Ok, mas nesse caso como eu mando a id da input para o arquivo php de pesquisa?

Problemas com Variáveis no JS


How do you play this trill?

Question:
This trill is in my music and I don't know how to play it.
Comment: As loudly as humanly possible, apparently.
Comment: It may be important to know which instrument you play.
Comment: I play the tenor sax, and an F-G trill would be just as easy as an F-F#
Comment: I'm not sure if I would trill to the first available diatonic note, the F#, or trill up to the G in note sequence. Since it resolves to the G, I'd probably trill to the F# and get the chromatic upwards resolution.  More context (style or time period) and what instrument would help.
Comment: It won't be piano, r.h., but what is it?
Comment: @Tim Could be anything: violin, flute, etc.
Comment: @yo' - true, but some fingerings for trills are probably easier on specific instruments, between F/F# or F/G.
Answer: You play:

fff so obviously very loudly. Note that probably the whole trill shall be very loud; a loud sharp attack would be better noted sfz, but actually, both interpretations are possible.
Then it's easy: you play the thrill on F-G the whole time. Accidentals don't have to be repeated after a tie, so there is certainly no F# involved.
The final eight-note G staccato just tells you that you shall end in G and that the G shall be prominent; not necessarily very loud, but the audience have to be sure that you intended to end in G rather than F (or fade out or whatever.
Comment: @AlphonsoBalvenie That's not how trills work. A trill *always* alternates between two pitches with adjacent note names. If the main note should be a version with an accidental, it is written to the left of the note, and an accidental for the ancillary note is notated above the trill. You *never* trill between f and f sharp. You could trill between e sharp and f sharp, but only if you notate it as an e sharp.
Comment: Playing F to G would be skipping the next available diatonic note of the key, so why wouldn't you play it F - F#? Is the accidental replacing the F#''s position in the diatonic sequence and not acting as an additional accidental note?
Comment: To clarify, I would expect that to trill up a whole step from the F to G, the trill sign should be a TR#, where a regular TR would select the next available note in the diatonic scale that the key signature presents.
Comment: @AlphonsoBalvenie That would have been likely noted as a trill on E# (with the # accidental explicitly written).
Comment: yeah, that's what I thought too. The confusion came when I looked it up in one of my theory books and it indicated that the trill should always go to the next available note in the diatonic sequence available in the key. In some cases transcriptions don't always get the rules correct and you have to rely on style knowledge.  Looking at the phrase again, it could be described as G Mixolydian,  making a F to G trill appropriate.
Comment: @AlphonsoBalvenie Well, any trill can be appropriate as we don't know the context really.
Answer: I think the sound of F and F# are more suited, as it's all leading to a cadence on the final G - subdominant of the key (more like D than Bm), so the trill would then give a leading note rather than the target note of G. Obviously very loudly.

How do you play this trill?


What is inverse of $I+A$?

Question: Assume $A$ is a square invertible matrix and we have $A^{-1}$. If we know that $I+A$ is also invertible, do we have a close form for $(I+A)^{-1}$ in terms of $A^{-1}$ and $A$?
Does it make it any easier if we know that sum of all rows are equal?
Comment: By substituting $A'=A-I$, you are basically asking for the inverse of *all* matrices.
Comment: The identity $(A^{-1}+I)^{-1} = A - A \, (I+A)^{-1}A$ (consequence of Woodbury matrix identity) does not answer you question, but perhaps you find it useful.
Comment: And of course, it might well be that $A$ is invertible, while $I + A$ is not.
Comment: equal row sum won't help either. Consider the 2x2 matrix obtained from I by interchanging its rows.
Comment: What does "convertible" mean?
Comment: I have edited my question. Assume (I+A) is invertible and also we have $A^{-1}$, then can we write $(I+A)^{-1}$ as a function of $A$ and $A^{-1}$ ?
Answer: I know I'am a bit late, but I wanted to add the following for future readers.
If you know the Eigendecomposition of your matrix $A = Q \Lambda Q^{-1}$ the result is the following:
\begin{equation}
\left( A + I\right)^{-1}
=\left( Q \Lambda Q^{-1} + I\right)^{-1}
=\left( Q \left(\Lambda + I \right) Q^{-1}\right)^{-1}
= Q \left(\Lambda + I \right)^{-1} Q^{-1}
\end{equation}
I know that this is a very trivial calculation and the result is maybe not helpful to many of you, but I wasted countless hours using the Shermann-Morrison-Theorem because I forgot about the Eigendecomposition.
Cheers,
Lukas
Comment: (+1) This answer was exactly what I was looking for. I have an iterative method with $A_i = a_iA_0$. So now inverting the matrix at step $i$ just involves inverting a diagonal matrix!
Answer: If the series $S = I - A + A^2 - A^3 + \dotsb$ converges, expand $S(I + A)$ to find that it is equal to the identity. See here for details on when $S$ converges.
$S$ clearly converges if $A^k = 0$ for some positive integer $k$ (nilpotency).
As for invertibility, if $A$ is diagonalizable, i.e. $A = PDP^{-1}$ for some diagonal matrix $D = \operatorname{diag}(e_1, e_2, \dotsc, e_n)$, then by Sylvester's Determinant Theorem,
$$
\det(I + (PD)P^{-1}) = \det(P^{-1}(PD) + I) = \prod_{i = 1}^n(e_i + 1)
$$
Hence, $I + A$ is invertible if no eigenvalue $e_i$ has a value of $-1$.
If $A$ is nilpotent, then its only eigenvalue is $0$, so $I + A$ is invertible.
Is there a closed-form solution?
I believe not. Basically, a closed-form expression of $(I + A)^{-1}$ using $A$ and $A^{-1}$ would amount to a closed-form expression of $(1 + x)^{-1}$ using $x$ and $x^{-1}$, where $x$ is real (or complex). A semi-rigorous articulation of this argument follows:

Proposition: There exists no family of matrices $\{X_{ij}\}_{m \times n}$, where every $X_{ij}$ is either equal to $A$, $A^{-1}$ or a constant dependent on the dimension of $A$, such that $(I + A)^{-1} = \sum_{i = 1}^m(\prod_{j = 1}^nX_{ij})$ for all values of $A$.

Proof:
Assume there exists such a family. Let $A$ be the $1 \times 1$ matrix $x$. Note that $\sum_{i = 1}^m(\prod_{j = 1}^nX_{ij})$ is a polynomial $P(x)$, which apparently equals $(1 + x)^{-1}$ for all values of $x$. Hence, $P(x)$ must be the taylor series $1 - x + x^2 - x^3 + \dotsb$, which contradicts the fact that $P(x)$ has a finite number of terms.
Comment: I doubt so. How can you express $\displaystyle\frac1{1+x}$ using only $\displaystyle\frac1x$ and $x$..?
Comment: Herng, thanks for your comment. if we know that (I+A) is invertible and also we have $A^{-1}$. Then can we write a close form solution for $(I+A)^{-1}$?
Comment: haha I had the same idea as @Berci and edited it into the answer.
Answer: Check this question. The first answer presents a recursive formula to retrieve the inverse of a generic sum of matrices. So yours should be a special case.
Comment: In particular to answer the question on how to express $\frac{1}{1+x}$ using only $1,x$ and $1/x$ we have
$$
\frac{1}{1+x}=\frac{1}{x}-\frac{1}{1+trace(1/x)} \frac{1}{x^2}
$$
Comment: Thanks for your answer. I have checked that question, but the first answer suggest recursive formula when rank of one of the matrices is 1. But rank of I is not 1.
Comment: And after that Lemma, the autor states the theorem for rank>1

What is inverse of $I+A$?


Regex. Spliting os blank spaces. Accounting for double quoted text

Question: I am using regex to split a string. This is the input:
Value1   Value2   "Val ue3"
The output should be:

Value1
Value2
Val ue3

What regex should be using for this?
Comment: Don't do serial downvotes on my posts. And I'm not the downvoter.
Comment: Which lang you're running?
Comment: Typical SO is typical
Answer: You can try this pattern:
"\\w+|\"[\\w ]+\""

It'll match words and words with spaces in between quotes.  Since your output indicates you want the quotes removed then a String.Replace() can take care of that.
using System;
using System.Text.RegularExpressions;

public class Program
{
    public static void Main()
    {
        string data = "Value1   Value2   \"Val ue3\"";
        MatchCollection matchCollection = Regex.Matches(data, "\\w+|\"[\\w ]+\"");
        foreach (Match match in matchCollection)
        {
            Console.WriteLine(match.Value.Replace("\"", String.Empty));
        }
    }
}

Results:
Value1
Value2
Val ue3

Fiddle Demo


Remover entrada de uma matriz pelo valor da mesma

Question: Para remover uma entrada de uma matriz, podemos utilizar a função unset():
<?php
$arr = array(1, 2);

unset($arr[0]);

var_dump($arr);
/*
Resultado:
array(1) {
  [1]=>
  int(2)
}
*/
?>

Pergunta
Como remover uma entrada de uma matriz pelo seu valor ao invés da sua posição?
Mediante o exemplo em cima, iríamos passar o valor 1 ao invés da posição 0.
Answer: Para remover um item do array passando o valor, a função array_search(), resolve. Ela retona a chave caso o valor se encontrado no array e depois basta passar o indice para unset(). Essa função não reordena o array.
$arr = array(1,2,3,4,5,6);
echo'
ANTES';
print_r($arr);

$key = array_search(4, $arr);
unset($arr[$key]);

echo'
DEPOIS';
print_r($arr);

saida:
ANTESArray
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [5] => 6
)

DEPOISArray
(
    [0] => 1
    [1] => 2
    [2] => 3
    [4] => 5
    [5] => 6
)

Answer: Consegui pensar em duas formas de fazer isso:
1 - Usando array_search e array_values
Como já respondido pelo @perdeu a função array_search() resolve o problema de encontrar o valor.
Porém, gostaria de adicionar que a função [array_values][1] resolve a questão da reindexação, isto é, ela retorna os valores do array original indexados a partir do zero.
Veja um exemplo:

    $array = array(1, 2, 3, 4);
    $pos = array_search(2, $array); //buscar posição do segundo elemento
    unset($array[$pos]); //remover elemento
    $array = array_values($array); //recriar índice

A saída final será:

    array(3) {
      [0]=> int(1)
      [1]=> int(3)
      [2]=> int(4)
    }

Veja um exemplo funcional [aqui][2].

# 2 - Usando `array_splice`

Outra alternativa é usar a função [`array_splice()`][3], que permite substituir um trecho de um array por alguma outra coisa, que pode ser *nada*. Esta função altera o array original e recria os índices.

Exemplo:

    $array = array(1, 2, 3, 4);
    $pos = array_search(2, $array); //buscar posição do segundo elemento
    array_splice($array, $pos, 1); //remove 1 elemento na posição encontrada

O resultado é o mesmo citado anteriormente.

Veja o código funcionando [aqui][4].

  [1]: https://www.php.net/manual/pt_BR/function.array-values.php
  [2]: http://codepad.org/at29cKJz
  [3]: http://us2.php.net/manual/en/function.array-splice.php
  [4]: http://codepad.org/nVQlrXc9


How many times do I need to cache an ad?

Question: I am fairly new to using Chartboost ads, and haven't managed to find much info regarding this.
I have written a game in which an interstitial ad and 'more apps page' ad is cached immediately when the game loads and is displayed when the user receives a game over message/clicks on show more apps button.
My question is do I have to call cacheInterstitial() and cacheMoreApps() again every time to cache a new ad whenever a previously cached add is displayed to the user, or is this handled automatically after the first time I call on the api to cache an add?
Answer: if you are not using Chartboost Autocache feature then YES you will have to call cacheInterstitial() and cacheMoreApps() again every time you display a previously cached Ad or chartboost will keep on showing same ad again and again.
To use Autocaching feature read the section 'Autocaching' in Chartboost docs.


Please help me understand this formula solution.

Question: I have the solution to a problem.
$$f(t)=t, \pi ≤t<\pi$$
The solution to coeffisient b_n is: $$ b_n= \frac{1}{\pi}\displaystyle\int_{-\pi}^\pi f(t)sin(nt) dt=\frac{2}{\pi}\displaystyle\int_{0}^\pi f(t)sin(nt) dt$$
so $$\frac{1}{\pi}$$ becomes $$\frac{2}{\pi}$$ and $$\int_{-\pi}^\pi f(t)sin(nt) dt$$ becomes $$\int_{0}^\pi f(t)sin(nt) dt$$
Can someone please explain?
Comment: the product of two odd functions, such as $f(t)=t$ and $\sin(nt)$,  is an even function, and the integral of an even function over a symmetric interval, such as $[-\pi,\pi],$ is twice the value of its integral over the interval $[0,\pi]$
Answer: The product of two odd functions, such as $f(t)=t$ and $\sin(nt)$,  is an even function,
and the integral of an even function over a symmetric interval, such as $[-\pi,\pi],$
is twice the value of its integral over the interval $[0,\pi]$.
Comment: The product of two even functions is also an even function, the product of an even function and an odd function is an odd function, and the integral of an odd function from $−\pi$ to $\pi$ is zero
Comment: as I said, the integral of an odd function over a symmetric interval is $0$
Comment: Thanks. My head isn't working right now. I guess its time to sleep. I spent my whole day trying to figure this out. Its a shame my book doesn't mention this anywhere. Feel like I wasted a whole day. Thank you so much for the help. Hopefully, tomorrow will be a productive day.
Comment: I get it. Thank you very much. I didn't know about this special rule. Are there similar special rules for a product of two even functions over a symmetrical interval, and the product of an odd and an even function over a symmetrical interval?
Comment: Thanks. But, what I meant was, when you say the integral of an even function over a symmetric interval is twice the value of its integral over the interval [0,]. Is there a special rule like this, for integrals of an odd function over a symmetric interval?


unique group structure on elliptic curve

Question: Let $C$ be a curve of genus $1$ over a field $k$ with a $k$-rational point $O$, then by the theory of elliptic curve, there is a group structure $(C(k),+)$ on $C$ given by geometric construction or induced by the group structure of Pic$^0(C)$, and these two constructions give the same group structure with $O$ as the zero element.
Then I want to know if there exists another group structure $(C(k),\oplus)$ on $C$ with $O$ as the zero element again, but now there exists some pair $P,Q\in C(k)$ such that $P+Q\neq P\oplus Q$.
Edit: After reading Servaes's answer to this question, I am more concerned  with a construction compatible with complex topology or Zariski topology.
Thanks!
Comment: Perhaps you want your $\oplus$ to be a morphism of varieties too??
Comment: @Mummytheturkey Yes. Without topology, it is less interesting.
Answer: The group structure on any abelian variety is unique up to zero section. See Remark 1.3 in Milne's notes on abelian varieties.
Comment: Yes, the identity map is a regular bijective map, by Milne this is a group homomorphism, so the group structure is really the same. Thanks!
Answer: Of course; let $\sigma$ be any permutation of $C(k)$ that fixes $O$. Then the operation
$$\oplus:\ C(k)\times C(k)\ \longrightarrow\ C(k):\ (x,y)\ \longmapsto\ \sigma^{-1}(\sigma(x)+\sigma(y)),$$
defines a group structure on $C(k)$ with $O$ as its identity element. It is not hard to see that if $|C(k)|>3$ then there exists a permutation $\sigma$ so that the two operations $\oplus$ and $+$ are distinct.
Comment: This is a correct answer to the question. I'd just point out that it doesn't answer the more pertinent question of whether $E/k$ can be equipped with another structure as a *group variety*.
Comment: Thanks for your answer. Moreover, I wonder if we assume that the group operation $C(k)\times C(k)\ \longrightarrow\ C(k)$ is continuous in the Zariski topology or when $k$ is the complex field $\mathbb{C}$, we assume that the group operation is holomorphic, then does there exist such a group structure different from the group structure given by Pic$^{0}(k)$?
Comment: @Mummytheturkey   I am more concerned about if there exists a construction compatible with topology, complex topology or Zariski topology.


App de musica não roda no Android

Question: Olá eu estava criando um app de musica cuja  eu aperto o botão toque a musica, eu copilei todo código e fui executar o programa não depurou no meu celular e abri da um erro em seguida abre  uma tela  do executável de musica do próprio pc e começa a tocar no pc a musica.
imagens

código usado

<code>package imperiogamerplay.music;

    import android.support.v7.app.AppCompatActivity;
    import android.media.MediaPlayer;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.Button;

public class MainActivity extends AppCompatActivity {
Button bt;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    bt = (Button)findViewById(R.id.buttons);
    final MediaPlayer mp = MediaPlayer.create(this,R.raw.Starboy);
    bt.setOnClickListener(new View.OnClickListener(){
        @Override
        public  void  onClick(View view) {
            mp.start();
        }
    });

}

}
</code>
Comment: Ele esta dizendo que o nome do arquivo deve ser em caixa baixa, ou seja tudo minusculo!
Comment: Mesmo eu colocando menusculo ele da este tipo de erro  o de baixo
Answer: Olá, o arquivo de áudio não aceita letras maiúsculas ou caracteres especiais, renomeie seu arquivo para starboy.mp3 e faça o teste.
Rode diretamente no celular ou através de emulador
Comment: Obrigado erro simples falta de atenção minha . Mas mt obrigado

App de musica não roda no Android


Identity regarding exponential integral

Question: I came across an identity which is described in this book as "classical" (page 85/350):
\begin{equation}
\int_{0}^{x} \frac{1 - e^{-y}}{y} dy = E_1(x) + \log(x) + \gamma, \qquad x > 0
\end{equation}
where $\gamma$ is the Euler-Mascheroni constant and $E_1$ is defined as below:
\begin{equation}
E_1(x) = \int_{x}^{\infty} \frac{e^{-s}}{s} ds.
\end{equation}
Unfortunately, I was not able to prove this identity. My attempts have only provided me that the bilaterally derived equation holds, but not sure why $\gamma$ is the desired constant on the right hand side. I have a suspicion that one should somehow use the Weierstrass product representation of the gamma function (as the Euler-Mascheroni constant appears there as well) but to no avail.
Answer: I think I came up with the solution after a long enough search for similar topics :D.
As I wrote in the original post, it is enough to prove that the right hand side of the original equation converges to zero (because the supposed equation is true when derived by $x$ variable). Let us look on the integral $\int_{0}^{\infty} \log (t)\,e^{-t} dt$ in two different ways. On one hand:
\begin{align}
\int_{0}^{\infty}\log(t)\,e^{-t}\,dt
&=\lim_{n\to\infty}\int_0^n\log(t)\,\left(1-\frac{t}{n}\right)^n\,dt\\
&=\lim_{n\to\infty}n\int_0^1(\log(t)+\log(n))\,(1-t)^n\,dt\\
&=\lim_{n\to\infty}\left(\frac{n}{n+1}\log(n)+n\int_0^1\log(1-t)\,t^n\,dt\right)\\
&=\lim_{n\to\infty}\left(\frac{n}{n+1}\log(n)-\frac{n}{n+1}H_{n+1}\right)\\[6pt]
&=-\gamma.
\end{align}
In the above sequence of equations we used the monotone convergence, $t \mapsto nt$ substitution, $t \mapsto 1-t$ substitution, integration by parts and the definition of Euler-Mascheroni constant, respectively.
On the other hand, we can use integration by parts to see that:
\begin{align}
\int_{0}^{\infty}\log(t)\,e^{-t}\,dt
&= \lim_{y\to0^{+}} \left(\left[-e^{-t}\log(t)\right]_{t=y}^{\infty} - \int_{y}^{\infty}\frac{-e^{-t}}{t} dt \right)\\
&= \lim_{y\to0^{+}} \left(\log(y) - \int_{y}^{\infty}\frac{-e^{-t}}{t} dt \right)\\
&= \lim_{y\to0^{+}} \left(\log(y) + E_1(y) \right)\\
&= -\gamma,
\end{align}
because $\lim_{y\to0^{+}} e^{-t}\log(t) - \log(t) = 0$ (which is pretty easy to prove using well known limits: $\lim_{x\to0^+} x\ln x = 0$ and $\lim_{x\to0} (e^x - 1) / x = 1$).
Answer: $$\begin{align}
\int_{0}^{x} \frac{1 - e^{-y}}{y} dy
&=\int_{0}^{1} \frac{1 - e^{-y}}{y} dy+\int_{1}^{x} \frac{1 - e^{-y}}{y} dy\\
&=\int_{0}^{1} \frac{1 - e^{-y}}{y} dy+\int_{1}^{x} \frac{1}{y} dy-\int_{1}^{x} \frac{e^{-y}}{y} dy\\
&=\int_{0}^{1} \frac{1 - e^{-y}}{y} dy+\int_{1}^{x} \frac{1}{y} dy-\left(\int_{1}^{\infty} \frac{e^{-y}}{y} dy-\int_{x}^{\infty} \frac{e^{-y}}{y} dy\right)\\
&=\int_{0}^{1} \frac{1 - e^{-y}}{y} dy+[\ln{|y|}]_1^x-\left(E_1(1)-E_1(x)\right)\\
&=E_1(x)+\ln{(x)}+\int_{0}^{1} \frac{1 - e^{-y}}{y} dy-E_1(1)\\
\end{align}$$
Now all you have to do is prove that
$$\int_{0}^{1} \frac{1 - e^{-y}}{y} dy=\sum_{k=1}^\infty\frac{(-1)^{k+1}}{k(k!)}=\gamma+E_1(1)$$
which I am unsure of how to do.

Identity regarding exponential integral


If $f([a]) = a$ is a function from $\mathbb Z/4 \mathbb Z $to $\mathbb Z$ is it well-defined?

Question: I know that $\mathbb Z/4 \mathbb Z = \{[0],[1],[2],[3]\}$
and that $[0]$ is equal to $[4]$ but I am not sure how to know if this function is well defined. To be well defined, every input must give only one unique output.
Any suggestions?
Comment: Well obviously it isn't. As you have pointed out, if it were, then $4= f([4]) = f([0]) = 0$, but $4\neq 0$
Answer: You need to just combine your two statements to find that this is not well defined. In particular $[0]$ and $[4]$ are the same, as you note. However, your definition says $f([0])=0$ and $f([4])=4$. That is, you can put in two inputs that are the same ($[0]$ and $[4]$) and get two that are different ($0$ and $4$) - so this is not well defined.
Note that you could define a function such that $f([0])=0$ and $f([1])=1$ and $f([2])=2$ and $f([3])=3$, but then necessarily we would have $f([4])=f([0])=0$. (And this function is even sometimes useful to define - but it is defined differently than the one you have)


Proof of $\chi(G)\leq 1+\max_i\min\{d_i,i-1\}$ in graph theory

Question: I am learning a coloring theorem in graph theory:

If a graph $G$ has degree sequence $d_1\geq\cdots\geq d_n$, then $\chi(G)\leq 1+\max_i\min\{d_i,i-1\}$.

The proof in the book consists of 4 sentences:

We apply greedy coloring to the vertices in nonincreasing order of degree.
When we color the $i$th vertex $v_i$, it has at most $\min\{d_i,i-1\}$ earlier neighbors, wo at most this many colors appear on its earlier neighbors.
Hence the color we assign to $v_i$ is at most $1+\min\{d_i,i-1\}$.
This holds for each vertex, so we maximize over $i$ to obtain the upper bound on the maximum color used.

The greedy coloring relative to a vertex ordering $v_1,\cdots,v_n$ of $V(G)$ is obtained by coloring vertices in the order $v_1,\cdots,v_n$, assigning to $v_i$ the smallest-indexed color not already used on its lower-indexed neighbors.

I don't understand the first sentence in the proof: Where do we use the nonincreasing order of degree in the rest of the proof?
Comment: The vertices are ordered in that way so that $v_i$ has order $d_i$, I think.
Answer: In context "greedy coloring" must mean something like:

Assign colors to vertices starting with the ones with the highest degree and ending with the ones of low degree.
For each vertex, give it the lowest-numbered color that has not yet been assigned to any of its neighbors.

The nonincreasing degree order is not actually used in the prof -- without that condition, the proof would work equally well to prove:

If a graph $G$ has nodes of degree $d_1, d_2, \ldots, d_n$ then $\chi(G)\le 1+\max_i \min(d_i,i-1)$.

The point of arranging the vertices with higher degree first is that this gives the best opportunity for $\max_i\min(d_i,i-1)$ to be a small number, and therefore gives a stronger bound on the chromatic number.
The key is the $\min(d_i, i-1)$. You want to prevent this from becoming large -- that is, you want to avoid any vertex where $d_i$ and $i-1$ are both large numbers. The simplest way to do that is to make sure that vertices with a large $d_i$ have as small an $i$ as you can give them -- that is, vertices with high degree should come first in the list.


Localize views menus links

Question: I need a way to localize menu Items pointing to Views in a menu that has field translation.
I cannot create them neither from views nor manually (weird access denied messages).
EDIT: Here comes the original post. The title was "Translate the main menu with preserving English in case the translation is missing". I learned a thing or two in the process ;-)
I think I am doing something basically wrong...
I have set up a basic multilingual site with fields (entity) translation. Now, all works fine up to the menus. If I translate the menus, however, only the menu links that have actually been translated show up in the other languages. What's more, the menu structure does in other languages does not preserve the weights of the particular links.
What I'd like is to happen is:

English (or other provided) menu link show up when no translation is available.
The translated links preserve the weights.

Settings the menu links to "language neutral" solved the issue to a point. I cannot apply this practice, however, to views. Menu Items from views have English by default. What's more, when I remove the menu item in Views menu and try to make a  menu item that points to it by path, I get:

You are not authorized to access this page.

Any ideas?
Answer: You should set in the content type translation settings, to show no fallback language, and set all english nodes to English, rather than Language neutral (if they are such).
Comment: I had more success, to the contrary, putting the links as Language Neutral. The problem, though, is that I get an error message saying I do not have Admin permissions.
Comment: f you wanted to actually show a link for any language, then yes. If you wanted to hide it for other languages, then set it to langauge-specific.
Answer: So, my problem was: How to localize menu links created by views?
In fact, I could neither create links by views *nor add menus links that point to those views manually (I got access denied messages).
Eventually I used the Menu Tokens module with paths like <code>[site-url]\xxx</code>. This worked.

Localize views menus links


Pullback of a Volume Form

Question: Suppose we have a a diffeomorphism between two manifolds, $f: M \rightarrow N$ and a volume form $\Omega$ on $N$. Then is it true that $f^{*}(\Omega) = \Upsilon$ will always be a volume form on $M$?
My thinking is that for any arbitrary vector fields $(X_1, X_2,...,X_N) \in T_pM$ then
$\Upsilon(X_1, X_2,..., X_N) = f^{*}\Omega(X_1, X_2,..., X_N) = \Omega(df_x(X_1),df_x(X_2),...df_x(X_N))$
is always non vanishing given that $\Omega$ is a volume form on $N$? This would be because $\Omega$ is acting on the tangent vectors $df_x(X_i) \in T_{f(p)}N$, which is non-vanishing given that $\Omega$ is a volume form on N.
I'm new to differential geometry, so any mistakes with notation, or comments which aren't accurate, please do let me know!
Answer: Your agrument is basically coorect, the only observation you have not put in explicitly that that for a basis $\{X_i\}$ of $T_pM$ the vectors $df_x(X_i)$ form a basis of $T_{f(p)}N$, which is needed to conclude that the value of $\Omega$ on these tangent vectors is non-zero.
Comment: What you need is that $f$ is a local diffeomorphism around $x$, but this is not the main point. What is missing in your describption is that you have to start with linearly independent tangent vectors (or vector fields whose values in $p$ are linearly independent) since this is needed for the volume form to have a non-zero value.
Comment: Thank you for the answer. I'm wondering what conditions on $f$ are required so that a basis {$X_{i}$} of $T_{p}M$ implies {$df_{x}(X_{i})$} forms a basis for $T_{f(p)}M$? Is there a weaker condition than $f$ having to be a diffeomorphism?

Pullback of a Volume Form