when a hosting mentions 100mbps bandwidth, what does it mean?

Question: Most of web hostings say 100mbps bandwith, does it mean 100mbps upload and download combined ? what is the share between upload speed and download ? is 50 50 ? or 40 60 ? or etc ? Can anyone explain please ?
Comment: I downvoted this and here's why: Hosts typically mean different things in their marketing material than industry standard terms mean. They abuse terms like "bandwidth" to mean "monthly data transfer" and 100Mb is rarely a vanilla full duplex 100Mb connection. Because of this, the answer always fundamentally boils down to "ask your host what they mean." I didn't vote to close it. Asking here *first* shows a lack of research which warrants a downvote, IMO.
Comment: -1 because I think it's fundamentally unanswerable.  As MDMarra has pointed out, it *ought* to mean FD 100Mbit/s, but hosting companies use weasel words all the time, and you're going to have to ask each hosting company what exactly they mean by what they say.
Answer: In general networking terms, it means that there is a 100Mbps full duplex connection. This means 100Mbps in each direction.
In practice, hosting companies use all kinds of slanted terminology and marketing mumbo jumbo to suck you in. You're best off getting the terms in writing from any host you're considering, since they don't always mean what they say.
Comment: +1 Also, just because you've got a X Mb connection to the server doesn't guarantee you'll actually get a X Mb connection to the Internet. When discussing link speeds you'll want to ask about ABR and CBR (DBR outside the US). ABR is the fastest your connection is capable of going (If they refuse to quote/estimate this number, run and never look back); CBR is what they'll guarantee (CBR guarantees always cost more, don't be surprised if they don't offer CBR at all).


ARMA Model Interpretation from R

Question:
I tried my data into an $ARMA$ model which is turned out to be $ARMA(2,3)$. I want to extract the model from the parameters I got in the pic (without any transformation). Is it right if I write the model like this?
$Y_t = 0.6218 + 0.126Y_{t-1} + 0.3964Y_{t-2} + e_t + 0.1488e_{t-1} + 0.9569e_{t-2} - 0.1057e_{t-3}$
Furthermore, how do I get $e_t$ (error of prediction on period-t) since I haven't got the prediction value yet.. I mean, $Y_t$ is something I want to predict, right?
Comment: I think your equation is correct. Furthermore, I think what you would do for a calculation you would fit your data to your model till the last known value and then you get the error for the forecast. See also https://www.otexts.org/fpp/8/8 . However you can use `forecast()` in order to come up with a forecast.
Answer: You will need to flip the signs on the MA coefficients. Here is the help page for arima():

Different definitions of ARMA models have different signs for the
       AR and/or MA coefficients.  The definition used here has
 X[t] = a[1]X[t-1] + ... + a[p]X[t-p] + e[t] + b[1]e[t-1] + ... + b[q]e[t-q]

and so the MA coefficients differ in sign from those of S-PLUS.

In forecasting, you will plug the last few residuals into $e_{t-3}$, $e_{t-2}$ and $e_{t-1}$. Get these using residuals(). For $e_t$, as you write correctly, we don't know this yet. But we assume normally distributed errors. So in forecasting, just plug in the expectation, which is zero.
Of course, if you are not interested in point forecasting, but in predictive densities or prediction-intervals, it makes sense to simulate and draw $e_t~\sim N(0,\widehat{\sigma}^2)$, with $\widehat{\sigma}^2=0.003064$ as per your output.

ARMA Model Interpretation from R


Use recursion on array of integers

Question: Write a function that by given array of integers, and a positive number X, returns
the product of all odd elements that are greater than X. Use recursion!
I tried this:
function result(arr, x) {
    if (arr.length <= 0) {
        return 0;
    }

    if (arr[0] > x && arr[0] % 2 === 1) {
        return arr[0] + result(arr.slice(1));
    }

    return result(arr.slice(1));
}

console.log(result([3, 2, 3, 4, 5, 6, 7, 8, 9], 1));

And the answer is 3.
After the first iteration (x becomes undefined).
Comment: product != sum, otherwise looks.good already. And please [edit] that into the question.
Comment: please add this to the question along with the error.
Comment: Concerning x becoming undefined: when you do the call, pass x on: `result(..., x)`.
Comment: Welcome on Stack Overflow. This community is here for helping not for making your task.
Answer: Try like this:

function result(arr, x) {
    if (arr.length <= 0) {
        return 0;
    }

    if (arr[0] > x && arr[0] % 2 === 1) {
        return arr[0] + result(arr.slice(1), x);
    }

    return result(arr.slice(1), x);
}

console.log(result([3, 2, 3, 4, 5, 6, 7, 8, 9], 1));

You were very close! You only needed to pass the value of x into the result function when calling it again. After that, it returns the correct answer: 3 + 3 + 5 + 7 + 9 = 27

EDIT: x needs to be passed into the function call each time because of the scope of the variables. So far, the result function only knows about the variables passed directly into it.
If x is a constant, another way to deal with that would be to define x at the beginning and then change the function to only accept the array:
    const x = 1;

    function result(arr) {
        if (arr.length <= 0) {
            return 0;
        }

        if (arr[0] > x && arr[0] % 2 === 1) {
            return arr[0] + result(arr.slice(1));
        }

        return result(arr.slice(1));
    }

    console.log(result([3, 2, 3, 4, 5, 6, 7, 8, 9]));

If x is not a constant, but you only want to pass the value into a recursive function once, you can do that too with a sub-function, e.g.:
    function result(arr, x) {
      function recur(arr) {
        if (arr.length <= 0) {
          return 0;
        }

        if (arr[0] > x && arr[0] % 2 === 1) {
          return arr[0] + recur(arr.slice(1));
        }

        return recur(arr.slice(1));
      }

      return recur(arr);
    }

    console.log(result([3, 2, 3, 4, 5, 6, 7, 8, 9], 1));

In this case, the recur function can access the variables passed directly into it (arr) as well as the variables of its parent function (x). The value of arr of the closest available scope is used. This method can be helpful in simplifying complicated recursive functions.
Comment: You're welcome :) I'm glad it worked for you. I've edited the answer to try and explain it and to show how you could change the function so that you don't need to pass the value of `x` each time.
Answer: Another recursive approach without mutating the array.

function sumResult(arr, x, i = 0, sum = 0) {
  if ([0, i].includes(arr.length)) {
    return sum;
  }

  const updated = sum + (arr[i] > x && arr[i] % 2 === 1 ? arr[i] : 0);

  return sumResult(arr, x, i + 1, updated);
}

console.log('sum: ', sumResult([3, 2, 3, 4, 5, 6, 7, 8, 9], 1));

function productResult(arr, x, i = 0, product = 1) {
  if ([0, i].includes(arr.length)) {
    return product;
  }

  const updated = product * (arr[i] > x && arr[i] % 2 === 1 ? arr[i] : 1);

  return productResult(arr, x, i + 1, updated);
}

console.log('product: ', productResult([3, 2, 3, 4, 5, 6, 7, 8, 9], 1));
Answer: You are trying to calculate the sum. The product of the odd numbers from [3, 2, 3, 4, 5, 6, 7, 8, 9] > 1 would imho be: 3 * 3 * 5 * 7 * 9 (= 2835). Here's a snippet that filters out the odd numbers > 1 first, than uses a recursive (sub) function to calculate the product. The use of the sub function is an optimization. You can also use Array.reduce btw.

function productOfUnEvenValuesGreaterThanX(arr, x) {
    // filter desired values
    const oddAndGreaterThanX = arr.filter(v => v > x && ~~(v % 2));
    //                                                  ^ bitwise to determine odd

    // calculate the product recursively
    function product(arrx, y) {
      return arrx.length
        ? product(arrx.slice(1), (arrx.shift() || 1) * y)
        : y;
    }

    return !oddAndGreaterThanX.length ? 0 : product(oddAndGreaterThanX, x);
}

console.log(productOfUnEvenValuesGreaterThanX([3, 2, 3, 4, 5, 6, 7, 8, 9], 1));
console.log(productOfUnEvenValuesGreaterThanX([2, 4, 6, 8], 1));

// alternatively you can use a reducer
function productOfUnEvenValuesGreaterThanXReducer(arr, x) {
  return arr.reduce( (acc, val) =>
    val > x && ~~(val % 2)
      ? (acc || 1) * val
      : acc, 0 );
}

console.log(productOfUnEvenValuesGreaterThanXReducer([3, 2, 3, 4, 5, 6, 7, 8, 9], 1));
console.log(productOfUnEvenValuesGreaterThanXReducer([2, 4, 6, 8], 1));

Use recursion on array of integers


Alt attribute encoding with JavaScript

Question: Html entities must be encoded in alt attribute of an image in HTML page. So

will work well.
On the other hand, the same JavaScript code will not work
document.getElementById('formula').alt = 'A → B';

and will produce A → B instead of A → B.
How to do it through JavaScript, when it is not possible to put the special (unencoded) characters in the source code?
Comment: Google peoples - see also: https://stackoverflow.com/questions/94037/convert-character-to-ascii-code-in-javascript
Answer: JavaScript has its own system for escaping special characters in strings:
document.getElementById('formula').alt = 'A \u2192 B';

Comment: +1. When you are assigning DOM properties, you **don't need HTML-encoding**. If you want the character `→` just paste it in; it's perfectly valid to say `img.alt= 'A → B';`. That only requires you to get the encoding you're saving your page as to match what you're serving it as (best: use UTF-8 for both). The JavaScript string literal escape `'A \u2192 B'` is a good fallback if you can't rely on non-ASCII characters being served properly.
Comment: @bobince: That was my first answer, too, but the question explicitly states: "How to do it through JavaScript, when it is not possible to put the special (unencoded) characters in the source code?" Moreover, this solution presupposes the source is a Unicode value, but the question's example uses an HTML entity. Oh, and really, no offence meant, I'm just wondering what to do in such a situation.
Comment: Yeah, my feeling is there's a common assumption that non-ASCII characters need escaping which is much less often true than people think. (Indeed, the phrase 'special characters' is itself a misnomer when we're talking about 99.9% of all characters...) In any case there will be no difference between setting `innerHTML` to `&#rarr;` or `→` because all HTML parsers replace entity references with their text equivalent: you never get a DOM EntityReference node.
Comment: @bobince: I think it would be great if authors could comfortably include any character in a document, but I've seen way too many encoding fails to recommend it, and I'd only do it myself if I had control over the website, server, VCS, and editors used by the developers. "Special characters" means every character that's at risk for being broken by bad encoding, everything but the ASCII 95.
Answer: <!DOCTYPE html>

    <meta charset="utf-8">
    <title>Decode HTML entities using JavaScript</title>

Credits to The JavaScript Source.
EDIT: I changed the original code to only use innerHTML on a
 element, instead of innerHTML and value of a <textarea>.
