É possivel usar Controladores hierarquicamente no Angular JS?

Question: Os Controladores são declarados no DOM via atributo ng-controller. A minha dúvida é: É possivel e robusto / seguro definir Controladores hierarquicamente no DOM em tags filhas ?
Exemplo:

    Fazer algo que usa o escopo do CtrlAbrangente e/ou do CtrlNoDIVFilhoDeAbrangente.

Vejo esta necessidade nos casos em que funcionalidade numa página podem ser reusadas em outras (mais Abrangente).
Comment: Sim, é possível e seguro.
Answer: Sim, é possível e comumente usado.
Um cenário seria de você ter uma página de contato com um controlador ContactCtrl e dentro desta página você possuir um formulário de contato com o controlador ContactFormCtrl onde você faria as validações e afins.
Você também poderia usar o ContactFormCtrl em um outro lugar, um formulário de contato no rodapé por exemplo, isso dependendo da sua aplicação, claro.
Espero ter ajudado
Answer: Não sei quanto as versões anteriores mas testei na versão 1.2.19 do Angular e funcionou sem problemas.
Veja código abaixo:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <title>AngularJS Dois Controladores Posicionados Hierárquicamente</title>

      Show

      Hide

      Do stuff that uses subACtrl or subCCtrl

      {{ aStuff }}

      {{ myEchoData}}

      {{ cStuff }}

      Do stuff that uses subBCtrl  or subCCtrl

      {{ bStuff }}

      {{ myEchoData}}

      {{ cStuff }}

        If click on 'Hide', to hide below box:

          <input type="text" ng-model="myEchoData"/>

Answer: Sim, é possível (e desejável em várias situações - por exemplo, em conteúdos Lista/Detalhe.) No código a seguir você pode verificar que o conteúdo de $scope é compartilhado hierarquicamente:

    var app = angular.module('app', []);

    app.controller('primeiroController', function($scope) {
      $scope.ValorPai = 0;

      $scope.funcaoPai = function() {
        alert('função Pai');
      };
    });

    app.controller('segundoController', function($scope) {
      $scope.ValorFilho = 0;
    });

            Controle Pai

                valorPai:
            <input type="text" ng-model="valorPai">

                Controle Filho

                valorPai:
                <input type="text" ng-model="valorPai">

                valorFilho:
                <input type="text" ng-model="valorFilho">

                Chamar função no Pai a partir do Filho

                <button ng-click='funcaoPai()'>Chamar</button>


The Boolean-valued model $V^B$ is extensional.

Question: I am currently studying forcing from Jechs Set Theory and i have encountered this seemingly innocent lemma which says:$\\$

Lemma 14.17. $V^B$ is extensional.
  Proof. Let $X,Y \in V^B$. By definition of $a \Rightarrow b$ we observe that if $a \le a'$, then $(a' \Rightarrow b) \le (a \Rightarrow b)$.
  Thus for any $u \in V^B$ we have $(\|u \in X\| \Rightarrow \|u \in Y\|) \le (X(u) \Rightarrow \|u \in Y\|)$ and therefore:
  $\hspace{2cm} \prod\limits_{u \in V^B}(\|u \in X\| \Rightarrow \|u \in Y\|) \le \prod\limits_{u \in V^B}(X(u) \Rightarrow \|u \in Y\|)$
  While the left-hand side is equal to $\|\forall u(u \in X \rightarrow u \in Y)\|$, the right-hand side is easily seen to equal $\|X \subset Y\|$. Consequently,
  $\hspace{2cm} \|\forall u(u \in X \leftrightarrow u \in Y)\| \le \|X = Y\|\hspace{7.7cm}\Box$
  What confuses me here is the fact that $dom(X)$ can't be all of $V^B$ since there exists some $\alpha$ such that $X \in V^B_{\alpha + 1}$ and $dom(X) \subset V^B_\alpha$. So how do we evaluate $X(u)$ for $u \not\in dom(X)$? Do we substitute with $0$? How is the proof in the book valid?
  Thanks, for your patience.
Comment: The same thing happens in the next lemma and we use $a_u(t)$ but in that lemma t can be outside of $dom(a_u)$ too.
Answer: Your guess is correct: $X(u)$ should be interpreted as $0$ if $u$ is not in the domain of $X$.  This makes sense intuitively: if you think of $X(u)$ as representing a "truth value" to which $u$ is an element of $X$, then any $u$ not in the domain should be assigned a truth value of $0$.
With this correction, the proof then works, since $X(u)\Rightarrow \|u\in X\|=1$ when $u\not\in dom(X)$ and these terms do not affect the meet and so $$\prod\limits_{u \in V^B}(X(u) \Rightarrow \|u \in Y\|)=\prod\limits_{u \in dom(X)}(X(u) \Rightarrow \|u \in Y\|)=\|X\subset Y\|.$$
Comment: There is no difficulty whatsoever here.  Just read $X(u)$ everywhere as an abbreviation for "if $u\in dom(X)$, the unique $v$ such that $(u,v)\in X$, and otherwise $0$".
Comment: Well, writing it out fully in the language of set theory would be excruciatingly long.  But, $\prod\limits_{u \in V^B}(X(u) \Rightarrow \|u \in Y\|) = T$ means that $T\in B$, $T\leq v\Rightarrow\|u\in Y\|$ for all $(u,v)\in X$, $T\leq 0\Rightarrow \|u\in Y\|$ for all $u\not\in dom(X)$, and $T\geq b$ for all other $b$ with these same properties.
Comment: (It is not entirely trivial that such a $T$ must exist, but this follows from completeness of $B$, since the collection of elements of the form $X(u)\implies\|u\in Y\|$ is a subset of $B$, even if $u$ is allowed to range over a proper class.)
Comment: But something isn't still ok, we work in ZFC then looking at X(u) from a truth value perspective then it becomes a class function and our reasoning fails in ZFC since we don't have classes.
Comment: Now that i am thinking more about it i can't formalize this in first-order logic. Can you please write this out for me? (The expanded form of: $\prod\limits_{u \in V^B}(X(u) \Rightarrow \|u \in Y\|) = T$.)
Comment: (To be nitpickingly precise : it's a subset of $B$ because of the axiom scheme of comprehension : write it as the set of $b\in B$ such that $\exists u, b=...$)
Answer:
So how do we evaluate $X(u)$ for $u \not\in dom(X)$? Do we substitute with $0$?

In this proof (1) that's exactly what we do. It's a slight abuse of notation (which is very common in all of mathematics).
(1) I wouldn't be surprised if the same abuse of notation occurs in a situation where evaluating it as $0$ does not yield the desired result. Hence I don't claim generality.
Comment: @ShervinSorouri Sorry, I actually copied the wrong part of the equation. What I meant to write was: $\prod\limits_{u \in V^B}(\|u \in X\| \Rightarrow \|u \in Y\|) = \prod\limits_{u \in x}(\|u \in X\| \Rightarrow \|u \in Y\|)$ for some set $x$ (of size $\le B$).
Comment: How would we proceed if we didn't want to use this notation? How would we write our proof formally?
Comment: @ShervinSorouri You can add an extra step and prove that there is some set $x$ such that $\prod_{u \in V^B}(X(u) \Rightarrow \|u \in Y\|)= \prod_{u \in x}(X(u) \Rightarrow \|u \in Y\|)$ (this you can formalize without referring to classes by showing that the infimum can't get any lower (any counterexample to that would be a single element)). And then show that you can replace $V^B$ with $\mathrm{dom}(X)$ on the right hand side and verify that the inequality still holds true.
Comment: I understand what you're trying to say but the moment you write $\prod\limits_{V^B}(X(u) ....$ you are giving $X$ parameters that are out of its domain.
Comment: I think what Eric suggested should do the trick. Thanks!
Comment: @ShervinSorouri That's intentional. There are only $B$ many values for $(X(u) \implies \| u \in Y\|)$ hence any infimum or supremum taken over a proper class is actually equal to the infimum/supremum over a set of size $\le \mathrm{card}(B)$.
Comment: I know i was referring to the notation abuse. (:))
Answer: $X$ is a partial function, since it may not defined for every argument from $V^B$ and this is not explained well in Jech's book. For a partial function, all notions involving it are contingent on the function being defined. For example, for partial functions $f$ and $g$ we have that $f = g$ if for all $x$ we have that whenever $f(x)$ is defined and $f(x) = y$, then $g(x)$ is defined and $g(x) = y$ and vice versa.
Comment: See Chapter 2 of J. Gallier's *Discrethe Mathematics* (Springer Universitet, 2011) for more on partial functions.
Comment: Can you provide a reference for me to study please?
Comment: You shouldn't say that $X$ is a partial function defined on all of $V$ or $V^{B}$ (since this leads to other issues -- like quantifying over all $B$-names). Rather, you should say that $X$ will be regarded as a partial function whenever we talk about its values on elements not in the domain.
Comment: Indeed; I will update my answer to reflect this.


Prevent a user from changing extended properties

Question: Question:
By default a user can change their own extended properties. Is the following code appropriate to prevent a user changing their user extended properties attributes?:
<code>USE [CustomerAccessDatabase];
GO
DENY SELECT ON sys.extended_properties to [Customer_Access_Role];
GO
USE [master];
GO
DENY EXEC ON sys.sp_addextendedproperty to [public];
GO
DENY EXEC ON sys.sp_dropextendedproperty to [public];
GO
DENY EXEC ON sys.sp_updateextendedproperty to [public];
GO
</code>
Answer: I am reasonably confident that I have solved this problem and secured this sufficiently.
Denying select on sys.extended_properties is not an option, as this prevents selecting on all tables.
However, denying Exec on the system stored procedures is sufficient on its own. The user can see extended properties but cannot change them. Attempting to change extended properties via the front end of SSMS also fails since the back end calls the same system stored procedures.
Comment: If anyone has a way to deny extended property edits on a specific object (e.g. the User) then I will change my accepted answer.


LIME explanation confusion

Question: I am working in R creating a GBM model using H2O and trying to use LIME to look at some local explanations to get a feel for what the model is doing. It's a binary classifier and I'm specifying 8 for n_features to the LIME package. However, I keep running into situations where all or most the 8 features are showing as contradicting the highest probability class. The funny thing is the predicted probability of the class is in the 90's.
How would one interpret this? Is there a problem in the LIME package implementation?
Here are a couple of examples:
Comment: Can you please provide additional information and potentially some reproducible code? Please note that LIME makes the rather significant assumption that a linear model can use *in terms of explanatory value* on a local scale. If your model is highly non-linear (almost) all bets are off. To that extent if you fit a simple GLM are the GLM estimates and the GLM-LIME estimates reasonable? (They should coincide actually) Finally you do not mention what you `TRUE/FALSE` training ratio. That might be an issue too.
Comment: Is this why all the examples, tutorials and talks I see about LIME only use very simple data/models and really only talk about the examples from the paper? Is it not really usable in the real world?
Comment: @Dan I do not think that is the case but that being said, as it is a very new methodology and people have not been fully accustomed to it, expositions of it tend to be somewhat basic. Please provide some of the information I requested but as it stands your question is not providing all the information needed unfortunately.
Comment: I'm not sure I'm following you. If I look at Case 8 for example. The predicted class is FALSE with probability 0.945. I see that for this case the feature "visitTotalCost" is <= 24.6 and this fact contradicts a prediction of FALSE and would instead support a prediction of TRUE. So what is causing the probability of FALSE to be so high?
Comment: You introduced a new tag [lime], can you please add a tag wiki?
Comment: If you reverse those inequalities, which are standardized to be of the $\leq$ or $<$ type, what will happen to the direction / color of the bars?  Think about what this means for your idea that the features are contradicting the highest possibility class...
Answer: Drawing on jbowman's comment, if you look at the values for the predictors in the example cases do they satisfy the conditions on the left? For example, in Case 8, if visitTotalCount is actually >24.6 then it will be having a positive effect on the predicting on the model.
Comment: No, the value is <= 24.6 that is how the label is created, so it contradicts the prediction of FALSE. And the top 8 features as shown in the graph all contradict the prediction. That is what has be confused.

LIME explanation confusion


Error in validating Latitude and Longitude in php

Question: I am trying to validate latitude and longitude using a function.
This is the function I am using:
// Function to validate latitude
function isValidLatitude($latitude){
    if (preg_match("/^-?([1-8]?[1-9]|[1-9]0)\.{1}\d{1,6}$/", $latitude)) {
            return true;
    } else {
            return false;
    }
}

This is how I call it:
// Check for the "latitude":
if (!empty( $_POST['geolat'])) {
    if (isValidLatitude($_POST['geolat'])) {
        $_SESSION['geolat'] = $_POST['geolat'];
    } else {
        $error_alert[] = "Find your location correctly";
    }
} else {
    $error_alert[] = "You didn't find your locaiton on google map";
}

But its not working for me. It is always going to :
$error_alert[] = "Find your location correctly";

My $_POST array looks like this:
Array
(
    [rest_location] => Colombo
    [geolat] => 6.929677319820927
    [geolng] => 79.86519121166998
    [submitted] => TRUE
)
1

Can anybody tell me what is wrong with this?
Thank you.
Comment: Can you post what is going into `isValidLatitude`? In this case - `$_POST['geolat']`
Comment: I need to validate this `[geolat]` using above function.
Comment: @user3733831 Can you explain in plain words what is the latitude format? And how did you build your regexp.
Comment: @user4035, This latitude and longitude generating dynamically when user select a location. So then I need these data to store in Mysql. Before run INSERT I need to validate these data. Thats why I use above function.
Answer: Your post value -
[geolat] => 6.929677319820927

doesn't match up against the regex that you've used.(It allows for 1 to 6 digits after decimal point)
So you can either change you regex to this -
^-?([1-8]?[1-9]|[1-9]0)\.{1}\d{1,20}$
                                 ^^ Changed from 6 to 20

OR

Change your geolat value to round upto 6 digits after decimal-
$_POST['geolat']) = floor($_POST['geolat']) * 1000000)/1000000

