Rows cannot be programmatically added to the DataGridView's rows collection when the control is data-bound

Question: I have a grid and when data is loaded in grid; I simply select a row and press edit button. On edit, new sub form is opened and values of row's cells are passed to controls on sub form. But, when I change some values on sub form and save them to be replaces in grid the error comes to me: Rows cannot be programmatically added to the DataGridView's rows collection when the control is data-bound. What is cause of this error and how to overcome this.
Comment: Well you can add a row/record to your datasource
Comment: are you set the `DataSource` property of DataGridView ?
Comment: Well, I've a DataSet as DataSource of Grid. How I can add row in DataSet Or I need to add row to table and then add that table to dataset ?
Answer: The cause is that "Rows cannot be programmatically added to the DataGridView's rows collection when the control is data-bound". It is as clear as crystalline water
The solution? Do not add rows to the DataGridView's rows collection, add them to the underlying datasource collection (the collection you are setting in to the DataSource property of the DataGridView)
Answer: Add or Edit your row in DataSource of your DataGridView. Do not directly add/edit to your grid.
If your DataSource is DataSet and you want to add new row
DataSet dsTempDataTable = (DataSet)MainApplication.dgvBooksDetails.DataSource;
DataTable dt = dsTempDataTable.Tables[0]; // use table index/name to get the exact table
DataRow dr = dt.NewRow();
//  code to fill record
dt.Rows.Add(dr);

To Edit
DataSet dsTempDataTable = (DataSet)MainApplication.dgvBooksDetails.DataSource;
DataTable dt = dsTempDataTable.Tables[0]; // use table index/name to get the exact table
dt.Rows[0]["columnName"] = "some value";
// your row edit  code
dt.AcceptChanges();

Comment: dt.Row[0] : here 0 indicates the index of row ? And how I can handle more then one columns in row ? I mean, hwo to set values to cells if I have 7 columns in a Row ?
Comment: @Itz.Irshad very simple, you can use the column name  like that.. dt.Rows[0]["column1"] = "value1";
dt.Rows[0]["column2"] = "value2";     dt.Rows[0]["column3"] = "value3";          and so on
Comment: Yeah, I did. But, since I have a `DataSet` as a `DataSource` to `Grid`....so getting this error: *Unable to cast object of type 'System.Data.DataSet' to type 'System.Data.DataTable'.* on first line having code: `DataTable dtTempDataTable = (DataTable)MainApplication.dgvBooksDetails.DataSource;`
Comment: @Itz.Irshad  see my updated answer, it converts the dataSource into DataSet object and than use the index to get the exact table
Comment: Well, I'm reading **xml file** via 'DataSet' and Providing it as 'DataSource' to 'Grid'. So, no tables is mentioned there. But, when as you suggest in latest code. use table in 'DataSet' and add row in it. I'm getting this error: **There is no row at position 1.** *I think it is because, in data is loaded from `DataSet` and newly created Table have no rows.* How it can be solved ?
Comment: @Itz.Irshad debug your code and check `DataSet` hs any tables? and tables has any rows?
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/13767/discussion-between-itz-irshad-and-talha)
Answer: I had the same problem and I found solution.
//create datatable and columns
DataTable dtable = new DataTable();
dtable.Columns.Add(new DataColumn("Column 1"));
dtable.Columns.Add(new DataColumn("Column 2"));

//simple way create object for rowvalues here i have given only 2 add as per your requirement
object[] RowValues = { "", "" };

//assign values into row object
RowValues[0] = "your value 1";
RowValues[1] = "your value 2";

//create new data row
DataRow dRow;
dRow = dtable.Rows.Add(RowValues);
dtable.AcceptChanges();

//now bind datatable to gridview...
gridview.datasource=dtable;
gridview.databind();

Source: http://www.codeproject.com/Questions/615379/Adding-rows-to-datagridview-with-existing-columns


Abrir e fechar div com recurso slideToggle do jQuery

Question: Tenho a seguinte estrutura:

Quando clico na div com a classe botao, a div sub-item abre com recuso slideToggle do jquery, eu gostaria que conforme eu clicasse em uma outra div com classe botao a div sub-item aberta que estivesse aberta, fechasse.
Já usei o sibling() e não funcionou
Alguém poderia me ajudar? Obrigado
Comment: O que você está procurando não seria o `Accordion`? Exemplo no [JQuery UI](https://jqueryui.com/accordion/)
Comment: fecha todas pela classe antes de abrir a nova
Comment: Não entendi wess?
Comment: Sim Victor, é quase um accordion, mas não posso usar jquery ui
Comment: "...não posso usar jquery ui"...ta escrevendo o próprio framework? Tem um pessoal bom aqui na página que tem o próprio framework. Se for o caso sucesso e mande uma versão quando ficar pronto.
Answer: Começo por dizer que tinha umas " em falta na sua estrutura de exemplo.
Quanto ao problema em si é mais facil resolver fazendo slideUp e slideDown manualmente. Quando clica num elemento faz slideUp a todos, que só irá afetar aquele que está para baixo e faz slideDown ao que foi clicado.
Exemplo:

$(".botão").on("click", function(){
  $(".sub-item").slideUp();
  $(this).next().slideDown();
});
.sub-item {
  display:none;
}

item 1

subitem1

item 2

subitem2

item 3

subitem3

Se utilizar slideToggle ao invés de slideDown irá ter exatamente o mesmo efeito, mas acaba por talvez ser mais confuso porque irá apenas sempre abrir e nunca fechar, logo corresponde sempre apenas a slideDown.

Como já foi referido em comentários não convem reinventar a roda e o que está a tentar construir já existe e é chamado de acordião. O JQuery UI já tem de facto isso nos plugins deles já contemplando várias configurações possíveis como:

Ícones personalizados
Menus colapsaveis
Sem tamanho automático
Ordenável

Referência para o JQuery UI Accordion
Comment: Isac, não quero reinventar a roda, simplesmente por decisão de um superior não posso usar jQuery UI


Fading a UIView with a subviewed button

Question: I'm trying to create a button that fades out and then in when I open the page.
Here is the current code that i'm using, it doesn't work to fade the buttons in/ out:
<code>- (UIView *)carousel:(iCarousel *)carousel viewForItemAtIndex:(NSUInteger)index reusingView:(UIView *)view
{
    if (index == 0) {
        view = [[[NSBundle mainBundle] loadNibNamed:@"nib1" owner:self options:nil] lastObject];
    }else {
        view = [[[NSBundle mainBundle] loadNibNamed:@"nib2" owner:self options:nil] lastObject];
        UIView *containView = [[UIView alloc] initWithFrame:CGRectMake(50, 50, 60, 100)];
        _btn = [UIButton buttonWithType:UIButtonTypeCustom];
        _btn.frame = CGRectMake(30, 90, 40, 30 );
        [_btn setBackgroundImage:[UIImage imageNamed:@"playButton.png"] forState:UIControlStateNormal];
        [_btn addTarget:self action:@selector(fadeButton:) forControlEvents:UIControlEventTouchUpInside];
        //[self fadeOut:_btn withDuration:1.0 andWait:1.0];
        [containView addSubview:_btn];
        [containView setAlpha:0.0];
        [view addSubview:containView];
        [UIView beginAnimations:nil context:nil];
        [containView setAlpha:1.0];
        [UIView commitAnimations];
    }
return view;
}
</code>
I've also tried using:
<code>[UIView animateWithDuration:0.5 animations:^{_btn.alpha = 1.0;}];
</code>
None of those work. Does anyone have any tips on how to fade a subview out? Thanks
Answer: When you call [UIView commitAnimations], the animations are animating at the same time.
When you want to animate something after an other animation try to nest animation blocks with completion:
<code>[UIView animateWithDuration:0.5 animations:^
{
   //animate out
}
completion:^ (BOOL finished)
{
    [UIView animateWithDuration:0.5 animations:^
    {
       //animate in
    }
    completion:^ (BOOL finished)
    {
      //Optional
    }];
}];
</code>
Answer: To fade out, you have to animate the alpha to 0, not to 1.
<code>[UIView animateWithDuration:0.5 animations:^{_btn.alpha = 0.0;}];
</code>
This should work.
Comment: I meant to say in my original post, that whenever I try that, as in set the alpha to 0.0, the button just never appears. It's always hidden.

Fading a UIView with a subviewed button


angularjs - HTTPpromise does not execute when JSONP is returned

Question: I am trying to get a stock quote from yahoo's api and I am using angular's $http.jsonp method. The goal is when the result comes back, to have the app go to the this route: '/stocks/show_stock'. I am trying to do it in two ways and neither works
1) I put the statement:
window.location = '/stocks/show_stock'

in the callback function that wraps the JSONP response
2) I put the statement:
$location.path '/stocks/show_stock'

in the HTTPpromise callback. (see the comments in the code)
Here is my code (in coffescript):
#THIS IS THE CALLBACK FUNCTION THAT I SEND WITH THE JSONP REQUEST
window.stock_quote_callback = (data)->
  console.log data #THIS WORKS AND I CAN SEE THE DATA RETURNED FROM YAHOO
  window.stock_quote_result = data.results
  alert 'I am in the callback'
  #THE STATEMENT BELOW DOES NOT WORK EVEN THOUGH I CAN SEE THE ALERT ABOVE
  window.location = '/stocks/show_stock'

angular.module('Services').service 'StockSupplier', ($http)->
  get_stock = (symbol)->
    q = 'select * from yahoo.finance.quotes
        where symbol in ("'+symbol+'")
        &format=json&
        diagnostics=true&
        env=http://datatables.org/alltables.env&
        callback=stock_quote_callback'
    url = 'http://query.yahooapis.com/v1/public/yql?q='+q
    $http.jsonp(url).then (data)->
      #THE CODE BELOW NEVER EXECUTES EVEN THOUGH RESULT IS RETURNED
      alert 'This should pop up when result returns'
      $location.path'/stocks/show_stock'

  {
    get_stock: (symbol)-> get_stock(symbol)
  }

Thank you in advance.
Comment: it is there. the 6th line of the 'q' string. As I mentioned that is not the problem I do get the callback to fire but window.location = '/stocks/show_stock' inside that callback does not work. That is why I tried to use the 'then' function of httpPromise but that didn't work either
Comment: you have not added callback=JSON_CALLBACK to the url, the url should be http://query.yahooapis.com/v1/public/yql?callback=JSON_CALLBACK&q='+q
Comment: Thanks Ajay now I know what you mean.
Answer: I don't write coffeescript, so I translated it to javascript. You forgot to inject the $location service, other than that I just replaced the callback=stock_quote_callback to callback=JSON_CALLBACK and created a plunker that runs just fine: http://run.plnkr.co/hCAdohIJIr9Odn3m/ (source: http://plnkr.co/edit/a7C6k0QVoXnaTyImSUkb?p=preview).
angular.module('Services').service('StockSupplier', function($http,$location) {
  var get_stock;
  get_stock = function(symbol) {
    var q, url;
    q = 'select * from yahoo.finance.quotes where symbol in ("' + symbol + '")&'+
        'format=json&'+
        'diagnostics=true&'+
        'env=http://datatables.org/alltables.env&'+
        'callback=JSON_CALLBACK ';
    url = 'http://query.yahooapis.com/v1/public/yql?q=' + q;
    return $http.jsonp(url).then(function(data) {
      alert('This should pop up when result returns');
      $location.path( '/stocks/show_stock' );
    });
  };
  return {
    get_stock: function(symbol) {
      return get_stock(symbol);
    }
  };
});