Comment: Setting the HTML of a `textarea` should *not* change its form field `value` according to the standard DOM; the contained HTML maps to the textarea's `defaultValue` property, not `value`. It's a browser quirk that `innerHTML` also affects `value`, and it doesn't happen in Opera. Don't rely on it. You could write `innerHTML` to any other element and read the text node child it ends up with (if non-blank string). Also, avoid `setAttribute`, which is unnecessary in HTML documents, and buggy in IE.
Comment: IE<8 treats `el.getAttribute(someattr)`/`el.setAttribute(someattr, ...)`) as being the same as property access, `el[someattr]`. Consequently, (1) any property whose value isn't a string will expose something that isn't a string. For integer properties you sometimes don't notice as weak typing hides it from you, but booleans, event handler functions and `style` will often trip you up. (2) any property whose name is different from the corresponding attribute will fail. That's `htmlFor`, `className`, and any attribute name made from multiple or hyphenated words.
Comment: (3) any property which has a different meaning to its attribute will behave strangely. For example `href` will return the full resolved URL in a link, not the original, possibly-relative version that was actually used in the attribute value, and `value` returns a form field's current value, and not the content of the `value` attribute (which actually maps to `defaultValue`). Also (4) custom-attributes can shadow real properties, so writing `` might confuse a script into thinking it's a text node.
Comment: (This is another reason custom attributes should be avoided, but if you must use them then yes, you must use `getAttribute` exclusively to access them, and if you've got any sense you'll limit this use to attributes prefixed `data-`.)
Comment: @jweyrich: it's easier to see the effect using the `title` attribute ;)
Comment: @bobince: FYI, I tested this example in Opera (10.10/Linux) and it worked fine. Also, why is `setAttribute` buggy in IE, in this case (and in cases you want to set a custom `data-…` attribute)? I can't find much about it, apart from [your post](http://stackoverflow.com/questions/748941/setattribute-onclick-and-cross-browser-compatability/749253#749253) explaining why setting event handlers using `setAttribute` doesn't work as expected (the same is true for e.g. the `style` object). If you want me to open a separate question about this, I'll be happy to do so.
Answer: Here's an alternative if you can't save your file using a Unicode format:
function decodeHTML(str) {
    return str.replace(/&#(\d+);?/g, function() {
        return String.fromCharCode(arguments[1])
    });
}

However, this requires you to use the numeric representation. In this case →.
Comment: I hate to be that guy, but please take a look at my answer.
Comment: IMHO you've suggested the *easiest workaround*. Even if it is a workaround, and not an answer, I accept it and that's the solution I will use for my code (converting entities like `↑` to `↑` on server side).
Comment: @Sidnicious No please, your solution is the best IMO! +1 from me! @MainMa feel free to accept his answer instead. I'd go for it :)
Comment: @Sidnicious: well, it may be an alternative solution. Both are good, I think, so I uprated yours, still letting the answer of jweyrich as accepted, because it seems more straightforward, and does not require to use JavaScript character codes (different from HTML codes).
Comment: JavaScript string literal escapes are in hex, like `→` escapes in HTML. If you really want to use the decimal codes you can: `'A '+String.fromCharCode(8594)+' B'`.
Comment: @MainMa: Like bobince said, the only difference is decimal/hexadecimal. It's trivial to convert, you can even use JavaScript: `(8594).toString(16) → "2192"`!
Answer: In that particular case, you don't have encode special HTML characters in JavaScript.
The W3C validator should not complain about this (just tested it) and the document should validate. If not post your code and I'll update my answer.
Comment: Fair point, but he didn't mention which file format he's using to save it.

Alt attribute encoding with JavaScript


Não tenho certeza se a minha classe realmente está correta

Question: a algum tempo atrás eu resolvi montar essa classe para facilitar a minha vida, não irei colocar ela completa para não ficar uma postagem grande demais, essa classe para fazer um insert você manda assim $Classe->Query("NOME_DA_TABELA",$ARRAY,"insert", ""); as informações da coluna são enviadas por array pelo $_POST " $_POST['nome_da_coluna'] " do form, e sem eu precisar ficar montando querys ela monta tudo e envia.
Resumindo...
ela pega os dados de um form e faz insert/update com 1 linha e o minimo de informações.
A questão é a seguinte...
Já estou usando ela para produção, já analisei várias vezes, não sou um expert na programação e tenho medo de ela ter alguma falha de segurança ou código desnecessário, o que eu gostaria era de uma avaliação para saber se está realmente boa ou preciso mudar alguma coisa...
caso não seja o suficiente para o entendimento segue o link dela no git Aqui
__construct
//==============================================================================
 public $host       = "localhost";
 public $dbname     = "dbname";
 public $user       = "root";
 public $pass       = "";
 const  ID          = "id";
//==============================================================================

 function __construct(){
    try{
        $this->conn = new PDO(
            "mysql:host=$this->host;
            dbname=$this->dbname;
            charset=utf8",
            $this->user,
            $this->pass,
            array(
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'
            ));
    }catch(PDOException $e){
        echo 'ERROR: ' . $e->getMessage();
    }
 }

Data
 public function Data($select,$type){
    if($type == 'fetch'){
        $select = $this->conn->prepare($select);
        $select->execute();
        return $select->fetch();
    }else if($type == 'fetchAll'){
        $select = $this->conn->prepare($select);
        $select->execute();
        return $select->fetchAll();
    }else if($type == 'update'){
        $select = $this->conn->prepare($select);
        return $select->execute();
    }
 }

MagicSelect
//Método de auxilio para o método Tables aqui que ele retorna o nome das colunas

 public function MagicSelect($table){
    $select = "DESCRIBE $table";
    return Connect::Data($select,"fetchAll");
 }

Tables
//Pega as tabelas do banco de dados

public function Tables($table){
    $search = Connect::MagicSelect($table);
    $count  = count($search);
    for ($i=0; $i < $count ; $i++) {
        if($search[$i]['Field'] !== self::ID){
            $result[] = $search[$i]['Field'];
        }
    }
    return $result;
 }

Query
//Aqui é onde é montada toda a estrutura para o bindParam

 public function Query($table, $array, $type, $where){
    $tableInfo = Connect::Tables($table);
    $fieldA     = "";
    $fieldB     = "";
    $field      = "";
    $count      = count($tableInfo);

 //CASO SEJA insert =========================== * * *
    if($type == "insert"){
        foreach ($tableInfo as $index => $value) {
            if($index+1 < $count){
                $fieldA .= $value . ", ";
                $fieldB .= ":".strtoupper($value).", ";
                $fieldA_array[] = $value;
                $fieldB_array[] = ":".strtoupper($value);
            }else{
                $fieldA .= $value;
                $fieldB .= ":".strtoupper($value);
                $fieldA_array[] = $value;
                $fieldB_array[] = ":".strtoupper($value);
            }
        }
        $stmt = $this->conn->prepare(
"INSERT INTO $table ($fieldA) VALUES ($fieldB) $where"
);
        for ($i=0; $i < count($fieldA_array) ; $i++) {
            $stmt->bindParam($fieldB_array[$i], $array[$fieldA_array[$i]]);
        }
        $stmt->execute();
 //CASO SEJA update =========================== * * *
    }else if($type == "update"){
        foreach ($tableInfo as $index => $value) {
            if($index+1 < $count){
                $field .= $value . " = :".strtoupper($value).", ";
                $fieldA_array[] = ":".strtoupper($value);
                $fieldB_array[] = $value;
            }else{
                $field .= $value . " = :".strtoupper($value);
                $fieldA_array[] = ":".strtoupper($value);
                $fieldB_array[] = $value;
            }
        }
        $stmt = $this->conn->prepare("UPDATE $table SET $field WHERE $where");
        for ($i=0; $i < count($fieldA_array) ; $i++) {
            $stmt->bindParam($fieldA_array[$i], $array[$fieldB_array[$i]]);
        }
        return $stmt->execute();
    }
    return;
 }

ps:. primeira pergunta aqui na comunidade
Answer: Pontos a serem melhorados:

Encapsular os atributos de conexão do banco de dados.
Remover a conexão do banco de dados do método construtor da classe e criar um método especifico para isso e outro método para desconectar.
Tratar o exception da conexão.
Observei que os métodos que você criou estão começando com letra maiúscula e por convenção e boa prática, nome de método e de atributo começa com letra minuscula, apenas nome da classe que tem letra maiúscula.
Comment: Obrigado pelas informações :) vou revisar aqui


Internet access via OpenVPN

Question: Note: This is a repost from the OpenVPN forums
I have just set up an OpenVPN on my Linode VPS, and I have successfully connected my Android phone to it. Now, I want to use the "route all traffic" option on the client. I'm not sure how to set up the routes on the server side though, so I would greatly appreciate any help. I'm taking a class this summer at my local Community College, and they seem to think that an open WAN with web authentication is secure enough.
Here are my interface configurations:

eth0      Link encap:Ethernet  HWaddr
  f2:3c:91:93:a8:c2
            inet addr:126.96.36.199  Bcast:18.104.22.168
  Mask:255.255.255.0
            inet6 addr: 2600:3c03::f03c:91ff:fe93:a8c2/64
  Scope:Global
            inet6 addr: fe80::f03c:91ff:fe93:a8c2/64
  Scope:Link
            UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
            RX packets:126144742 errors:0 dropped:0 overruns:0 frame:0
            TX packets:315279 errors:0 dropped:0 overruns:0 carrier:0
            collisions:0 txqueuelen:1000
            RX bytes:2301671639 (2.3 GB)  TX bytes:136422020 (136.4 MB)
            Interrupt:44
lo        Link encap:Local Loopback
            inet addr:127.0.0.1  Mask:255.0.0.0
            inet6 addr: ::1/128 Scope:Host
            UP LOOPBACK RUNNING  MTU:16436  Metric:1
            RX packets:3971 errors:0 dropped:0 overruns:0 frame:0
            TX packets:3971 errors:0 dropped:0 overruns:0 carrier:0
            collisions:0 txqueuelen:0
            RX bytes:753104 (753.1 KB)  TX bytes:753104 (753.1 KB)
tun0      Link encap:UNSPEC  HWaddr
  00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00
<code>      inet addr:10.8.0.1  P-t-P:10.8.0.2  Mask:255.255.255.255
      UP POINTOPOINT RUNNING NOARP MULTICAST  MTU:1500  Metric:1
      RX packets:0 errors:0 dropped:0 overruns:0 frame:0
      TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
      collisions:0 txqueuelen:100
      RX bytes:0 (0.0 B)  TX bytes:0 (0.0 B)