Comment: Kamehameha, If I use second method, should `geolat` change to '6.929677' ?
Comment: @user3733831 Yep. It will be modified.
Comment: This is how I used it `  $geolat = floor(($_POST['geolat']) * 1000000)/1000000;

  if (isValidLatitude($geolat)) {
   $_SESSION['geolat'] = $_POST['geolat'];
  }`
Comment: But `latitude` store in session like this - `[geolat] => 6.928484466599483`. its not modified.
Comment: @user3733831 That should work. But it defeats the purpose of validating. You are pasting the orignal into the session. It needs to be `$_SESSION['geolat'] = $geolat;` inside the if, when you are using the second method
Comment: You are correct. sorry its my mistake. Thank for your help.
Comment: One question. When I use modified version to latitude and longitude, will it a problem when I set the location with this modified data?
Comment: @user3733831 I have no idea. It depends on your application. Try both and see for yourselves :). I would rather go for the simpler first solution
Comment: But keep in mind that the second option (though I also prefer simpler approaches) does not test for $_POST['geolat']==='x'. This would result in latitude=0 instead of an error.
Answer: Change your Function to something like below:
function isValidLatitude($latitude){
    if (preg_match("/^-?([1-8]?[1-9]|[1-9]0)\.{1}\d+$/", $latitude)) {
            return true;
    } else {
            return false;
    }
}

ie, {1,6} means only 1 to 6 numbers allowed + means 1 or any number of  numbers allowed
Answer: function isValidLatitude($latitude){
    if (preg_match("/^[-]?(([0-8]?[0-9])\.(\d+))|(90(\.0+)?);[-]?((((1[0-7][0-9])|([0-9]?[0-9]))\.(\d+))|180(\.0+)?)$/", $latitude)) {
            return true;
    } else {
            return false;
    }
}


How to create a url/link preview?

Question: I'm managing a content sharing site built on drupal 7 and I would like to let users submit links as content.
Is there a simple way of creating a thumbnail / preview of the link (like on facebook)?
Answer: I think Opengraph Filter is a better solution than Facebook-Style Micropublisher since FBSMP relies on Statuses module and both modules are not very stable yet and also they serve for a more specific purpose. Opengraph Filter does only that what you need.
Comment: Looks like this is a better solution.
Comment: True, and has been proved before http://drupal.stackexchange.com/questions/50615/link-format-as-a-preview
Answer: This module might help
Facebook-style Micropublisher

This module lets users publish content (links, images, videos and
  documents) in a stream
Features

Attaches content using AHAH which keeps everything smooth.
Ability to re-share/re-post attachments (links, images, etc).
API to allow users to share content (URL) from other sites on your website (similar to Google Bookmarks, Digg, Reddit links). More...
Publish links, photos, videos, documents (ppt, doc, pptx, odt, etc)    out of the box.
Extensible to publish any kind of content.
Integration with Activity 2, Twitter, Rules, Heartbeat,    Triggers/Actions, Input Filters, Views, ImageCache, Token,
  Application Toolbar(Appbar), Emvideo, Emaudio, Userpoints (through
  Rules), SlideShare.net API and more.
Extensive developer API (including hooks) and theming methods.    More...
Comment: Do you think this module is what was asked for and will serve the purpose?..As far as I know, this module is meant for attaching contents to FBSS and has a dependency on it. And here the question poster wants to have similar functionality for field added to content type. Though maybe the code fbsmp uses can be used.:)

How to create a url/link preview?


Apache reverse proxy forwarding different source IP ranges to different destination URLs

Question: There's probably an existing question (or guide somewhere on the web) about this, but I couldn't find it.
We want to slowly migrate our user base from one implementation of the back end server to a new implementation on different servers.
There's already an Apache2 reverse proxy in front of the back end server.
So we'd like to proxy  some source IP ranges/subnets to the new server, leaving all others redirecting to the original server. Then add to the IP ranges that proxy to the new server until they all do. Then remove the old server.
Can someone give me some pointers to how this is done in Apache?
Answer: For me an approach would be something like this:
<code># /etc/httpd/conf/httpd.conf
<snip>
<If "-R '10.1.0.0/16'">
  ProxyPassReverse /app /http://new-app/app
</If>
<ElseIf "-R '192.168.1.0/24'">
  ProxyPassReverse /app /http://new-app/app
</ElseIf>
<Else>
  ProxyPassReverse /app /http://old-app/app
</Else>
</code>
From the apache manual
Comment: This will only work from apache 2.4 onwards, as older apache versions do not support `If` statements.
Answer: You could do this using mod_rewrite for proxying. You will have to setup a rewrite condition based on the source IP and a rewrite rule with the [P] flag. Something like this should work:
<code>RewriteCond %{REMOTE_ADDR} ^10\.2\.
RewriteRule ^/(.*) http://old-app/$1 [P]
ProxyPassReverse / http://old-app/

RewriteCond %{REMOTE_ADDR} ^10\.3\.
RewriteRule ^/(.*) http://new-app/$1 [P]
ProxyPassReverse / http://new-app/
</code>
Check http://httpd.apache.org/docs/2.2/rewrite/proxy.html for more information.
Comment: I also have to `RewriteEngine On`.


Using mongoose findById() over more than one field?

Question: I have a model looks like this
var mongoose = require('mongoose');
var tableSchema = new mongoose.Schema({
    version: { type: String, uppercase: true , required: true, trim: true },
    name: { type: String, uppercase: true , required: true, trim: true },
    descr: String
});
uctableSchema.index({ version: 1, name: 1 }, { unique: true });
module.exports = mongoose.model('Table', tableSchema);

This model will generate a collection like this
> db.tables.findOne()
{
        "_id" : ObjectId("56fc97d6e81ed6faf5e75b58"),
        "version" : "4",
        "name" : "address",
        "descr" : "contact address table"
}

That's all fine. I intentionally to leave mongoose to generate auto _id.
And I create a unique composite index to serve as primary key.
The data is actually imported from RDBMS via json file. So mongoimport will auto-generate _id for it. And that is fine.
The _id value does not have real meaning and I would like to retrieve, modify, and delete data by the composite primary key.
In my case, can I still use findById?
Model.findById(id, [projection], [options], [callback])
Model.findByIdAndUpdate(id, [update], [options], [callback])
Model.findByIdAndRemove(id, [options], [callback])

I understand that the first parameter id refers to _id that I don't want to use.
Is there a work around to make id parameter to refer to my composite key, version and name? Or I shouldn't use findById at all in my case?
Thanks,
Answer: Nope, the xxxById methods are all designed to work with _id only.
For example, here's the source for findById:
Model.findById = function findById(id, projection, options, callback) {
  if (typeof id === 'undefined') {
    id = null;
  }
  return this.findOne({_id: id}, projection, options, callback);
};

You'll need to use the more general findOne, findOneAndUpdate, and findOneAndRemove methods.


Access a template variable from another template (or theme hook)

Question: I have two templates (and two corresponding preprocess hooks), one rendering a Paragraph, one rendering items from this paragraph.
How to access a variable available in the parent paragraph template (or preprocess Hook) from the items rendering template (or item preprocess hook) ?
paragraph--paragraph-row.html.twig
{{ content.MyVARIABLE }}  //it works

field--paragraph--paragraph-row2.html.twig

  {% for item in items %}

         {{ item }}

{% endfor %}

THANKS !
David
Comment: `parent.` is a bit confusing here, for a field the parent is the entity the field is placed in, possible a paragraph for nested paragraphs, but can be any entity. Or do you mean the paragraphs stored in the field, more like children then?
Comment: "parent" means I want to access the paragraph the field is nested in.
Answer: You can't access easily variables from other templates. But you can use the entity objects to access field values.
For a nested paragraph you find the parent paragraph in element['#object']:
field--paragraph.html.twig
{{ element['#object'].field_my_field.value }}

Comment: This is a really important information. Where can it be found in the documentation?


Expanding the HTML view

Question: I am new to Drupal and am having trouble getting my custom HTML to take up most of the page. As you can see below, it is confined to the center and takes up a tiny percentage of the screen.
Here is the image of my module:

Thanks for all the help!
Answer: First of all, you should't use a Drupal default theme. As when you update Drupal core, you're going to overwrite all your theme files. So if you want to use a default Drupal theme you need to create a sub theme, if you haven't already. Follow this tutorial Creating A Drupal 7 Sub Theme.
Secondly, it looks small because you have items in your left column.
Thus, you need to remove the left column blocks. Go to /admin/structure/block and disable those blocks. OR Edit those blocks and in the Show block on specific pages you can control on which pages you want them to show up or be excluded from.
If that still doesn't do it, you need to edit your theme files. Go to /sites/all/themes/YOURTHEME/ folder and edit the page.tpl.php file and get rid off the left column.
Even after doing this, if you still want it bigger, then right mouse click on the page and select inspect element. Find the name of the div class or id that is controlling your output.
example

then on your css you put
#hello { width: 5000px; } if its and ID
.cool { width: 5000px; } if its class
If it has both, pick whichever you want
BTW: Your themes css file is located in the sites/all/themes/YOURTHEME/css folder.
Finally, after you make changes always remember to clear/empty your cache
Answer: Here are a few contributed (+ free of charge) themes you may want to look at (assuming your using Drupal version 7):

Zen.
Omega.
Bootstrap.
Zeropoint.

