Check local (internal) IP with JavaScript

Question: I know that this will seem like a duplicate, but I honestly have not been able to find any answer that solves this.
I have two iPads set up with static IP addresses on a network that can only access www.example.com (network restriction, not iPad restriction). example.com is an eCommerce site and I want to fill in a coupon field whenever either of these two iPads visit the site.
The only way I can think of doing this is getting the local IP addresses of the iPads (e.g. 192.168.0.x) and creating a whitelist array. But my problem is trying to detect the browsing device's local IP.
I cannot use any resources outside of the example.com domain and I can't use the network's public IP as there will be lots of other devices connected.
Also, I've tried WebRTC but it's Chrome and Firefox only, and I am limited to the iPad's native Safari browser.
Help me Overflow Kenobi, you're my only hope!
EDIT
Conditions have changed. I found out that no other devices will be using the checkout service, so I can now target the external IP. Details about how I did this are below.
Comment: java and rtc are the only hacks i've seen to get an IP from JS, which alone doesn't provide such capability.
Comment: I'm open to any options, even if there is a PHP alternative that I can then carry over into JS. Although I have very little experience with PHP.
Answer: OK, I've found a solution to my problem.
One correction first to my original question:
I just found out that none of the other devices on the network will actually be used for purchasing on the website, so the iPads are the only two devices that will enter the checkout.
Knowing this now, I am able to target the public IP of the network. I've done this using two scripts, one in an external PHP file (our server isn't setup to run PHP in HTML files) and one in an external JavaScript file (easier management as there are multiple versions of the checkout page, so if I need to change the discount code I just have to update the JS file.)
PHP file:
// Declare content as JavaScript
Header("content-type: application/x-javascript");
// Declare variables for IP adress requests
$http_client_ip = $_SERVER['HTTP_CLIENT_IP'];
$http_x_forwarded_for = $_SERVER['HTTP_X_FORWARDED_FOR'];
$remote_addr = $_SERVER['REMOTE_ADDR'];

// Request for most accurate IP address
if (!empty($http_client_ip)) {
    $ip_address = $http_client_ip;
} else if (!empty($http_x_forwarded_for)) {
    $ip_address = $http_x_forwarded_for;
} else {
    $ip_address = $remote_addr;
}

// Add results to array - multiple IP addresses may be returned
$list = explode(',', $ip_address, 2);

// Write the first IP address in array as JavaScript
echo 'document.write(\'
' . $list[0] . '
\')';

JS file:
// Array of allowed IP addresses
var allowedIP = ['x.x.x.x'];
// Coupon code
var couponCode = "CODE001";

// Run script when page is loaded
$(document).ready(function () {
    // Get device IP from 'myIP' div loaded by php
    var ipAddress = $('.myIP').text();
    // Check if device IP matches any of the IPs in the Allowed array
    for (var i = 0; i<allowedIP.length;i++) {
        if (ipAddress == allowedIP[i]) {
            // If it matches, write to console
            console.log("Your external IP is allowed");
            // Add coupon code to input field
            $('input[name="coupon"]').val(couponCode);
        } else {
            // If it does not match, write to console
            console.log("Sorry buddy, you're not on the list.");
        }
    };
});


Require specific access for certain pages with only one input field

Question: For certain pages i have to require a login first (custom form with 1 input field).

When you try to reach the URL of one of those pages you are
redirected to a login-page
They have to fill-in a number of 11 digits. If the filled in field
contains 11 digits they are redirected to the protected page(s).

It's not an age gate. It's for doctors the have to fill in a 11-digit code. If the code contains 11 digital characters they can see the protected page(s).
How (which modules) are best practices to built this functionality?
Comment: The first part is easy, just add a required permission on the restricted pages. If a user is not permitted to view that page, he is automatically redirected to the login page. Can you clarify the 11-digit field? Is it some kind of captcha?
Comment: no not captcha. Just a boolean field. The only validation of this field is that it needs to have 11 digits.
Comment: that needs to be saved in cookies/db? what exactly needs to be achieved? Is it kind of a age-gate?
Comment: A boolean field can only be true or false. I think you mean a textfield which only validates if it contains 11 (random?) digits, am I right?
Comment: yes you are wright! @nikunj see my updated question
Comment: IMO this is not a duplicate of http://drupal.stackexchange.com/questions/72983 ... This question here is NOT asking for 2 login form, but only to "get redirected to '***A***' (= 1 ...) login page". Therefor I think it should no longer be marked as such (which is why I used the 'reopen' link below it). To Mees: if you agree, please try to EDIT your question to make it more clear why it is not a duplicate (and let me know via an extra comment if it ever gets reopened please).
Answer: so the characters can be random or need to be verified against some database table entries?
best thing would be to have a custom code/solution for this, use ctools popup and custom javascript to check for the right cookies on the selected pages, we can add a field defining the setting whether the page requires verification or not, and overridden node tpl (template) for that particular content type which can contain drupal_add_js or inline javascript based on the field condition. Adding a module and customising will add more pain in my opinion.


ReactiveX: filter out numbers from observable so that total never goes below zero

Question: The following RxJs code displays numbers from the input list and the running total:
let inputs = [10, 10, -30, 10, -30, 50, -25, -30, 10]

let obs$ = Rx.Observable.from(inputs)
let totals$ = obs$.scan((acc, next) => acc + next, 0)
obs$.subscribe(x => console.log('x:', x));
totals$.subscribe(x => console.log("total:", x))

totals$ will emit: 10, 20, -10, 0, -30...
I would like to transform the obs$ observable somehow, so that the resulting totals$ never emits a negative number.
I.e., in this case, both first and last "-30" should be filtered out:
otherObs$: 10, 10, 10, -30, 50, -25, 10
totals$: 10, 20, 30, 0, 50, 25, 35
edit: Note that I'm interested in the modified otherObs$ observable, i.e., a sequence of the original input numbers with some filtered out (obs$ will actually contain more data, so I really do need the original elements; the "value" is just a key to filter on). The totals$ here is only for showing what is going on.
Answer: You can easily achieve that by incorporating that logic in your reduce function, aka inside the .scan():
let total$ = obs$.scan((acc, next) => {
    if (acc + next < 0) { //less than zero, don't take in the current number
        return acc;
    }
    return acc + next; //all is good, continue to add next
}, 0)

Or even in one liner:
let totals$ = obs$.scan((acc, next) => (acc + next < 0 ? acc : acc + next), 0)

If you want to retain each and every value and still check the sum, then there is no choice but to store each sequence in the array:
let other$ =
    obs$
        .scan((acc, next) => {
            let sum = acc.reduce((a,b)=>a+b);
            if((sum+next)<0){
                return acc; // less than zero, return current arrray
            }
            return  acc.push(next); //greater or equal to zero, add current item to array
        }, [...0])
        .switchMap(array => Observable.from(array))

Comment: Unfortunately, I'm interested in numbers from the original sequence, not in the total. I want to get an observable, such that when I apply my original `totals$` reduce, I get the non-negatives
Answer: Based on @CozyAzure's ideas, I figured out a better answer. I simply need to store more state in the reducer: the original value, the accumulated total, and whether this value was added to the total or not.
let other$ = obs$
  .scan(({value, total, valid}, next) => {
     if (total + next < 0)
       return { value: next, total: total, valid: false }
     else
       return { value: next, total: total + next, valid: true }
  }, { value: undefined, total: 0, valid: false })
  .filter(x => x.valid)
  .map(x => x.value)

This way, I can filter out the values that were not added, and get back the original values that were.


Let $(G,\circ)$ be a finite group with an identity element $e$ ...

Question: If $H$ is a non-empty subset of $G$ ($H \subseteq G$) with the property $x, y ∈ H \Rightarrow x \circ y \in H$ shows $H$ is a subgroup of $G$.
The part that I'm mainly stuck on is that I'm not sure how to show $e \in H$.
Comment: Welcome to math.SE!! When writing mathematical expressions you must use MathJax to render the math correctly.
Comment: @manooooh Hiiiiiiiiiiii...I agree with you. I'm very happy to meet you here.
Comment: @Sebastiano heyyyy, it has been a long time since we didn't match! Nice to see you here.
Comment: You should have your whole question in the body. Right now, part of it is in the title, which increases the chance of misunderstading.
Comment: @manooh Thanks for the heads up; I'm relatively new to this so I don't really know what MathJax is yet but I'll keep that in mind for future reference :)
Comment: @verret Yeah I didn't like the way I set it up either. The limit for the question was 150 characters which was too long to fit. I'm completely new to this so I didn't know how it would show up to the viewer but I'll do that next time.
Comment: I didn't expect responses to come this quickly but thanks to everyone who answered and I did figure it out
Comment: I don't think there is a character limit for questions?
Answer: The fact that $H$ is finite is crucial.
Since $H$ is not empty, choose $y\in H$ and consider the map $\mu_y\colon H\to H$ defined by $\mu_y(x)=xy$. This is well defined (in particular the codomain is $H$) by assumption.
The map is injective1, so also surjective because $H$ is finite. Then there exists $x\in H$ such that $\mu_y(x)=xy=y$. Since we're in a group $G$, this implies $x=e$. Therefore $e\in H$.
Now, for the same reason, there exists $z\in H$ such that $\mu_y(z)=zy=e$. Then $z=y^{-1}\in H$. Since this holds for any $y\in H$, you're done.

1 If $\mu_y(a)=\mu_y(b)$, then $ay=by$. We can multiply both sides by $y^{-1}$ and get $a=b$. You don't need to know that $y^{-1}\in H$, at this point: the relation $ay=by$ holds for $a,b,y\in G$ and $G$ is a group.
Comment: Your comment actually helped me understand this problem much more conceptually. I wouldn't have thought of this problem in the context of mapping
Answer: $H$ is nonempty so it contains some element $x$. Therefore, by the property $H$ satisfies we have $x^2 \in H$. Either $x^2$ is the identity, or $x^2$ is not the identity in which case we look at all possible products of elements we know are in $H$. This process must terminate since $H$ is a finite set, so $e$ must be in $H$.
Answer: Hint Since $G$ is finite, for each $x \in H$ there exists some $n \geq 1$ such that
$$x^n=e$$
Show that $x \in H$ implies that $x^n \in H$.
Comment: I know you didn't intend to give the full answer, but this definitely helped a lot
Answer: With
$\emptyset \ne H \subset G, \tag 1$
and $H$ multiplicatively closed, which is simply another way of saying
$\forall x, y \in H, \; x \circ y \in H, \tag 2$
we have
$\exists x \in H; \tag 3$
by (2),
$x^2 = x \circ x \in H, \; x^3 = x \circ x^2 \in H, \tag 4$
and in fact
$\forall m \in \Bbb N, \; x^m \in H, \tag 5$
which may in fact be proved by a simple induction:  taking (4) as the basis, we assume
$x^k \in H; \tag 6$
then by (2),
$x^{k + 1} = x \circ x^k \in H \tag 7$
as well; thus (5) binds.
Now since
$\vert G \vert = n < \infty, \tag 8$
$\exists m \in \Bbb N, \; x^m = 1; \tag 9$
this is easily seen by observing that the sequence of powers of $x$,
$x, \; x^2, \; x^3, \ldots \tag{10}$
must at some point begin to repeat itself in light of (8); that is,
$\exists k, l \in \Bbb N, \; k < l, \; x^l = x^k; \tag{11}$
then
$x^{l - k} = x^l x^{-k} = x^k x^{-k} = e, \tag{12}$
so we may take
$m = l - k. \tag{13}$
We may now affirm that, in light of (5),
$e = x^m \in H; \tag{14}$
furthermore, if $m = 1$,
$e^{-1} = e \in H, \tag{15}$
whilst with $m > 1$
$x \ast x^{m - 1} = x^m = e, \tag{16}$
which shows that
$x^{-1} = x^{m - 1} \in H. \tag{11}$
We thus see that $H$, in addition to satisfying (2), contains both $e$ and the invere of each of its elements; thus we conclude that $H$ is in fact a subgroup of $G$.
Comment: I don't like this approach. The fact that $G$ is finite is irrelevant: it's sufficient to assume that $H$ is finite. My preferred proof needs no reference to powers and is just based on the pigeonhole principle.