</code>
Answer: You will need to have your VPN traffic run through NAT or masquerading, as well as configure the system for IP forwarding. By default, Linux will have IP forwarding disabled. Once that is enabled, you have to do something (NAT or MASQ) to convert the IP address from 10.8.0/24 to a publicly-routable address.
Answer: Bear in mind that although openvpn will provide you a secure tunnel it won't stop access to your android device across the LAN, so you might want to be having a look at that too.
What is your network layout on the vpn server side of things? That will help get the ball rolling.
Comment: Thanks. I have edited the question with my current interfaces. I'm not as concerned about LAN accessibility as I am about sniffing and/or firesheep type attacks. I am running CyanogenMod 7.1 RC1 (which is based on Android 2.3.4, which is the latest version as of this writing), so I should be protected from most exploits that are in the wild.
Comment: Ok so if your server is directly available on the internet and there are no other private subnets to route to I think all you should need to do is go to the VPN settings page on the openvpn admin interface and add 0.0.0.0/0 as a private subnet that the server would provide access to.
Comment: I don't have the admin interface installed, so I read the config file, /etc/openvpn/server.config, and added the line

;push "route 0.0.0.0 0.0.0.0"

with no success.
Comment: OK, well I've not played around with the config files before, our openvpn server is a virtual appliance and, as such, seems to be a little weird when trying to locate config files. Anyway, I'm not sure my original idea is necessary, openvpn's website has a small guide as to how to route all traffic through the VPN server: http://openvpn.net/index.php/open-source/documentation/howto.html#redirect

Internet access via OpenVPN


How to get the unread message count using EntityFieldQuery

Question: Using below query I am getting the count of all messages of a user. Now i need to filter them to unread messages only.
<code>global $user;
$query = new EntityFieldQuery();
$count = $query->entityCondition('entity_type', 'message')
 ->propertyCondition('uid', $user->uid)
 ->count()
 ->execute();
</code>
Comment: Then you will need another `condition`.  What have you tried?  What research have you done?
Comment: I know, I need that condition only. Search results show me related to privatemessage moudule only.
Answer: If you are using the privatemsg module you can use privatemsg_unread_count().
Comment: I am not using privatemessage moudule.....
Comment: As Darvanen said above you need to add a condition to your query. Which field and which value to filter on depends on your model. Do you have a list of fields for the 'message' entity type? Which module implements that entity?


