Offset in Logistic regression: what are the typical use cases?

Question: Offset is commonly used in Poisson regression to take into account different exposure (different time periods for instance): offset = log of exposure
Question: what's the typical use case of offset in logistic regression?
I assume we can't do exposure (proportional effect) in classification problems since E(y|x) can't go beyond 1 so I'm curious about why someone would need to use offset in a logisic regression.
Comment: @Frank Harrell:  He is probably a computer type, google "use case" almost all hits are computer things ...
Comment: Why "use cases" and not "examples"?
Answer: I sometimes use an offset in a logistic regression model.  The use case is where I already have a complex model, which needs to be re-estimated to cover some new data outside the realm of the original data sample (in time, or in cross section), but where, for various reasons, it is practically infeasible to re-estimate the model on the entire, expanded data set.  The goal is a new model that gives good predictions on some out-of-sample data, but which gives unchanged predictions on the in-sample data.
So I take the linear predictors from the original model, specify those as an offset, and then introduce additional variables aimed at fitting the new data, in such a way that it wouldn't change the predictions on the original data.
It's admittedly ad hoc, but an awfully useful trick in practice.  I have no idea what the "legitimate" use of an offset in logistic regression is, but I'm glad statistical software packages allow for it.
Answer: You include an offset when you know what the coefficient of that variable should be. Typically software fixes it at unity. As you point out in Poisson regression this is often used to include the effect of the denominator when we assume that if we multiplied the denominator by a factor we would also multiply the outcome by the same factor.
One case where an offset might be used outside the Poisson special case is when you have a hypothesised value for the coefficient from theory of previous studies. If you then include your predictor variable in the regression multiplied by the theoretical value and as an offset this will have the effect of including it with the theoretical value of the coefficient. If you also include the predictor as a standard regressor you will see from testing its coefficient against zero whether the offset is sufficient (so the theoretical value is supported) or whether you can reject that.
Answer: When the model is based on oversampled data, offset is used to correct the bias. An alternative is to use weights argument. Note however that offset produces correct probabilities by changing the intercept, usually a judgment based override. On the other hand, weights produces correct parameter estimates by countering the effect of oversampling, as if the model was based on correctly sampled data.
Answer: There are a variety of uses for offsets in logistic regression, whether for specific factors or the outputs of other models.
For specific factors, they may be included or excluded from the final implementation. Included, if the goal is fix them in the final model, whether to force assumptions (based upon past experience) or restrict influence.  Excluded, if the goal is to control for those factors {maturity effect, disparate impact}.
For model outputs they can be i) part of a full development process to stage in groups of variables; ii) to incorporate new data sources in new samples without affecting the original model; iii) to validate a model's ranking abilitys pre- or post-implementation.
Comment: The question is about the use of offsets but your answer does not appear to mention them at all.
Comment: All of the points mentioned relate to offsets.  I have submitted an edit.  Something not mentioned was that they can also be used as an alternative to weights when adjusting for different sampling rates, albeit with some intermediary calculation to express the weight differential as a natural log of odds.


How to properly notate scales that are not heptatonic

Question: As far as I understand Scales are defined on intervals. So, for example, the major scale is defined by the following intervals from the root:
C - Root
D - Major Second
E - Major Third
F - Perfect Fourth
G - Perfect Fifth
A - Major Sixth
B - Major Seventh

This is perfectly clear to me, and it makes sense, because we have 7 note names, so every note must be included on the scale, but then when trying to figure out the proper name notes for an octatonic scale it becomes blurry to me. I mean when building an octatonic scale you only stack Tone-Semitone-Tone-Semitone...
But how do I properly define the Note names??
For the semitone spacing the interval could either be a augmented prime, a minor second, or even a doubly diminished third.
For the tone spacing the interval could be a doubly augmented prime, a major second or a diminished third.
How do I find the proper note names for non heptatonic scales?
Does the same rules apply for the chromatic scale?
Answer: In heptatonic scales, we have one instance of each note name, because there are seven note names. But you're correct: if the scale doesn't have seven tones, some note names will need to be repeated or omitted.
Octatonic ("diminished") scales have been addressed in Notating the diminished Scale
The same stipulations discussed in that question apply in other non-heptatonic scales: some composers prefer to write exclusively with flats or sharps, and composers often aid our understanding of a tonal center by how pitches are spelled.
But there's one additional stipulation that I can think of that applies to your question. Let's imagine we're writing a hexatonic scale, often understood as a half-step pattern of 3 1 3 1 3 1:

This looks like a great way to notate this, and it is: we have no repeated note names, and we only omit the F. This is what mathematicians might call a "maximally even" distribution of note names, meaning it's as evenly spread as possible, considering one note name must be missing.
But let's look closer at this collection. It contains the following triads:

CM
Cm
EM
Em
A♭M
G♯m

Sometimes, composers writing hexatonically like to highlight the juxtaposition of two harmonies. And if they want to highlight the mixture of, say, the C minor and E major triads (what we call hexatonic poles, because combined they create a hexatonic collection), a composer may well choose to notate this collection as:

Even though the two versions of E and G look awful, the notation makes clear the juxtaposition between the C minor and E major triads.
In short: depending on the musical situation, some composers (though not all!) may choose to use notation that looks less than ideal because it illustrates the musical process more clearly.
Comment: Thanks for your answer @Richard, So I think the note naming in non heptatonic scales is not as relevant as in heptatonic scales, though as you said it is clearer to the reader the juxtaposition of the triads.
Comment: Which goes a little way to answering my last question!


Trying to create a horizontal centered menu

Question: I am trying to create a horizontal centered menu but it appears vertically centered after adding bootsrap css codes.
this is the css code of my application

