Como ordenar eventos interligados com JQuery?

Question: Estou desenvolvendo um Sistema Web que possui uma página que pode conter 4 blocos de Script. Eu escrevi um Script que pode ser encontrado em um desses blocos, mas não sei qual deles, isso é manipulado pelo Controller.
Inseri alguns eventos Onclick em um botão, mas às vezes eles executam em uma ordem que eu não esperava.
Existe uma maneira de garantir a ordem de execução?
Answer: Segue um plugin jQuery que liga um ouvinte de eventos que é acionado sempre antes dos outros:
<code>(function($) {
    $.fn.bindFirst = function(/*String*/ eventType, /*[Object])*/ eventData, /*Function*/ handler) {
        var indexOfDot = eventType.indexOf(".");
        var eventNameSpace = indexOfDot > 0 ? eventType.substring(indexOfDot) : "";

        eventType = indexOfDot > 0 ? eventType.substring(0, indexOfDot) : eventType;
        handler = handler == undefined ? eventData : handler;
        eventData = typeof eventData == "function" ? {} : eventData;

        return this.each(function() {
            var $this = $(this);
            var currentAttrListener = this["on" + eventType];

            if (currentAttrListener) {
                $this.bind(eventType, function(e) {
                    return currentAttrListener(e.originalEvent);
                });

                this["on" + eventType] = null;
            }

            $this.bind(eventType + eventNameSpace, eventData, handler);

            var allEvents = $this.data("events") || $._data($this[0], "events");
            var typeEvents = allEvents[eventType];
            var newEvent = typeEvents.pop();
            typeEvents.unshift(newEvent);
        });
    };
})(jQuery);
</code>
Notas:
1 - Isso não foi totalmente testado.
2 - Baseia-se no interno da estrutura jQuery não mudando (testado apenas com 1.5.2).
3 - Não será necessariamente desencadeada antes dos ouvintes de eventos que estão vinculados de forma alguma além de um atributo do elemento de origem ou usando jQuery bind() e outras funções associadas.


where to find html code of a page

Question: I am using Opigno (a LMS based on drupal) and I want to edit a page. I am looking for its HTML but when I open the code for the page this is what I found.
<code><?php print render($page['content']);
<?php print render($page['content_bottom']); ?>
</code>
I try to use print_r function in PHP and it displays an array of stuff.
How could I change the page if it is from php.
Thanks!
Answer: I have never used Opigno but since it's based on Drupal, I'd say that you should change/edit the content of a page from its corresponding form once you're logged in.
If you want to edit the HTML, than you have to look for the page templates in your theme folders. This link may help you: https://www.drupal.org/search/site/theme%20template
Comment: Hi @scatteredbrainV I will try your comment ! Thanks!

where to find html code of a page


What is the distinction between bias in prediction and parameter estimation?

Question: I am trying to understand the distinction between bias in prediction and parameter estimation. This example in Gelman, Bayesian Data Analysis, 2nd ed. 2004 pp. 255-256 is very confusing to me.

Why do you get the estimate $\hat{y} = 160 + 0.25(\theta - 160)$ given fixed $\theta$ and $\hat{\theta} = 160 + 2(y - 160)$ under repeated sampling of $y$ conditional on $\theta$? I'm not sure where these equations are coming from.