Solve this differential equation (can't do the integral in the last step)

Question: $\displaystyle{%
{\rm y}'\left(x\right)
=
\sqrt{x\,}\,\, {\rm y}\left(x\right) + {{\rm e}^{x} \over \sqrt{x\,}\,}\,,
\qquad{\rm y}\left(0\right) = 2}$
I don't know how to do the integral in the last step.
Comment: What integral are you left with?
Comment: The integral is non-elementary.  If this is homework, leave it in the form of an integral.
Comment: What integrating factor did you get?
Comment: @RobertIsrael thank you.
Answer: (EDITED):
It looks like there's a "closed-form" solution to the differential equation in terms of the Heun T function and its derivative: in Maple's notation
$$y(x) = {\frac {3^{1/3} {2}^{2/3}{{\rm e}^x} {\it HeunT}
 \left( 0,-3,-{2}^{2/3}3^{1/3}/4,{3}^{2/3}2^{1/3}
 \left( 2\,\sqrt {x}-1 \right)/6  \right) }{{\it HeunTPrime}  \left( 0,-3,-{2}^{2/3}3^{1/3}/4,-{3}^{2/3}2^{1/3}
 /6  \right) }}
$$
This particular solution doesn't satisfy the initial condition: you must add an appropriate solution of the homogeneous equation.
Comment: +1 Everyday one learn something new and unheard of. I start to wonder whether there are infinitely many special functions.
Answer: The integrating factor is $$\mu(x)=e^{-\int\sqrt x~dx}=e^{-\frac{2x^{3/2}}{3}}$$ and you need to evaluate the integral $$\int\frac{e^{-\frac{2x^{3/2}}{3}+x}}{\sqrt x}~dx,$$ but unfortunetley, it is not possible to do that by elementary techniques of integration, so you leave the integral as it stands (as proposed in comments).


DNS records on suffix of domain not subdomain

Question: I use Cloudflare for DNS. Is it technically possible to set records on the extended domain rather than subdomain.
EG: domain.com -> Server 1 and domain.com/abc -> Server 2. The practical side effect is the root switches from '/' to '/suffix' at the DNS level
Currently its setup to use subdomains eg: abc.domain.com
Answer: No, that's not possible to do with DNS. However, you could proxy that path to Server 2. On NGINX, this will be a proxy_pass to Server 2 in the location /abc block.
Answer: You can't do it. You can use iFrame or redirect.


Can't choose checkboxes as field widget in d7

Question: I recall in previous versions (Or maybe even this version and mine is just bugging) you could take text or int fields and supply a list of key|values and make checkboxes or a selectbox from it.
The core module "Options" seems to offer this functionality from the module description but whenever I select field type Integer, Decimal, Float, or text the only widget option I have is a standard textbox.
Term and node references do allow checkbox widgets.
Am I seeing a bug? Is there a different way of doing this in D7? I've tried adding these field types to both node types and vocabs but neither acknowledges the existence of the checkboxes widget.
Answer: Set "Type of data to store" to List (text), List (integer) or List (float) and Check boxes will be default widget. If you can't see them, make sure List module is enabled.
Answer: No this isn't a bug. The options module doesn't itself define any field types for which it can be used. This is left to modules wishing to implement hook_field_widget_info_alter() and add to the field types property.
For example, the taxonomy module provides that functionality through taxonomy_field_widget_form_alter():
function taxonomy_field_widget_info_alter(&$info) {
  $info['options_select']['field types'][] = 'taxonomy_term_reference';
  $info['options_buttons']['field types'][] = 'taxonomy_term_reference';
}

The number module doesn't implement that hook, so you can be pretty sure the behaviour you see is by design.
The list types are instead provided by the List module (List(Text), List(integer), etc.)


converting RDD to dataframe fails on string to date conversion

Question: I am working on extracting some data from xml. My overall workflow, which might be inefficient, is:

Read xml into a dataframe ('df_individual')
Filter unwanted columns
Make the target schema (shared below)
Convert the dataframe to RDD
Create a dataframe using schema and RDD from step 3 and 4

I created the RDD like below:
rddd = df_individual.rdd.map(tuple)

'df_individual' is the orignal dataframe where read the xml.
Below is the schema:
schema = types.StructType([
        types.StructField('applicaion_id', types.StringType()),
        types.StructField('cd_type', types.StringType()),
        types.StructField('cd_title', types.StringType()),
        types.StructField('firstname', types.StringType()),
        types.StructField('middlename', types.StringType()),
        types.StructField('nm_surname', types.StringType()),
        types.StructField('dt_dob', types.DateType()),
        types.StructField('cd_gender', types.StringType()),
        types.StructField('cd_citizenship', types.StringType())
    ])

It fails on
df_result = spark.createDataFrame(rddd, schema)

The error is
TypeError: field dt_dob: DateType can not accept object '1973-02-19' in type <class 'str'>

The main purpose of creating the 'df_result' dataframe is having a predefined schema and implicitly casting all the columns where there is difference between RDD and dataframe. This is my first time working with RDD and I couldn't find a straight forward casting mechanism for such a case.
If you can help with solving the casting error or share a better workflow that would be great.
Thanks
Answer: If your aim is only to get your data into the right schema and transform some string columns into date columns, I would use a select combined with to_date.
df.select('applicaion_id', 'cd_type', 'cd_title', 'firstname', 'middlename', 'nm_surname', \
          F.to_date('dt_dob').alias('dt_bob'), \
          'cd_gender', 'cd_citizenship') \
  .printSchema()

prints
root
 |-- applicaion_id: string (nullable = true)
 |-- cd_type: string (nullable = true)
 |-- cd_title: string (nullable = true)
 |-- firstname: string (nullable = true)
 |-- middlename: string (nullable = true)
 |-- nm_surname: string (nullable = true)
 |-- dt_bob: date (nullable = true)
 |-- cd_gender: string (nullable = true)
 |-- cd_citizenship: string (nullable = true)

with the column dt_bob having a date datatype.


JSON parse error

Question: Estou desenvolvendo uma aplicação web (Spring) e preciso salvar uma data no banco de dados. Fiz uma função Ajax para salvar o valor, porém recebo o seguinte erro:

JSON parse error: Can not deserialize value of type
  java.time.LocalDate from String "02/07/2018": Text '02/07/2018' could
  not be parsed at index 0

Já configurei o Maven para baixar as dependências para trabalhar com JSON. Abaixo, as dependências que estou utilizando:

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <scope>compile</scope>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.module</groupId>
            <artifactId>jackson-module-parameter-names</artifactId>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.datatype</groupId>
            <artifactId>jackson-datatype-jdk8</artifactId>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.datatype</groupId>
            <artifactId>jackson-datatype-jsr310</artifactId>
        </dependency>

Atributo da class model:
@Column(name = "data_contribuicao", columnDefinition = "DATE")
@NotBlank(message = "Informe a data da contribuição")
private LocalDate dataContribuicao;

Controller:
@PostMapping("/salvar")
    private @ResponseBody ResponseEntity<?> salvar(@RequestBody @Validated Contribuicao contribuicao, BindingResult bindingResult) {

        if (bindingResult.hasErrors()) {
            return ResponseEntity.badRequest().body(bindingResult.getFieldError().getDefaultMessage());
        }

        return ResponseEntity.ok(cadastroContribuicaoServe.cadastrar(contribuicao));

    }

Script Ajax:

Tentei várias alternativas, mas sem sucesso. Como eu poderia resolver este problema?
Answer: A data em que você está passando não é um formato de data e data local.
Mudar paraespecificar o formatador correto.
@Column(name = "data_contribuicao", columnDefinition = "DATE")
@NotBlank(message = "Informe a data da contribuição")
@JsonFormat(pattern = "dd/MM/aaaa")
@DateTimeFormat(iso = DateTimeFormatter.ISO_LOCAL_DATE_TIME)
private LocalDate dataContribuicao;

Aqui pode ajudar você:
https://stackoverflow.com/questions/40327970/deserialize-java-8-localdatetime-with-jacksonmapper/40476708#40476708
https://stackoverflow.com/questions/40327970/deserialize-java-8-localdatetime-with-jacksonmapper
Comment: Obrigado pela resposta! Aproveito aqui para dizer que agora tenho um outro erro, rs: "JSON parse error: Can not deserialize value of type java.lang.Double from String "15,00": not a valid Double value;"
Comment: Qual erro? Posta aí
Comment: Esse: "JSON parse error: Can not deserialize value of type java.lang.Double from String "15,00": not a valid Double value;"  Tenho um outro atributo no form, e também preciso salvar ele. Atributo da class model: `@NotBlank(message = "Por favor, informe o valor da contribuicao")
    @Column(name = "valor_contribuicao")
    private Double contribuicao;`
Comment: e um erro de  conversão.....vc está passando um string para um Double.
Comment: Sim, mas como eu posso resolver isso? Não tenho tanto conhecimento em JS. Preciso pegar os valores do form e passar o tipo correto para o objeto do controller.
Comment: como vc está passando so valore , passa sem  as virgulas. 15,00  para 15
Comment: @VictorAlves use BigDecimal

JSON parse error


Number of triangles in a Graph/Network

Question: Given An undirected graph/Network, and its adjacency matrix A, and 1 (A column vector with all elements as 1).
How do we represent the problem of finding the number of triangles in the network (3-cliques) in terms of A, and 1.
I do understand to find the triangle A summation of $A_{ij}*A_{jk}*A_{ik}$,where $i,j,k$ are vertices, but how do we represent in terms of A, and 1
Answer: The summation $A_{ij} A_{jk} A_{ki}$ can be written $\text{trace}(A^3)$. Don't forget to divide by 6.
Answer: $|\{(x,y,z) : x \ne y, x\ne z, z\ne y, A[x][y]=A[x][z]=A[z][y]=1\}|$.
Comment: ...divided by 6.  But this seems equivalent to the OP's candidate answer that was excluded since it didn't fit the description "in terms of $A$ and $\mathbf{1}$".

Number of triangles in a Graph/Network


Alternate highest counting in array

Question: I have an array which is sorted but contains zeroes in between like
a[10]={0,0,3,5,0,6,7,0,9,0}

I want to neglect zeroes and find sum of alternate elsments i.e.
3+6+9 and 5+7 seperately.
Here is what m trying to do
while(i<10)
{
     if(a[i]!=0)
     {
         s1=s1+a[i];
         i++;
     }
     if(a[i]!=0)
     {
         s2=s2+a[i]
         i++;
     }
     i++;
}

any alternate to this??
Comment: What are "alternate elements"?
Comment: What if you encounter 2 zeros in a row? Switch twice or just once?
Comment: we have to ignore all zeroes
Answer: Use a boolean to keep track of which sum to add the element to:
bool alt = true;
int sum1 = 0;
int sum2 = 0;
for(int i = 0; i<10; ++i)
{
    if(a[i])
    {
        if(alt)
        {
            sum1 += a[i];
        }
        else
        {
            sum2 += a[i];
        }
        alt = !alt;
    }
}

Answer: If you can modify the array,
following does what you say (ignore zero, and then compute alternate sum):
int a[] = {0,0,3,5,0,6,7,0,9,0};
const auto end = std::stable_partition (std::begin(a), std::end(a),
                                        [](int e) {return e != 0;});

int sum1 = 0;
for (int i = 0; a + i < end; i += 2) { sum1 += a[i]; }
int sum2 = 0;
for (int i = 1; a + i < end; i += 2) { sum2 += a[i]; }

std::cout << sum1 << std::endl;
std::cout << sum2 << std::endl;

Note: if you can't use lambda (C++11),
you have to write the predicate NotZero.
Answer: Here is a very simple solution if I have understood correctly what you need.
int sum[2] = {};

int j = 0;

for ( int x : a )
{
   if ( x ) sum[j++ % 2] += x;
}

And here is a demontsrative program
#include <iostream>

int main()
{
    int a[] = { 0, 0, 3, 5, 0, 6, 7, 0, 9, 0 };

    int sum[2] = {};

    int j = 0;

    for ( int x : a )
    {
        if ( x ) sum[j++ % 2] += x;
    }

    for ( int s : sum ) std::cout << s << std::endl;
}

The output
18
12

If you are using MS VC++ 2010 then you can substitute the loops in the program for the following
for each ( int x in a )
for each ( int s in sum ) std::cout << s << std::endl;

Or instead of the range based for loops you can use ordinary loops.

Alternate highest counting in array


How to interpret the p- values and intercept in a Poisson glm with catagorical predictors

Question: When looking at a glm with non categorical predictors I am given to understand that the intercept the the predicted value of your measure when all predictor variables are at 0.
This therefore means that when looking at the coefficients of such a glm we take the estimate to be the ratio change of the measure with a 1 unit increase in the predictor variable. The p-value associated with this then shows is this change is significant enough for that predictor variable to have an effect on the models predictive power?
However when we look at a glm with categorical variables the intercept is the value of your measure when all predictor variables are at their first factor level? How do I then interpret the p-values associated with these coefficients?
Here is an example model:
Call:
glm(formula = count ~ origin + variable + origin * variable,
    family = "poisson", data = count_filt_FGT_free)

Deviance Residuals:
    Min       1Q   Median       3Q      Max
-1.6877  -0.6963  -0.3758   0.0306   5.1953

Coefficients:
                                 Estimate Std. Error z value Pr(>|z|)
(Intercept)                      0.217065   0.110432   1.966   0.0493 *
originfree                      -0.247836   0.166794  -1.486   0.1373
variableDuplication              0.136576   0.151107   0.904   0.3661
variableKnown_target            -1.634130   0.273254  -5.980 2.23e-09 ***
variablePhylogeny                0.125880   0.151485   0.831   0.4060
originfree:variableDuplication   0.008606   0.227974   0.038   0.9699
originfree:variableKnown_target  0.040197   0.408914   0.098   0.9217
originfree:variablePhylogeny     0.005696   0.228629   0.025   0.9801

The intercept is made up of the first factor level of origin (FGT) and variable (proximity). So when looking at the exp of originfree estimate we see that the count changes by a ratio of exp(-0.247836) = 0.7804879. Does the p-value associated with this (0.1373) show that for variableProximity there is no significant difference when being originFree ?
Answer:
The intercept is made up of the first factor level of origin (free)

This appears to be incorrect because of:

originfree                      -0.247836   0.166794  -1.486   0.1373

if free was the reference level for origin this line would start with originXYZ where XYZ is the other level.

when looking at the exp of originfree estimate we see that the count changes by a ratio of exp(-0.247836) = 0.7804879.

This is also incorrect. The variable origin is involved in an interaction with variable so the main effect is conditional on variable being at it's reference level, so you can just add "when variable is at it's reference level" to that sentence.

Does the p-value associated with this (0.1373) show that for variableProximity there is no significant difference when being originFree ?

Not quite. It should be interpreted as: If there is actually no difference in the outcome between origin "free" and it's reference level, when variable is at it's reference level, then the probability of obtaining -0.247836 (or less) again, is 0.1373.
Try to avoid statements about "significant differences" because they depend on arbitrary thresholds for p values - if you obtained a p value of 0.0999999 someone might say that there is a significant difference, whereas if the p value was 0.1000001 the same person might say there is no significant difference (at the 0.1 level). I would say that the results are the same. Also, if a different person had a "bible" that told them 0.05 was the "correct significance level" they would say both results are not significant, whereas the person who's bible told them to use 0.15 would conclude that both are significant. I hope you can see how arbitrary this is.
Comment: Ah yeh my bad I mean the intercept is made up of `origin`at its reference level, edited to change now. But thank you for clarifying how I should be looking at the p values. So the p values associated with coefficients are not really meant to be used in saying X or Y is important in the model? But rather that `variableknown_target` has evidence suggesting estimates of count associated with is when `origin` is at it's reference level are different from `variable`at its reference level (p= 2.23e-09) ?
Comment: For `variable` you can say that there is (strong) evidence that the oucome is different between `known_target` and the reference level, **when `origin` is at it's reference level**. But note that there is almost no evidence of an interaction so unless you have *a priori* reason to believe there should be an interation, then take it out and it will make your life easier with interpretation of the main effects (because when there is no interaction the main effects are not conditional)
Comment: @RovertLong My reason for including it is as you say I expected there to  be an interaction as `origin` is just where the sample came from and `variable` are the different categories of  things I am counting. So if there is a difference in `origin` I expected that difference to be reflected in `variable` Would this then lead us to believe there is something else wrong with the model?
Comment: It's a bit difficult to say. Have you plotted the residuals ? Are they approximately normally distributed ?
Comment: I am not entirely sure how to plot the residuals so have included the code I used to do it along with the plot above. It is wrong of me to include `variable` in the model if it is itself the categories things I am counting?
Comment: Oh I forgot this is a poisson model, so the plots are not so relevent, sorry. I will think about this a bit more later today after I finish work.


Is there a non-continuous Riemann integrable function with an anti-derivative?

Question: Is there a function $f:[a,b]\rightarrow\mathbb{R}$ (for real $a<b$) which is Riemann integrable and has an antiderivative in $[a,b]$, but is not continuous?
Answer: Consider:
$$f(x) = \begin{cases} 2x \sin \left( \frac1{x} \right) - \cos \left( \frac1{x} \right), x \neq 0 \\ 0, x=0 \end{cases}$$
$f$ is Riemann integrable on $[-1,1]$ (by Lebesgue's theorem for Riemann integrals, for instance), and has the antiderivative:
$$F(x) = \begin{cases} x^2 \sin \left( \frac1{x} \right), x \neq 0 \\ 0, x = 0 \end{cases}$$
Answer: Assume we have a function $g(x)$ is continuous and Riemann integrable with an antiderivative. Let's define another a new function $$f(x)= \begin{cases} g(x), x \neq c \\ \neq g(c), x = c \end{cases}$$
The new function $f(x)$ is not continuous but it is Riemann integrable and has the same antiderivative as $g(x)$.
Comment: It doesn't have an antiderivative because of the "jump" discontinuity and by Darboux's theorem.
Comment: Can you elaborate it a little more? Thanks.
Comment: Why do you think $f$ has an antiderivative?


Como mudar o botão() de "Ver senha" para uma imagem ()

Question: Existe um campo do cadastro de um funcionário chamado senha da qual existe um botão chamado "Ver senha" que permite ver a senha do usuário, só que eu quero retirar o botão Ver senha que fiz em javascript e queria saber como substituir esse <button> por um ícone chamado olho.png que combine melhor com o campo (questão de affordance).
<!DOCTYPE html>

    <meta charset="utf-8">
    <title> Cadastrar Funcionário </title>
    <link rel="stylesheet" href="/WEB/css/css.css">

    <form method="POST">

 Senha: <input type="password" name="senha" id="senha" size=30 maxlength="32" required="">
        <button type="button" onclick="mostrarSenha()"> Ver senha</button>

    </form>

caminho da imagem da qual eu quero substituir o <button> por um : img/olho.png

Comment: pq não coloca `background: url('img/olho.png')` no css que define o botão?
Comment: Tem como me demonstrar em código?
Comment: sim, veja a resposta
Comment: Se entendi o que você quer fazer, acho uma solução com svg mais agradável, como [essa](https://codepen.io/maxpelic/pen/gygLxm). Quando precisei fazer, usei isso como referência e adaptei pra minha necessidade :)
Comment: @RafaelTavares interessante esse código.
Answer: Pode definir uma imagem como background do botão, assim:

function mostrarSenha() {
   document.getElementById('senha').type = 'text';
}
.btn-senha {
   background: url('http://icons.iconarchive.com/icons/custom-icon-design/mono-general-4/16/eye-icon.png') no-repeat;
   width: 18px;
   height: 18px;
}

    Senha: <input type="password" name="senha" id="senha" size=30 maxlength="32" required="">
    <button class="btn-senha" type="button" onclick="mostrarSenha()"></button>

Comment: Os dois primeiros códigos ficam no CSS?
Comment: No ```Executar``` de seu código não oculta a senha
Comment: se digitar uma senha e apertar o botão ele exibe a senha. veja que no meu exemplo mudei o type de "password" para "text". Não conseguiu identificar o código? precisa estudar isso @Fujjin :) o primeiro é javascript, o segundo é css
Comment: Ricardo, acho que ele quer que alterne entre mostrar/ocultar ao clicar no ícone ;0
Comment: eu pensei nisso @Sam mas pelo texto *"só que eu quero retirar o botão Ver senha"* não dá pra ter certeza.. de qualquer forma, era só estilo, no exemplo ainda foi "grátis" o exibir senha ;)
Comment: O texto diz uma coisa mas o código mostra um if...else alternando o type entre text/password. Mas tá tranquilo.
Comment: sim, o core mesmo da resposta é o `background`, que tá passando quase desapercebido :)


