Is Bonferroni Correction Appropriate for this Analysis?

Question: Suppose I have performed a study wherein I compare a novel intervention (N) against the standard intervention (S). Participants are assigned to N or S randomly, and the study is performed. There are two outcome variables, A and B.
My question:
With only two outcome variables, is it appropriate and/or necessary to apply a Bonferroni correction to my analysis? If N shows statistically significant improvement in both outcomes, but S does not, can I reject the null hypothesis that N has a more significant effect than S?
In other words, could the Bonferroni correction possibly lead to a false-negative when the number of comparisons is only 2? And is there a way to detect whether Bonferroni correction is leading to a false negative?
Comment: Do you compare N vs S for outcome A and also N vs S for outcome B?
Comment: Yes, although A and B are not necessarily independent.
Answer: Strictly speaking, you should adjust for multiplicity when there is more than one comparison, so the answer is yes. Another possibility is MANOVA with a two-dimensional response.
Answer:
If N shows statistically significant improvement in both outcomes, but S does not, can I reject the null hypothesis that N has a more significant effect than S?

"More significant effect" — yes, but is there any use in such a statement? "Significantly higher improvement" — definetely not. You have to compare two treatments explicitly to be able to claim that. Imagine treatment N making small barely significant improvement, and treatment S — small barely unsignificant one. Since effect size of S eff(S) is greater than zero, it could happen that eff(N)-eff(S) does not differ from zero siginificantly, while eff(N) itself does.


Combine data and make less rows in table?

Question: I currently have a script that fetches data from my MikroTik router and then inserts it into my database but It creates thousands and thousands of rows.
Is there anyway to combine the data per src and dst IP address and then insert it into the database or is there a better solution to store accounting data.
My server runs a cron job every 5 minutes to run the script.
All my accounting data automatically gets a time stamp by sql when it is inserted into the database (CURRENT_TIMESTAMP).
Here is my current script:
#!/usr/bin/env php
<?php
    //Include needed files
    require 'config.php';
    require ("html/includes/routeros_api.class.php");
    require ("html/includes/formatbytes.php");
    require ("html/includes/converttobytes.php");

    //Set ini
    ini_set ("expose_php",$ExposePHP);
    ini_set ("display_errors",$DisplayErrors);
    ini_set ("max_execution_time","90000");

    //UPDATE ACCOUNTING
    //Connect to database
    $conn = mysqli_connect($SQLserver, $SQLusername, $SQLpassword, $SQLdatabase);
    if (!$conn) {
        //die("Could not connect: " . mysqli_connect_error());
        die("Error Connecting to database!");
    }

    //Fetch accounting data from router
    $routerconnect = "http://$RouterIP:$WebPort/$AccountingLocation";
    $orig = file_get_contents($routerconnect);

    foreach ( explode( "\n", $orig ) as $line ) {
        if ( trim( $line )) {
            list( $src, $dst, $bytes, $packets ) = explode( ' ', trim( strip_tags( $line )));

            //Create Insert query for accounting data
            $sql = "INSERT INTO ip_accounting (src_address, dst_address, bytes, packets) VALUES ('$src', '$dst', '$bytes', '$packets')";

            //Execute query
            $result = mysqli_query($conn,$sql);
        }
    }
    echo ("Accounting updated!");
?>