@media (max-width: @screen-xs) {
  body {
    font-size: 10px;
  }
}
@media (max-width: @screen-sm) {
  body {
    font-size: 14px;
  }
}
h2 {
  font-size: 300%;
  margin-bottom: 0px;
  clear: both;
  margin-left: 7px;
}
h5 {
  margin-top: 0px;
  padding: 0px;
  margin-left: 15px;
  color: #fff;
  margin-bottom: 1px;
  clear: both;
}
hr {
  margin: 0px;
}
.container {
  width: auto;
  margin-left: 200px;
  margin-right: 200px;
  height: 500px;
  max-height: 500px !important;
  padding-left: 0px;
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" crossorigin="anonymous">

Header

... caption

Mission

About Us

Grants

News

Please how can I horizontally align the menus to the center
Comment: You mean, you want nav in inline? `Mission - AboutUs - Grants`
Comment: Yes with the hover effect applied to only color of the menu text
Comment: [ https://jsfiddle.net/tjbaezid/325503tm/2/ ] is that you looking for ??
Answer: You need to set your li's to line up with inline-block and then center it.
https://jsfiddle.net/x1w2ewt8/
.nav.sf-menu li {
  display: inline-block;
  text-align: center;
}

Answer: If you're using bootstrap, make sure to use container and row classes.
The code below will align the links horizontally if you zoom out far enough.

I've reduced the left and right margins for the container from 200px to 10%.
I've set each link to have a column width of 1 using col-sm-1 The first element was offset (so the links are centered) using col-sm-offset-4. Remember, bootstrap uses 12 columns in total.
I've used text-align: center in #main_menu to make it look nicer.

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
crossorigin="anonymous">

Header

... caption

Mission

About Us

Grants

News

Comment: The gaps between the menu is much
Comment: I've reduced the column size from 3 to 1.
Answer: You can set text-align:center for your parent div
Answer: Try this css, li is taking display:block if you want to set all li in a line you need to set display: inline-block;

@media (max-width: @screen-xs) {
  body {
    font-size: 10px;
  }
}
@media (max-width: @screen-sm) {
  body {
    font-size: 14px;
  }
}
h2 {
  font-size: 300%;
  margin-bottom: 0px;
  clear: both;
  margin-left: 7px;
}
h5 {
  margin-top: 0px;
  padding: 0px;
  margin-left: 15px;
  color: #fff;
  margin-bottom: 1px;
  clear: both;
}
hr {
  margin: 0px;
}
.container {
  width: auto;
  margin-left: 200px;
  margin-right: 200px;
  height: 500px;
  max-height: 500px !important;
  padding-left: 0px;
}
.nav>li {
    position: relative;
    display: inline-block!important;
 }
.nav>li>a:focus, .nav>li>a:hover {
    text-decoration: none;
    background-color:transparent!important;
  color:red;
}
.nav>li>a {
    padding: 10px 8px!important;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" crossorigin="anonymous">

         Header

... caption

Mission

About Us

Grants

News

Comment: can I close the gaps between the menus a bit and apply the hover effect to the menu text alone
Comment: all you have to do is add padding to increase/decrease the gaps between the words
Comment: I mean like Mission | Grants >>>> between Mission and Grants the spacing is much
Comment: Take a look, I have updated ans, you need to remove padding in `.nav>li>a` to reduce gap,
Comment: I am trying to add vertical lines between the menus but the vertical lines are not centered
Comment:
Mission |
About Us |
Grants |
Grants
Comment: Use `border-right` or `border-left`  to give vertical lines.


how to sort results based on pivot table in laravel

Question: i have three table like this :

tour (id name) -> assume (id:1 , name : something)
meta (id key) ->assume (id:1 , key: tour_duration)
meta_tour (tour_id meta_id value) ->assume (tour_id:1 , meta_id:1 , value: 15)

it's ManyToMany relationship.
i want to sort tours based on meta value in meta_tour table like this :
tours orderBy tour_duration.value

Update
i tried this :
        Tour::with(['metas' => function ($query) {
        $query->where('key', 'tour_duration')
        ->orderByDesc('value');
        }])->paginate(15);

and this :
        Tour::with(['metas' => function ($query) {
        $query->where('key', 'tour_duration');
        }])->orderByDesc('value')->paginate(15);

and this :
        Tour::whereHas('metas' , function ($query) {
        $query->where('key', 'tour_duration')
              ->orderBy('value', 'desc')
        })->paginate(15);

but not working.
Comment: There is a little problem: You are trying to get a list of tours, but as you can have more than one meta per tour, you'd end up with lists where you have a duplicitiy of tours, and (I think) you cannot get this unless you query it up with a join
Comment: Thanks, can you show me a example of join? i'm new with this and i don't know how join tables based on my problem.
Comment: Do you want to get tours with multiple `meta_tour` entries multiple times? Or just once?
Comment: i want get all tours who have meta name "tour_duration".(each tour has one tour_duration) and sort tours with tour_duration value.
Answer: You can use the withPivot method to order by a pivot table column:
// Tour model
public function meta () {
    return $this->belongsToMany(Meta::class)
                ->withPivot('meta_tour')
                ->orderByDesc('meta_tour.value');
}

Update
To only get the meta with tour duration, try eager loading and adding a where clause on the meta:
$tour->with(['meta' => function ($query) {
    $query->where('key', 'tour_duration');
}])->orderByDesc('meta.value')->get();

Comment: it's not working .. i want sort by tour_duration value not every items value.
Comment: I added another example that would limit the meta being queried.
Answer: You can use a modified withCount():
Tour::withCount(['metas as tour_duration' => function ($query) {
    $query->select('meta_tour.value')->where('key', 'tour_duration');
}])->orderByDesc('tour_duration')->paginate(15);

This uses a subquery to get the value from the pivot table:
select `tours`.*,
  (select `meta_tour`.`value`
   from `metas`
   inner join `meta_tour` on `metas`.`id` = `meta_tour`.`meta_id`
   where `tours`.`id` = `meta_tour`.`tour_id`
     and `key` = 'tour_duration') as `tour_duration`
from `tours`
order by `tour_duration` desc

Answer: Try:
Tour::join('meta_tour', 'meta_tour.tour_id', '=', 'tour.id')
    ->join('meta', 'meta_tour.meta_id', '=', 'meta.id')
    ->where('meta.key', '=', 'tour_duration')
    ->orderBy('meta_tour.value', 'DESC')
    ->get();


Export RadGrid with CSS Style

Question: Iam Trying to Export my RadGrid to Pdf in the same CSS Style of the Grid...
here is my approach:
<ExportSettings IgnorePaging="true" OpenInNewWindow="true">
   <Pdf PageHeight="162mm" PageWidth="600mm" PageTitle="Payment Orders" DefaultFontFamily="Arial Unicode MS" Title="Payment Orders"
                PageBottomMargin="50mm" PageTopMargin="35mm" PageLeftMargin="150mm" PageRightMargin="50mm" Author="AbdanSoftware" PaperSize="A4" />
</ExportSettings>

Any way from Code-behing or ClientSide to do it..
Answer: You can set export settings for you RadGrid like so:
RadGrid1.ExportSettings.FileName = "File Name"
RadGrid1.ExportSettings.ExportOnlyData = True
RadGrid1.ExportSettings.IgnorePaging = True
RadGrid1.ExportSettings.OpenInNewWindow = True
RadGrid1.ExportSettings.Pdf.PageHeight="162mm"
RadGrid1.ExportSettings.Pdf.PageWidth="600mm"
RadGrid1.ExportSettings.Pdf.PageTitle="Payment Orders"
RadGrid1.ExportSettings.Pdf.DefaultFontFamily="Arial Unicode MS"
RadGrid1.ExportSettings.Pdf.Title="Payment Orders"
RadGrid1.ExportSettings.Pdf.PageBottomMargin="50mm"
RadGrid1.ExportSettings.Pdf.PageTopMargin="35mm"
RadGrid1.ExportSettings.Pdf.PageLeftMargin="150mm"
RadGrid1.ExportSettings.Pdf.PageRightMargin="50mm"
RadGrid1.ExportSettings.Pdf.Author="AbdanSoftware"
RadGrid1.ExportSettings.Pdf.PaperSize="A4"

Edit: To include css in your export you can do so in the HTMLExporting event for Word and Excel formats. For PDF exporting only inline styles are applied.
Private Sub RadGrid1_HTMLExporting(sender As Object, e As Telerik.Web.UI.GridHTMLExportingEventArgs) Handles RadGrid1.HTMLExporting
    Dim css As String = "body { color: red; }"
    e.Styles.Append(css)
End Sub

Take a look at this documentation for more help on Word/Excel export, and this documentation for PDF export help.
Comment: You got me wrong ... the ExportSettings in my question code doesn't have a property to export Grid with the same grid CSS.. So Is there is any way to Import my grid CSS and apply it to the Exported Pdf file also....

Export RadGrid with CSS Style


Preenchimento de input com o dia da semana de acordo com a data no input anterior

Question: Criei dois inputs. O primeiro atribuí a data já pré-preenchida desta forma:
Data Reserva
<input type="date" id="Data" name="Data" value="<?php echo date("Y-m-d");?>"/>

Pretendia que o segundo input preenchesse o dia da semana de acordo com a data que seleccionei no input anterior:
Dia da Semana/Utilização
<input type="text" id="Dia" name="Dia" style="width:220px"/>

Answer: Pode utilizar um evento change no input da data e inserir o dia da semana no outro input sempre que você alterá-lo.
Mas você deverá utilizar o objeto Date() para extrair o dia da semana da data no input. No caso eu fiz um split na data, que está no formato aaaa-mm-dd, para construir o objeto Date(ano, mês, dia), e com .getDay() se obtém o valor numérico referente ao dia da semana, que é puxado o nome segundo a posição na array:
$(function(){

   $("#Data").on("change", function(){

      var d = this.value.split("-");
      var data = new Date(d[0], d[1]-1, d[2]).getDay();
      var dia_semana = ['DOM', 'SEG', 'TER', 'QUA', 'QUI', 'SEX', 'SÁB'][data];
      $("#Dia").val(dia_semana);

   }).change();

});

Exemplo de funcionamento:

$(function(){

   $("#Data").on("change", function(){

      var d = this.value.split("-");
      var data = new Date(d[0], d[1]-1, d[2]).getDay();
      var dia_semana = ['DOM', 'SEG', 'TER', 'QUA', 'QUI', 'SEX', 'SÁB'][data];
      $("#Dia").val(dia_semana);

   }).change();

});

Data Reserva
<input type="date" id="Data" name="Data" value="2019-04-23"/>

Dia da Semana/Utilização
<input type="text" id="Dia" name="Dia" style="width:220px"/>


How to show pager in terms of views of tags?

Question: I've lists of tags suppose good and bad, now when I click to good tag it lists all good posts ( full posts ). But I wanted to show good posts only upto 5 items then all other should be there while I navigate.
So, how can I show the pager for the clicked tags. I tried it with views module, but nowhere I could see it to do this.
I've setup my views like this:
Comment: Could you post a screenshot of how you setup your view?
Comment: @PontusNilsson updated.
Comment: Looks like you forgot to check the checkbox "Use a pager"?
Comment: @PontusNilsson That pager is for tags itself(how many tags should be displayed). But I wanted to show pager when I click to the tags.
Comment: Create a view of content with pager and pass the term id as contextual filter.
Comment: @wolverine could you please add the pictures to do the steps.
Answer: Create a view of content ( as a page with pager ) and add a contextual filter named Content: Has taxonomy term ID. Refer the images below.

Once you have configured this then you can acces this view using a url like mysite.com/view-path/tag-name.
Comment: Is that in 7? I can't see that.
Comment: Yes, else you can follow the answer provided by @Bhuvana. Which will be easy for you.
Comment: Her answer is correct and views provide a view to list content based on taxonomy term.
Comment: and is the second image for tags view?
Comment: all the images are for the single contextual filter that you create.
Comment: all for content pager? and what to do in taxonomy terms views?
Comment: You display the term name and rewrite the result to create a link to the content view like `content-view-path/[term-name-token]`
Comment: all steps as per the images I did but couldn't get.....
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/15153/discussion-between-wolverine-and-navin-rauniyar).
Comment: The last step I was modifying was not working and by removing and adding again worked fine. Thank you very much again.
Comment: I think you could answer this question. http://drupal.stackexchange.com/questions/118689/how-to-show-view-item-by-trimming
Answer: Views module provides a view for Taxonomy terms to cater to the requirement of displaying articles related to a tag.
Under Structure -> Views look for the view "Taxonomy term" and enable it in case it is disabled. You do not need to create a view for this purpose.

The taxonomy page by default has the pager configured with 10 items per page.You may edit it by clicking on the edit option of the view and editing the pager option as shown in the screenshot here.
Comment: Thank you Bhuvana for your reply, but that's not what I wanted.


Import csv files containing data with commas into MySQL

Question: I have more than 10GB .csv files. I m trying to import the data from these files into MySQL using python. Since csv files are comma separated files, and I have data which itself contains commas, therefore I can not use ',' here for splitting. There please suggest some other option
for splitting the csv file.
I want to import the data from the csv file(where the data itself contains comma) to MySQL (i am using Wamp server for the same).
I have data like 'london, u.k.', '2010', 'credit, saving'
Comment: maybe if you provide example of the data we can think of something.
Comment: i have provided the example data in the question :)
Answer: A good answer has been provided for importing using Python. But I'm unclear as to why you need Python to do it. MySQL has built-in commands for importing CSV data---see the load data manual page. For example,
LOAD DATA LOCAL INFILE 'source_data.csv'
INTO TABLE my_table
FIELDS TERMINATED BY ','
OPTIONALLY ENCLOSED BY '"'
IGNORE 1 LINES;

That last part ignores the first line (use if your CSV file has a "header").
Comment: @user869790, well, the "optionally" part indicates that there doesn't always have do be double-quotes around the field. If you want to see what encloses your fields, you could open the file and look through the data before running the `LOAD` command on it.
Comment: Thanks a ton for helping. But since I am a novice, i don't know whether my csv file(which i am viewing in xls) is enclosed by quotes, also my data has comments, so I think there must be quotes in it, the data is just like stackoverflows data, which i converted to csv for storing into database. Can u please give me a clue so that i may check the enclosing symbol. Thanks again for helping
Comment: Thanks again for the help. Is there a good way by which I can only enter records pertaining to some years and not all years as are there in the dataset
Comment: Using this approach, not directly. I would recommend loading it all into a single table that you plan to throw away, and then use `CREATE TABLE .. SELECT` syntax to generate the table with the data you actually want. See http://dev.mysql.com/doc/refman/5.1/en/create-table.html
Answer: First of all, I am assuming that the CSV files have quotes around the string values.
Thus each value containing a comma is surrounded by a quote like this:

a, b, 2, 'foo, bar'

If so, then you can use the following:
import
 csv

quoteChar = "'"

myReader = csv.reader(open('largefile.csv', 'rb'), delimiter=',', quoteChar = quoteChar)

for row in myReader:
    print row # this prints a list. Row is a list of values per line in your
    # 'largefile.csv' file. Each row is splitted on the delimiter char.
    # (comma in this case) and strings that are quoted by quoteChar (in your case
    # a ' are treated differently.) This will work for your input that you've given
    # in your question.

# this is what you used to do:
for line in open('largefile.csv', 'rb'):
     row = line.split(quoteChar)

If otherwise it'll depend on how your CSV files look like.
Comment: Thanks for the help. Since I also have to transfer this content to MySQL database, therefore I was doing the following: for row in myReader: values=row.split(',') and then storing these values into MySQL. This split is essentially causing the problem. Is there an alternative way of transferring data into MySQL
Comment: @user869790: Daan is showing you how an alternative way. Python's built-in `csv` module is what you should be using for this task. Don't reinvent what's already been built and tested for you.
Comment: @user869790 Adam Bernier is right. I've updated my answer to clarify things a bit more. the row from in myReader is the same (type) of 'row' that you'll get after line.split() but then 'better'. The CSV module does all of this for you. No need to reinvent the wheel.
Comment: @AdamBernier Just a naive question, please forgive me since I am a novice. How do i check to know the kind of csv file i have. Since i ran the above code and found my data is not surrounded by double quotes, also I am able to view the file in 'xlsx'
Comment: @DaanTimmer Thanks your approach too worked. Really appreciate your help
Comment: @AdamBernier Thanks for the help the approach worked. Really appreciate your help
Comment: @user869790 no problem. The other solution is more elegant and probably faster. Mine is more python-related (because you too were having problems with parsing a CSV data). Glad to have been of help :-)
Answer: You can use mysqlimport
mysqlimport --ignore-lines=1 --fields-terminated-by=, --fields-optionally-enclosed-by='"' --verbose --local -u root -p DB_Name csv/path.csv > save_log.log


Como executar uma função N vezes em 1 segundo

Question: Preciso executar uma função N vezes, porem oque eu fiz até agora não funcionou, lembrando que esse N vezes tem que ser distribuído igualmente por 1 segundo.
async function sendImage() {
    Console.log('teste');
}
function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

async function demo() {
    while(true){
        sendImage();
        await sleep(1000/60);
    }
}

demo();

Comment: Não, é javascript puro.
Answer: Por que não passar o valor "N vezes" na função demo(), desta forma:
demo(5); // executar função 5 vezes em 1 segundo

E na função demo() receber e dividir esse valor em 1000, que equivale a 1 segundo:
async function demo(n) {
    while(true){
        sendImage();
        await sleep(1000/n);
    }
}

Ficaria assim:

async function sendImage() {
    console.log('teste');
}
function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

async function demo(n) {
    while(true){
        sendImage();
        await sleep(1000/n);
    }
}

demo(5); // 5 vezes em 1 segundo

Como observado, o correto é console.log (tudo minúsculo), senão o
  script para de rodar.