What happens when there is no variation within a category in panel data?

Question: I have a dataset with multiple rows per individual. Each row represents the number of items sold by an employee on a given day. Suppose I have thousands of employees, and each of them has roughly five records each. Likewise, all employees are assigned to a branch (i.e., branches group multiple employees).
For example, the data for branch 01 would look as follows:

employee_id
day
branch_id
employees_in_branch
items_sold

1234
1
branch_01
7
12

1234
2
branch_01
7
0

1234
3
branch_01
7
4

1234
4
branch_01
7
22

1234
5
branch_01
7
15

5678
1
branch_01
7
2

5678
2
branch_01
7
3

5678
3
branch_01
7
7

5678
4
branch_01
7
2

5678
5
branch_01
7
14

The number of employees in each branch does vary from one branch to another. However, there is no variation in the column employees_in_branch within each branch.
What would happen if I were to run a fixed effects model and include employees_in_branch as an independent variable?
$$
E(Y|X) = g(\text{branch_id}, \text{employees_in_branch})
$$
I know neither column is a linear combination of the other. However, employees_in_branch seems like a variable that the fixed effect coefficient could absorb, so I am wondering if adding employees_in_branch would be redundant.
Answer: The short answer is you can't; a fixed-effects model cannot include cluster-level covariates (in your case, anything that is constant within each store).
More generally, your data set has a hierarchical structure that is ideal for a multilevel model, as you presumably expect to have both within-employee and within-store correlation. If $y_{ijk}$ is the number of items sold in day $i$ by employee $j$ in store $k$, your model would be something like
$$
y_{ijk} = \boldsymbol{\beta}'\mathbf{x}_{ijk} +  u_{jk} + v_k + \varepsilon_{ijk}
$$
where $u_{jk}$ and $v_k$ are, respectively, the random effects associated with the employee and the store. The matrix $\mathbf{x}_{ijk}$ can contain explanatory variables be defined at any of the levels (day, employee, or store).
Answer: You cannot include either variable since there is no variation in those covariates within each employee. When you perform the demeaning/within transformation, they will drop out of the model. They get absorbed into the fixed effect but are not separately identified. You can only include covariates that vary across time for each employee.
Here's a demonstration:
. webuse pig, clear
(Longitudinal analysis of pig weights)

. xtset id week

Panel variable: id (strongly balanced)
 Time variable: week, 1 to 9
         Delta: 1 unit

. xtdescribe

      id:  1, 2, ..., 48                                     n =         48
    week:  1, 2, ..., 9                                      T =          9
           Delta(week) = 1 unit
           Span(week)  = 9 periods
           (id*week uniquely identifies each observation)

Distribution of T_i:   min      5%     25%       50%       75%     95%     max
                         9       9       9         9         9       9       9

     Freq.  Percent    Cum. |  Pattern
 ---------------------------+-----------
       48    100.00  100.00 |  111111111
 ---------------------------+-----------
       48    100.00         |  XXXXXXXXX

. gen group_id = inrange(id,1,15)

. egen pigs_in_grp = nvals(id), by(group_id)

. xtsum

Variable         |      Mean   Std. dev.       Min        Max |    Observations
-----------------+--------------------------------------------+----------------
id       overall |      24.5   13.86946          1         48 |     N =     432
         between |                   14          1         48 |     n =      48
         within  |                    0       24.5       24.5 |     T =       9
                 |                                            |
week     overall |         5   2.584983          1          9 |     N =     432
         between |                    0          5          5 |     n =      48
         within  |             2.584983          1          9 |     T =       9
                 |                                            |
weight   overall |  50.40509   16.64113         20         88 |     N =     432
         between |             3.953498         43   59.77778 |     n =      48
         within  |             16.17366   20.12731   83.40509 |     T =       9
                 |                                            |
group_id overall |     .3125   .4640498          0          1 |     N =     432
         between |             .4684174          0          1 |     n =      48
         within  |                    0      .3125      .3125 |     T =       9
                 |                                            |
pigs_i~p overall |    27.375   8.352897         15         33 |     N =     432
         between |             8.431514         15         33 |     n =      48
         within  |                    0     27.375     27.375 |     T =       9

. xtreg weight i.week i.group_id c.pigs_in_grp, fe
note: 1.group_id omitted because of collinearity.
note: pigs_in_grp omitted because of collinearity.

Fixed-effects (within) regression               Number of obs     =        432
Group variable: id                              Number of groups  =         48

R-squared:                                      Obs per group:
     Within  = 0.9857                                         min =          9
     Between = 0.0000                                         avg =        9.0
     Overall = 0.9311                                         max =          9

                                                F(8,376)          =    3232.74
corr(u_i, Xb) = 0.0000                          Prob > F          =     0.0000

------------------------------------------------------------------------------
      weight | Coefficient  Std. err.      t    P>|t|     [95% conf. interval]
-------------+----------------------------------------------------------------
        week |
          2  |   6.760417   .4231323    15.98   0.000     5.928414    7.592419
          3  |   13.84375   .4231323    32.72   0.000     13.01175    14.67575
          4  |     19.375   .4231323    45.79   0.000       18.543      20.207
          5  |   25.13542   .4231323    59.40   0.000     24.30341    25.96742
          6  |   31.42708   .4231323    74.27   0.000     30.59508    32.25909
          7  |    37.4375   .4231323    88.48   0.000      36.6055     38.2695
          8  |   44.28125   .4231323   104.65   0.000     43.44925    45.11325
          9  |   50.19792   .4231323   118.63   0.000     49.36591    51.02992
             |
  1.group_id |          0  (omitted)
 pigs_in_grp |          0  (omitted)
       _cons |   25.02083   .2991997    83.63   0.000     24.43252    25.60915
-------------+----------------------------------------------------------------
     sigma_u |  3.9534984
     sigma_e |  2.0729165
         rho |  .78436522   (fraction of variance due to u_i)
------------------------------------------------------------------------------
F test that all u_i=0: F(47, 376) = 32.74                    Prob > F = 0.0000

The collinearity warnings above alert you to the problem and are omitted in the output.
Comment: Jesus, is that stata? D: Just kidding. Thank you for your response! When you say I cannot include either variable, how come I cannot include `branch_id`? Obviously, I would one-hot encode each branch and drop one level (or use `branch_id` as a second index) to tell python those are my fixed effects.
Comment: It is Stata, but exact collinearity is a math fact, so the software does not matter. The branch does not vary for each employee, so demeaning always removes the branch dummy. In your example, both employees work at branch 1, so the average of the branch 1 dummy is also 1 for each of them them, and 1-1=0. For those who work in other branches, the average of branch 1 dummy is 0, so 0-0 is 0. This means the demeaned branch 1 dummy is always zero for everyone. You could only include branch FEs if employees work at multiple branches.


I can't check a checkbox group before submiting a form

Question: I need to validate several checkboxGroups on a form before submiting and I can't do it.
here is my code:

                <form class="form1" action="update-2.php" id="profile" onClick="validate()" method="post">
                    <fieldset class="preguntas">

\ - here I created 7 checkbox groups with different id, I will post one as an exampte- \

                                <input type="checkbox" name="maquillaje[]" class="option" value="Rimel" id="maquillaje">
                                Rimel

                                <input type="checkbox" name="maquillaje[]" class="option" value="Sombra" id="maquillaje">
                                Sombra

                                <input type="checkbox" name="maquillaje[]" class="option" value="Delineador" id="maquillaje">
                                Delineador

                                <input type="checkbox" name="maquillaje[]" class="option" value="Cuidado para sombracelhas" id="maquillaje">
                                Cuidado para sombracelhas

                                <input type="checkbox" name="maquillaje[]" class="option" value="Batom" id="maquillaje">
                                Batom

                                <input type="checkbox" name="maquillaje[]" class="option" value="Batom liquido" id="maquillaje">
                                Batom liquido

                                <input type="checkbox" name="maquillaje[]" class="option" value="Gloss" id="maquillaje">
                                Gloss

                                <input type="checkbox" name="maquillaje[]" class="option" value="Batom que aumenta labios" id="maquillaje">
                                Batom que aumenta làbios

                                <input type="checkbox" name="maquillaje[]" class="option" value="Delineador de labios" id="maquillaje">
                                Delineador de làbios

                                <input type="checkbox" name="maquillaje[]" class="option" value="Primer" id="maquillaje">
                                Primer

                                <input type="checkbox" name="maquillaje[]" class="option" value="Corretivo" id="maquillaje">
                                Corretivo

                                <input type="checkbox" name="maquillaje[]" class="option" value="Base hidratante" id="maquillaje">
                                Base hidratante

                                <input type="checkbox" name="maquillaje[]" class="option" value="Po corretivo" id="maquillaje">
                                Pó corretivo

                                <input type="checkbox" name="maquillaje[]" class="option" value="Blush" id="maquillaje">
                                Blush

                                <input type="checkbox" name="maquillaje[]" class="option" value="Iluminador" id="maquillaje">
                                Iluminador

                                <input type="checkbox" name="maquillaje[]" class="option" value="Bronzer e contorno" id="maquillaje">
                                Bronzer e contorno

                                <input type="checkbox" name="maquillaje[]" class="option" value="Pincéis e outros aplicadores de maquiagem" id="maquillaje">
                                Pincéis e outros aplicadores de maquiagem

                                <input type="checkbox" name="maquillaje[]" class="option" value="Rimel" id="maquillaje">
                                Rimel

                                <input type="checkbox" name="maquillaje[]" class="option" value="Sombra" id="maquillaje">
                                Sombra

                                <input type="checkbox" name="maquillaje[]" class="option" value="Delineador" id="maquillaje">
                                Delineador

                                <input type="checkbox" name="maquillaje[]" class="option" value="Cuidado para sombracelhas" id="maquillaje">
                                Cuidado para sombracelhas

                                <input type="checkbox" name="maquillaje[]" class="option" value="Batom" id="maquillaje">
                                Batom

                                <input type="checkbox" name="maquillaje[]" class="option" value="Batom liquido" id="maquillaje">
                                Batom liquido

                                <input type="checkbox" name="maquillaje[]" class="option" value="Gloss" id="maquillaje">
                                Gloss

                                <input type="checkbox" name="maquillaje[]" class="option" value="Batom que aumenta labios" id="maquillaje">
                                Batom que aumenta làbios

                                <input type="checkbox" name="maquillaje[]" class="option" value="Delineador de labios" id="maquillaje">
                                Delineador de làbios

                                <input type="checkbox" name="maquillaje[]" class="option" value="Primer" id="maquillaje">
                                Primer

                                <input type="checkbox" name="maquillaje[]" class="option" value="Corretivo" id="maquillaje">
                                Corretivo

                                <input type="checkbox" name="maquillaje[]" class="option" value="Base hidratante" id="maquillaje">
                                Base hidratante

                                <input type="checkbox" name="maquillaje[]" class="option" value="Po corretivo" id="maquillaje">
                                Pó corretivo

                                <input type="checkbox" name="maquillaje[]" class="option" value="Blush" id="maquillaje">
                                Blush

                                <input type="checkbox" name="maquillaje[]" class="option" value="Iluminador" id="maquillaje">
                                Iluminador

                                <input type="checkbox" name="maquillaje[]" class="option" value="Bronzer e contorno" id="maquillaje">
                                Bronzer e contorno

                                <input type="checkbox" name="maquillaje[]" class="option" value="Pincéis e outros aplicadores de maquiagem" id="maquillaje">
                                Pincéis e outros aplicadores de maquiagem