Comment: what do you mean by *Is there anyway to combine the data per src and dst IP address* ?
Comment: You can only really combine them if they are all the same. Otherwise the bytes and packets may seem useless to keep around, since it would only be storing one of those values per src/dst address. If you want to ADD bytes to bytes and packets to packets by unique src/dst address.... you would first try to UPDATE the row, and if not exist, INSERT a new row.
Comment: That is pretty much what I'm wanting to do but my problem is that if I UPDATE, my accounting system will not work correctly as It will be updating with old timestamps and vica versa... I actually need the PHP script to combine the bytes with bytes and packets with packets with the all src and dst matching each other and then insert it into the database
Comment: **WARNING**: When using `mysqli` you should be using [parameterized queries](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) and [`bind_param`](http://php.net/manual/en/mysqli-stmt.bind-param.php) to add user data to your query. **DO NOT** use string interpolation or concatenation to accomplish this because you have created a severe [SQL injection bug](http://bobby-tables.com/). **NEVER** put `$_POST`, `$_GET` or **any** user data directly into a query, it can be very harmful if someone seeks to exploit your mistake.
Comment: Note: The object-oriented interface to `mysqli` is significantly less verbose, making code easier to read and audit, and is not easily confused with the obsolete `mysql_query` interface. Before you get too invested in the procedural style it's worth switching over. Example: `$db = new mysqli(…)` and `$db->prepare("…")` The procedural interface is an artifact from the PHP 4 era when `mysqli` API was introduced and should not be used in new code.
Comment: A lot of problems can be detected and resolved by [enabling exceptions in `mysqli`](https://stackoverflow.com/questions/14578243/turning-query-errors-to-exceptions-in-mysqli) so mistakes aren't easily ignored.
Comment: Um okay now this got a whole lot more complicated... I am new to both PHP and MySQL
Answer: I have updated my code to use a different method, instead of storing IP accounting data in a table, data is accounted and then updated in a traffic_counters table
$API->write('/ip/accounting/snapshot/take',true);
        $READ = $API->read(false);
        $ARRAY = $API->parseResponse($READ);

        $API->write('/ip/accounting/snapshot/print',true);
        $READ = $API->read(false);
        $ARRAY = $API->parseResponse($READ);

        foreach($ARRAY as $ACCOUNTING) {
            $ip_src = $ACCOUNTING['src-address'];
            $ip_dst = $ACCOUNTING['dst-address'];
            $bytes = $ACCOUNTING['bytes'];

            if(isset($config['debug']) AND ($config['debug'] == true)) {
                echo "Checking $ip_src -> $ip_dst bytes: $bytes\n";
            }

            //Check if ip in use UPLOAD
            $query = "SELECT service_id, ip_address FROM service_info WHERE ip_address='$ip_src' AND deleted='0'";
            $result = mysqli_query($mysql_connection, $query);
            $row = mysqli_fetch_array($result);

            if(mysqli_num_rows($result) > 0) {
                $service_id = $row['service_id'];
                //Update Download Traffic
                $check_if_exist_query = "SELECT * FROM traffic_counters WHERE service_id='$service_id' AND date=CURRENT_DATE()";
                $check_result = mysqli_query($mysql_connection, $check_if_exist_query);
                $check_num_rows = mysqli_num_rows($check_result);

                if($check_num_rows == 0) {
                    $add_query = "INSERT INTO traffic_counters (service_id, upload_bytes, date) VALUES ('$service_id', '$bytes', CURRENT_DATE());";
                    $add_result = mysqli_query($mysql_connection, $add_query);
                } else {
                    $update_query = "UPDATE traffic_counters SET
                                        upload_bytes = upload_bytes + $bytes
                                        WHERE service_id='$service_id' AND date=CURRENT_DATE();
                                    ";
                    $update_result = mysqli_query($mysql_connection, $update_query);
                }
            }

            //Check if ip in use DOWNLOAD
            $query = "SELECT service_id, ip_address FROM service_info WHERE ip_address='$ip_dst' AND deleted='0'";
            $result = mysqli_query($mysql_connection, $query);
            $row = mysqli_fetch_array($result);

            if(mysqli_num_rows($result) > 0) {
                $service_id = $row['service_id'];
                //Update Download Traffic
                $check_if_exist_query = "SELECT * FROM traffic_counters WHERE service_id='$service_id' AND date=CURRENT_DATE()";
                $check_result = mysqli_query($mysql_connection, $check_if_exist_query);
                $check_num_rows = mysqli_num_rows($check_result);

                if($check_num_rows == 0) {
                    $add_query = "INSERT INTO traffic_counters (service_id, download_bytes, date) VALUES ('$service_id', '$bytes', CURRENT_DATE());";
                    $add_result = mysqli_query($mysql_connection, $add_query);
                } else {
                    $update_query = "UPDATE traffic_counters SET
                                        download_bytes = download_bytes + $bytes
                                        WHERE service_id='$service_id' AND date=CURRENT_DATE();
                                    ";
                    $update_result = mysqli_query($mysql_connection, $update_query);
                }
            }
        }
        $API->disconnect();


Need to configure Android libs on every Eclipse start

Question: After several years with Eclipse and Android development this combination is driving me nuts.
On every start of Eclipse the lib settings I've configured on the page 'Project/Properties/Android' section 'Lib' need to be re-applied.
After a Eclipse restart all existing projects are marked in red. For every project I have to select that project, change to the page described above, remove all Libs, hit Apply, re-enter the same Libs and hit apply again. .classpath and .project look ok. It's the latest Android SDK and the latest Helios Eclipse release. MotoDEV is installed as plugin.
This is a stupid and time-consuming process. Please, has anybody an idea what's wrong with Eclipse (or the Android SDK) or my configuration?
Many thanks in advance.
Comment: Did a fresh install already, last time last week. I did it already so many times in these years. That future day a new tool comes around the corner that's prepared for Android development I would switch in that second.
Comment: Never had this problem with Eclipse and Android SDK, but didn't ever tried MotoDEV plugin; maybe this is the problem!?
Answer: Which OS are you using and is it 32- or 64-bit? Are you logged in as root/administrator or as a regular user? This sounds suspiciously like the ~/.eclipse folder isn't getting written correctly.  We can look at this in MOTODEV Studio and see if it's something unique to us, but it definitely is strange behavior.
Update: one of the MOTODEV Studio team says this is a known bug in ADT when using linked folders. http://code.google.com/p/android/issues/detail?id=14217
Comment: Windows 7 32bit. I'm user with administrator rights. In the past this did not happen on a daily base. After installing MotoDev installation it's on every Eclipse start now. Is it possible to use individual  MotoDev features, especial the language translation utility, without using Eclipse integration?
Comment: Wait, during the last installtion I used the folder C:\My Programs\Android SDK. I changed the path to the shortname (8.3) and all was working as expected. Perhaps one of the tools has problems with these shortnames.
Comment: We've not had problems with shortnames in the past, but we'll look. As for using MOTODEV Studio features without the rest of Eclipse features, you could do a separate install of the product. Studio will open "plain Eclipse" projects without any changes so long as only one copy has the workspace open at the same time.
Comment: Some of the Android SDK tools do not like being in a path with spaces. Proguard is one that comes to mind, but there may be others. I would suggest putting the SDK itself outside the "Program files" hierarchy and into a folder with no spaces (e.g. C:\Android).
Comment: Stupid me ;-) Having 261 chars in a path is such a new feature - I couldn't resist to use it immediately when I read about it. Thanks for your answers. I will re-install these tools on my DOS 3.1 ahm, Windows 7 ;-)


How to deploy multiple database on Team build

Question: I tried the following in MSBuild Arguments but this didn't work out.
<code>/t:Build;Publish /p:SqlPublishProfilePath=McMData1.local.publish.xml
/p:SqlPublishProfilePath McMData1.local.publish.xml
</code>
Answer: You can only specify one SqlPublishProfilePath value. You can create another msbuild command task to publish another database project separately or create another build definition.
Also, you could make the database properties inside the xml file command line driven , but you can still only specify one .xml file and have one deployment.


is my following fingering even a thing?

Question:
My trouble is with the LH in the bass clef, I start with thumb on E4, then index on B3, then pinky on E3, spanning an octave, then switch to thumb on E3 so my pinky is ready to jump to A2 in the next measure.
The switch from pinky to thumb at E3, is it very bad practice? I'm very new to piano just trying to figure out fingerings.
Answer: No its not bad practice. There's a lot of variations in fingering that you can do for this; just do whatever makes it  manageable and sound good.
If you have long fingers you can do 2 1 2 2 5 as well, but that might not work for faster tempi.
Answer: I think either LH: 1 2 5 4-1 5 or 1 2 5 1 5 would feel OK. 4-1 being a silent finger change.
Answer: Since everything in the first bar is part of the same harmony, you may well be using pedal for the whole bar. In that case, when you need to bounce off the low E, it'll sound like you're still holding it down anyway, giving you time to let go and move to the low A.
That said, as in the other answers, whatever works for you. The only real rule on fingering is to find (by trial and error!) your best option. It may well be no-one else's but isn't that better than trying to play, with difficulty, what someone else says is the way to do it?

is my following fingering even a thing?


What are good values for autocorrelation, Gelman, and cross-correlation in rjags?

Question: I don't want to post my whole code since it is long, so I will only post part of it:
model <- jags.model('model.txt', data=previous, inits=inits, n.chains=3)

update(model, 20000)
mcmc_samples <- coda.samples(model, variable.names=c('b.0','b.X', 'b.Ratio', 'b.pct', 'b.per',),n.iter=200000,thin=100)
post_samples <- jags.samples(model, variable.names=c('b.0','b.X', 'b.Ratio', 'b.pct', 'b.per',),n.iter=200000,thin=100)

I then checked the Gelman diagnostic, cross correlation, and autocorrelation.
gelman.diag(mcmc_samples)
crosscorr(mcmc_samples)
autocorr.plot(mcmc_samples)

For the gelman, the highest Upper C.I.  for a variable I got was 1.08. I also got a few values in the .42-.46 range for the crosscorr. Are these acceptable?
However, for the autocorrelation, the plots for some variables clearly did not converge to 0. How can I improve this? Do I have to exclude some variables from the regression and MCMC?
Or do I have to increase the number of iterations or burn-ins? If so, how do I do that?
Comment: Andrew Gelman is definitely one of the better values of Gelman.
Comment: @Sycorax ...it takes also other values, e.g. https://en.wikipedia.org/wiki/Gelman
Answer: It's hard to suggest excluding variables without seeing your model. With the code you post above, you can increase the burn-in steps by increasing the number in the call to jags.update().  The number of iterations is indicated with the value you set as n.iter.  It doesn't appear the call to jags.samples() is doing anything for you here.
There are a lot of opinions out there about convergence, but in general I look for a Gelman-Rubin statistic less than 1.05.


Quarter counter (kotlin)

Question: Ok, so first off I want to say that I am a newer programmer and I'm self taught. I'm currently trying to wrap my mind around how I would make a program (I'm using Kotlin) that would count the number of quarters out of a give value, and state the left over change.
so if I type input: 1.45
output will tell me:
5 quarters
0.20 Change
Now, I have done research on void methods, but I'm still confused on what that looks like. would anyone be willing to help me out on how id get started with this?
I mean like a quarter in terms of USD. So if you have $1.40 / $0.25 (quarter) = 5 Quarters and $0.20 left over. So I'm trying to make something that counts currency. I already have a weak code that calculates the math, but I need the number of quarters and left over change separated on 2 different lines of output.
Comment: Good question and my apologies for not specifying. I mean like a quarter in terms of USD. So if you have $1.40 / $0.25 (quarter) = 5 Quarters and $0.20 left over. So I'm trying to make something that counts currency. I already have a weak code that calculates the math, but I need the number of quarters and left over change separated on 2 different lines of output.
Comment: Check my answer in a similar question --> https://stackoverflow.com/a/70188551/16572295.
Answer: fun main() {
    val input = "1.45"

    // here you convert the input into minor units, e.g. $1.45 => 145 cents
    val total = (input.toFloat() * 100).toInt()

    // here you get whole number of quarters
    val quartersCount = total / 25

    // here you get the change and convert it back to major units (20 cents => $0.2)
    val change = (total - 25 * quartersCount) / 100f

    println("$quartersCount quarters")
    println("${"%.2f".format(change)} Change")  // bit more complex just to keep 2 decimal places
}

Comment: @Alex.T it's just an illustration of algorithm to a "newer programmer". Float money is discouraged from using in commercial software which is obviously not the case here
Answer: You can do println to put each of the outputs on seperate lines
fun main() {
    change(1.25)
    changeWithNames(1.25)
}

fun change(x: Double) {
    println(x.div(0.25).toInt()) // toInt to cut off the remainder
    println(x.rem(0.25).toFloat()) // toFloat so that it rounds to the nearest hundreds place
}

fun changeWithNames(x: Double) {
    println("${"%s".format(x.div(0.25).toInt())} quarters")
    println("${"%.2f".format(x.rem(0.25))} Change")
}

fun changeWithDimes(x: Double) {
    var q = x.div(0.25).toInt() // Quarters
    var d = x.rem(0.25).div(0.10).toInt() // Dimes
    var rem = (x - (q * 0.25 + d * 0.10)).toFloat() // Remainder
    println(q)
    println(d)
    println(rem)
}

Comment: Thank you for this! now might I pester you for something additional? Say I wanted it to add the number dimes in addition to the quarters, what would that look like?

For example:
having $1.60, which would be 6 quarters and 1 dime output
Comment: I added the dimes
Comment: would you be willing to explain how you are using the rem() operator? More specifically, why do you have it filled with 0.25?
Comment: The rem() operator gives the remainder after dividing. I have .25 in it because you want to get the remainder after removing the quarters.

Quarter counter (kotlin)


Updating windows server 2016 from eval version to standard retail version

Question: We are running an evaluation copy of windows server 2016. We have rearmed the license and extended the time for the trial version for several times. Now the rearm count has reached the limit we want to update our current version to a fully licensed version. We have purchased the Windows Server 2016 Standard - Retail (16-Core) and received a message with the product key and a download link. the message looks like the following.

I have read the documentation on how to update in here Converting a current evaluation version to a current retail version
I have found that i need to run the following command to update
<code>DISM /online /Set-Edition:<edition ID> /ProductKey:XXXXX
</code>
My confusion and question are
- I have received a product key and a download link from the seller.
- Can I run update with the product key with the above command , if the download link is not active?
The download link is now expired. I need to infor the seller to send a new download link. But I just want to know - When I update my server with the command do I need the download link to be active? Or do I just need the product key?
FYI: The post in this link ( Can you help me with my software licensing issue? ) does not answer my question. I have received the answer from someone on this post
Comment: Does this answer your question? [Can you help me with my software licensing issue?](https://serverfault.com/questions/215405/can-you-help-me-with-my-software-licensing-issue)
Comment: `What is the purpose of the download link?` Ask the vendor.
Comment: No the link does not answer my question
Answer: You only need the product key to update the license on an existing Windows installation; you only need to download the software if you need to perform a new installation.
Comment: Thank you so much. Thats all i needed to know


Every subset of ideals of $R$ has maximal element $\implies$ Every ideal of $R$ is finitely generated, if $R$ is Noetherian.

Question: We know that a commutative ring $R$ is Noetherian, if for the increasing sequence of ideals $I_1\subseteq I_2 \subseteq...,\ \exists m\in \mathbb{Z}^+,\forall k\in \mathbb{Z}_{\geq m}:\ I_m=I_k$.

Question. If $R$ is Noehterian and every non-empty subset of ideals of $R$ has maximal element, then every ideal of $R$ is finitely
  generated.

Proof. We take an ideal $I$ of $R$ and we define the set
$$F:=\{J: J\text{ finitely generated ideal of } R  \text{ and } J\subseteq   I\}.$$
We can see that $F\neq \emptyset$ (because $\langle 0_R \rangle \in F$). So, from hypothesis, there exists a maximal element $M\in F$.
We want to show that $I=M$.
Obviously, $M\subseteq I$, because $M\in F$.
We suppose now that $M\subsetneq I$. Then, there exists an element $a\in I\backslash M\iff a\in I$, with $a\notin M$.
We consider the ideal
$$J:=M+\langle a\rangle.$$
Then, if $M=\langle m_1,...,m_n \rangle$, we have $J=M+\langle a\rangle=\langle m_1,..., m_n,a \rangle \implies J\in F$
Question: Why $M\neq M+\langle a \rangle $?
If  $M= M+\langle a \rangle$ $\underline{ \text{and}}$ $R$ has $1_R$, then
$a=1_R\cdot a \in M+\langle a \rangle =M $, contradiction.
But what happens if $R$ hasn't unity?
Answer: The argument you are giving in no way requires $R$ to be unital.  Note that if $R$ is not unital, then $\langle a\rangle$ still refers to the ideal generated by $a$.  That means it is the smallest ideal which contains $a$, which is not necessarily the same as the set $Ra$.  So, by definition, $a\in\langle a\rangle.$
(Note also that your statement of what you are proving seems to be mangled.  You have never used the assumption that $R$ is Noetherian, nor do you need to.  The assumption that every nonempty set of ideals has a maximal element is actually equivalent to assuming that $R$ is Noetherian.)


Does SQL Server have a way to substitute a different version of a table based on login?

Question: I'd like to know if there is a way that SQL server can provide a different version of a table based on the database login. For example I'd like to be able to give a different list of items and prices for a given region/locale based on the login.
I realize I can add schema and changes join conditions across the application but this would be a lot of work in updating and testing.
Can this be done by creating different schema such as [en-ca].[items] vs [en-us].[items] or [pt-br].[items] available only in brazil for example?
Comment: Have you tried it?  It should be possible to have the same table name under different schemas in SQL Server.  You could then set the default schema for each user.  Depending on how you connect and query, it should work.
Comment: You could add another column to your table, which will indicate the region. Another approach would be creating table per region. But I think first approach is closest to what you're after.
Comment: You should be able to do what you want using a view(s)
Comment: @Jimbo without changing the application how would I be able to configure a view(S) to hand back the appropriate set of rows ?
Comment: 1. application is currently selecting from table A
2. Rename table a to table x
3. Create view with same name as table A
4. Inside view add logic to check current_user and return appropriate results from table x
Answer: You could use Row-Level Security to control which users see which rows. Some links:
Row-Level Security
SQL Server 2016 Row Level Security – A Practical Example


is it possible to find all the triplets in the given array for the O (n) time?

Question: Given an array of numbers find all such triplets that satisfy the given condition.
Condition: a[i] < a[j] < a[k] where I < j < k.
it is possible to solve this problem in O (n) time?
This is not home work !!!
Comment: Find them or count them? (I believe finding them in O(n) is impossible since there are O(n^3) such triplets in the worst case)
Answer: The size of the output (worst case) is a lower bound on the complexity.
Since there are possibly O(n^3) such triplets, the complexity cannot be O(n).
For example if the array is sorted from lowest to highest, you will have n choose 3 such triplets which is order of n^3.
If the question refers to finding the number of triplets, here is the most efficient solution I saw:
https://cs.stackexchange.com/questions/7409/count-unique-increasing-subsequences-of-length-3-in-on-log-n
Comment: I believe it's not formulated correctly. "*find* all the triplets" should be "*count* all the triplets" or "find the number of triplets"
Comment: how do you count the number of triplets in the given array ?
Comment: the source of the problem http://www.geeksforgeeks.org/amazon-interview-set-60-internship/
Question 1:
Given an array of numbers find all such triplets that satisfy the given condition.

The Problem not correctly formulated ?
Comment: and how to find the number of triplets ?


Add icons to the parent rows of a DT table

Question: The problem:
Including an emoticon to a parent/child table mutes the child table. How to overcome this difficulty?
The added issue is that the inclusion of virtually any special character leads to the same result. I suspect that the answer is in the call back but it beats my JS skills.
The code:

library(shiny)
library(DT)
library(tidyverse)

### == script knicked from https://github.com/rstudio/shiny-examples/issues/9
shinyApp(
    ui = fluidPage(DT::DTOutput("tbl")),
    server = function(input, output, session) {

df <- tibble(names=c("Joan", "Michael", "Vincent"), hex =c("🦁","🦁","🦁"), DOB=c("2020-04-05", "2020-04-05","2020-04-05"))

            df <- df %>%
                as.data.frame() %>%
                nest(-names, -hex)

            # add control column
            data <- df %>% {bind_cols(data_frame(' ' = rep('►',nrow(.)))
                                                  ,.)}

            # get dynamic info and strings
            nested_columns         <- which(sapply(data,class)=="list") %>% setNames(NULL)
            not_nested_columns     <- which(!(seq_along(data) %in% c(1,nested_columns)))
            not_nested_columns_str <- not_nested_columns %>% paste(collapse="] + '_' + d[") %>% paste0("d[",.,"]")

            # The callback
            # turn rows into child rows and remove from parent
            callback <- paste0("
                    table.column(1).nodes().to$().css({cursor: 'pointer'});

                    // Format data object (the nested table) into another table
                    var format = function(d) {
                      if(d != null){
                        var result = ('
').replace('.','_') + '

'
                        for (var col in d[",nested_columns,"]){
                          result += '' + col + '	'
                        }
                        result += '

'
                        return result
                      }else{
                        return '';
                      }
                    }

                    var format_datatable = function(d) {
                      var dataset = [];
                      for (i = 0; i < + d[",nested_columns,"]['DOB'].length; i++) {
                        var datarow = [];
                        for (var col in d[",nested_columns,"]){
                          datarow.push(d[",nested_columns,"][col][i])
                        }
                        dataset.push(datarow)
                      }
                      var subtable = $(('table#child_' + ",not_nested_columns_str,").replace('.','_')).DataTable({
                        'data': dataset,
                        'autoWidth': false,
                        'deferRender': true,
                        'info': false,
                        'lengthChange': false,
                        'ordering': true,
                        'paging': false,
                        'scrollX': false,
                        'scrollY': false,
                        'searching': false
                      });
                    };

                    table.on('click', 'td.details-control', function() {
                      var td = $(this), row = table.row(td.closest('tr'));
                      if (row.child.isShown()) {
                        row.child.hide();
                        td.html('►');
                      } else {
                        row.child(format(row.data())).show();
                        td.html('▼');
                        format_datatable(row.data())
                      }
                    });

                           "
            )

            DDT <-  datatable(
                data,
                escape = -c(2,4), # raw HTML in column 2
                options = list( paging=FALSE,info = FALSE,
                                columnDefs = list(
                                    list(visible = FALSE, targets = c(0,nested_columns) ), # Hide row numbers and nested columns
                                    list(orderable = FALSE, className = 'details-control', targets = 1) # turn first column into control column
                                )
                ),
                callback = JS(callback)
            )

        output$tbl <- DT::renderDT({
            DDT

        }, server = FALSE, width = 6)

        session$onSessionEnded(function() {
            observe(cat(paste0("Ended: ", values$sessionId)))
        })

        if(format(Sys.time(), "%M")=='00'){
            onStop(function() {
                dbDisconnect(con)
            })
        }

        # you need set the server to FALSE
    },
    options = list(port = 33333)
)

Any thoughts?
Answer: In order to make a datatable with children, it's better to use the method I give on my blog. Currently there are some mistakes in the callback code, I need to update this post, so I provide the full code here for your case:
library(DT)

NestedData <- function(dat, children){
  stopifnot(length(children) == nrow(dat))
  g <- function(d){
    if(is.data.frame(d)){
      purrr::transpose(d)
    }else{
      purrr::transpose(NestedData(d[[1]], children = d$children))
    }
  }
  subdats <- lapply(children, g)
  oplus <- ifelse(lengths(subdats), "⊕", "")
  cbind(" " = oplus, dat, "_details" = I(subdats),
        stringsAsFactors = FALSE)
}

Dat <- NestedData(
  data.frame(
    names = c("Joan", "Michael", "Vincent"),
    hex = c("🦁","🦁","🦁"),
    stringsAsFactors = FALSE
  ),
  children = list(
    data.frame(DOB = "2020-04-05", stringsAsFactors = FALSE),
    data.frame(DOB = "2020-04-05", stringsAsFactors = FALSE),
    data.frame(DOB = "2020-04-05", stringsAsFactors = FALSE)
  )
)

## whether to show row names
rowNames = FALSE
colIdx <- as.integer(rowNames)
## the callback
parentRows <- which(Dat[,1] != "")
callback <- JS(
  sprintf("var parentRows = [%s];", toString(parentRows-1)),
  sprintf("var j0 = %d;", colIdx),
  "var nrows = table.rows().count();",
  "for(let i = 0; i < nrows; ++i){",
  "  var $cell = table.cell(i,j0).nodes().to$();",
  "  if(parentRows.indexOf(i) > -1){",
  "    $cell.css({cursor: 'pointer'});",
  "  }else{",
  "    $cell.removeClass('details-control');",
  "  }",
  "}",
  "",
  "// --- make the table header of the nested table --- //",
  "var formatHeader = function(d, childId){",
  "  if(d !== null){",
  "    var html = ",
  "      '

';",
  "    var data = d[d.length-1] || d._details;",
  "    for(let key in data[0]){",
  "      html += '' + key + '	';",
  "    }",
  "    html += '

'",
  "    return html;",
  "  } else {",
  "    return '';",
  "  }",
  "};",
  "",
  "// --- row callback to style rows of child tables --- //",
  "var rowCallback = function(row, dat, displayNum, index){",
  "  if($(row).hasClass('odd')){",
  "    $(row).css('background-color', 'papayawhip');",
  "    $(row).hover(function(){",
  "      $(this).css('background-color', '#E6FF99');",
  "    }, function(){",
  "      $(this).css('background-color', 'papayawhip');",
  "    });",
  "  } else {",
  "    $(row).css('background-color', 'lemonchiffon');",
  "    $(row).hover(function(){",
  "      $(this).css('background-color', '#DDFF75');",
  "    }, function(){",
  "      $(this).css('background-color', 'lemonchiffon');",
  "    });",
  "  }",
  "};",
  "",
  "// --- header callback to style header of child tables --- //",
  "var headerCallback = function(thead, data, start, end, display){",
  "  $('th', thead).css({",
  "    'border-top': '3px solid indigo',",
  "    'color': 'indigo',",
  "    'background-color': '#fadadd'",
  "  });",
  "};",
  "",
  "// --- make the datatable --- //",
  "var formatDatatable = function(d, childId){",
  "  var data = d[d.length-1] || d._details;",
  "  var colNames = Object.keys(data[0]);",
  "  var columns = colNames.map(function(x){",
  "    return {data: x.replace(/\\./g, '\\\\\\.'), title: x};",
  "  });",
  "  var id = 'table#' + childId;",
  "  var options = {",
  "    'dom': 't',",
  "    'data': data,",
  "    'columns': columns,",
  "    'autoWidth': true,",
  "    'deferRender': true,",
  "    'info': false,",
  "    'lengthChange': false,",
  "    'ordering': data.length > 1,",
  "    'order': [],",
  "    'paging': false,",
  "    'scrollX': false,",
  "    'scrollY': false,",
  "    'searching': true,",
  "    'sortClasses': false,",
  "    'rowCallback': rowCallback,",
  "    'headerCallback': headerCallback",
  "  };",
  "  var hasChild = colNames.indexOf('_details') > -1",
  "  if(!hasChild){",
  "    var columnDefs = ",
  "      {'columnDefs': [{targets: '_all', className: 'dt-center'}]};",
  "    var subtable = $(id).DataTable(",
  "      $.extend(options, columnDefs)",
  "    );",
  "  } else {",
  "    var columnDefs = {",
  "      'columnDefs': [",
  "        {targets: -1, visible: false},",
  "        {targets: 0, orderable: false, className: 'details-control'},",
  "        {targets: '_all', className: 'dt-center'}",
  "      ]};",
  "    var subtable = $(id).DataTable(",
  "      $.extend(options, columnDefs)",
  "    ).column(0).nodes().to$().css({cursor: 'pointer'});",
  "  }",
  "};",
  "",
  "// --- display the child table on click --- //",
  "// array to store id's of already created child tables",
  "var children = [];",
  "table.on('click', 'td.details-control', function(){",
  "  var tbl = $(this).closest('table'),",
  "      tblId = tbl.attr('id'),",
  "      td = $(this),",
  "      row = $(tbl).DataTable().row(td.closest('tr')),",
  "      rowIdx = row.index();",
  "  if(row.child.isShown()){",
  "    row.child.hide();",
  "    td.html('⊕');",
  "  } else {",
  "    var childId = tblId + '-child-' + rowIdx;",
  "    if(children.indexOf(childId) === -1){",
  "      // this child has not been created yet",
  "      children.push(childId);",
  "      row.child(formatHeader(row.data(), childId)).show();",
  "      td.html('⊖');",
  "      formatDatatable(row.data(), childId, rowIdx);",
  "    }else{",
  "      // this child has already been created",
  "      row.child(true);",
  "      td.html('⊖');",
  "    }",
  "  }",
  "});")

datatable(
  Dat,
  callback = callback, rownames = rowNames, escape = -c(colIdx+1, 3),
  options = list(
    paging = FALSE,
    searching = FALSE,
    columnDefs = list(
      list(
        visible = FALSE,
        targets = ncol(Dat)-1+colIdx
      ),
      list(
        orderable = FALSE,
        className = "details-control",
        targets = colIdx
      ),
      list(
        className = "dt-center",
        targets = "_all"
      )
    )
  )
)

Comment: Merci beaucoup!!!! Je te dois une grande bière bien fraîche
Comment: @UlysseColonna ;-) Glad to help. Please do not forget to [accept the answer](https://stackoverflow.com/help/someone-answers#:~:text=To%20accept%20an%20answer%3A,the%20answer%2C%20at%20any%20time.)


The exponential distribution belongs to the exponential family

Question: I'm new here.
I'm trying to proof that the exponential distribution belongs to the exponential family, but I don't know how to do that. Can you help me?
Thanks a lot.
Comment: There's evidence on the Wikipedia article for exponential family distributions. This sounds like a homework/practice question though, so please tag as [tag:self-study]. What have you tried so far? What do you already understand, and where are you stuck.
Answer: Hint:
From Wikipedia:

A single-parameter exponential family is a set of probability distributions whose probability density function (or probability mass function, for the case of a discrete distribution) can be expressed in the form $f_X(x\mid\theta) = h(x)\,\exp\!\bigl[\,\eta(\theta) \cdot T(x) +A(\theta)\,\bigr]$ where $T(x),h(x),η(θ),$ and $A(θ)$ are known functions.

and

The probability density function (pdf) of an exponential distribution is $$ f(x;\lambda) = \begin{cases}
\lambda  e^{-\lambda x} & x \ge 0, \\
0 & x < 0.
\end{cases}$$

Your mission, should you choose to accept it, is to find suitable $T(x),h(x),η(θ),$ and $A(θ)$ to demonstrate the exponential distribution pdf is of an exponential family form. It is not particularly difficult, especially if you spot $\exp\!\bigl[\,\eta(\theta) \cdot T(x) +A(\theta)\,\bigr] = e^{A(\theta)}e^{\eta(\theta) \cdot T(x)}$.  You can presume $\lambda=\theta$.


Grid computing: how to redistribute calculation to optimise response time

Question: I have set up an infrastructure for grid computation. That is, an operation of N iterations is distributed and independently calculated on different servers, and the final result is the aggregation of the individual results.
Each server has a different number of CPU cores. Each core operates independently.
I have three servers: S1, S2, S3.

S1 has 4 cores.
S2 has 8 cores.
S3 has 4 cores.

So, in total, 16 cores.
Say I have an operation of 500.000 iterations, I distribute the calculation in the following way:

S1 => (500.000 / 16 * 4) = 125.000 iterations
S2 => (500.000 / 16 * 8) = 250.000 iterations
S3 => (500.000 / 16 * 4) = 125.000 iterations

Now the response times:

S1 completes 125.000 iterations in 4587 ms.
S2 completes 250.000 iterations in 8403 ms.
S3 completes 125.000 iterations in 9356 ms.

As you can see the servers have different performances: S3 is more than twice slower than S1.
What I want is to redistribute the calculation in a non uniform way, so that the response time is optimised (for example, S3 should be assigned approximately half of the iterations than S1).
What's the math behind this operation?
Answer: Let $r_s$ be the number of iterations per ms for server $s$.  Let decision variable $x_s$ be the number of iterations assigned to server $s$.  You want to minimize the makespan
$$\max_{s\in\{1,2,3\}} x_s/r_s$$
subject to
\begin{align}
x_1 + x_2 + x_3 &= 500000 \tag1 \\
x_s &\ge 0 &&\text{for all $s$}
\end{align}
The optimal value will occur when $$x_1/r_1 = x_2/r_2 = x_3/r_3. \tag2$$  Solving $(1)$ and $(2)$ yields $x \approx (193646, 211414, 94940)$.
Comment: So brilliant. Thanks!


infinte scroll with loading msg after 10 items

Question: I am displaying a list of items. I want, when we scroll, after displaying 10 items. it displays " loading more..."
(ionInfinite)="doInfinite($event)"

is not triggering.
.html file
<ion-content padding>

  <ion-list>
    <ion-item *ngFor="let i of items">{{i}}</ion-item>
  </ion-list>

  <ion-infinite-scroll (ionInfinite)="doInfinite($event)">
    <ion-infinite-scroll-content loadingSpinner="bubbles" loadingText="Loading more data...">
    </ion-infinite-scroll-content>
  </ion-infinite-scroll>

</ion-content>

.ts file
import { IonInfiniteScroll, IonVirtualScroll } from '@ionic/angular';

export class FoodMenuPage implements OnInit {
  @ViewChild(IonInfiniteScroll) infiniteScroll: IonInfiniteScroll;
  items = [];

  constructor() {
    for (let i = 0; i < 30; i++) {
      this.items.push( this.items.length );
      }
  }

  doInfinite(infiniteScroll) {
    console.log('Begin async operation');

    setTimeout(() => {
    for (let i = 0; i < 30; i++) {
    this.items.push( this.items.length );
    }

    console.log('Async operation has ended');
    infiniteScroll.complete();
    }, 500);
    }

Comment: some one plz...help me...provide me the solution
Answer: HTML
<ion-infinite-scroll (ionInfinite)="doInfinite($event)">
<ion-infinite-scroll-content loadingSpinner="bubbles" loadingText="Loading more data...">
</ion-infinite-scroll-content>

 No more data is available.

TS
if (this.image1 != 0) {
        for (let i in this.image1) {
          this.images = this.images.concat(this.image1[i]);
        }
      } else {
        this.pagingEnabled = true;
      } \\image1 and image have same json value

if (Infinitescroll) { \\every scroll infinite has been fire
        Infinitescroll.target.complete();\\every scroll tarhas been completed
      }

no need for viewchild or anything
Comment: I am not using any image
Comment: image is an array.u can change ur array value
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/196352/discussion-between-naveen-pandi-and-annaya).


Projective modules over polynomial rings

Question: Let $M$ be a finitely generated right module over a polynomial ring $R$ (in any number of variables) over a field $\mathbb F$. Given a maximal ideal $\mathfrak{m}$ of $R$, consider $\frac{R}{\mathfrak{m}}$ as a natural right $R$-module.
If the dimension of $M \otimes_R \frac{R}{\mathfrak{m}}$ over $\mathbb F$ is independent of the maximal ideal $\mathfrak{m}$, then $M$ is projective?
I have seen this argument many times and I don't know why it is true (or even if some hypothesis are being forgotten).
__ The field $\mathbb F$ can be assumed algebraically closed.
Answer: Let $R, M$ be as in the answer of Andrew. Let $n$ be the (constant) rank of $R_\mathfrak p/\mathfrak pR_\mathfrak p$ for all prime ideals $\mathfrak p$ of $R$.
Fix any $\mathfrak p$. By Nakayama's lemma, $M_\mathfrak p$ is generated by $n$ elements $x_1,\cdots, x_n\in M$. Writing the elements of a generating system of $M$ as linear combinations of the $x_i$'s with coefficients in $R_\mathfrak p$, we find an $f\in R\setminus \mathfrak p$ such that $M_f$ is generated by $x_1,\cdots, x_n$. This implies that we can cover $\mathrm{Spec}(R)$ by various Zariski open subsets $D(f)$ such that $M_f$ is generated by $n$ elements.
Let's show that $M_f$ is free of rank $n$. For simplicity, we replace $R, M$ by $R_f, M_f$. Let $R^n\to M$ be a surjective linear map with kernel $N$. For any $\mathfrak p$, the induced map
$$(R_\mathfrak p/\mathfrak pR_\mathfrak p)^n\to M_\mathfrak p/\mathfrak pM_\mathfrak p$$
is surjective, hence bijective. This implies that $N_\mathfrak p\subseteq (\mathfrak p R_\mathfrak p)^n$ and $N\subseteq (\mathfrak p )^n$. By Krull's intersection theorem, and because $R$ is reduced, we get $N=0$ and $R^n\simeq M$.
In particular, $M$ is a flat and finite generated module over $R$. When $R$ is noetherian, it is known thant $M$ is then projective. Otherwise the same result holds if $M$ is finitely presented.
To return to your case where $R$ is a finitely generated algebra over an  algebraically closed   field $F$, the methods works with the following two observations: (1) $M\otimes_R R/\mathfrak m=M_\mathfrak m/\mathfrak mR_{\mathfrak m}$ and $R/\mathfrak m=F$; (2) By Hilbert's Nullstellensatz, the intersection of all maximal ideals is $0$ (because $R$ is reduced).
Answer: A version of this is actually Exercise 20.13 of Eisenbud. We only need to assume that $R$ is reduced (and commutative with unit). Then it is true, for a finitely generated $R$-module $M,$ that $M$ is projective of constant rank iff the number $\dim_{R_p/pR_p}\left(M_p/pM_p\right)$ is constant on primes $p\subseteq R.$ There is a hint to this problem, and I haven't worked it out yet, so hopefully it's helpful enough to just point you in the right direction for now.
Comment: It is bad (but unfortunately frequent) style to have a blanket assumption hidden somewhere : a  mathematics book is not a detective novel that you read from first to last page. But  actually , I don't think that $R$ has to be assumed noetherian for the result in this answer.
Comment: I think $R$ must be noetherian.
Comment: @Cantlog: Good point! This was hidden at the front of the chapter.
Comment: Dear @GeorgesElencwajg, I now realize that without noetherianity, one can show $M$ is (Zariski) locally free. Thanks ! But how to see $M$ is projective ?
Comment: I don't see how to use this exercise and its hint to solve my problem!


Kendo Dropdownlist mobile rendering

Question: Is it possible to render the dropdownlist as a select on mobiles.
So that it works as a native select html tag on mobile devices?
Answer: Actually Kendo UI DropDownList is rendered similar to an ActionSheet when used in Kendo UI Mobile exactly with this idea in mind. Check the Forms demo in a mobile device.
Comment: How can i force this behavior on a website that is also used by desktop ?
Comment: You mean to look the same on mobile and desktop, or native-like only on mobile and not on desktop?
Comment: Native look only on mobile.

Kendo Dropdownlist mobile rendering


Kernel panic when bringing up DRBD resource

Question: I'm trying to set up two machines synchonizing with DRBD.  The storage is setup as follows: PV -> LVM -> DRBD -> CLVM -> GFS2.
DRBD is set up in dual primary mode.  The first server is set up and running fine in primary mode.  The drives on the first server have data on them.  I've set up the second server and I'm trying to bring up the DRBD resources.  I created all the base LVM's to match the first server.  After initializing the resources with
``

drbdadm create-md storage

I'm bringing up the resources by issuing

drbdadm up storage

After issuing that command, I get a kernel panic and the server reboots in 30 seconds.  Here's a screen capture.

My configuration is as follows:
OS: CentOS 6
uname -a
Linux host.structuralcomponents.net 2.6.32-279.5.2.el6.x86_64 #1 SMP Fri Aug 24 01:07:11 UTC 2012 x86_64 x86_64 x86_64 GNU/Linux

rpm -qa | grep drbd
kmod-drbd84-8.4.1-2.el6.elrepo.x86_64
drbd84-utils-8.4.1-2.el6.elrepo.x86_64

cat /etc/drbd.d/global_common.conf
global {
        usage-count yes;
        # minor-count dialog-refresh disable-ip-verification
}

common {
    handlers {
            pri-on-incon-degr "/usr/lib/drbd/notify-pri-on-incon-degr.sh; /usr/lib/drbd/notify-emergency-reboot.sh; echo b > /proc/sysrq-trigger ; reboot -f";
            pri-lost-after-sb "/usr/lib/drbd/notify-pri-lost-after-sb.sh; /usr/lib/drbd/notify-emergency-reboot.sh; echo b > /proc/sysrq-trigger ; reboot -f";
            local-io-error "/usr/lib/drbd/notify-io-error.sh; /usr/lib/drbd/notify-emergency-shutdown.sh; echo o > /proc/sysrq-trigger ; halt -f";
            # fence-peer "/usr/lib/drbd/crm-fence-peer.sh";
            # split-brain "/usr/lib/drbd/notify-split-brain.sh root";
            # out-of-sync "/usr/lib/drbd/notify-out-of-sync.sh root";
            # before-resync-target "/usr/lib/drbd/snapshot-resync-target-lvm.sh -p 15 -- -c 16k";
            # after-resync-target /usr/lib/drbd/unsnapshot-resync-target-lvm.sh;
    }

    startup {
            # wfc-timeout degr-wfc-timeout outdated-wfc-timeout wait-after-sb
            become-primary-on       both;
            wfc-timeout             30;
            degr-wfc-timeout        10;
            outdated-wfc-timeout    10;
    }

    options {
            # cpu-mask on-no-data-accessible
    }

    disk {
            # size max-bio-bvecs on-io-error fencing disk-barrier disk-flushes
            # disk-drain md-flushes resync-rate resync-after al-extents
            # c-plan-ahead c-delay-target c-fill-target c-max-rate
            # c-min-rate disk-timeout

    }

    net {
            # protocol timeout max-epoch-size max-buffers unplug-watermark
            # connect-int ping-int sndbuf-size rcvbuf-size ko-count
            # allow-two-primaries cram-hmac-alg shared-secret after-sb-0pri
            # after-sb-1pri after-sb-2pri always-asbp rr-conflict
            # ping-timeout data-integrity-alg tcp-cork on-congestion
            # congestion-fill congestion-extents csums-alg verify-alg
            # use-rle
            protocol C;
            allow-two-primaries yes;
            after-sb-0pri   discard-zero-changes;
            after-sb-1pri   discard-secondary;
            after-sb-2pri   disconnect;
    }
}

cat /etc/drbd.d/storage.res
resource storage {
        device          /dev/drbd0;
        meta-disk       internal;

        on host.structuralcomponents.net {
                address         10.10.1.120:7788;
                disk            /dev/vg_storage/lv_storage;
        }
        on host2.structuralcomponents.net {
                address         10.10.1.121:7788;
                disk            /dev/vg_storage/lv_storage;
        }

/var/log/messages is not logging anything about the crash.
I've been trying to find a cause of this but I've come up with nothing.  Can anyone help me out?  Thanks.
Answer: Machine check exception is a hardware issue. You can use mcelog to interpret it, if you can boot the system.
The resolution is to replace the failing hardware. Since it looks like you're most likely leasing a server, contact the provider.
Comment: I've checked the mcelog and it's not coming up with any errors, none when the machine is running and nothing added if I force the crash.

Also, just curious, but what led you to think it was a leased server? (it's not btw)
Comment: Your KVM-over-IP screenshot looked similar to what I've seen commonly used by server leasing companies for customer use. Anyway, the answer is still to isolate and replace the failing hardware, which it seems you've already done.
Answer: Looks like the kernel panic was caused by the network adapter.  The server was set up with a dedicated NIC for the DRBD traffic.  When I switched the DRBD traffic onto the onboard NIC's the crashes stopped.  I'll report back if I find a better explanation for why this was happening (other traffic over that interface seems to be working fine).


How to analyse unbalanced panel data with attrition and defiers?

Question: I'm working with a panel data from a quasi-experimental study with the following characteristics
1) Unbalanced covariates between the control and the treatment group (according to Hotelling's T-squared test), though I've read that it's not cause for concern (https://www.ncbi.nlm.nih.gov/pmc/articles/PMC4310023/);
2) High level of attrition, though similar in rate for both the control and treatment group, and no statistical difference in covariates between drop-outs from the two groups (Pearson chi2 for each covariate) but significant using Hotelling's T-squared test;
3) Treatment assignment at the regional level, participants were randomly selected in three random towns within a region;
4) Defiers in both the control and the treatment group;
5) Most likely heterogenous effects by region.
I was thinking of using a DID analysis, given that the control and treatment groups' covariates and key indicators differ, and then use a LATE approach to estimate the average treatment on the treated. I was wondering if:
a) that would be the correct approach?
b) I read somewhere that DID is ATE, and that for LATE, I would need to estimate the ITT. How can I estimate the ITT?
c) can I estimate ATT on DID?
d) any suggestions on different approaches, given the type of data (i.e. FE, PSM)?
Answer: If you are assigning a treatment, it is not a "quasi-experimental" study as you say in the header.
1) The paper which you cite has a subtle claim: statistical testing of differences in baseline covariates is bad practice. Historically, RCT analyses were initiated with a litany of t-tests and chi-square tests, and provided none of these were significant, the authors claimed that "randomization was good" or "balanced". This is just untrue and misleading, especially with deliberate variable omission which occurs frequently in practice. Regrettably, it's true that large imbalances in baseline covariates between randomization arms will lead to biased or inefficient analyses. The solution they propose is simply to adjust (or perhaps block-randomize) for strongly prognostic variables.
2) There is no widely accepted solution to this problem. The approach most often used is what we'd call an intent-to-treat analysis. Use the data from the non-compliant participants up until the time they leave the study (either with censoring or including them as imbalanced clusters in a mixed model). Some sensitivity analyses can be done to guess at what their trajectory would have been had they stayed in the study. Last-observation-carried-forward (LOCF) is never recommended. You can use multiple imputation via chained equations if there is no growth component (time-covariate interactions) in the model, or you can use some Martingale processes like a simple random walk with Markov Chain to forecast outcomes. Another type of sensitivity analysis is worst-observation-carried-forward (WOCF) where you use the worst observed or unobserved outcome (within an individual or the whole panel) in those who drop out. Presumably drop-out is higher in the treatment group because the treatment is more invasive and different from standard of care, so this can be seen as a conservative approach; however you must verify this.
3) I will just say that you should read this: https://www.ncbi.nlm.nih.gov/pmc/articles/PMC4458010/. Community randomized studies are important and widely popular for evaluating policies and interventions.
4) Again, for any evaluation, analyze "defiers" with intent-to-treat. If I randomize a set of cancer patients to chemotherapy, but 50% of them tolerate the treatment so poorly they refuse to show up for infusions, I can't say the treatment was effective in 100% of the 50% who showed up, it was only 50% effective.
5) With community randomized studies it can be difficult with perfectly nested effects due to site. The best way to handle this variability per the above referenced article is to adjust for important site based predictors of the outcome, where available. This increases the generalizability of the results. While adjusting for site directly is tempting and would normally be done in other circumstances, with few sites (typically the case) perfectly nested within treatment, there can be some forms of bias that occur.
Comment: Hi AdamO, thank you for your answer! Extremely helpful! I had a follow-up question - how would you test ITT if the covariates differ? From my understanding, ITT can be done with a t-test between two statistically similar groups. Because they differed from the baseline (though not drastically), I thought it would be best to perform an initial DID analysis (but DID=ATT). From then, how would I implement a LATE on the compliers (http://egap.org/methods-guides/10-things-you-need-know-about-local-average-treatment-effect) on a DID? I'll then analyse the data as per your recommendations! Thank you!
Comment: @Nick ITT is not a test, it is referred to as an analysis (more of an approach, really). To say you did an ITT analysis tells us who is included in the sample and how their randomization/treatment (assignment) is coded. It has no bearing on the type of model used. Choose the analysis (per adjustments, coding of the outcome, and type of inference)  that suits the problem. continued...
Comment: @Nick I'm glad you cited this LATE thing... I could not google a source. The converse of ITT which I have seen in clinical trials is a *per protocol* analysis: here the coding of the main effect "treatment *assignment* is restricted to *treatment*. As your paper suggests, never-takers are excluded from analyses. They never conform to what is considered a "safety population" (a group who was exposed to investigational treatment and comparable control). Also implied is that, in longitudinal studies, participants who take intermittently contribute imbalanced cluster data.
Comment: Hi AdamO, thanks for your comments. I didn't fully understand your first point - if I were to use LATE (or per-protocol analysis, as from what I read, they are similar), I would first need to derive the ITT, as LATE is evaluated by dividing ITT by the compliers rate. I know how this could be done when the control and treatment groups have balanced covariates. However, if this is not the case, how could I estimate the ITT? Thanks again!


setOnItemLongClickListener não está funcionando

Question: Alguém pode me ajudar dizendo pq o meu setOnItemLongClickListener não está sendo chamado quando eu dou um long click no item da minha lista?
Tenho no mesmo adapter 2 métodos do tipo onclick, um é o setOnItemClickListener e o outro é setOnItemLongClickListener, mas apenas o primeiro está funcionando, segue o código:
public class CategoriaAdapter extends BaseAdapter {
private Context context;
List<Categoria> lista;
private ListView listView;
private SubCategoria subcategoria = new SubCategoria();

public CategoriaAdapter(Context context, List<Categoria> lista, ListView listView) {
    this.context = context;
    this.lista = lista;
    this.listView = listView;
}

@Override
public int getCount() {
    return lista.size();
}

@Override
public Object getItem(int position) {
    return lista.get(position);
}

@Override
public long getItemId(int i) {
    return i;
}

@Override
public View getView(int position, View view, ViewGroup viewGroup) {
    final int auxPosition = position;

    final Categoria categoria = new Categoria();

    LayoutInflater inflater = (LayoutInflater)
            context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    final RelativeLayout layout = (RelativeLayout)
            inflater.inflate(R.layout.categoria_row, null);

    final TextView categ = (TextView)
            layout.findViewById(R.id.tvCat);
    categ.setText(lista.get(position).getNome());

    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, final long l) {
            AlertDialog.Builder alert = new AlertDialog.Builder(context);
            alert.setTitle("Adicionar subcategoria");
            alert.setMessage("Digite um nome para a subcategoria:");

            Toast.makeText(context, "Item with id [" + l + "] - Position [" + i + "] ", Toast.LENGTH_SHORT).show();

            final EditText input = new EditText(context);
            alert.setView(input);

            alert.setPositiveButton("Adicionar", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    //int idCategoria = (Integer) button.getTag();
                    int position = (int) l;

                    subcategoria.setNome(input.getText().toString());
                    subcategoria.setIdCategoria(position);

                    SubCategoriaDAO subCategoriaDAO = new SubCategoriaDAO(context);

                    subCategoriaDAO.inserir(subcategoria);
                }
            });

            alert.setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    return;
                }
            });

            alert.show();
        }
    });

    listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
            AlertDialog.Builder dialog = new AlertDialog.Builder(context);
            dialog.setTitle("Apagar categoria?");
            dialog.setMessage("Essa ação não poderá ser desfeita");

            dialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    CategoriaDAO categoriaDAO = new CategoriaDAO(context);

                    categoriaDAO.deletar(categoria);
                }
            });

            dialog.setNegativeButton("Voltar", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    return;
                }
            });
            return false;
        }
    });

    SubCategoriaDAO subcategoria = new SubCategoriaDAO(context);
    List<SubCategoria> list = subcategoria.getLista();
    ListView listView = (ListView) layout.findViewById(android.R.id.list);
    listView.setAdapter(new SubCategoriaAdapter(context, list, listView));

    return layout;
}
}