Actually there are hundreds of great themes.
When cherry picking from this list, you may want to use criteria such as responsive, fluid (that appears to be one of the issues you're struggling with), base theme, etc ...

Expanding the HTML view


Complex limit proving

Question: For complex number $z$, how to prove the limit exits by definition
$$\lim_{z\to 0} \frac{\sin z}{z} =1$$
By def I've tried, but I got a difference always greater than 1..
Comment: @Dietrich Burde: None of these related questions address the case where $z$ is taken to be a complex number.
Comment: @J.J. OK, sorry. I thought the arguments would also work for complex numbers, and that this is a duplicate.
Answer: L'Hopital's rule is a local statement; it concerns the behavior of functions near a particular point. The global issues (multivaluedness, branch cuts) are irrelevant.
$$\lim_{x \to 0} \frac{\sin(x)}{x} \stackrel{\text{de l'hopital}}{=} \lim_{x \to 0} \frac{cos(x)}{1}=1$$
Comment: I just worry about, if the limit not exits, the L'hospital rule would not hold, thus, can we use it to prove the limit exist..?
Comment: I'm not sure, I'm inclined to No though. Sounds like circular logic to me.
Comment: ye... the derivative of $\sin x$ at $x=0$ require this limit exist, so, here we cannot use it to prove itself...

Complex limit proving


Asymptotic Expansion for heat operator $e^{-t\triangle}$

Question: I'm afraid the question below might turn out to be very stupid -
I just don't know how to make sense of two asymptotic expansions,
given the heat operator $e^{-t\triangle}$ with $\triangle$ a Laplace type operator on smooth functions over an n-dimensional manifold we have an asymptotic expansion of the kernel
\begin{equation}
\text{k}(e^{-t\triangle}) \backsim \sum_{j \geq 0} c_{\frac{-n - j}{2}} \,t^{\frac{-n - j}{2}}
\end{equation}
and we also have an asymptotic expansion for the trace,
\begin{equation}
\text{Tr}(e^{-t\triangle}) \backsim \sum_{j \geq 0} c_{\frac{-n - j}{2}} \,t^{\frac{-n - j}{2}}
\end{equation}
Now, where is the difference in these two expansions ?
I realize this question suggests I don't know enough about both the kernel and the definition of the trace - which is absolutely true. The problem though is I don't know how to find an answer since all sources I have go on a large detour on how to construct the heat kernel, and on general definitions and properties of trace structures on operator algebras. I am totally aware I need to eventually understand these concepts, what I hope for with this question is to get a first idea in order to proceed. If that's not possible I'd also appreciate a reference to literature that starts at a low level so that I can get an overview.
Hope this makes sense, thanks a lot for your help!
Answer: You just have to sort this a little bit. Let's assume we're talking about an closed Riemannian manifold $(M,g)$ with its Laplace-Beltrami-Operator $\Delta_g$. Then you have the heat kernel as fundamental solution of the heat equation:
$$ \mathcal{K} \in C^{\infty}(M \times M \times \mathbb{R}^+)$$
Note that the notation $e^{-t\Delta}$ sometimes refers to both,
the kernel itself and the heat operator, which is
defined as integral operator acting on functions $f \in C^{\infty}(M)$
via integration against the heat kernel:
$$e^{-t\Delta}: C^{\infty}(M) \rightarrow C^{\infty}(M)$$
$$e^{-t\Delta}(f)(x) := \int_M \mathcal{K}(t,x,y)f(y) \mathrm{dy}$$
The heat operator can be expanded to an operator on $L^2(M)$. This allows to consider the heat trace, defined as the $L^2-$trace of
the heat operator. For the heat trace, you have the identity:
$$\text{Tr}_{L^2}(e^{-t\Delta}) = \int_M \mathcal{K}(t,x,x) \mathrm{dx}$$
which relates your objects to each other. Now you're interested in asymptotic expansions for $t \downarrow 0$ for the heat kernel and for the heat trace.
$$ \mathcal{K}(x,x,t) \sim \sum\limits_{k=0}^{\infty} u(x,x) t^k $$
for some (very interesting) smooth maps $u(x,y)$ and the latter gives you the expansion for the trace of the heat operator by the above identity:
$$ \text{Tr}_{L^2}(e^{-t\Delta}) = \int_M \mathcal{K}(t,x,x) \mathrm{dx} \sim \int_M \sum\limits_{k=0}^{\infty} u(x,x) t^k $$
I hope this is still useful for you. A great book including this topic is The Laplacian on a Riemannian manifold by S.Rosenberg.
Answer: If you know the Hamiltonian of the system then
$$\text{tr}(\exp(-t \Delta)\sim \int \mathrm{d}q \int \mathrm{d}p \exp\left(-t\sum_{ab}p^{2}_{a}p^{2}_{b}-tV(q)\right)$$
The integral is taken over ALL the $p$'s and the $q$'s momenta and position of the particle.
If the operator is a Laplacian operator then
$$\text{tr}(\exp(-t \Delta)\sim \int \mathrm{d}q \int \mathrm{d}p \exp\left(-t\sum_{ab}p^{2}_{a}p^{2}_{b}g^{ab}(q)\right)$$
Here the metric $$\mathrm{d}s^{2}= \sum_{ab}g_{ab}\mathrm{d}x_{a}^{2}\mathrm{d}x_{b}^{2}$$


Which category of music theory would the topic of "which scales to play over which chords" fall into?

Question: For example, in blues it's common to play a minor pentatonic scale over a major chord, and in a lot of rock music it is common to play the corresponding major/minor pentatonic scale over a major/minor chord.
Would this fall into the boundaries of harmony?
Comment: "Inverse harmonisation"?
Answer:
Would this fall into the boundaries of harmony?

The answer is simple and it's yes.
There are many kinds of harmony. The blues harmony is different than the jazz which is different than the classical etc.


Como criar uma API RESTful com processamento e resposta assíncrona usando C# + Angular(v5+)

Question: Olá, estou trabalhando com C# e tenho o seguinte problema:
Imaginem que tenho uma rota para minha API api/estoque/inventario onde essa rota deverá fazer o cálculo do inventário de todo o estoque da aplicação e por demanda retornar o resultado. Pra montar essa rota da API, eu teria algo semelhante a isso:
namespace Api
{
  public class Estoque { ... }

  [Route("api/estoque/inventario")]
  [ApiController]
  public class EstoqueController: ControllerBase
  {
    [HttpGet]
    public async Task<IActionResult<ICollection<Estoque>>> GetInventario()
    {
      try
      {
        // pega os produtos
        // faz todas as regras de negócio (síncronas e assíncronas)
        // retorna o estoque com o inventário (como?)
      }
      catch(Exception ex)
      {
        throw;
      }
    }
  }

}

O problema é que, mesmo que eu tenha uma tarefa assíncrona na minha API, a resposta ao meu cliente não é assíncrona. No lado do Cliente, eu uso a biblioteca RxJS juntamente com o Angular e o serviço que faz as requisições para a API tem o retorno de um objeto observável, Assim:
export const API_URL = '...';

export interface IEstoque { ... }

@Injectable({
  providedIn: 'root',
})
export class EstoqueService {

  private baseUrl: string = "/api/estoque";

  constructor(public http: HttpClient) { }

  public getInventario(): Observable<IEstoque[]> {
    return this.http.get(`${API_URL}${this.baseUrl}/inventario`);
  }

}

Minha intenção é usar a lista de itens processados no estoque juntamente com o pipe AsyncPipe que existe no angular, que faz com que eu possa fazer um loop assíncrono com base no retorno do serviço, ficando assim:

  {{estoque | json}}

@Component({
  selector: 'estoque-list',
  templateUrl: 'estoque-list.component.html',
})
export class EstoqueList {

  public estoqueList: Observable<IEstoque[]>;

  constructor(public estoqueService: EstoqueService) {
    this.estoqueList = estoqueService.getInventario();
  }

}

O que eu preciso fazer para que minha rota api/estoque/inventario passe a enviar a lista de estoque de forma assíncrona e contínua ao meu frontend com base no processamento?
Comment: Nesse caso pra enviar dados continuos melhor usar websockets. Nao sei como faz em c#.
Comment: Uma coisa eu não entendi, quando você diz que o lado server precisa ser assincrono, por qual motivo?

Você descreveu que quer "fazer o cálculo do inventário de todo o estoque da aplicação e por demanda retornar o resultado", o que seria esse por demanda?

Você quer uma aplicação que fique escutando e conforme vão surgindo novos dados em estoque ele já vá exibindo nessa aplicação em tempo "real"?
Comment: A declaração da sua *api* está correta, agora precisa ver o restando do código dentro dela. Todas as chamadas em cadeia, em todas as camadas/projetos que você tiver uma chamada a partir da sua *api* devem retornar tasks `async`, e ser chamadas usando o `await`, ou não irão funcionar corretamente de forma assíncrona
Comment: Uai, não entendi sua dúvida, já não estão assíncronas as chamas no serviço e o método no C#?
Comment: Se vc souber um pouco de nodejs recomendo o https://socket.io/
Comment: Por mais que você faça um flush parcial e observando o stream da resposta, ainda assim o que você receberia seria um Json, incompleto e inválido. Se você deseja um broadcast em tempo real vai precisar mudar completamente a sua arquitetura.
Comment: O que estou precisando fazer é o que o Eduardo disse, como websockets, só que não faço idéia de como fazer isso em C#
Comment: Essa seria uma atualização em realtime Juliano. A apicação em si é uma aplicação de controle de logística e isso precisa ter uma gestão em realtime.
Comment: Sim Ricardo, eu tenho ciência disso, tanto que estou gerando uma Api e não uma camada de acesso direto a dados.
Comment: Mesmo que as chamadas estejam assíncronas no serviço, o retorno do conteúdo não é assíncrono, eu tenho que processar todos os dados antes de retornar. A intenção é que eu possa retornar aos poucos, creio que como o Eduardo disse com websockets
Comment: eu tenho costume de trabalhar com socket.io em NodeJS, o problema é que o pessoa da empresa onde trabalho não quer trocar de tecnologia, portanto sou obrigado a usar C# + ASPNETCore + Angular...
Comment: eu tava até vendo aqui sobre o Broadcast do Laravel, o que ele e o Socket.io faz é o que eu to procurando
Comment: Caso você queira trabalhar via websockets, pode utilizar signalr no .net e fazer a comunicação. asp.net/signalr. No angular ja tem bibliotecas de signalr tambem.
Comment: @porfavorexcluirconta quando digo que preciso enviar de forma assíncrona é porque não posso fazer tudo e depois mandar... Minha ideia é mandar sempre que tiver completado um item do estoque para que não trave a aplicação em ambos os lados
Comment: @RicardoPontual eu fazer isso não garante que o envio para o cliente será assíncrono, ou seja, por finalização de cálculo
Answer: Leandro, a assinatura da sua API está assíncrona. Isso quer dizer que nessa parte (assinatura do método) ela está correta. Mas vamos revisar algumas coisas aqui, que podem estar interferindo com o que você deseja.
1 - Todo o fluxo deve ser assíncrono.
Quando se trabalha de forma síncrona, tudo deve ser síncrono. Igualmente, quando se trabalha assíncrono, tudo deve ser assíncrono. Isso porque misturar os comportamentos traz resultados indesejados. Portanto, verifique se todo o código, o fluxo de obtenção de dados e todo o processamento também são assíncronos, não apenas a assinatura do seu método. PS: jogar tudo dentro de Task.Factory.StartNew não é um caminho...
2 - A palavra-chave async na sua API não torna o HTTP assíncrono.
Vale lembrar que o HTTP em si não é assíncrono. Ou seja, o seu cliente (JavaScript) vai sempre esperar pela resposta do servidor e mesmo que o seu método na API seja assíncrono, a sua interface não necessariamente será.
Usar async na assinatura do método está relacionado aos internos de requisição/resposta, alocação de threads de recepção de chamadas e I/O, e não a permitir que a sua interface seja mais responsiva. Basicamente, usar async deixa sua API mais leve e mais escalável, especialmente quando ela precisa "seguir" para tarefas mais lentas (como buscar dados num banco de dados).
Isso quer dizer que o cliente (JavaScript) vai, sim, esperar todo o processamento ocorrer e finalmente receber a resposta. A diferença é que enquanto o cliente espera, a thread de I/O que ficaria travada esperando a resposta (e essa thread pertence a um grupo com quantidade finita) não vai ficar travada e poderá ser usada para outras requisições (mais rápidas, por exemplo). Mas o cliente permanecerá aguardando até que todo o processamento esteja concluído e o resultado seja retornado pela sua API.
3 - Então como melhorar a experiência?
Existem vários métodos e não há uma resposta em definitivo porque cada cenário tem uma saída diferente. Em alguns casos, uma tela "loading" (indicando o carregamento) já basta. Em outros pode ser necessário usar SignalR ou SocketIO para enviar dados à medida que forem disponibilizados. Em outros cenários você pode criar uma tarefa de processamento e retornar uma espécie de ID que poderá consultar mais tarde (de tempos em tempos) para saber se já foi concluída. Tudo depende do que exatamente você quer, dos requisitos do projeto (e do cliente) e do tempo total de processamento esperado. Da mesma forma que é intolerável deixar um "loading..." travado por 4h para processar os dados, é irreal criar toda uma estrutura SignalR para uma tarefa que leva 1 segundo para ser processada.
Comment: eu estou acostumado a usar isso com socket.io no Laravel e também NodeJS mas não encontrei nenhum código "legível" e simples de entender para implementar esse recurso de forma aceitável e escalável...
Comment: @LeandroLuk Como o cliente depende de uma conexão aberta com o servidor para que comunicação em tempo real aconteça, de duas, uma: ou você criará um API-Gateway ou Proxy ou similar que será responsável por receber as conexões e realizar chamadas internas, ou o seu gateway/proxy/etc deverá compreender e promover um fixation de forma que as chamadas sejam sempre redirecionadas ao mesmo servidor em um farm.
Comment: eu pensei em prover isso usando Websocket's, onde eu implementaria o mesmo junto ao método HTTP HEAD, onde ele por si só serviria pra me dizer o os status do conteúdo... a idéia é fazer algo como o firebase faz...
Comment: Do lado do cliente está certo. Do lado do servidor, o Firebase está usando um gateway que redistribui as tarefas em vários nós de servidores replicados. Se você vai fazer o servidor "escalável" também, tem que pensar do lado dele também, não só do cliente da aplicação :)
Answer: Quando usamos Api, nós fazemos requisições, quando o método é async ele não mandará nada assíncrono para você como respostas ao usuário, e como trabalhamos com request em API, não possuiremos nada constante, para isso você deverá pesquisar sobre SocketI que fará isso melhor a sua necessidade, hoje em 2019 uma das novidades da Microsoft é o RazorComponent, que fará uma aplicação WEB usando o SignalR e tals assim você ficara realmente ligado ao seu BackEnd podendo fazer esse método assíncrono que precisa.


How can I use WPF menus and dialog boxes in F#?

Question: I've been trying to find an example of using XAML and F# - without C# - to set up traditional menus and dialog boxes. Everything I can find online either uses C# or it is old, before the most recent versions of F# and .NET. Can anyone suggest an example I can look at?  Thanks.
Comment: http://fsprojects.github.io/FsXaml/
Comment: you will need FsXAML and either FSharp.ViewModule or [Gjallarhorn](https://github.com/ReedCopsey/Gjallarhorn/tree/master/samples) to do  binding. The latter has a few samples.
Comment: As this is quite open ended, you should probably come by the [F# chatroom](http://chat.stackoverflow.com/rooms/51909/f) or even better [F# Slack](http://foundation.fsharp.org/join).
Comment: Thanks to both of you for responding.  I'll look where you suggest and try to figure it out.  If anyone else has any other ideas, please add them to this list.
Comment: I would love to use the chatroom, but I'm new here and I only have 19 rep points and I need 20 to post.
Answer: When you try to learn WPF, you come across many C# examples based on "good old" code behind rather than MVVM or MVC. The following explains how to quickly create an F# WPF code behind application. Using this, it becomes easier to experiment with all those examples.
Create an F# console application.
Change the Output type of the application to Windows Application.
Add FsXaml from NuGet.
Add these four source files, and arrange them in this order.
MainWindow.xaml
<Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="First Demo" Height="200" Width="300">
    <Canvas>
        <Button Name="btnTest" Content="Test" Canvas.Left="10" Canvas.Top="10" Height="28" Width="72"/>
    </Canvas>
</Window>

MainWindow.xaml.fs
namespace FirstDemo

type MainWindowXaml = FsXaml.XAML<"MainWindow.xaml">

type MainWindow() =
    inherit MainWindowXaml()

    let whenLoaded _ =
        ()

    let whenClosing _ =
        ()

    let whenClosed _ =
        ()

    let btnTestClick _ =
        this.Title <- "Yup, it works!"
        ()

    do
        this.Loaded.Add whenLoaded
        this.Closing.Add whenClosing
        this.Closed.Add whenClosed
        this.btnTest.Click.Add btnTestClick

App.xaml
<Application xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Application.Resources>
    </Application.Resources>
</Application>

App.xaml.fs
namespace FirstDemo

open System
open System.Windows

type App = FsXaml.XAML<"App.xaml">

module Main =

    [<STAThread; EntryPoint>]
    let main _ =
        let app = App()
        let mainWindow = new MainWindow()
        app.Run(mainWindow) // Returns application's exit code.

Delete the Program.fs file.
Change the Build Action to Resource for the two xaml files.
Add a reference to the .NET assembly UIAutomationTypes.
Compile and run.
You can't use the designer to add event handlers. Simply add them manually in the code behind.
StackOverflow is possibly not the best place to post complete demos like this one, especially if this spins off more questions along the same line. If there is another better place, e.g. a public repo for this kind of thing, please let me know.
Comment: I adde more material here: http://stackoverflow.com/documentation/f%23/9008/f-wpf-code-behind-application-with-fsxaml
Comment: And I added my solution in a Spirograph application here: http://stackoverflow.com/documentation/f%23/9145/using-f-wpf-fsxaml-a-menu-and-a-dialog-box#t=201702200527195231483
Comment: Bent, thank you, thank you, thank you!  It's my birthday today and your reply is the best present I got.  Your answer was simple, step-by-step, and it actually worked.  Now I have to learn from it and see if I can apply it to menus and dialog boxes in WPF.  Thanks again.
Comment: Thanks, Bob. If you need help with controls, how to add window icons, an application icon, and possibly other stuff, then just ask again. Most stuff is like C#, but the bits that are specific to F# can be really hard to google.
Comment: Oh, and - happy birthday, Bob!


How can I find the index of two integers that have the smallest difference from a series of integers?

Question: i've a problem that asks me to print the index of the integers whose difference is smallest. If the inputs are 5 and 10 12 13 15 10, I have to print 5 1. The problem is here. Below is my code:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main(){
    int n;
    int temp=1005,pos1=0,pos2=0;
    cin>>n;
    vector <int> vec;
    for(int i=0;i<n;i++){
        int in; cin>>in;
        vec.push_back(in);
    }
    for(int i=0;i<n;i++){
        for(int j=1;j<n;j++){
            if(i==j)break;
            int ans=abs(vec[i]-vec[j]);
            cout<<i+1<<"-"<<j+1<<" = "<<ans<<endl;
            if(ans<temp){
                temp=ans;
                pos1=i,pos2=j;
            }
        }
    }

    cout<<pos1+1<<" "<<pos2+1<<endl;
    return 0;
}

Comment: I think that you might've missed the part where it tells you that the soldiers are standing in a circle. Also, `i` gets updated every iteration, so I don't think you want to start `j` from 1.
Comment: what's the problem? ("it does not work" is not an answer))
Comment: it gives wrong output at times and doesnt get accepted. i dont understand where's the flaw here rn
Comment: Just as a side note: [Why is "using namespace std;" considered bad practice?](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice)
Comment: why not sort the vector and then do binary serche?
Comment: Your loop does not examine neighbouring elements. The first iteration compares the first element to all other elements. The second exits immediately. The third iteration compares the  second and third elements. The fourth compares the fourth element to the second and third. Work out an algorithm first. Draw numbers in a circle on paper and figure out what to do.
Answer: Here's my solution in C. Remember that you need only be concerned with neighboring elements and that the soldiers are organized in a circle. Also, I found it a bit weird that the solution is asking for indexes starting at 1 and not 0.
#include <stdio.h>

#define ABS(n) ((n) * (((n) > 0) - ((n) < 0)))

void solution(int n, int soldiers[static 2])
{
    int indexA  = 1,
        indexB  = 2,
        minDiff = ABS(soldiers[0] - soldiers[1]),
        heightDiff;

    for (int i = 1; i < n; i++)
    {
        if ((heightDiff = ABS(soldiers[i] - soldiers[(i + 1) % n])) < minDiff)
        {
            minDiff = heightDiff;
            indexA = i + 1;
            indexB = ((i + 1) % n) + 1;
        }
    }

    printf("%d %d\n", indexA, indexB);
}

int main()
{
    solution(5, (int[5]){10, 12, 13, 15, 10});
    //5 1
    solution(4, (int[4]){10, 20, 30, 40});
    //1 2

    return 0;
}

Answer: The soldiers stand in a circle and you are supposed to look at soldiers standing next to each other.
This means you don't need the j loop. You can simply compare vec[i] with vec[(i+1) % n].


Using log-linear models for presence/absence data in wildlife

Question: I'm working on a project wherein I compare the presence/absence of a number of bird and herptile species between wetlands that have received three different treatments.  The populations were surveyed across two different years.  So the response variable is a binary categorical variable, and the predictor variables (wetland treatment and year of sampling) are also categorical.
The situation gets a bit more complicated in that different sampling schedules were used between the two years, resulting in different sample sizes between the two years.  I'm looking at modeling animal presence/absence using the glm() function in R, but I'm not sure if there might be a more appropriate approach?
Answer: You can use the binomial GLM, as it provides the freedom to model different sample sizes, $m_i$. So, you can use glm() function as follows:
<code>glm(cbind(presence, absence) ~ 1 + treatment + year, family=binomial)
</code>
where "presence" and "absence" show the number of present or absent cases.
Answer: I highly recommend you the R book, chapters 15 till 17.
If you have just categorical variables and no continuous ones, Crawley' R Book suggests to make a contingency table or to convert your binary data in proportion data and analyze it then.
I had the same problem (binary count data and just categorical explanatory variables) and made a binomial GLM and later a GLM with proportion data of counts. Both worked fine, outcome was the same.
Comment: This is fine, but just so you know, if you analyze your presence/absence data as a chi-squared, you will be using a *score* test, whereas the tests that come by default w/ a logistic regression are *Wald* tests. For more see [here](http://stats.stackexchange.com/a/144608/7290).


how to debug mysql has gone?

Question: I have a virtual machine(Ubuntu 12.04, MySQL 5.5) running under VMware and is dedicated to host a mysql server. I connect to this server on internal IP.
I'm trying to find out why I get mysql server has gone error. One my windows machines apache it stops because of this issue. I have been trying to fine tune my mysql my.cnf with the following parameters but did not bring the desired result.
# Instead of skip-networking the default is now to listen only on
# localhost which is more compatible and is not less secure.
 bind-address           = 0.0.0.0
#
# * Fine Tuning
#
wait_timeout = 180
key_buffer              = 384M
max_allowed_packet      = 64M
thread_stack            = 192K
thread_cache_size       = 8
# This replaces the startup script and checks MyISAM tables if needed
# the first time they are touched
myisam-recover         = BACKUP
max_connections        = 500
table_cache            = 64
#thread_concurrency     = 10
#
# * Query Cache Configuration
#
query_cache_limit       = 1M
query_cache_size        = 32M

how to debug this issue what is missing from configuration to avoid this error?
Answer: this is a very generic, annoying error.
you can try to up your timeouts on the mysql server side (not only wait-timeout, but connect-timeout as well).... how long are your queries running when you run them manually on mysql shell? longer than your timeouts? thats a problem.
it could be on the application side, such as, if you are using php, if the code hits max_execution_time [sic], then you may see this error.
also, the mysql variable, max_packet [sic], will cause this error, and commonly occurs on importing mysqldumps.
lastly, if you have iptables rate limiting for tcp/3306 (or whatever mysql is listening on), you may see this as a result of dropped packets.
in short, try upping all limits/timeouts, both and mysql side and application side, one at a time, and repeat until fixed.

how to debug mysql has gone?


How to make secure route in Laravel 5.2?

Question: I have a application with Laravel 5.2. I have some route. Now i want to make few routes secure so that anyone can not guessing and insert any value.Now i want to add some character before {id} and after {id} So that anyone can't reach it by guessing.
Route::get('/prize/{id}','PrizeCalculateController@showPrizePage');

Now user can go to localhost/laravel/public/prize/1 or replace 1 by anything and can go to that url. I want make it secure so that anyone can't go by guessing.
I have tried with:
$parameter = $qrcode->id;
$encryption= Crypt::encrypt($parameter);

What will be the best approach to make a route secure?
Comment: I think it's best to use `middleware`. Please see the docs! https://laravel.com/docs/5.2/middleware
Comment: @HirenGohel i have used `middleware` for users. But i want to make any user can't visit this url typing `../prize/12` etc `id`.
Answer: Encrypt the ID will generate a very long (188+ chatacters) string, not so friendly.
You can generate an UUID (32 characters) to represent your model. There's many packages that generates and validate UUID, for example this one.
To use the UUID, you should create a column on your table to represent it, and load the model by the uuid field instead of id.
Since the UUID represents a very large number (128 bits one), is very hard to guess it (virtually impossible, one chance in 3.402823669×10³⁸).
Also do difficult guessing (the probability increases as your table size increase), you can expire the UUID periodically (or invalidate it if used for example). There are many ways to secure it, but all depends on your application design.
Since you do not need the universally unique part of UUID, you can also just generate a big random string using str_random() helper from Laravel. A 16 alphanumeric characters string is also very strong (4.767240171×10²⁸ combinations).
Consider add a rate limiting to this route also make it very hard to guess.
Comment: I think `str_random()` will serve my purpose. Could you tell me how will i do that? I mean i will generate this string in controller then passes this into the url?
Answer: I use this lib to hash IDs: http://hashids.org/php/
Here's my wrapper for Laravel:
public static function staticHash($number, $obfuscate = false)
{
   $hashids = new \Hashids\Hashids(\Config::get('app.key'));

   return $hashids->encode($number);
}

public static function staticHashDecode($hash, $obfuscate = false)
{
   $hashids = new \Hashids\Hashids(\Config::get('app.key'));
   $number = $hashids->decode($hash);

   if (isset($number[0])) {
      $number = $number[0];
   } else {
      $number = false;
   }

   return $number;
}


How to calculate predicted hazard rates from a Cox PH model?

Question: I have the following Cox PH model:

(Time, Event) ~ X + Y + Z

I would like to get the predicted hazard rates (i am talking about hazard rates NOT hazard ratios) given specific values of X, Y, Z. I know the muhaz R package can calculate the observed hazard rates, but I am interested in the predicted model.
Is there a way to do this in R?
Comment: It seems that your "equation" models a binary outcome. Now, Cox's PH model deals with survival data and what lies it the left-hand side should be an hazard rate... I think you should clarify...
Comment: The Cox model does not estimate the baseline hazard function (usually indicated as $\lambda_0(t)$). To estimate the incidence rate from a model, you should use a parametric survival model instead.
Comment: There's some ambiguity in your question. The hazard function is a probability, not a rate. Is it the hazard function you want, or something else?
Answer: The function in the R survival package to get the baseline hazard rate is basehaz.
Then you need to multiply it for the various $e^{\beta}$ to get the specific hazard rate given the coefficients you have found.
A simple example may help:
library(survival) #survival analysis
library(eha) #used for data
data(oldmort) #create the data

# Create surv data set
mort <- Surv(time=oldmort$enter,time2=oldmort$exit,event=oldmort$event)

reg_fit <- coxph(formula=mort~oldmort$sex)
summary(reg_fit)

# Now get baseline curve
baseline <- basehaz(reg_fit)

# Draw baseline hazard (that's male)
plot(baseline$time, baseline$hazard, type='l',main="Hazard rates")

# Draw female hazard
lines(baseline$time, exp(-0.1929)*baseline$hazard, col="blue")

the $\exp(-0.1929)=0.8245$ is copied and pasted from the summary results of cox regression, summary(reg_fit), implying that the females in the data have hazard rates $18\%$ lower than the males.
Answer: The function basehaz (from the previous answer) provides the cumulative hazard, not the hazard function (the rate). I believe that question was about the hazard function. Estimating the hazard function would require specification of the type of smoothing (like in density estimation). The Muhaz R package can do this for one sample data. I am not aware of a function that can do this for the baseline hazard in the Cox model. I also need this. I think I will need to smooth the cumulative hazard on my own.


Group by clause using max(date) mysql

Question: Below is the structure of my table. I want the rows marked blue. My query isnt working even when using multiple group by.
<code>SELECT * FROM drug_refills WHERE drug_inventory_id = 1 GROUP BY drug_entity_id, start_date
</code>
for the blue ticks the date is max followed by drug_entity_id (group by)
Comment: If ONLY_FULL_GROUP_BY is disabled, a MySQL extension to the standard SQL use of GROUP BY permits the select list, HAVING condition, or ORDER BY list to refer to nonaggregated columns even if the columns are not functionally dependent on GROUP BY columns. This causes MySQL to accept the preceding query. In this case, the server is free to choose any value from each group, so unless they are the same, the values chosen are nondeterministic, which is probably not what you want. https://dev.mysql.com/doc/refman/5.7/en/group-by-handling.html
Answer: Using a correlated sub query to establish the last date
<code>    drop table if exists t;
    create table t(drug_refill_id int auto_increment primary key,drug_inventory_id int,drug_entity_id int,start_date date);

    insert into t (drug_inventory_id,drug_entity_id, start_date) values
    (1,1,'2018-01-01'),(1,3,'2018-01-02'),(2,4,'2018-01-01'),(1,5,'2018-01-01'),(1,5,'2018-02-01');

    select *
    from t
    where start_date = (select max(start_date) from t t1 where t1.drug_entity_id = t.drug_entity_id) and
            drug_inventory_id = 1;

+----------------+-------------------+----------------+------------+
| drug_refill_id | drug_inventory_id | drug_entity_id | start_date |
+----------------+-------------------+----------------+------------+
|              1 |                 1 |              1 | 2018-01-01 |
|              2 |                 1 |              3 | 2018-01-02 |
|              5 |                 1 |              5 | 2018-02-01 |
+----------------+-------------------+----------------+------------+
3 rows in set (0.00 sec)
</code>
BTW if you want answers to more closely resemble your data then include data as text in your question rather than images.

Group by clause using max(date) mysql


Sincronização de Thread em Java (sincronizar coleções)

Question: Tenho definido uma Thread em Java na qual pretendo simular aviões chegando e partindo do aeroporto, a classe Aviao contém apenas número e 10 passageiros
public class Aviao  {
    //numero de Aviao
    private int numeroAviao;
    //contém uma lista de passageiros
    private List<Passageiro> passageiros;

   public Aviao(int numero, int tamanho) {
            this.numeroAviao = numero;
            this.passageiros = new ArrayList<>(tamanho);
    }

    @Override
    public void adicionaPassageiro(Passageiro p) {
            this.passageiros.add(p);
    }
}

A classe Aeroporto:
public class Aeroporto {
    private List<Passageiro> passageirosNoAeroporto;
    private List<Aviao> avioes;
    private Map<Aviao, ThreadAviao> threadAviao;
    private final Object mutex;
    private boolean comecou;
    private final Relogio relogio;

public Aeroporto(int qtAviao) {
        this.mutex = new Object();
        this.comecou = false;
        this.passageirosNoAeroporto = new ArrayList<>();
        this.avioes = Collections.synchronizedList(new ArrayList<>());
        this.relogio = new Relogio();
        this.threadAviao = new HashMap<>();
        for (int j = 0; j < qtAviao; j++) {
            Aviao aviao = new Aviao(j + 1, 10);
            this.threadAviao.put(aviao, new ThreadAviao(this, aviao));
     }
}

Método adicionar avião no aeroporto:
public synchronized void AviaoChegou(Aviao aviao) throws InterruptedException {
        //adicionar aviao no aeroporto
        this.avioes.add(aviao);
        //usar uma lista sincronizada
        List list = Collections.synchronizedList(avioes);
        synchronized (list) {
            //iterar lista de avioes
            Iterator i = list.iterator();
            while (i.hasNext()) {
                aviao = (Aviao) i.next();
                // iterar a lista de passageiros
                Iterator<Passageiro> it = aviao.getPassageiros().iterator();
                  while (it.hasNext()) {
                     Passageiro p = it.next();
                     //adicionar os pasageiros no aeroporto
                     passageirosNoAeroporto.add(p);
                     //remove os passageiros do aviao
                     it.remove();
                }
            }
        }
    }

Método para avião partir quando estiver vazio
 public synchronized void AviaoPartiu(Aviao aviao) {
      //usar uma lista sincronizada
            List<Aviao> lista = Collections.synchronizedList(avioes);
            synchronized (lista) {
              //iterar a lista de avioes
                Iterator<aviao> i = lista.iterator();
                while (i.hasNext()) {
                    aviao = (Aviao) i.next();
                   //remove o aviao do aeroporto -> e da thread Aviao e Dá erro
                   //(Exception in thread
                   //"Thread-2" java.util.ConcurrentModificationException)
                    this.avioes.remove(aviao); //usar isto ou não?
                   //remove o aviao do aeroporto -> e não da thread Aviao?
                   i.remove();//usar isto o aviao
                  //faz a simulação outra vez até morrer
                }
            }
        }

e depois tenho a classe ThreadAviao
public class ThreadAviao extends Thread {

        private final Aviao aviao;
        private final Aeroporto aeroporto;

        public ThreadAviao(Aeroporto aeroporto, Aviao aviao) {
            this.aviao = aviao;
            this.aeroporto = aeroporto;
        }

        @Override
        public void run() {
            try {
                synchronized (mutex) {
                    while (!comecou) {
                        mutex.wait();
                    }
                List<Aviao> lista = new ArrayList<>();
                //adiciona o aviao a lista
                lista.add(aviao);
                //ordena os avioes
                Collections.sort(lista);
                //escolhe um aviao
                for (Aviao av : lista) {
                    //inicia a etapa
                    etapaAviao.executar(aeroporto, av);
                }
               }
            } catch (InterruptedException e) {
                // Não faz nada.
            }
        }
    }

Minha dúvida é que quando tenho 2 aviões criado em vez de cada um faz o seu processo, e quando um partir e é removido do da lista de aviões no aeroporto dá erro tal como mostra a imagem abaixo

e o meu objetivo é tentar sincronizar a Thread para que possa atingir o objetivo tal como mostra na figura em baixo?

acho que o problema mesmo é que não está excluindo o avião do
  aeroporto quando partiu com destino a outro país

Alguma sugestão?
Comment: o método AviaoPartiu vc está removendo todos os aviões?
Comment: @Skywalker, apenas estou removendo o aviao que chegou, alterei o metodo aviao partiu, o aviao que vai partir será igual ao aviao iterado da lista e apagado atraves  da operação  `this.avioes.remove(aviao); ` e depois a thread do outro aviao executa mas só que dá erro depois
Comment: @Skywalker, se no método aviaoPartiu eu estiver removendo todos os aviões, acho que a outra `thread` não iria executar como mostra na figura 1
Comment: Assim, não tinha visto aquele if de comparação,  experimente dar  `break;` após remover. Isso deve resolver.
Comment: Não sei se é necessário isso `i.remove();`
Comment: @Skywalker,  experimentei dar `break;` após remover o aviao em `this.avioes.remove(aviao);` e não deu erro mas não resolveu e continuou a executar  a etapa do mesmo aviao que acabou de partir
Comment: Ai ja é problema da lógica. Logo vo da mais uma analisada no seu código.
Comment: @Skywalker, obrigado
Comment: @Skywalker, acho que consegui resolver o problema do erro e na verdade em vez de usar o `this.avioes.remove(aviao);` o melhor mesmo é usar `i.remove();` quando estámos usar o iterador para eliminar um objeto numa lista,e não tinha que fazer nenhuma condição `if`, era necessario fazer `aviao = (Aviao) i.next();` e depois na execução da etapa e criar um `contador` para controla a etapa de cada thread que será executada apenas  vez e deu certo como mostra na figura em cima, apenas falta ordenar e visto que resolve a minha dúvida a solução está foi edita no codigo que já tinha sido colocado antes.
Comment: Olá Renata, bem vinda ao [pt.so]. Vi que resolveu o seu problema, legal! Só que a solução deveria estar como resposta, pois aqui funcionamos um pouco diferentes dos fóruns. Poderia separar a pergunta da resposta em publicações diferentes? Aproveite e faça um [tour] para conhecer um pouco melhor o funcionamento da nossa comunidade.
Comment: @Math, obrigada pela orientação
Answer: já consegui colocar a funcionar como esperado, eis a solução
a classe Aviao contém apenas número e 10 passageiros
public class Aviao implements Comparable<Aviao>  {
    //numero de Aviao
    private int numeroAviao;
    //contém uma lista de passageiros
    private List<Passageiro> passageiros;

   public Aviao(int numero, int tamanho) {
            this.numeroAviao = numero;
            this.passageiros = new ArrayList<>(tamanho);
    }

    public void adicionaPassageiro(Passageiro p) {
            this.passageiros.add(p);
    }

    public List<Passageiro> getPassageiros() {
            return this.passageiros;
    }

   public int getNumeroAviao() {
           return this.numeroAviao;
    }

   public int compareTo(Aviao novoAviao) {
            return this.numeroAviao - novoAviao.getNumeroAviao();
    }
}

A classe Aeroporto:
public class Aeroporto {
    private List<Passageiro> passageirosNoAeroporto;
    private List<Aviao> avioes;
    private Map<Aviao, ThreadAviao> threadAviao;
    private final Object mutex;
    private boolean comecou;
    private final Relogio relogio;

public Aeroporto(int qtAviao) {
        this.mutex = new Object();
        this.comecou = false;
        this.passageirosNoAeroporto = new ArrayList<>();
        this.avioes = new ArrayList<>();
        this.relogio = new Relogio();
        this.threadAviao = new HashMap<>();
        for (int j = 0; j < qtAviao; j++) {
            Aviao aviao = new Aviao(j + 1, 10);
            this.threadAviao.put(aviao, new ThreadAviao(this, aviao));
     }
}

Método adicionar avião no aeroporto:
public synchronized void AviaoChegou(Aviao aviao) throws InterruptedException {
        //adicionar aviao no aeroporto
        this.avioes.add(aviao);
        //usar uma lista sincronizada
        List<Aviao> lista = Collections.synchronizedList(avioes);
        synchronized (lista) {
            //iterar lista de avioes
            Iterator<Aviao> i = lista.iterator();
            while (i.hasNext()) {
                  // o aviao que chegou é igual ao aviao iterado
                  aviao = (Aviao) i.next();
                // iterar a lista de passageiros
                Iterator<Passageiro> it = aviao.getPassageiros().iterator();
                  while (it.hasNext()) {
                     Passageiro p = it.next();
                     //adicionar os pasageiros no aeroporto
                     passageirosNoAeroporto.add(p);
                     //remove os passageiros do aviao
                     it.remove();
                }
            }
        }
      }

Método para avião partir quando estiver vazio
 public synchronized void AviaoPartiu(Aviao aviao) {
      //usar uma lista sincronizada
            List<Aviao> lista = Collections.synchronizedList(avioes);
            synchronized (lista) {
              //iterar a lista de avioes
                Iterator<aviao> i = lista.iterator();
                while (i.hasNext()) {
                  //aviao que vai partir é igual ao aviao iterado
                  aviao = (Aviao) i.next();
                   //remove o aviao do aeroporto
                   i.remove();
            }
          }
        }

e depois tenho a classe ThreadAviao
    public class ThreadAviao extends Thread {

            private final Aviao aviao;
            private final Aeroporto aeroporto;

            public ThreadAviao(Aeroporto aeroporto, Aviao aviao) {
                this.aviao = aviao;
                this.aeroporto = aeroporto;
            }

            @Override
            public void run() {
                try {
                    synchronized (mutex) {
                        while (!comecou) {
                            mutex.wait();
                        }
                   //usar uma lista sincronizada
                    List<Aviao> lista = Collections.synchronizedList(new ArrayList<>());
                    //adiciona o aviao a lista
                    lista.add(this.aviao);
                    //escolhe um aviao
                    synchronized (lista) {
                    for (Aviao novoAviao : lista) {
                    System.out.println(" Aviao " + novoAviao.numeroAviao());
                      //inicia a etapa
                      etapaAviao.executar(this.aeroporto, novoAviao);
                        }
                    }
                } catch (InterruptedException e) {
                    // Não faz nada.
                }
            }
        }

método que executa a etapa do aviao
public void executar(Aeroporto aeroporto, Aviao aviao) {
         //contador
         int contador = 0;
        //por enquanto a cada aviao executar uma
        //etapa sai de executa a etapa de outro aviao
        while (contador != 1) {
            aeroporto.AviaoChegou(aviao);
            //aguardar um tempo
            aeroporto.getRelogio().esperar();
            //aviao partiu
            aeroporto.AviaoPartiu(aviao);
            //incrementa contador
            contador++;
        }
    }

eis a figura da simulação


Center of mass and moment of inertia of a $2$-dimensional donut?

Question: I have a an assignment and I'm stuck on this question:

First of all I can't figure out the equation for a $2$-dimensional donut as shown in the diagram. For the calculation of the center of mass, I have tried polar coordinates and took the limits of $r$ to be from $1$ to $2$ and $\theta$ from $0$ to $2\pi$. Is it right? What should I do? plz help!!
Answer: As far as I can understand, the question implies that:
For uniform areal density the center of gravity is at  center of inner circle.
Suggest a function for areal density such that the unbalanced mass center of gravity is forced out of the inner circle.
Try out some odd functions like:
$$ \rho (y) = a + b y , a > b , \rho(y) = c + d y^3, c>0, d>0. $$
EDIT1
$$  y \_{CofM}  = \frac{\int  y \, dx dy }{\int dx dy } = \frac{\int  r \sin \theta \,  r dr d\theta}{\int r dr d\theta }. $$
Can take forward?
Comment: which formula should I use for calculation of center of mass? and secondly why areal density has to be a function of y?


Projection valued measure: $E(A \cap B) = E(A) \cdot E(B)$ if disjoint

Question: Let $M \subseteq \mathbb{R}$. Define a projection valued measure as a function $E: \mathbb{B}(M) \rightarrow B(H)$ from the set of Borel sets of $M$ to the set of bounded linear operators on a Hilbert space $H$ s.t. for each $S \in \mathbb{B}(M)$ the operator $E(S)$ is an orthogonal projection. Furthermore for $S_1, S_2, \ldots \in \mathbb{B}(M)$ disjoint we have for each $x \in H: E(\cup_{n = 1}^{\infty} S_n) x = \sum_{n = 1}^{\infty} E(S) x$.
Now I want to show that for any disjoint sets $A, B \in \mathbb{B}(M)$ we have $E(A \cap B) = E(A) \cdot E(B)$.
I was able to show that if $A \subseteq B$ then $rg(A) \subseteq rg(B)$. Together with the fact that for orthogonal operators $S,T$ we have $rg(S) \subseteq rg(T) \Leftrightarrow ST = TS = S$ we get that
$$ E(A) \cdot E(A \cap B) = E(A \cap B), ~~~ E(B) \cdot E(A \cap B) = E(A \cap B)$$
Multiplying the two gives that $E(A) E(B) E(A \cap B) = E(A \cap B)$ which implies that $rg(E(A\cap B)) \subseteq rg(E(A) \cdot E(B))$.
If I can show the other inclusion then we are done, but I don't know how. I am almost certain that I am missing some easy argument.
Answer: Lemma 1.  If $E$ and $F$ are orthogonal projections and $E+F$ is also an orthogonal projection, then $EF=0$.
Proof. For every $x$ in the range of $F$ we have
$$
  \|x\|^2 =
  \|Fx\|^2 \leq
  \|Fx\|^2 + \|Ex\|^2 =
  \langle Fx, Fx\rangle  + \langle Ex, Ex\rangle  =
  \langle (F+E)x, x\rangle  \leq  \|x\|^2,
  $$
so equality holds throughout and in particular $Ex=0$.  This says that the range of $F$ is contained in the null space
of $E$, and hence $EF=0$.
Lemma 2.  If $A$ and $B$ are disjoint then $E(A)E(B)=0$.
Proof. $E(A)+E(B)=E(A\cup B)$ so the conclusion follows from Lemma 1.
Theorem.  If $A$ and $B$ are disjoint then $E(A)E(B)=E(A\cap B)$.
Proof.  In view of Lemma 2, it suffices to prove that $E(\emptyset)=0$, but this follows immediately from
$$
  E(\emptyset) =   E(\emptyset\cup \emptyset)  =   E(\emptyset)+E(\emptyset).
  $$
Theorem.  For all Borel sets  $A$ and $B$ whatsoever one has that $E(A)E(B)=E(A\cap B)$.
Proof. Letting $A'=A\setminus B$ and $B'=B\setminus A$ we have that $A$ is the disjoint union of $A'$ and $A\cap B$,
whence
$$
  E(A)= E(A')+ E(A\cap B),
  $$
and similarly  $E(B)= E(B')+ E(A\cap B)$.   Since any two of $A'$, $B'$, and $A\cap B$ are disjoint, we have that
$$
  E(A)E(B)= (E(A')+ E(A\cap B))(E(B')+ E(A\cap B)) = E(A\cap B)^2 = E(A\cap B).
  $$


Configure Squid to pass througt SSL traffic for specific hosts instead of intercepting it

Question: I'm currenty using squid on a pfSense box to intercept SSL which works well. The problem now is that WhatsApp Web will not work throught this proxy because it does not hold up to the Handshake proceedure as expected which causes squid to terminate this connection.
Is it possible to exclude specific targets from SSL interception in squid to prevent this problem?
Answer: What you are asking for is not possible. What you are apparently trying to achieve requires doing something else.
Because the interception is actually being done by the pfSense NAT system. Squid is just the process receiving the intercepted TCP connections and performing the TLS decryption parts.
To bypass interception you need to alter the pfSense NAT configuration. Once the packets reach Squid it is too late - the only option then are to proxy or terminate. However, detecting in advance whether any particular TCP SYN packet is going to turn into an HTTPS or WhatsApp connection is a problem. So bypassing the interception is usually not worth the trouble.
So what you actually have to do is to detect these in Squid during the SSL-Bump processing and tunnel (not bypass) the relevant traffic though the proxy.
Squid-3.5 can do that with the "ssl_bump splice" action if the traffic actually is TLS but not decryptable (use the TLS SNI and/or server certificate details to decide on splicing). If that is not sufficient, Squid-4 provides a http://www.squid-cache.org/Doc/config/on_unsupported_protocol/ feature for tunneling traffic that turns out to be non-TLS on port 443.
Comment: If you're able to determine the IPs whatsapp's connecting to, you may be able to alter the interception rules, as Amos implies - its a bit of a brutal solution, and may mean a lot of traffic's not ever seen by squid (particularly if whatsapp ends up being on shared infrastructure like AWS).
Answer: yes, totally doable and although it might not have been there 7 years ago, there's an example by now, to do exactly that:
<code>    # Example: Bump all TLS connections except those originating from
    # localhost or those going to example.com.

    acl broken_sites ssl::server_name .example.com
    ssl_bump splice localhost
    ssl_bump splice broken_sites
    ssl_bump bump all
</code>
http://squid-cache.org/Doc/config/ssl_bump/


regex for number between numbers

Question: I'm in need of a regex, which takes a minimum and a maximum number to determine valid input, And I want the maximum and minimum to be dynamic.
I have been trying to get this done using this link
https://stackoverflow.com/a/13473595/1866676
But couldn't get it to work. Can someone please let me know how to do this.

Let's say I want to make a html5 input box, and I Want it to only receive numbers from 100 to 1999
What would a regex for this like this look like?
Comment: Could you please update your question with 1) your sample input with expected behavior 2) what you exactly tried and how 3) and of course your programming language.
Comment: I suggest you have a look at [How do I write a regular expression that matches an IPv4](https://blogs.msdn.microsoft.com/oldnewthing/20060522-08/?p=31113/). It isn't an answer (or even a forum) but it's fun to read and highlights why you can do many things with regular expressions, but you shouldn't always do them. As about your question, if numbers are not fixed you clearly cannot write a static regular expression and if you can use a programming language to build the expression you can probably use that language to just compare numbers in a simpler way.
Comment: @WiktorStribiżew tried updated it as you requested
Comment: See http://www.regular-expressions.info/numericranges.html for example. It can be done, but it's probably not something you want to do. It would be better to extract the number from whatever string you are parsing and then check if it's within the specified range after.
Comment: @DaCh You wrote his name in your question, but didn't really supply any of the three points ;-)
Comment: @ÁlvaroGonzález it's true that some "native" comparing of number would be easy, but then i would need to the code for all my apps, where instead i could send the regex within the requested to my server,
Comment: @ÁlvaroGonzález I think i did, 1. your sample input with expected behavior =  And i Want it to only receive numbers from 100 to 1999. 2.I have been trying to get this done using this link http://stackoverflow.com/a/13473595/1866676 and 3. Let say i want to make a html5 input box. but if i misunderstod something, i will of curse try to change it.
Comment: @ÁlvaroGonzález Check my answer, it explains how to do it. It's not too difficult or impossible
Comment: @yosefh Check my link, it explains why not to do it (your answer assumes a fixed range anyway so my concerns remain the same).
Answer: First off, while it is possible to do this, I think if there is a simpler way to choose a number range such as <input type="number" min="1" max="100">, that way would be preferred.
Having said that, here's how the kind of regex you requested works:
ones: ^[0-9]$  // just set the numbers -- matches 0 to 9
tens: ^[1-3]?[0-9]$ //set max tens and max ones -- matches 0 to 39
tens where max does not end in 9 ^[1-2]?[0-9]$|^[3][0-4]$ // 0 to 34
only tens: ^[1][5-9]$|^[2-3][0-9]$|^[4][0-5]$ // 15 to 45

Here, lets pick an arbitrary number 1234 to 2345
^[1][2][3][4-9]$|
^[1][2][4-9][0-9]$|
^[1][3-9][0-9][0-9]$|
^[2][0-2][0-9][0-9]$|
^[2][3][0-3][0-9]$|
^[2][3][4][0-5]$

https://regex101.com/r/pP8rQ7/4
Basically the ending of the middle series always needs to be a straight range that can reach 9 unless we are dealing with the ones place, and if it cant, you have to build it upwards toward the middle each time we have a value that can't start in 0 and then once we reach a value that cant end in 9 break early and set it in the next condition.
Notice the pattern, as each place solidifies. Also keep in mind that when dealing with going from lower to higher places, optional operators ? should be used.
Its a bit complex, but its nowhere near impossible to design a custom range with a bit of thought.
If you are more specific, we can craft an exact example, but this is generally how it is done:beginning-range|middle-range|end-range
You should only need beginning or end-ranges in certain cases like if the min or max does not end in 9. the ? means that the range that comes after it is optional. (so for example in the first case it lets us have both single and double numbers.
so for 100 - 1999 it's quite simple actually because you have lots of 9's and 0's
/^[1-9][0-9][0-9]$|^[1][0-9][0-9][0-9]$/

https://regex101.com/r/pP8rQ7/1
Note: Single values don't need ranges [n] I just added them for readability.
Edit: There is a new regex range generator at: https://3widgets.com/
Comment: `Here, lets pick an arbitrary number 1234 to 2345` if in understand it. if i use that regex, i would be able to enter 2344? am i right?
Comment: ugh wait i made a mistake - fixing
Comment: You have my +1 for the information but this expression needs to be placed somewhere and it's in the larger picture where the whole approach starts flickering. If you put it in the `` attribute you've written a convoluted replacement for `max/min`. If you validate with JavaScript you've written a convoluted replacement for `<` and `>`. And so on.
Comment: @ÁlvaroGonzález I completely agree. This is more trivia and invention than anything else. I had fun coming with it :D
Comment: @ÁlvaroGonzález sry, but ain't you saying it may not be 2340 ?
Comment: @DaCh thanks for catching that - I updated the post - So yeah this is definitely more difficult than it needs to be :P
Comment: @ÁlvaroGonzález I'm sry, for a couple of seconds i mistake you guys from each other.
Comment: @yosefh Thanks a bunch, this was what i was looking for. thanks for this nice explained answer!
Comment: @DaCh You're very welcome, but just remember that is preferable to use simple > and < operators along with min and max numbers. such as if (x >= min and x  <= max)
Answer: Essentially, you can't.
For every numeric range, there exists a regex that will match numbers in that range, therefore it is possible to write code that can generate a such regex. But such a regex is not a simple reformatting of the range ends.
However, such code would require colossal effort and complexity to write compared to code that simply checked the number using numeric methods.
Comment: Not an expert on this subject, but since it is html5 he needs the regex to filter it. If not he would have to pass the values to another page to validate them? `^[1-9][0-9][0-9]$|^1[0-9][0-9][0-9]$` would catch it all?
Comment: @Andreas you are correct. I've developed a system for this. it's easier than one might think. Check out the answer below

Although it definitely might be overkill in some situations as Bohemian has suggested
Comment: Thanks for suggesting this. I've decided to change my approach rather than coming up with a regex.
Answer: With HTML 5 simply put a range input...
<form>
  Quantity (between 100 and 1999):
  <input type="number" name="quantity" min="100" max="1999">
</form>

with regex:
^([12345679])(\d)(\d)|^(1)(\d)(\d)(\d)

So if you need to create the regex dinamically it's possible but a bit tricky and complex
Comment: Out of curiosity... Can plain HTML actually enforce the restriction, or will merely style the element accordingly?
Comment: The value will be constrained but Note: The max and min attributes of the input tag is not supported in Internet Explorer 9 and earlier versions.--
Note: The max and min attributes will not work for dates and time in Internet Explorer 10 (and newer), or Firefox, since IE 10+ and Firefox does not support these input types.--Note: Anyone can fake client-side validation, so its always important to validate on the server also http://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_input_max_min
Comment: of course any input can be fake client-side, so you need a validation server side (javascript can be skipped with more difficoulty but skipped as normal input).

regex for number between numbers


Survival estimation when death/censoring is probabilistic

Question: I am trying to estimate survival function, but in case where each event is censoring with probability $p_i$. (That is, I am never sure if the event is right-censoring or death, but I can estimate the probability of each.)
Typical Kaplan-Meier works only for binary right-censoring. Is there any straightforward generalization?
Comment: @PiotrMigdal have you looked at using customer CLV to measure this? See a good intro in ""Counting Your Customers" the Easy Way:
An Alternative to the Pareto/NBD Model" by Fader et al. An implementation is available at https://github.com/CamDavidsonPilon/lifetimes
Comment: Out of interest, do you have an application in mind? I'm struggling to think of a situation where you would know $t_i$ but not whether the event is right censoring or death.
Comment: @tristan I am looking at user churn rate. But what I have are points in time (e.g. if transactions), rather than anything continuous. So I need to estimate, whether the time between the last interaction and end of measurement corresponds to a typical time between transactions, or did user resigned.
Comment: So how have you come up with the $p_i$ in this case? It sounds to me that all of the users are right-censored in fact.
Comment: @Cam.Davidson.Pilon Thanks! Yesterday I learnt about R [Buy 'Til You Die](http://cran.r-project.org/web/packages/BTYD/vignettes/BTYD-walkthrough.pdf), but I prefer Python (and I am already using [Lifelines](https://github.com/CamDavidsonPilon/lifelines)).
Answer: If we can assume that for each item/individual you have $ x_i $ (covariates), $ t_i $ (last observation) and $ p_i $ (probability of death rather than censoring), and that the $ p_i $ are conditionally independent given $ x_i $ and $ t_i $: I don't see a problem with a simple modification to the Kaplan-Meier product limit formula.
If the standard formula is:
$$
\hat S (t) = \prod_{t_i<t}{\frac{n_i-d_i}{n_i}}
$$
Where $ n_i $ is the number of individuals at risk at time $ t_i $ and $ d_i $ is the number dying at time $ t_i $.
Then you should be able to use
$$
\hat S (t) = \prod_{t_i <t}{\frac{n_i-\sum_{t_j=t_i}{p_j}}{n_i}}
$$
Where $ n_i $ is now the expected number of individuals at risk. (Note that I have actually used $ p_i $ as probability of death rather than censoring for notational convenience.)
For other analyses (e.g., Cox proportional hazards) you may find it more difficult to construct the likelihood function in a computationally convenient or tractable form. What you should be able to do if nothing else is sample $ D_i \sim Bernoulli (p_i) $ and perform your analyses multiple times in a Monte Carlo manner.

EDIT
I have now simulated this in R and I am happy with it. Briefly I created the following data generating process:
\begin{align}
T_{death} &\sim Weibull(\alpha_{death},\beta_{death}) \\
T_{cens}  &\sim Weibull(\alpha_{cens}, \beta_{cens} ) \\
T &= \min\{T_{death},T_{cens}\} \\
\lambda_{death}(t) &= \frac{\alpha_{death}}{\beta_{death}}\left(\frac{t}{\beta_{death}}\right)^{\alpha_{death}-1} \\
\lambda_{cens}(t) &= \frac{\alpha_{cens}}{\beta_{cens}}\left(\frac{t}{\beta_{cens}}\right)^{\alpha_{cens}-1} \\
p(t) &= \frac{\lambda_{death}(t)}{\lambda_{death}(t)+\lambda_{cens}(t)}
\end{align}
Using the estimator as I suggested above gives the following good match to the survival curve for $T_{death}$ (i.e., the censoring process has not interfered with estimation).

The code for it is:
<code>library(ggplot2)

# Data generating function parameters
a_death = 1.5
b_death = 10.0
a_cens = 1.0
b_cens = 7.5
n = 1000

# Generate data
t <- c(rweibull(n*mix_deathcens, a_death, b_death), rweibull(n*(1-mix_deathcens), a_cens, b_cens))
t_death <- rweibull(n, a_death, b_death)
t_cens  <- rweibull(n, a_cens,  b_cens )
t <- pmin(t_death, t_cens)
g <- (t_death < t_cens) * 1

# Assign probabilities based on hazard rates
hr_death <- (a_death/b_death) * (t/b_death)^(a_death-1)
hr_cens  <- (a_cens /b_cens ) * (t/b_cens )^(a_cens -1)
p <- hr_death/(hr_death+hr_cens)

# PRODUCT LIMIT
ord <- order(t)
df <- data.frame(t=t[ord], p=p[ord], S=rep(NA,n))
S_i <- 1
n_i <- n
for (i in 1:length(df$t)) {
  n_i <- n_i - (1 - df$p[i])
  df$S[i] <- S_i * (n_i - df$p[i])/n_i
  S_i <- df$S[i]
  n_i <- n_i - df$p[i]
}

# Calculate desired survival curve
df$S_death <- pweibull(df$t, a_death, b_death, lower.tail = FALSE)

# Plot
ggplot(df) + geom_step(aes(x = t, y = S)) + geom_line(aes(x = t, y = S_death)) + xlab("Time") + ylab("Survival")
</code>
Comment: It won't work that way. I mean, the tricky part with KM is that the product is only of death events, not censoring.
Comment: So in this case it's the product of all events. I have simulated a dataset and analysed it in R and I'm happy with the result - will add to my answer.
Comment: @PiotrMigdal I have updated my answer
Comment: Now I see it. I.e. the hazard function estimator should be just $-\log[(n_i - p_i)/n_i]$, giving this result.


Why is ROC AUC equivalent to the probability that two randomly-selected samples are correctly ranked?

Question: I found there are two ways to understand what AUC stands for but I couldn't get why these two interpretations are equivalent mathematically.
In the first interpretation, AUC is the area under the ROC curve. Picking points from 0 to 1 as threshold and calculate sensitivity and specificity accordingly. When we plot them against each other, we get ROC curve.
The second one is that the AUC of a classifier is equal to the probability that the classifier will rank a randomly chosen positive example higher than a randomly chosen negative example, i.e. P(score(x+)>score(x−)).
(from What does AUC stand for and what is it?)
Answer: It's easy to see once you obtained a closed-form formula for AUC.
Since we have finite number of samples $\{(x_i, y_i)\}_{i=1}^N$, we'll have finite number of points on the ROC curve. We do linear interpolation in between.
First, some definitions. Suppose we'd like to evaluate an algorithm $A(x)$ that outputs a probability of $x$ lying in the positive class $+1$. Let's define $N_+$ as the number of samples in the positive class $+1$ and $N_-$ as the number of samples in the negative class $-1$. Now, for a threshold $\tau$ let's define False-Positive-Rate (FPR, aka 1-specificity) and True-Positive-Rate (TPR, aka sensitivity):
$$
\text{TPR}(\tau) = \frac{\sum_{i=1}^N [y_i = +1] [A(x_i) \ge \tau]}{N_+}
\quad \text{and} \quad
\text{FPR}(\tau) = \frac{\sum_{i=1}^N [y_i = -1] [A(x_i) \ge \tau]}{N_-}
$$
(where $[\text{boolean expression}]$ is 1 if expression is true, and 0 otherwise). Then, ROC curve is built from points of the form $(\text{FPR}(\tau), \text{TPR}(\tau))$ for different values of $\tau$. Moreover, it's easy to see that if we order our samples $x_{(i)}$ (note the parentheses) according to the algorithm's output $A(x_i)$, then neither $\text{TPR}$ nor $\text{FPR}$ changes for $\tau$ between consecutive samples  $A(x_{(i)}) < \tau < A(x_{(i+1)})$. So it's enough to evaluate FPR and TPR only for $\tau \in \{A(x_{(1)}), \dots, A(x_{(N)})\}$. For $k^{\text{th}}$ point we have
$$
\text{TPR}_k = \frac{\sum_{i=k}^N [y_{(i)} = +1]}{N_+}
\quad \text{and} \quad
\text{FPR}_k = \frac{\sum_{i=k}^N [y_{(i)} = -1]}{N_-}
$$
(Note both sequences are non-increasing in $k$). These sequences define x and y coordinates of points on the ROC curve. Next, we linearly interpolate these points to get the curve itself and calculate area under the curve (Using a formula for area of a trapezoid):
$$
\begin{align*}
\text{AUC} &= \sum_{k=1}^{N-1} \frac{\text{TPR}_{k+1} + \text{TPR}_{k}}{2} (\text{FPR}_{k} - \text{FPR}_{k+1}) \\
 &= \sum_{k=1}^{N-1} \frac{\sum_{i=k+1}^N [y_{(i)} = +1] + \tfrac{1}{2} [y_{(k)} = +1]}{N_+} \frac{[y_{(k)} = -1]}{N_-} \\
 &= \frac{1}{N_+ N_-} \sum_{k=1}^{N-1} \sum_{i=k+1}^N [y_{(i)} = +1] [y_{(k)} = -1]
 = \frac{1}{N_+ N_-} \sum_{k < i} [y_{(k)} < y_{(i)}]
\end{align*}
$$
Here I used the fact that $[y = -1] [y = +1] = 0$ for any $y$.
So there you have it: AUC is proportional to the number of correctly ordered pairs, which is proportional to the probability of random pair of samples being ranked according to their labels.
EDIT (6 years later): Since for $a, b \in \{-1, +1\}$ we have $[a < b] = 1$ only when $a = -1$ and $b = +1$, it's easy to see that
$$
\frac{1}{N_+ N_-} \sum_{k < i} [y_{(k)} < y_{(i)}] = \frac{1}{N_+ N_-} \sum_{\substack{k < i \\ y_{(i)} = 1 \\ y_{(k)} = -1}} [y_{(k)} < y_{(i)}]
$$
In essence, we form all possible negative-positive pairs and see what fraction of them is correctly ordered according to our algorithm $A$, that is, $A($positive sample$)\; > A($negative sample$)$.
Comment: This is all covered in Hanley and McNeil 1982: https://pubs.rsna.org/doi/10.1148/radiology.143.1.7063747 (Wilcoxon-Mann-Whitney equivalence etc.).
Comment: Thanks @Barmaley.exe. This is really helpful. Finally connect the dots. A following up question though, is how AUC is equivalent to Mann Whitney U test.
Comment: I don't have an answer to that, but either way it'd not be a good idea to answer another (mostly unrelated) question here. I suggest you create a new thread.
Comment: Can you please clarify how did the numerator before the last step is rearranged? where did $1/2[y_(k) =  +1]$ go?
Comment: @christopher, $[y_{(k)} = +1] [y_{(k)} = -1]$ is always 0.
Comment: Hi @ArtemSobolev and thank you for your input. I did not yet carefully think about the derivation but one question though: Is the set $\{A(x_{(1)}), \dots, A(x_{(N)})\}$ enough? I mean when $\tau \in A(x_{(1)})$ everything is classified as positive and when $\tau \in A(x_{(N)})$ only the $(x_{(N)}, y_{(N)})$ sample is classified as positive. Should we still try another threshold like $A(x_{(N)})+c$ where $c$ is e.g. a very small number? Wouldn't this threshold be the case where everything is classified as negative? Wouldn't we now cover all the $(TPR(\tau), FPR(\tau))$ cases?
Comment: To add to the previous, would it be more correct to say instead of: "...it's enough to evaluate FPR and TPR only for $\tau \in \{A(x_{(1)}), \dots, A(x_{(N)})\}$..." that "...it's enough to evaluate FPR and TPR only for $\tau \in \{A(x_{(1)}), \dots, A(x_{(N)})\}$ which cover all the TPR,FPR cases except the one where all points are classified as negative."
Comment: This is a clear answer compared to the answers in the question linked here. But I wonder whether the last part $\sum_{(k < i)} [y_{(k)} < y_{(i)}]$ is really explains what we want here. Since $y_{(k)} < y_{(i)}$ for all $k < i$ based on our ordering. I think some conditioning needs to be there. Specifically $y_{(k)}$ has to be a true negative sample and $y_{(i)}$ has to be a true positive sample.
Comment: @user2939212, I think they are the same thing. Then $y_{(k)}=1$ then $y_{(k)} < y_{(i)}$ is always false, since both $1 < -1$ and $1 < 1$ is false. Same when $y_{(i)} = -1$. Hence the cases when $y_{(i)}$ is not a true positive or $y_{(k)}$ is not a true negative only contribute zeroes to the sum.
Comment: @user2939212, that said, having $N_+ N_-$ as normalizers indeed hints us that we should be enumerating a cartesian product of two sets, one of size $N_+$ and the other of size $N_-$, which is exactly what you're suggesting in the last sentence. I've added a paragraph on that.


Splitting 'unlimited' body fields

Question: I have set the 'Body field settings' > 'Number of values' to 'Unlimited'; so the user can add as many 'body' fields as they like.
I have then added the following piece of code to my themes 'node.tpl.php' file:
<?php $i=0;
while ($i<=10) : ?>

<?php print render($content['body'][$i]);
$i++; ?>

<?php endwhile; ?>

This code outputs each of the 'body' fields in a section/div and then adds a number of blank sections/divs until it hits 10!
How would I find out the total number of 'body' fields so that it only outputs the available number and not all 10? I was trying to use 'foreach' but couldn't seem to get it working.
Comment: `foreach` is the appropriate control structure to use in this instance. You should post the code that you used when attempting to use `foreach` and explain what the unintended result was, so that you can get help with executing the appropriate solution, rather than trying to hack around the real issue.
Answer: This issue was solved using a function in my template.php file to get the field data out of entities, which I found here.
/**
 * Returns field values as actual entities where possible,
 * also allows selection of individual items to be returned
 */
function field_fetch_field_values($entity_type, $entity, $field_name, $get_delta = NULL, $get_key = NULL) {
  $values = array();
  if (isset($entity->$field_name) && !empty($entity->$field_name)) {
    foreach (field_get_items($entity_type, $entity, $field_name) as $delta => $item) {
      $value = $item;
      $keys = array_keys($item);
      if (count($keys)==1) {
        $key = $keys[0];
        switch ($key) {
          case 'nid':
            $value = array_shift(entity_load('node', array($item[$key])));
            break;
          case 'uid':
            $value = array_shift(entity_load('user', array($item[$key])));
            break;
          case 'tid':
            $value = array_shift(entity_load('taxonomy_term', array($item[$key])));
            break;
          case 'vid':
            $value = array_shift(entity_load('taxonomy_vocabulary', array($item[$key])));
            break;
          case 'value':
            $value = $item['value'];
            break;
        }
      }
      else {
        if ($get_key && isset($item[$get_key])) {
          $value = $item[$get_key];
        }
        elseif (array_key_exists('value', $item)) {
          $value = isset($item['safe_value']) ? $item['safe_value'] : $item['value'];
        }
      }
      $values[$delta] = $value;
    }
  }
  if (is_numeric($get_delta)) {
    return isset($values[$get_delta]) ? $values[$get_delta] : NULL;
  }
  return $values;
}

I then created the code below in my node.tpl page to check how many 'body' fields were in the array.
<?php if (render($content)) :
$contArray = array();
$summary = field_fetch_field_values('node', $node, 'body');
$contArray = $summary;
foreach ($contArray as $value) : ?>

<?php print $value; ?>

<?php endforeach; else : ?>

There is currently no content for this page.

<?php endif; ?>

Answer: Well, first of all, you can inspect the contents of the $content['body'] array using the php native print_r() function.
If the assumptions you have prove to be correct, there is no reason why foreach would not work. However, you can find out the number of an array's elements using the function count(). In this case, you would use it on $content['body'].
Comment: Many thanks for the reply; when i use `count($content['body']);` i'm getting a value of 26, when there are only 3 instances of the 'body' field. If I use `count($content);`, it returns a value of 4. How do I target the 'body' field only?
Comment: Like I said in the reply: use the `print_r()` function to see what you are dealing with. It is perfectly ok to use it in the template (while developing of course).

Splitting 'unlimited' body fields