I tried to validate it with a php error handler stating
if(empty($_POST['maquillaje'])){
header("location: wahtever.php?check");
}else{ .... all the code to write on the database...}

but it will refresh the page nomatter what,
I also tried to use javascript to validate it

but I had the same result, it won't validate the checkbox, instead will refresh the page even if the checkbox is checked...
also tried a Jquery but I will get the alert textbox all the time and it will never submit the form
I'm a rookie here and probably I making a stupid mistake
PLEASE HELP!!!!
Answer: The jQuery method would likely be your easiest solution.
The main thing you need to add is a "preventDefault" function. This will stop the form from submitting to the backend. Then you can check for blank fields. If there were no errors, submit the form by adding this.submit()

In the Docs: https://api.jquery.com/event.preventdefault/
Comment: Thaks for the tip, really useful, now what if I wanted to check all the 7 checkbox groups before submiting the data. I just add the same code for each one before the else statement?
Comment: You'll need to loop through all elements of the form. Take a look at this [post](https://stackoverflow.com/questions/14120564/how-to-loop-through-all-elements-of-a-form-jquery)


Trying to make a Python project requirements version-free

Question: Imagine a project MyLibrary which used to have its own requirements.txt file specifying all the versions needed by each of the dependencies...
lib_a==0.1
lib_b==0.11
lib_c==0.1.1
lib_d==0.1.2
lib_e==0.1.8

And a project ChildProject which happens to have the same kind of setup, with its own requirements.txt file and everything.
ChildProject uses MyLibrary as it needs some common functionality it has. The problem with this two, is that ChildProject has a library which is also specified in MyLibrary, but with a different version which causes conflict and causing the build to fail.
What I've done to get rid of the problem is to erase the dependencies in MyLibrary and specify the minimum and maximum versions for each of the libraries, specifying those in the setup_requires property within the setup() method...
setup(
    setup_requires=['pbr', 'pytest-runner'],
    install_requires=[
        'lib_a>=0,<1',
        'lib_b>=0,<2',
        'lib_c>=0,<3',
        'lib_d>=0,<4',
        'lib_e>=0,<5'
    ],
    pbr=True,
)

And here is where I get lost...
Should I remove requirements.txt in MyLibrary and leave all the versioning to child projects using ?
If so, how do I know that ChildProject is specifying all of the needed dependencies? What if I miss to specify lib_a in ChildProject?
Does the latest version that complies with the setup_requires constraints gets automatically installed or how does it work? (I ask this because AFAIK, install_requires just specified the constraints but doesn't include any library whatsoever in the project).
Comment: You can build MyLibrary first (as a dependency on your setup.py inside ChildProject), then the next dependency in ChildProject would be the conflicting package used in MyLibrary (I would assume it would force a new install on that one with the version specified in ChildProject). As to whether this will uninstall the previous version and MyLibrary will still work... I am not sure, it might BUILD at least
Answer: General suggestions for managing deps versions:

libraries dont't pin versions (i.e. either install_requires doesn't have version at all, or loose restrictions, i.e. <4). That's what you have already

applications can do whatever needed. In reality, it's highly recommended to pin your dependencies to some exact version (ant better yet — provide hash, to save yourself from forged libs). Reason for this — you can not guarantee 3rd-party libraries to follow semver. Which means that having >2, <3 in your requirements.txt may lead to broken build/deployment, because 3rd party lib released 2.5 which appears to be backward-incompatible with 2.4. So, you must do you best to avoid breaking builds by just re-building in different time. In other words, your build should be idempotent on PyPI state.
In general — you pin version to some state, test your application and commit/save/build/however you deliver. Some time later, you're revising versions (i.e. to update framework or address security patch), updating version in requirements.txt, testing your app with new deps state, if there's no conflicts/broken parts, you "freeze" that state with pinned versions, and build/deploy/etc. This kind of loop gives you space to occasionally update your requirements to stay up to date, and at the same time you have code that will not be broken by just re-installing dependencies.

If you're looking to easier dep management with version, I suggest taking a look at pipenv


Let $a,b \in R$, such that $a \lt b$, $f: [a,b] \rightarrow R$ (continuous). Prove that if f is monotonic in (a,b) then it's also monotonic in [a,b]

Question: Let a,b $\in R$, such that $a \lt b$, and $f: [a,b] \rightarrow R$ (continuous). Prove that if f is monotonic  in (a,b) then it's also monotonic in [a,b].
Could the intermediate value theorem be used to prove this?
Answer: Suppose $f$ is monotonically increasing. Then for any $c \in (a,b)$,
$$f(c)\leq f((1/n) c +(1-1/n)b),$$
for $n\geq 1$ by monotonicity. Taking the limit as $n \to \infty$ and using the continuity of $f$ gives
$$f(c) \leq f(b).$$
Since this holds for all $c \in (a,b)$, $f$ is monotone on $(a,b]$. Similar logic can be used to show that $f(a)\leq f(c)$ for all $c \in (a,b)$, so $f$ is monotonically increasing on $[a,b]$.
Answer:
Could the intermediate value theorem be used to prove this?

That is possible. Assume that $f$ is monotonically increasing in $(a, b)$ but not
in $[a, b]$. Then

$f(a) > f(c)$ for some  $c \in (a, b),$ or
$f(c) > f(b)$ for some  $c \in (a, b).$

Without loss of generality assume the latter. Then
$$
  f(c) > \frac {f(c)+f(b)}2 > f(b)
$$
and according to the  intermediate value theorem,
$$
 f(d) = \frac {f(c)+f(b)}2 \text{ for some } d \in (c, b)
$$
which is a contradiction to $f$ being increasing on $[c, d] \subset (a, b)$.
Comment: @RonaldB: $(f(c) + f(b))/2$ is a value *between* $f(c)$ and $f(b)$, and therefore must be taken by $f$ somewhere between $c$ and $b$. I have changed the answer a bit to make it (hopefully) more clear.
Comment: Thanks for the help. Could you elaborate on where$ f(d) = \frac 12 (f(c)+f(b)) \text{ for some } d \in (c, b)$ came from and how it helps here? having difficulties understanding.
Answer: Like Richard said, continuity of f on $[a,b]$ is the important property we can use.
First observe that $\lim \limits_{\epsilon \rightarrow 0}f(a+\epsilon)=f(a)$ and $\lim \limits_{\epsilon \rightarrow 0}f(b-\epsilon)=f(b)$.
Suppose $f$ is increasing on $(a,b)$, then for all $\epsilon \in (0, \frac{b-a}{2})$, $f$ is also increasing on $(a+\epsilon, b- \epsilon)$. Thus for all x, y in $(a+\epsilon, b- \epsilon)$, if $x<y$, then:
$$f(a+\epsilon)<f(x)<f(y)<f(b-\epsilon)$$
The result follows from our first observation. There are many ways to show this, but continuity of $f$ on $[a,b]$ is key.Best wishes.
Answer: It is possible to establish very easily the following facts:

If $f$ is monotonic in $(a, b)$ then $f$ is monotonic in $[a, b]$.
If $f$ is strictly monotonic in $(a, b)$ then $f$ is strictly monotonic in $[a, b]$.

Here we use provide proof for both the results for functions which are monotonically increasing. The case of decreasing functions is obtained by reversing all the inequalities involved.
So let $f$ be increasing on $(a, b)$ which means that if $x, y \in (a, b)$ with $x < y$ then $f(x)\leq f(y)$. We need to prove that if $a < x < b$ then $f(a) \leq f(x) \leq f(b)$. Let take another number $x'$ such that $a < x' < x$. Then $f(x') \leq f(x)$ and letting $x' \to a^{+}$ we get $f(a) \leq f(x)$ via continuity of $f$. Same way we can prove $f(x)\leq f(b)$. Thus $f$ is increasing on $[a, b]$.
Now let $f$ be strictly increasing on $(a, b)$ so that $x, y \in (a, b)$ with $x < y$ implies $f(x) < f(y)$. Let $a < x < b$ and we prove that $f(a) < f(x) < f(b)$. We choose two number $x, x''$ such that $a < x' < x'' < x$ then we have $$f(x') < f(x'') < f(x)$$ and letting $x' \to a^{+}$ we get $$f(a) \leq f(x'') < f(x)$$ and similarly we can prove that $f(x) < f(b)$. Thus $f$ is strictly increasing on $[a, b]$.


Regression on Negatively Skewed Data

Question: I am trying to explore the relationship between a customer satisfaction rating and a response time (in days).  I have been using linear, logistic and quantile regression, to no avail.  I believe the issues lies with the distribution of the data.  85% of respondents give a 9 or 10 rating (regardless of response time) and 70% of the data lies in the 9/10 rating and the 0-4 day response time.
Since the data is so negatively skewed, I'm looking for some advice on whether or not to normalize the data and if regression is the right method to define the relationship between the variables (and if not, what would be a better method).
I've attached a summary of the data distributions percents.  The range for the rating is 1-10 inclusive and the response rate is continuous, but we limit to 10 days because of low volume for 10+ days.  Any assistance is appreciated.
Comment: The skewness I take as a secondary issue; the major issue is just the lack of relation between rating and response time. For example, the mean rating from these summaries is lowest for time 3 days at 9.265 and highest for 10 days at 9.379! I'd plot summary statistics for each time rather than try to force this into any kind of regression model, because the total fit is likely to be disappointing.
Comment: Can you describe what is the "no avail" when you attempted to use logistic and quantile regressions? What failed in those two techniques? From what it looks, using logistics to predict if anyone would even rate lower than 9 seems reasonable. So, I'd like to know more why it didn't work.
Comment: I would suggest some ordinal logistic regression, for example logistic regression with cumulative link.
Comment: @Penguin_Knight "To no avail" meaning not getting any models with any kind of significance (R^2 <1).
Comment: @NickCox, If that is the case, is there any better way to prove that there is no relationship between the two?
Comment: @Eudora, $R^2$ should be less than $1$ for most of the time. When it's $1$ the model is perfect, which is very rare. The success of a model should not be based on if we can spot a significant association, because there are times in which there is indeed no association.
Comment: See graphs in answer below. But in general there is no proof in data analysis!
Comment: These response values are discrete with the majority of values in one category, so even if there were some reason to try, you simply *can't* 'normalize' them.
Answer: This isn't a complete answer, just an attempt to explore the lack of relationship graphically.
Various plots are naturally possible for these data. Here I give a two-way bar chart or graphical table in which the height of each bar is proportional to the percent in each cell:

and another in which conditional distributions are given for each time:

Regression on Negatively Skewed Data


Combination definition question

Question: I am relatively new to math.
I am confused as to the formula given is this Wikipedia page on
combination, where it states in the first paragraph
$$\displaystyle C^n_k={n\choose k}=\frac{n(n-1)…(n-k+1)}{k(k-1)…1},$$
which can be written using factorials as $\displaystyle\frac{n!}{k!(n-k)!}.$
How do these two formulas equate to each other? In the first formula I understand the denominator is $k!$, but what does '$n(n-1)...(n-k+1)$' mean?
Answer: It means the product starting at $n$ and going backwards several times, multiplying each time along the way, until we get $k$ numbers. We thus get
$$n \times (n-1) \times (n-2) \times (n-3) \times \cdots \times (n-(k-1))$$
Notice how $(n-1)$ is the point where we have $2$ numbers, $(n-2)$ is the point where we have $3$, and so on, so that $(n-(k-1))$ is the point with the $k^{th}$ number. We often rewrite this last as $(n-k+1)$ since it's simpler.
Some examples of this, explicitly, are below. Notice how each will have $k$ numbers being multiplied together, the integers from $n-k+1$ all up to $n$.

$n=3,k=2$ gives the product of $3 \times 2$
$n=4,k=2$ gives the product of $4 \times 3$
$n=5,k=4$ gives the product of $5 \times 4 \times 3 \times 2$
$n=6,k=3$ gives the product of $6 \times 5 \times 4$

Of course, then, notice that you can extend the original product of $n \times (n-1) \times \cdots \times (n-k+1)$ all of the way down to $1$, by multiplying by the intermediate integers, which would be the next lowest ones: $(n-k)$, $(n-k-1)$, $(n-k-2)$, and so on. But to keep it equal, you will need to divide by those factors as well. Thus,
$$n(n-1)\cdots (n-k+1) = \frac{n(n-1)\cdots (n-k+1)(n-k)(n-k-1)\cdots(2)(1)}{(n-k)(n-k-1)(n-k-2)\cdots(2)(1)}$$
But notice! The numerator is precisely the definition of $n!$, and the bottom is that for $(n-k)!$ as well! That means,
$$n(n-1)\cdots (n-k+1) = \frac{n!}{(n-k)!}$$
Thus, when one says that
$$\binom n k = \frac{n(n-1)\cdots(n-k+1)}{k!}$$
it is equivalent to say that, substituting our new expression in terms of factorials in for the product,
$$\binom n k = \frac{n!}{k!(n-k)!}$$
Answer: $n(n-1)\cdots(n-k+1)=\frac{n(n-1)\cdots(n-k+1)(n-k)(n-k-1)\cdots1}{(n-k)(n-k-1)\cdots1}=\frac{n!}{(n-k)!}$
hence:$$\frac{n(n-1)\cdots(n-k+1)}{k!}=\frac{n!}{k!(n-k)!}$$
Comment: Thanks, I see it now.

Combination definition question


TypeError: Missing 1 required positional argument: 'Caption'

Question: So I have 2 .py files:

FW_Engine.py
test.py

In FW_Engine.py, I have this code:
import pygame

pygame.init()

class Display:

  def __init__(self, window, button):
      self.window = window
      self.button = button

  def Window(self, WindowWidth, WindowHeight, Caption):
      GameDisplay = pygame.display.set_mode((WindowWidth, WindowHeight))
      pygame.display.set_caption(Caption)

  def Button(self, DisplayWindow, Position_X, Position_Y):
      GreyColor = (96, 96, 96)
      pygame.draw.rect(DisplayWindow, GreyColor, (Position_X, Position_Y, 100, 20))

And on test.py, I have this code:
from FW_Engine import Display
import pygame

pygame.init()

GameDisplay = Display.Window(800, 600, "TestTitle")

I keep getting this error tho:
TypeError: Window() missing 1 required positional argument: 'Caption'

But as you can see, I have all 3 required arguments supplied into the function call. What's the problem?
EDIT: BOTH .py files are in the same directory.
Answer: The problem is that you try to call Display.Window as if it were a static method (ie does not need an instance), but it is not. Since it requires an instance, one argument is missing (the 3 arguments that you provided are shifted left, ie self is 800, etc) hence Caption is not provided as the error suggests.
You have 2 options:

Call Window from a Display instance:
Display(window, button).Window(800, 600, "TestTitle")

Another, less preferable way, would be to pass a Display instance to
Display.Window:
display = Display(window, button)
Display.Window(display, 800, 600, "TestTitle")

Since Display.Window does not reference self at all, it can be a static method, then the rest of your code will work as-is:
class Display:
    def __init__(self, window, button):
        self.window = window
        self.button = button

   @staticmethod
   def Window(WindowWidth, WindowHeight, Caption):
       GameDisplay = pygame.display.set_mode((WindowWidth, WindowHeight))
       pygame.display.set_caption(Caption)

Comment: To me, the second way seems more readable. Any pros/cons between them?
Comment: @KitsuneMakoto No. The first is actually a syntactic sugar for the second. BTW see the update answer that shows how to use `staticmethod` properly.
Comment: Will mark as accepted answer, staticmethod example solved my issue and helped me understand. :)
Answer: Your Window method is not a static method, it's a instance method, so you can not call it without instantiating Display object.
The first argument of Window method is self which should reference to the object you create, for this case it is Display object.
But actually you don't instantiate it, so when you call Window method, you lack the self argument, that's why you see the TypeError.
Try to use it as below, call Window method after creating Display object.
GameDisplay = Display(window, button).Window(800, 600, "TestTitle")


Aggregate initialization in C++

Question: I have a base class Event, from which concrete events derive:
struct Event
{
};

struct CollisionEvent : Event
{
    //CollisionEvent(Entity entityA, Entity entityB) : entityA(entityA), entityB(entityB) {}

    Entity entityA;
    Entity entityB;
};

this class is a POD, and I should be able to perform aggregate initializaion. But the following code fails to compile:
called from application:

eventBus->DispatchEvent<CollisionEvent>(mEntities[i], mEntities[j]);

in EventBus.h:

template <typename TEvent, typename... Args>
    void DispatchEvent(Args&&... args)
    {
        auto it = mEventHandlers.find(typeid(TEvent));

        if (it != mEventHandlers.end())
            for (auto &&eventHandler : it->second)
                eventHandler->Invoke(TEvent{ std::forward<Args>(args)... });
    }

saying that it cannot convert initializer list to TEvent. Why?
Comment: There is the missing base `Event` init. `CollisionEvent {{}, entityA, entityB}`.
Comment: Which C++ standard are you using? Pre C++17 inheritance disqualifies aggregate.
Comment: @Yksisarvinen C++17
Comment: @Jarod42 so I have to explicitly initialize the base?
Answer: For aggregate initialization you need to initialize the base class, even if it's empty.
eventBus->DispatchEvent<CollisionEvent>(Event{}, mEntities[i], mEntities[j]);

There were also some changes regarding what is and what isn't an aggregate in recent standards - until C++17 a class having a base class can't be aggregate-initialized, so you can't make it work in C++14. (see https://godbolt.org/z/Pq5PfecKq)

Aggregate initialization in C++


Show the following space is Banach

Question: Show that $(X, \| \cdot\|_\star)$ is a Banach space, where $X$ is the following linear space:
$$
X = \left\{ f : \mathbb{N}_{\ge 1} \to \mathbb{R} \mid \|f\|_\star := \left( \sum_{k=1}^\infty (k+1) |f(k)|^2 \right)^{1/2} < \infty \right\}.
$$
Here's my work: Let $\epsilon>0$ be given. Let $(f_n)$ be Cauchy in $X$. Then, there is $N \in \mathbb{N}$ such that whenever $n,m \ge N$, we have
$$
(\forall k) \quad   |f_n(k) - f_m(k)| \le \|f_n - f_m\|_\star < \epsilon
$$
Since $\mathbb{R}$ is complete, each $f_n(k)$ converges to some $a_k \in \mathbb{R}$. Define a new function $f$ by $f(k) = a_k$. Then, we want to show $\| f_n - f\|_\star \to 0$. But this is where I'm stuck.
$$
\|f_n - f\|_\star^2 = \sum_{k=1}^\infty (k+1) |f_n(k) - a_k|^2 \stackrel{?}{\to} 0
$$
The rate of convergence for $f_n(k) \to a_k$ obviously depends on $k$, so I can't take a supremum. Moreover, I see no way to push the limit within the sum.
The final step might depend on the $k+1$, which I haven't made use of.
Or maybe I have approached the problem incorrectly, but this seems quite natural to me . . .
Thank you for the help.
Comment: It may be easier to consider the linear map $T:\ell^2 \to \ell^2$ given by $$(x_k) \mapsto \left( \frac{x_k}{\sqrt{k+1}} \right)$$ This map is linear and bounded, hence continuous. Now you are simply looking at $T^{-1}(\ell^2)$, which must be closed and hence complete.
Comment: @PrahladVaidyanathan Can you expound on this? $T$ is not bounded below, so $T^{-1}$ does not exist . . .
Comment: It means inverse image not inverse
Comment: Ok I should have realized. So $T$ is bounded (continuous) and since $\ell^2$ is trivially closed, the inverse image $T^{-1}(\ell^2)$ is closed. That is, $T^{-1}(\ell^2) \subset \ell^2$ is closed, meaning it must be complete as well. (I think this is correct).
Comment: Out of curiosity, do you have any insight on the original method I was trying to use?
Answer: Continuing where you left off, you have two things to show:

Does the new sequence $f$ belong to $X$?

For this, note that $(f_n)$ is Cauchy and hence norm-bounded. Thus, $\exists R>0$ such that
$$
\sum_{k=0}^{\infty} (k+1)|f_n(k)|^2 \leq R \quad\forall n\in \mathbb{N}
$$
For each $m\in \mathbb{N}$, this implies
$$
\sum_{k=0}^m (k+1)|f_n(k)|^2 \leq R
$$
Let $n\to \infty$ to conclude that
$$
\sum_{k=0}^m (k+1)|f(k)|^2 \leq R
$$
This is true for all $m \in \mathbb{N}$, so letting $m\to \infty$, you see that $f\in X$ as required.