Answer: Você tem que definir setOnItemLongClickListener() no ListView:
        listView.setOnItemLongClickListener(new OnItemLongClickListener() {

        public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
                int pos, long id) {
            // TODO Auto-generated method stub

            Log.v("long clicked","pos: " + pos);

            return true;
        }
    });

Para cada item na lista, O XML (você deve usar um XML personalizado) deve ter android: longClickable = "true", bem como (ou você pode usar o método listView.setLongClickable (true);). Mas desta forma, você pode ter uma lista com apenas alguns itens que respondem a longclick.
Answer: Só esqueci de uma linha que já resolveu tudo:
dialog.show();

Funcionou na hora, mas agora ele chama o onItemClick e o onItemLongClick, os dois juntos, como resolver?
Comment: Só retornar `true` do `onItemLongClick`. Para entender melhor: http://developer.android.com/reference/android/widget/AdapterView.OnItemLongClickListener.html.
Answer: Cara, tente utilizar Log na sua aplicação, e assim saber onde está ocorrendo o erro!
No entanto, crie um método para colocar o AlertDialog, e assim você chama ele dentro desse método!
(desculpe colocar como resposta, mas não tenho pontos suficientes para comentar!)
Comment: Não tem erro @TaironeDias, ele não da qualquer mensagem nem nada, coloquei um Log.i no método porém ele não é chamado.