How to represent kWh usage by year against average temperature?

Question: Just for fun, I want to chart my monthly household power consumption year-over-year.  However, I wish to include some reference to monthly temperature so I can determine if my home or behavior is improving, worsening, or holding steady in regards to kWh usage.
The data I am working with:
+----------+--------+-----------+----------------+----------+-----------+------------+
|  Month   | # Days | kWh Usage | Daily kWh Avg. | Avg. Low | Avg. High | Avg. Temp. |
+----------+--------+-----------+----------------+----------+-----------+------------+
| Mar 2015 |     32 |      1048 |             33 |       40 |        60 |         50 |
| Feb 2015 |     29 |      1156 |             40 |       32 |        54 |         43 |
| Jan 2015 |     33 |      1143 |             35 |       38 |        57 |         47 |
| Dec 2014 |     30 |       887 |             30 |       39 |        61 |         50 |
| Nov 2014 |     29 |       645 |             22 |       45 |        67 |         56 |
| Oct 2014 |     29 |       598 |             21 |       60 |        78 |         69 |
| Sep 2014 |     32 |       893 |             28 |       70 |        85 |         77 |
| Aug 2014 |     30 |       965 |             32 |       72 |        87 |         79 |
| Jul 2014 |     29 |       784 |             27 |       72 |        87 |         79 |
| Jun 2014 |     32 |      1018 |             32 |       69 |        87 |         78 |
| May 2014 |     30 |       702 |             23 |       63 |        82 |         72 |
| Apr 2014 |     33 |       722 |             22 |       50 |        71 |         60 |
| Mar 2014 |     29 |       830 |             29 |       41 |        62 |         52 |
| Feb 2014 |     28 |      1197 |             43 |       32 |        52 |         42 |
| Jan 2014 |     33 |      1100 |             33 |       38 |        59 |         49 |
| Dec 2013 |     30 |       856 |             29 |       40 |        63 |         51 |
| Nov 2013 |     33 |       686 |             21 |       48 |        70 |         59 |
| Oct 2013 |     30 |       527 |             18 |       61 |        77 |         69 |
| Sep 2013 |     30 |       817 |             27 |       69 |        86 |         77 |
| Aug 2013 |     28 |       991 |             35 |       72 |        86 |         79 |
| Jul 2013 |     31 |       993 |             32 |       73 |        86 |         79 |
| Jun 2013 |     30 |       847 |             28 |       66 |        83 |         74 |
| May 2013 |     29 |       605 |             21 |       59 |        76 |         67 |
| Apr 2013 |     34 |       791 |             23 |       47 |        66 |         57 |
+----------+--------+-----------+----------------+----------+-----------+------------+

I started with a column chart easily comparing month-to-month values:

I envisioned a nice background area or line graph mapped to a secondary (right) vertical axis showing the high/low ranges but realized that would be problematic with the multi-year groupings.
It would be easy with one single year:

I am curious to know if anyone can recommend a way of combining all the yearly data into a single chart with temperature comparisons?
Is there some ratio I could use that could effectively relate the kWh usage to average temperature... or some other display technique I am overlooking... or am I stuck with one chart per year?
Answer: I would like to suggest that the important thing is to develop a physically realistic, practically useful model of energy cost.  That will work better to detect changes in costs than any visualization of the raw data can accomplish.  By comparing this to the solution offered on SO, we have a very nice case study in the difference between fitting a curve to data and performing a meaningful statistical analysis.
(This suggestion is based on having fit such a model to my own household usage a decade ago and applying it to track changes during that period.  Note that once the model is fit, it can easily be calculated in a spreadsheet for the purpose of tracking changes, so we should not feel limited by the (in)capabilities of spreadsheet software.)
For these data, such a physically plausible model produces a substantially different picture of energy costs and usage patterns than a simple alternative model (a quadratic least-squares fit of daily usage against monthly mean temperature).  Consequently, the simpler model cannot be considered a reliable tool for understanding, predicting, or comparing energy use patterns.