Does the problem here stem from the fact that the distribution is bivariate (normal) rather than $y$ having a distribution based on each $\theta$?
Answer:
Conditional on $\theta$, the distribution of $y$ is normal with mean $160 + 0.5 (\theta - 160)$. For each realization $y'$ from this conditional distribution, the posterior mean of $\theta$ is
$$
\hat\theta(y') = 160 + 0.5 (y' - 160).
$$ So the expected value of  $\hat\theta(y')$ conditional on $\theta$ is
$$
160 + 0.5 [160 + 0.5 (\theta - 160) - 160] = 160 + 0.25 (\theta - 160).
$$

The bivariate distribution is introduced into the example so that one can talk about "...under repeated sampling of $y$ conditional on $θ$...", i.e. from the conditional distribution of $y$ on $\theta$.

In any case, it seems very Bayesian, and a bit strange from the frequentist perspective, to speak of "...under repeated sampling of $y$ conditional on $θ$...", where $\theta$ is the variable one is trying to predict.
(For a frequentist, unbiased prediction means the mean of the predicted value $\hat{\theta}$ equals the mean of the variable $\theta$ conditional on the predictor, $E[\theta|y]$.)


Is this question based on inspection bias?

Question: This table describes the positive corona tests in all three open ports of country X, in two different days, plus for the total positive for all people entering the country via those three ports:
Day 2     Day 1      Port
1.7%      1.4%        A
0.7%      0.4%        B
0.9%      0.2%        C
-------------------------
1.2%      1.3%   Total entering the country

How is it possible that although the proportion of the corona positive tests, for each port, were higher in Day 2, but Day 1 has a higher proportion in the total!
What paradox is this?
Comment: https://plato.stanford.edu/entries/paradox-simpson/ (Simpson's Paradox)
Answer: Consider the following scenario:
On Day 1, the ports of entry A, B, and C see 40000, 2000, and 2000 entries respectively. With a 1.4%, 0.4%, and 0.2% positive test rate in each of the ports, you will see 560, 8, and 4 positive tests. This yields a total of 572 positive tests, or 1.3% of 44000 entries in total.
On Day 2, the ports of entry A, B, and C now see 16000, 10000, 10000 entries respectively. With a 1.7%, 0.7%, 0.9% positive test rate in each of the ports, you will see 272, 70, and 90 positive tests. This yields a total of 432 positive tests, or 1.2% of 36000 entries in total.
This phenomenon is an example of Simpson's paradox, where (quoting Wikipedia) "a trend appears in several groups of data but disappears or reverses when the groups are combined."
Usually, the paradox arises due to unaddressed confounding variables (e.g. it is a public holiday in Country Y on Day 2 and people from that country prefer using Ports B and C) and assumptions made from early patterns that turn out to be not true (e.g. entries via a given port remain largely constant over days).
Answer: It is because the number of tested people can be different.
Imagine that on Day 2, 99% of your tests were done in Port C, and on Day 1, 99% of your tests in Port A. Then you would have on Day 2 roughly 0.9% and on Day 1 roughly 1.4%, which would even bee more "strange" than your actual data.


Como recuparar o novo nome de um arquivo em um upload "Drag and Drop" automatico

Question: Encontrei um sistema de upload de imagens Drag and Drop na internet que faz o upload da imagem em uma pasta especifica e renomeia o arquivo com um nome aleatório sem precisar enviar o formulário.
Porem não consigo recuperar o novo nome do arquivo para gravar no banco de dados?
Link do projeto
https://github.com/CreativeDream/php-uploader
Simplifiquei o código:
<!DOCTYPE>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Example 1 - jQuery Filer 1.3 - CreativeDream</title>

    <link href="https://fonts.googleapis.com/css?family=Roboto+Condensed" rel="stylesheet">

    <link href="../../css/jquery.filer.css" rel="stylesheet">
    <link href="../../css/themes/jquery.filer-dragdropbox-theme.css" rel="stylesheet">

    <form name="form" action="" method="post">

            <input type="file" name="files[]" id="filer_input2" multiple="multiple">

            <input class="button" type="submit" name="publicar" value="Publicar"/>

    </form>

if( isset( $_POST['publicar'] ) ) {
    $img = $_POST['files']
}

Comment: https://github.com/CreativeDream/php-uploader/blob/master/src/class.uploader.php olha o código pronto ai!!!! igual está no exemplo! entendeu?
Answer: Se você enviar vários arquivos ou apenas um existe um array que informa os nomes gerados que possui a chave name:
Local especifico no código exemplo:
if($data['isComplete']){
    $files = $data['data'];
    foreach($files['metas'] as $values)
    {
        //aqui são os nomes gerados
        echo $values['name'];
    }
}

ou seja, $values['name'] utilize para gravar na sua base de dados.

Além do nome do arquivo gerado possui diversas informações:
Array
(
    [files] => Array
        (
            [0] => uploads/Lh3EGOrl7D.jpg
            [1] => uploads/nJVhvxBXQD.jpg
            [2] => uploads/0kJOf_ABQt.jpg
            [3] => uploads/lH9ZrpGAbM.jpg
        )

    [metas] => Array
        (
            [0] => Array
                (
                    [date] => Thu, 06 Oct 2016 17:15:00 -0300
                    [extension] => jpg
                    [file] => uploads/Lh3EGOrl7D.jpg
                    [name] => Lh3EGOrl7D.jpg
                    [old_name] => 14064104_10209380587605927_5793335061447087469_n.jpg
                    [replaced] =>
                    [size] => 8251
                    [size2] => 8.06 KB
                    [type] => Array
                        (
                            [0] => image
                            [1] => jpeg
                        )

                )

            [1] => Array
                (
                    [date] => Thu, 06 Oct 2016 17:15:00 -0300
                    [extension] => jpg
                    [file] => uploads/nJVhvxBXQD.jpg
                    [name] => nJVhvxBXQD.jpg
                    [old_name] => 14192672_1402374739778600_7123746786432954771_n.jpg
                    [replaced] =>
                    [size] => 14404
                    [size2] => 14.07 KB
                    [type] => Array
                        (
                            [0] => image
                            [1] => jpeg
                        )

                )

como extensão, antigo nome de arquivo, tamanho, data de envio, etc. Esses valores em chave pode ser utilizado no foreach se assim quiser.

Código Completo:
Html
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Laravel</title>
    <link href="css/jquery.filer.css" type="text/css" rel="stylesheet" />
    <link href="css/themes/jquery.filer-dragdropbox-theme.css" type="text/css" rel="stylesheet" />

        <form action="upSave.php" method="post" enctype="multipart/form-data">
            <input type="file" name="files[]" id="filer_input" multiple="multiple">
            <input type="submit" value="Enviar">
        </form>

PHP
<?php

    require_once("class.uploader.php");

    $uploader = new Uploader();
    $data = $uploader->upload($_FILES['files'], array(
        'limit' => 10, //Maximum Limit of files. {null, Number}
        'maxSize' => 10, //Maximum Size of files {null, Number(in MB's)}
        'extensions' => null, //Whitelist for file extension. {null, Array(ex: array('jpg', 'png'))}
        'required' => false, //Minimum one file is required for upload {Boolean}
        'uploadDir' => 'uploads/', //Upload directory {String}
        'title' => array('auto', 10), //New file name {null, String, Array} *please read documentation in README.md
        'removeFiles' => true, //Enable file exclusion {Boolean(extra for jQuery.filer), String($_POST field name containing json data with file names)}
        'replace' => false, //Replace the file if it already exists {Boolean}
        'perms' => null, //Uploaded file permisions {null, Number}
        'onCheck' => null, //A callback function name to be called by checking a file for errors (must return an array) | ($file) | Callback
        'onError' => null, //A callback function name to be called if an error occured (must return an array) | ($errors, $file) | Callback
        'onSuccess' => null, //A callback function name to be called if all files were successfully uploaded | ($files, $metas) | Callback
        'onUpload' => null, //A callback function name to be called if all files were successfully uploaded (must return an array) | ($file) | Callback
        'onComplete' => null, //A callback function name to be called when upload is complete | ($file) | Callback
        'onRemove' => 'onFilesRemoveCallback' //A callback function name to be called by removing files (must return an array) | ($removed_files) | Callback
    ));

    if($data['isComplete']){
        $files = $data['data'];
        //print_r($files);
        foreach($files['metas'] as $values)
        {
            echo $values['name'];
            echo '
';
        }
    }

    if($data['hasErrors']){
        $errors = $data['errors'];
        print_r($errors);
    }

Comment: :D Funcionou, obrigado!
Comment: Não consigo recuperar o array com o nome
Comment: @DanilloEder coloque na sua pergunta o código html e o código do upload por favor!
Comment: Adicionei, o restante não muda nada.
Comment: @DanilloEder esse pacote de `Drag and Drop` tem um classe pronta pra upload (https://github.com/CreativeDream/php-uploader/blob/master/src/class.uploader.php) que facilita isso com códigos de exemplo, eu postei o html e o código pronto com um `require_once("class.uploader.php");` e o resto do código, vai facilitar sua codificação.


how to use sweet alert just before exporting excel file

Question: I'm trying to use sweet alert library to add a dialog box just before downloading my excel file

  <button onclick="downloadExcel()" id="download" class="tab-group"  > Download</button>

then my Javascript function is as such

my problem is that when i run my button it automaticly download the excel and the dialog box just show and hide without letting me click ok button in the dialog box .
how can i achieve this scenario
(click download button --> dialog box show -->click ok in the dialog box --> excel will be downloaded ? )?
Answer: You need to use confirm like:
function s2ab(s) {
  let buf = new ArrayBuffer(s.length); //convert s to arrayBuffer
  let view = new Uint8Array(buf); //create uint8array as viewer
  for (let i = 0; i < s.length; i++) view[i] = s.charCodeAt(i) & 0xFF; //convert to octet
  return buf;
}

function downloadExcel() {
  // notifications part
  Swal.fire({
    title: 'Do you want to continue?',
    icon: 'success',
    showCancelButton: true,
    confirmButtonColor: '#3085d6',
    cancelButtonColor: '#d33',
    confirmButtonText: 'Yes!'
  }).then((result) => {
    if (result.isConfirmed) {
      let wb = XLSX.utils.book_new();
      wb.Props = {
        Title: "excel",
        Subject: "excel",
        Author: "aaa",
        CreatedDate: new Date()
      };
      wb.SheetNames.push("excel");
      const column1 = document.getElementById('column1').value;
      const column2 = document.getElementById('column2').value;
      let ws_data = [
        ['key', 'value'],
        ['column1', column1],
        ['type', 'excel'],
        ['column2', column2]
      ];
      let ws = XLSX.utils.aoa_to_sheet(ws_data);
      wb.Sheets["excel"] = ws;
      let wbout = XLSX.write(wb, {
        bookType: 'xlsx',
        type: 'binary'
      });

      saveAs(new Blob([s2ab(wbout)], {
        type: "application/octet-stream"
      }), 'excel.xlsx');

    } else if (
      result.dismiss === Swal.DismissReason.cancel
    ) {
      Swal.fire(
        'Abort download',
        'Download stopped!',
        'error'
      );
    }
  });

}

With .then((result) you can catch if user press ok or not, then choise the action, for example if user abort, another messagge will display.
Example work here (without excel download):

downloadExcel();
function downloadExcel() {
  // notifications part
  Swal.fire({
    title: 'Do you want to continue?',
    icon: 'success',
    showCancelButton: true,
    confirmButtonColor: '#3085d6',
    cancelButtonColor: '#d33',
    confirmButtonText: 'Yes!'
  }).then((result) => {
    if (result.isConfirmed) {
      console.log('download excel');
    } else if (
      result.dismiss === Swal.DismissReason.cancel
    ) {
      Swal.fire(
        'Abort download',
        'Download stopped!',
        'error'
      );
    }
  });

}

Last advice, please don't use inline call function, instead use addEventListener
Comment: Hello thanks for your code ! but there is a problem that i'm facing is that when the dialog box show it disspears suddenly just after few seconds is it because my navigator (using chrome)
Comment: the page refresh just when i click the download but
Comment: I don't understand, the only possibility is if you click on black background on open popup it will close and what do you mean by page refresh???? Because you didn't metioned that to your question


Best practice for method chaining ("return this")

Question: I have an abstract class called DatabaseRow that, after being derived and constructed, is mainly loaded from a Load(object id) method.
I have lots of code that creates a new instance of the class, loads it from an ID, then returns the class. I'd like to simplify this code into one line of code (just to be neat, there are plenty of classes that will just have lists of properties that return these Loaded instances).
There are two ways I can think of doing it, but neither seem 'right' to me.
1. I could return this; at the end of my Load method and use return new Derived().Load(id);
2. I could create a generic method to return a loaded method.
public static T LoadRow<T>(object id) where T : DatabaseRow, new()
{
    T row = new T();
    row.Load(id);
    return row;
}

I've seen some other code that uses the same method as number 1, but I've never seen any experienced developer recommend it, nor have I came across any methods in the .NET framework that do the same thing, so maybe this isn't best practice?
Does anybody know of any other solutions that could be better than both of these?
Solution:
After reading SirViver's answer and comment, I realised that all the properties being returned need to be cached anyway. The solution was sightly different, but similar to option 2 (that I wouldn't expect anyone to come up with this answer as I didn't explain this part of the design)
All these instances will be loaded from a value retrieved from another column in the database (database relationships if you like). Instead of trying to load the new instance from this value, I made a method to load the instance from the column name and cache the loaded value in a Dictionary. This works well as this is one of the primary functions of the DatabaseRow class.
    private Dictionary<string, DatabaseRow> linkedRows;

    protected T GetLinkedRow<T>(string key) where T : DatabaseRow, new()
    {
        if (linkedRows.ContainsKey(key)) return (T)linkedRows[key];
        else
        {
            T row = new T();
            row.Load(this[key]);
            linkedRows.Add(key, row);
            return row;
        }
    }

Answer: Personally, I think it's bad practice to chain method calls that have actual sideffects on the object instance. To be honest, I think both examples are quite ugly "hacks" whose only purpose is saving two lines of code. I don't think the result is actually more readable either.
If you want a record to be loaded immediately, I'd probably rather supply a constructor variant that takes the ID you load from and make the object auto-populate itself on construction, though when I think about it, I wouldn't bother at all to be honest - cramming more information in a single line does not make for more read- and maintainable code.
Comment: Since I agree with everything you said your first paragraph and your comment triggered my solution, I feel this should be the accepted answer. Thanks.
Comment: In my case, I have a class that inherits `DatabaseRow`, and have 5 properties which all use this same function. Having 5 lines of code, similar to `public Derived MyProperty { get { return new Derived().Load(myInt); } }` would be much neater than separating the properties into multi-line code.
Comment: But how does the "neatness" of the property code matter at all? In most cases the property code should be collapsed by Visual Studio anyway, and it's not like you constantly have to look at the class implementation anyway. That said, constructing and loading data on a property access seems quite dangerous to begin with. If someone doesn't know that the result needs to be cached this could quickly result in bad performance and/or unexpected behavior.
Comment: Thats it!!! I feel like such an idiot now. Your comment on caching reminded me that I've already created this function right at the bottom of my DatabaseRow class! `protected T GetLinkedRow(string key) where T : DatabaseRow, new()` loads the row and caches it in a dictionary based on the value of `key`.
Answer: Number 1 is gaining in popularity in some circles; it's often called fluent programming when there's an interface that defines great numbers of these methods and long chains can be assembled. The key to doing this successfully is never to define a method that sometimes returns this, but other times returns null. If this is always returned (unless there's an exception) it's perfectly good style.
Personally I'm not as fond of solutions like number 2, as it could be said to violate the "one responsibility" principle.
Answer: Although I personally like methods returning this as it allows them to be chained, I think in the .NET framework (up until Linq), this was frowned upon. The reason that pops to mind is this:
Methods either return a result or change the state of the object. Returning this is a bit of both: Changing the state of the object and then returning a "result" - except that result is the modified original object. This doesn't fit the expectations of the user.
What about:
public class Derived : DatabaseRow
{
    public Derived(object id):
    {
        Load(id);
    }
}

And use it like this:
return new Derived(id);

Comment: I couldn't agree more with your second paragraph here. I was actually originally using something similar to your solution, however I decided against it and changed to the Load method because I don't think constructors should have that much functionality (in this case, executing SQL queries)
Comment: @Connell Watkins: I have thought similarly about constructors before myself, but now tend to think of them as being a guarantee that the object is in a usable state. So, if the objects are only ever meant to be used after calling the Load method, then you really can put that in the constructor!
Answer: Option 1 is only acceptable if it is possible to have a row without being loaded. This is due to the pattern allowing you to do this:
return new Derived();

Personally I would prefer the static method. But I suspect it is simply a matter of personal preference.
As ssg says the other option (lets call it option 3) is to overload the constructor in Derived which would also work, however having lots of constructors can often be confusing as the calling code does not have anything in it which describes what is going on.
Option 1:
return new Derived().Load(10);

Option 2:
return Derived.Load(10);

Option 3:
return new Derived(10);

Option 1 looks like you are getting a superfluous object created. Option 2 is good because it does what it looks like it is doing. Option 3 leaves confusion about what it does.
Comment: It is quite possible to have a class and not load it. If you were creating a new row in the database, you'd create a new instance, fill the properties and then call a `Save()` method. Do you mean the generic static method? Or a static method in each derived class?
Comment: Ah, I've just seen your edit. Option 2 looks perfect, but the thing with that is that it would require me to create the same static method for every derived class of this type, which seems to be unnecessary.


Generate a dataframe with all possible combinations between two lists

Question: Hello I have two lists:
list1<-c("A","B")
list2<-c(1,2,3)

and i would like to get all possible combinations and save it into a dataframe such as :
with a colum called Possibilities which refers to the name of the possibilities.
list1 list2 Possibilities
A     1     P1
B     1     P1
A     2     P2
B     2     P2
A     3     P3
B     3     P3
A     1     P4
B     2     P4
A     2     P5
B     1     P5
A     3     P6
B     1     P6
A     1     P7
B     3     P7
A     2     P8
B     3     P8
A     3     P9
B     2     P9

The solution :
> expand.grid(list1,list2)

did not what I whant since it gives:
  Var1 Var2
1    A    1
2    B    1
3    A    2
4    B    2
5    A    3
6    B    3

Comment: What is the difference between entry 1 and entry 7 in your output? Aren't both 'A' from list1 and '1' from list2?
Comment: It's hard to know how to help without a clear explanation of your logic. Calling `expand.grid` the way you've shown it does indeed give all combinations of the two vectors. Whatever the logic is that makes one (A,1) differ from another (A,1) should be here in the question
Comment: Does this answer your question? [Unique combination of all elements from two (or more) vectors](https://stackoverflow.com/questions/11388359/unique-combination-of-all-elements-from-two-or-more-vectors)
Comment: It is not the same thing, try their code and you will see you won't have the same output
Answer: I think you can try expand.grid like below
data.frame(
  lst1 = list1,
  lst2 = c(t(rev(expand.grid(rep(list(list2), length(list1)))))),
  Possibilities = paste0("P", rep(seq(length(list2)^length(list1)), each = length(list1)))
)

which gives
   lst1 lst2 Possibilities
1     A    1            P1
2     B    1            P1
3     A    1            P2
4     B    2            P2
5     A    1            P3
6     B    3            P3
7     A    2            P4
8     B    1            P4
9     A    2            P5
10    B    2            P5
11    A    2            P6
12    B    3            P6
13    A    3            P7
14    B    1            P7
15    A    3            P8
16    B    2            P8
17    A    3            P9
18    B    3            P9


Blending Musical Genres To Create a New Genre

Question: Throughout history mankind has created musical genres. This probably had its origins thousands of years ago when someone first banged 2 rocks together in a cave to accompany someone grunting. Or maybe it emerged as a byproduct of communication. Genre-creating has continued to this day. For example, according to Wordnik, Rockabilly is "A form of popular music combining features of rock music and bluegrass."
I believe that it is possible to write or train a computer algorthm that can take audio samples from 2 different genres (such as rock and bluegrass) and blend them together to produce a "new" genre similar to what we know as Rockabilly.
My questions are:

Has this been accomplished yet?
If yes or no, what major steps would be required to write such an algorthm?
If these questions are too large in scope to be easily answered, then is it possible to define what a genre is in computer code? I'm thinking the answer is yes if such things as tempo, rhythm, swing, musical instruments, etc. are identified.

Thanks for any insight into this.
Comment: Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/138344/discussion-on-question-by-steve-blending-musical-genres-to-create-a-new-genre).
Answer: There are several programs already that generate music- for example, Dadabots (known for "relentless doppelganger" on Youtube), OpenAI Jukebox, and Google's Magenta. Some skip the whole "music" part and go straight for generating audio, but some (like AIVA) do generate music based on musical scores.
As far as I can tell, there is much more focus on generating convincing songs right now, rather than having AI make any new styles of music.  At least, the "new" elements of AI music are mostly accidental.
If you wanted to create new genres instead of just new songs, I suppose you could feed such an algorithm only content from 2 genres, but it's likely that its output will be in one genre or the other, rather than right in between. You'd probably have to modify any open-source program you used as a starting point (working-as-intended adversarial models will reject genre-benders if they don't exist in the original data). If you had an AI that generated musical scores rather than audio, you could certainly design it to pull e.g. "rhythm" data from one genre, and "harmonic" data from another.  You probably want the AI to learn what each genre means on its own, rather than trying to define it yourself.  I do believe that your goal could be done.  AI is a huge topic that I barely understand, but maybe with a few years of research, you may be able to answer your second question.
Comment: @Steve I think he means that he doesn't like the or the answer question but doesn't understand enough that he could express in words why he doesn't like it. To me the question sounds more like profound lack of research, but this answer is really good.
Comment: Generally, these AIs require large data sets.  I don't think it's even possible to quantify a genre from a single song, much less create a program that can do it.  A more realistic goal might be an AI that will generate a new song from 1000 examples in genre A, and 1000 examples in genre B.  Maybe an ideal program would only need 20-30.  OpenAI Jukebox used over 1 million examples in their dataset.
Comment: Thanks Edward, if my original post wasn't clear I'm not asking about software code that can produce sheet music or chord charts in a "new" genre but rather audio. So it would be given an MP3 audio sample from genre A and an audio sample from genre B and mix or blend the two to produce audio in genre C. But step 1 is to be able to define (in computer terms), what  a "genre" actually is. I'm not sure that musicologists and computer scientists have accomplished even that yet. Maybe someone here knows that answer.
Comment: I'm not limiting the size of the training sets in any way. Let's say it is trained on 1000 examples of rock and 1000 of blue grass; or 10 million of each. When asked to blend 1 example of rock with 1 example of bluegrass the question is would it arrive at rockabilly?  If this has been attempted and the answer is no, then I think we can say more AI research is required. I just don't know if it has been attempted.
Comment: To whoever downgraded because he doesn't see how this would be useful. Here are 2 answers 1) basic music and human psychology research with possible benefits in music therapy and 2) new genres can take years or decades or more to develop often by accident and random chance. If such a tool existed new genres could be developed and explored much faster, perhaps in days.
Comment: OK, I see now that Aaron downvoted this. Aaron, I didn't realize that why a question is useful needed to be included in the question. And, I respectfully disagree that this revolves around sound. It revolves around music, musical genres, musical styles and computers.
Comment: Damn you touchpad… What I tried to write was "doesn't like the question or the answer"


Coefficients of Chebychev Polynomials

Question: Is there a known formula for the coefficient of x^k in the nth chebychev polynomial of the first kind?
Comment: What about the 4th formula in https://en.wikipedia.org/wiki/Chebyshev_polynomials ,"explicte expressions" ?
Comment: ah nice, did not see that
Answer: Here is a link to a paper that claims to do just this: Link
Comment: is there a way of viewing papers on that site?
Comment: I doubt it for this one.  IEEE is a real pain sometimes;  you have to go through your university or local library.
Comment: http://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber=271362

Coefficients of Chebychev Polynomials


Which hook to implement to limit node creation?

Question: I'm looking to limit the number of nodes that a user can create in Drupal 7.
Which hook should I implement to step in before the 'add node' page is shown?
Comment: There is also a module that provides this functionality: http://drupal.org/project/node_limit. You could maybe just use that or look at how it's implementing it.
Comment: I couldn't seem to find a D7 version of node_limit.  It looked like a perfect solution though.
Comment: Related topic: [How to limit users to a create only one instance of a node type in Drupal 7?](http://drupal.stackexchange.com/questions/33438/how-to-limit-users-to-a-create-only-one-instance-of-a-node-type-in-drupal-7)
Answer: Alter the access callback for the menu callback:
function custom_module_menu_alter(&$items){
    $items['node/add/page']['access callback'] = 'my_custom_access_callback';
    // Next line needed for Drupal 7
    unset($items['node/add/page']['access arguments']);
}

Add a function as your custom access callback:
function my_custom_access_callback() {
   global $user;
   $allowed_limit = variable_get('allowed_limit', 10);

   // If Drupal 6.
   $node_counts = db_result(db_query("SELECT count(*) FROM {node} WHERE uid = %d;", $user->uid));
   // End If

   // If Drupal 7.
   $node_counts = db_query("SELECT count(*) FROM {node} WHERE uid = :uid", array(':uid' => $user->uid))->fetchField();
   // End If

   if ($node_counts < $allowed_limit && user_access("create page")) {
     return TRUE;
   }
   else{
     drupal_set_message(t('Print message about exceeded limit and/or user permissions.'));
     return FALSE;
   }
}

This kind of logic will restrict a user to exceed the limit.
Comment: Yeah, the code above is for Drupal 6. I suggest you directly edit your adjustments into the above answer (yes, you can do that). You could for example add both queries, document for which version they are and comment one out. Then this question/answer isn't specific to Drupal 7 anymore :)
Comment: Lastly for searchers, I also had to change the db_query. `$node_counts = db_query("SELECT count(*) FROM {node} WHERE uid = :uid", array(':uid' => $user->uid))->fetchField();`  I'm assuming just D7 quirks. :)  Thank you for the code block, it was exactly what I needed! @Shoaib Nawaz
Comment: Worked Beautifully.  Did need to unset access arguments as well. `unset($items['node/add/page']['access arguments']);` in custom_module_menu_alter
Comment: @Shoaib Nawaz, I just attempted my first ever edit.  :)
Answer: The Node Limit project now has a Drupal 7 port as an Alpha release.

The Node Limit module allows administrators to restrict the number of
  nodes of a specific type that roles or users may create. For example,
  if a site has an "Advertiser" role that can create "advertisement"
  nodes, then the node limit administrator can restrict all users in
  that role to a specific number of nodes. He may also restrict users on
  a per-user basis.

There is a plan to include Rules support in the near future as well.  The documentation could use some work but if you poke through the module it will likely accomplish what you need.
Answer: Hook node validate may be more appropriate here. http://api.drupal.org/api/drupal/modules--node--node.api.php/function/hook_node_validate/7
That way if you use Services the solution will work, while the one proposed by Shoaib will only work if a user accesses the actual node creation page. If a remote client calls node.save via Services the menu access hack will fail.
Comment: This solution is recommend than menu altering.
Answer: For what it's worth, there's no need to alter the menu and remove the default node access callback.
Drupal provides hook_node_access to be used for this purpose:
e.g:
/**
 * Implements hook_node_access
 */
function MY_MODULE_node_access($node, $op, $account) {
  // Get node type, can be string or node object
  $type = is_string($node) ? $node : $node->type;
  if ($type == 'type_of_interest') {
    // Check node create limit
    if ($op == 'create') {
      // Check if some condition, limit check, is true
      // omitted for brevity
      // ...
      if($limit_reached){
        return NODE_ACCESS_DENY;
      }
    }
  }
  return NODE_ACCESS_IGNORE;
}


Piano practice for adult beginner

Question: I've been practicing piano for over a year. My intention was the cliche'd just-have-to-learn-für-elise-before-i-die. So I've learned the whole piece and a couple of more simple tunes but you know, as i understand now, many adults approach piano in this wrong way and end up with playing WITHOUT any sign of musicality.(And I did this stupid mistake too.) Now I see clearly that I have to begin from scratch and establish the fundementals.
I've searched the net about books, methods, suggestions, etc. which didn't bring me to an obvious idea for regular practice. I'm thinking about practicing GRADE 1 songs(to be able to play them musical surely), practicing scales and all supplemented with various method and theory books.
What are your opinions on this? Can i simply follow and practice ABRSM exam contents? By the way, I won't be able to take lessons from a teacher.
Answer: The ABRSM exam syllabus, and the set pieces for each grade, will certainly work as a logical progression. ABRSM also publish other "graded" collections of pieces.
However these ABRSM publications don't include any teaching material, though you can find YouTube videos created by qualified teachers to provide some of that.
It is probably worth supplementing the ABRSM books with material which has its primary aim of teaching. There are several series of "adult piano course" books available - Alfred, Bastien and John Thompson are three well known ones.
The best way is undoubtedly to get a teacher, who can see when you are doing something wrong and correct it before it turns into a bad habit - but if you can't use a teacher for whatever reason, that's no reason not to try to learn without one!
If the problem is simply the lack of a teacher where you are living, you may be able to find somebody who gives "remote lessons" via Skype, etc. That is certainly being done for advanced music tuition, but I don't know how common it is at beginner level.
Answer: Make establishing a proper technique your first priority. Improving on sight reading and extending your repertoire will not immediately change how you play other songs, but lack of technique will set you back in your ability to musically express yourself and potentially cause harm if you play a lot.
My 2 cents (25 years of piano playing.)

Piano practice for adult beginner


Of fibonomials, pellonomials, and tribonomials, etc

Question: I. Linear recurrence with order 2
Given the Fibonacci numbers $F_n$, we have
$$\begin{aligned}
&F_n+F_{n+1}-F_{n+2}=0\\[1mm]
&F_n^2-2F_{n+1}^2-2F_{n+2}^2+F_{n+3}^2=0\\[1mm]
&F_n^3+3F_{n+1}^3-6F_{n+2}^3-3F_{n+3}^3+F_{n+4}^3=0\\
&\small\text{and so on.}
\end{aligned}$$
The coefficients are called fibonomials. (The version for the Pell numbers are quaintly called the pellonomials.)
II. Linear recurrence with order 3
For the tribonacci numbers $T_n$, we have,
$$\begin{aligned}
&T_n+T_{n+1}+T_{n+2}-T_{n+\color{brown}3}=0\\[1mm]
&T_n^2 - T_{n + 2}^2 + 6T_{n + 3}^2 - 3T_{n + 4}^2 - 2T_{n + 5}^2 + T_{n + \color{brown}6}^2 = 0\\[1mm]
&T_n^3 - 2T_{n + 1}^3 + 2T_{n + 2}^3 - T_{n + 3}^3 - 14T_{n + 4}^3 \;\;+\;\; \dots \;\;+\;\; T_{n + \color{brown}{10}}^3 = 0\\
\end{aligned}$$
Notice that $3,6,10$ (and next is $15$) are generated by $m=\tfrac{1}{2}(k+1)(k+2)$.

III. Question:
Given a linear recurrence of order $d$,
$$s_n = a_1s_{n-1}+a_2s_{n-2}+\dots+a_ds_{n-d}$$
with $a_d\neq0$. Assume one can find a formula valid for all positive integer $n$,
$$c_0s_n^k+c_1s_{n+1}^k+c_2s_{n+2}^k+\dots+c_{m}s_{n+m}^k=0$$
with integer $c_i$ and positive integer $k$. How do we show that the required $m$ is a function of $k$ (and $d$) and in fact is a figurate number? Hence,
$$\begin{array}{|c|c|c|}
\hline
\text{Order}\; d&m&\text{Name}\\
\hline
2&k+1&\text{linear}\\
\hline
3&\tfrac{1}{2}(k+1)(k+2)&\text{triangular numbers}\\
\hline
4&\tfrac{1}{6}(k+1)(k+2)(k+3)&\text{tetrahedral numbers}\\
\hline
\end{array}$$

P.S. I tested it with the Padovan sequence $P_n = 1, 1, 1, 2, 2, 3, 4, 5, 7, 9,\dots$ (and others with 3rd order) and it has the same pattern,
$$\begin{aligned}
&P_n+P_{n+1}-P_{n+\color{brown}3}=0\\[1mm]
&P_n^2 - P_{n + 1}^2 + P_{n + 2}^2 - P_{n + 3}^2 - P_{n + 4}^2 - P_{n + 5}^2 + P_{n + \color{brown}6}^2 = 0\\
\end{aligned}$$
and so on. I also tested the tetranacci sequence and for $k = 1,2,3$ we have $m=4,10,20$ which are the first tetrahedral numbers.
Answer: Caveat: this is more a sketch of a possible approach than a complete answer.
Given a general linear recurrence $x_n = a_1 x_{n-1} + \ldots + a_r x_{n-r}$ the solution is typically of the form $x_n = \alpha_1 \beta_1{}^n + \ldots + \alpha_r \beta_r{}^n$.
So if we consider $$x_n^k = (\alpha_1 \beta_1{}^n + \ldots + \alpha_r \beta_r{}^n)^k = \sum_{\lambda \,\vdash\, k} A_\lambda \left(\beta_1{}^{\lambda_1}\ldots \beta_r{}^{\lambda_r}\right)^n$$(where $\lambda \,\vdash\, k$ means that $\lambda$ is a partition of $k$, and the formulation of $A_\lambda$ in terms of the $\alpha_i$ is left as an exercise) we see that we can expect it to satisfy a linear recurrence.
Gaps in the argument:

I haven't covered the case where the characteristic polynomial of the original recurrence has repeated roots. I think this gap can be filled because that gives terms $\alpha_i x^j \beta_i^x$ which carry through to give similar terms in the new recurrence.
I haven't argued for the order of the derived recurrence.
Comment: I've generalized my question. I guess the hard part is to show what is the required value of $m$. (I've empirically observed they are figurate numbers where the variables are in terms of $k$.)
Comment: As a disclaimer, I only tested sequences where the characteristic polynomial has **no** repeated roots, so I don't know how valid my observations are (especially $m$ being a figurate number) if we include the case with repeated roots.
Comment: @TitoPiezasIII, I would guess that being figurate numbers is a consequence of the figurate numbers being binomials; I can see how binomial numbers might be related to the number of different values of $\prod_i\beta_i{}^{\lambda_i}$ in the case that the $\beta_i$ are sufficiently independent.
Answer: Here's a way of phrasing Peter's proof that I think makes it less bookkeeping-intensive:

Define the Hadamard product of two sequences $\{a_n\}$, $\{b_n\}$ to be the sequence $\{a_n b_n\}$.
Note that the vector space of sequences forms an algebra under Hadamard product (that is, it distributes over ordinary addition and is compatible with ordinary scalar multiplication).
Call a sequence simple if it is of the form $\{n^k \alpha^n\}$ for some constants $k,\alpha$.
Note that the Hadamard product of simple sequences is simple.
Note that a sequence is the solution to a constant-coefficient linear recurrence relation if and only if it is a linear combination of simple sequences.
Conclude that the Hadamard product of two such solutions is also the solution to a constant-coefficient linear recurrence relation.
Induct!

Alternately, see these notes for another perspective...
Comment: @TitoPiezasIII: Short answer before I run off to dinner, which I'll probably update later: you can certainly use it to derive an upper bound for $m$, which will be the correct value in almost all cases. However there's the possibility of numerical coincidences. A possibly instructive example is given by the sequence $\{4^n+6^n+9^n\}$, which satisfies an order-3 recurrence and whose square satisfies an order-5 recurrence.
Comment: I've generalized the question. Is it possible to tweak your answer to derive the variable $m$? (Kindly see my comment to Peter's post.)


How to solve a binomial for $n$

Question: How do you solve the equation:
$$
\binom{n}{3}=4\binom{n}{2}
$$
I've tried multiple times I'm just not sure what I'm supposed to do to be honest.
What I did try doing was the combinatorial theorem, and re-arranging to get n, but I didnt get a solution. So I'm wondering how I would go about solving for n.
Comment: do you mean $\binom{n}{3}=4\binom{n}{2}$?
Comment: yea thats it thanks
Comment: Isn't it straightforward by following the definition?
Answer: If you write out these expressions in terms of their definitions, you are greeted with simply a polynomial equation:
$${n\choose3} = 4{n\choose2} \implies \frac{n(n-1)(n-2)}{3!}=\frac{4n(n-1)}{2!}.$$
From here, it should be very easy to extract such a value for $n$.
Comment: And in fact for $n \ge 2$ you can cancel $n(n - 1)$ and the resulting equation is linear in $n$!
Answer: You can just write the definitions on each side and solve for $n$:
$$\dfrac {n!}{3!(n-3)!}=4\dfrac {n!}{2!(n-3)!}$$
$$\iff \dfrac {1}{6(n-3)!}=\dfrac {2}{(n-2)!}$$
$$\iff \dfrac {(n-2)!}{(n-3)!}=12$$
$$\iff (n-2)=12$$
$$\iff n=14$$
Comment: It's common to define $\binom{n}{k}$ to be zero if $n<k$. If you follow that convention, then 0 and 1 are also solutions.

How to solve a binomial for $n$


Deploying an app with Crystal Reports in IIS

Question: I am trying to deploy an app that I used Crystal Reports in. I want to say that it works on local host as I am using IIS Express and in staging I am using IIS. This is the main difference that I can think of but just to be sure I want to write out the entire process that have done.

Build Report in Visual Studio
Create ODBC Connection on local host
Run Report in localhost - it works
publish MVC app
add ODBC connection with same name on server
copy report to correct location on IIS server
run app and report app works report doesn't.

The log that I am getting is:

FATAL 2018-08-28 03:22:30,923 37280ms Log Service            GenerateReport     - Exception during StringFormat: Index (zero based) must be greater than or equal to zero and less than the size of the argument list. Generate Reports at: 8/28/2018 3:22:30 AM, Exception: CrystalDecisions.CrystalReports.Engine.InternalException: Failed to open the connection.
  QuoteReport 5092_4216_{0FAD9DBD-DCD7-4158-816D-56895A79B362}.rpt
  Details:  [Database Vendor Code: 4060 ] ---> System.Runtime.InteropServices.COMException: Failed to open the connection.
  QuoteReport 5092_4216_{0FAD9DBD-DCD7-4158-816D-56895A79B362}.rpt
  Details:  [Database Vendor Code: 4060 ]
     at CrystalDecisions.ReportAppServer.Controllers.ReportSourceClass.Export(ExportOptions pExportOptions, RequestContext pRequestContext)
     at CrystalDecisions.ReportSource.EromReportSourceBase.ExportToStream(ExportRequestContext reqContext)
     --- End of inner exception stack trace ---
     at CrystalDecisions.ReportAppServer.ConvertDotNetToErom.ThrowDotNetException(Exception e)
     at CrystalDecisions.ReportSource.EromReportSourceBase.ExportToStream(ExportRequestContext reqContext)
     at CrystalDecisions.CrystalReports.Engine.FormatEngine.ExportToStream(ExportRequestContext reqContext)
     at CrystalDecisions.CrystalReports.Engine.ReportDocument.ExportToStream(ExportOptions options)
     at CrystalDecisions.CrystalReports.Engine.ReportDocument.ExportToStream(ExportFormatType formatType)
     at QuickQuote.Controllers.ReportsController.GenerateReport(Int32 reportId, String json) in C:\Users\James\Source\Repos\QuickQuote3\QuickQuote\Controllers\ReportsController.cs:line 84{}

Can someone please tell me what my issue is? I have google this error and I don't understand what my issue is.
try
{
    var stream = _reportBuilder.BuildReport(dataSet, report, filePath, parameters);
    stream.Seek(0, SeekOrigin.Begin);

    return File(stream, "application/pdf", $"Quote{report.Name}-{DateTime.Now}.pdf");
}
catch (Exception e)
{
    _loggingService.FatalFormat($"Generate Reports at: {DateTime.Now}, Exception: {e}");
    throw;
}

Inside reportBuilder.BuildReport is where it is breaking. I'm sure that it is this line:
var stream = reportDocument.ExportToStream(ExportFormatType.PortableDocFormat);

BuildReport method:
public Stream BuildReport(DataSet dataSet, Report report, string path, string parameters)
{
    var reportDocument = new ReportDocument();
    reportDocument.Load(path);
    reportDocument.SetDataSource(dataSet);
    AddParametersToReport(ref reportDocument, report, parameters);
    return reportDocument.ExportToStream(ExportFormatType.PortableDocFormat);
}

Comment: I have updated my question
Comment: im 100% sure that it is `var stream =reportDocument.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);`
Comment: https://blog.lextudio.com/web-application-differences-in-visual-studio-and-iis-60fec7e311b3
Comment: I have done the ODBC Data Source Administrator (both 32-bit and 64-bit) and now I get new error. `Database logon failed`
Comment: thank you very much! That did it. It now runs. thanks so much.
Comment: I'm glad it helped. I'm going to remove my comments and post them as answer to your question.
Answer: The exception message is Failed to open the connection.
Verify if System Data Sources are set up correctly in ODBC Data Source Administrator (for both 32-bit and 64-bit).
You may get Database logon failed error, as credentials specified in .rpt file might be invalid for the database. The solution is to provide database credentials in code:
public Stream BuildReport(DataSet dataSet, Report report, string path, string parameters)
{
    try
    {
        var reportDocument = new ReportDocument();
        reportDocument.Load(path);
        reportDocument.SetDataSource(dataSet);
        AddParametersToReport(ref reportDocument, report, parameters);

        // Set database credentials
        reportDocument.SetDatabaseLogon("dbUsername", "dbPassword");

        return ReportDocument.ExportToStream(ExportFormatType.PortableDocFormat);
    }
    catch(Exception ex)
    {
        _loggingService.FatalFormat($"Exception: {ex}");
        throw;
    }
}


where is D6's statistics_counter in D7?

Question: I want show the number of  views count in node.tpl.php with Drupal 7, but I cant find  the Drupal 7 Equivalent of statistics_counter.
where can I find it?
Answer:
The Statistics module shows you how often a given page is viewed, who
  viewed it, the previous page the user visited (referrer URL), and when
  it was viewed.
In Drupal 7 configure statistics via configuration > statistics.
To enable collection of statistics, the Enable access log checkbox on
  the Statistics settings page must be checked.
Enable Count content views to turn on and off the node-counting
  functionality. If turned on, an extra database
  query is added for each node displayed, which increments a counter.

Make sure you set permissions for the module at admin/user/permissions and configure it.
Based on drupal.org and http://groups.drupal.org/node/147619
Comment: You need the `view post access counter` permission to see the statistics_counter pseudo-link.

where is D6's statistics_counter in D7?


Windows server 2012 PPPoE share to NAT

Question: I have dedicated server (Windows Server 2012) and two network ports on NIC, my ISP gives internet connection via PPPoE. One network port is using for ISP cable, and second one for Windows 8.1 local PC.
I can share internet connection only if ISP cable goes thought router (in that case I have two lan connection on window server, and there's no problem to configure NAT with RRAS service).
Can I share windows server PPPoE connection to my local PC (like NAT) without using router?
Question similar to How can I configure Windows Server 2008 R2 to NAT while connecting to the internet with PPPoE?, but unanswered.
Answer: Okay, I solve problem why ICS is not working after sharing PPPoE adapter, all I need to do is to restart the ICS (SharedAccess) after connecting to PPPoE, then NAT is working perfectly.
Very weird ...

Windows server 2012 PPPoE share to NAT


I am playing a song in D Major, and it contains an Am. How do I notate this in roman numerals?

Question: I am learning music theory and I was told to transcribe some songs and also note the chords as roman numerals.
The song I have is in the key of D Major, but contains an A minor, which to my understanding is not part of this scale. The V of D Major would be an A Major, right?
So, I went on a google search bonanza and read some things about "altered chords". And since A Major became A Minor in my example, I guess that is what it is since it is the third that has been flattened. So, can I note this as I v IV for the progression "D Am G"?
Answer: I v IV would be correct, because what seems to be going on here is that you have 'borrowed' a chord from D natural minor scale. The v from the D natural minor is Am, and it is common to borrow chords from the parallel minor scale (scale with the same name); (the same happens when you are in the minor scale; you can borrow a chord from the major scale)
Comment: It's called the parallel major/minor.
Comment: This would be what is called a "naive" name for the chord.  There's no way to produce an accurate name without knowing the CONTEXT of the chord...i.e. chords leading up to the Am, and chords following the Am, as well as the melody across that section.   But, given the amount of information we have been given, a simple parallel minor substitution isn't a bad option.
Answer: With a lower case v
minor chords are indicated in our figured bass with smaller case roman letters and the Major chords with upper case roman letters.
So I --> i for the tonic chord
II --> ii for the super tonic chord
III --> iii for the mediant
IV --> iv for the Sub dominant
V --> v for the Dominant
Vi --> vi for the Sub mediant
and lastly Vii --> vii for the leading tone chord.
Just remember that the Major Sub dominant and Dominant chords have to have two horizontal line going above and below them. That part of the notation gets lost when we use the computer but when writing a figured bass of your own they should include it.
Comment: "Figured Bass" ??
Comment: 'Have to have the two horizontal lines'? Why? There is absolutely no reason, as they're very clear as they are. In fact, it's only in some printed copies that they do, and that's down to the printer's discretion. In fact, as you say, it gets lost on computer font - unless we go to the trouble of changing to trajan font - for what?


Stop Google Cloud Load Balancer

Question: Is there a way to stop/disable the Google Cloud Balancer?
I want to use it 8 hours a day, 5 days a week, only.
I can stop the instances but I can't stop the load balancer.
The idea here is to lower the charges.
The only way that I've found is to delete the load balancer and I will lose all the configurations.
Answer: To stop the charges for load balancing, you need to delete the forwarding rules and/or delete the load balancers themselves.
Remember, Google Cloud charges for forwarding rules whether they are created for load balancing, and for most load balancing use cases, you need only one forwarding rule per load balancer.
I might consider the low cost vs delete the load balancing:
The following examples use US pricing:
For example, if you create one forwarding rule, you are charged $0.025/hour. Entire weekend =0.025 x 64 hours =  1.6 USD
(Just for forwarding rules, it suppose no traffic because you have the VM instance stopped).
It is on the GCP's documentation
Keep safe.
Comment: It makes sense what you said. But If I could use it 5 days a week, and 8 hours a day, it will be 160 hours * 0.025 = ~ 4 USD. If I use it 24 hours for 30 days, it will be 720 hours * 0.025 = ~18 USD. It is a huge difference. I will be using 3 load balancers. If I delete the rule I will lose its configuration...
Comment: I agree, that's why you should consider spend this 14 USd versus lose the configuration and recreate every day your forwarding rule.  No way to disable or stop the LB.
Comment: Losing the configuration and recreate it every day shouldn't be a problem since I am using Terraform. But still not the best practice/solution. I will try to contact GCP support and see if there's something else I can do. Thanks for your help! :)

Stop Google Cloud Load Balancer


What kind of line is formed when a piece of paper is folded?

Question: What kind of line is formed when a piece of paper is folded?
I am 17, and I'm homeschooled. I have a book from 1958 that's called "Plane Geometry, Welchons Krickenberger Pearson" It has no answers in the back of the book.
I found this question in the beginning of the book, and I tried asking my parents, and I researched it on the internet, and I came up with no solution.
1) I need to know what the Geometry question is asking.
2) What do I need to know to solve this problem.
I would really appreciate your help. This is my first time posting on here, I will look into the posting rules in depth today. It sort of sounds like what dimension is the line.
Thank you,
Sebastian
Comment: Do you mean that "What kind of line is formed when a piece of paper is folded?" is the actual question in the book? It is completely unclear to me what that even _means_. Unless the answer is "a **straight** line" because that is what the fold itself is (assuming you lay your folded sheet of paper flat).
Comment: Welcome to the Math Stack Exchange.  Please include the question in your post.
Comment: Thank you for correcting me. I just added it :)
Comment: The question is kind of vague. Is there absolutely no more information?
Comment: Perhaps they are looking for the response "a line segment", but it could be something else too.
Comment: Perhaps it is an allusion to the dragon curve! Consider reading Jurassic Park, OP.
Comment: Could you provide a bit of context? In what regard do they talk about different kinds of lines?
Comment: Does the line change the dimension from 1D to 2D? When the paper is folded? Does it turn into a curved line?
Comment: @Aurey The 10 questions that is near this question mentions: intersection, how many lines through 1, 2, and 3 points, if two lines intersect can they intersect again, etc... :)
Answer: I suppose from common knowledge the book is trying to introduce some elementary concepts of straightness.
A straight line is formed when a piece of paper is folded. The new straight line forms along the fold with two parts of paper on either side of the fold or line.
Comment: Yes, it's introducing elementary concepts. How did you come to that conclusion? Does the line turn into a curved line?
Comment: Just guessing it as you mention it was at the beginning of book. To get to curvature  concept of a line may be you have turn some 20 pages or so more after introduction to  concepts of circle, its circumference,$ \pi$, area &c..
Comment: Thank you very much! I will move on. Very interesting! I chose your answer as the most helpful!
Comment: Welcome. More guessing than math !


Inserir dados do DataSet em banco de dados

Question: Tenho o seguinte codigo:
using System;
using System.Linq;
using FirebirdSql.Data.FirebirdClient;
using System.Configuration;
using System.Data;

namespace TblCliente
{
    public class Program
    {
        static void Main(string[] args)
        {
            FbConnection fbConnectionPrincipal = new FbConnection
            {
                ConnectionString = ConfigurationManager.ConnectionStrings["strFirebirdPrincipal"].ToString()
            };
            FbConnection fbConnectionSecundaria = new FbConnection
            {
                ConnectionString = ConfigurationManager.ConnectionStrings["strFirebirdSecundaria"].ToString()
            };

            FbDataAdapter fbDataAdapterPrimario = new FbDataAdapter("SELECT * FROM PRODUTO WHERE PRODUTO.CODPROD = '000399'", fbConnectionPrincipal);
            FbDataAdapter fbDataAdapterSecundario = new FbDataAdapter("SELECT * FROM PRODUTO WHERE PRODUTO.CODPROD = '000399'", fbConnectionSecundaria);

            DataTable dataTableP = new DataTable();
            DataTable dataTableS = new DataTable();

            fbDataAdapterPrimario.Fill(dataTableP);
            fbDataAdapterSecundario.Fill(dataTableS);

            dataTableP.Merge(dataTableS);

            var Produto = dataTableP.AsEnumerable().Distinct();

            Console.ReadKey();

        }
    }
}

Esse código trás resultados de duas base de dados distintas e inclusos em DataSet diferentes, apos isso fiz um DataSet.Merge e em cima dele foram retornados os valores distintos.
Como faco para incluir essas linhas distintas em um novo banco de dados ?
Comment: Então é só escrever o Insert utilizando a `fbConnectionSecundaria` mesmo...
Comment: Abrindo uma nova conexão e fazendo o insert?
Comment: Essa nova conexao seria a fbConnectionSecundaria mesmo!
Answer: Se já tem toda a informação armazenada no DataTable então o necessário será inseri-la na base de dados:
private void InsertData(dynamic fbCon, string table, List<(string Field, dynamic Value)> parameters)
{
    string fields = string.Join(", ", parameters.Select(r => r.Field));
    string values = string.Join(", ", parameters.Select(r => $"@{r.Field}"));
    string sql = $"INSERT INTO {table}({fields}) VALUES({values})";

    FbCommand fbCom = new FbCommand(sql, fbCon);

    foreach (var parameter in parameters)
        fbCom.Parameters.AddWithValue(parameter.Field, parameter.Value);

    fbCom.ExecuteNonQuery();
}

Este método pode ser utilizado na generalidade dos casos, e a forma de o utilizar é algo deste género:
var list = new List<(string Field, dynamic Value)>();

list.Add((Field: "price", Value: 10));
list.Add((Field: "name", Value: "teste"));
list.Add((Field: "date", Value: DateTime.Today));

InsertData(null, "products", list);


Club sets of $\omega_1$ have the same order type as $\omega_1$

Question: This is a short lemma that I've come up with that I need to prove in a solution to a homework problem. I'm sure that it's true, but I'm not sure how to prove it.
What I need to do is show that if $C \subset \omega_1$ is club, then there is an increasing bijection $f:\omega_1 \to C$.
So I should try to inductively construct this $f$. So for $0$, define $f(0) = \inf(C)$. Then, for each $\alpha + 1\in \omega_1$, define $f(\alpha +1) = \inf\{ C \setminus \{f(\beta) : \beta < \alpha\}\}$. Then if $\lambda$ is a limit ordinal, define $f(\lambda) = \sup\{ f(\beta): \beta < \lambda\}$. Since $C$ is closed, $f(\lambda) \in C$.
Does this construction work?
Comment: Yes, though depending on your instructor you might want to mention explicitly that $\sup\{f(\beta):\beta<\lambda\}<\omega_1$, so the construction does not terminate prematurely.
Comment: @BrianM.Scott Ok, thank you!
Comment: You're welcome!
Answer: That works but it's unnecessarily complicated. In fact every unbounded subset $S$ of $\omega_1$ has the same ordertype as $\omega_1$.
To see this we use a simpler version of your bijection: recursively set $f(\alpha)=\min(S\setminus \{f(\beta): \beta<\alpha\})$ for all $\alpha<\omega_1$, successor or limit.
By induction together with the fact that $S$ is unbounded you can prove that for all $\alpha<\omega_1$ the ordinal $f(\alpha)$ exists (that is, $S\setminus \{f(\beta): \beta<\alpha\}$ is nonempty and so has a minimal element) and is $<\omega_1$; this uses as a key step the fact that every countable subset of $\omega_1$ is bounded below $\omega_1$, which is a good exercise.
Comment: This is a great answer. Thank you.


Force of interest and Present value

Question: Express the present value of the sums $c_{t_{1}},c_{t_2},...,c_{t_n}$ due at times $t_1,t_2,...,t_n$ in terms of the force of interest at time $t$, denoted by $\delta (t)$.
The answer given is $$\sum_{j=1}^n(c_{t_j}exp(-\int_{0}^{t_j}\delta(s)ds)$$
Can anyone explain why and how? Thanks in advance.
Answer: First of all we may assume $n=1$ since we are just adding up the value of the sums. So we want to justify that the present value of $c$ due at time $t$ is
$$c\exp\left(-\int_0^t\delta(s)\,ds\right).$$
The present time is time 0 and the present value $x$ should evolve into $c$ at time $t$:
$$x\exp\left(\int_0^t\delta(s)\,ds\right) = c.$$
This is just expressing that force-of-interest $\delta$ is related to interest $i$ by $$e^{\delta\cdot t}=(1+i)^t,$$
and that when $\delta$ is not constant, $\delta\cdot t$ is replaced by $\int_0^t\delta(s)\,ds$.
Comment: By the way, $\exp(x)=e^x$

Force of interest and Present value


Caching vs Tempview

Question: I have a parquet file which I reading atleast 4-5 times within my application. I was wondering what is most efficient thing to do.
Option 1. While writing parquet file read it back on dataset and call cache. I am assuming by doing an immediate read I might use some existing hdfs/spark cache as part from write process.
Option 2. In my application when I need the dataset first time, after reading it cache it.
Option 3. While writing parquet file, after completion create a temp view out of it. In all subsequent usage, use the view.
I am also not very clear about efficiency of reading from tempview vs parquet dataset.
The datasets doesn't fit all into memory.
Answer: You should cache dataset (Option 2).

writing to disk will provide no improvements over Spark in-memory format
temporary views don't cache.
Comment: Here is the thing, since the data doesn't fit in memory. Spark would probably need to persist on disk. Thus if the data-nodes are on the same computing need data is local to the executor and there won't be much improvement using the caching mechanism but you can skip this if you don't feel like talking about it
Comment: You might be interested in reading this https://www.quora.com/What-are-ways-to-improve-latency-in-a-Spark-single-node-cluster/answer/Elias-Abou-Haydar?srid=agpP&share=1df7144d
Comment: Your answer is correct but I would also add a note about performance and data locality. Also why the other options are not a better choice :)
Comment: @eliasah I don't understand your comment :( Why data locality affects choice here?
Comment: I'd rather you explain why the other options aren't good thought :)
Comment: @eliasah I don't fully understand though, so lets day I have 50 gb memory available, while the dataset is something like 80GB, so when I execute a map reduce, all 80 gb of data will first read in partition and then processes. Will there any difference caching will do in that case. Do you have a recommendation for this scenario, how data locality comes in picture and how it can help. PS I am a newbie to spark so appreciate your comments.
Comment: @eliasah Thank you!!! If you think there is something missing in the answer it is wiki now.
Comment: @LostInOverflow I'll try to write something when I have some spare time.