Comment: Thanks a bunch jo! Reading the angular documentation I thought that 'JSON_CALLBACK' was a placeholder for the name of the function you want executed when the response returned, and not that I have to literally put 'JSON_CALLBACK' as the name of the function. That solved it.


How to deal with a Windows path given as an argument

Question: I have a script that takes a file path as an argument and I'm having issues with how to handle Windows paths in this situation.  How do I avoid a situation like this "T:\not\a\good\path" which is causing issues due to the escape characters like \n in the given path?
I'm using Click to parse my arguments and I prefer using the Pathlib module but I haven't figured out a good way to prevent those escape characters from messing things up the given path when it's passed to my code.
Example of code and what it's outputting.
import click
@click.command()
@click.argument("inpath")
def main(inpath):
    # "T:\not\a\good\path"
    print(inpath)

if __name__ == "__main__":
    main()

Run: foo.txt T:\not\a\good\path
Output:
T:notagoodpath
Comment: Can you clarify how your script takes a file path as an argument? If its a command line argument read from `sys.argv`, then there is no escaping needed. Escaping is only needed if this is a python string literal - usually that means a quoted string you typed into the program. But that wouldn't be an argument to the script...
Comment: IT would help to have an example that fails. Did `click` process an agrument and give you a string? You could `print(argument)` and see what you got. Or `print(repr(argument))` and post it here so we can see it.
Comment: @tdelaney Updated my post with some code.  Here I'm simply printing out what the `inpath` argument is passing.  But it's representative of the issue I'm having.  It's not passing along a literal string.
Comment: @tdelaney BTW, I know this is probably a really simple problem.  I'm an experience coder, but I mainly code in a Unix environment.  But this windows path is really stumping me.
Comment: Thanks for the update. I reproduced the problem, but its shell problem, not a python one, at least in common linux shells. \ escapes the next character, so whoever runs the program would have to know to write `foo.py "T:\not\a\good\path"`. But any program run by the shell has the same issues. Of course, linxu avoids \ in file names. I don't have Windows up and running at the moment so don't know its rules but i think that there is no need to escape there. Which OS are you running on?
Comment: @tdelaney Oh I see, the path has to be wrapped in quotes.  So I'm developing on my Debian instance.  But I know this tool will be run on a Windows machine and has to accept Windows style paths.  So I'm just trying to make sure I'm handling the incoming path arguments properly to idiot proof it as much as possible.  I had assumed there was a pythonic way to handle arguments such as this.  But is the answer really expecting the user to wrap their paths in quotes?
Comment: This only applies when running on the command line where you need to consider the shell's string escape rules. Not a problem on Windows. If a user is entering a Windows path on a linux machine, then there is a problem. But that linux command line user should be expected to know that sort of thing, IMHO. Windows accepts forward slashes these days, and that should work fine. Python won't know that, for instance, `\n` was converted to `n`, so there isn't much it can do.
Answer: You can use the "r" prefix to make your string raw and interpret "\n" as 2 regular characters.
path = r"T:\not\a\good\path"
print(path)

The result will be
"T:\not\a\good\path"

Comment: But how do you enforce that from a user given argument.  That's the problem I'm having right now.
Comment: @Berkyjay - well, you don't. Those are rules for literal strings in the python program itself. Suppose your program is `foo.py T:\not\a\good\path`. That is a good path. Since python didn't parse it, there was no special treatment of `\n`. Its the two characters \ and n.
Answer: Give this a try:
@click.argument("inpath", type=click.Path(exists=False))

def main(inpath):
    # "T:\not\a\good\path"
    click.echo(click.format_filename(inpath))

Note: if you want to make sure the path exists, change exists to True.
Comment: Thanks for the response.  Unfortunately verifying the existence of a path isn't my issue.  It's that backslashes in a string are escape characters and can cause issues with examples like the one I gave.  I'm trying to figure out how best to handle windows paths passed as arguments.


Major Scale Ascending Formula in reverse direction

Question: I Know that major scale ascending formula is TTSTTTS (T-tone, S- semitone)
Using This we can find G major notes and those will be in the order GABCDEF#G (from left to right on keyboard)
So my question is what if we use the same formula to find G major notes but in reverse direction (from right to left on keyboard)
In this way Notes came out to be GFEbDCBbAbG
So does this mean anything if use this formula in the above way?
I hope U get my pt.
Comment: Well, that's, if you write it again bottom-to-top, [STTTSTT](https://en.wikipedia.org/wiki/Phrygian_mode). But you may consider this just a coincidence; it only works this way if you really interpret semi- and whole tones as fundamental entities (as in Pythagorean or 12-edo systems). It doesn't work in e.g. a Ptolemaic, harmony-guided understanding of scales.
Comment: I have just started learning music theory and the above is a bit difficult to understand.So, can u explain it in an easy way?
Answer: Interesting theory! What you end up with is the major scale notes of Eb, with its 3 flats of Bb Eb and Ab. Except that doing it your way, starting on G, actually produces a mode of Eb called G Phrygian.
The concept of scales is that they are more easily considered as cycles rather than linear - as in when you get back to the start note, the cycle starts again. True, on a keyboard, the notes are laid ouy in a linear fashion, but name wise it's cyclic.
Modes, if they're new to you, are the same notes as a major scale (thus TTSTTTS), but the seven modes start on each of the different major scale notes. So - Dorian (the 2nd mode) starts on the second note, therefore the pattern is TSTTTST.
Comment: And thus Dorian is its own inversion!
Comment: @Richard - indeed - whichever way you look at it. 'Dorian: I can play that mode backwards...'
Comment: Amateur. I can play it backwards and upside down.
Comment: @Richard - that's a fair trick. I tried playing the piano standing on my head, but kept falling over... It was easier when I turned the *piano* upside down though...
Comment: Now you're getting some idea of what it's like being a musician here in the Land Down Under, where we have to spell that mode n-a-i-r-o-d and play it accordingly (with one hand tied in front of our back).
Comment: @AreelXocha - and exactly where is the observer standing when it's decided it's Down Under?  Could just as easily be Up on Top...
Answer: The procedure you describe of running the steps (intervals) backwards can be called an inversion. The resulting notes of the inverted major scale make the phrygian mode. So you can say the inversion of the major scale is the phrygian mode.
You can do other inversions. For example, major chord inverted becomes a minor chord.


Comparing the Markov and Chebyshev's inequalities

Question: This question was given to me as a review for an upcoming exam.
Let X be a positive random variable with mean 3 and variance $\frac{1}{4}$. Use Chebyshev's and Markov's inequalities to obtain the probability that $X \geq 6$.
Also give an example of such an X
My work thus far:
Chebyshev's
$P(|X-\overline{x}| \geq a) \leq \frac{\sigma^{2}}{a^2} $
$P(X -3 \geq6-3) \leq \frac{\frac{1}{4}}{3^2} = \frac{1}{36}$
Markov's
$P(X \gt a) \leq \frac{E[X]}{a}$
$P(X \gt 6) \leq \frac{3}{6}= \frac{1}{2}$
I feel as though I've made an error somewhere, could someone help me figure out where?
Answer: Your expression for Chebyshev's two sided inequality perhaps should have been $$P(|X-\mu| \geq a) \leq \frac{\sigma^{2}}{a^2}$$  and would have led to an upper bound of $\frac1{36}$, slightly higher than you have. What you have actually used looks like a one sided version $$P(X-\mu \geq a) \leq \frac{\sigma^{2}}{\sigma^{2}+a^2}$$ for $a \gt 0$, and your result of $\frac1{37}$ as an upper bound would then appear to be correct.  There would be equality if $P(X=6)=\frac1{37}$ and $P\left(X=\frac{35}{12}\right)=\frac{36}{37}$
Your use of Markov's inequality for a non-negative random variable and $a \gt 0$ and your result of $\frac12$ as an upper bound both appear to be correct.  There would be equality if $P(X=6)=\frac1{2}$ and $P\left(X=0\right)=\frac{1}{2}$, though this would have a variance of $9$, rather higher than that given in the question, and showing that taking the variance into account here gives a tighter bound through Chebyshev's one sided inequality


select rows that vary in only one column - R

Question: I have a dataframe that looks somewhat like the following:
   v1 v2 v3 v4 v5 v6
r1 1  2  2  4  5  9
r2 1  2  2  4  5  10
r3 2  2  2  4  5  9
r4 2  2  2  4  5  10

I would like to select rows r1 and r3 based on the fact that they differ in their values in v1. The numbers in that column range from 1 to 100. Is that possible and if yes, how?
Any help greatly appreciated, thank you!
Update:
Some clarification: The values in v1 are random seeds that go from 1 to 100. Basically, I run (in NetLogo) a simulation that runs through all parameter configurations (v2 - v6) with 100 different random seeds. I would now like to select all rows that belong to the same parameter configuration, i.e. if v2 = 2 and v3= 5, get me all rows that meet that condition and have different values in v1/random seeds. But since I have quite a lot of parameter configurations, I would like to do this generically, so that I don't have to write these manually. Hence the question if it is possible to select rows that are the same in a number of columns, but differ in one specific column.
Comment: Sorry, but your conditions for selecting the rows is really vague. Can you be a little bit more specific? Are you just looking for `duplicated`, `unique` or one of those related functions.
Comment: Done, hope it helps :)
Comment: So you are ignoring the fact that column `v6` has different values in it?
Comment: Yes, exactly. This is because v6 (and others) contain simulation results that depend on the random seed and are not parameters. In a later stage I want to get the average of the values in these columns, but before I can do that I need to select all rows that belong to the same parameter configuration.
Answer: Here is one way using plyr to split the data.frame up into chunks. Each chunk consists of those that have the same values in the first column. We simply return the first row from each chunk. Like this:
#  Here function(x) x[1,] - mean return the first row from each piece
ddply( df , .variables = "v1" , .fun = function(x) x[1,] )
#  v1 v2 v3 v4 v5 v6
#1  1  2  2  4  5  9
#2  2  2  2  4  5  9

Comment: Is there a way to make this just get the rows with the highest number in another variable? So if v6 has values 4, 5, 6, 10 for the same v1 value, I only get the row where v6 = 10?
Comment: @LukasKawerau this would be better posed as a seperate question. More people will see it and you will possibly get upvotes for posting a well-formed question.
Comment: Alright, thanks! Asked the question here: http://stackoverflow.com/questions/18764825/get-row-with-highest-value-from-one-column-after-chunking-with-plyr-r


Does this conjecture imply the prime number theorem?

Question: Background
I had asked on a forum if my conjecture was of any value:
$$ \lim_{k \to \infty}  \lim_{n \to \infty}\ \sum_{r=1}^n d_r \left(  f\left(\frac{rk}{n}\right)\frac{k}{n} \right) =  \lim_{s \to 1} \! \underbrace{\frac{1}{\zeta(s)}   \sum_{r=1}^\infty  \frac{d_r}{r^s}}_{\text{removable singularity}} \int_{0^+}^\infty f(x) \, dx  $$
Where $f(x)$ is a smooth continuous function whose integral $\int_0^\infty f(x) d x  $ is absolutely convergent. $d_r$ is the $r$-th number of an arbitrary sequence.
One of the commentor's said:

... For example for $d_r=\log(p)$ if $ r=p^k$ and $d_r=0$ if $r$ is not a prime power (the Von Mangoldt function) your formula is a famous theorem: the prime number theorem ....