Does $\|f_n - f\|_{\ast} \to 0$?

For this, once again use a similar trick: For $\epsilon > 0, \exists N_0 \in \mathbb{N}$ such that
$$
\|f_n - f_l\|_{\ast} < \epsilon \quad\forall n,l\geq N_0
$$
In particular, for $m \in \mathbb{N}$ fixed
$$
\sum_{k=0}^m (k+1)|f_n(k) - f_l(k)|^2 < \epsilon
$$
Let $l \to \infty$, and then $m \to \infty$ to conclude that $\|f_n - f\|_{\ast} \leq \epsilon$ for $n\geq N_0$ as required.

This is all very reminiscent of proving that the $\ell^p$'s are complete, which is why I recommended exploiting that in my remark.
Comment: Excellent! I will have to review that proof about the completeness of $\ell^p$. Thank you

Show the following space is Banach


Is OpenVPN right for this? If not, what is?

Question: I have a server sitting in a data center.  It's running Linux.  WAN interface on eth0 connected to the public Internet; LAN interface on eth1 connected to the data center's network on 10.0.0.0.
The machine is running a group of services on ports n, p and q; and a group of services on ports r, s and t.
It's firewalled on the WAN interface so nothing is open to the public internet.
I want users to be able to connect to the machine with OpenVPN (or whatever, don't care what as long as it's encrypted and secure).  The users should be able to then connect to the services on ports n, p and q, but NOT to the services on ports r, s and t or the 10.0.0.0 network.
I also need to track bandwidth consumption by user.  It would be a big bonus if I could cap the user per unit time (eg 1GB/week, 10GB/mo), and/or limit their sustained transfer rate (eg 100KB/sec); allowing them to burst faster would be really great, too.
I'm a total OpenVPN noob.  I'm not even sure it's right for the task, though somebody suggested it.  It's clear that using ssh wouldn't be a great solution, since it'd depend on a bunch of restrictions in the authorized_keys file and bandwidth monitoring/capping would be difficult.
I welcome any suggestions.
Answer: OpenVPN will get you basic connectivity from the client to the host.  From there, it's just a matter of configuring iptables or your firewall of choice to allow traffic to the services and devices you want available.  OpenVPN uses its own TAP/TUN interface and a separate network, so you should be able to create rules to lock down traffic to just about anything you want to.
You will need to use some other tools to get the bandwidth consumption.  Maybe someone else can chime in on that.
Answer: OpenVPN will not do - it can do the dial in, not the rest.
You basically need a proper VPN endpoint that has all functionality. I would put up a server for that - with Mikrotik RouterOS, likely a Miktrotik 1xxx router, they are quite cheap and can do all that.
If you like hand doing it, get Linux and get complex wwith IpTables for firewalling (port limitation) and a LOT of other software for bandwidth control.
Comment: I should mention it's a cloud host, so anything I do will need to be in software -- and given the cost structure, probably on the same box. Thanks for the information!
Comment: Well, RouterOS can also be purchased for Intel installation: Isn't it always funny how "Cloud computing" comes back as a bad solution for pretty much most non trivial cases? I am all for cloud computing, but I run a private cloud where I control the hardware. A LOT cheaper.


What is the correct way to move an rss feed? Is there a temporary workaround for google reader users?

Question: I run a website that has published its RSS feed at a given location for years. However, I'm now forced to move the feed to another URL. Let's say the original URL was www.example.com/rss.xml and the new address is feeds.example.com/example.
I see from google webmaster tools that there's lots of activity picking up feeds from the existing URL.
I understand that HTTP-correct way of signalling a move to the feed fetcher is for the HTTP header on www.example.com/rss.xml to send a response code 301 "Moved Permanently" and the target URL.
With existing constraints on the site, I can't do this right now. Is there a way I can tell google reader about the redirection? Say through google site tools or maybe some other way?
Answer: As you said, 301 is THE correct way. Is the server Apache and if so, Rewrite is disabled in .htaccess?
Howto redirect feed urls to feedburner in .htaccess
If you have access to the code of the whatever-your-blog-engine-might be, you could use the language to modify the HTTP headers to return the "301 MOVED PERMANENTLY" instead of 200 FOUND". If so, which software/language are you running?
Comment: The .htaccess redirection worked fine thanks! (Using Apache under Linux)


wrapping templated function call in another function call

Question: Anyone know if it is possible to do something similar to the following:
void my_inner_func(int i, double d, ...) {
    // do stuff here
}

template <typename Func, typename... Args>
void my_outer_func(Func&& f,Args&&... args){
    // do other stuff here, put this inside loop, etc
    f(std::forward<Args>(args)...);
}

template <typename OuterFunc,typename InnerFunc,typename... Args>
void func(OuterFunc&& outer, InnerFunc&& inner, Args&&...args) {
    outer(std::forward<InnerFunc>(inner),std::forward<Args>(args)...);
}

Where the calling code might look something like this:
func(my_outer_func, my_inner_func, 1, 2.0, ...);

The issue that I am running into is that the type of the OuterFunction cannot be deduced. I've tried a bunch of different things including converting func to a functor and making OuterFunc a template template parameter.
Comment: `my_outer_func` needs to be wrapped in a lambda when passing it to `func`. Or it must be a lambda to begin with.
Comment: @HolyBlackCat thanks for your reply. Are you able to elaborate? I tried a few things with lambdas, but couldn't get it to work. Wrapping `my_outer_func` in a lambda still gave me the same errors.
Answer: my_outer_func needs to be wrapped in a lambda when passing it to func:
func([](auto &&... params){my_outer_func(decltype(params)(params)...);}, my_inner_func, 1, 2.0);

Where decltype(params)(params) is equivalent to std::forward<decltype(params)>(params), but with less typing.
Or, my_outer_func can itself be a lambda:
auto my_outer_func = []<typename Func, typename... Args>(Func&& f,Args&&... args)
{
    f(std::forward<Args>(args)...);
};

Explicit template parameters in a lambda are a C++20 feature. Pre-C++20 you'd have to use auto, like in the first example.
Comment: I accepted the other answer because I saw that one first, but this is equally helpful. Again, thanks so much!
Answer: It works if you make my_outer_func a function object rather than a function:
struct my_outer_func {
    template <typename Func, typename... Args>
    void operator()(Func&& f,Args&&... args) const {
        // do other stuff here, put this inside loop, etc
        f(std::forward<Args>(args)...);
    }
};

Then:
func(my_outer_func(), my_inner_func, 1, 2.0);

If you don't like the parentheses at the call site, you can remove them if you create a global struct instance instead:
struct {
    template <typename Func, typename... Args>
    void operator()(Func&& f,Args&&... args) const {
        // do other stuff here, put this inside loop, etc
        f(std::forward<Args>(args)...);
    }
} my_outer_func;

Comment: @JacobMerson Your original code didn't work because `my_outer_func` didn't have a type until template arguments are substituted into it, but a type is needed to pass it into another function. Template lambdas (or structs with templated `operator()`, which are the same) don't have this limitation, because the lambda itself has a specific type, regardless of its templated `operator()`.
Comment: My solution (and the lambda solution) works because `my_outer_func` is now a non-template.  The template is only found when you "call" it, at which point the arguments are known and the template parameters are deduced.
Comment: Thanks. I just realized that as I was staring at it. This makes a ton of sense now that I see how it works.
Comment: Thanks! I'm not sure that I completely understand how this solves the issue but it does work. I guess this must have to do with the order in which the template parameters are deduced at the class/function scope vs the method scope? Anyways thanks!


Sample size estimation for MANOVA

Question: I am trying to run a replication of a study which used a factorial design (2x2) with three DVs (dependent variables) and subsequently ran three ANOVAs to test their hypotheses. Given that the DVs in their study are highly correlated (they reflect different proportions and therefore add up to 1), I want to do a MANOVA instead.
To calculate the sample size necessary for my replication I can use the effect sizes from their ANOVAs (around Eta squared = 0.03/0.05, so quite small) and compute an average N. Instead, I want to estimate a necessary sample size for a MANOVA design which has more power. Given that I don't have Pillai's trace to begin with this leads to guessing. Anybody know a better idea?
Answer: You can use sample size determination software that has MANOVA capability, such as PASS.  Be advised, however, that you will need to estimate the components of the variance-covariance matrix, as this is part of the input.
Comment: I don't know why you feel that you need to run three ANOVAs in order to estimate a sample size for MANOVA.  Indeed, running multiple ANOVAs won't provide any info that would help you estimate the covariances that must be input into a MANOVA sample size routine.
Comment: It's not that I feel like it, I rather want to understand what the right choice is. Is there anyway of estimating a sample size for MANOVA based on the results on the paper or do I just have to skip doing a MANOVA and replicate the three ANOVAs (meaning a significantly higher sample size).
Comment: Yes, I am using GPower, which has this function too. The problem is rather in choosing the correct solution. Using multiple ANOVAs to somehow estimate a sample size for a MANOVA or ignoring the MANOVA option and redo the original with three ANOVAs.

Sample size estimation for MANOVA


Icons on top of footer background-image

Question: I'm in the process of learning but I have a problem. I have a footer done with the background-image in css, made into a link. Used text-indent: -9999px; to get rid of the H1 on top of the footer image. I was told to write the h1 in there to be semantically correct so search engines still see it. And then hide it with the text-indent. I want to put four social media icons on top of that footer that are clickable as a link. I keep getting stuck.

Goodbye, feel free to follow

And this is my CSS.
#footer {
    background-image: url(../images/footer.png);
    height:214px;
    width: 960px;
    background-repeat: no-repeat;
    background-position: center;
    margin: 0 auto;
    border-style: solid;
    border-width: 1px;

}

#footer a {
    text-indent: -9999px;
    height:214px;
    width:100%;
    display:block;

}

This is the footer I am trying to make.
Thanks
Comment: Why are you using `text-indent: -9999px;`? What text do you want to get rid of?
Comment: I am using it to get rid of the H1 on top of the footer image. I was told to write the h1 in there to be semantically correct so search engines still see it. And then hide it with the text-indent.
Comment: That's actually against search engines' TOS. You can't put an element in there just for the search engine, and hide it from everybody else.
Comment: Ok, git rid of it. Positioned the icons and they are clickable links. Is there a way to make the rest of the footer background-image another link? If I try to link it, the icons jump and get messed up.
Answer: It is the text-indent which makes the images invisible. Remove it.
#footer a {
    height:214px;
    width:100%;
    display:block;
}

Answer: You need to create your icon links in css - you need one for each icon
.facebook a:link {
    width: 214px;
    height: add height here
    margin-right: 15px;
    display:block;
    background:transparent url('../images/facebook.png')center bottom no-repeat;
        background-size:25px 25px;
}
Put this div in you footer where you want it.
Repeat sets for other Icons
Answer: Matewka is right just remove the text-indent. You only need that to remove text you don't want to show on the site, but you want it there for seo bots to see.

Icons on top of footer background-image