Comment: Como eu tinha dito, meu código não funciona, por exemplo, usando o código que você disponibilizou na resposta, coloquei para fazer 60 vezes por segundo, porem como pode ver nessa imagem i.stack.imgur.com/dtLmh.png o tempo entre cada console.log é diferente.
Como eu coloquei 60, seria 1000/60 = 16.6666...., ou seja, a cada 16.6666 milissegundos era para ter um console.log, mas isso não acontece com meu código.
Justamente esse meu problema, preciso que isso seja preciso em milissegundos.
Comment: @LucasCarezia Entendi. Vou ver aqui...
Comment: Agora eu peguei. Acredito que a precisão em tempo vai ser definido pela resolução da Promise :p nesse caso um `setInterval` possa ser mais recomendado.
Comment: @LucasCarezia Trabalhar com valores muito baixos no setTimeout não é garantia de precisão. Fiz o teste do código em 3 navegadores diferentes (Chrome, FF e Opera) e cada um mostra um valor diferente de processamento, apesar de aproximados. O que isso quer dizer? Que valores muito baixos de intervalo (milionésimos de segundo), depende muito da capacidade de processamento do computador, e o navegador não consegue processar isso de forma exata. Veja, testei 60 processamentos em 4 segundos... (continua)
Comment: @LucasCarezia ... que seria 4*60 = 240... no Chrome processou 226, no FF 227 e no Opera 232... Isso, sem falar que em cada F5 o valor às vezes muda... Concluindo, acho que não tem como processar isso de forma precisa, vai processar sempre um valor aproximado...
Comment: @LucasCarezia Se o cara tem um computador ruim, vai processar bem menos ainda. Isso pq meu PC é rápido, e mesmo assim não processa tudo.
Comment: Tudo bem, vou abrir uma nova pergunta, dizendo o meu problema completo para ver se encontra uma solução melhor do que estou tendo agora.
Comment: @LucasCarezia Criei uma página de teste, se quiser testar em vários navegadores verá o que estou falando: http://dvdteste.hospedagemdesites.ws/processa.php
Comment: https://jsperf.com/
Comment: @LucasCosta A página não abre... fica carregando e termina com erro 500
Comment: Aqui tb @dvd, provavel que o servidor esta com problemas (primeira vez que vejo isso). Mas em outro momento teste o jsperf.com, se vc nao conhece, conseguimos testar a performance entre scripts nele.
Comment: @LucasCosta Blz... vou esperar um tempo e tentar de novo
Answer: Para chegar a 1 segundo precisa passar os milissegundos, que é igual à 1000.

async function sendImage(i) {
    console.log('teste ' + Math.random());
}
function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

async function demo() {
    while(true){
        sendImage();
        await sleep(1000);
    }
}

demo();

PS: Tinha um erro em Console.log, o correto é console.log


Multiple FAQ pages using FAQ module

Question: I am using the FAQ module in drupal7. My website has many pages which should have a FAQ of their own. So adding FAQ from "Add Content" adds and lists all the FAQs in different categories in the "faq-page". For example, I have two applications so i need dedicated faq page for application 1 and 2.
Is this possible using the FAQ module ?
Answer: Yes, the FAQ module provides the ability to have separate categories of FAQ via the taxonomy module as per the project page:

"In addition, if the 'Taxonomy' module is enabled, it is possible to
  put the questions into different categories when editing. Users will
  need the 'view faq page' permission to view the built-in 'faq' page
  and will need the 'administer faq' permission to configure the layout,
  etc."

To use the individual faq categories, use the urls: faq-page/[tid] - where the [tid] is the term ID of the category you want.
You can also use views to make additional faq pages for specific categories if you like.
Comment: Just updated my answer. The url is faq-page/[tid] where [tid] is the term id of the category you want to view.
Comment: how can i make additional faq pages ? I have made categories in which i classify questions of a particular topic. But they all show up in the "faq-page".
Comment: I am using the collapsible Q&A. If i have to link to another answer in one answer then how can i do that? For example i write in answer 2.4 to refer to answer 1.2, then how can i do that? any ideas?
Comment: (hope this makes sense) If you hover over the link for the answer you want to link to it should be a url with a hash and then some more text after the hash. This is the link to that answer. If you create another link the same it should work.
Comment: edited my previous answer
Comment: but as in my example the question 1.2 is a node but i want the link to open the question in the same page.

Multiple FAQ pages using FAQ module


Ask for input then open in new window