Caching vs Tempview


Make Hikari discord bot only listen to one channel

Question: I just mada a discord bot with hikari that for now listens to a whole server, and if someone types
$shares https://tiktok.com/@xxx/2938923

It runs a script, that sends shares to that tiktok video. Because there is a lot of members in the server, The channel members are supposed to write the comand in has a cooldown. But because the bot listens to the whole server, they could just type the command in another channel without cooldown.
This is my code for now:
import hikari
import time

bot = hikari.GatewayBot(token="xxx")

@bot.listen()

async def ping(event: hikari.GuildMessageCreateEvent) -> None:
    global link
    if event.is_bot or not event.content:
        return
    if event.content.startswith("$docu"):
        await event.message.respond(f"""To send shares, write **$shares**, followed by the TikTok url.
        > Ex: **$shares https://tiktok.com/@xxx/29835027502**""")

    if event.content.startswith("$shares"):
        split = event.content.split()
        try:
            link = split[1]
            await event.message.respond(f"Sending 1k shares to <{split[1]}>")
            start_time = time.time()
            xshares()
            await event.message.respond(f"Shares Sent! | TTC > {round(time.time() - start_time, 1)}s | SPEED > {round(1100 / (time.time() - start_time), 1)}/s")

        except:
            await event.message.respond(f"Please include link!")