He didn't give any further hints.
Question
Can someone elaborate on how this implies the PNT?
Comment: I would try writing the left-hand side as a [Dirichlet convolution](https://en.wikipedia.org/wiki/Dirichlet_convolution). Note that the sums here are over divisors, which the Von-Mangoldt function being zero on composite numbers might help you manipulate your sum into. Also note that $\sum_{r = 1}^\infty d_r/r^s$ is well-known for $d_r = \Lambda(r)$ being the von-mangoldt function --- it's $-\zeta'(s)/\zeta(s)$ (see [this page](https://en.wikipedia.org/wiki/Von_Mangoldt_function#Dirichlet_series) for a citation).
Answer: This has nothing to do with the PNT.
If $d_r \ge 0$ and $
\sum_{r \le y} d_r \sim ay$ and $f$ is continuous and $L^1$ then
$$\lim_{n \to \infty} \sum_{r=1}^n d_r  f\left(\frac{rk}{n}\right)\frac{k}{n} =\lim_{n \to \infty} \sum_{r=1}^n a  f\left(\frac{rk}{n}\right)\frac{k}{n} = a\int_0^k f(x)dx$$
On the other hand
$$\lim_{s \to 1^+} (s-1) \sum_{r=1}^\infty d_r r^{-s}=a$$
If $\sum_{r \le y} d_r = o(y)$ then both side converges to $0$, if $ y = o(\sum_{r \le y} d_r)$ then both side diverge to $\infty$.
If $\sum_{r \le y} d_r \sim ay$ you can use partial summation to remove the assumption $d_r \ge 0$


generating dynamic onclick events with javascript

Question: I am dynamically generating a series of onclick events where an alert() is associated with loop number of the pretended content.  My problem is that currently the alerts outputs the 'i' value of the last loop rather than the i'th loop associated with the pretended content.  Any thoughts?
JavaScript:
for (i = 1; i < 4; i++) {

    prepend_content = 'foo';
    $('#dynamic_div').prepend(prepend_content);

}

Many thanks.
Answer: Try concatenating it like you do before:
for (i = 1; i < 4; i++) {
    prepend_content = 'foo';
    $('#dynamic_div').prepend(prepend_content);
}

You might want to declare i and prepend_content (with var) in case you already haven't, to make sure they don't leak into the global scope.
At the same time, I wouldn't suggest using or adding HTML with inline event handlers. Try creating the element like this:
prepend_content = $("").attr({
    href: "#",
    id: "img1_link_" + i
}).text("foo").on("click", (function (i) {
    return function () {
        alert(i);
    };
})(i));

DEMO: http://jsfiddle.net/ujv4y/
The extra use of the immediately invoked function for the click handler is to make a closure that captures the value of i in the loop.
Comment: Concatanate is exactly what I needed.  Thanks!  : )
Comment: @user1497338 No problem, glad it helped! Let me know if you need more help with this :)
Answer: You can create a function using currying for the alert (for more complex stuff):
function(i) {
return function(){alert(i);}
}


Why is K-Means++ SLOWER than random initialization K-Means?

Question: K-Means is an iterative clustering method which randomly assigns initial centroids and shifts them to minimize the sum of squares. One problem is that, because the centroids are initially random, a bad starting position could cause the algorithm to converge at a local optimum.
K-Means++ was designed to combat this - It chooses the initial centroids using a weighted method which makes it more likely that points further away will be chosen as the initial centroids. The idea is that while initialization is more complex and will take longer, the centroids will be more accurate and thus fewer iterations are needed, hence it will reduce overall time. (Source)
In fact, the people who devised K-Means++ tested how fast it could cluster data, and found that it was twice as fast. (Source)
However, some basic tests in R show that K-Means++ requiring fewer iterations than K-Means does not make up for the extra time taken to initialize, even for normal sized datasets.
The test:
I tested it with datasets sized from 100 to a few thousand points. The data is named 'comp' in the code. If you want to test it, you can use whatever dataset you want.
K-Means
First, we do the clustering:
k <- kmeans(comp, 2, nstart=1, iter.max=100, algorithm = "Lloyd")

Next, the sum of squares can be added to a list
results <- k$withinss

Now, if we put the clustering in a loop, which adds to the 'results' list every time it loops, we can see how many times it has looped in a certain amount of time
repeat {
k <- kmeans(comp, 2, nstart=1, iter.max=10, algorithm = "Lloyd")

results <- c(results, k$withinss)
}

(I did it in this inefficient way because I initially used this code to test the accuracy i.e which method had the average total Sum of Squares)
If we let the loop run for 60s, we find that the list is 132,482 objects long. (it looped 66241 times since each time adds two objects to the list).
K-Means++
Now compare that with ++ initialisation.
#Set-up
library(LICORS)
k <- kmeanspp(comp, k = 2, start = "random", iter.max = 100, nstart = 1)

results <- k$withinss

#Loop
repeat {
k <- kmeanspp(comp, k = 2, start = "random", iter.max = 100, nstart = 1)

results <- c(results, k$withinss)
}

The 'results' list ended up having 22712 objects (it looped 11356 times).
K-Means was over 5 times faster than K-Means++, so this is clearly not just a measurement error. The ratio changes depending on the dataset I use for the test, but I've tried everything up to datasets with thousands of points, and the results consistently show that K-Means++ is slower.
My first thought was that maybe the package I used (LICORS) has inefficient code for performing K-Means, but then I saw that LICORS actually uses the default kmeans function after ++ initialization. In other words: Everything was the same except for the method of initialization, and ++ was slower. (another package for K-Means++ called flexclust which uses different code was even slower!)
Perhaps the dataset needs to have tens of thousands of points for K-Means++ to be faster? In this case, it would be very misleading for every source I've seen to say that K-Means++ is faster. Perhaps I've misunderstood something, or there's something wrong with the test?
Can any experts here (such as Tim, who claims here that K-Means++ is faster) explain these results?
Comment: Note that there is some work on faster alternatives to kmeans++ initialization for very large datasets. For example, [this paper](http://papers.nips.cc/paper/6477-fast-and-provably-good-seedings-for-k-means) proposes an algorithm called AFK-MC2 which approximates kmeans++ initialization using MCMC.
Answer: kmeans in R is pretty good Fortran code.
I haven't looked at the package you got kmeanspp from, but I wouldn't expect it to be of the same quality. If it uses R code to do the initialization that can hurt badly.
So in the end, you haven't been benchmarking kmeans vs. kmeans++, but you have been showing that the quality of R packages varies a lot, and the R interpreter is substantially slower than Fortran/C/C++ functions, and you therefore cannot rely on such benchmarks.
The low performance of flexclust is probably because it uses even more R code?
Comment: +1. I am dishearten on how sometimes people think that high-performance code (or even plain old Fortran/C/C++) magically happens. `kmeanspp` is exclusively written in R btw...
Comment: Well, YangLi indicated it is a R function to do the initialization, then uses regular `kmeans`. It may be necessary to rewrite the kmeans++ initialization in Fortran to get a fair benchmark. it may also be helpful to measure initialization time and actual run time independently.
Comment: Obviously yes. `kmeans` is not part of the code *written* for `kmeanspp` though. :)
Comment: +1 and Accepted. I was wondering if I had the mathematical theory wrong, but it looks like I'll just have to rewrite in Fortran to do a fairer test.
Answer:
Why is K-Means++ SLOWER than random initialization K-Means?

I would argue that it depends. First recall the difference between the two:
K-means ++
K-means++ involves a somewhat intensive initialization step where:

Choose on center uniformly at random among the data points
For each data point, compute the distance $D(x)$ between $x$ and the nearest center that has already been chosen
Choose one new data point at random as a new center, using a weighted probability distribution where a point $x$ is chosen with probability proportional to $D(x)^2$
Repeat the above steps until $k$ centers have been chosen
Proceed with standard $k$-means

K-means

Jump straight here --> Randomly initialize $k$ centers
Repeat until convergence:

For every obervation $i$, assign it to the closest cluster center:
    $$ c^{(i)} := \arg min_{j} \ || x^{(i)} - \mu_j ||^2_2$$
For every cluster $j$, update its value as the mean of assigned observations
    $$ \mu_j := \frac{\sum_{i=1}^m \mathcal{I}\{ c^{(i)} = j\} x^{(i)} }{\sum_{i=1}^m \mathcal{I}\{ c^{(i)} = j\}} $$

An intuitive interpretation of relative speeds
Steps 2 and 3 involve computing the euclidean distance between all points $k$ times before the actual algorithm even starts. It must also calculate the proportional probabilities for each point, and implementations often add an inner loop which performs "trials" and selects the best result. All these steps are performed across the entire dataset, which can be quite slow.
On the other hand, where k-means++ gains in speed is in the convergence of step 6. But that is dependent on the structure of your dataset, not necessarily on its size.
See here for the Sklearn implementation - around lines 100


Recurrence relation with summation and 2 variables

Question: I have a nice looking recurrence relation but i cant figure out the closed form. Any help or tips are much appreciated.
$$
s_{i,k}(n) = \sum_{l=k}^{n} \dfrac{1}{l}s_{i-1,l}(n)
$$
With the base condition that $s_{1,k} = \dfrac{1}{n}$
I already tried splitting the sums to get something going with the harmonic function but it doesn't paid out.
Answer: There is no hope of a closed form.
The values of $s_{1,k}$ are the suffix sums of the $n$ first terms of the ordinary harmonic series (to a factor $1/n$), which does not simplify.
And the values of the $s_{i,k}, i>2$ are even harder.

I guess that you will have asymptotically $s_{i,1}(n)=\dfrac{\log^{i-1}(n)}{ni!}$ (by successive integrations).
Comment: thx a lot, a bit disappointing but thx ^^


The pushout of an open/closed injective map is open/closed

Question: In this question, it is proved that the pushout of an open embedding is still open. I have two question about this:

The given answer is very set-theoretic in spirit – is there a more category-theoretical approach to proving this, rather using universal properties instead of the set realization of pushouts?
Does this statement hold true for closed maps as well?
Comment: A topological embedding is not necessarily open. For example, the inclusion $\mathbb{R}\to\mathbb{C}$ is a topological embedding, but $\mathbb{R}$ is not open in $\mathbb{C}$.
Comment: @V.Semeria Yep. Changed it.
Answer: Ok, after thinking about it for a bit, I found an answer myself:
Say there's a pushout square in $\mathrm{Set}$ or $\mathrm{Top}$:
\begin{align*}
 \require{AMScd}
 \begin{CD}
  T @>{f}>> A\\
  @V{g}VV @VV{α}V \\
  B @>>{β}> X
 \end{CD}
\end{align*}