Question: I don't know much JavaScript so I was just wondering if it would be possible for a Java alert to pop up asking for a URL and then set the iframe arc to the URL (this will run as a bookmarklet).
Basically, I am looking for a prompt to pop up asking for a url and then open a new window and create an iframe in the new window with the arc that was typed earlier l.
javascript:
    var win = window.open();
    win.document.write('

                       ');

Thank's in advance!
Answer: Yes it's possible, you can use a self calling function to enclose the script:
javascript: (function() {
var alertWinRes  =  prompt("Please enter Site", "bing.com");
if(alertWinRes !== null){
   var win = window.open("My new Window");
   win.document.write('');
 }
})();

The same functionality can be achieved without iframe:
javascript: (function() {
var alertWinRes  =  prompt("Please enter Site", "bing.com");
if(alertWinRes !== null){
   var win = window.open("https://" + alertWinRes, "_blank");
}
})();

Using prompt creates an alert the user can use to enter the text and the second parameter is used to set a default. You'll have to have website already open for this to trigger, for security reasons in a new tab it doesn't work (there's work arounds posted online about it if needed).
Comment: Could you add that to the existing code, it would just be really helpful, I don't know JavaScript to well, thank you.
Comment: What I mean is could you change the iframe arc to the answer from the prompt?
Comment: Hello, I seemed to have gotten a notification from you or somebody on the topic but I do not see the comment.
Comment: I just updated the answer with your code in it to open a window
Comment: You could also just replace the iframe with window.open(URL, '_blank'); where URL is the string the user adds plus the "https://" in front of it and pretty much would be the same functionality
Comment: I would love that, but I need the iframe so that your searches do not go to your history.

Ask for input then open in new window


Is there any function $f(z)$ such that $f(z)^i = z$?

Question: Basically, is there a formula for $\sqrt[i]{z}$.
I was thinking about complex numbers and trying to come up with formulas like $log_i(x)$ and $x^i$. I then thought about this:
$$\sqrt[i]{z} = f(z)$$
So I started trying. We know that $x^i = \cos(\ln(x))+i\sin(\ln(x))$, from Euler's formula. I then tried to reverse it:
$$\ln(x) \to e^x$$
$$\cos(x) \to \arccos(x)$$
$$...e^{\arccos(x)}$$
But, obviously, it will give you the wrong answer for $i\sin(\ln x)$.
I'm also unsure if $\arccos$ is even defined for values > 1.
Comment: $\arccos$ has a complex definition btw.  Mainly, look up hyperbolic trig functions.
Comment: @Olly Britton do the provided answers answer your question? If so, you should consider accepting one of them by clicking the checkmark.
Answer: It's a multi-valued function (see here for an explanation of branch cuts). Specifying a branch and taking an appropriate subset of $\mathbb{C}$ let's you define it on that subset.
To see how to define it, notice that $\frac{1}{i}=-i$ and so $z^{\frac{1}{i}}=z^{-i}=\frac{1}{z^i}$ and see if you can derive it from there via Euler's formula.
Comment: Writing it as $z^{-i}$ is probably better for use though, but +1 anyways for covering everything.  :-)
Answer: Hint:
$$\sqrt[i]{z}=z^{1/i}=z^{-i}$$
And then apply Euler's formula.
Comment: @OllyBritton $$\cos(-x)=\cos(x)\\\sin(-x)=-\sin(x)$$
Comment: So it's
$$\cos(-\ln x) + i\sin(-\ln x)$$
Comment: @OllyBritton and take the negatives out of the trig functions for simplicity.
Comment: Wait... you can do that?
Answer: Note that $1/i=-i$. So, we may in fact define
$$
f(z)= z^{-i}
$$
Keep in mind, however, that $z^w$ is a multi-valued function for any non-real complex number $w$.


How can I use a views template to modify the titles of taxonomy links?

Question: I have a view that shows a field which is a taxonomy term reference set to display each term as a link.  The taxonomy names are quite long so I want to rewrite them using a views template.
I made a template like this:
foreach ($row->field_field_ad_purpose as $data):
  if ($data['rendered']['#title'] == 'Apples, oranges, pears, and strawberries'):
    $data['rendered']['#title'] = 'Fruits';
  print $output;

Using dpm(), I was able to confirm that the #title is in fact shortened.  However, printing $output prints out the original title.  I also tried printing $data, but this just gives Array.  What is the function to call to print out the term as a link?
Answer: You need to create another field with the 'path' and set this to not display by default within the views UI.
You can then get the 'path' variable in your template along with the 'title' variable and create your link using Drupals l() function.
   print l($data['rendered']['#title'], $path);

http://api.drupal.org/api/drupal/includes%21common.inc/function/l/7
Comment: Ok, I see.  Since I already set it to output a link in the views UI, though, there is no need to add another field.  I did it like this: `print l($data['rendered']['#title'], $data['rendered']['#href']);`
Comment: Ahh even better!


Multiprocessing Queue in Python

Question: I'm trying to use a queue with the multiprocessing library in Python. After executing the code below (the print statements work), but the processes do not quit after I call join on the Queue and there are still alive. How can I terminate the remaining processes?
Thanks!
def MultiprocessTest(self):
  print "Starting multiprocess."
  print "Number of CPUs",multiprocessing.cpu_count()

  num_procs = 4
  def do_work(message):
    print "work",message ,"completed"

  def worker():
    while True:
      item = q.get()
      do_work(item)
      q.task_done()

  q = multiprocessing.JoinableQueue()
  for i in range(num_procs):
    p = multiprocessing.Process(target=worker)
    p.daemon = True
    p.start()

  source = ['hi','there','how','are','you','doing']
  for item in source:
    q.put(item)
  print "q close"
  q.join()
  #q.close()
  print "Finished everything...."
  print "num active children:",multiprocessing.active_children()

Answer: try this:
import multiprocessing

num_procs = 4
def do_work(message):
  print "work",message ,"completed"

def worker():
  for item in iter( q.get, None ):
    do_work(item)
    q.task_done()
  q.task_done()

q = multiprocessing.JoinableQueue()
procs = []
for i in range(num_procs):
  procs.append( multiprocessing.Process(target=worker) )
  procs[-1].daemon = True
  procs[-1].start()

source = ['hi','there','how','are','you','doing']
for item in source:
  q.put(item)

q.join()

for p in procs:
  q.put( None )

q.join()

for p in procs:
  p.join()

print "Finished everything...."
print "num active children:", multiprocessing.active_children()

Comment: @Dilettant - no, that won't actually change anything. q is available in the global namespace when the processes are created so the worker will actually have a copy of q when it is called. it would probably be better to specify `args=(q,)` in the call to `multiprocessing.Process` because then we are explicitly sharing the item - which is good to get in the habit of so you avoid accidentally sharing things you should/can not share.
Comment: Is there any reason you are putting None into the queue after completion? I thought task_done() could help avoid that problem? I was trying to model my code after the example on the bottom of this page: http://docs.python.org/library/queue.html
Comment: Not rating the solution, but hinting at how to have it run: move the "q =" declaration line before it's first usage in def worker() ... ;-)
Comment: @aerain - but it does work ... there is a reason i put None into the the queue. the line `for item in iter( q.get, None ):` is key. It tells the loop itself to exit after getting the value of None from the queue. This is what makes the actual process exit. q.join waits for all task_done calls. p.join waits for the termination of processes which can only happen if something breaks out of the look in the worker (or you call terminate on the process but that is less ideal).
Comment: I take the exact code from above, copy it and paste it into a file. Run it. When I hit the q.join() in the middle, processes are spawned in an endless loop and my machine locks up. I see nothing in the code that leads me to believe that would happen, but, I have done this twice. This is with Python 2.7.1.
Answer: Your workers need a sentinel to terminate, or they will just sit on the blocking reads.  Note that using sleep on the Q instead of join on the P lets you display status information etc.
My preferred template is:
def worker(q,nameStr):
  print 'Worker %s started' %nameStr
  while True:
     item = q.get()
     if item is None: # detect sentinel
       break
     print '%s processed %s' % (nameStr,item) # do something useful
     q.task_done()
  print 'Worker %s Finished' % nameStr
  q.task_done()

q = multiprocessing.JoinableQueue()
procs = []
for i in range(num_procs):
  nameStr = 'Worker_'+str(i)
  p = multiprocessing.Process(target=worker, args=(q,nameStr))
  p.daemon = True
  p.start()
  procs.append(p)

source = ['hi','there','how','are','you','doing']
for item in source:
  q.put(item)

for i in range(num_procs):
  q.put(None) # send termination sentinel, one for each process

while not q.empty(): # wait for processing to finish
  sleep(1)   # manage timeouts and status updates etc.

Comment: while not q.empty(), is not a reliable way to know processing is finished, only when a worker grabs the last piece of work to be done.  Frankly, with how you're improperly using the JoinableQueue, you don't need a JoinableQueue.  If you chose not to use a one, you wouldn't need the worker threads to flag task_done.  The purpose of using such a queue is so you can join it, which is exactly what you want to do at the end of this program instead of waiting for the queue to be empty.
Comment: Yes, with this method, the job finishes prematurely.
Answer: Here is a sentinel-free method for the relatively simple case where you put a number of tasks on a JoinableQueue, then launch worker processes that consume the tasks and exit once they read the queue "dry". The trick is to use JoinableQueue.get_nowait() instead of get(). get_nowait(), as the name implies, tries to get a value from the queue in a non-blocking manner and if there's nothing to be gotten then a queue.Empty exception is raised. The worker handles this exception by exiting.
Rudimentary code to illustrate the principle:
import multiprocessing as mp
from queue import Empty

def worker(q):
  while True:
    try:
      work = q.get_nowait()
      # ... do something with `work`
      q.task_done()
    except Empty:
      break # completely done

# main
worknum = 4
jq = mp.JoinableQueue()

# fill up the task queue
# let's assume `tasks` contains some sort of data
# that your workers know how to process
for task in tasks:
  jq.put(task)

procs = [ mp.Process(target=worker, args=(jq,)) for _ in range(worknum) ]
for p in procs:
  p.start()

for p in procs:
  p.join()

The advantage is that you do not need to put the "poison pills" on the queue so the code is a bit shorter.
IMPORTANT : in more complex situations where producers and consumers use the same queue in an "interleaved" manner and the workers may have to wait for new tasks to come along, the "poison pill" approach should be used. My suggestion above is for simple cases where the workers "know" that if the task queue is empty, then there's no point hanging around any more.
Answer: You have to clear the queue before joining the process, but q.empty() is unreliable.
The best way to clear the queue is to count the number of successful gets or loop until you receive a sentinel value, just like a socket with a reliable network.
Answer: The code below may not be very relevant but I post it for your comments/feedbacks so we can learn together. Thank you!
import multiprocessing

def boss(q,nameStr):
  source = range(1024)
  for item in source:
    q.put(nameStr+' '+str(item))
  q.put(None) # send termination sentinel, one for each process

def worker(q,nameStr):
  while True:
     item = q.get()
     if item is None: # detect sentinel
       break
     print '%s processed %s' % (nameStr,item) # do something useful

q = multiprocessing.Queue()

procs = []

num_procs = 4
for i in range(num_procs):
  nameStr = 'ID_'+str(i)
  p = multiprocessing.Process(target=worker, args=(q,nameStr))
  procs.append(p)
  p = multiprocessing.Process(target=boss,   args=(q,nameStr))
  procs.append(p)

for j in procs:
  j.start()
for j in procs:
  j.join()

Multiprocessing Queue in Python


Learning Smooth Manifolds

Question: This may come off being a silly question but I was curious if it would be possible for me to learn smooth manifolds from Lee's Introduction to Smooth Manifolds and learn multi-variable analysis along-side it. My current knowledge consists of real analysis (single variable), topology, abstract algebra, linear algebra.
From other posts I've read that it is recommended to understand multi-variable analysis before understanding manifolds. But I want to know if I can just learn the necessary as I move through lee's book.
Comment: If you read Baby Rudin ch. 9 and do the exercises you should be OK.
Comment: IMHO Baby Rudin is about the worst place to read multivariable analysis, but so be it. Regardless, you need multivariable analysis (including the derivative as a linear map, inverse and implicit function theorems) before you start wrestling with manifolds. You should know the statement of the change of variables theorem for integrals, although you need not know the proof.
Comment: @TedShifrin I understand that you have a YouTube channel that includes your class lectures of multi-variable calculus, but sadly your book "Multi-variable Mathematics: Linear Algebra, Multi-variable Calculus, and Manifolds" is a bit on the pricey side. Would James Munkres "Analysis on Manifolds" or Hubbard and Hubbard's "Vector Calculus, Linear Algebra, and Differential Forms: A Unified Approach" work alongside your lectures?
Comment: I sadly have no control over the price of books. I am not a fan of Hubbard's book; I wrote mine because my students couldn't deal with his. Munkres's book is fine. You mostly need a source of exercises; the lectures are pretty much self-contained. (Both Hubbard and I purport to teach linear algebra and multivariable calculus to students who don't already know it computationally. Munkres is writing an analysis book for students who've had multivariable calculus and single-variable analysis.)
Answer: Putting whether or not you can aside. You really should learn multivariable analysis first. The logical order is

Linear functions on linear spaces ((finite dimensional) Linear Algebra)
Non-linear functions on linear spaces which can be approximated by linear functions (Multivariable Calculus)
Non-linear functions on non-linear spaces which can be approximated by linear functions and linear spaces (Smooth Manifold Theory)

Now you certainly can learn the third one without the other two, since it is a generalization. But, and this is important, Lee's book assumes that you've already done steps 1 and 2 and are comfortable with that material. So do yourself a favor and instead of going back and forth between multivariable calculus and Lee's book, do multivariable first and then go through Lee's book. You aren't saving yourself any time by trying to interleave the learning.
Of course, nobody will stop you from picking up Lee's book and trying to work through it. We are just saying you will understand things much better if you have a solid understanding of multivariable calculus. For example, you should know:

the inverse function theorem
how derivatives are linear maps and how second derivatives are bilinear maps
the topology of $\mathbf{R}^n$
how to actually work with multivariable functions (this is huge because a lot of examples rely on this knowledge)

On the other hand, there are textbooks that develop the theory of mutivariable analysis along side of manifolds. Two examples are Spivak's "Calculus on Manifolds" and Munkres's "Analysis on Manifolds". The key differences are: these are aimed at the undergraduate level and they don't assume prior knowledge of multivariable calculus.
Comment: Very late to the party. But in addition to those two books, I want to recommend: [Advanced Calculus of Several Variables by C.H. Edwards](https://www.amazon.com/Advanced-Calculus-Several-Variables-Mathematics/dp/0486683362/), [Advanced Calculus: A Differential Forms Approach](https://www.amazon.com/Advanced-Calculus-Differential-Approach-Birkhäuser-ebook/dp/B00HWUNKHG/), and the classic but monstrous [Advanced Calculus by Loomis and Sternberg](http://www.math.harvard.edu/~shlomo/docs/Advanced_Calculus.pdf).

Learning Smooth Manifolds


Is is possible to apply a generic method to a list of items?

Question: Lets say I've written my own method to reverse a list in place.
public static void MyReverse<T>(List<T> source)
{
    var length = source.Count;
    var hLength = length / 2;
    for (var i = 0; i < hLength; i++)
    {
        T temp = source[i];
        source[i] = source[length - 1 - i];
        source[length - 1 - i] = temp;
    }
}

I call it like so, and it works.
var fooList = new List<Foo>();
MyReverse(fooList);

If I want to reverse multiple lists, I call it like so.
var fooList = new List<Foo>();
var barList = new List<Bar>();
var bazList = new List<Baz>();
MyReverse(fooList);
MyReverse(barList);
MyReverse(bazList);

If I want to reverse an arbitrary number of lists, I'd try:
public static void Main(string[] args)
{
    var lists = new List<object>
    {
        new List<Foo>(),
        new List<Bar>(),
        new List<Bar>()
    };

    ReverseLists(lists);
}

public static void ReverseLists(List<object> sourceLists)
{
    foreach (var sourceList in sourceLists)
    {
        MyReverse(sourceList); // Error: Type arguments cannot be inferred from usage
    }
}

But this throws a compile time error. Is what I'm trying to do possible - could the ReverseLists method be implemented?
Comment: Worth noting you can make all this compile and run by abandoning generics and changing the signature of your MyReverse method to `public static void MyReverse(IList source)` (and elsewhere replace `List` with `IList`) I appreciate this isn't an answer to your question though, hence why not posted as one!
Comment: If you *really* need this, try it with `List` as the parameter type of `ReverseLists`.
Comment: `sourceList` is `object`.
Comment: @Rik: Clearly that wont make the compiler happy...
Comment: sourceList is an object - youll need some sort of cast to List to let this work
Comment: @JamesS I'm be sorely tempted to post that as an answer, it would be better than the answers we have already and IMO it's a really good solution.
Comment: @Rawling - ok, posted as an answer then :)
Answer: Assuming you have a static method like this
public static class ReverseHelper
{
    public static void MyReverse<T>(IList<T> source)
    {
        var length = source.Count;
        var hLength = length / 2;
        for (var i = 0; i < hLength; i++)
        {
            T temp = source[i];
            source[i] = source[length - 1 - i];
            source[length - 1 - i] = temp;
        }
    }
}

With the help of non generic interface and a generic class you can do it.
public interface IReverser
{
    void Reverse();
}
public class ListReverser<T> : IReverser
{
    private readonly IList<T> source;
    public ListReverser(IList<T> source)
    {
        this.source = source;
    }
    public void Reverse()
    {
        ReverseHelper.MyReverse<T>(source);
    }
}
static void Main(string[] args)
{
    var lists = new List<IReverser>
    {
        new ListReverser<Foo>(new List<Foo>()),
        new ListReverser<Bar>(new List<Bar>()),
        new ListReverser<Bar>(new List<Bar>())
    };

    foreach (var reverser in lists)
    {
        reverser.Reverse();
    }
}

I've used IList<T> as opposed to List<T> to support broader number of types; If you want List<T> you can put it back.
Comment: IMO this is the neatest option.
Answer: As per my comment above...
The compiler cannot covert infer the type of T when passed object (which is effectively what's happening)
However there is a much simpler option - which is to just abandon using generics, and change the signature of your MyReverse method to public static void MyReverse(IList source) (and elsewhere replace List<object> with IList)
ie:
public static void Main(string args[])
{
    var lists = new List<IList>
    {
        new List<Foo>(),
        new List<Bar>(),
        new List<Bar>()
    };

    ReverseLists(lists);
}

public static void MyReverse(IList source)
{
    var length = source.Count;
    var hLength = length / 2;
    for (var i = 0; i < hLength; i++)
    {
        var temp = source[i];
        source[i] = source[length - 1 - i];
        source[length - 1 - i] = temp;
    }
}

public static void ReverseLists(List<IList> sourceLists)
{
    foreach (var sourceList in sourceLists)
    {
        MyReverse(sourceList); // Error: Type arguments cannot be inferred from usage
    }
}
public class Foo
{
}
public class Bar
{
}

Comment: This will introduce unnecessary boxing and unboxing in case of value types.
Comment: I just started writing this up. I'm glad you beat me to it. This has taught me that `IList` isn't just a holdover from the pre-generic days.
Answer: If you change your ReverseLists method signature to
public static void ReverseLists<T>(IEnumerable<object> sourceLists)
{
    foreach (var sourceList in sourceLists.OfType<List<T>>())
    {
        MyReverse(sourceList);
    }
}

Then you can call this for each list type:
ReverseLists<Foo>(lists);
ReverseLists<Bar>(lists);

Maybe not ideal having to call it once per list type, but a comparatively small change to your existing code.
Comment: @Nathan: Ah - now I got it: You call `ReverseLists` on the same list for all possible types and each "run" that type is reversed. That *would* work, but you would need to run it for every type: What if there are many different types in the list not just 2 - there it would start to get messy...
Comment: @ChrFin Indeed - as per my last line in the answer text :)
Answer: To compliment the answer from Sriram Sakthivel - the key to your problem is that the Type cannot be inferred from what you are passing in. It's worth noting that List<T> implements IList so your issue above can be reframed using a parameter array of List like:
void Main()
{
    var fooList = new List<string>();
    var barList = new List<string>();
    var bazList = new List<string>();
    ReverseLists(fooList, barList, bazList);
}

public static void ReverseLists(params IList [] sourceLists)
{
    foreach (var sourceList in sourceLists)
    {
        MyReverse(sourceList);
    }
}

public static void MyReverse(IList source)
{
    var length = source.Count;
    var hLength = length / 2;
    for (var i = 0; i < hLength; i++)
    {
        var temp = source[i];
        source[i] = source[length - 1 - i];
        source[length - 1 - i] = temp;
    }
}

Answer: change this line in the original post:
MyReverse(sourceList); // Error: Type arguments cannot be inferred from usage

to this:
MyReverse(((System.Collections.IList)sourceList).Cast<object>().ToList());


Is the logistic function continuous

Question: By using the Epsilon Delta Definition I have to prove that $$f(x)=\frac{e^x}{1+e^x}$$
is continuous on R s.t
$|\Delta f| <\epsilon$ and $|\Delta x| < \delta$
I'm not really sure what to do
Comment: What theorems about continuity do you have at your disposal?. Do you know that $e^x$ is continuous?  Do you know that if $f$ and $g$ are continuous that $f + g$ is continuous and $f/g$ is continuous if $g(x) \ne 0$ for any x?  $e^x > 0$ so $e^x + 1 > 1 > 0$ for all real $x$.
Comment: ... if you know those things, then the continuity follows.  If you don't know those things, we'll have to prove them... which we can do.  So, at this stage of your course, what can we assume you know?
Comment: I know $e^x$ is continuous and $f+g$ $f$/$g$ is continuous then continuity follows. But in my course we have not proven $e^x$ is continuous. I must therefore use the Epsilon Delta Definition to prove $f(x)$ is continuous.
Comment: Would it be acceptable to prove $e^x$ is continuous and then conclude $f(x)$ is continuous?  Proving $e^x$ via delta epsilon is straightforward and I can help you with that.  Proving $f(x)$ directly is ... kind of a pain but not impossible.
Comment: I would like to prove both $e^x$ is continuous and $f(x)$ is continuous . If it's okay. I really appreciate your help and time.
Answer: Okay.  To prove $e^x$ is continuous at a fixed point $w \in \mathbb R$.
If we assume $\epsilon > 0$ we have to find a $\delta_{\epsilon} > 0$ such that:
If $|x - w| < \delta$ then it must follow that $|e^x - e^w| < \epsilon$.  So we must figure out what is required for the second condition to always be true.
So if $|e^x - e^w| = |e^w(e^{x-w} - 1)| = e^w*|1 - e^{x-y}|$.
So $|e^x - e^w| < \epsilon \iff |1- e^{x-w}| = |1 - e^x/e^w| < e^{-w}*\epsilon$.
This will be true if $e^x/e^w = e^{x-w} < \min(|e^{-w}*\epsilon - 1|,|e^{-w}*\epsilon + 1| )$.
This will be true if $|x - w| < \min(\ln(|e^{-w}*\epsilon -1|), \ln(|e^{-w}*\epsilon + 1|)$
So.. for any $\epsilon > 0$ we can choose $\delta = \min(\ln(|e^{-w}*\epsilon -1|), \ln(|e^{-w}*\epsilon + 1|)$.  Then it follows that $|e^x - e^w| < \epsilon$
So $e^x$ is continuous at $w$.  We can do this for all $r \in \mathbb R$ so $e^x$ is continuous on all reals.
Then we can conclude $e^x + 1$ and $e^x/(1 + e^x)$ are continuous on all reals.

Is the logistic function continuous


I can't understand the definition of the convergence in probability

Question: https://en.wikipedia.org/wiki/Convergence_of_random_variables
Wikipedia defines convergence in probability as follows:
A sequence $X_n$ of random variables converges in probability towards the random variable $X$ if for all $\epsilon$ > 0
$\lim_{n\to\infty}\Pr(|X_n-X|\gt\epsilon)=0$.
I don't know how to evaluate $X_n-X$ in particular.
Is it necessary to consider the joint distribution of $X_n$ and $X$?
I don't think so, but, then, I don't know what $X_n-X$ actually means.
Is the following evaluation correct if there are probability density functions $f_{X_n}$  of $X_n$ and $f_X$ of $X$?
\begin{align}
\Pr(|X_n-X|\gt\epsilon)&=\int_{-\infty}^\infty\left(\int_{-\infty}^{x-\epsilon} f_{X_n}(y)dy+\int_{x+\epsilon}^\infty f_{X_n}(y)dy\right)f_X(x)dx
\end{align}
EDIT
I just want to know how to calculate $\Pr$ in convergence in probability formula for given random variables.
Usual calculation of $\Pr$ doesn't seem to converge to zero for most cases when $n \to \infty$.
Even if $X_n$ equals to $X$!?
Comment: If $X$ is not a constant but a truly random variable, the joint distribution of $(X_n,X)$ must be considered, indeed.
Comment: "$X_n - X$" is, by definition, the sum of the random variables $X_n$ and $-X.$  See https://stats.stackexchange.com/questions/95993 for intuitive accounts of what a sum of random variables means.
Answer: I found out that the formal definition of the convergence in probability is as follows:
\begin{align}
\forall\epsilon>0,\ \lim_{n\to\infty}\Pr(\omega|\ |X_n(\omega)-X(\omega)|\gt\epsilon)=0.
\end{align}
And if you define sample space $\Omega$ as [0, 1], $X(\omega)$ becomes $F_X^{-1}(\omega)$ for $\omega \in \Omega$ with $F_X$ as the cumulative distribution function of $X$.
Therefore, the condition of the convergence in probability with cumulative distribution functions becomes as follows:
\begin{align}
\forall\epsilon>0,\ \lim_{n\to\infty}\int_0^1 H\left(\left|F_{X_n}^{-1}(s)-F_X^{-1}(s)\right|-\epsilon\right)ds&=0.
\end{align}
Where H(t) is the unit step function.
Comment: 1. note that the formal definition in the beginning of this answer is essentially 2. The construction $\Omega = [0,1],~X(\omega)=F_{X}^(-1)(\omega)$ does not make much sense if you want to consider more than 1 random variable (hint: can you eg represent two independent $U(0,1)$ random variables  with this construction?).  3. Thus, the latter condition does not work in general.
Comment: But I asked for random variables defined in the same probability space, there is no "different $\omega" for each random variable, whatever that would mean. In each ticket in https://stats.stackexchange.com/questions/50/what-is-meant-by-a-random-variable/54894#54894, a value of $X_1$ and a value of $X_2$ is written in the same ticket). I suspect this question and this mistaken answer) partially stem from unfamiliarity with the formal definitions of probability spaces and random variables.
Comment: (Yes, you need to consider the joint distribution of $X_n$ and $X$ to evaluaate $P(|X_n-X|<\epsilon)$ while the last integral in the answer depends only on  the marginal distributions)
Comment: Thanks a lot for the comment.
If you need two independent random variables according to $U(0,1)$, you can use $X_1(\omega_1)=\omega_1$ and $X_2(\omega_2)=\omega_2$ with $\omega_1, \omega_2 \in [0, 1]$.
Convergence of probability requires values of $X, X_n$ to be estimated at the same point $\omega$.
Comment: Thanks again.
It is said that t-distribution with n freedom converges to the standard normal distribution when $n \to \infty$.
Is there any joint distribution supposed between them?
I can't see any and I'm confused.
If $X \sim N(0,1)$, $X_n \sim t(n)$, and they are independent, I don't think $Pr(|X_n - X| \gt \epsilon)$ converges to zero when $n \to \infty$.
What kind of joint distribution is supposed behind them?
Comment: Is it said that those $X_n$s converge in _probability_ to $X$? Do you have a reference ?  Also, if that example is what prompted the question, you might want to edit that to the question itself
Comment: I didn't think about that!
Because they are well-known continuous functions.
Do they converge in distribution but not converge in probability?
https://en.wikipedia.org/wiki/Student%27s_t-distribution


How to uninstall OAuth2 OR fix it

Question: i'm new in Drupal.
I tried on my site to mount the OAuth2 world but I can't get to the top. The website shows an error that is

Error: Interface 'League\OAuth2\Server\Repositories\AccessTokenRepositoryInterface' not found in include() (line 13 of modules/simple_oauth/src/Repositories/AccessTokenRepository.php).

same applies if I try to manually uninstall the module via ssh with drush pm-uninstall simple_oauth oauth2_server it is impossible:

In Connection.php line 896:
SQLSTATE[42S02]: Base table or view not found: 1146 Table
'site_drupal.oauth2_token' doesn't exist: SELECT "base_table"."id"
AS "id", "base_table"."id" AS "base_table_id" FROM
{oauth2_token} "base_table"
LIMIT 1 OFFSET 0; Array
(
)
In StatementWrapper.php line 116:
SQLSTATE[42S02]: Base table or view not found: 1146 Table
'site_drupal.oauth2_token' doesn't exist

Basically: the site (or the admin section to uninstall the module) cannot be accessed unless this module presents this kind of error, and via ssh I can't figure out how to remove it.
I thank you for any kind of help.
Comment: How did you install the module? Did you not use composer? It should have retrieved the library for you when you installed it. I'm guessing maybe you did it manually?
Comment: You can add `metatag: 0` to `core.extensions.yml`.
Comment: @Jaypan ok, this has greatly reduced the error block, i added also webprofiler: 0 and this reduced more the error block, but there are still a few lines left: https://postimg.cc/dhFP2tbB. I think it is about "simple_oauth: 0" that i removed for solve the first "..Interface 'OAuth2\..". We returned to the beginning. :-(
Answer: You can do the following:

Run drush cex to export your configuration to the config directory.
Find the core.extensions.yml file in the configuration directory. Edit it, and remove the line that says: oauth2_server: 0
Run drush cim  to import your configuration. It should disable that module.

How to uninstall OAuth2 OR fix it


stylesheet view helper in zend framework

Question: I wanted to append css stylesheet inside head tag but gets appended to body tag.
Here's what i did:
i have a controller 'countries' with action 'index' and my view is index.phtml
index.phtml contains:
<?php
 $this->headLink()->appendStylesheet($this->baseUrl().'/js/dojo-1.7/dojo/resources/dojo.css')
             ->appendStylesheet($this->baseUrl().'/js/dojo-1.7/dojox/grid/resources/claroGrid.css');
 echo $this->headLink();

This causes the stylesheet to be appended inside body tag.
I only want these stylesheet to be appended to this action. I dont want to include this stylesheet inside my layout.phtml
How can i do it?
Answer: What you've done is correct, but you're echoing headLink() in your view just after adding the stylesheet which is what is outputting the links in the wrong place. Change your code so you have:
In index.phtml:
$this->headLink()->appendStylesheet($this->baseUrl().'/js/dojo-1.7/dojo/resources/dojo.css')
         ->appendStylesheet($this->baseUrl().'/js/dojo-1.7/dojox/grid/resources/claroGrid.css');

And then in layout.phtml (in the  section where you want the stylesheet links to appear):
echo $this->headLink();

Answer: you're adding this in the incorrect place.
 If you add a a style sheet in this manner from inside your .phtml you are in the body of the document. To add a style sheet to the head of a single page add the stylesheet from your action code inside your controller:
public function someAction() {
    $this->view->headLink()->appendStylesheet($this->baseUrl().'/js/dojo-1.7/dojo/resources/dojo.css');
}

alternately if you want to add a style sheet to all the actions of a controller you can use the same code in the init() method of your controller:
public function init() {
     $this->view->headLink()->appendStylesheet($this->baseUrl().'/js/dojo-1.7/dojo/resources/dojo.css');
}

you can use setStylesheet() if you need to override the current stylesheets or you can use prependStylesheet() or appendStylesheet().
Good Luck...
Comment: You can add placeholder content in the view as well, since it is rendered before the layout.
Comment: Sorry I assumed he already had the placeholder in his layout. Also I didn't realize that the code would work from the view (never really thought about it) because I would never consider putting this kind of code in a view. However I stand corrected, Thank you


Adding a title to a ul in the menus

Question: I need to create the following to a menu system in drupal 7. I want to be able to create a href that is not connected to a content type. Is this possible?

link

link

I need this link to not be attached to a content type

link

link

Comment: What do you mean by "attached to content type"? Links can be given by node id or by path, and may as well be external. And could you make question's title and body match? Now I fail to see a connection between them.
Answer: try this module "Nice Menus" and this "Menu Attributes".
You can follow these tutorials for more informations:
http://codekarate.com/daily-dose-of-drupal/drupal-7-menu-attributes-module
http://codekarate.com/daily-dose-of-drupal/drupal-7-nice-menus-module
I hope it helps you out. Thank you
Answer: I used the following to fix this issue,
special_menu_items module
This allows me to nolink so I could create a href="#"
menu_attributes  module
To add an id

Adding a title to a ul in the menus


Android Notifications not display the message body

Question: I am writing my own message provider to send out push notifications on both iOS and Android.  I have the provider working well for iOS.  My problem is Android.  With the app not running, The phone gets the message and notifies the user a message came in.  I only see the icon in the message.  The message body is not displayed.  If the app is running, the app gets the message event and I can see in the JSON, the message body and message title.  So it would appear that the information is coming through.  I've tried this on an Android running JellyBean and Marshmallow and get the same results.  I also tried using Googles test notification from their web site for FCM.  I get the same results with their web notification send.  Any ideas?
Here is the code I am using in Delphi:
<code>HttpClient.Request.URL := 'https://fcm.googleapis.com/fcm/send';

HttpClient.Request.ContentType := 'application/json';
HttpClient.Request.CustomHeaders.Add('Authorization: key = ***'); // Server Key from Google
HttpClient.Request.CharSet := 'utf-8';

JSONMsg := TJSONObject.Create;
JSONMsg.AddPair('to', devicetoken);

JSONInfo := TJSONObject.Create;
JSONInfo.AddPair('body', edtMessage.Text);
JSONInfo.AddPair('title', 'CODY Mobility');
JSONInfo.AddPair('priority', 'high');
JSONTrue := TJsonTrue.Create;
JSONFalse := TJsonFalse.Create;
JSONInfo.AddPair('content_available', JSONTrue);
JSONInfo.AddPair('dry_run', JSONFalse);

JSONToSend := TStringStream.Create(JSONMsg.ToString, TEncoding.UTF8);

StatusMemo.Lines.Add('Sending Android message to device: ' + deviceToken);
try
    HttpClient.Post('https://fcm.googleapis.com/fcm/send', JSONToSend);
except
    on E:Exception do begin
        StatusMemo.Lines.Add('Message send failed: ' + E.Message);
    end;
end;

StatusMemo.Lines.Add('Android message response: ' + HttpClient.ResponseText);
FreeAndNil(JSONTrue);
FreeAndNil(JSONFalse);
</code>
Comment: Have you tried sending a [`data`](https://developers.google.com/cloud-messaging/concept-options#notifications_and_data_messages)-*only* message payload for Android? With this, it is sure that your app should be the one to handle the notification, not the System Tray.
Comment: Yes, I did try just sending a data only payload but that did not solve my problem.  I want to be able to send and display messages to the phone, when the app is not running.  When the app is running, the app gets all the information in the payload, data or notification, which the app can then display without problems.
Comment: Hi Joe. So you mean to say that your app is able to receive messages in both foreground and background and that you just want to receive messages even when your app is closed or killed. Is that right?
Comment: Correct.  When the app is closed, I want Android OS to display the message text.  All it displays is the app icon for the notification.
Answer: I have found my problem! It appears to be a bug with Delphi. My original message sent was:
<code>{"to":<MyDeviceID>","notification":{"body":"It finally works!!!!!","title":"CODY Mobility Title","priority":"high","content_available":false,"dry_run":false}}
</code>
If I change my message to the following, it now works:
<code>{"to":"<MyDeviceID>","data":{"message":"It finally works!!!!!","title":"CODY Mobility Title","priority":"high","content_available":false,"dry_run":false}}
</code>
I had to change from "notification" to "Data" and I had to change the "body" element to a "message" element. With those changes in place, the phone gets and displays the message when the app is closed. Of course, this no longer matches Google's specs for sending a notification with Firebase Cloud Messaging. I dug into the Delphi code and I found a Delphi java script called NotificationPublisher.Java. In there, there is code which specifically looks for a message element.
<code> if (jsonVal != null) {
if (jsonVal.has("message"))
{ msg = jsonVal.optString("message"); }

else if (jsonVal.has("msg"))
{ msg = jsonVal.optString("msg"); }

else if (jsonVal.has("alert"))
{ msg = jsonVal.optString("alert"); }

if (jsonVal.has("title"))
{ title = jsonVal.optString("title"); }

}
} else {
// Look for msg or message in bundle
if (key.equals("message"))
{ msg = valstr; } else if (key.equals("msg")) { msg = valstr; }

if (key.equals("title"))
{ title = valstr; }
}
</code>
I am not sure where Delphi checks for Notification elements versus Data elements. But I believe this is part of the problem. I created a support ticket so Embarcadero can look into this further. If anyone else has this problem... Just change your message and it'll work.


Is it necessarly abelian $2$ group?

Question: Is the following correct ?
Let $n_2$ be a number of elements of $G$ of order $2$ if $n_2> \dfrac {|G|}2$ then $G$ is elemantary abelian $2$ group.
Edit: we see that the conclusion "if $n_p> \dfrac {|G|}p$ then $G$ is a $p$ group is wrong" thanks to JyrkiLahtonen.
Comment: @JyrkiLahtonen: thanks, I see.
Comment: Even though it's been answered, you should leave the second question in the OP.
Comment: @MikeMiller: you are right, I guess.
Comment: Oh well. Then I need to retype the comment telling that $D_5$ is a counterexample :-)
Comment: @JyrkiLahtonen: yeah it can be good :)
Comment: @Jyrki Post it as an answer! :)
Answer: The direct product of an elementary abelian group of order $2^n$ with a dihedral group of order $8$ has $3 \times 2^{n+1} - 1$ involution, so the proportion is $3/4 - 2^{-(n+3)}$.
It is a known result that if at least $3|G|/4$ elements are involutions, then $G$ is elementary abelian. See Involutions and Abelian Groups
Comment: I don't know of any bounds for $n_p$. But, for any prime, a Frobenius group with complement $C_p$ will have $n_p/|G| = (p-1)/p$, and you can increase that slightly by taking a direct product with a big elementary abelian $p$-group. So, for $p=3$, by taking $A_4 \times E$, I can get arbitrarily close to $3/4$ for $n_p/|G|$. I don't know if anyone can beat that or prove it's the best possible.
Comment: Thanks,
Do you know any other bound for $n_p$ to get $G$ as an $p$ group ?

Is it necessarly abelian $2$ group?


Migrating data from a CSV source: Where should the source go?

Question: I'm trying to do a migration of an old (and full of nodes and comments) D7 site, to a Drupal 8 brand new one.
In order to import only the contents, I'm trying to do the migration from a csv file (with the stuff that I've exported using views).
My question is, how to set the source? Full path?
I'm using a test csv file and I put it at the root folder, at the same place where the index.php file is.
I tried this:
source:
  plugin: csv
  path: 'http://www.example.com/myfile.csv'