Analysis
Newton's Law of Cooling says that, to a good approximation, the cost of heating (during a unit of time) should be directly proportional to the difference between the outside temperature $t$ and the inside temperature $t_0$.  Let that constant of proportionality be $-\alpha$. The cost of cooling also should be proportional to that temperature difference, with a similar--but not necessarily identical--constant of proportionality $\beta$.  (Each of these is determined by the insulating capability of the house as well as the efficiencies of the heating and cooling systems.)
Estimating $\alpha$ and $\beta$ (which are expressed as kilowatts (or dollars) per degree per unit time) are among the most important things that can be accomplished, because they enable us to predict future costs, as well as measure the efficiencies of the house and its energy systems.
Because these data are total electricity usage, they include non-heating costs such as lighting, cooking, computing, and entertainment.  Also of interest is an estimate of this average base energy usage (per unit time), which I will call $\gamma$: it provides a floor on how much energy can be saved and enables predictions of future costs when efficiency improvements of known magnitude are made.  (For instance, after four years I replaced a furnace by one claimed to be 30% more efficient--and indeed it was exactly that.)
Finally, as a (gross) approximation I will assume the house is maintained at a nearly constant temperature $t_0$ throughout the year.  (In my personal model I assume two temperatures, $t_0 \le t_1$, for winter and summer respectively--but there aren't yet enough data in this example to estimate both of them reliably and they would be pretty close anyway.)  Knowing this value helps one evaluate the consequences of maintaining the house at a slightly different temperature, which is one important energy-saving option.
The data present a singularly important and interesting complication: they reflect total costs during periods when outside temperatures fluctuate--and they fluctuate a lot, usually about one-quarter of their annual range each month.  As we will see, this creates a substantial difference between the correct underlying instantaneous model just described and the values of the monthly totals.  The effect is especially pronounced in the in-between months, where both (or neither) heating and cooling take place.  Any model that does not account for this variation would mistakenly "think" energy costs should be at the base rate $\gamma$ during any month with an average temperature of $t_0$, but the reality is far different.
We don't (readily) have detailed information about the monthly temperature fluctuations apart from their ranges.  I propose handling that with an approach that is practical, but a tiny bit inconsistent.  Except at the extreme temperatures, each month will usually experience gradual increases or decreases in temperature.  This means we can take the distribution to be approximately uniform.  When the range of a uniform variable has length $L$, that variable has a standard deviation of $s = L/\sqrt{6}$.  I use this relationship to convert the ranges (from Avg. Low to Avg. High) to standard deviations.  But then, essentially to obtain a nicely behaved model, I will downweight the variation at the ends of these ranges by using Normal distributions (with these estimated SDs and means given by Avg. Temp).
Finally, we must standardize the data to a common unit time.  Although that's already present in the Daily kWh Avg. variable, it lacks precision, so let's instead divide the total by the number of days in order to gain back the lost precision.
Thus, the model of unit-time cooling costs $Y$ at an outdoor temperature of $t$ is
$$y(t) = \gamma + \alpha(t-t_0)I(t\lt t_0) + \beta(t-t_0)I(t\gt t_0) + \varepsilon(t)$$
where $I$ is the indicator function and $\varepsilon$ represents everything not otherwise explicitly captured in this model.  It has four parameters to estimate: $\alpha,\beta,\gamma$, and $t_0$.  (If you're really sure of $t_0$ you could fix its value rather than estimating it.)
The reported total costs during a time period $x_0$ to $x_1$ when the temperature $t(x)$ varies with time $x$ will therefore be
$$\eqalign{
&\text{Cost}(x_0,x_1) = \int_{x_0}^{x_1} y(t)dt \\
&=\int_{x_0}^{x_1} \left(\gamma + \alpha(t(x)-t_0)I(t(x)\lt t_0) + \beta(t(x)-t_0)I(t(x)\gt t_0) + \varepsilon(t(x))\right) t^\prime(x) dx.
}$$
If the model is any good at all, the fluctuations in $\varepsilon(t)$ ought to average to a value $\bar\varepsilon$ close to zero and will appear to randomly change month to month.  Approximating the fluctuations in $t(x)$ with a Normal distribution of mean $\bar{t}$ (the monthly average) and standard deviation $s(\bar t)$ (as previously given from the monthly range) and doing the integrals yields
$$\bar{y}(\bar{t}) = \gamma + (\beta-\alpha)s(\bar t)^2 \phi_s(\bar t-t_0) + (\bar{t}-t_0)\left(\beta + (\alpha-\beta)\Phi_s(t_0 - \bar{t})\right) + \bar\varepsilon(\bar{t}).$$
In this formula, $\Phi_s$ is the cumulative distribution of a Normal variate of zero mean and standard deviation $s(\bar t)$; $\phi$ is its density.

Model fitting
This model, although expressing a nonlinear relationship between costs and temperature, is nevertheless linear in the variables $\alpha,\beta,$ and $\gamma$.  However, since it is nonlinear in $t_0$, and $t_0$ is not known, we need a nonlinear fitting procedure.  To illustrate, I simply dumped it into a likelihood maximizer (using R for the computation), assuming the $\bar\varepsilon$ are independent and identically distributed, with normal distributions of mean zero and common standard deviation $\sigma$.
For these data, the estimates are
$$(\hat\alpha,\hat\beta,\hat\gamma,\hat {t_0}, \hat\sigma) = (-1.489, 1.371, 10.2, 63.4, 1.80).$$
This means:

The cost to heat is approximately $1.49$ kWh/day/degree F.
The cost to cool is approximately $1.37$ kWh/day/degree F.  Cooling is a little more efficient.
The base (non-heating/cooling) energy usage is $10.2$ kWh/day.  (This number is fairly uncertain; additional data will help pin it down better.)
The house is maintained at a temperature near $63.4$ degrees F.
The other variations not explicitly accounted for in the model have a standard deviation of $1.80$ kWh/day.

Confidence intervals and other quantitative expressions of uncertainty in these estimates can be obtained in standard ways with the maximum likelihood machinery.

Visualization
To illustrate this model, the following figure plots the data, the underlying model, the fit to the monthly averages, and a simple least-squares quadratic fit.

The monthly data are shown as dark crosses.  The horizontal gray lines on which they lie show the monthly temperature ranges.  Our underlying model, reflecting Newton's law, is shown by the red and blue line segments meeting at a temperature of $t_0$.  Our fit to the data is not a curve, because it depends on the temperature ranges.  It is shown therefore as individual solid blue and red points.  (Nevertheless, because the monthly ranges do not vary a lot, these points do seem to trace out a curve--almost the same as the dashed quadratic curve.)  Finally, the dashed curve is the quadratic least squares fit (to the dark crosses).
Notice how much the fits depart from the underlying (instantaneous) model, especially in the middle temperatures!  This is the effect of monthly averaging.  (Think of the heights of the red and blue lines being "smeared" across each horizontal gray segment.  At extreme temperatures everything is centered at the lines, but at middle temperatures the two sides of the "V" get averaged together, reflecting the need for heating at some times and cooling at other times during the month.)

Model comparison
The two fits--the one painstakingly developed here and the simple, easy, quadratic fit--agree closely both with each other and with the data points.  The quadratic fit is not quite as good, but it's still decent: its adjusted mean residual (for three parameters) is $2.07$ kWh/day, whereas the adjusted mean residual of the Newton's law model (for four parameters) is $1.97$ kWh/day, about 5% lower.  If all you want to do is plot a curve through the data points, then the simplicity and relative fidelity of the quadratic fit would recommend it.
However, the quadratic fit is utterly useless for learning what's going on!  Its formula,
$$\bar y(\bar t) = 219.95 - 6.241 \bar t + 0.04879 (\bar t)^2,$$
reveals nothing of use directly.  In all fairness, we could analyze it a little:

This is a parabola with vertex at $\hat t_0 = 6.241/(2\times 0.04879) = 64.0$ degrees F.  We could take this as an estimate of the constant house temperature.  It does not differ significantly from our first estimate of $63.4$ degrees.  However, the predicted cost at this temperature is $219.95 - 6.241(63.4) + 0.04879(63.4)^2 = 20.4$ kWh/day.  This is twice the base energy usage fit with Newton's Law.
The marginal cost of heating or cooling is obtained from the absolute value of the derivative,  $\bar{y}^\prime(\bar t) = -6.241 + 2(0.04879)\bar{t}$.  For example, using this formula we would estimate the cost of heating a house when the outside temperature is $90$ degrees as $-6.241 + 2(0.04879)(90) = 2.54$ kWh/day/degree F.  This is twice the value estimated with Newton's Law.
Similarly, the cost to heat the house at an outdoor temperature of $32$ degrees would be estimated as $|-6.241 + 2(0.04879)(32)| = 3.12$ kWh/day/degree F.  This is more than twice the value estimated with Newton's Law.
At the middle temperatures, the quadratic fit errs in the other direction.  Indeed, at its vertex in the $60$ to $68$ degree range it predicts nearly zero marginal heating or cooling costs, even though this mean temperature comprises days as cool as $50$ degrees and as warm as $78$ degrees.  (Few people reading this post will still have their heat off at $50$ degrees (=$10$ degrees C)!)

In brief, although it looks almost as good in the visualization, the quadratic fit grossly errs in estimating fundamental quantities of interest related to energy usage.  Its use for evaluating changes in usage is therefore problematic and should be discouraged.

Computation
This R code performed all the computing and plotting.  It can readily be adapted to similar datasets.
#
# Read and process the raw data.
#
x <- read.csv("F:/temp/energy.csv")
x$Daily <- x$Usage / x$Length
x <- x[order(x$Temp), ]
#pairs(x)
#
# Fit a quadratic curve.
#
fit.quadratic <- lm(Daily ~ Temp+I(Temp^2), data=x)
# par(mfrow=c(2,2))
# plot(fit.quadratic)
# par(mfrow=c(1,1))
#
# Fit a simple but realistic heating-cooling model with maximum likelihood.
#
response <- function(theta, x, s) {
  alpha <- theta[1]; beta <- theta[2]; gamma <- theta[3]; t.0 <- theta[4]
  x <- x - t.0
  gamma + (beta-alpha)*s^2*dnorm(x, 0, s) +  x*(beta + (alpha-beta)*pnorm(-x, 0, s))
}
log.L <- function(theta, y, x, s) {
  #   theta = (alpha, beta, gamma, t.0, sigma)
  #   x = time
  #   s = estimated SD
  #   y = response
  y.hat <- response(theta, x, s)
  sigma <- theta[5]
  sum((((y - y.hat) / sigma) ^2 + log(2 * pi * sigma^2))/2)
}
theta <- c(alpha=-1, beta=5/4, gamma=20, t.0=65, sigma=2) # Initial guess
x$Spread <- (x$Temp.high - x$Temp.low)/sqrt(6)            # Uniform estimate
fit <- nlm(log.L, theta, y=x$Daily, x=x$Temp, x$Spread)
names(fit$estimate) <- names(theta)
#$
# Set up for plotting.
#
i.pad <- 10
plot(range(x$Temp)+c(-i.pad,i.pad), c(0, max(x$Daily)+20), type="n",
     xlab="Temp", ylab="Cost, kWh/day",
     main="Data, Model, and Fits")
#
# Plot the data.
#
l <- matrix(mapply(function(l,r,h) {c(l,h,r,h,NA,NA)},
                   x$Temp.low, x$Temp.high, x$Daily), 2)
lines(l[1,], l[2,], col="Gray")
points(x$Temp, x$Daily, type="p", pch=3)
#
# Draw the models.
#
x0 <- seq(min(x$Temp)-i.pad, max(x$Temp)+i.pad, length.out=401)
lines(x0, cbind(1, x0, x0^2) %*% coef(fit.quadratic), lwd=3, lty=3)
#curve(response(fit$estimate, x, 0), add=TRUE, lwd=2, lty=1)
t.0 <- fit$estimate["t.0"]
alpha <- fit$estimate["alpha"]
beta <- fit$estimate["beta"]
gamma <- fit$estimate["gamma"]
cool <- "#1020c0"; heat <- "#c02010"
lines(c(t.0, 0), gamma + c(0, -alpha*t.0), lwd=2, lty=1, col=cool)
lines(c(t.0, 100), gamma + c(0, beta*(100-t.0)), lwd=2, lty=1, col=heat)
#
# Display the fit.
#
pred <- response(fit$estimate, x$Temp, x$Spread)
points(x$Temp, pred, pch=16, cex=1, col=ifelse(x$Temp < t.0, cool, heat))
#lines(lowess(x$Temp, pred, f=1/4))
#
# Estimate the residual standard deviations.
#
residuals <- x$Daily - pred
sqrt(sum(residuals^2) / (length(residuals) - 4))
sqrt(sum(resid(fit.quadratic)^2) / (length(residuals) - 3))

Comment: This may be the single best response to any stack overflow question I have read.  I greatly appreciate the time taken to explain the logic and reasoning behind the solution.
Comment: Physics is more hairy than this.  The condenser and evaporator switch roles in heating vs. cooling.  This means they act like two different systems, not one continuous.  Heating degree days, cooling degree days, and dehumidification degree days are three separarate cost-drivers, and depending on geographic location (think ak, wi, ca, az, mo, and fl) and year can act discontinuously (end of heating season isn't the same as start of cooling).  Decent stats on the data say there are 5 seasons, not 4.  May is its own season, at least within the last 5 years.
Comment: I love this good foundation/analysis, please hear this as applause, not criticism.  The heating process is different than cooling, so the non-piecewise quadratic on both sides might be at odds with that.  The evaporator coil is indoors during cooling and outdoors during heating.  In heat-pump there is also defrost cycling and "back up heat".  Also, the compressor has to work harder to fight against a more extreme outdoor temperature, so not only are you moving more heat, you are moving it up a higher hill.  It isn't linear.  Humidity is big, and can be 2/3 the energy budget. Air infiltration.
Comment: @EngrStudent All good points and much appreciated.  I would maintain that the approach presented here, although simplified, shows what is needed to lay a foundation to tease out these subtler effects.  Once you handle the big terms in the model--and I think nobody will deny that temperature has to be a dominant contributor to costs--then, *if you have done that in a physically meaningful way,* you might be able to identify other terms and perhaps even estimate their effects accurately. If you don't deal with the big terms correctly, then you haven't any hope of characterizing the others.
Comment: @EngrStudent Thank you again--those are all interesting points.  I had no idea that humidity might account for such a large proportion of the budget.  That's the kind of observation that exemplifies the potential value of coupling a good theory (or "conceptual model" in some circles) with the statistical analysis.
Comment: A theorist will look at vapor-compression cooling on a psychrometric chart and assume that the liquid condensate is at the temperature where it condensed, but it is typically a few degrees below the lowest coil temperature.  Cooling that much liquid by that much is a sink.  Inefficiency/entropy.  Infiltration/leaks (such as people walking in the door) can be big. There are requirements about how frequently the air in the conditioned space is fully replaced by outside air.  In a place like Houston, a proposition like that means you have a constant inflow of humidity with your warm N2+oxygen.
Answer: I received an answer over at StackOverflow.  If anyone has additional thoughts, I am still very interested in alternative solutions.
https://stackoverflow.com/questions/29777890/data-visualization-how-to-represent-kwh-usage-by-year-against-average-temperatu
Comment: The solution on SO is implausible. [Newton's law of cooling](http://en.wikipedia.org/wiki/Convective_heat_transfer#Newton.27s_law_of_cooling), which is a reasonable first-order approximation useful as a point of departure, suggests the plot of energy usage vs. temperature should be the union of two lines (perhaps of different slopes).  The average hides daily (and even hourly) temperature swings which will blur the region at the intersection of those lines (where neither heating nor cooling are needed). A quadratic fit might be reasonable there, but *asymptotically the fit needs to be linear*.
Comment: I couldn't quite fit my response to that last question in the space for a comment, so I posted it as an answer instead. I don't see how you infer that per-degree cooling costs are greater than per-degree heating costs, though. Your data seem to indicate the opposite is true (although the costs are pretty close, as one would expect). And please note that a *linear model* does not imply a linear *fit*! There's a lot going on here to cause the data to deviate systematically from this underlying model.
Comment: I know averages blur accuracy but its the data I have.  Due to poor understanding of statistics I fail to grasp phrases _"should be the union of two lines..."_ and _"asymptotically the fit needs to be linear"_.  From a novice POV, the SO post seems intuitive as it fits my expectation that energy consumption increase at opposite ends of temperature scale while being lowest in mid-range where neither heating nor cooling were needed. Wouldn't a quadratic fit be symmetrical? I dont believe power usage is symmetrical as we use more power to heat than cool. I appreciate any corrections or advice.
Comment: A quadratic fit, although symmetrical, is non-physical at the extremes, because it says you will pay much more for heating at the lowest temperatures, and much more for cooling at the highest temperatures, than is physically plausible. Moreover, symmetry in the plot would be expected only when the cost to cool the house per degree is the same as the cost to heat it per degree, which assumes the heating and cooling systems are equally efficient. That might or might not be the case--but you shouldn't impose that symmetry on your model.
Comment: I agree it differs as it costs more to cool than heat per degree.  However, so I understand the first comment, are you suggesting the quadratic fit from the SO post -- although reasonable -- is not truly accurate and that a linear fit is the technically correct answer due to Newtons's law of cooling?  It is the _implausibility of the SO solution_ that I am failing to understand.


Prove that for vectors $v_1,...,v_n$ in $\mathbb C^n$, $\{v_1,...,v_n\}$ is a basis for $\mathbb C^n$ iff its conjugate is a basis for $\mathbb C^n$

Question: Prove that for vectors $v_1,...,v_n$ in $\mathbb C^n$, $\{v_1,...,v_n\}$ is a basis for $\mathbb C^n$ if and only if $\{\bar v_1,..., \bar v_n\}$ is a basis for $\mathbb C^n$.
I know intuitively that the conjugate of $a+bi$, $a-bi$ is orthogonal to $a+bi$. Since they are orthogonal, then the span of $v_1,...,v_n$ and $\bar v_1,...,\bar v_n$ is the same, and $v_i \in \mathbb C^n$ and $\bar v_i\in\mathbb C^n$.
Please drop hints on how I can prove this formally.
Edit: not all conjugates are orthogonal, thanks Abramos.
Comment: Are you sure that $z$ and $\bar{z}$ are orthogonal in the complex plane? I wouldn't say so
Comment: You might be able to argue that there is some nontrivial way to write $\sum a_iv_i=0$ if and only if there is a nontrivial way to write $\sum b_i\bar v_i=0$.
Comment: Looks like everybody and their brothers and sisters are going to weigh in on this one!
Answer: Hints: for $\;a_i\in\Bbb C\;$ :
$$\sum_{i=1}^n a_iv_i=0\iff 0=\overline 0=\overline{\left(\sum_{i=1}^n a_iv_i\right)}=\sum_{i=1}^n\overline{(a_iv_i)}=\sum_{i=1}^n\overline{a_i}\overline{v_i} $$
So we get that $\;\forall\,i\;,\;a_i=0\;\iff\;\forall\,i\;,\;\overline{a_i}=0\;$
Answer: This should be very straightforward - just write out the usual arguments for proving that a set of vectors is (a) linearly independent and (b) spans the whole space, and use the fact that the conjugate satisfies the properties:
$$\overline{z} = 0 \iff z = 0\text{ and }\overline{z_1 + \dots z_n} = \overline{z_1} + \dots \overline{z_n} \text{ and } \overline{az} = \overline{a}\,\overline{z}$$
So, for example, if there were a linear combination equal to zero:
$$a_1v_1 + \dots a_nv_n = 0$$
then we would have
$$\overline{a_1v_1 + \dots a_nv_n} = 0$$
and then
$$\overline{a_1v_1} + \dots \overline{a_nv_n} = 0$$
etc.
Answer: What I say below may be more than is wanted, and it may only be USD $ \$ 0.02 $ worth, but it's my $ \$ 0.02 $, so what the hell, here goes:
If the $v_i \in \Bbb C^n$ span $\Bbb C^n$, then for any vector $w \in C^n$ we also have $\bar w \in C^n$, so there exist coeffiecients $b_i \in \Bbb C$ such that
$\bar w = \sum_i b_i v_i, \tag{1}$
whence
$w = \sum_i \bar b_i \bar v_i, \tag{2}$
which shows that the $\bar v_i$ also span $\Bbb C^n$.  The argument for linear independence of the $\bar v_i$ over $\Bbb C$ is of course the same as given by Old John and DonAntonio in their answers:  if
$\sum_i b_i \bar v_i = 0, \tag{3}$
then by the august factoid that $\bar 0 = 0$ we have
$\sum_i \bar b_i v_i = 0, \tag{4}$
which shows that the $\bar b_i = 0$ by linear independence of the $v_i$.  Thus the $b_i = 0$ implying the $\bar v_i$ are linearly independent,and hence form a basis for $\Bbb C^n$.
Of course the whole argument can be run in reverse to show that the $\bar v_i$ form a basis implies the $v_i$ do.  QED
Hope this helps.  Cheerio,
and as always,
Fiat Lux!!!
Answer: A different approach would be to note that $\mathbb{C}^n \cong \mathbb{R}^{2n}$ and then write down the image of a basis under the canonical isomorphism. After that you can work with real basis in order to prove the statement.


Zero dimensional compact manifold is finite

Question: I working through the proof of the stack of records theorem and am stuck on this fact.
The following is taking from http://www.math.sjsu.edu/~simic/Spring09/Math213/final.213.09.soln.pdf page 35.
$f^{−1}(y)$ is a regular submanifold of $M$ of dimension zero, i.e.,$f^{−1}(y)$ is a discrete subset of $M$. This implies that $f^{−1}(y)$ is at most countable. If $f^{−1}(y)$ is infinite, then by compactness of $M$, $f^{−1}(y)$ has an accumulation point, which must be in $f^{−1}(y)$, since $f^{−1}(y)$ is closed. But this contradicts the fact that $f^{−1}(y)$ is discrete.Therefore, $f^{−1}(y)$ is a finite set $\{x_1,...,x_N\}$.
Having an accumulation point means that every neighborhood of the accumulation point contains another point that is not the accumulation point. Why does this mean that the set is not discrete? Could it not be the case that there are only a discrete set of neighborhoods around the point?
Comment: Discrete spaces have no accumulation points, see e.g. [here](https://math.stackexchange.com/questions/1765898/limit-point-of-a-set-under-discrete-topology)
Comment: Manifolds are locally homeomorphic to Euclidean space. How do you arrive at a discrete set of neighborhoods of a point?
Comment: @TedShifrin I don't have a reason why there is a discrete set of neighborhoods, I just cannot see why it must be that every neighborhood contains another point implies the set is infinite.
Comment: Think in Euclidean space. If the origin is an accumulation point of a set of points, that set must be infinite. If it were finite, say $\{x_1,\dots,x_N\}$, consider the numbers $r_n = \|x_n\|$ (i.e., the distance from the origin to the elements of the set). Let $r = min(r_1,\dots,r_N)$, and note that the ball $B(0,r)$ contains *no* point of your set.
Answer: A discrete space $X$ cannot have an accumulation point $x$ since the singleton $\{x\}$ is  an open neigbourhood of $x$ which does not contain a point different from $x$.


C# Array numero proximo

Question: Estou precisando de ajuda não sei mas onde recorrer. O problema e o seguinte temos uma Array do tipo Double.
Temos uma variável x = 91.30 na Array (a) o valor mais próximo é 91.39.
Eu queria saber como fazer a variável y receber o valor do índice 91.39 que é o mais próximo de x. no caso 91.30
Comment: Seria interessantíssimo você colocar o código na publicação para que possamos fazer os devidos testes.
Answer: Você pode usar Linq para obter esse número, e até brevemente o índice no Array onde ele se encontra.
Não esqueça de importar a biblioteca System.Linq no começo do código.
double[] arr = new double[] { 1.5, 1.7, 1.88, 2.0, 2.6, 3.0 };

double numeroBase = 1.65;
double numeroDaArray = arr.Aggregate((x,y) => Math.Abs(x - numeroBase) < Math.Abs(y - numeroBase) ? x : y);
int indice = Array.IndexOf(arr, numeroDaArray);

Console.WriteLine("Número {0} no índice {1} é o mais próximo de {2}.", numeroDaArray, indice, numeroBase);

Veja funcionando no .NET Fiddle.

C# Array numero proximo


Inner-margin on columns [Foundation]

Question: I have row with 2 columns. I want the columns to span the whole width of the row and have a margin between them. This way they align with the rows above and beneath.
The default options add margins to both sides of the columns, which doesn't work for me because then the columns don't align with the other rows. I discovered the class "collapse' which removes the default margins, but I still need that margin between the 2 columns.
I can fix this creating my own classes and modifying my markup a little bit, but I want to make sure Foundation doesn't do this for me somehow.
Do you have any advice or best practice for handling this scenario?
I've attached an image to show you what my design calls for.
Thanks!
Comment: what is your verion of Foundation?
Answer: https://gist.github.com/slawaEremin/7993669
If I understand right, you need add some block inside columns.
The problem is that you always should wrap your content using .row and *-12, if there is only one column:
For example:

     Some content

     Some content

      Some content

Comment: Hey Slawa, thanks for your suggestion. I don't follow, though. Your code is the same as mine, except you don't have another row on top of the existing one. If you add one, you'll see my problem (margin on both sides of the columns, I only need on the inside). Here's dirty edit to show you. http://codepen.io/anon/pen/parqH
Comment: an you insert your code into jsfiddle?Because your exapmle isn't working. Try to open your link in the new tab.  Links for Foundation: cdn.foundation5.zurb.com/foundation.css cdn.foundation5.zurb.com/foundation.js
Comment: Just extend the rendering area horizontally so that the columns are side by side. Then notice how the 2 columns have a 5 pixel margin on the outer edges, separating them from the red row above.

Inner-margin on columns [Foundation]


Como recarregar uma activity

Question: Estou com o seguinte problema, em minha aplicação tenho uma ListView na act 1, e faço um cadastro na act 2, porém quando eu finalizo o cadastro eu também finalizo a act 2, com isso retorno para act 1, o problema é que o meu método de pesquisar já carregou a minha ListView da primeira vez que eu executei a act 1. Como faço para chamar esse método novamente?
Comment: Chame o metodo notifyDataSetChanged() de seu Adapter sempre que há alterações nos dados.
https://www.youtube.com/watch?v=wDBM6wVEO70&t=17m38s
Comment: muito obrigado esse problema eu consegui resolver, porem surgiu outro se puder me ajudar eu agradeço !                        http://pt.stackoverflow.com/questions/154431/manter-os-dados-em-uma-variavel-da-primeira-act-apos-voltar-da-segunda-act-pelo
Answer: Você tem que explorar o ciclo de vida da sua Activity utilizando o onResume(). Teria que colocar sua busca novamente dentro do método.
@Override
public void onResume(){
    super.onResume();
    // coloque sua busca novamente aqui

}

Ciclo de vida
Conforme o usuário navega, sai e retorna para o seu aplicativo, as instâncias Activity no aplicativo transitam entre diferentes estados no ciclo de vida. Por exemplo, quando a atividade começa pela primeira vez, ela fica em primeiro plano no sistema e tem o foco do usuário.
Durante o processo, o sistema Android chama uma série de métodos do ciclo de vida na atividade, onde você define a interface do usuário e outros componentes. Se o usuário executa uma ação que inicia outra atividade ou alterna para outro aplicativo, o sistema chama outro conjunto de métodos do ciclo de vida em sua atividade conforme ela fica em segundo plano (onde a atividade já não está visível, mas a instância e seu estado permanecem intactos).

Detalhes

Como gerenciar o ciclo de vida da atividade
Pausando e reiniciando uma atividade
Answer: Faça seu cadastro na act2 e encerre a act2. Faça sua busca no onResume da act1 (o método deve ser chamado na activity mesmo, e ele é automaticamente chamado quando a tela se inicia ou quando uma outra tela sai de cima dela) e chame meuAdapter.notifyDataSetChanged(); (não se esqueça de preencher o adaptar com os novos dados) que o adaptador sozinho vai se atualizar. (tudo no onresume).
@Override
public void onResume(){ // escreva esse método na act1
    super.onResume();
    // Código da busca
    meuAdapter.notifyDataSetChanged();
}

O interessante é que, quando voce faz isso no onResume, toda vez que a act1 abre, o onResume vai ser executado sozinho. Então não precisa reescrever o código de busca no onCreate.
Comment: muito obrigado esse problema eu consegui resolver, porem surgiu outro se puder me ajudar eu agradeço !                        http://pt.stackoverflow.com/questions/154431/manter-os-dados-em-uma-variavel-da-primeira-act-apos-voltar-da-segunda-act-pelo

Como recarregar uma activity


Fixing Multi-site files path

Question: I have two separate fully developed Drupal 7 sites, which I now want to make as Multi-site.

I did it like in the above pic, and it worked, except all the images on both sites are broken.
Upon inspecting element, the paths are still trying to read from /sites/default/files folder instead of /sites/site1.com/files and /sites/site2.com/files respectively.
How can I fix the paths so it reads from /sites/site1.com/files and /sites/site2.com/files?
Answer: You may be aware of this. Change file path for individual sites at Configuration/Media/File system. By default it is set to sites/default/files. So your both sites are addressing same path.

So just change the path there accordingly for both sites.
Comment: Looks like @NoSssweat is too much involved with D8, which results in forgetting how D7 works, no?

Fixing Multi-site files path


Disparar evento click com trigger não funciona como esperado

Question: Estou usando o plugin de Wordpress MetaSlider para slides, e nele é possível adicionar links para as imagens.
Criei um botão e preciso simular o click, como estivesse clicando na imagem ativa no momento no slider.
Estou usando o trigger para fazer a simulação, mas não consigo fazer o trigger funcionar.

        <?php
            echo do_shortcode("[metaslider id=135]");
        ?>

            <button class="button saiba-mais"> SAIBA MAIS </button>

Imagem do código gerado pelo plugin:

Script:

Comment: Quer dizer que o seletor estava errado?
Comment: Era a posição da variavel target que estava faltando. Como é retornado um objeto, a URL é a primeira posição.
Comment: A unicas coisa que você mudou foram o seletor para `".flex-active-slide a"` e extraiu o target de um objeto jquery para dom usando `[0]`. Não entendi a "posição da variavel"
Comment: Me expressei errado. É que o retorno é um objeto, e o primeiro elemento é o link, então eu passo a posição [0]. Alterei os seletores para não fica grande, mas eles existem, são gerados pelo plugin MetaSlider.
Comment: Você quer dizer que trocar `target.trigger("click");` por que fez a diferença `target[0].click();`?


How to iframe a web page on a sharepoint site?

Question: I've a website and a team services sharepoint site, both authenticating against the same corporate active directory. I want to embed a page from my website in an iframe on a page in my sharepoint site.
I got the following error message:

This content cannot be displayed in a frame. To help protect the
  security of information you enter into this website, the publisher of
  this content does not allow it to be displayed in a frame. You can
  try: Open this page in a new window

I found a stackoverflow answer that says adding the meta tag
<code><meta http-equiv="X-Frame-Options" content="allow"/>
</code>
in the page that needs to be go within the iframe will do it, and I've tried this, but it does not work. Why is this so? What am I missing/doing wrong here?
When opening in the new window, it works fine, but iframing would be really ideal, so that is the question I have been looking for.
Answer: The X-Frame-Options: SAMEORIGIN" response header prevents the browser from displaying iFrames that are not hosted on the same domain as the parent page. Maybe your site responses that way and thats the reason for "the publisher of this content does not allow it to be displayed in a frame" If you got any chance to prevent sending the X-Frame-Option it will work.
Comment: How do I check if my site is sending this response? And how do I prevent it?


Why metrizable group requires continuity of inverse?

Question: A metrizable group is a metric space $(G,d)$ with a binary operation $\cdot$ such $(G,(\cdot))$ is a group and maps $(\cdot):G\times G\to G$ and $f:G\to G$ given by $(\cdot)(x,y)=xy$ and $f(x)=x^{-1}$ are continuous respect $d$.
Why requires definition that $f$ be continuous? Is it possible to have continuity of $(\cdot)$ without continuity of $f$?
Comment: (i) Actually, formally a group is defined by *three* operations: a binary operation (the product), a *unary* operation (inversion), and a *nullary* operation (the identity element). (ii) Are you asking whether the continuity of inversion follows from continuity of the product?
Comment: I don't understand your last sentence.  Of course, $y^{-1}$ exists; the question is whether the inversion map is continuous.
Comment: Yes, they are "related", but are they "related" enough that the continuity of the binary operation implies the continuity of the inversion map?  I think the answer is no although I don't have a counterexample at hand.
Comment: @GastónBurrull: First, no, they don't "induce new operations". They are **part of the definition** of a group when you describe a group as an algebra. Second: the point is that if you really want to define a topological group, you need to consider *all* operations as functions; the inverse function cannot be expressed that way in terms of the product function alone (you need existential quantifiers to describe it). The nullary function is continuous because it is constant, so you don't need to put conditions on it.  So your question is *really* "does continuity of $\cdot$ imply that of $f$?"
Comment: But.. inverses are related with the binary operation, I don't know why need an aditional condition.
Comment: @ArturoMagidin of course, identity continuity follow from product ontinuity, do you say that existence of inverses and null elements induces a new opration?. I think that it is right but I didn't see with this point of view. Thanks!

Why need continuity of inverse, not enought with product (and identity  induced by product)?
Comment: @ArturoMagidin Yes, you're right. The other question have not sense. I dont know a counterexample when we have continuity of $\cdot$ and $f$ is discontinuous in some point. I saw that continuity of product implies continuity of identity, but is because definition of group we dont need continuity of binary operation to conclude continuity of identity as you said.
Comment: @GastónBurrull: Perhaps you could edit the question and clarify it, then, so people don't have to dig through the comments to find the explanations?
Answer: I made a mistake here before. Sorry!
Continuity of multiplication is not sufficient for general topological groups.
Consider the standard additive group of reals with Sorgenfrey topology.
Inverse is clearly not continuous, since $-[a,b)=(-b,-a]$.
Multiplication (or, rather, addition) is continuous, since, intuitively, the open sets in the product topology are the sets which do not have "upper" and "right" edge (but may possibly have "left" and "lower" edge, or some parts of those). More precisely, for any $x+y=c\in [a,b)$, then let $0<\varepsilon<(b-c)/2$. Then for any $(x',y')\in [x,x+\varepsilon)\times [y,y+\varepsilon)$, $a\leq x+y\leq x'+y' <x+y+\varepsilon<b$, so $(+)^{-1}[a,b)$ is open.
EDIT:
I found an example in Topological Groups and Related Structures by Archangel'skii & Tkachenko, example 3.5.6 on pages 175-176. It is the group of homeomorphisms of the space $\lbrace n,0,1/n\mid n\in \mathbf N\rbrace$ with the natural topology, the compact-open topology.
It is metrizable, but not metrizable by a left- or right- invariant metric, and the inverse is not continuous.
Comment: To follow up on André's comment, continuity of inversion follows from continuity of multiplication in quite some generality by a Baire category argument, e.g. for locally compact Hausdorff or completely metrizable spaces with a group structure such that multiplication is (separately) continuous: Pfister, *[Continuity of the inverse](http://dx.doi.org/10.1090/S0002-9939-1985-0801345-5)*, Proc. Amer. Math. Soc. **95** (1985), 312-314 contains the best results in this direction I'm aware of.
Comment: @Gastón: No, metrizability is not a sufficient condition for continuity of the multiplication to imply continuity of the inversion. tomasz made an edit to the answer giving a reference to a counterexample.
Comment: I think things are OK for completely metrizable spaces. Forget where I saw it.
Comment: I need more time to full understand your answer.

I'll acept when I'll totally sure. Thanks!
Comment: @t.b. Thanks a lot!!. Must you mean that be metrizable is not sufficient condition?.
Answer: Take $G=\mathbb R$ with addition and put on it the topology which has the set $\{(-\infty,a):a\in\mathbb R\}$ as a basis. Then addition is continuous but inversion is not.
You want it metrizable, though...


How can i find out when the next cron will run?

Question: How can i find out programmatically when the next cron will run in order to present it to the author scheduling stuff?
i am using ultimate cron and an external cron process.
Comment: What software are you using to make cron run happen? Built in mechanism once called "poor man's cron"? External cron?
Comment: I am agree with @Mołot, though you can get last cron run time.
Comment: @RajeevK - it's nice to know, sometimes, but it's useless for content authors. Like "We don't know when what you added will be visible, but last time we synced was an hour ago" - frustrating.
Comment: Ultimate Cron handles cron runs, it does not trigger them. If you are not using any other tools, see first case of my answer.
Comment: @Mołot Though I have never worked with cron much except declaring my own work for cron in module, but I knew we can get the last time when it ran. Somethings are really frustrating, should look simple but take days to make it work according to us :)
Comment: @RajeevK I didn't disagree with you, all I meant to say is yes, you can know last time, but it's of no use for OP here, sadly.
Answer: Basically, you cannot.
If you are using Drupal 7 built-in CRON triggering method, in Drupal 6 Poormanscron module, CRON run depends on the availability of visitor. If no one visits your page, CRON will not run. Drupal can't predict if or when visitor will appear, so the best you can know is when CRON will not yet run anyway, even if visitor is available.
If you are using external tools, Drupal has no way to predict if and how they will trigger it. It will accept all proper request, so you know even less than in the first case. Even if you know when it is supposed to run, you don't know time difference between servers, as it is subject to change slightly. You don't know the lag between a moment when CRON should happen and when it will, as practically no web servers are hosted on real time operating systems, so there are no guarantees about maximum time between action request and it's execution. In simpler words, server can postpone CRON task if it's to loaded, sometimes even skip it.
If you need predictable and reliable cron, go to http://example.com/admin/config/system/cron, find URL described as "To run cron from outside the site, go to". Then, mail your server administrator and ask him to add this to server's crontab:
*/5 * * * * wget -O - -q -t 1 http://www.example.com/cron.php?cron_key=yourcronkeyrandomstring

This will make your site's CRON run every 5 minutes, and you shouldn't need to know when exactly - it's ofthen enough for most tasks. If it's not, make it */2 to run it every 2 minutes, or just leave * at every position to get it triggered each and every minute. You can read more about system's CRON configuration on Wikipedia. Of course it will not allow Drupal to know, it will just free you from the need to know.
Comment: Good answer. I'd go so far as to say that if you're trying to predict when a cron run is going to happen, you've either got something wrong in your application design, or you're not running cron often enough
Comment: I agree. On largest projects we were using */5 minutes external cron and Elysia Cron to limit tasks we didn't need quite that often. Worked like a charm.
Comment: In OP I'm assuming "external cron process" means cron is being kicked off at regular intervals by crontab or something.
Comment: @JohnathanElmore First, it was edited only after my answer. Second, it means it is **supposed to be** kicked at regular intervals, not that it actually **is**.
Answer: The easiest method here (though by no means a good, reliable one) is to set up the cron job to run at a known time (let's say hourly, on the hour) and then take that knowledge back to Drupal where you can do something low-tech like
$minutes_left_until_next_cron = 60 - date('i', REQUEST_TIME);

Of course this relies on things like the web server and external cron servers' system times being synced correctly, and isn't really an elegant solution. But, it'll do in a pinch.
Comment: Yes, in an ideal world, where the interval is a standard value... thanks!
Comment: Only problem with that is `cron_last` gets set _after_ a potential 3 minute long cron run. When you invoke a cron at 10:59, and it records cron_last as 11:02, that method would be an hour out-of-whack. But I'm just being petty (as we programmers oh so love to be ;)
Comment: @Clive - Ultimate and Elysia logs start time too. Both ways of guessing have their ups and downs, constant error equal to servers ΔT, theoretically up to an hour, or small error occasionally going huge, to an hour. Readers will need to choose problems they prefer from these methods ;)
Comment: It'll give good guess, not knowledge. I guess in my answer I should have accepted that for most people good guess is acceptable.
Comment: @Clive - to avoid sync problem, use `variable_get('cron_last');` If it;s supposed to happen every hour, make it `(60 + $cron_last - $minute_now)%60`. That way, if ΔT is constant, prediction will be a bit better, and only assumption needed is how often cron runs, not at what minute in an hour.


Metric balls with finite perimeter

Question: I have a couple of questions of the same nature related to the perimeters of metric balls in $\mathbb{R}^n$. By perimeter, I mean the notion of perimeter reffered by the Caccioppoli definition, i.e. the perimeter of $E \subseteq \mathbb{R}^n$ in an open set $\Omega$  is the total variation of its characteristic function on that open set.

Must the metric ball $B_d(x, \delta) \subseteq \mathbb{R}^n$ have finite perimeter for any distance function $d$?
Same question, but this time $d$ being a distance induced by a norm $\|\cdot\|$ on $\mathbb{R}^n$.
Comment: This isn't my area, but I just wanted to say, you can choose any non-empty $\Omega \subseteq \Bbb{R}^n$ you wish, and there exists a metric whose open ball (or closed ball) is equal to this $\Omega$. All you do is define$$d(x, y) = \begin{cases} 0 & \text{if } x = y \\ 1 & \text{otherwise if }x, y \in \Omega \\ 2 & \text{otherwise.} \end{cases}$$and any (open or closed) ball of radius $1.5$ centred in $\Omega$ is equal to $\Omega$. I would imagine that this answers your first question in the negative, but I can't be sure.
Comment: That's a good point! I had the intuition that the first question should be false. After your comments, I was looking for a similar result for a norm $\| \cdot \|$. Any closed ball in $\mathbb{R}^n$ is convex (https://math.stackexchange.com/questions/137738/proving-that-closed-and-open-balls-are-convex). Conversely, any bounded, open, convex, and the centre symmetry set having centre at 0 will induce a norm (https://math.stackexchange.com/questions/137738/proving-that-closed-and-open-balls-are-convex). This might help answer the second point.
Answer: Fix a norm $|\cdot| : \mathbb{R}^{d} \to [0,\infty)$ on $\mathbb{R}^{d}$.  Recall that $\|\cdot\|$ is equivalent to the Euclidean norm $\|\cdot\|$, that is, there is a $C > 1$ such that
\begin{equation*}
C^{-1} \|v\| \leq |v| \leq C\|v\| \quad \text{if} \, \, v \in \mathbb{R}^{d}.
\end{equation*}
Hence $v \mapsto |v|$ is Lipschitz as $||w| - |v|| \leq |w - v| \leq C\|w - v\|$.  By the co-area formula,
\begin{equation*}
\int_{\{y \in \mathbb{R}^{d} \, \mid \, |y| \leq 1\}} \|D|\cdot|(x)\| \, dx = \int_{0}^{1} P(\{y \in \mathbb{R}^{d} \, \mid \, |y| = r\}) \, dr
\end{equation*}
Hence there is an $r \in (0,1)$ such that $P(\{y \in \mathbb{R}^{d} \, \mid \, |y| = r\}) < \infty$.  At the same time, for any $s > 0$, we have
\begin{equation*}
P(\{y \in \mathbb{R}^{d} \, \mid \, |y| = r\}) = P(r s^{-1} \{y \in \mathbb{R}^{d} \, \mid \, |y| = s\}) = (r s^{-1})^{d-1} P(\{y \in \mathbb{R}^{d} \, \mid \, |y| = 1\}).
\end{equation*}
Thus, the $|\cdot|$-ball centered at the origin has finite perimeter, no matter the radius.  Perimeter is translation-invariant, though, so any ball has finite perimeter, no matter the center or the radius.
Another proof I can think of uses the fact that if $C_{1}, C_{2}$ are convex sets and $C_{1} \subseteq C_{2}$, then $P(C_{1}) \leq P(C_{2})$: see here, for instance.  I suspect there are other easier proofs.
Edit:  It's worth remarking that the argument above shows any convex set $C$ has locally finite perimeter.
First, note that if $C$ has empty interior, then it is contained in an affine hyperplane.  In this case, $C$ has Lebesgue measure zero so it trivially has finite perimeter.  We assume henceforth that $C$ has nonempty interior.
Note that if $C$ is convex, then $\text{int}(C)$ is also convex.  Let us show, then, that open convex sets have locally finite perimeter.
One concludes by arguing that $C \setminus \text{int}(C)$ has zero Lebesgue measure.
Fix $x_{0} \in C$ and $R > 0$ arbitrary.  Define the Minkowski gauge $\psi_{R}$ by
\begin{equation*}
\psi_{R}(y) = \inf \left\{ \alpha \, \mid \, \alpha^{-1} y \in (C - x_{0}) \cap B(0,R) \right\}.
\end{equation*}
It is well-known (see, for example, Brezis's functional analysis textbook) that $\psi_{R}$ is a Finsler norm: it is convex and one-homogeneous.  (It satisfies all the hypotheses of a norm, except for symmetry.)  In particular, as in the case of a genuine norm, $\psi_{R}$ is Lipschitz.
Arguing as above, we see that $\{y \in \mathbb{R}^{d} \, \mid \, \psi_{R}(y) = s\}$ has finite perimeter for each $s \in (0,\infty)$.  Translating (and setting $s = 1$), this implies that $C \cap B(x_{0},R)$ has finite perimeter.  Given that this is true for all $R > 0$, we conclude $C$ has finite perimeter.
(Other proofs might be shorter, but recently I find working with gauges makes proving things easier.)
Comment: Thank you, that's really helpful ! I have also come across an argument proving that a convex set must have locally finite perimeter (https://mathoverflow.net/questions/355693/every-convex-set-is-of-locally-finite-perimeter). Since in $\mathbb{R}^n$, closed balls induced by a norm are convex and compact, I guess we can deduce that they are also of finite perimeter.
Comment: That claim --- convex sets have locally finite perimeter --- is related to your question about norms.  I added an edit explaining why.

Metric balls with finite perimeter


What is the problematic part in finding the center of mass of one eight of a sphere in this construction?

Question:
Find the centre of mass of that portion of homogeneous hemispherical
  surface $x^2 + y^2 + z^2 = a^2$ lying above the first quadrant in the
  xy-plane

I did the necessary calculation and the transformations of the axis to the spherical coordinates and last step was the following:
$$\vec{r}_{cm} = \frac{\int_0^{\pi/2} \int_0^{\pi/2} [(\sin\phi \cos\theta)\hat x + (\sin\phi \sin\theta )\hat y + (\cos\phi)\hat z ] a^3 \sin\phi d\phi d\theta}{\frac{\pi a^2}{2}}$$
The x and the y coordinates of $\vec{r}_{CM}$ are correct, but not the z coordinate.I mean with this construction r becomes
$$\vec{r}_{CM}=a/2 (\hat x + \hat y) + 2a(\hat z).$$
I couldn't find where is my mistake.
Comment: Your integral corresponds to the region $0\leq\theta\leq\pi/2$, $0\leq\phi\leq\pi/2$. Have you drawn out that region?
Comment: @StevenStadnicki Yes, as far as I see, there is still no problem in that.
Comment: Ahh, I see. (The title of your question says 'one quarter of a sphere', but it looks like the body refers to an eighth, the positive xyz octant?)
Comment: @StevenStadnicki You are right, I mix then up.Thanks for pointing out
Comment: Your integral for the center of mass is wrong.  You've 'popped out' $\hat{x}$, etc. but those aren't constant vectors; they depend in an essential way on $\rho, \theta, \phi$ and that needs to be accounted for in your integration.
Comment: @StevenStadnicki I constructed my setup by assuming they they are constant unit vectors.
Answer: The problem setup looks fine; I would just check the arithmetic at each step.
For the $z$ coordinate, we first have
$$\int_0^{\pi/2} (\cos\phi) a^3 \sin\phi\, d\phi = \frac12a^3.$$
Next,
$$\int_0^{\pi/2}  \frac12a^3 = \frac{\pi a^3}{4}.$$
Finally,
$$\frac{\pi a^3/4}{\pi a^2/2} = \frac a2.$$


How to desctructure an object to this

Question: Here's how destructuring works:
let o = {a:0, b:1};
let {a, b} = o;
console.log(a,b);

How do I assign properties a, b to this?
In a situation like this, for example:
class myClass {
    constructror(){
        this.a = null;
        this.b = null;
    }
    myMethod(o){
        //destructure o here, so that 'this' was assigned a and b
    }
}
const o = {a:0, b:1};
const myInstance = new myClass();
myInstance.myMethod(o);

Comment: @AndrewLi, sorry, added some missing parts
Answer: let o = {a: 0, b: 1};
Object.assign(this, o);

Comment: Not really. By deconstructing the object, you're splitting the values into separate variables, which then must each be assigned to `this`.
Comment: Thank you, it works for me, but I was thinking if there was syntax something like `this {a, b} = o;`

How to desctructure an object to this


Dficuldade para tratar uma lista com JavaScript

Question: Estou com uma dificuldade de tratar um lista pelo javascript gostaria de uma dica ou ajuda se possível
esse é o erro que estou tomando

Array [ "AC.FIXA" ]  cadastro:280:4
  ReferenceError: $ is not defined[Learn More]  cadastro:282:4
  String vazia passada para getElementById(). cadastro
  String vazia passada para getElementById(). cadastro

e meu javascript

pelo que li por cima diz que meu jQuery não esta instalado, mas está tudo correto.
Comment: Cadê a parte que você referencia o jQuery na página?
Comment: pelo codigo que voce postou o erro nao esta acontecendo nessa parte, porque nao tem nenhum getElementByID no seu codigo mas o erro vem dali (e tb acho que o jQuery nao foi referenciado)
Comment: aqui esta o código acima com a referencia do jQuery
Comment: se o jquery esta instalado corretamente você pode não ter referenciado ele no seu HTML por exemplo, algo assim ``
Comment: pois é cara mais eu referenciei ele na pagina normal
Answer: Primeiramente, verifica os ; no final das linhas.
Seguindo, acrescenta o jQuery logo acima do teu script e verifica se o erro persiste, assim:


Clang failed with exit code 1 error in objective-c

Question: what is this error.. I'm trying to converting a non-ARC project to arc project and error is showing  Command /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang failed with exit code 1
ProcessPCH /Users/amit/Library/Developer/Xcode/DerivedData/Corlocation-gfdftvxjfdzkejebtysirafavnmv/Build/Intermediates/PrecompiledHeaders/Corlocation-Prefix-fjwexhbcqsylinfenhkyculomcng/Corlocation-Prefix.pch.pth Corlocation/Corlocation-Prefix.pch normal i386 objective-c com.apple.compilers.llvm.clang.1_0.compiler
    cd "/Users/amit/Desktop/My Apps/Corlocation"
    setenv LANG en_US.US-ASCII
    setenv PATH "/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin:/Applications/Xcode.app/Contents/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin"
    /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang -x objective-c-header -arch i386 -fmessage-length=0 -std=gnu99 -fobjc-arc -Wno-trigraphs -fpascal-strings -O0 -Wno-missing-field-initializers -Wno-missing-prototypes -Wreturn-type -Wno-implicit-atomic-properties -Wno-receiver-is-weak -Wduplicate-method-match -Wformat -Wno-missing-braces -Wparentheses -Wswitch -Wno-unused-function -Wno-unused-label -Wno-unused-parameter -Wunused-variable -Wunused-value -Wempty-body -Wuninitialized -Wno-unknown-pragmas -Wno-shadow -Wno-four-char-constants -Wno-conversion -Wno-shorten-64-to-32 -Wpointer-sign -Wno-newline-eof -Wno-selector -Wno-strict-selector-match -Wno-undeclared-selector -Wno-deprecated-implementations -DDEBUG=1 -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator6.0.sdk -fexceptions -fasm-blocks -Wprotocol -Wdeprecated-declarations -g -Wno-sign-conversion -fobjc-abi-version=2 -fobjc-legacy-dispatch "-DIBOutlet=__attribute__((iboutlet))" "-DIBOutletCollection(ClassName)=__attribute__((iboutletcollection(ClassName)))" "-DIBAction=void)__attribute__((ibaction)" -mios-simulator-version-min=6.0 -iquote /Users/amit/Library/Developer/Xcode/DerivedData/Corlocation-gfdftvxjfdzkejebtysirafavnmv/Build/Intermediates/Corlocation.build/Debug-iphonesimulator/Corlocation.build/Corlocation-generated-files.hmap -I/Users/amit/Library/Developer/Xcode/DerivedData/Corlocation-gfdftvxjfdzkejebtysirafavnmv/Build/Intermediates/Corlocation.build/Debug-iphonesimulator/Corlocation.build/Corlocation-own-target-headers.hmap -I/Users/amit/Library/Developer/Xcode/DerivedData/Corlocation-gfdftvxjfdzkejebtysirafavnmv/Build/Intermediates/Corlocation.build/Debug-iphonesimulator/Corlocation.build/Corlocation-all-target-headers.hmap -iquote /Users/amit/Library/Developer/Xcode/DerivedData/Corlocation-gfdftvxjfdzkejebtysirafavnmv/Build/Intermediates/Corlocation.build/Debug-iphonesimulator/Corlocation.build/Corlocation-project-headers.hmap -I/Users/amit/Library/Developer/Xcode/DerivedData/Corlocation-gfdftvxjfdzkejebtysirafavnmv/Build/Products/Debug-iphonesimulator/include -I/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include -I/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include -I/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include -I/Users/amit/Library/Developer/Xcode/DerivedData/Corlocation-gfdftvxjfdzkejebtysirafavnmv/Build/Intermediates/Corlocation.build/Debug-iphonesimulator/Corlocation.build/DerivedSources/i386 -I/Users/amit/Library/Developer/Xcode/DerivedData/Corlocation-gfdftvxjfdzkejebtysirafavnmv/Build/Intermediates/Corlocation.build/Debug-iphonesimulator/Corlocation.build/DerivedSources -F/Users/amit/Library/Developer/Xcode/DerivedData/Corlocation-gfdftvxjfdzkejebtysirafavnmv/Build/Products/Debug-iphonesimulator fno-objc-arc --serialize-diagnostics /Users/amit/Library/Developer/Xcode/DerivedData/Corlocation-gfdftvxjfdzkejebtysirafavnmv/Build/Intermediates/PrecompiledHeaders/Corlocation-Prefix-fjwexhbcqsylinfenhkyculomcng/Corlocation-Prefix.pch.dia -c "/Users/amit/Desktop/My Apps/Corlocation/Corlocation/Corlocation-Prefix.pch" -o /Users/amit/Library/Developer/Xcode/DerivedData/Corlocation-gfdftvxjfdzkejebtysirafavnmv/Build/Intermediates/PrecompiledHeaders/Corlocation-Prefix-fjwexhbcqsylinfenhkyculomcng/Corlocation-Prefix.pch.pth -MMD -MT dependencies -MF /Users/amit/Library/Developer/Xcode/DerivedData/Corlocation-gfdftvxjfdzkejebtysirafavnmv/Build/Intermediates/PrecompiledHeaders/Corlocation-Prefix-fjwexhbcqsylinfenhkyculomcng/Corlocation-Prefix.pch.d

clang: error: no such file or directory: 'fno-objc-arc'
Command /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang failed with exit code 1

Answer: you are use the fno-objc-arc that's a command line argument, you probably need to prefix it with a hyphen, such as with:
Replace fno-objc-arc to -fno-objc-arc
Answer: fno-objc-arc should be -fno-objc-arc and is used to turn off ARC for the file, so there is obviously a mistake in your Xcode project settings.
See the screenshot in this SO question for details of where this is set.


change color of button on click and push it into array using javascript

Question: I am trying to change color of button to see that button is selected. When button is select the value of button is push in to array. If I again click on selected button the selected button will become unselected and new color of button will be removed also this button's value is remove from array.
I have total 40 buttons. I made a demo.
Here is my Link
JSFiddle snippet
<code>function ctrl($scope) {
$scope.tooth=[];
var count=0;
$scope.setTooth = function(event,code) {

    if($scope.tooth.indexOf(code) > -1){
        alert("hiii");
        $scope.styleO = "styleOne";
        $scope.tooth.splice($scope.tooth.indexOf(code), 1);
        //$scope.tooth.push();
    }else{
         $scope.tooth[count]=code;
         alert("hello");
        $scope.styleT = "styleTwo";
    }
}
$scope.setQuadrantsTeeth = function(quadarent){

}
}
</code>
Thanks in advance.
Answer: I will leave the pushing and splicing from array upto you.
But as far applying style 1 and 2 is concerned why don't you do this?
<code>        $("button").click(function(){
         if($(this).hasClass("styleOne")){
          $(this).removeClass("styleOne");
          $(this).addClass("styleTwo");
         } else if($(this).hasClass("styleTwo")) {
          $(this).removeClass("styleTwo");
         } else if(!($(this).hasClass("styleTwo") || $(this).hasClass("styleOne"))){
          $(this).addClass("styleOne");
         }
        });
</code>


Order by SQL Server em Procedure

Question: Olá,
Estou com a seguinte situação:
Preciso selecionar a quantidade de atendimento de pessoas de algumas faixas etárias e dessas quantos são masculinos e femininos.
Tenho a seguintes tabelas:
cadastro (id, natendimento, data, sexo, fokfaixaetaria) e faixaetaria (id, nomefaixaetaria) a tabela cadastro possui a coluna faixaetaria que é chave estrangeira de faixaetaria. Atualmente estou com a seguinte consulta:
CREATE PROCEDURE [dbo].[SELECIONAR_NUMERO_ATENDIMENTOS]
@DATAINICIO DATETIME,
@DATAFIM DATETIME
AS

SELECT

faixaetaria.nomefaixaetaria AS FaixaEtaria,
COUNT(case when sexo = 'Masculino' then 1 end) AS Masculino,
COUNT(case when sexo = 'Feminino' then 1 end) AS Feminino,
COUNT(fokfaixaetaria) AS Total

from cadastro
left join faixaetaria on faixaetaria.id = cadastro.fokfaixaetaria

WHERE data_dte_cadastro BETWEEN @DATAINICIO AND @DATAFIM
GROUP BY
faixaetaria.nomefaixaetaria

Porém durante a consulta ela não vem organizada de acordo com a faixa etária,ou seja, queria que viesse 0 a 3 - tantos masculinos tantos femininos e total,
4 a 6 - tantos masculinos tantos femininos e total,
7 a 12 - tantos masculinos tantos femininos e total,
tudo na sequência. Isso não acontece ele agrupa de acordo com o que vem primeiro da minha tabela cadastro. Acredito que ai deva ter um order by só que não estou conseguindo colocá-lo.
Tabela faixaetaria:

Execução da Query:
Comment: consegue enviar uma imagem de como a consulta está retornando?
Comment: @JeanGustavoPrates a primeira imagem é da tabela faixaetaria a segunda é o resultado da consulta eu apenas gostaria que ficasse em ordem mas não na ordem de como elas são cadastradas na tabela cadastro e sim por uma questão de estética ficar em ordem igual como está na tabela faixaetaria, isso facilita em um relatório que irei fazer, só que não consigo colocar o order by no sql dá erro após o group by: `O nome de coluna "faixaetaria.id" é inválido na cláusula ORDER BY porque não está contido em uma função de agregação nem na cláusula GROUP BY.`
Answer: Não precisas de criar uma subquery. O SQL Server permite incluir no GROUP BY colunas que não aparecem na instrução SELECT. Basta adicionar a coluna id no GROUP BY e fazer a ordenação usando a nova coluna incluida no GROUP BY.
CREATE PROCEDURE [dbo].[SELECIONAR_NUMERO_ATENDIMENTOS]
@DATAINICIO DATETIME,
@DATAFIM DATETIME
AS

SELECT faixaetaria.nomefaixaetaria AS FaixaEtaria,
       COUNT(case when sexo = 'Masculino' then 1 end) AS Masculino,
       COUNT(case when sexo = 'Feminino' then 1 end) AS Feminino,
       COUNT(fokfaixaetaria) AS Total

FROM cadastro
LEFT JOIN faixaetaria
  ON faixaetaria.id = cadastro.fokfaixaetaria

WHERE data_dte_cadastro BETWEEN @DATAINICIO AND @DATAFIM
GROUP BY faixaetaria.nomefaixaetaria, faixaetaria.id
ORDER BY faixaetaria.id

Em resposta ao comentário, sim é possível. Basta, por exemplo fazer
CREATE PROCEDURE [dbo].[SELECIONAR_NUMERO_ATENDIMENTOS]
@DATAINICIO DATETIME,
@DATAFIM DATETIME
AS

SELECT faixaetaria.nomefaixaetaria AS FaixaEtaria,
       COUNT(case when sexo = 'Masculino' then 1 end) AS Masculino,
       COUNT(case when sexo = 'Feminino' then 1 end) AS Feminino,
       COUNT(fokfaixaetaria) AS Total

FROM faixaetaria
lEFT JOIN cadastro
  ON cadastro.fokfaixaetaria = faixaetaria.id
 AND data_dte_cadastro BETWEEN @DATAINICIO AND @DATAFIM
GROUP BY faixaetaria.nomefaixaetaria, faixaetaria.id
ORDER BY faixaetaria.id

Para incluir no conjunto de resultados um registo com o total podes usar o ROLLUP/GROUPING SETS fazendo o seguinte
CREATE PROCEDURE [dbo].[SELECIONAR_NUMERO_ATENDIMENTOS]
@DATAINICIO DATETIME,
@DATAFIM DATETIME
AS

SELECT CASE WHEN GROUPING(faixaetaria.nomefaixaetaria) = 1 THEN 'Total geral' ELSE faixaetaria.nomefaixaetaria END AS FaixaEtaria,
       COUNT(case when sexo = 'Masculino' then 1 end) AS Masculino,
       COUNT(case when sexo = 'Feminino' then 1 end) AS Feminino,
       COUNT(fokfaixaetaria) AS Total

FROM faixaetaria
LEFT JOIN cadastro
  ON cadastro.fokfaixaetaria = faixaetaria.id
 AND data_dte_cadastro BETWEEN @DATAINICIO AND @DATAFIM
GROUP BY GROUPING SETS((faixaetaria.nomefaixaetaria, faixaetaria.id),())
ORDER BY ISNULL(faixaetaria.id, 99)

Comment: Obrigado deu certo! Não tinha percebido a não existência da cláusula Where.
Comment: sua solução é bem simples!
Comment: Seria possível na consulta acima, trazer todas as faixas etarias da tabela faixaetaria mesmo que não tenham informações na tabela cadastro? e setar 0 para ambos os sexos e total?
Comment: Não deu certo ele somente trás os valores que estão na tabela cadastro.
Comment: Tem a certeza? Repara que na minha segunda query, estou a seleccionar todos os registos da tabela faixaetaria. A primeira e a segunda query têm uma base diferente: na segunda estou a seleccionar tudo da tabela faixaetaria, independentemente se está na tabela cadastro ou não.
Comment: Repara também que já não existe cláusula Where. Isto é importante para não excluir registos da tabela faixaetaria que não existem na tabela cadastro.
Comment: Mas uma dúvida, se eu quisesse somar os valores da tabela total e exibir em uma única coluna apenas a soma de todos os valores da tabela total como posso fazer? Estou fazendo da seguinte forma mas não está dando certo ele repete e trás valores errados: `SUM(fokfaixaetaria) AS TotalGeral` Dento da consulta acima conforme você me passou.
Comment: Vamos [continuar esta discussão no chat](http://chat.stackexchange.com/rooms/27724/discussion-between-bruno-and-coreid).

Order by SQL Server em Procedure


Holomorphic functions and functions which coincides

Question: I have a problem in which I have to find a non-constant function on $\mathbb{C} $ such that it has no zeros. That's clear, because the function $f(z)=e^z$, or more generally $f(z)=e^{g(z)}$ with $g(z)$ an entire number, has no zeros.
But the problem comes now. I am asked to find an holomorphic function also on $\mathbb{C}$ which coincides with $f$ on the disc $D(0,1)$, but is zero outside of $D(0,2)$.
My guess:
I think the function $h(z)=\sum \frac{z^n}{n!}$, which is the series expansion of the exponential function, coincides in the disc $D(0,1)$ with $f$ (Well, I'm not sure if I can use it, because, in fact, is the same function, doesn't it?)
But, I cannot find a function which matches the both criteria (coincides with $f$ in the unit disc, but it zero outside $D(0,2)$).
Comment: Only one holomorphic (analytic) function coincides with the zero function, that's the [identity theorem](https://en.wikipedia.org/wiki/Identity_theorem).
Comment: this translates to 'mission impossible' :-)
Comment: @Dr.MV how does this admit a nonconstant extension to $\mathbb{C}$ without zeros?
Comment: It doesn't.  The only analytic extension of $0$ is $0$
Answer: Say I have a function, holomorphic on $\Bbb{C}$ and $0$ outside the disk $D(0,2)$.  Then its modulus is a continuous function, particularly on the closed disk $\overline{D(0,3)}$.  This disk is compact, so the modulus attains a maximum, $M$, on that disk.  Then the function is bounded on $\Bbb{C}$ (by $\max\{M,0\}$).  By Liouville, it's constant.  We know it takes the value $0$, so the function is identically $0$.
Comment: So, as stated in the comments, it is impossible, isn't it?
Comment: @rdguez : Yes.  Impossible.


mobile backend starter listbykind error

Question: I am creating a new entity kind in the datastore (named "xyz"), Sending the data works fine. and I see a record created under the new kind on cloud dasboard however, when I try to read it using
mProcessingFragment.getCloudBackend().listByKind( "xyz", CloudEntity.PROP_CREATED_AT,
Order.DESC, 50, Scope.FUTURE_AND_PAST, handler);

I get an error saying "SubscriptionIds: String property must be 500 chars or less. My send code is
CloudEntity newPost = new CloudEntity("xyz"); newPost.put("message",
mMessageTxt.getText().toString());

As you can see all I have done is replacing "Guestbook" by "xyz", I do not understand why I get the above error. Do I need to change the entity type I subscribe to?
ANy suggestions? Thanks
Answer: I am not sure if it is too late for this. I had the same problem which I managed to resolve by going to the appspot backend (*.appspot.com) and click the "Clear all query subscriptions".
Initially, it seems that I was unable to change the kindName on the listByKind where I will get the same error like you. However, after clearing the query subscriptions, I was able to change the kindName in the listByKind to anything. I am still about to figure out why this is the case. Perhaps there is a limit on the number of active subscriptions? I will do more testing today.
Anyway, hope this solves your issue.
Answer: Have a look at this thread Mobile Backend Starter subscribeToCloudMessage will not work
What worked for me was first clearning all query subscriptions as advised by Pascal on this thread and then doing what jamrockRay suggests, adding
.substring(0,16);

to this method is located in the GCMIntentService.java file
private static String doRegister(Context context) { String msg = "";
try { GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(context);
String regId = gcm.register(Consts.PROJECT_NUMBER).substring(0,16);
msg = "Device registered, registration ID=" + regId;

Worked for me

mobile backend starter listbykind error


Multi Conditional Probability of selecting balls

Question: My question is this; what is the probability of withdrawing at least one red ball and at least one blue ball from a bag with a certain number of attempts?
The requirements are, this bag has n number of balls, consisting of x-red balls, y-blue balls and z-green balls. The balls are placed back into the bag after being removed so the probability of any colour being withdrawn is constant.
In order to achieve a win at least one blue and at least one red ball must be withdrawn, e.g. if you only decide to make 3 withdrawals, then a win is one red ball, one blue ball and one ball of any colour.
My main question is, is there a formula that can be constructed to answer this question? If so what is that formula?
Answer: We first find the probability of failure, that is, the probability that we get no red, or no blue (this includes the possibility we get neither a red nor a blue).  Once we have that, the probability of success is easy to find. Let us suppose that we do the experiment $k$ times.
Let $A$ be the event we get no red in $k$ trials, and $B$ be the event we get no blue. We want $\Pr(A\cup B)$. Recall that in general
$$\Pr(A\cup B)=\Pr(A)+\Pr(B)-\Pr(A\cap B).\tag{1}$$
We find the probabilities on the right of (1).
The probability of no red in $k$ trials is $\left(\frac{n-x}{n}\right)^k$. The probability of no blue is  $\left(\frac{n-y}{n}\right)^k$.  And the probability of no red and no blue is $\left(\frac{n-x-y}{n}\right)^k$.
Now put the pieces together.
Comment: Thank you very much, the annoying thing was I answered this question myself about 2 years ago but I forgot the method I used to answer it.
Comment: You are welcome. It is annoying. However, things you once knew can be recovered fairly quickly. But it's not instantaneous.


Distance of ray reflection inside a unit cube

Question: There is a unit cube with internal mirror faces. A ray is  emitted into the cube from one vertex, reflects off four faces (without touching vertices or edges), and stops at the opposite vertex from which it started. What is the minimum possible distance the ray travels?
Comment: Can you explain how is it achieved? Thanks!
Answer: Suppose to watch the cube "from above", so that emitting vertex (red in diagram below) and receiving vertex are opposite vertices of a unit square. We can reflect this square about its sides, so that the light path is a straight line in this lattice. I represented in the diagram the shortest paths from the red point to one of the black points (which are reflections of the receiving vertex). Each horizontal reflection is represented by the path crossing one of the lines.
The blue path is the shortest one and has no reflections: that means the four reflections occur along the vertical. This path is identical with the black paths, which have four horizontal reflections and no vertical one. The other paths must be discarded, because they either have too many reflections (red paths) or hit a vertex/edge (violet and green paths). The case of the green path is not so obvious, but to make four reflections it has to include two vertical reflections and the only way is to travel a unit vertical distance at each step.

The only allowed path is represented below in 3D. It is made of five segments, each of length $\sqrt{1^2+(1/5)^2+(1/5)^2}=\sqrt{27}/5$. The total length is then $\sqrt{27}$.
Comment: This is awsome! Thanks for the clear explanation.
Answer: Well it could hit a face right below it by reflecting off the wall opposite it half way down. We consider a triangle with one side of length $1$ and the other side of length $\frac{1}{2}$. Applying the Pythagorean Theorem, the third side has
length $\frac{\sqrt{5}}{2}$. Since it has to reflect back, the answer I come up with is $\sqrt{5}$.
Bob
Comment: As the problem description, the ray cannot touch any vertices or edges.


Windows: How to forbid users modifying C

Question: In a school we have many Windows 7 client PCs and one 2008 R2 AD.
We have to make sure, that noone can modify the C drive exept the systemadministrators.
Is this possible without any third-party software?
Comment: `We have to make sure, that noone can modify the C drive exept the systemadministrators` - What do you mean "modify"? Make sure the users are standard users and not Administrators and you should be fine.
Answer: I think what you mean is to prevent users writing their own data to the C Drive and only having the C Drive for apps - no data.
You can do this through a GPO:
Computer Configuration > Windows Settings > Security Settings > File System:
In the pane on the right, right-click > Add File > Select the C Drive > Edit Permissions (for Database Security for %SystemDrive%)
Then deploy the GPO to the relevant OU of Computers.


Android AVD Won't Display Multiple Panes

Question: I'm learning about multi-pane apps and am running the Master/Detail Flow application that gets set up by Android Studio when you create a new project (and select this option). According to the comments within the Google code that gets created, the app should display in multi-pane mode for devices with large-screen layouts. The problem that I am having is that no matter what AVD I use, I only get a single pane. First, here is the onCreate method of the main activity. Please note that this code comes straight from Google (it isn't my code):
<code>protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_item_list);

        if (findViewById(R.id.item_detail_container) != null) {
            // The detail container view will be present only in the
            // large-screen layouts (res/values-large and
            // res/values-sw600dp). If this view is present, then the
            // activity should be in two-pane mode.
            mTwoPane = true;

            // In two-pane mode, list items should be given the
            // 'activated' state when touched.
            ((ItemListFragment) getFragmentManager()
                    .findFragmentById(R.id.item_list))
                    .setActivateOnItemClick(true);
        }

        // TODO: If exposing deep links into your app, handle intents here.
    }
</code>
According to the Android Developer docs, running this code on a device with dp of at least 640dp x 480dp is large enough to qualify as a large screen, and presumably will then render in multi-pane mode. I'm using an AVD to model the Nexus 10 API 19 device, which has 800dp x 1280: xhdpi. Here is more information:

Here is what I get when I run this. Clearly not displaying multiple panes:

What do I need to do to get this to show multiple panes? When I run this on a USB-connected device, it works perfectly, so the code is accurate. The issue must be the AVD that I am using? Thanks!
Answer: I had the same problem : edit your AVD, go to advanced settings, then select no skin in the "Custom skin definition" combo box.


Where to put php objectToArray logic? Which layer?

Question: I am developing an application in Zend Framework and have the following layers: controller, service, domain model and mapper.
My domain objects need to be represented as arrays for several different purposes.  For example, the mapper turns the object into an array prior to persisting it; the form requires an array as a parameter to its populate() method; and there are a few other examples too.
So, my question is, in what layer should I be doing the translation to an array?  The translation for an object varies slightly depending on the context in which it is used, e.g. the object ID is not required when persisting a new object, but is required when persisting updates, or when populating a form.
As far as I can see there are two options.  Option 1 is to do the translation in each component (i.e. the mapper, the form, etc).  Option 2 is to put it in the domain object itself, and let the client code pass a parameter to determine which array variation they require, e.g. $array = $domObject->toArray('populateForm');
Option 1 would involve a fair amount of duplication, but it seems to adhere to the separation of concerns rule.  Option 2 would avoid the duplication, but I'm not sure that my domain object should be concerned with representing itself in variety of different ways.
Perhaps the domain object should just produce a 'vanilla' array, and each component should tailor it for its own use?  And another point relates to patterns.  Should I be looking to apply the decorator or some other pattern?
Your thoughts are much appreciated!
Answer: My thoughts on this are first, do you think you are doing this the right way? It sounds fairly complicated without any real knowledge about the project. It feels like you are trying to do a typical solution someone very new to Zend would do to then realise it was unnecessary. Then again I do not know alot about your project.
Secondly, I would probably put such functionality in the service layer. Service layer to me has almost always been about manipulating objects.


How to use short codes with arguments

Question: I came across this. That shows how you can get a code like {{ cta }} populated with any data you want, and get that inserted in a template. I want the same sort of solution, but for content. In other words, let's say I have a blog post, I want to be able to add:
{{ cta }}

or
[[ cta ]]

or any convention that works. But the end result is that I must be able to populate the variable via code.
BACKGROUND INFO
I have a bunch of events on my website. I often write blog posts where I refer to events on the site. To add dynamic content to my blog posts, I'd love to simply add things like:
{{ events || from:19dec2014 || to: 23dec2018 }}

I would then populate these with the correct information.
Any ideas on how to do this correctly?
Answer: Try the Shortcode module. It was the among the first hits when I searched for Drupal 8 shortcode.

For the second part of your question I'd recommend Insert View. You can embed a view via a short code in your content and also pass arguments to it.

Insert View is a filter that allows users to embed content lists
  generated by the Views module into node bodies and blocks using
  relatively simple tag syntax.
Why would you want to use an Insert View tag when you could just
  invoke a view using PHP? Simple. When you want to allow users to
  insert views or edit content on a page with an inserted view without
  granting them permission to use PHP.
The tag syntax is [view:name=display=args]
The parameters are: view name, view display id, view arguments.
Valid examples:

[view:my_view] is replaced by the content listing.
[view:my_view=my_display] invokes the view using the specified display.
[view:my_view=my_display=arg1/arg2/arg3] invokes the view using the specified display and passes arg1, arg2 and arg3 to the view.
[view:my_view==arg1/arg2/arg3] passes arg1 to the view and will use the "default" display set for the view.

How to use short codes with arguments