Is it standard practice to always have internal A records for an AD Domain point to GCs?

Question: Full disclosure: I'm not an AD guy so this might pertain to something obvious.  I apologize in advance if that's the case - I did try searching for prior questions regarding this.
I'm installing a Linux-based web application server in an AD environment (vanilla CentOS 5.x - no special integration with AD).  The app performs LDAPS queries against Global Catalog servers.  In order to discover which AD server to talk to, it performs a DNS Lookup for A records pertaining to the AD domain (foo.int).  This specific query appears to be failing (I'm still looking into it).
In the meantime though, I'd like to confirm a few things:

If I'm pointing the Linux server to Microsoft DNS servers, and query for the AD domain (foot.in), is it reasonable to assume that I should get A records pointing to some GCs?
Is the availability of A records for GCs something that is pretty standard?  Or is this something that varies from environment to environment? In other words, are there some environments that just don't have internal A records published at all for DCs?
Are these specific records something that is automatically managed/updated, or are they manually added/edited by admins?
Comment: You can't know which DC is a GC by querying for the DC A records. You need to query for the GC SRV records.
Answer:
If I'm pointing the Linux server to Microsoft DNS servers, and query for the AD domain (foot.in), is it reasonable to assume that I should get A records pointing to some GCs?

No, what you will get is all Domain Controllers  in the domain not necessarily just the Global Catalog Servers. If you just want the Global Catalog servers you can query _gc._tcp.<your_AD_FQDN> or you can query _gc.<your_site_name>._sites.<your_AD_FQDN> if you just want the GCs in a specific site. This is actually an SRV type record.