...

And this:
source:
  plugin: csv
  path: '/myfile.csv'
...

(with and without the slash)
I keep receiving this error when I try to run the migration script:

An AJAX HTTP error occurred.
HTTP Result Code: 500
Debugging information follows.
Path: /batch?id=20&op=do_nojs&op=do
StatusText: Internal Server Error
ResponseText: The website encountered an unexpected error. Please try again later.

What should I do?
Comment: put source as public://csv/test.csv and sites default make a folder named csv and place the file inside that
Comment: Thanks! It worked. Please add it as a reply so I can mark it as accepted.
Answer: Please add the file as :
source:
  plugin: csv
  path: 'public://csv/test.csv'

And under sites/default make a folder named as csv and place the file inside that. It will work.


System Crash Using pandas for datetimeindex

Question: I'm trying to work my way through this RealPython tutorial on the Python visualization package called bokeh https://realpython.com/lessons/using-columndatasource-object/#transcript . This video version is 2.5 years old, and the text version that preceded it is 3.5 years old https://realpython.com/python-data-visualization-bokeh/#generating-your-first-figure . Needless to say, here and there neither work as expected due to changes in the affected programs.
At this particular point, I'm trying to put a datetimeindex on a data frame that's been created from some CSV data. The problem is that every time I've run this, once last night and twice this morning, the whole system freezes and I have to restart the computer. There is no error message or other output.
Python 3.9.12
bokeh 2.4.2
pandas 1.3.3
Ubuntu 20.04 LTS
PyCharm 2020.1
Here's the script:
import pandas as pd
from pandas import Timestamp
from datetime import datetime, date
import time