def xshares():
    #shares script (not relevant here)
    return
bot.run()

What can I add to this code to make it only listen to a certain channel (<#xxxxxx>)
Or should I use another discord python bot library?
Thanks for your help
Answer: GuildMessageCreateEvent has the channel_id attribute which contains the ID of the channel that the message was created in. You can use a simple if-statement guard to ensure that the command is only run in your chosen channel.
For example:
@bot.listen()
async def message_listener(event: hikari.GuildMessageCreateEvent) -> None:
    # Replace with the required channel ID
    if event.channel_id != 1234567890:
        return

Answer: import hikari
import time

bot = hikari.GatewayBot(token="xxx")

@bot.listen(https://vt.tiktok.com/ZSdUQ2dvx/)

async def ping(event: hikari.GuildMessageCreateEvent) -> None:
    global link
    if event.is_bot or not event.content:
        return
    if event.content.startswith("$docu"):
        await event.message.respond(f"""To send shares, write **$shares**, followed by the TikTok url.
        > Ex: **$shares https://tiktok.com/@xxx/29835027502**""")

    if event.content.startswith("$shares"):
        split = event.content.split(1)
        try:
            link = split[1]
            await event.message.respond(f"Sending 1k shares to <{split[1]}>")
            start_time = time.time(6:09)
            xshares(0)
            await event.message.respond(f"Shares Sent! | TTC > {round(time.time(6:10) - start_time, 1)}s | SPEED > {round(1100 / (time.time(6:11) - start_time), 1)}/s")

        except:
            await event.message.respond(f"Please include link!")

def xshares(10000000000000000):
    #shares script (not relevant here)
    return
bot.run(1000)

Comment: [A code-only answer is not high quality](//meta.stackoverflow.com/questions/392712/explaining-entirely-code-based-answers). While this code may be useful, you can improve it by saying why it works, how it works, when it should be used, and what its limitations are. Please [edit] your answer to include explanation and link to relevant documentation.


Confusion about definition of least upper bound

Question: I'm learning set theory and I got to bounded sets. I got to the following definition and I have a question about it:

The problem that I have is the quantified variable $a$. If I would write the quantified statement down it would look like this: $\forall \epsilon \in \mathbb{N}, \exists a \in A, M - \epsilon < a$. My question is wouldn't the right quantified variable $a$ be a $\forall$ as well, like this: $\forall \epsilon \in \mathbb{N}, \forall a \in A, M - \epsilon < a$. Now, with the definition from the book, I'm not fully targetting all of the elements of $A$, as I actually should since a least lower bound is targetting the whole set. So the question is, which version is right, mine or the one from the book ?
Comment: "as I actually should"  No.  You should not.  There are two aspects of least upper bound.  The "upper bound aspect", that does target all $\alpha \in A$.  ANd the *least* aspect which most certainly does *NOT* target all elements of $A$.  In fact it doesn't target *any* elements of $A$.  As lest upper bound its target are the REAL NUMBERS (nothing to do with $A$) that are all smaller than $M$.  What is is saying is "$\forall w; w< M;w$ is not upper bound.  Now its the target of $w$, *not* of $M$, that is the elments of $A$. Namely $w$ is *not* u.b. so $\exists a\in A; w< a$......
Comment: The actual statement is twofold  i) $\forall a\in A: a \le M$.  (that is "$M$ is an upper bound") and ii) $\forall w\in \mathbb R, w<M: \exists a\in A, w< a$.
Answer: There are two parts to the definition:

Upper bound: $\forall a\in A, a \le M$
Least: $\forall \epsilon>0, \exists a \in A, M - \epsilon < a$

For the "least" part, it might help to think of an equivalent statement:
$\forall \epsilon>0, \lnot(\forall a \in A, M - \epsilon \ge a)$, which says that $M - \epsilon$ is not an upper bound.  That is, there is no upper bound smaller than $M$.
Comment: No, the $\forall a$ goes only with the upper bound part.  Also, note that $\epsilon >0$ (any positive real number), not $\epsilon \in \mathbb{N}$.
Comment: I understood that. The problem that I have is with how the variable $a$ has been quantified. My problem is understanding why the variable $a$ has been quantified the way it is. Shouldn't the variable $a$ be quantified with a $\forall$ as well ? So $\forall \epsilon \in \mathbb{N}, \forall a \in A, M - \epsilon < a$ ?
Comment: I added a little bit of explanation that might help.
Comment: The least upper bound of $(0,1)$ is $1$. Why? Because for all $a\in A$ we have $a\le 1$ and for all $\epsilon >0$ the number $1-\epsilon$ is not an upper bound. Let's test that for $\epsilon =0.1$. Is $0.9$ an upper bound? No, because **there exists** $a\in A$  ($0.95$ is an example) such that $a \not\le 0.9$. It just isn't true (or relevant) that all elements $a \in A$ satisfy $a \not\le 0.9$.


GWT (Google Web Toolkit) Slider for Touch Devices such as iOS, Android Tablets and so on

Question: we develop an application for a big swiss company. The application is developed using the Google Web Toolkit (GWT) and the main devices from which the application is accessed are iPads. Therefore, we try to find a Widget (also a proprietary framework is acceptable) which helps us to implement a slider which can be used on an iPad and whereby the widget incorporates with standard GWT widgets. Any ideas?
Answer: Take a look at http://www.m-gwt.com
Its an extension to gwt for mobile devices. It is still pre 1.0 but the 1.0 release is due in a few weeks and yes it contains a slider (but much more...)


Why is the Hecke algebra commutative

Question: I am following some course notes about local representation theory. It introduces the Hecke algebra of $G=GL_n(F)$ for a non-Archimedean local field F as the space of compactly supported, bi-$K$-invariant functions on $G$, considered as an algebra under convolution.
I would like to show that this Hecke algebra is commutative. It advises to "consider the transpose map and show that it induces a map on the Hecke algebra which is both an involution and an anti-involution". However I do not see what map to consider: is it $f(g) \mapsto f({}^t g)$? (which is still $K$-invariant)
Comment: I am not familiar with the setting, but if you have an algebra $A$, and a mapping $s:A\to A$ such that 1) $s$ is an involution, i.e. $s^{-1}=s$, 2) $s$ is a ring homomorphism, $s(ab)=s(a)s(b)$ for all $a,b\in A$, and 3) $s$ is an antihomomorphism, $s(ab)=s(b)s(a)$ for all $a,b\in A$, then it does follow that $A$ must be commutative. Don't know if this fits here.
Comment: @JyrkiLahtonen Thanks for your answer, I did understand this point, and indeed this should lead to the conclusion. However, I do not see which map $s$ we are considering in this case...
Comment: Does the one you suggested work? I don't know what $K$-invariant refers to this time, but judging from similar situations elsewhere (that I'm more familiar with) it looks like a natural thing to try.
Answer: We follow Exe 5.14 of a GTM preprint by Getz and Hahn. What to be considered is indeed $f\mapsto f({}^t*)=:f^\dagger$. We show this is an anti-homomorphism. First, for $f\in C_c^\infty (G)$, we have
$$
\int f(g)dg = \int f({}^tg^{-1})dg.
$$
This is because sending $f$ to the RHS of the above is left invariant, and because the above is true for $f = \mathbf 1_{GL_n(\mathcal O_F)}$.
By the above, for $f_1, f_2\in C_c^\infty (G)$ and $g\in GL_n(F)$, we have
$$
(f_1*f_2)({}^tg)=\int f_1(h)f_2(h^{-1}{}^tg)dh = \int f_1({}^th^{-1})f_2({}^th{}^tg)dh = \int f_1({}^tg{}^th^{-1})f_2({}^th)dh = (f_2^\dagger*f_1^\dagger)(g).
$$
In place of proving that $\dagger$ is a homomorphism on $C_c^\infty(GL_n(F)//GL_n(\mathcal O_F))$, we show that $\dagger$ is the identity here. Fixing a uniformizer $\pi\in\mathcal O_F$, notice
$$
GL_n(F) = \bigcup_{a_1\geqq a_2\geqq\dots a_n} GL_n(\mathcal O_F)\mathrm{diag}(\pi^{a_1},\dots, \pi^{a_n})GL_n(\mathcal O_F).
$$
This is because for an arbitrary $A\in GL_n(F)$, we can arrange that $A_{11}$ has the largest absolute value by the multiplication of elementary matrices on both sides, conduct the Gaussian elimination with respect to $A_{11}$, and then continue.
Now, $\dagger$ is the identity on $C_c^\infty(GL_n(F)//GL_n(\mathcal O_F))$ since the same is true on the set of diagonal matrices.
Comment: Yes, this is the classic argument, perhaps attributable to Gelfand and Kazhdan. Yes, it uses something non-trivial about the group! Nevertheless, quasi-amazingly, an analogous fact holds for all the reductive $p$-adic groups I know (or maybe "care about" :) so it turns out to be a generally useful argument.

Why is the Hecke algebra commutative


Primary key is not generated in JPA with app engine Java

Question: I have entity class "User" as shown below but its not generating primary key. I am using JPA in my app engine application and using app engine endpoints in my android client.
Enitty class:
@Entity
public class UserMaster {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long userId;

    private String userName;
    private String fullName;
    private String userAvtarUrl;
    private String userAbout;
    private String userGender;

    public String getUserName() {
        return userName;
    }

    public Long getUserId() {
        return userId;
    }

    public void setUserId(Long userId) {
        this.userId = userId;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getFullName() {
        return fullName;
    }

    public void setFullName(String fullName) {
        this.fullName = fullName;
    }

    public String getUserAvtarUrl() {
        return userAvtarUrl;
    }

    public void setUserAvtarUrl(String userAvtarUrl) {
        this.userAvtarUrl = userAvtarUrl;
    }

    public String getUserAbout() {
        return userAbout;
    }

    public void setUserAbout(String userAbout) {
        this.userAbout = userAbout;
    }

    public String getUserGender() {
        return userGender;
    }

    public void setUserGender(String userGender) {
        this.userGender = userGender;
    }
}

Endpoint persistence code :
@ApiMethod(name = "insertUserMaster")
    public UserMaster insertUserMaster(UserMaster usermaster) {
        EntityManager mgr = getEntityManager();
        try {
            if (containsUserMaster(usermaster)) {
                throw new EntityExistsException("Object already exists");
            }
            mgr.persist(usermaster);
        } finally {
            mgr.close();
        }
        return usermaster;
    }

Android client
Userendpoint.Builder builder = new Userendpoint.Builder(
                        AndroidHttp.newCompatibleTransport(),
                        new JacksonFactory(), new HttpRequestInitializer() {
                            public void initialize(HttpRequest httpRequest) {
                            }
                        });

                Userendpoint endpoint = CloudEndpointUtils.updateBuilder(
                        builder).build();

                User objUser = new User();

                objUser.setUserName(txtName.getText().toString());
                objUser.setUserEmail(txtEmail.getText().toString());

                Bitmap bmp = BitmapFactory.decodeFile(imagePath);
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                bmp.compress(Bitmap.CompressFormat.PNG, 100, out);
                byte[] imgByte = out.toByteArray();
                String encodedImage = Base64.encodeToString(imgByte,
                        Base64.DEFAULT);
                objUser.setImage(encodedImage);

                User result = endpoint.insertUser(objUser).execute();

Please guide me where i am lacking. Thank you.
Answer: If using JPA and GAE/Datastore either use all JPA annotations, or all as a vendor-extension use all JDO annotations. You cannot mix and match.
Comment: Yes, you are right. I was mixing JPA and JDO but now i am just using JPA but then also its not working. I edited my code.
Comment: But "not working" doesnt really tell us much. The log will tell you a lot about what is sent to the datastore (and you present no actual JPA persistence code either). An object after persist will have an id (whether that is 0, or some other value) and you can print that out too. But when debugging the LOG should be your first point of call
Comment: if i don't set `userId` then it doesn't insert record in DB and i don't want to set my id programatically. I want that it should be autogenerated. I have already posted my entity persist code which i am using from android client.
Comment: I'm talking about JPA persist code, which maybe is hidden by this EndPoint stuff, but at the end of the day nobody here knows what that is calling. As already mentioned, the LOG is where you should look (when you have it set to IDENTITY).
Answer: May be your database server does not provide the auto id generation.
IDENTITY

IDENTITY, it is depend on the Database to auto generate.
Some DB Server Like, MySQL or Microsoft SQL Server do provide ID generation for the primary key field during insertion.

The common way is to use the IdGeneratorStrategy.TABLE. It is not depend on DB.
Answer: In my case problem was in method "containsUserMaster(usermaster)"
Method check existing in way like this:
UserMaster item = mgr.find(UserMaster.class, userId);

Problem that until add operation not complete, userId will be null, and because program stops with NullPointerExeption..
I'm add userId checkinq on null - and this solves the problem


Where does "Uniform" in "Uniform central limit theorem" come from?

Question: We may all know about the CLT. Today I have seen two articles where the use a new term (to me), that is "Uniform central limit theorem".

A uniform central limit theorem and efficiency for deconvolution estimators

Empirical Processes in M-Estimation

My question is that where the word "uniform" come from? Does it come from "uniform Donsker class"?
Comment: Can you please include the full citations for the articles? Thanks!
Answer: Uniform Central Limit theorems relate to functional extensions of the classic central limit theorem (extending from application to single valued random variables to random functions). They are about the convergence of random functions. For instance think about a the Wiener process as a limit of a random walk. With a random walk we do not deal with the convergence of a single random value, but with the convergence of an entire function (the entire walk).
Uniform relates to uniform convergence.
See also

The Glivenko Cantelli theorem, which is about a uniform law of large numbers (more specifically the case of convergence of the empirical distribution to the true distribution function). The theorem proves that this convergence is not just pointwise, but also uniform.

Donsker's theorem, which states that a scaled random walk converges uniformly in distribution to a normal distribution.

There is a whole book written about this topic.
Dudley, Richard M. Uniform central limit theorems. Vol. 142. Cambridge university press, 2014.
Comment: May I ask to understand something? 1. "functional" in "functional extensions" is an adjective, it is not a noun referring to functional in "functional analysis"? 2. Do you mean "random functions"=stochastic process (as you mentioned Wiener and random walk processes)? 3. Is it correct that classical limit theorems are applied to a sequence of random variables, while theorems that you mentioned are applied to stochastic process? 4. Am I correct that both empirical process (a) and empirical measure (b) are extensions of empirical distribution function. Could you help to differentiate (a) and (b)?
Comment: **1** functional refers to 'application to functions' **2** 'random function' refers to stochastic process. **3** yes, it applies to a sequence of stochastic processes **4** I do not understand what you mean by *"empirical process (a) and empirical measure (b)"*.
Comment: Thank you for your clarification! For point 4, I think I will make a new question because they are far from the original question (although related, I guess).


Polynomials with high probability resulting in primes

Question: Are there polynomial functions $p:\mathbb N\to\mathbb N$ which increase the probability of resulting in a prime value further than the increment from the polynomials $p_1(n)=n$ to $p_2(n)=2n+1$?
Comment: How about the polynomial of degree $0$, $p(n)=2$?
Comment: @BarryCipra: Nice! But of higher degree then.
Answer: For $n$ from $0$ to $N$, $6n+1$ or $6n-1$ has about $3/2$ as many primes as $2n+1$.
Comment: How do you know that?
Comment: @Lehs https://en.wikipedia.org/wiki/Prime_number_theorem#Prime_number_theorem_for_arithmetic_progressions


Is it possible for a router misconfiguration to cause a telephone line fault/issue?

Question: I apologise if this is posted in the wrong stackexchange but I am currently in the process of building and testing a router running pfSense.
Having recently had a line fault, the BT Openreach engineer that did the repair told me of the huge cost implications of a subscriber causing the fault. As such, I began to question whether or not a router misconfigured with either a software or hardware fault/issue could cause issues on the telecomms network externally. This does seem absurd to be, surely the network should be pretty well protected against router issues and only the subscriber would be knocked offline should an issue arise but I wanted to be absolutely certain.
Comment: First sentance was right.  it is a wrong stackexchange site. Not sure where it does fit though.
Comment: @Hennes I assumed since Serverfault is mostly for Server and Networking that this'd be a fit. If anyone does have a suggestion for where I should ask though, I'd happily ask somewhere else.
Comment: Hardware issue can always happen. I hope their equipment is secure from that. Software/routing issues should not propagate to an providers network anyway. (though an error can obviously result in a network setup which does not work on your side. But it should not take down or disturb the provider.  Having written that. BGP can result in 'fun'.
Comment: I would assume they'd have a pretty resilient network, especially considering isolated faults don't _usually_ take down an entire exchange.
Comment: I was going to mention BGP but realistically if nobody is peered with you, you can advertise what you want and who cares? I suspect most competent ISPs will block BGP traffic if they are not expecting it anyway.
Comment: Thanks for the clarification. I might have do some reading into BGP
Comment: It's an interesting topic to read around but you shouldn't need to actually touch it for a small premises internet connection.
Answer: You're not going to be able to cause physical line faults by misconfiguring the software on your router. I suppose if you physically shorted out the pins in the telephone socket you may trip something out in the exchange, but you're unlikely to be doing that.
The worst you can probably do with software misconfiguration is temporarily break your own internet access.
Comment: I should be up and running on a FTTP installation soon, although that was promised over a year ago (part of a fibre upgrade scheme run by the government). I will likely be using an external modem in that case so there  should be no issues. Thanks!


Design decision regarding std::array fill

Question: std::array in C++11 is a useful class that provides a C++ Container interface over a C stack array.
But why does std::array not have the typical fill constructor that most containers have? Instead, it has a method fill.
Is there some reason why std::array is unique among STL containers in this regard?
Comment: @Channel72: POD: *"A POD struct is a non-union class that is both a __trivial class__ and a standard-layout class [...]"*. trivial class: *"A trivial class is a class that has a default constructor (12.1), has no __non-trivial default constructors__, and is trivially copyable."* However, `std::array` is an aggregate, and such have to follow similar rules (see Borgleader's answer).
Comment: Because otherwise std::array wouldn't be a POD anymore.
Comment: I thought C++11 relaxed the definition of POD
Answer: From section 126.96.36.199:

An array is an aggregate (8.5.1) that can be initialized with the syntax
  array a = { initializer-list };

If it worked like std::vector it wouldn't be a POD anymore. Additionally from the same section:

The conditions for an aggregate (8.5.1) shall be met.

These conditions are:

An aggregate is an array or a class (Clause 9) with no user-provided constructors (12.1), no brace-or-equalinitializers
  for non-static data members (9.2), no private or protected non-static data members (Clause 11),
  no base classes (Clause 10), and no virtual functions (10.3).
Answer: Yes; std::array is meant to be an aggregate (C++11 §8.5.1) so that at can be used in as many contexts as possible where a plain array can be used. An aggregate can have no explicit constructors or destructor.
Answer: Everybody's explained the "why" pretty well I think, so I'll just put up a workaround suggestion, which should compile to be just as good as a native constructor:
template< typename T, std::size_t n > std::array<T,n> filledArray( const T& v ) {
    std::array<T,n> r;
    r.fill( v );
    return r;
}

auto arr = filledArray<int,4>( 7 );

Comment: Hm, any reason for not using a for-range loop? Just curious.
Comment: Or the `fill` member function?
Comment: also @Zeta, only because I keep forgetting it exists. Changed to use `fill` because it makes more sense and is more likely to have optimisations.
Comment: @Dave: Completely forgot `fill()` during the discussion about PODs and aggregates, doh.


Combobox drops up in IE 8 and it works correctly in IE 6

Question: I have a simple select/combo box with 100 options in the middle of a HTML page. When I open it in IE 6 it appears fine dropping down with a few elements displayed and a vertical scroll bar.
In IE 8, it opens upward. Looks like it drops down till it reaches edge of browser screen when it has few options and then opens upward for new options added with a vertical scroll bar.
Is there a way the select box can be adjusted to appear in IE 8 similar to IE 6?
Thanks
Ravi
Comment: A link or a few screenshots would be very useful.
Answer: This is down to the browser/os that your site is being viewed on - you can't control this, bar writing a custom javascript select box, which I personally don't like.  Let the OS control how the form entry fields look and live with it.


AppleScript: match and delete files in folder

Question: My photo camera allows to save pictures in RAW and JPG in parallel. I find this convenient because on my Mac I can quickly browse the JPGs and delete the "bad" ones. Besides, I keep the RAW files of the "good" JPGs in case I need to do some deep editing.
I would like to write an AppleScript which deletes all the "bad" RAWs (RAW files which don't have a corresponding JPG anymore). All files are in the same directory.
This is my outline (far away from correct syntax!):
tell application "Finder"
  set source_folder to choose folder with prompt "Please select directory."
  my clearFiles(source_folder)
end tell

on clearFiles(source_folder)
  set theItems to ""
  tell application "System Events"
    set theItems to get the name of every disk item of source_folder
  end tell
  repeat with theFile in theItems
    if the extension of theFile is "raw" and exists name of theFile & ".jpg" then
      tell finder
        delete (name of theFile & ".raw") in source_folder
      and tell
    end if
  end tell
end clearFiles

Answer: try this
set source_folder to choose folder with prompt "Please select directory."
tell application "Finder"
    set rawFiles to every file of source_folder whose name extension is "raw"
    repeat with aFile in rawFiles
        set baseName to text 1 thru -5 of (get name of aFile)
        set jpgFile to baseName & ".jpg"
        if not (exists file jpgFile of source_folder) then delete aFile
    end repeat
end tell

Comment: that's what the OP wants: _deletes all the "bad" RAWs_. And it's not that dangerous: all deleted files are in the trash


jQuery nextUntil() stops at closing tag

Question: I am trying to grab all the td elements between the first two that have the class 'selected'. and change the text color to green. I am using nextUntil but the problem I am facing is that when there is a new
 it doesn't grab those td elements. Is there a way to ignore any
 tags using nextUntil? Thanks
jQuery:
var firstDate = $('table.jCalendar tbody').find($('td.selected')[0]);
var secondDate = $('table.jCalendar tbody').find($('td.selected')[1]);
$(firstDate).nextUntil(secondDate).css("color", "green");

HTML:

   18
   19
   20
   21
   22
   23
   24

   25
   26
   27
   28
   29
   30
   31

so to clarify i want the td elements with the texts 20 through 26 selected but 21 through 24 is only being selected. Sometimes there are more then just one set of
 tags between the td tags with the class selected.
Comment: `.nextUntil(` check `siblings` only. `25,26` aren't siblings of first `.selected`.
Comment: Are they always layed out consecutive in rows with the same number of td's in each?
Answer: My understanding is to highlight every TD regardless of row between the 2 selected class.
Am using a class change instead of inline CSS as it is much easier to remove on subsequent selections with one line of code.
DEMO: http://jsfiddle.net/5txeq/
var firstRow = $('td.selected:first').parent()
var secondRow = $('td.selected:last').parent();

$('tr').slice(firstRow.index() + 1, secondRow.index()).find('td').addClass('green')

firstRow.find('.selected').nextAll().andSelf().addClass('green')
secondRow.find('.selected').prevAll().andSelf().addClass('green')

Alternate  shorter version:
DEMO: http://jsfiddle.net/5txeq/2/
var $cells = $('tbody td'),
    idx_1 = $cells.index($('td.selected:first')),
    idx_2 = $cells.index($('td.selected:last'));

$cells.slice(idx_1, idx_2 + 1).addClass('green');

Comment: if need to adjust so green class doesn't conflict with selected class, just adjust the 2 index variables in slice()
Answer: Not really; that's how nextUntil is designed. You'll need to create an each loop that runs through all the  tags in order:
var color_it = false;
$('table.jCalendar tbody').find('td').each(function() {
    var $this = $(this);
    if $this.is(firstDate) {
        color_it = true;
    };
    if $this.is(secondDate) {
        color_it = false;
    };
    if (color_it) {
        $this.css("color", "green");
    };
});

For what it's worth, you could also replace your table cells with
 tags which have display: table-cell; styles attached. Then they would all be siblings. However, this isn't supported in older browsers.
Answer: In this method you select all the cells and filter out the ones before and after the selection
var selectStart = false;
$('table.jCalendar td').not(function() {
    if ($(this).hasClass('selected')) {
        selectStart = !selectStart;
    }
    return !selectStart;
}).css({color:'green'});

FIDDLE

jQuery nextUntil() stops at closing tag