Is the availability of A records for GCs something that is pretty standard? Or is this something that varies from environment to environment? In other words, are there some environments that just don't have internal A records published at all for DCs?

All DCs will have an A record, It should be auto registered. But it's possibly that if auto-dns registration is turned off for the NIC that there will be no A record if someone didn't do it manually. AD will be broken if this stuff is turned off.

Are these specific records something that is automatically managed/updated, or are they manually added/edited by admins?

The _sites, _msdcs, _tcp, and _udp zones are managed automagically. The A records should be too, as long as someone hasn't done something silly with the config to turn this stuff off.


multiple lines of subtitles in Moviepy

Question: I'm using MoviePy to create a video with subtitles.
Here's the code to illustrate:
    generator = lambda txt: TextClip(txt, font='Arial', fontsize=48, color='Black')
    subtitles = SubtitlesClip("captions_cropped.srt", generator)
    video = VideoFileClip("my_video.mp4")
    result = CompositeVideoClip([video, subtitles.set_pos(('center',(0.885*1220)))])

I couldn't find anything on the documentation or Google about specifying the number of lines in the subtitles. Currently, when the subtitles are too long, they're just "cut" in the middle instead of starting a new line. I'd like the code to smart enough to start a new line of subtitles when needed.
Answer: You should specify the method attribute for that purpose.
E.g.:
gen = lambda txt: mp.TextClip(
    txt, color='white', fontsize=20, font='Georgia-Regular',
    stroke_width=3, method='caption', align='south', size=video.size)