In $\mathrm{Set}$: If $f$ is injective, then so is $β$:
For any set $C ⊂ B$, by the injectivity of $f$ the set $D = f(g^{-1}(C))$ is disjoint from $f(g^{-1}(B\setminus C))$ and so the indicator maps $1_C \colon B → \{0,1\}$ and $1_D\colon A → \{0,1\}$ satisfy
$$1_C ∘ g = 1_{g^{-1}(C)} = 1_{f^{-1}(D)} = 1_D ∘ f,$$
because $f^{-1}(D) = f^{-1}(f(g^{-1}(C)) = g^{-1}(C)$ by the injectivity of $f$.
Therefore, by the universal property of pushouts there's a $χ \colon X → \{0,1\}$, such that $1_C = χ ∘ β$. Thinking about this for a second, this implies that $β(C)$ must be disjoint from $β(B\setminus C)$. As $C$ has been arbitrarty, this implies $β$ must be injective.
In $\mathrm{Set}$: $E = α^{-1}(β(B)) ⊂ f(T)$:
Use the universal property of pushouts on $1_{f(T)}\colon A → \{0,1\}$ and $1_B \colon B → \{0,1\}$ which obviously agree on $T$ via $f$ and $g$ respectively. Then there's a $χ\colon X → \{0,1\}$ such that $χα = 1_{f(T)}$ and $χβ = 1_B$. Then
$$1_{f(T)}(E) = χα(E) = χα(α^{-1}(β(B))) ⊂ χβ(B) = 1_B(B) = 1,$$ and so $E ⊂ f(T)$.
In $\mathrm{Top}$: If $f$ is injective and open/closed, then so is $β$:
By (1.), $β$ is injective (as pushouts in $\mathrm{Top}$ are automatically pushouts in $\mathrm{Set}$ as well). Let $C ⊂ B$ be open/closed. Then

$β^{-1}(β(C)) = C$, by $β$ being injective, hence is open/closed.
Let $D = α^{-1}(β(C)))$. Then $f^{-1}(D) = g^{-1}(C)$ is open/closed in $T$ and so is $f(f^{-1}(D))$ because $f$ is open/closed. But $f(f^{-1}(D)) = D$, because of (2.).

So yes, the statement generalizes to any property which $f$ preserves under images and preimages and which is characterized at $X$ through the preimages of $α$ and $β$. The reasoning here is a bit more categorical in flavour, but I guess one can use only subobject-classifier-parlance to prove the results as well.


What's the meaning of the separator?

Question: I'm learning the Bach's French suite using this edition. Throughout there is a small separator (small vertical line) and I cannot guess its meaning. It definitely have something to do with this question, but it doesn't explain whole of them, and if it is just a change in a repetitive pattern, not all of them are noted. Here is an example (see the vertical line between the first and the second eighth-note.). Here it is indeed a change in a repetitive pattern.

If it is indeed the meaning, what exactly qualify for a change in a repetitive pattern? Do you use these marking when studying/playing the piece?
Comment: There is a footnote on the first page of the music (page 3) which explains what they mean!
Comment: "Do you use these marking when studying/playing the piece?" No, because they are just the personal view of some editor. Bach didn't write them.
Comment: Oh! Thanks. I guess one should not start directly with the second suite :)
Answer: As  @alephzero commented, the marks are explained at the bottom of the page.  The editor felt the structure of the piece was worth marking out, and he exhorts you to  consider them in your phrasing.
You should consider his opinions, and follow them if you see fit.  They're not stupid opinions.

What's the meaning of the separator?


What's a good transform for decaying function with a plateau

Question: I have a dataset (y vs. t) that I think is best described by:

Slight initial downward slope
At maybe t = 1 or 2, steep downward slope
Asymptote at y = 0

I would like to transform the data so I can build a strong linear regression.
The second portion looks good for exponential decay (use ln(y) as the dependent variable), but how do I combine with the first part?
How should I transform my data before regression?
Images below are intended to respond to commenters' requests
Comment: Your approach appears to be misguided - you're transforming in order to make a regression 'significant' - and you will almost certainly succeed, but the significance will be meaningless. Perhaps you'd be better served by a nonparametric regression approach, perhaps a local polynomial in the logs, or a logspline fit. "I want to confirm my intuition" relates to your preferred outcome, not what the actual point of the activity is. What is $y$ measuring?
Comment: if your data shows a clear pattern, presumably you want a model that fits that shape. Why are you trying to transform first? What is the transformation to achieve?
Comment: With 30,000 data points a very low P-value is not surprising even for a lousy model.
Comment: Glen - Many thanks.  Splitting the model into logit*mean has made the data appear much stronger.  So glad you commented.
Comment: workglide - should I post my comments as an answer? It might help if the question was also modified to more clearly reflect what you needed to know.
Comment: The data is too fuzzy to see clearly with the naked eye. I'd like to use p-values to confirm/refute my intuition. I'm trying to build a transform before I regress that will show good significance (and later work for predictions).
Comment: Agree with @Glen_b. Might be worth taking a look at polynomial distributed lag models. Difficult to tell from the graph if these would be helpful, though.
Comment: To start with, from the look of that data, take logs of both $y$ and $t$ so you can perhaps begin to make out what's going on.
Comment: I won't try guessing a suitable model form from a plot of the raw data. Assuming that all your y values are positive, a plot with a log scale for y seems the second move.
Comment: I believe there's exponential decay, plus the plateau (from domain knowledge, not stats).  ln(y) vs. t (pure exponential decay) gives a model with p-level = 0.00093 (there are many binary variables which improve the model, but they're a distraction here), but I also want to catch the plateau. Please forgive my lack of good statistical vocabulary - I'm more of an engineer.
Comment: Glen - Y is roughly, "how much does someone like a web page?". I expect the data to be pretty flat when extremely fast, but exponential decay past this point (maybe after a second).
Comment: What values can $y$ take? Can it be 0? The ln(y) vs ln(time) plot ... what value is the line of points at the bottom? It looks like maybe you should model the probability of being down there, and the way the mean changes when it isn't there.
Comment: y can be 0+, but I limited to 0.00001 so I could transform. The largest value in this set is 750.
Comment: Just keep in mind that the overall mean is not the same as the mean conditional on not being zero; if you do need the overall mean, you should be able to compute it.
Comment: How do you obtain Y? Is this an objective measure? Is this a survey answer?
Answer: A Gaussian Mixture (1,2,3) might be an acceptable, "textbook", fit for your first plot.
The second plot looks like hyperbolic transformed material.  When I see the second plot I think $ y=\frac {1}{x}$.   Could you try transforming the second using $ y_{2} = \frac{1}{y}$ and show what that graph looks like?
Glens has a good point: If you are trying to do the speaking for the data, you can always accomplish that goal, you can always "win", but it most often causes you to lose.  Be careful to let the data do the talking.
One question behind the question is: what is your motivation.  The human brain is an amazing computer able to find signal when the signal-to-noise ratio is stunningly bad.  We see patterns where they are highly obscured.  The human heart is deceitful above all things - our emotions can mislead us ten thousand times a day.  We see patterns that aren't there and we write them into the data and thereby guarantee that our "solution" doesn't actually work.  Being able to tell the difference between a highly obscured pattern and a pattern that isn't there takes mental clarity of vision into the emotional state.  Hard stuff.  Sorry for the philosophy lesson.
Comment: I appreciate the philosophy and agree. I'm applying domain knowledge, not pattern recognition (looks like a cloud to me). Hoping there's a usable transform to find my answer (your links might be over my head, but will try).
Comment: The motivation: a strong model will help the customer. The plateau is a useful result in itself.
Comment: Added inverse of t per your request (y inverse is too distributed to see anything at all)
Comment: wrong inverse.  Not inverse of "T", inverse of what the y-axis is.
Comment: I tried inverse of y first, but it's impossible to read (most values are around 1 or 10^6).
Comment: Can you supply a 4-plot of the y-data?  http://www.itl.nist.gov/div898/handbook/eda/section3/4plot.htm


How do I compute $\Delta_x\frac{1}{|x-y|}$ when $x$ has arbitrary $n$ components?

Question: How do I compute $\Delta_x\frac{1}{|x|}$ when $x$ has arbitrary $n$ components?
Is there any good way to simply this?
Comment: Is $\Delta_x$ some sort of derivative?
Comment: Where do you see the problem? If you know how to compute derivatives, this is straightforward (away from zero).
Comment: As Michal says, depending on what you want, you can take a deep breath, and just do the calculus... If spherical coordinates are more convenient, you might take a look at 'my' answer https://math.stackexchange.com/questions/2044919/the-laplacian-in-polar-coordinates-using-the-chain-rule/2045926#2045926
Comment: It is a laplacian operator, $\sum_i \partial_{ii}$ where $x=(x_1,\dots,x_n)$
Comment: I'm wondering if I need a case argument in computation... I know this is basic but I somehow get 2 cases because when I differentiate $\frac 1{\sqrt{x-y}}$, with respect to $x_i$, I seem to have absolute value in the numerator, and the second derivative becomes more cumbersome... Given that the expression is very simple, maybe I feel that I'm missing something
Comment: @jk001 in your last comment, aren't you missing some squares? $$|x| = \left (x^2_1 + \cdots + x^2_n\right)^{1/2}.$$
Comment: Ah yes! it should be $|x-y|$ instead of squre. Thanks for pointing out
Answer: This is just an exercise in computing partial derivatives. All you need to know is the chain rule and the product rule. Remember in $\mathbb{R}^n$, $$ \vert x-y \vert = \bigg ( \sum_{k=1}^n (x_k-y_k)^2 \bigg )^{\frac 1 2}$$ where $x = (x_1, \dots , x_n)$ and $y = (y_1, \dots , y_n)$. Fix $y \in \mathbb{R}^n$ and let $$u(x) = \vert x - y \vert^{-1} = \bigg ( \sum_{k=1}^n (x_k-y_k)^2 \bigg )^{-\frac 1 2}.$$ Via the chain rule, \begin{align*}
\frac \partial {\partial x_i} \vert x-y \vert &=\frac 1 2  \bigg ( \sum_{k=1}^n (x_k-y_k)^2 \bigg )^{-\frac 1 2} \cdot 2(x_i-y_i) \\
&= \frac{x_i-y_i}{\vert x-y \vert }.
\end{align*} Hence, $$ \frac{\partial u}{\partial x_i} = - \frac{1}{\vert x-y \vert^2} \cdot \frac \partial {\partial x_i} \vert x-y \vert = - \frac{x_i-y_i}{\vert x -y \vert^3}. $$ Now by the product rule, \begin{align*}
\frac{\partial u}{\partial x_i^2} &= - \frac 1 {\vert x -y \vert^3}+3 \frac{x_i-y_i}{\vert x -y \vert^4}\frac \partial {\partial x_i} \vert x-y \vert \\
&= - \frac 1 {\vert x -y \vert^3}+3 \frac{(x_i-y_i)^2}{\vert x -y \vert^5}.
\end{align*} Finally, \begin{align*}
\Delta u &= \sum_{i=1}^n\frac{\partial u}{\partial x_i^2} \\
&= - \sum_{i=1}^n\frac 1 {\vert x -y \vert^3}+3 \sum_{i=1}^n\frac{(x_i-y_i)^2}{\vert x -y \vert^5} \\
&= -\frac n {\vert x -y \vert^3} +  \frac 3 {\vert x -y \vert^3} \\
&= - \frac {n-3} {\vert x -y \vert^3}.
\end{align*}
Answer: Hint: after making the substitution $\boldsymbol r := \boldsymbol x - \boldsymbol y $, switch to hyperspherical coordinates on $\mathbb R^n\setminus\{0\}$, for example using the following convention:
$$
\begin{split}
r_{1}&=\rho \cos \theta \prod_{j=1}^{n-2} \cos \varphi_{j} \\
r_{2}&=\rho \sin \theta \prod_{j=1}^{n-2} \cos \varphi_{j} \\
r_{k}&=\rho \sin \varphi_{k-2} \prod_{j=k-1}^{n-2} \cos \varphi_{j}, \quad 3 \leq k \leq n,
\end{split}
$$
with $r \in (0,\infty)$, $\theta \in (0,2\pi)$, and $\varphi_j \in (-\pi/2,\pi/2)$. Write the laplacian $\Delta_\boldsymbol r$ in these coordinates, then apply it to the spherically-symmetric function $(r,\theta,\dots)\mapsto 1/r$.