start = time.time()

player_stats = pd.read_csv('data/2017-18_playerBoxScore.csv', index_col='gmDate')

team_stats = pd.read_csv('data/2017-18_teamBoxScore.csv', index_col='gmDate')

standings = pd.read_csv('data/2017-18_standings.csv', index_col='stDate')

dti_p = pd.DatetimeIndex(player_stats.index)
dti_t = pd.DatetimeIndex(team_stats.index)
dti_s = pd.DatetimeIndex(standings.index)

player_stats.replace(to_replace=player_stats.index, value=dti_p, inplace=True)
team_stats.replace(to_replace=team_stats.index, value=dti_t, inplace=True)
standings.replace(to_replace=standings.index, value=dti_s, inplace=True)

end = time.time()
prgrm = start-end

print(f"start : {start}")

print(f"total time = {prgrm}")

print(f"end : {end}")

This version uses DatetimeIndex() and replace(), but previously I tried .apply() and Timestamp.date() without success. In writing this post, I ran the script again just to see what coverage and the debugger would give me before posting and now, for reasons I can't explain, I am getting an error:
/home/malikarumi/.virtualenvs/chronicle/lib/python3.9/site-packages/pandas/core/indexing.py
    def _validate_key_length(self, key: Sequence[Any]) -> None:
line 791 → if len(key) > self.ndim:
            raise IndexingError("Too many indexers")

(<class 'pandas.core.indexing.IndexingError'>, IndexingError('Too many indexers'), <traceback object at 0x7fe8c8d45b80>)

Your assistance greatly appreciated.
Comment: The function [`pd.read_csv()`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html) can also parse dates. If you want to get a DatetimeIndex, try to use `parse_dates=True`. Then you have only one function call, you don't have to call the `replace()` part and maybe you solved your problem. If not, try to run only one csv-file per time to see where the error comes from.
Answer: Does this give the desired result? (For player_stats)
player_stats = pd.read_csv('data/2017-18_playerBoxScore.csv')
player_stats['gmDate'] = pd.to_datetime(player_stats['gmDate'])
player_stats.set_index('gmDate', inplace=True)


Relative extrema and absolute extrema with only one relative extrema in the function

Question: If a relative maximum is the only relative extrema for it's function, and the function is continuous, can it be guaranteed to be the absolute maximum of the function? And a relative minimum which is the only relative extrema would be the absolute minimum? If so, is there any law that states this?
Comment: Look at the graph of $f(x)=x^2(x-1)$
Comment: @JohnWaylandBales did you mean $f(x) = (x^2)(x-1)$? Or $f(x) = x^(2(x-1))$?
Comment: The expressions $f(x)=x^2(x-1)$ and $f(x)=(x^2)(x-1)$ are equivalent.
Comment: There are 2 relative extrema for the function $f(x) = x^2(x-1)$
Comment: Sorry, I misread your question as "If a relative maximum is the only relative **maximum** $\cdots$".
Comment: @JohnWaylandBales yes, I had accidentally worded the question like that, but I made an edit to fix it. Thank you for your input though!
Answer: You might want to specify continuity, otherwise there are counter-examples.
$$f(x)=\frac{|x|(x-1)}{x^3}$$