There's also some ongoing work for the upcoming v.2, issue.

multiple lines of subtitles in Moviepy


How to quickly kill java processes in bash?

Question: On a linux box, I have at most 3 java jars files running. How do I quickly kill all 3 with one command?
Usually I would:
ps ex - get the processes running
then find the process ids then do:
kill -9 #### #### ####
Any way to shorten this process? My eyes hurts from squinting to find the process ids.
My script does the following:
nohup ./start-gossip &

nohup ./start &

nohup ./start-admin &

Is there a way to get the process ids of each without looking it up?
Comment: "squinting" -- bigger fonts.
Comment: the font is big enough, just too much stuff show up whenever i use "ps ex"
Answer: Short answer:
pkill java

This looks up a process (or processes) to kill by name. This will find any other java processes too, so be careful. It also accepts -9, but you should avoid using -9 unless something is really broken.
EDIT:
Based on updates, you may be able to specify the script names to pkill as well (I'm not positive). But, the more traditional way to handle this issue is to leave pid files around. After you start a new process and background it, its pid is available in $!. If you write that pid to a file, then it's easy to check if the process is still running and kill just the processes you mean to. There is some chance that the pid will be reused, however.
Comment: awesome!!! do you this is a way to combine these commands? something like "kill -9 pgrep java"? but then i could just use pkill command.. hmm...
Comment: `pgrep java | xargs kill` but like you said, kind of redundant when you have `pkill`.
Comment: this looks good, but i guess i gotta be careful with this since it kills all java..
Comment: If you are unsure, there is a corresponding `pgrep` command that you can use to look for pids first.
Comment: i was really hoping that when i start these jars i can save the process id somehow, the just read it off a txt file or something then kill them off that way.. but pkill is good for now. thanks!!
Answer: You can save the PIDs when you start the processes so you can use them later:
nohup ./start-gossip &
START_GOSSIP_PID=$!

nohup ./start &
START_PID=$!

nohup ./start-admin &
START_ADMIN_PID=$!

...

kill -9 $START_GOSSIP_PID
kill -9 $START_PID
kill -9 $START_ADMIN_PID

This has the advantage (over pkill) of not killing off any other processes that coincidentally have similar names. If you don't want to perform the kill operation from the script itself, but just want to have the PIDs handy, write them to a file (from the script):
echo $START_GOSSIP_PID > /some/path/start_gossip.pid

Or even just do this when you launch the process, rather than saving the PID to a variable:
nohup ./start-gossip &
echo $! > /some/path/start_gossip.pid

Comment: indeed. back in 2013, newb programmer. that's what i use now. of course i save my pid to /tmp
Answer: To get the process id of that java process run
netstat -tuplen
Process ID (PID) of that process whom you want to kill and run
kill -9 PID


R: gsub inserting whitespaces between capture groups

Question: I'm desperately trying to insert whitespaces between capture groups. My naive approach was
c = c("WesternSaharaRegion", "ColumbiaState", "OneTwoThreeFourFiveSix")
gsub("(.+[a-z])([A-Z].+)","\\1 \\2", clist, perl=T)

which is only inserting a whitespaces between the last two capital-letter-words. Using
gsub("(?=([a-z][A-Z]))"," ", c, perl = T)

works not quite exactly for it's a one-character-shifted version
"Wester nSahar aRegion"       "Columbi aState"              "On eTw oThre eFou rFiv eSix"

How am I able to elegantly receive
    "Western Sahara Region"       "Columbia State"              "One Two Three Four Five Six"

strsplit() unfortunately doesn't keep the capture group :/
Answer: We can either use regex lookarounds
 gsub('(?<=[a-z])(?=[A-Z])', ' ', c, perl=TRUE)
 #[1] "Western Sahara Region"       "Columbia State"              "One Two Three Four Five Six"

Or use capture groups
gsub('([a-z])([A-Z])', '\\1 \\2', c)
#[1] "Western Sahara Region"       "Columbia State"              "One Two Three Four Five Six"

Comment: Jep, done. Your answer helped me to finally get my head around 'lookarounds', thank you.


How to apply an AR(MA) model to a prewhitened signal?

Question: I have two (vehicle velocity) signals that should consist of similar "latent" drivers, but have different autocorrelation structures. The driver-signals are quite nasty statistically, so I'm not attempting to model them.
I can get quite nice results by prewhitening the signals using AR(1)-residuals, but these are very difficult to interpret in "real world terms" (ie. velocities). So what I'd like to do is to prewhiten one of the signals and then add the AR-model of the other signal to this, so that I'd have two signals with same autocorrelation structures.
It may be that there is a very simple method for doing this, but unfortunately I haven't found one, or it maybe impossible. I guess it should be sort of an inverse of the Yule-Walker method. One also that is quite close is to use arima.sim with innovations, but with the difference that I don't have innovations, but residuals.
Comment: Cross-posted: http://stackoverflow.com/questions/8436569/how-to-apply-a-arma-model-to-a-prewhitened-signal
Answer: Given that you have an ARIMA filter, you can restate this as a pure AR by simply multiplying out the ARI and then dividing by the MA. This would be a pure auto-regressive formulation which is called the PI WEIGHTS ( see any book on time series analysis ) . The right-hand side constant might take you some to time to figure it out but I am sure you will. Use this pure right-hand side equation in conjunction with your residuals and you will get a realization of a process that will have "the same acf" as the series that was used to identify the ARIMA Model. Of course what you will have will be a realization of a sample ACF which of course would depend on the input "error/noise vector".


Transformers for embedding sequences as fixed-length vectors

Question: An encoder decoder network of recurrent neural networks can be used to learn the identity function over some set of sequences. If you do this without attention, the output of the decoder can be thought of as a fixed length representation of these sequences. I've been calling this idea a recurrent autoencoder, but I haven't seen it explored by anyone else, yet. This could be very useful for machine learning tasks on sequences, since you can learn from fixed-length vectors. (Especially if you have lots of unlabeled data, but a small amount of labels)
My question is, "Can a similar thing be done with Transformers?" I see that this question is a bit vague, but this is my best effort at asking it in a way that could be answered.
Comment: This is actually a very old idea. See RAAM (recursive auto-associative memory) from Pollack, 1990.
Answer: The simple answer would be: yes, it can and BERT already does something like this.
In an RNN, you take the last hidden because it is the state the network is in after reading the entire sentence. In a transformer network, it is not clear what should the special state be.
BERT does that by prepending a special token (they call it [CLS]). BERT is trained on sentence pairs and the vector corresponding to the [CLS] is used to predict if the two sentences are adjacent in a coherent text. When BERT is fine-tuned for downstream tasks, this vector is used as a single vector representation of the input (no matter if the input is a sentence pair or just one sentence).
You can certainly simulate this also in the sequence-to-sequence setup. The simplest way would be using just a vector for the <s> (beginning of a sentence) token instead of the context vector from encoder-decoder attention. However, I doubt it would get you a better representation than BERT and his Transformer friends do.


multi if statment in my expression with shorthand if statment in angular

Question: I have an expression that has three checks that need to be done.
so i was thinking of using it as follow:
<code>{{payload.finance ==='value1' ? 'message 1'}}
</code>
but i need to do 3 checks so is there a way to do something like
<code>{{payload.finance ==='value1' ? 'message 1' || payload.finance === 'value2' ? 'message 2' : 'message 2'}}
</code>
Answer: You might be missing a colon in the first condition. Try the following
<code>{{  payload.finance === 'value1' ? 'message 1' : payload.finance === 'value2' ? 'message 2' : 'message 3'}}
</code>


ClientError: Multiple different grub/menu.lst files found when try to import ubuntu-16.04-server-cloudimg-amd64.ova to AWS EC2

Question: Trying to import
https://cloud-images.ubuntu.com/releases/16.04/release/ubuntu-16.04-server-cloudimg-amd64.ova
to Amazon EC2 with
<code>aws ec2 import-image
    --description "XXX"
    --disk-containers file://xxxx.json
    --platform Linux
    --profile XXX
</code>
I get StatusMessage: ClientError: Multiple different grub/menu.lst files found.
<code>{
    "ImportImageTasks": [
        {
            "Status": "deleted",
            "Description": "XXXX",
            "Platform": "Linux",
            "SnapshotDetails": [
                {
                    "UserBucket": {
                        "S3Bucket": "images.XXXX",
                        "S3Key": "ubuntu-16.04-server-cloudimg-amd64.ova"
                    },
                    "DiskImageSize": 320673792.0,
                    "Format": "VMDK"
                }
            ],
            "StatusMessage": "ClientError: Multiple different grub/menu.lst files found.",
            "ImportTaskId": "import-ami-XXXX"
        }
    ]
}
</code>
Is it possible to import official Ubuntu 16.04 LTS OVA into AWS EC2?
Comment: Seems that it's an issue with official Ubuntu OVA file. Exporting a runing machine to OVA and import to AWS works like a charm.
Answer: You can't import officual Ubuntu 16.04 LTS OVA file.
Exporting a runing machine to OVA and import to AWS works like a charm.
Comment: Thanks, but I am missing why I can't import it? Thanks in advance.


Should I tie across beats 2 and 3 in 3/4?

Question: I know that 3/4 is strong-weak-weak. I've also heard that when it comes to rests, if I have a quarter note on 1, I should then have two quarter rests rather than a half rest.
But how about the opposite? Is this ok?

Or should it instead be tied quarters for beats 2 and 3?
I have a score where these notes are basically echoing an attack on 1 in another staff, a few measures in a row. I think it would look messier if it were tied quarters instead, but I also want to do the right thing.
(I don't generally tie across 2 and 3 in 4/4, since 3 is a strong beat; that case is more obvious.)
Comment: Consider the *Sarabande*, an old dance in 3/4 time, with emphasis on the *second* beat of the bar. There's no real need to tie two crotchets for beats 2 and 3, a minim will suffice, and probably be more welcomed by readers. Even the ubiquitous 4/4 is more and more written 'against the rules', with no designation as to where the middle of the bar is. Obviously that 'rule' can't be followed in 3/4 time!
Answer: Yes, this is totally fine, common practice and if fact using tied quarters for no real reason would be the more obscure choice here.
An important thing to keep in mind about 3/4 is that the composition 1 + 2 is historically a very typical type of syncope since renaissance music (usually in the typical form [4 4. 8]). So notating this with tied quarters may even defeat the purpose.
Comment: Thanks! My brain has trouble reconciling that 2 and 3 should have quarter rests rather than a half rest, while a half note is preferable to tied quarters. But I'm happy to be reassured. :)


Values of the Christoffel symbols

Question: Are the values of the christoffel symbols the same for all coordinate systems on a surface/manifold? I would love to see an example for the cone in two different parametrizations.
Comment: Around every point you can choose [normal coordinates](http://en.wikipedia.org/wiki/Normal_coordinates) in which the christoffel symbols vanish.
Answer: The answer is no. The reason is that the Christoffel symbols are not scalar fields, nor tensor fields, they might vanish completely in a coordinate system and yet be non-vanishing in another.
As a simple example consider the plane in cartesian coordinates: All Christoffel symbols vanish. Now consider polar coordinates, there will be some which are non-vanishing.

Values of the Christoffel symbols


rate app reminder actionscript 3

Question: I tried looking on stackoverflow for this, but didn't have any luck.
Does anyone have an as3 script that would work for asking a user to rate the app after app launches so many times? Also, How would I code it so once they hit the "already rated it" button, it doesn't ask them again?
Thanks
Comment: Thanks, Meps. Thinking about the SharedObject class... What if, when the user pressed the quit button it popped up a rate this app message and either they click the link or they click "don't show this again" and if they choose the later, it stores that they don't want this popup seen again in the SharedObject data. Does that make sense? I just really don't want it to popup evertime they close the app and want a "permanent" way to have the app remember.
Comment: Anyone? How would I permanently remove an MC once the user clicks a button? Permanent meaning, they close the app, re-open the app and that MC does not show up again...
Answer: If you want to store locally some data look for SharedObject class.
But I suppose that your problem have no sense because nobody knows how one user rates application without spreading this info with server-side support.

rate app reminder actionscript 3


JOOQ batch update dates with Oracle 11g

Question: While I'm trying to batch update a field in a Oracle 11g table with Jooq 3.9.0, and I'm getting date related exceptions:
org.jooq.exception.DataAccessException: SQL [null]; error occurred during batching: ORA-01843: not a valid month

We're using Java 8 time types (javaTimeTypes = true). Pseudo code:
List<Query> updates = singletonList(
        jooq.update(TABLE).set(TABLE.FIELD, LocalDateTime.now()));
jooq.batch(updates).execute();

The field has TIMESTAMP(3) type in the table.
So far I've tried to do non-batch updates, e.g.:
updates.forEach(Query::execute);

this works, but I wouldn't sacrifice performance unless it's absolutely necessary.
Also tried to add a type binding in Jooq's config which wraps date fields in a to_timestamp(<Val>, "pattern") call, that also worked, but it seems to be fragile, already raised NLS issues and it looks ugly. Would be nice to figure out why batch updates behaving differently compared to regular ones.
Comment: Can you see the SQL generated in the log? (note I've also opened an issue for this: https://github.com/jOOQ/jOOQ/issues/5910)
Answer: I think you ran into this issue here: #2738, which is fixed for 3.10 and will be integrated in 3.9.2.
Since you're using batch updates with the batch(Collection) API for static statement batches, the bind variables need to be inlined, which doesn't work correctly for Java time API types in jOOQ 3.9.1
Comment: Yes that's the issue we're facing, thanks for the feedback -- sorry about the delay.

JOOQ batch update dates with Oracle 11g


Let $p(x) = ax^2+2bx+c$ be a quadratic form, where $a$, $b$, $c$ are real numbers. Find supremum of $p(x)$

Question: If $p(x) = ax^2+2bx+c$ be a quadratic form, where $a$, $b$, $c$ are real numbers. how to find the supremum of $p(x)$ where $x$ belongs to $\mathbb R$.
Comment: To what corresponds the supremum of a function ?
Answer: Hint: If $a > 0$ then $\text{sup}\{p(x)\}=+\infty$. If $a<0$ then you could find the vertex of the parabola $y=p(x)$ ($\text{sup}\{p(x)\}$ is the $y$th coordinate of the vertex). Also, if $a=b=0$ then $\text{sup}\{p(x)\}=c$. Finally, if $a=0$ and $b \neq 0$ then $\text{sup}\{p(x)\}=+\infty$.
Update: If $a<0$ then we have a parabola opened down. So, the highest point of the parabola is its vertex. The $x$th coordinate of the vertex is $x=-\frac{b}{2a}$ (according to Vieta's theorem if $x_1,x_2$ are the roots of the quadratic form then $x_1+x_2=-\frac{b}{a}$ and the $x$th coordinate of the vertex is $\frac{x_1+x_2}{2}$).
Comment: You are not serious with the last $-\infty$, are you?
Comment: @HagenvonEitzen: :) You are right, sorry
Comment: can you please elaborate the case when $a$ < $0$
Comment: You need to complete the square.
Comment: @liesel: I updated my post.


is there a standard C function to get abs of a Double variable

Question: Is there a standard C function that would take a double and return its absolute value as a double? It is not that difficult to write one, but if it exists why bother. There is int abs(int x), but why isn't there double abs_d(double x)?
Answer: What you want is fabs.  fabsf for floats, fabs for doubles.
http://pubs.opengroup.org/onlinepubs/009695399/functions/fabs.html
Comment: And `fabsl` for `long double`. (BTW, that link is to the POSIX standard; the definitive description is in the ISO C standard.)


Inserir um checkbox dentro de um botão JavaScript JQuery

Question: Tenho uma lista com um mousedown dentro de cada

 e eu preciso colocar um checkbox dentro desse li tbm só que o checkbox não pode ter o mousedown.
Há algum jeito de fazer isso?

  <input style="float: right;" type="checkbox" id="checkbox">

Answer: Nesse caso, precisa tratar o evento mousedown no input e cancelar o evento usando stopPropagation()

$("li").mousedown(function() {
  // faz log de uma mensagem para demonstrar
  console.log( "li.mousedown()" );
});

$("li > input").mousedown(function(event) {
 // aqui cancela o evento. Se comentar essa linha vai ver que aparece o log do event do parent
  event.stopPropagation();
});
li {
  border: solid 1px #000
}

     <input type="checkbox" id="checkbox">

Comment: E como seria para passar um parametro dentro do li mousedown? Porque eu ali no modalCartao(1), esse 1 é um exemplo de um id que eu puxo pra abrir minha modal daquele reigstro
Comment: Eu também queria saber um pouco sobre esse li > input. É possível voce me explicar de forma resumida como que funciona isso?
Comment: sim, esse seletor seleciona "dentro de todos elementos **LI** todos os INPUT **>** aninhados abaixo dele", ou seja, seleciona os elementos ``. Se seus inputs tiverem uma classe, pode selecionar direto por ela
Comment: E outra pergunta como que passo parametro para ->$("li").mousedown(function() { }
Comment: pode passar o evento, ou o proprio objeto com `this` `$("li").mousedown(function(evento)`, mas pode fazer como no seu exemplo, com `onmousedown="modalCartao(1)"
Comment: Ah deu certo, muito obrigado mesmo, uma ultima pergunta, porque (li > input)  nao cancela o evento do checkbox (de selecionar o checkbox) e apenas cancela o da ?


Proving uniform convergence of moment restriction score function in GMM asymptotic normality proof

Question: I am asked in a homework question to prove asymptotic normality for the generalized method of moments estimator. The assumptions (which i think are necessary to solve this particular subproblem) given in the theorem are

$ (Z_i)_{i \in \mathbb{N}}$ is a sequence of i.i.d. random variables.
$g(z|\theta)$ is continuously differentiable wrt. $\theta$ in a neighborhood $\mathcal{N}$ of $\theta_0\in Int(\Theta)$ ($g$ is a moment restriction function, $\theta_0$ is the true parameter, and $\Theta\subset\mathbb{R}^k$ is the parameter space)
$\mathbb{E}[\sup_{\theta\in \mathcal{N}}||g(Z_i|\theta)||]<\infty $

In the concluding argument of the proof I need to show that $G_n(\theta):=\frac{1}{n}\sum_{i=1}^{n}\partial_\theta g(Z_i|\theta)$ converges uniformly to $G(\theta) = \mathbb{E}[\partial _\theta g(Z_i|\theta)]$, i.e. $$\sup_{\theta\in\mathcal{N}} ||G_n(\theta) - G(\theta)||\stackrel{P}{\rightarrow}0$$ It is hinted at that the convergence follows from conditions 2 and 3. I have also snooped around various stack exchanges and gotten a hunch that the Borel-Cantelli lemma might be helpful. But at this point I am truly lost.
Any help would be greatly appreciated!
(If you feel like you would need more information on the problem, please let me know)
Answer: Conditions 2. and 3. are essentially the conditions for the Uniform Law of Large Numbers. In particular, condition 3. is the compact way to express the dominance condition of the ULLN.
A literature pointer to start is Newey, W. K., & McFadden, D. (1994). Large sample estimation and hypothesis testing. Handbook of econometrics, 4, 2111-2245.
Lemma 2.4,


Android change Locale on One Activity Only

Question: I have Just one Activity that i need it with a different locale.
Example my Default App Local is English and i want to Open an Activity where it content is Arabic.
how can i force this activity to read from the values-ar ?
Comment: Possible duplicate of http://stackoverflow.com/questions/4985805/set-locale-programatically
Comment: I just want a specific locale for one Activity, not the whole application
Comment: http://stackoverflow.com/questions/11705963/forcing-a-different-locale-works-only-for-top-activity-in-back-stack
Answer: update the locale by using the below code and change the locale to your preferred one and restart the activity
<code> Configuration config = getBaseContext().getResources().getConfiguration();
    config.locale = Globals.locale;
    getBaseContext().getResources().updateConfiguration( config, null );
    Intent restart = getIntent();
    finish();
    startActivity( restart );
</code>
Comment: Edit your answer with explanation. It was flagged as low quality post


How do umpires make decisions without a third umpire?

Question: I was shocked when I saw umpires making decisions for Run out/Stumped without a third umpire in classic matches. So how do umpires make these decisions without a third umpire?
Answer: The same way they did before the existence of the third umpire, the same way that the vast majority of cricket is played.
The officials learn the laws and best practice for umpiring. Then they pay attention to the game at hand and make observation of the events, determine a course of action based on combination of all the previous points, and effect a decision.
Comment: Probably worth mentioning that the benefit of the doubt goes to the batsman.
Comment: I think that falls under 'best practise' - and I'm not keen to list every major concern involved.
Answer: The umpire makes the decision. Whatever the umpire decides whether it is wrong or right has to be accepted, so basically the umpire's ruling is final. The umpire is trained to spot run outs so MOST of the decisions they make are correct.
Answer: Usually they to consult both the team players which are involve in that specific run-out. They ask both the team players and they discuss it if there is a voting tie or any doubt it goes with the batsman. Usually you hear a line from commentators that the doubt will be in the favor of batsman. For Six or Four they need to ask the audience.
Comment: -1: there is nothing in the Laws whatsoever about consulting the players or the crowd.
Comment: Tell me i dint just read this :P


apache2 and mysql automatically starts up after out of memory failure

Question: I have a server where I'm having out of memory problems. This is causing apache and mysql to be killed, according to the message log.
kernel: [29992047.769005] Out of memory: Kill process 13541 (httpd) score 10 or sacrifice child
kernel: [29992047.769005] Killed process 13541 (httpd) total-vm:70432kB, anon-rss:11016kB, file-rss:168kB

Oddly (although a good thing) it starts up automatically and I can't figure out how. I need to investigate the out of memory errors still but I'm clueless on how it actually starts up automatically.
I've setup apache and mysql on my own Amazon EC2 small instance. There is no cron job on this or any other automatic script other than the usual chkconfig setup for boot time.
Mostly curiosity at this point but it would be useful to know when and how apache and mysql started up again. Might be useful for my other services as well.
Answer: Some clues for you:

Are you running monit?
Or supervisord with autorestart turned
on?
Or Nagios with an Event
Handlers?
...

You can also using the auditd to set a watch on the Apache binary file:
auditctl -w /usr/sbin/httpd -p x -k apache-binary-file

then find out who called it:
# ausearch -f /usr/sbin/httpd
----
time->Tue Mar 19 05:23:22 2013
type=PATH msg=audit(1363674202.844:241): item=1 name=(null) inode=3237 dev=fd:00 mode=0100755 ouid=0 ogid=0 rdev=00:00 obj=system_u:object_r:ld_so_t:s0
type=PATH msg=audit(1363674202.844:241): item=0 name="/usr/sbin/httpd" inode=14695 dev=fd:00 mode=0100755 ouid=0 ogid=0 rdev=00:00 obj=system_u:object_r:httpd_exec_t:s0
type=CWD msg=audit(1363674202.844:241):  cwd="/root"
type=EXECVE msg=audit(1363674202.844:241): argc=1 a0="/usr/sbin/httpd"
type=SYSCALL msg=audit(1363674202.844:241): arch=40000003 syscall=11 success=yes exit=0 a0=9ff7c38 a1=9ff7c00 a2=9ff6bd8 a3=9ff7c00 items=2 ppid=2593 pid=2594 auid=500 uid=0 gid=0 euid=0 suid=0 fsuid=0 egid=0 sgid=0 fsgid=0 tty=pts0 ses=2 comm="httpd" exe="/usr/sbin/httpd" subj=unconfined_u:system_r:httpd_t:s0 key="apache-binary-file"

Comment: None of those things are running, but thanks for the useful tip on `auditd`. I'll try to solve this mystery with that!


Não consigo encontrar qual Style está separando meus elementos

Question: Olá,
Tenho um site que está no ar. Sei que essa dúvida parece bem boba, mas não estou conseguindo encontrar o que está causando um espaçamento entre o Google Maps e meu banner.
Link do site: https://www.bmzveiculos.com.br/
O espaçamento é esse demonstrado na imagem.

Se alguém puder me ajudar eu agradeço!
Answer: Uma imagem é um elemento inline, e ela tem algumas propriedades default desse tipo de box-model, se vc quer que esse espaço não aparece e como sua imagem tem 100% da largura da tela, basta vc colocar um display:block nela que resolve.
Isso vai resolver o problema, adicionando o display:block na classe .banner__two__image que vc usa na tag  do banner.
.banner__two__image {
    height: 100%;
    -o-object-fit: cover;
    object-fit: cover;
    width: 100%;
    display: block; /* aqui */
}

Veja como resolveu
Comment: Perfeito. Obrigado.
Comment: @Jhonny sem problemas meu caro!
Comment: A alteração já está publicada (:
Comment: @Jhonny parece que resolveu mesmo! Quem bom que deu certo ai!
Answer: você tem a
 que contém as duas divisões, a esquerda o mapa e a direita o carro.
dentro da
 você tem todo o código apresentando o mapa.
na parte da direita você deveria ter outra div para dividir o código da forma correta, mas foi colocado apenas um <a href....
O seu código está com essas identificações de divisão.
Comment: Você está querendo dizer que meu `` deve estar dentro de uma ``? Por que isso, por causa do `display: block`? Eu testei e não funcionou.
Comment: Se liga nessa classe .half__banner>* {
    padding: 0;
    width: 50%;
}
Comment: Tenta deixar o width 100%
Comment: .half__banner>* {
    padding: 0;
    width: 100%;
}


How to pay with site credit in Commerce?

Question: I would like to allow users to pay for products with site credit.
A field keeps track of how much credit a user has with us, and if they have enough of it to pay for an order they should have that option. Even better would be if they could dump the last bit of credit onto an order and pay the rest the regular way.
I have a few ideas; I'm just wondering if there's a standard or best practice in this situation. Thanks in advance.
Edit: Some of the ideas:

Using Rules, add a payment method if the user has more credit than the order total. If this payment method is selected, no validation is needed. The user clicks through and credit is deducted.
Add a checkbox to the checkout pane called ~"use site credit". If checked, subtract the user's credit from the price (up to the order total). This has the advantage that a user can pay with credit even if they don't have enough for the whole order, but seems much harder to do.
At the calculate price stage, automatically subtract credit from the order appropriately. Add some notification informing the user that this has been done.

I may update this more as I explore options further
Answer: you can use user-points module with Commerce userpoints. they work nice togather.
Comment: If you could add a little more explanation? Just a sentence or two about each module?


help with hyperbolic functions like sinh and tanh

Question: Show that $\sin^{-1}(\tanh x)=\tan^{-1}(\sinh x)$.
Got a hint that $\sin\theta=\tanh x$ but I still don't know how to proceed...
Comment: Does $\tan hx$ denote $\tan (hx)$ or $(\tan h) \times x$?
Comment: @Paul: Neither. $\tanh x$ denotes the [hyperbolic tangent](http://en.wikipedia.org/wiki/Hyperbolic_function) of *x*.
Comment: @Lucian Thanks. I see!
Answer: Differentiate both to show they share the same derivative. Then, check one value to show equality is met. (if $f'(x)=g'(x)$ on a connected domain then $f(x)=g(x)+c$. You want $c=0$)
Answer: Let $\sin\theta=\tanh x$. $\sin^{-1}(\tanh x)=\sin^{-1}(\sin\theta)=\theta$.
We only need to prove $$\sinh x= \tan \theta. $$ To prove it, by using $\sin\theta=\tanh x$,  it only need to prove that
$$\cos \theta =\frac{1} {\cosh x}.$$
In fact: $$\cos^2 \theta=1-\sin^2 \theta=(1-\sin \theta)(1+\sin \theta)=\frac{4}{(e^x+e^{-x})^2}.$$
Now it is easy to get our conclusion.


How to build libxerces-c for Windows 32-bit from CMake generated Visual Studio project files?

Question: I'm trying to build libxerces-c for Windows. Instruction on their xerces site looks like this:
mkdir build
cd build
cmake -G "Visual Studio 14 2015 Win64" -DCMAKE_INSTALL_PREFIX=D:\libs    \path\to\xerces-c\source
cmake --build . --config Debug
ctest -V -C Debug -j 4
cmake --build . --config Debug --target install

I'm using VS2017 so using this instead: "Visual Studio 15 2017 Win64"
Looking at the generated VS project file only x64 platform is generated. I tried changing "Win64" to "Win32" and "x86", but get and error that only "Win64" and "ARM" are available:
cmake .. -G "Visual Studio 15 2017 Win32"
CMake Error: Could not create named generator Visual Studio 15 2017 Win32

Generators
  Visual Studio 16 2019        = Generates Visual Studio 2019 project files.
                                 Use -A option to specify architecture.
* Visual Studio 15 2017 [arch] = Generates Visual Studio 2017 project files.
                                 Optional [arch] can be "Win64" or "ARM".
  Visual Studio 14 2015 [arch] = Generates Visual Studio 2015 project files.
                                 Optional [arch] can be "Win64" or "ARM".
  Visual Studio 12 2013 [arch] = Generates Visual Studio 2013 project files.

Can I control this from CMake somehow?
Answer: Reading more carefully I see Win64/ARM are OPTIONAL. Omitting arch gives me the x86 platform:
cmake -G "Visual Studio 14 2015" -DCMAKE_INSTALL_PREFIX=D:\libs


How to stop Spark from changing varchar to string?

Question: I have a Hive table with below schema:
hive> desc <DB>.<TN>;
id int,
name varchar(10),
reg varchar(8);

When I try to describe the same table on Spark (Pyspark shell) it's converting Varchar to String.
spark.sql("""describe <DB>.<TN>""").show()
id int
name string
reg string

I would like to retain Hive datatypes while querying on Spark. Means I am expecting varchar in the place of String. Does anyone know how to stop spark from inferring datatypes of its own?
Answer: There is no varchar in Apache Spark, it's all Strings. Yeah, this page says there is a VarcharType but it is only for schemas.
Once the data is in the dataframe, things are transparent. When you save the data, all should be back to varchar in Hive.
You can force a schema on reading the dataframe when it is available (like CSV for example), but I do not think it is available for Hive, which is already typed.
Answer: I was going to tell you to just add a schema
schema = StructType([StructField('ID', IntegerType(), True),StructField('name', VarcharType(10), True),StructField('reg', VarcharType(8), True)])
df3 = sqlContext.createDataFrame(rdd, schema)

to a dataframe but data frames do not have a varchar type in spark <= 2.4.  Which is likely why your varchars are being converted to StringType.  That isn't to say that they aren't available in spark(2.4 >).