Gradle Plugin is not found

Question: As you can see, the plugin [id: 'org.gradle.toolchains.foojay-resolver-convention', version: '0.4.0'] is not found, and I don't understand why. I am working on this project with other colleagues. The Gradle build works for them. We have analyzed our classes, and they are identical. I don't understand what I'm doing wrong. (https://i.stack.imgur.com/ySIGD.png)
I have cloned the project from the repository several times, but with no success. Furthermore, my colleagues have sent me their project folder, but that doesn't work for me either. Finally, I tried creating a new test project, adding Gradle from IntelliJ right away, and it works in this case.The environment variables appear to be correct.
Comment: Does it work out of IntelliJ?
Answer: Are you sure you have installed Gradle correctly on your machine? Check in the terminal using 'gradle -version
Comment: Yes, I'm. I'm using Gradle 8.3
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).

Gradle Plugin is not found


Submit button not triggering a form submit

Question: I have a strange phenomenon. The code seams to be correct but the submit button is not triggered. dpm says the callback functions are loaded correctly in the $form value like this:

When I pressed one of the buttons nothing happened. I do not get any error message or log entry.
Any solution or ide for debuging?
CODE:
/**
* Implements hook_menu().
*/
function payu_ui_menu() {
  $items = array();
  $items['admin/config/services/payu/merchant'] = array(
    'title' => 'PayU merchant settings',
    'access callback' => 'user_access',
    'access arguments' => array('payu_administer'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('payu_merchant_settings_form'),
     'description' =>  '',
    //'type' => MENU_NORMAL_ITEM,
    'type' => MENU_CALLBACK,
  );
  $items['admin/config/services/payu/merchant/%payu_merchant'] = array(
    'title callback' => 'payu_merchant_edit_form_title',
    'title arguments' => array(5),
    'access callback' => 'user_access',
    'access arguments' => array('payu_administer'),
    'page callback' => 'payu_merchant_edit_form',
    'page arguments' => array(5),
    'description' =>  '',
    //'type' => MENU_VISIBLE_IN_BREADCRUMB,
    'type' => MENU_CALLBACK,
  );
  $items['admin/config/services/payu/merchant/%payu_merchant/delete'] = array(
    'title' => 'Delete',
    'access callback' => 'user_access',
    'access arguments' => array('payu_administer'),
    'page callback' => 'payu_merchant_delete_confirm_form',
    'page arguments' => array(5),
    'description' =>  '',
    'type' => MENU_VISIBLE_IN_BREADCRUMB,
  );
  return $items;
}

...

/**
 * Payu merchant settings form validate.
 */
function payu_merchant_settings_form_validate(&$form, &$form_state) {
  drupal_set_message('Settings validate');
  $form_state['values']['merchant_id'] = trim($form_state['values']['merchant_id']);
  $form_state['values']['secret_key'] = trim($form_state['values']['secret_key']);
  $merchant_id = $form_state['values']['merchant_id'];
  if (substr($merchant_id, 0, 1) === 'P' && !ctype_digit(substr($merchant_id, 1, 6))) {
    form_set_error('merchant_id', t('Merchant ID always start with "P" and 6 digits'));
  }
  elseif (substr($merchant_id, 0, 1) === 'P' && strlen($merchant_id) != 7) {
    form_set_error('merchant_id', t('Merchant ID length is always 7 character!'));
  }
  if (!isset($form['#merchant'])) {
    // new item from "add merchant" form
    $merchant = ($merchant_id);
    if (!empty($merchant)) {
      form_set_error('merchant_id', t('Merchant ID is unique!'));
    }
  }
}

/**
 * Edit merchant settings.
 */
function payu_merchant_edit_form($merchant) {
   $form['#merchant'] = $merchant;
   $form['merchant_id'] = array(
    '#type' => 'textfield',
    '#required' => TRUE,
    '#title' => t('Merchant ID'),
    '#default_value' => $merchant->merchant_id,
    '#value' => $merchant->merchant_id,
    '#size' => 7,
    '#maxlength' => 7,
  );
  $form['secret_key'] = array(
    '#type' => 'textfield',
    '#required' => TRUE,
    '#title' => t('Secret key'),
    '#default_value' => $merchant->secret_key,
    '#value' => $merchant->secret_key,
    '#size' => 32,
    '#maxlength' => 32,
  );
  $form['currency'] = array(
    '#type' => 'select',
    '#required' => TRUE,
    '#title' => t('Currency'),
    '#options' => variable_get('payu_currencies'),
    '#default_value' => $merchant->currency,
    '#value' => $merchant->currency,
  );
  $form['name'] = array(
    '#type' => 'textfield',
    '#required' => FALSE,
    '#title' => t('Merchant name'),
    '#default_value' => $merchant->name,
    '#value' => $merchant->name,
    '#size' => 64,
    '#maxlength' => 64,
  );
  $form['actions'] = array(
    '#type' => 'actions',
    'submit' => array(
      '#type' => 'submit',
      '#value' => t('Save'),
      "#executes_submit_callback" => TRUE,
      '#validate' => array('payu_merchant_settings_form_validate'),
      '#submit' => array('payu_merchant_edit_save_submit'),
    ),
    'delete' => array(
      '#type' => 'submit',
      '#value' => t('Delete'),
      "#executes_submit_callback" => TRUE,
      '#submit' => array('payu_merchant_edit_delete_submit'),
    ),
  );
  return $form;
}

/**
 * Save edited merchant data.
 */
function payu_merchant_edit_save_submit($form, $form_state) {
  drupal_set_message('saving');
  $currencies = variable_get('payu_currencies', array());
  $result = db_merge('payu_merchants')
    ->key(array(
      'merchant_id' => $form_state['values']['merchant_id'],
    ))
    ->fields(array(
      'merchant_id' => $form_state['values']['merchant_id'],
      'secret_key' => $form_state['values']['secret_key'],
      'currency' => $currencies[$form_state['values']['currency']],
      'name' => $form_state['values']['name'],
    ))
    ->execute();
  switch ($result) {
    case MergeQuery::STATUS_INSERT:
      drupal_set_message(t('PayU merchant: %merchant_id added.', array('%merchant_id' => $form_state['values']['merchant_id'])));
      break;

    case MergeQuery::STATUS_UPDATE:
      drupal_set_message(t('PayU merchant: %merchant_id updated.', array('%merchant_id' => $form_state['values']['merchant_id'])));
      break;
  }
  $form_state['redirect'] = array('admin/config/services/payu/merchant');
}

/**
 * Delete merchant: menu callback function.
 */
function payu_merchant_edit_delete_submit(&$form, &$form_state) {
  $merchant = $form['#merchant'];
  $form_state['redirect'] = array('admin/config/services/payu/merchant/' . $merchant->merchant_id . '/delete');
}

/**
 * Delete merchant data: confirm form.
 */
function payu_merchant_delete_confirm_form($merchant) {
  $form['#merchant'] = $merchant;
  dpm($merchant);
  return confirm_form($form, t('Are you sure delete "%merchant_id" merchant?', array('%merchant_id' => $merchant->merchant_id)), 'admin/config/services/payu/merchant');
}

/**
 * Delete merchant data.
 */
function payu_merchant_delete_confirm_form_submit(&$form, &$form_state) {
  $merchant = $form['#merchant'];
  //drupal_set_message($merchant->merchant_id);
  db_delete('payu_merchants')
    ->condition('merchant_id', $merchant->merchant_id)
    ->execute();
  drupal_set_message(t('PayU merchant: %merchant_id deleted.', array('%merchant_id' => $merchant->merchant_id)));
 //$form_state['redirect'] = array('admin/config/services/payu/merchant');
}

Comment: Is there an HTML Element laying over the submit button?
Comment: No nothing. I uploaded a screenshot about the html layout.
I can click on the button but nothing happened.
Answer: You need to update your merchant edit form menu callback to use drupal_get_form, just like your first one. Or have your menu callback properly build the form.
  $items['admin/config/services/payu/merchant/%payu_merchant'] = array(
    'title callback' => 'payu_merchant_edit_form_title',
    'title arguments' => array(5),
    'access callback' => 'user_access',
    'access arguments' => array('payu_administer'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('payu_merchant_edit_form', 5),
    'description' =>  '',
    //'type' => MENU_VISIBLE_IN_BREADCRUMB,
    'type' => MENU_CALLBACK,
  );

Drupal is properly rendering your Form API array because it's a render array. However, it is not attaching regular form interaction because it was not built properly.
EDIT: You need to update your form function, as well, for the new parameters.
/**
 * Edit merchant settings.
 */
function payu_merchant_edit_form($form, &$form_state, $merchant) {
...
}

Comment: Thanks Matt, it solve the problem of submit function, but with this solution page argument 5 $merchant is empty. The title callback get the right $merchant value.
Comment: I forgot to highlight you need to alter the form function. I've added that to answer. See the $form, $form_state parameters that needed to be added.


diminuição de código

Question: Tem algum outro jeito em realizar esse código?
Esse código está muito repetitivo, queria saber se é possível diminuir e deixar mais fácil o entendimento.
if (games.getBallId() == btnBal0l.getId()){
    btnBal0l.setBackgroundResource(R.mipmap.ball_verde);
}else if (games.getBallId() == btnBal02.getId()){
    btnBal02.setBackgroundResource(R.mipmap.ball_verde);
}else if (games.getBallId() == btnBal03.getId()){
    btnBal03.setBackgroundResource(R.mipmap.ball_verde);
}else if (games.getBallId() == btnBal04.getId()){
    btnBal04.setBackgroundResource(R.mipmap.ball_verde);
}else if (games.getBallId() == btnBal05.getId()){
    btnBal05.setBackgroundResource(R.mipmap.ball_verde);
}else if (games.getBallId() == btnBal06.getId()){
    btnBal06.setBackgroundResource(R.mipmap.ball_verde);
}else if (games.getBallId() == btnBal07.getId()){
    btnBal07.setBackgroundResource(R.mipmap.ball_verde);
}

Comment: Dá pra melhorar com `switch { case:  }`, mas ficaria maior
Answer:
Esta é uma resposta baseada em opiniões! Existem várias formas de realizar a mesma operação. Aqui apresento apenas uma, baseada no meu ponto de vista!

Acredito que existe uma forma de deixar mais legível.
Para isso, podemos quebrar as funcionaidades:

Selecionar um Button através de um Id
Setar o background em um Button

Sugiro que adicone os 7 botões em uma lista, logo após criá los!
Exemplo:
private List<Button> buttons = new ArrayList<>(0);
buttons.add(btnBal0l);

Ao invés de manter uma referência na classe, e outro na lista, pode se criar diretamente na lista :
buttons.add(Button.class.cast(findViewById(R.id.btnBal01));

Para podermos pegar o Button através do Id da lista, vamos criar um método:
private Button getButtonById(int id){
    for(final Button b : buttons){
       if(id == b.getId()){
           return b;
     }
   }
  return null;
}

Agora vamos setar o resource no Button:
 private void setImageInButton(int gameId){
        final Button b = getButtonById(gameId);
        if( b != null){
            b.setBackgroundResource(R.mipmap.ball_verde);
        }
    }

Agora você pode chamar a funcção da seguinte forma:
setImageInButton( games.getBallId() );

Segue o código completo e comentado:
 /**
     * Vamos armazenar em uma lista, todos os botões...
     */
    private List<Button> buttons = new ArrayList<>(0);

    /**
     * verifica se o Button com o mesmo id está na lista
     * O retorna, caso exista, senão retorna null.
     * @param id
     * @return
     */
    private Button getButtonById(int id){
        for(final Button b : buttons){
            if(id == b.getId()){
                return b;
            }
        }
        return null;
    }

    /**
     * Através de um id, seleciona o Button e adiciona a imagem caso não seja nulo!
     * @param gameId
     */
    private void setImageInButton(int gameId){
        final Button b = getButtonById(gameId);
        if( b != null){
            b.setBackgroundResource(R.mipmap.ic_gps_action);
        }
    }

Answer: Se todos esses botões estiverem dentro de um mesmo layout, pode usar o método findViewById() da classe view(esse layout).
int id = games.getBallId();
Button button = (Button)layout.findViewById(id);
button.setBackgroundResource(R.mipmap.ball_verde);

Comment: Muito bom! +1...

diminuição de código


Elasticsearch - Query by parent id

Question: I have three document types with the following mappings with Parent/Child relationships. I have omitted other properties as I thought they are not relevant to the question.
   "mappings": {
     "Parent": {
        },
     "Child": {
        "_parent": {
           "type": "Parent"
        },
        "_routing": {
           "required": true
        }
     },
     "GrandChild": {
        "_parent": {
           "type": "Child"
        },
        "_routing": {
           "required": true
        }
     }
  }

I'm using java api to insert documents to the index. Before indexing a document, existing  documents with the same ids needs to removed to avoid duplicates. Parent's Id and Child's Id are stored externally. First all "GrandChild" documents are deleted using a term query on its parent id (which is an id of type "Child" in this case). There are no errors but the "GrandChild" docs are not getting deleted.
By running the following term query using the chrome plugin Sense, I found out that the problem is in the term query. It doesn't return hits. Parent, Child and GrandChild have the same routing value which is set to the id of Parent. This is the query I tried.
POST /myindex/GrandChild/_search?routing=DFC0E8CD59EBC00EC2DDC9A0FF5D1F2DB272B2449680824CCE60B6864568D498
{
    "query" : {
        "term" : { "_parent" : "//id/of/doc/of/type/Child" }
    }
}

When I try to search for a "Child" document using its parent id, it works. I get a "Child" using the following query.
POST /myindex/Child/_search?routing=DFC0E8CD59EBC00EC2DDC9A0FF5D1F2DB272B2449680824CCE60B6864568D498
{
    "query" : {
        "term" : { "_parent" : "DFC0E8CD59EBC00EC2DDC9A0FF5D1F2DB272B2449680824CCE60B6864568D498" }
    }
}

What could I be doing wrong in the "GrandChild" search?
Any help is appreciated. Thanks.
Answer: Got an answer for the question from elasticsearch mailing list
https://groups.google.com/forum/#!topic/elasticsearch/d_aZejNMBD8
There is an open issue for this here:
https://github.com/elasticsearch/elasticsearch/issues/5399
Edit :
As shown in the Github issue the way to perform your query is to prefix the ID by the parent type :
POST /myindex/GrandChild/_search?routing=DFC0E8CD59EBC00EC2DDC9A0FF5D1F2DB272B2449680824CCE60B6864568D498
{
    "query" : {
        "term" : { "_parent" : "Child#//id/of/doc/of/type/Child" }
    }
}

Comment: this not working in elasticsearch 5+
you need to use https://www.elastic.co/guide/en/elasticsearch/reference/master/query-dsl-parent-id-query.html

Elasticsearch - Query by parent id


Big $O$ small $o$ notation True or False

Question: I'm stuck on a few big-$O$ and small $o$ notation True or False questions, any insight would be appreciated.
$4n^3+6n+17=O(n^4)$ True. The degree of complexity is directly related to n, but it is not represented there. The function grows much faster (left side is like n^2, since it grows faster).
$4n^3+6n+17=O(n^2)$ I think this is false, but no idea why
$n^{17}=o(2^n)$ True. if n^17 increase by 1, an increase is no more n^18, whereas if 2^n increase by 1, an incease is double: 2^n+1. Somewhere 2^n begans to grow faster, because small o notion includes funkction, that grows only slower like in this case.
$5^n=o(3^n)$
       False. if lim n->inf (5^n / 3^n) = 0. Since(5^n / 3^n) = (5/3)^n and since for any 0 <= x < 1, lim n->inf (x^n) = 0, is false 5^n = o(3^n).
Is here anything correct?
Comment: First of all you have to show us what you have tried. Do you have any opinion at all on the truth or falsity of these statements?
Comment: Also, you can gain a lot of intuition by knowing what the definitions of O and o are. Do you know these?
Answer: [When using this notation, it is important to specify which limit you are thinking about. I assume from your attempted solutions that you mean $n\to\infty$.]
You have got the correct answers. For the second one, you're right that it is false. How can you prove it? Suppose it's true. $$4n^3+6n+17=O(n^2)$$ Then $\exists M$ such that for sufficiently large $n$, $$4n^3+6n+17\le Mn^2\\4n+\frac6n+\frac{17}{n^2}\le M$$ Clearly LHS grows unboundedly, so this is not true.
Comment: @Naji yes that's correct. But $o(f(n))\implies O(f(n))$, so either one is correct.
Comment: For the first case, wouldn't it imply that it would be equal to $\mathcal{o} (n^4)$ as opposed to $\mathcal{O}(n^4)$ as $n\rightarrow\infty$?
Answer: Think again for the first case. $4n^3+6n+17 = \mathcal{O}(n^4)$ implies that
$$
4n^3+6n+17 \leq C n^4
$$
for some real number $C$. Divide both sides by $n^4$:
$$
\frac{4}{n}+\frac{6}{n^3}+\frac{17}{n^4} \leq C
$$
You will notice that as $n$ approaches $0$, the left hand side shoots off to $\infty$, and therefore cannot be bounded by a real number $C$.
Hint for the second case:
Take the same approach as above and then take $n = C$. You will see that the left hand side can be greater than the right hand side, rendering the inequality to be false.
Comment: Wait why did you take $n\to0$? By the notation, I assumed $n\in\Bbb N$, and so the limit was $n\to\infty$. Admittedly, it could be clearer.
Comment: I see, thank you for clarifying - I was under the impression that a limit to any number can be taken


How much sub-questions impact one ordinal question in a survey?

Question: I have a variable Net Promoter Score (NPS) which is an item on a survey, the answer format is ordinal, 0 to 10.
Then, there are sub-questions on the same survey, some are ordinal, some are categorical.
I would like to determine which sub-question or which group of sub-questions are the best predictors of NPS. The goal is to be able to prioritize which area(s) to focus on in order to improve NPS over time.
What would be some appropriate methods to identify and verify such a relationship?
Answer: I love your question, and I'm going to answer it a little more broadly then you asked. There are four main approaches that I would use to identify opportunities to improve Net Promoter Score, in order of analytical sophistication and the maturity of the project you're using NPS to evaluate. (For those not familiar, Net Promoter is a common satisfaction score methodology used by many companies. Unless you tend to avoid surveys, you have probably answered the "net promoter" question many times.)

Segmentation
Qualitative evaluation of open-ended responses
Quantitative evaluation of open-ended responses
Experimentation

Segmentation: A business can usually divide its customers into a small number of groups along a couple of key dimensions. For example, between "new" and "returning" customers, or "enterprise" and "small business". These will often closely align with the distinctions made in pricing and in the businesses financial reporting, and, happily, they often have dramatically different NP scores. The differences can sometimes surprise. The great thing about this approach is that it requires very little communications overhead. Most people listening to your data will already be familiar with the segments you describe and can envision the aspects of the product that could drive some groups to be more or less satisfied than others. It also makes it relatively easy to organize followup work and report on subsequent improvements.
Qualitative evaluation of open-ends: A common component of Net Promoter implementations is a followup question along the lines of "why did you answer the way that you did". Often, for a project new to Net Promoter, simply reading these responses and associating them with their ordinal responses will have people slapping their foreheads. "I thought our customers liked that feature!" "People love the rubberized grips - let's put them on everything!" This approach often peters out fairly soon, as a business identifies all the surface-level opportunities and makes strategic decisions to resolve or not resolve them.
Quantitative evaluation of open-ends: Following up on the qualitative evaluation, quantitative evaluation can yield some additional surprises. This approach would generally be to label each open-ended response with one or more categories, which can be done by hand at small scales, or using a variety of software at larger scales. This can reveal additional insights along the lines of "I knew that was an issue... but I didn't realize it affected 30% of our customers!" or "Most people who complain about xyz also complain about abc - maybe there is a common root cause"
Experimentation: It's often difficult to perform rigorous controlled-variable random-assignment experiments with Net Promoter. Because Net Promoter is intended to be a very holistic measure of the relationship between a company and its customers, companies are usually limited in their ability to experiment with the entirety of the relationship, due to the expense and risk of maintaining what might amount to two separate businesses at the same time. That said, other less rigorous forms of experiments are possible.

Every major decision the business makes can be evaluated for its potential to impact NPS, and then the resulting changes can be subsequently measured. Because it fails to isolate a single variable at a time, care must be taken to build realistic predictions and also to be very cautious about results that were not predicted in advance.
Sometimes we are lucky enough that natural experimental groups emerge that allow us to experiment with the past. A national retailer may roll out a new store format only on the west coast due to the logistical constraints of construction, or a content company may need to censor some types of searches in countries where the local regulations are different. It's not random assignment, but sometimes it's close.

Prediction: I know that I didn't address your real question about using other questions in surveys to "predict" NPS, and that's intentional. The approach that you describe has certain limitations and although I'm planning to try it again myself in the near future, I've had limited success with it in the past.
There are two main predictor approaches I've seen: correlation, and logit regression. Correlation looks at the strength of the relationship between two variables (do they always go up and down together? opposite? no relation?) The idea would be to find the variables most strongly correlated with NPS. Logit regression is a technique that takes all the variables you give it and uses them to try to predict the probability of a particular outcome. For example, you can try to predict the probability of each of your three NPS outcomes (Promoter, Neutral, Detractor). From this you can build a model that shows how much variation in different variables can affect NPS up or down, taking the NPS outcome with the highest predicted probability as the definitive outcome. I have also heard of people using Structural Equation Modelling with NPS, although I know little of this approach.
Some limitations of the predictor approach

Few good independent variables in surveys: In order to be actionable, this approach requires that you think of NPS as a dependent variables and treat other questions as independent. But, even many of the "hard facts" type questions, such as you might use for your key customer segments are not truly independent from NPS. A returning customer is a returning customer in part because they had a positive experience in the past.  Most customer satisfaction questions move together in lockstep, unless you have an offering with very distinctive and low-interacting components that can be performing at two different levels of service (a leisure hotel may try to break into the conference business and do so very poorly at first, in which case separate satisfaction questions on bedroom quality and conference room quality may be useful).
Difficulty communicating: This analytical approach is usually quite far separated from the group that will be implementing recommendations. Because it relies on relatively sophisticated analysis, it's often difficult for implementors to take actions based on these sort of recommendations, because they don't understand what needs to be fixed.
Answer: The NPS works well as a performance monitoring or controlling tool. But what you want to find out is something else: You want to identify the true drivers of satisfaction.
The NPS is an aggregate score. If you want to say something about drivers of satisfaction, than you have to develop a model which explains the 10-point-scale "ultimate question".
However, rating scales are contaminated with scale usage heterogeneity (see paper). If you run a regression model, you will find that those sub-questions are highly correlated, causing high VIFs and maybe no significant betas, depending on how many sub-questions you have. You might also be overconfident in the significance of sub-questions, depending on the exact model set-up.
Consider this simple R script:
nobs=1000
p=12
means = rnorm(nobs)
vars = 1/rgamma(nobs,3,3)
data=matrix(,nobs,p)
for(i in 1:nobs){
data[i,]=rnorm(p,means[i],sqrt(vars[i]))
}
cor(data)

Despite the fact that there is no relationship between the 12 variables, the correlations are far from being 0.
If you further reduce the scale level (Promotor yes/no), you throw away information.
However, scale-adjusting models are very challenging, especially when you have ordinal and categorical variables, and if you look for a ready-made solution.
You could treat bottom, middle and top box as categorical outcomes and use a Bayesian Network to model the relationships. BNs treat everything categorical, thus providing a nice general purpose tool.
Have you considered a conjoint experiment? Depending on the service or product this is a nice alternative.
Answer: Some good answers already here.  Here is a much simpler one, which is really an addition to the good answers you have received, not a substitute.  Ordered logistic regression is the appropriate tool for modelling an ordinal response variable.  There is an implementation - polr() - in Benables & Ripley's library(MASS) in R.
Then you are back in the standard world of model selection, on which there are many good questions and good answers on Cross-Validated.
Comment: Right, this probably the most straightforward approach. The categorical variables would need to be dummied up somehow, which is also easy.


C# - Como abrir o Form2 sem perder as informações da TextBox que está no Form1 e vice versa?

Question: namespace TesteAbertura
{
    public partial class FormularioTeste : Form
    {
        public FormularioTeste()
        {
            InitializeComponent();

        }

        private void button1_Click(object sender, EventArgs e)
        {

            panel1.Controls.Clear();
            Form1 f = new Form1();
            f.TopLevel = false;
            panel1.Controls.Add(f);
            f.Show();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            panel1.Controls.Clear();
            Form2 f = new Form2();
            f.TopLevel = false;
            panel1.Controls.Add(f);
            f.Show();

        }

Comment: Não entendi ...?
Comment: Em cada um dos formulários tem uma caixa de texto que digito algo, quando clico no botão para mudar para o Form2 o que foi digitado na caixa de texto do Form1 desaparece, eu quero que permaneça o que foi digitado nas caixas de texto de ambos formulários.
Comment: Não é só tirar  esse `panel1.Controls.Clear()`?
Comment: Linq tirar panel1.Controls.Clear() não resolve.
Answer: Você pode criar uma variável e receber esses dados no formulário 2, e quando voltar você preenche novamente.
Por exemplo :
public Form2(string texto)
{
//.......
}
E quando voltar para o outro form você devolve o que estava escrito.
Comment: David Pereira obrigado pela sua resposta, quero lhe dizer que sou novato na programação e estudo por hobby, peço por gentileza poderia deixar a sua resposta ainda mais clara para que eu possa compreender melhor e conseguir incluir o seu exemplo no código.
Answer: Ao chamar:
Form1 f = new Form1();

Você está criando um novo objeto do tipo Form1, se toda vez que clica no botão, cria um novo, ele com certeza perderá a informação no textbox.
Você pode colocar a definição dos forms no form principal, e mostrá-los quando for necessário, assim reterá a informação nos controles:
namespace TesteAbertura
{
    public partial class FormularioTeste : Form
    {
        // Definição no escopo da classe
        Form1 f1 = new Form1();
        Form2 f2 = new Form2();

        public FormularioTeste()
        {
            InitializeComponent();

        }

        private void button1_Click(object sender, EventArgs e)
        {
            panel1.Controls.Clear();
            f1.TopLevel = false;
            panel1.Controls.Add(f1);
            f1.Show();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            panel1.Controls.Clear();
            f2.TopLevel = false;
            panel1.Controls.Add(f2);
            f2.Show();
        }
}

Porém, se você fechar o Form, o GC vai coletá-lo mesmo assim (o form será descartado), será necessário cancelar o evento de fechamento:
private void Form2_FormClosing(object sender, FormClosingEventArgs e)
{
    e.Cancel = true;
    Hide();
}

Normalmente não se usa Form dentro de um Panel, Forms são abstrações de janelas, mas nada te impede (fiquei abismado que isso funciona), o mais adequado para seu caso é utilizar UserControl ou até mesmo dois paineis alternando sua visibilidade.
Comment: Edney muito obrigado por solucionar esse meu problema, funcionou perfeitamente, agora as informações não desaparecem mais. Como disse mais acima para o David Pereira eu sou novato na programação e busco sempre aprender e tentar compreender a linguagem C#. Que você e a todos que tentaram solucionar esse problema tenham uma ótima semana.


Json Format Date

Question: I encounter a problem where I could not get the  new Date()  because the  date it's in JSON format. This code is done using MVC C#.
The  date is in  \/Date(1531364413000)\/.
The date in the database is in yy-mm-dd
Can I change the format in the controller or in the web config?
Anybody knows how do I change the default date into JavaScript format?
Comment: Like https://stackoverflow.com/questions/18820896/convert-datetime-to-json-datetime or https://stackoverflow.com/questions/11757757/json-datetime-issue ?
Comment: There is no "JSON format". You can specify a pattern or format in your schema to validate against though.
Comment: nope. I want to make the Javascript date format default. I'm using Model-View-Controller
Comment: What do you consider the "date format default"?
Comment: so that it will be able to change it automatically without adding  a class to it
Comment: What do you call "JavaScript format"? The value can be converted to an ECMAScript date usng `new Date(1531364413000)`, though you must ensure you convert it to number first. You can use various methods to extract the time value from the string.
Answer: You can create helper javascript function like this
function (date) {
     if (!date)
          return "";
     var dtStart = new Date(parseInt(date.substr(6)));
     var dtStartWrapper = moment(dtStart);
     return dtStartWrapper.format('DD/MM/YYYY');
}

It uses Moment Js

Json Format Date


Drupal 8: How to properly add a settings widget to a node add/edit form and save the value?

Question: So I reviewed the code in the core book, menu_ui, and path modules, and they all seem to handle adding a settings widget in a vertical tab differently.
The book module uses a method called addFormElement(), which is called within a hook_form_BASE_FORM_ID_alter() hook.
The menu_ui module is similar, but uses hook_form_BASE_FORM_ID_alter() directly.
Path seems to use a method called formElement(), and I'm not even sure where/how this method is used at the moment.
The real question I have is, how does one actually process the form setting and save it to the database? I have tried to find an example, but I'm at a loss.
Is there a help page with examples like the ones I found for adding an admin settings page?
If not, is there a recommended approach to displaying/saving a value in a vertical tab on a node add/edit form?
Answer: I'm going to take a stab and show how I solved it, but I'm still curious to know if there's a better way.
In a nutshell, I used hook_form_BASE_FORM_ID_alter(), hook_node_submit(), and hook_ENTITY_TYPE_insert() or hook_ENTITY_TYPE_update() in the .module file.
Then I have a class called HierarchyManager that does all the heavy lifting that the D7 .module and .inc files used to do. It's listed as a service named "nodehierarchy.manager".
Lastly, I have a class called HierarchyOutlineStorage that handles the database inserts and updates. Quite a bit of that code was copied directly from D7.
In my .module file:
/**
 * Implements hook_form_BASE_FORM_ID_alter() for node_form().
 *
 * Adds the hierarchy form element to the node form.
 */
function nodehierarchy_form_node_form_alter(&$form, FormStateInterface $form_state, $form_id) {

  // Load the node object associated with this form
  $node = $form_state->getFormObject()->getEntity();
  $account = \Drupal::currentUser();

  // Optional but keeps the .module code cleaner IMO
  $hierarchy_manager = \Drupal::service('nodehierarchy.manager');

  // Do your permission checks here
  $has_permission = ...;
  if($has_permission) {
    $form = $hierarchy_manager->addHierarchyFormElement($form, $form_state, $node, $account, $collapsed);
  }
}

/**
 * Implements hook_node_submit().
 */
function nodehierarchy_node_submit(NodeInterface $node, $form, FormStateInterface $form_state) {
  // Here the node object gets updated with the form value to be used later
  // If you aren't sure about the $form_state, download/enable devel and add
  // dsm($form_state->getValues()) to show all available values
  if (!$form_state->isValueEmpty('nodehierarchy_parents')) {
    $node->nodehierarchy_parents = $form_state->getValue('nodehierarchy_parents');
  }
}

/**
 * Implements hook_ENTITY_TYPE_insert() for node entities.
 *
 * Save the form settings
 */
function nodehierarchy_node_insert(NodeInterface $node) {
  $hierarchy_manager = \Drupal::service('nodehierarchy.manager');
  $has_permission = ...
  if ($has_permisson) {
    $hierarchy_manager->hierarchySaveNode($node);
  }
}

/**
 * Implements hook_ENTITY_TYPE_update().
 */
function nodehierarchy_node_update(EntityInterface $node) {
  $hierarchy_manager = \Drupal::service('nodehierarchy.manager');
  $hierarchy_manager->hierarchySaveNode($node);
}

In the HierarchyManager.php file:
public function addHierarchyFormElement(array $form, FormStateInterface $form_state, NodeInterface $node, AccountInterface $account, $collapsed = TRUE) {
  // Insert $form array here
  $form['hierarchy'] = array(...);
}

public function hierarchySaveNode(&$node) {
  // Do all your processing here, then insert or update dB record
  $isNew = ...
  if ($isNew) {
    return $this->hierarchyOutlineStorage->insert($item);
  }
  else {
    return $this->hierarchyOutlineStorage->update($item->hid, $item);
  }
}


How to implement template file that would reside in database?

Question: I was wondering if it would be possible to have a template "file" that would be stored only in DB and would not exist physically?
Twig tempaltes are parsed from files only once and they are processed and stored in DB anyway so would it be possible to have such DB entry from the get-go?
Comment: Since the processed files are already stored in the database, what is the point to store a template file in the database? Drupal 8 is going in the direction opposite with the configuration data because a database cannot be versioned.
Comment: I have case where this would be a good solution but it interests me more out of a curiosity than necessity.
Comment: Where did you get the idea that twig templates are stored in the DB? They are not. They're stored as php files in the php storage.
Comment: I am not saying they are stored in DB, I am saying they are cached in DB so the files are not touched after that.
Comment: No, they are not. As I said, they're cached as PHP files in php storage.
Comment: OK, and so would it be possible to "inject" via some hook a "fake" template into the template discovery process?
Answer: You can register a loader, see Drupal\Core\Template\Loader for the implementations that drupal core uses and their parent classes/interfaces.
See also how they're registered in core.services.yml, for example:
twig.loader.filesystem:
    class: Drupal\Core\Template\Loader\FilesystemLoader
    arguments: ['@app.root', '@module_handler', '@theme_handler']
    tags:
      - { name: twig.loader, priority: 100 }

So, it's certainly possible to do it, if it's a good idea is another question ;)
Answer: Based on @Berdir suggestion I have created my implementation like this(just finished so probably som fine-tuning will take place):
/**
 * Twig loader that uses the database as backend for templates.
 */
class DatabaseLoader implements \Twig_LoaderInterface {

  /**
   * The name of the template collection in the backend storage.
   */
  CONST COLLECTION = 'twig_templates';

  /**
   * The key value backend service.
   *
   * @var \Drupal\Core\KeyValueStore\KeyValueStoreInterface
   */
  protected $key_value;

  /**
   * The list of all templates stored in the database backend
   * for the currently active theme. Each key is the template name
   * and each value is the UNIX timestamp of last change made to the template.
   *
   * @var array
   */
  protected static $registry = NULL;

  /**
   * Static cache for loaded templates keyed by their name.
   *
   * @var array
   */
  protected static $templates = [];

  /**
   * Constructs a new DatabaseLoader object.
   *
   * @param \Drupal\Core\KeyValueStore\KeyValueFactoryInterface $key_value
   *   The key_value storage backend service.
   * @param \Drupal\Core\Extension\ThemeHandlerInterface $theme_handler
   *   The theme handler service.
   */
  public function __construct(KeyValueFactoryInterface $key_value, ThemeHandlerInterface $theme_handler) {
    $this->key_value = $key_value->get(static::COLLECTION);
    $this->theme = $theme_handler->getDefault();
    $this->registryLoad();
  }

  /**
   * Helper method to load the registry from the storage.
   */
  protected function registryLoad() {
    if (is_null(static::$registry)) {
      static::$registry = $this->key_value->get('registry_' . $this->theme, []);
    }
  }

  /**
   * Helper method to write registry into the storage.
   */
  protected function registryUpdate() {
    $this->key_value->set('registry_' . $this->theme, static::$registry);
  }

  /**
   * Helper method to flush the registry.
   * This method is called when the site cache is being flushed
   * and it will set timestamps for all templates to current time
   * so all templates will indicate they need to be rebuilt.
   *
   * @see foo_rebuild()
   */
  public function registryRebuild() {
    static::$registry = array_fill_keys(array_keys(static::$registry), REQUEST_TIME);
    $this->registryUpdate();
  }

  /**
   * Helper method to normalize the template name.
   * For example "profiles/foo/themes/bar/templates/system/html.html.twig"
   * will get transformed into "html".
   *
   * @param string $name
   *   The full template name.
   *
   * @return string
   *   Normalized template name.
   *
   * @throws \Twig_Error_Loader
   *   If inline template is provided.
   */
  public function normalize($name) {
    if (stripos($name, '{') !== FALSE) {
      throw new \Twig_Error_Loader(sprintf('Template "%s" is not defined.', $name));
    }

    $split = explode('/', $name);
    return explode('.', end($split))[0];
  }

  /**
   * Helper method to get the storage key for provided template.
   *
   * @param string $name
   *   The template name.
   *
   * @return string
   *   The key-value storage collection key for the provided template.
   */
  protected function getKey($name) {
    return $this->theme . '.' . $name;
  }

  /**
   * Upserts a template into the storage.
   *
   * @param string $name
   *   The template name.
   * @param string $template
   *   The content of the template.
   */
  public function saveTemplate($name, $template) {
    $this->key_value->set($this->getKey($name), $template);
    static::$templates[$name] = $template;

    static::$registry[$name] = time();
    $this->registryUpdate();
  }

  /**
   * Deletes provided template.
   *
   * @param string $name
   *   Template name.
   */
  public function deleteTemplate($name) {
    if (isset(static::$registry[$name])) {
      $this->key_value->delete($this->getKey($name));
      unset(static::$templates[$name]);

      unset(static::$registry[$name]);
      $this->registryUpdate();
    }
  }

  /**
   * {@inheritdoc}
   */
  public function getSource($name) {
    $name = $this->normalize($name);

    if (isset(static::$registry[$name])) {
      if (!isset(static::$templates[$name])) {
        static::$templates[$name] = $this->key_value->get($this->getKey($name), '');
      }
      return static::$templates[$name];
    } else {
      throw new \Twig_Error_Loader(sprintf('Template "%s" is not defined.', $name));
    }
  }

  /**
   * {@inheritdoc}
   */
  public function getCacheKey($name) {
    $name = $this->normalize($name);

    if (isset(static::$registry[$name])) {
      return $name;
    } else {
      throw new \Twig_Error_Loader(sprintf('Template "%s" is not defined.', $name));
    }
  }

  /**
   * {@inheritdoc}
   */
  public function isFresh($name, $time) {
    $name = $this->normalize($name);

    if (isset(static::$registry[$name])) {
      return static::$registry[$name] <= $time;
    } else {
      throw new \Twig_Error_Loader(sprintf('Template "%s" is not defined.', $name));
    }
  }

}

The service:
foo_twig_db_loader:
    class: Drupal\foo\Template\Loader\DatabaseLoader
    arguments: ['@keyvalue', '@theme_handler']
    tags:
      - { name: twig.loader, priority: 101 }

The module file:
/**
 * Implements hook_rebuild().
 */
function foo_rebuild() {
  \Drupal::service('foo_twig_db_loader')->registryRebuild();
}

Comment: https://github.com/Merqio/TwigDbLoader


Is it possible to flash IPMI controller firmware from remote?

Question: I just wondered if someone could install malicious firmware from remote on IPMI controllers (similar to a rootkit)? Is something like that possible? I though about installing a keylogger sending summaries over SNMP. I know normally IPMIs are in different subnets, protected by passwords,.. but commit that the attacker has knowledge to overcome those barriers.
Answer: At last Defcon, Jonathan Brossard gave a talk regarding hardware backdooring, and how it is possible to install a rootkit into a bios or a NIC rom (remotely).
They were also able to reverse engineer the kon-boot payload and include it in their malware.
The slides can be found here, and the article is here.
So yes, I'd say it's possible to get access to IPMI and maybe install a rootkit on it...


How to enable block programmatically

Question: I need to enable block from my custom module, to show block when the module is enabled, I set the status 1, but nothing happens until I manually change in Structure > Blocks .
function test_block_info() {
   $blocks['my-block-id'] = array(
    'info'   => t('My block'),
    'status' => 1,
    'region' => 'sidebar_first',
    'cache'  => DRUPAL_NO_CACHE,
      );
    return $blocks;
 }

Comment: Best way would be to add your elements using `hook_page_alter()`
Answer: For drupal 7 the best way will be write hook_enable function in *.install file of your custom module:
<?php

function YOUR_MODULE_NAME_enable() {
          $blocks = array(
            array(
              'status' => 1,
              'weight' => 20,
              'region' => 'sidebar_second',
              'visibility' => 1,
              'pages' => "instruments/*",
              'module' => 'instruments',
              'delta' => 'instruments_sidebar',
              'theme' => 'markets',
            ),
            array(
              'status' => 1,
              'weight' => 19,
              'region' => 'sidebar_second',
              'visibility' => 1,
              'pages' => "instruments/*\n<front>",
              'module' => 'instruments',
              'delta' => 'instruments_search',
              'theme' => 'markets',
            )
          );

          foreach($blocks as $block){
            db_merge('block')
              ->key(array(
                'module'=>$block['module'],
                'delta'=> $block['delta'],
                'theme'=> $block['theme']
              ))
              ->fields(array(
                'status' => $block['status'],
                'weight' => $block['weight'],
                'region' => $block['region'],
                'visibility' => $block['visibility'],
                'pages' => $block['pages'],
              ))
              ->execute();
          }
    }

This is code from my custom module, and it works :)
Here I enable my custom blocks, so I modify 'block' table. For custom blocks you should update 'block_custom' table too.
If you don't know how drupal store settings, just make changes manually and then check DB.
NOTE: db_merge function is very useful - it inserts data if they absent (if you just installed your module) or updates it (if you disabled and then enabled module)
Answer: you also can utilize Context API. Below is what I did to enable/place a block programmatically.
function MYMODULE_context_load_alter(&$context) {

  $your_custom_requirement = ... Whatever you define ...;

  if ($your_custom_requirement === TRUE) {

    $context['reactions']['block']['blocks']['block-machine-name-here'] = array(
      'module' => 'module_that_defined_the_block',
      'delta'  => 'block_delta_name',
      'region' => 'sidebar_first', // place to sidebar
      'weight' => '-10', // block weight in the region
    );
  }

}

Answer: You have to update database table block like Drupal core does:
  db_update('block')
    ->fields(array(
      'status' => $block['status'],
      'weight' => $block['weight'],
      'region' => $block['region'],
    ))
    ->condition('module', $block['module'])
    ->condition('delta', $block['delta'])
    ->condition('theme', $block['theme'])
    ->execute();
  // Flush cache
  cache_clear_all();

I didn't test it. Maybe you also need to flush block cache before query.
Comment: Nice, i looked around for this so long! For me the only function which could activate a custom block in a custom region, but is there a little fault in your script?  'status' => $block['status'], should be 'status' => 'your_custom_block_status', and the same with other lines.
Answer: You just have to additionally call hook_block_info_alter() like in the following example. Don't know why. Seems the block needs to be registered first with hook_block_info(). And only after that you can alter its settings to enable and place it programmatically. Please feel free to add any better explanation to this answer in the comments.
The downside of this approach is, that this block ain't configurable through the back-end. I mean, indeed it is, but the new values always will always get overridden by the code below.
/**
 * Implements hook_block_info().
 */
function mymodule_block_info() {
    $blocks['mymodule_block'] = array(
        'info' => t('A Super Duper Custom Block (ASDCB)'),
        'cache' => DRUPAL_CACHE_PER_ROLE,
    );
    return $blocks;
}
/**
 * Implements hook_block_info_alter().
 */
function mymodule_block_info_alter(&$blocks, $theme, $code_blocks) {
    if (!path_is_admin(current_path())) {
        if (isset($blocks['mymodule']['mymodule_block'])) {
            $blocks['mymodule']['mymodule_block']['status'] = 1;
            $blocks['mymodule']['mymodule_block']['region'] = 'Header';
            $blocks['mymodule']['mymodule_block']['weight'] = 2;
            $blocks['mymodule']['mymodule_block']['visibility'] = BLOCK_VISIBILITY_LISTED;
            $blocks['mymodule']['mymodule_block']['pages'] = '<front>';
        }
    }
}
/**
 * Implements hook_block_view().
 */
function mymodule_block_view($delta = '') {
    $block['subject'] = t('ASCDB');
    $block['content'] = _mymodule_block_content();
    return $block;
}

function _mymodule_block_content() {
    return t('Hello World');
}

Answer: Managing blocks through code can be very valuable, especially if you are running clean deployments of just the codebase. You can use hook_block_info_alter() to configure the default blocks disable/move/change visibility status.
<?php
/**
 * Implements hook_block_info_alter().
 */
function mymodule_block_info_alter(&$blocks, $theme, $code_blocks) {
  // move navigation to footer
  $blocks['system']['navigation']['region'] = 'footer';
  // disable the powered by drupal block and login block
  $blocks['system']['powered-by']['status'] = 0;
  $blocks['user']['login']['status'] = 0;
  // change the visibility to front page only
  $blocks['search']['form']['visibility'] = BLOCK_VISIBILITY_LISTED;
  $blocks['search']['form']['pages'] = '';
}

The same options can be used to manage your own blocks:
/**
 * Implements hook_block_info().
 */
function mymodule_block_info() {
  $blocks = array();
  $blocks['mymodule_block_example'] = array(
    'info' => t('MyModule: Block example'),
    'status' => 1,
    'region' => 'header',
    'visibility' => BLOCK_VISIBILITY_LISTED,
    'pages' => '',
  );
  return $blocks;
}

How to enable block programmatically