Strange MVC problem in VB.NET application with EditorFor method

Question: I have a VB.NET MVC application and there I have the next code:
<%=Html.EditorFor(Function(m) m.UserName, New With {.class = "someClassName"})%>

which works fine on my dev machine, but returns this error after publishing the application to a QA server:

Compiler Error Message: BC30311: Value
  of type ' (line 91)'
  cannot be converted to 'String'.

Also if I remove the second param in EditorFor method, it works, e.g.:
<%=Html.EditorFor(Function(m) m.UserName)%>

The error is same for Editor method.
Any ideas?
This is MVC 2 application on .NET 3.5
Update:
The problem not in name of the 'class' attribute in this case, as I checked other attributes as well without success.
Answer: The method EditorFor doesn't have the overload you are using.
The ones that have two arguments are:
EditorFor(Expression<Func<TModel, TValue>>, Object)
where the object is additional view data.
EditorFor(Expression<Func<TModel, TValue>>, String)
where the string is the template name.
The sad thing is that there isn't any overload that lets you add html attributes.
Comment: I've changed the answer entirely and I think I found the reason.


What is the highest number of consecutive matches lost by a football player?

Question: Jack Grealish (Aston Villa) lost his 20th consecutive game in the Premier League.
So I wonder which players have done worse than that ?
Comment: It's worth making the distinction between "most consecutive defeats in one competition" and "most consecutive defeats overall". Grealish's 20-game losing streak in the Premier League was interrupted by a three-year spell in the Championship, during which time he won quite a few games.
Comment: Surely this has to be a player from [Fort William FC](https://www.bbc.co.uk/sport/football/49186402) ;)
Answer: Probably a player of Darwen 1898-1899 (2nd division). This team has the record of 18 consecutive defeats as mentioned in the Wikipedia article about UK football records.
Comment: The question already pointed out a player who lost 20 consecutive games. How would a player have more straight losses than that (20) if their team only lost 18 straight games?
Comment: It's the first of only two sentences. I'm not sure how you miss it.
Comment: The question doesn't mentionned 20 games **What is the highest number of consecutive matches lost by a football player?**
Comment: Like @F1Krazy says, answer is not correct because _Grealish's 20-game losing streak in the Premier League was interrupted by a three-year spell in the Championship, during which time he won quite a few games_
Comment: This is exactly why I said that the distinction needed to be made. Regrettably, OP has not done that.


Is the ring $K=\mathbb R[t] /( t^3+1)$ integral domain and/or a field? What's $[K: \mathbb R]$?

Question: Is the ring $K=\mathbb R[t] / (t^3+1)$ integral domain and/or a field? What's $[K:R]$?
Since $t^3+1$ is reducible over $\mathbb R$, $K$ isn't a field. How do I check whether it's an integral domain?
Also, how do I calculate this (bizarre?) degree $[K: \mathbb R]$? Maybe it's a typo and should be $[K:\mathbb R[x]]$? How do I calculate it then?
Thanks in advance for any assistance!
Comment: $t^3+1$ is not irreducible over $\mathbb{R}$... $(-1)^3+1=0$...
Comment: $t^3 + 1 = (t - 1)(t^2 + t + 1)$ isn't irreducible over $\Bbb R$. Also, when you write $R$, do you mean $\Bbb R$?
Comment: oops, my bad! Will fix it right away!
Comment: Unless I'm missing something, the 'degree' $[K:\mathbb{R}]$ isn't defined since $K$ isn't a field.
Comment: Yeah, it was asked in case it were a field. How would I calculated it then?
Comment: @Hayden: $[K : \mathbb{R}]$ is well-defined for any $\mathbb{R}$-algebra $K$ (as the dimension of $K$ as an $\mathbb{R}$-vector space). Admittedly that notation is usually reserved for field extensions, though.
Answer: The ring is not an integral domain. Since $t+1$ and $t^2-t+1$ are non zero elements, however their product is $t^3+1=0$.


Find the probability of an event determined by an inequality on exponential random variables

Question: Let X and Y be independent random variables such that $X∼Exp(1)$ and $Y∼Exp(2)$.
Find the probability that $3X+4Y≤5$.
I thought the equation for solving this was the integral from $\int_0^a \int_ 0^{(a-y)} \lambda_1 e^{-\lambda_1 x}\lambda_2 e^{-\lambda_2 y} dx dy$ where $a = 5$, so I first started with the integral from $\int_0^5 \int_0^{(5-y)} 3 \times 1e^{-1x} \times 4 \times 2e^{-2y} dx dy$ and got $23.83828927$ which is much larger than a probability can be. Any help?
Comment: There are two issues: your integral evaluates the integral of $3\times 4=12$ over the triangle $X+Y\le 5, X\ge 0, Y\ge 0$ (which is not what the problem asks for). You evaluated it incorrectly; it works out to $6e^{-10}(e^5-1)^2 \approx 5.919$.
Comment: http://math.stackexchange.com/q/775500/
Answer: The probability density function of an Exponential($\lambda$) variate is, as shown in the question, given by
$$f_\lambda(x) = \lambda\exp(-\lambda x),\ x\ge 0.$$
($f$ is zero for $x\lt 0$.)
The independence assumption says the probability densities of $X$ and $Y$ multiply to give the joint probability density as
$$f_{X,Y}(x,y) = \left(1\times \exp(-1\times x)\right)\left(2\times \exp(-2\times y)\right) = 2\exp(-x-2y).$$
($f_{X,Y}$ is zero if either of $x$ or $y$ is negative.)
Joint densities give probabilities via integration: to find the probability of an event $E$, you integrate the density over the set $E$:
$${\Pr}_{f_{X,Y}}(E) = \iint_E 2 \exp(-x-2y)dx dy.$$
In this case, by remembering the restrictions $x\ge 0$ and $y\ge 0$, $E$ can be written as  $\{(x,y)\ |\ 3x + 4y \le 5, x\ge 0, y\ge 0\}.$  Here is a picture of the graph of $f_{X,Y}$ near this region, with it filled in over $E$ to show how the volume under the graph (the integral) corresponds to the desired probability:

(The gray curves are contours of the graph of the joint density.  Because the density does not change when $-x-2y$ is held fixed, these contours are all curves of the form $-x-2y=\text{ constant},$ which are portions of parallel lines all perpendicular to the vector $(-1,-2)$.)
Evidently $E$ is a triangle determined by $x\ge 0$, $y\ge 0$, and $3x+4y\le 5$. If we choose to perform the $x$ integration last, we find that for each $x$ the value of $y$ can range from a low of $0$ to a maximum of $(5-3x)/4,$ deduced by solving the simultaneous equations $3x+4y\le 5$ and $y\ge 0$.  It is also evident from the figure and the inequalities that $3x$ cannot exceed $5$, whence $x$ must lie between $0$ and $5/3$.  Therefore the desired probability should be computed with an integral like
$${\Pr}(3X+4Y\le 5) = \int_0^{5/3}\int_0^{(5-3x)/4} 2\exp(-x-2y) dy dx .$$
Working it out is elementary and not very instructive (but do it anyway to make sure the result is reasonable this time: partial steps in this direction appear in a duplicate thread on the Math site).  The key thing to learn and remember is how to use joint densities to represent probabilities; the rest is part of the rote branch of Calculus.  It might also be useful to remember that this kind of problem can be solved from first principles with relatively little work and the help of a simple sketch: you multiply (the marginal densities) and integrate the result over the event in question. It's always a good idea to draw a picture of it.  The figure is a good summary of the general procedure.
Answer: Check the distribution function of the generalized integer gamma distribution.
http://en.wikipedia.org/wiki/Generalized_integer_gamma_distribution
(Edit) Also, and answering your question better, check theorem 1 from here http://ac.els-cdn.com/S0047259X97917103/1-s2.0-S0047259X97917103-main.pdf?_tid=8558a38e-cfe5-11e3-b244-00000aacb35d&acdnat=1398807224_cff728a90ab971c59330b2f21843a383 This gives a closed expression for the distribution of what you're looking for.


How to compute the mean of this ratio?

Question: Let $X_i$ be i.i.d. exponential random variables with mean $1$. How to compute the mean of this ratio?
$$ Y = \dfrac{X_i}{\sum\limits_{j=1,j\neq i}^{n}X_j}$$
Is it ?
\begin{align}\mathbb{E}[Y] &= \dfrac{\mathbb{E}[X_i]}{\sum\limits_{j=1,j\neq i}^{n}\mathbb{E}[X_j]}= \dfrac{1}{n-1}\end{align}
Comment: You don't, in general, have that $\mathbb{E} \frac{1}{X} = \frac{1}{\mathbb{E} X}$.
Answer: I will call the denominator $S$. Then recognize that $S\sim\text{Gamma}(n-1, 1)$ and so $\frac{1}{S}$ follows an inverse gamma distribution with expectation $\frac{1}{(n-1)-1} = \frac{1}{n-2}$. If you didn't know that, then you can check with some math
\begin{align*}
E\left[\frac{1}{S}\right] &= \int_0^\infty \frac{1}{s}\cdot f_S(s)\,ds\\
&=\int_0^\infty \frac{1}{s}\cdot \frac{1}{\Gamma(n-1)}1^{n-1}s^{(n-1)-1}e^{-s}\,ds\\
&=\frac{\Gamma(n-2)}{\Gamma(n-1)}\int_0^\infty \frac{1}{\Gamma(n-2)}1^{n-2}s^{(n-2)-1}e^{-s}\,ds\tag 1\\
&=\frac{1}{n-2},
\end{align*}
where the integral in $(1)$ is a gamma density.
Finally, since $S$ and $X_i$ are independent, then
$$E\left[\frac{X_i}{S}\right] = E[X_i]E\left[\frac{1}{S}\right] = 1\cdot \frac{1}{n-2} = \frac{1}{n-2}.$$
Answer: Yes, it is. The sum (call it $S$) in the denominator of $Y$ has the gamma distribution with scale parameter $1$ and shape parameter $n-1$. That is, $S$ has density $f_S(s) = s^{n-2}e^{-s}/(n-2)!$ for $s>0$. By an easy integration, $\Bbb E[1/S]=1/(n-2)$, so $\Bbb E[X_i/S]=1\cdot 1/(n-2)=1/(n-2)$ by independence.

How to compute the mean of this ratio?


$R^2$ in multivariate regression

Question: I'm trying to determine how the population $R^2$ value is defined in the multivariate regression model where we have
$Y_i = \mu_y + B^\prime(X_i - \mu_x) + err$
Where $Y_i \in \mathbb{R}^q$ and $X_i \in \mathbb{R}^p$ and $q, p>1$
Comment: Do you have a multivariate response variable (e.g., predicting blood pressure and pulse) or just multiple predictors?
Comment: @Dave $Y_i$ is a vector in the question, so it's genuine multivariate linear regression. Some assumptions wouldn't hurt though (regarding independence of residuals and samples, mostly)
Answer: For all purposes, a regression like that amounts to several independent multiple regressions. You'd end with $q$ $R^2$ values.
Another way of looking into it, however, is seeing that, for multiple linear regression, $R^2$ is a comparison between deviances. See this answer.
If you specify you model as being a conditional Multivariate Gaussian likelihood, then you can calculate a single $R^2$ (quoting from aforementioned answer):

$$\begin{matrix} \text{Null Deviance} \quad \quad \text{ } \text{ } &
 & \text{ } D_{TOT} = 2(\hat{\ell}_{S} - \hat{\ell}_0), \\[6pt]
 \text{Explained Deviance} & & D_{REG} = 2(\hat{\ell}_{p} -
 \hat{\ell}_0), \\[6pt] \text{Residual Deviance}^\dagger \text{ } & &
 \text{ } D_{RES} = 2(\hat{\ell}_{S} - \hat{\ell}_{p}). \\[6pt]
 \end{matrix}$$
In these expressions the value $\hat{\ell}_S$ is the maximised log-likelihood under a saturated model (one parameter per data point), $\hat{\ell}_0$ is the maximised log-likelihood under a null model (intercept only), and $\hat{\ell}_{p}$ is the maximised log-likelihood under the model (intercept term and $p$ coefficients).

In your case: $y_{q\times 1} \sim MVN(\beta_{q\times p} X_{p \times 1}, \Sigma_{q\times q})$.
Let $\hat y = E[y] = \beta x$.
Let $Y$ be the concatenation of all $y$, and similarly for $X$.
You can derive the maximum likelihood estimates and compute the following:

$$R^2 = 1-\frac{D_{RES}}{D_{TOT}} = 1-\frac{(\hat{\ell}_{S} - \hat{\ell}_{p})}{(\hat{\ell}_{S} - \hat{\ell}_0)}$$

$R^2$ in multivariate regression


urllib2 - counting number of lines in a .xlsx file - python

Question: file_url = 'http://127.0.0.1:8000/media/temp/aggregate_bill_export_20180427055420580970.xlsx'
meta = urllib.urlopen(file_url)

total_records = len(meta.readlines())

print total_records

Output that I'm getting:
Out[97]: 20
But this file contains only 10 records. However it returns correct count in case of .csv file. Please suggest what to do for .xlsx file.
Thanks!
Answer: You can't read xlsx file as the way you read normal text files. You need to use xlrd module for this.
First get the file and then use xlrd module to read that xlsx
In [12]: import requests

In [13]: import urllib

In [14]: import xlrd

In [15]: link = "http://f8f44d1e.ngrok.io/static/covernote_receipt/xyz.xlsx"

In [16]: file_name, headers = urllib.urlretrieve(link)

In [17]: workbook = xlrd.open_workbook(file_name)

In [18]: sheet = workbook.sheet_by_index(0) # Get your sheet here

In [19]: sheet
Out[19]: <xlrd.sheet.Sheet at 0x10fd3e090>

In [21]: sheet.nrows # No. of rows
Out[21]: 3

In [22]: sheet.ncols # No. of columns
Out[22]: 1

In [23]:

Here is my xlsx contents,
Comment: Thanks for your quick response Rakesh. I beleive that you tried this for .txt file. Do try the same with any .xlsx file
Answer: file_url = 'http://127.0.0.1:8000/media/temp/aggregate_bill_export_20180427055420580970.xlsx'
meta = urllib.urlopen(file_url)

xlsx=meta.read()

wb = load_workbook(StringIO.StringIO(xlsx))

sheet = wb.worksheets[0]

total_records = sheet.max_row

Please review and suggest if something can be optimized.
Answer: A CSV file is a text file that simply consists of rows separated by linebreaks. An Excel file is a binary file using a proprietary Microsoft format. For a CSV file the notion of "lines" makes sense. It is nonsensical for an Excel file.
If you want to count the rows in an Excel file you will have to use a library that can parse such a file. Just using .readlines() on the HTTP response body of an Excel file will not work.
Comment: Got it. Thanks for sharing this info


Upper bound for network connection game when $\alpha > n^2$

Question: I have proven that when $\alpha > n^2$ every equilibrium must be a tree and that the lower bound for the social cost is $\Omega(\alpha n + n^2)$. I know that the PoA = $O(1)$, so the upper bound must be $O(\alpha n + n^2)$ but I can't prove it. Any kind of help is appreciated.
Answer: Since $\alpha > n^2$, the lower bound actually is $\Omega(\alpha n)$. As for the upper bound, overestimating the distance for every node we get also $O(\alpha n)$. So, PoA=O(1).


Interactive filter options for views

Question: I have setup a view with contextual filters; it works great.
Now I just need to setup a few drop downs to allow users to filter on criteria. Does the Views module support this in Drupal 7?
Should I just build a quick module using the form API, set the module to block level, and show the block above the listings?
What's the best practice here?
Answer: You can allow your users to filter the view data by "exposing" your filters. See screenshot:

Interactive filter options for views


Confusion regarding least squares method

Question: I am having some confusion regarding least squares method. Actually, least squares method is for minimizing the square of the $L_2$ norm of $Ax-b$ as given in this video lecture. However I am confused if we are given a set of points like $(x_1,y_1),(x_2,y_2)...(x_4,y_4)$. Then our model is something like
$$y=ax+b$$
where we have to find the parameters and b. So we need to minimize the square of the $L_2$ norm of
$$(y-ax-b)$$
isn't it?
Answer: Minimizing $(Ax-b)^2$ is wrong; minimizing $(y-(Ax+b))^2$ is right.
Comment: They're not solving linear regression. They're doing a math problem. There's no need for them to mention "y" in this context at all. The only problem they have is to minimize Ax-b. Linear regression just happens to be a problem you can reduce to that form. "A" becomes a matrix of [[1 x1] [1 x2] [1 x3] [1 x4]]; "x" is the vector of [b a]; "b" is y.
Comment: Oh, that's just notation. They're doing plain convex optimization, not linear regression, so they're defining "b" to be (y-b) in the linear regression case. In the problem they're solving, there is no "y". Is that clear? They're just solving for x; A and b are assumed known. (edit: last statement was wrong)
Comment: It's in this video lecture http://www.stanford.edu/class/ee364a/videos/video01.html. This is really popular. I think I might have misinterpreted something. I just need some clarifications
Comment: Can you give me a good working example?


How to pop item from list and push it back to list based on condition using python

Question: I have list with urls for crawling.['http://domain1.com','http://domain1.com/page1','http://domain2.com']
Code:
prev_domain = ''
while urls:
    url = urls.pop()
    if base_url(url) == prev_domain: # base_url is custom function return domain of an url
        urls.append(url) # is this is possible?
        continue
    else:
        crawl(url)

Basically I dont want to crawl webpages of same domain continuously. Continuosly crawling a domain url, return http response status code with 429: Too Many Requests. The user has sent too many requests in a given amount of time ("rate limiting"). To by-pass this issue, I'm planning to go with below logic.
Loop through all items in the list and compare current element base url with previously processed element base url.
If base urls are different then process for next step, otherwise do not process current element, just append this element to the same list.
Note : If urls in list are of same domain, make delay in processing each element and then execute.
Please provide your thoughts.
Comment: Problem description is bit confusing, can you provide the sample output which you are expecting ?
Comment: @BharatJogdand i have edited my question for better understanding.
Answer: Your algorithm is almost correct, but not the implementation:
>>> L = [1,2,3]
>>> L.pop()
3
>>> L.append(3)
>>> L
[1, 2, 3]

That's why your program loops forever: if the domain is the same as the previous domain, you just append then pop then append, then.... What you need is not a stack, it's a round robin:
>>> L.pop()
3
>>> L.insert(0, 3)
>>> L
[3, 1, 2]

Let's take a shuffled list of permutations of "abcd":
>>> L = [('b', 'c', 'd', 'a'), ('d', 'c', 'b', 'a'), ('a', 'c', 'd', 'b'), ('c', 'd', 'a', 'b'), ('b', 'd', 'a', 'c'), ('b', 'a', 'd', 'c'), ('b', 'c', 'a', 'd'), ('a', 'b', 'd', 'c'), ('d', 'a', 'b', 'c'), ('a', 'b', 'c', 'd'), ('d', 'c', 'a', 'b'), ('a', 'd', 'c', 'b'), ('d', 'a', 'c', 'b'), ('c', 'd', 'b', 'a'), ('d', 'b', 'c', 'a'), ('d', 'b', 'a', 'c'), ('a', 'd', 'b', 'c'), ('b', 'd', 'c', 'a'), ('c', 'b', 'd', 'a'), ('c', 'a', 'b', 'd'), ('b', 'a', 'c', 'd')]

The first letter is the domain. Here's a slightly modified version of your code:
>>> prev = None
>>> while L:
...     e = L.pop()
...     if L and e[0] == prev:
...         L.insert(0, e)
...     else:
...         print(e)
...         prev = e[0]
('b', 'a', 'c', 'd')
('c', 'a', 'b', 'd')
('b', 'd', 'c', 'a')
('a', 'd', 'b', 'c')
('d', 'b', 'a', 'c')
('c', 'd', 'b', 'a')
('d', 'a', 'c', 'b')
('a', 'd', 'c', 'b')
('d', 'c', 'a', 'b')
('a', 'b', 'c', 'd')
('d', 'a', 'b', 'c')
('a', 'b', 'd', 'c')
('b', 'c', 'a', 'd')
('c', 'd', 'a', 'b')
('a', 'c', 'd', 'b')
('d', 'c', 'b', 'a')
('b', 'c', 'd', 'a')
('c', 'b', 'd', 'a')
('d', 'b', 'c', 'a')
('b', 'a', 'd', 'c')
('b', 'd', 'a', 'c')

The modification is: if L and, because if the last element of the list domain is prev, then you'll loop forever with your one element list: pop, same as prev, insert, pop, ...(as with pop/append)
Here's another option: create a dict domain -> list of urls:
>>> d = {}
>>> for e in L:
...     d.setdefault(e[0], []).append(e)
>>> d
{'b': [('b', 'c', 'd', 'a'), ('b', 'd', 'a', 'c'), ('b', 'a', 'd', 'c'), ('b', 'c', 'a', 'd'), ('b', 'd', 'c', 'a'), ('b', 'a', 'c', 'd')], 'd': [('d', 'c', 'b', 'a'), ('d', 'a', 'b', 'c'), ('d', 'c', 'a', 'b'), ('d', 'a', 'c', 'b'), ('d', 'b', 'c', 'a'), ('d', 'b', 'a', 'c')], 'a': [('a', 'c', 'd', 'b'), ('a', 'b', 'd', 'c'), ('a', 'b', 'c', 'd'), ('a', 'd', 'c', 'b'), ('a', 'd', 'b', 'c')], 'c': [('c', 'd', 'a', 'b'), ('c', 'd', 'b', 'a'), ('c', 'b', 'd', 'a'), ('c', 'a', 'b', 'd')]}

Now, take an element of every domain and clear the dict, then loop until the dict is empty:
>>> while d:
...     for k, vs in d.items():
...          e = vs.pop()
...          print (e)
...     d = {k: vs for k, vs in d.items() if vs} # clear the dict
...
('b', 'a', 'c', 'd')
('d', 'b', 'a', 'c')
('a', 'd', 'b', 'c')
('c', 'a', 'b', 'd')
('b', 'd', 'c', 'a')
('d', 'b', 'c', 'a')
('a', 'd', 'c', 'b')
('c', 'b', 'd', 'a')
('b', 'c', 'a', 'd')
('d', 'a', 'c', 'b')
('a', 'b', 'c', 'd')
('c', 'd', 'b', 'a')
('b', 'a', 'd', 'c')
('d', 'c', 'a', 'b')
('a', 'b', 'd', 'c')
('c', 'd', 'a', 'b')
('b', 'd', 'a', 'c')
('d', 'a', 'b', 'c')
('a', 'c', 'd', 'b')
('b', 'c', 'd', 'a')
('d', 'c', 'b', 'a')

The output is more uniform.
Answer: Check the following code snippet,
urls = ['http://domain1.com','http://domain1.com/page1','http://domain2.com']

crawl_for_urls = {}
for url in urls:
    domain = base_url(url)
    if domain not in crowl_for_urls:
        crawl_for_urls.update({domain:url})
        crawl(url)

crawl() will be called only for unique domain.
Or you can use:
urls = ['http://domain1.com','http://domain1.com/page1','http://domain2.com']

crawl_for_urls = {}
for url in urls:
    domain = base_url(url)
    if domain not in crowl_for_urls:
        crawl_for_urls.update({domain:[url]})
        crawl(url)
    else:
        crawl_for_urls.get(domain, []).append(url)

This way you can categories the URL's based on domain and also can use crawl() for unique domain.