Como salvar globalmente o output de uma função no R?

Question: Tenho problemas para salvar a saída de funções no R. No código a seguir, por exemplo, crio uma matriz que representa um jogo de sudoku:
quantLinhas <- readline(prompt = 'insira o número de linhas do sudoku: ') #para saber a dimensão do sudoku
quantLinhas <- as.numeric(quantLinhas) #readline salva como string, transferindo para numérico

construcaoSudoku <- function(){
  matrizSudoku <- NA   #atribuindo NA para o rbind funcionar corretamente

  for(i in seq(1, quantLinhas)){
    linhaEntrada <- scan()
    matrizSudoku <- rbind(matrizSudoku, linhaEntrada)
  }
  matrizSudoku <- matrizSudoku[-1,]    #retirando a primeira linha, composta por NAs
  sudoku <- return(matrizSudoku)
}

reparem na última linha, onde tento retornar a matrizSudoku e salvá-la na variável sudoku.
Acontece que não funciona, ao que parece, a variável sudoku é gerada localmente, mas não globalmente. Preciso dela salva globalmente pois será usada mais a frente por outra função
Comment: Aparentemente, depois de criada a função, eu posso rodar ela atribuindo-a a uma variável, desta forma: `sudoku <- construcaoSudoku()`
Mas não há como fazer isso dentro da própria função?
Answer: O princípio a seguir é este:

Em R as funções retornam o resultado da última instrução.

Então, para retornar uma variável, basta pô-la sózinha na última instrução.
construcaoSudoku <- function(){
  matrizSudoku <- NA   #atribuindo NA para o rbind funcionar corretamente

  for(i in seq(1, quantLinhas)){
    linhaEntrada <- scan()
    matrizSudoku <- rbind(matrizSudoku, linhaEntrada)
  }
  matrizSudoku <- matrizSudoku[-1,]    #retirando a primeira linha, composta por NAs
  matrizSudoku
}

Também podia ser return(matrizSudoku) mas a função return não é necessária neste caso.
Para atribuir o resultado da função no .GlobalEnv é fácil. Basta atribuir o resultado da função, não dentro da função.
sudoku <- construcaoSudoku()

Finalmente, isto responde à pergunta tal como foi colocada. Mas eu não utilizaria uma variável, quantLinhas definida fora da função e que não é passada como argumento. Creio que isto é má prática, a evitar se possível.
A função ficaria melhor com um argumento:
construcaoSudoku <- function(n){
  matrizSudoku <- NA   #atribuindo NA para o rbind funcionar corretamente

  for(i in seq_len(n)){
    linhaEntrada <- scan()
    matrizSudoku <- rbind(matrizSudoku, linhaEntrada)
  }
  matrizSudoku <- matrizSudoku[-1,]    #retirando a primeira linha, composta por NAs
  matrizSudoku
}

sudoku <- construcaoSudoku(quantLinhas)

Uma função equivalente, mas mais simples, é a versão abaixo, com um ciclo replicate.
construcaoSudoku2 <- function(n){
  matrizSudoku <- t(replicate(n, scan()))
  matrizSudoku
}

sudoku2 <- construcaoSudoku2(quantLinhas)

Ou até, numa única linha de código,
construcaoSudoku3 <- function(n) t(replicate(n, scan()))


How do I get Location / GMap / Views setup to display non-US map nodes?

Question: Drupal 6, Views 2
I'm using the Location module to store address information for various contacts in nodes. I am then using the Views module along with the GMap sub-module of Location to display these nodes as map markers on a Google Maps style map on a page in my site.
This works perfectly for USA addresses, but I can't get Canada or UK addresses to display on the node map. The link inside the node (from Location module) to view the location in an external Google Map works just fine, so I can confirm the addresses are valid. However, they do not display on my Drupal Views generated Google Map a la Location/GMap.
Note - disabled and/or cleared cache to make sure this wasn't an issue. Also Regenerated marker cache inside of Location configuration to rule that out also.
Is there some kind of configuration setting I'm missing?
Comment: Off the top of my head, I'd look at  `admin/settings/location/geocoding` and make sure you've selected google for Canada and the UK.
Comment: I added a screenshot showing that I have enabled Canada in the Geocoding section like you mentioned. It was one of the first things I looked at. Thank you
Answer: I can confirm that it is possible to get locations and GMAP running on Drupal 6 for Canadian addresses.  I have done this on more than one occasion.
From your description it simply sounds some setting preventing the reverse geocoding of addresses. Edit one of your nodes with canadian addresses and confirm that the Lat and Lon field are empty.  Save then edit again and confirm it is still empty.
If the lat/lon fields are empty try the following

Make sure you have a valid google maps API key for the URL you are running the site under.
Confirm that the location module has access to this API keys. Reverse geocoding settings for locations module is under /admin/settings/location/geocoding go to Canada and click "Configure parameters"   Or go there directly: /admin/settings/location/geocoding/ca/google  Your Gmap google map api key should be displayed.
Confirm that as a user you have permission to save lat/long info.  Under user permissions (/admin/user/permissions) go to "location module" and check that  "submit latitude/longitude" is selected for users that will be creating the nodes with address information. If not then there will be no reverse geocoding for any address, Canadian or otherwise.
Once you have confirmed the above, revisit a node with a Canadian address.  Edit and hit save. This will re-run the reverse geocoding.  If a lat/long is not saved then I will have to do some more digging. Also if you have lots of nodes in need of reverse geocoding, it is possible to do this programmatically.
Are you using CCK field or location module itself to save the address and lat/on? I am uncertain whether or not reverse geocoding works with the cck location field in D6.
Comment: @DavidCsonka - an manually enter the lat/lon (use map.google.com) on a Canadian node and have it show up on your map? For example the lat/ lon coordinates 49.268033, -123.147000 should put you just outside of downtown Vancouver in the Kitsilano neighbourhood.
Comment: @DavidCsonka - Beyond that I think I would need to login to troubleshoot.  It has to be some innocuous setting.
Comment: @DavidCsonka - Yes there are some oddities with the location module and that was one I forgot. The real rub, is if you look at the fields available (devel module) you will see that it does know about province abbreviation.  Glad I could help
Comment: Thanks for the excellent troubleshooting. Still not working, here is my feedback. I have an API key, how do I confirm that it is valid? I assume it is since it resolves USA addresses. The API key is displayed for the Canada Google Geocoding config page. I have confirmed that all user roles have "submit latitude/longitude - location module" checked. I went to one of my Canada nodes, and confirmed that there is *no* Lat/Long info, I edited the node and saved, and still no Lat/Long info was input into the Location fields. Field = Locations - Node Locations module form.
Comment: Conversely, one of my test USA nodes *does* have the Lat/Long coordinates in the appropriate fields on the node, and it *does* display correctly on my map. So, the problem is how do I get my Canada/UK nodes to populate the Lat/Long fields automatically like the USA ones do.
Comment: Ok, I think I figured it out. Again, your exceedingly thorough process helped me figure it out. I again went through everything, refreshed the supported country list, also went in and did manual edits to the location info in the nodes. What worked was changing the Province data in the location field. I had manually input "BC" for *British Columbia* but when I went back and manually input "British Columbia" causing autocomplete to activate, and offer the same data *British Columbia*, upon saving the Lat/Long info was correctly added.
Comment: So, apparently one cannot input abbreviations manually into the location field. It seems to confuse the geocoder and causes it to fail.
Answer: Hi there is a table in drupal which stores locations postal code.
The name of the table you should look is for drupal.zipcodes
Now, you need to import Canada's zipcode sql dump to this zipcode table.
Once you have imported the codes, refresh the cache and then create content and it should display Canada's location nodes.


Which one to compromise between MAPE and Adj R square in multiple regression

Question: I'm trying to forecast sales of a product based on the other variables like Competitor sales, Fuel Price and CPI (Consumer Price Index).
The below given output (based on 1 to 44 months) gives me the lowest MAPE 11.62 when I validated with 45 to 48 actual sales
Coefficients:
                              Estimate Std. Error t value Pr(>|t|)
(Intercept)                 -2320.6320   496.3898  -4.675 3.83e-05 ***
Sales lag_1                     0.2124     0.1119   1.898 0.065515 .
Competi_sales(1) lag1          -1.6535     0.8875  -1.863 0.070404 .
Competi_Sales(1)_lag3          -5.4108     0.8352  -6.478 1.42e-07 ***
Competi sales(2)_lag1           2.3004     0.5726   4.017 0.000277 ***
Fuel price                     -48.3714    17.5225  -2.761 0.008926 **
CPI                            22.2696     3.4485   6.458 1.51e-07 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 212.7 on 37 degrees of freedom
Multiple R-squared:  0.7252,    Adjusted R-squared:  0.6806
F-statistic: 16.27 on 6 and 37 DF,  p-value: 4.58e-09

I understand that by removing Sales lag_1 and Competi_sales(1) lag1 from the model (since both are not significant at alpha 0.05), the Adjusted R squared can be improved from 0.6806 but when If I do that the MAPE is increasing.  For business use, MAPE is often preferred because apparently managers understand percentages better than other accuracy parameters.
Should I go ahead and forecast the sales using this model or should I remove the insignificant variables?
Comment: In-sample performance may be a poor indicator of out-of-sample forecasting performance. Instead you could estimate your candidate models on a training sample, validate them on a validation sample and then select the best one (in terms of MAPE if you like) to be used for actual forecasting.
Comment: Only 4 obs. in the validation set is quite little... I understand your whole sample is small (48 obs.) but validation set should preferably be larger (e.g. 32 obs. for training and 16 for validation). And if you are in a time series setting, you could use a rolling window.
Comment: The above given Regression output is based on 44 (1 to 44) months then I validated the model with 4 months (45 to 48) which I retained for validation. I have given this information in my recent edit. I missed to mention, sorry about that..
Comment: Thanks, Going forward I will get enough sample. Unfortunately, now I would need to predict the next 3 or 4 months sales figures with available data. Will this regression approach still work for me?
Comment: Not quite sure what you mean by *this regression approach*. The suggestions by @StephanKolassa make sense to me, you could very well try them out.
Comment: The provided results are from multiple regression output.. So I mentioned as Regression approach. Thanks for your inputs.
Answer: +1 to @RichardHardy's comment. In-sample fit is not a good guide to out-of-sample forecast accuracy. Relying on in-sample fits can/will lead to overfitting and poor out-of-sample performance. Instead, use a holdout sample and check accuracy on that.
I heartily recommend this free open source online forecasting textbook, especially the section on evaluating accuracy.
In addition, it is not automatically the case that removing insignificant predictors will improve your adjusted $R^2$. This may happen or not.
Finally, you are including lagged sales. You may want to look at ARIMA models (e.g., auto.arima() in the forecast package, where you can include additional eXplanatory or eXternal variables like laggged competitor sales - note: which you will need to forecast again out-of-sample - or CPI via the xreg parameter.
Comment: If you want to predict, $R^2$ is irrelevant - it's a measure of model fit. Do what the holdout sample suggests. However, remember that real data is noisy, so if the improvement in MAPE is trivial, it may turn out afterwards that the other model may have been better anyway.
Comment: Provided links are very useful. This validation (MAPE) is based on hold out sample (my recent edit have this information, sorry for not mentioning this earlier). I agree with you on improving the Adj R-sqrd, if it improves by removing insignificant predictor at the same time if increases MAPE.  (Let's ignore lagged predictors from this scenario) For example we have CPI, Fuel Price and Product price are the predictors and one of them is insignificant and removing that improves the Adj-R sqrd and reduces the accuracy. What's your suggestion in this scenario?


In R, extract lists with same name from lists of list

Question: I have a list of lists where I would like to extract and combine those with the same name (in the example below I'd like to separate cof and pred). (I would prefer a tidyverse solution.)
Example data:
outputlist <- list(
    list(cof=0.12),
    list(pred=c(1, 2, 3)),
    list(cof=0.34),
    list(pred=c(4, 5, 6)),
    list(cof=0.56),
    list(pred=c(7, 8, 9))
  )

I would like to separate these so that I have one vector/dataframe with all cofs; and then another dataframe/vector with all predictions.
I've tried this (but it does not separate them):
 outputlist %>% bind_cols()

Thanks in advance
Answer: You can try :
library(dplyr)
library(purrr)

outputlist %>% bind_rows() %>% split.default(names(.)) %>% map(na.omit)

#$cof
# A tibble: 3 x 1
#    cof
#  <dbl>
#1  0.12
#2  0.34
#3  0.56

#$pred
# A tibble: 9 x 1
#   pred
#  <dbl>
#1     1
#2     2
#3     3
#4     4
#5     5
#6     6
#7     7
#8     8
#9     9

Answer: Not a tidyverse solution, but a base R one-liner:
lapply(split(outputlist, sapply(outputlist, names)), as.data.frame)
#> $cof
#>    cof cof.1 cof.2
#> 1 0.12  0.34  0.56
#>
#> $pred
#>   pred pred.1 pred.2
#> 1    1      4      7
#> 2    2      5      8
#> 3    3      6      9

Answer: We can also do
library(dplyr)
library(purrr)
library(tidyr)
outputlist %>%
      map_dfr(~ enframe(.x) %>%
                    unnest(c(value))) %>%
      {split(.$value, .$name)}


Is there a way to set automatic properties in secondary constructors?

Question: I have this class:
type Sample() =
    member val test1 = "" with get,set
    member val test2 = "" with get,set

    // is something like the below constructor possible
    new Sample(result1, result2) =
        this.test1 <- "failed"
        this.test2 <- "passed"
        Sample()

I've tried several different ways, but I can not get it to work.
Answer: Is this what you want?
type Sample(result1, result2) =
    member val Test1 = result1 with get,set
    member val Test2 = result2 with get,set
    new () = Sample("failed", "passed")

FSI:
> Sample();;
val it : Sample = FSI_0002+Sample {Test1 = "failed";
                                   Test2 = "passed";}
> Sample("foo", "bar");;
val it : Sample = FSI_0002+Sample {Test1 = "foo";
                                   Test2 = "bar";}

Comment: Well I am aware that it can be done that way in the primary constructor, but I was just curious if it were possible the other way around.
Answer: @Mark Seemann's answer is the proper solution, but you can get exactly what you want using this odd construction:
type Sample() =
    member val test1 = "" with get,set
    member val test2 = "" with get,set

    new (result1, result2) as sample =
        Sample()
            then
                sample.test1 <- result1
                sample.test2 <- result2

But truth be told, this is something I have never used myself, likely never seen used in the wild and more of a language-trivia sort of thing than anything else.
Comment: @Mark Seemann, Sorry, but what you expect it to do? https://dotnetfiddle.net/wq711M
Comment: Huh. I suppose that's because the arguments were not used (which is also what OP's code did).
Comment: This is perfectly valid, but it will result in runtime initialization checks in the compiled code, which is a small perf hit.
Comment: @FoggyFinder I would have expected it to do *sensible* initialization, like not throwing away the constructor arguments, but I realise that perhaps I've slightly misread the OP...
Comment: @FoggyFinder: check the previous revision - the properties were set to hardcoded strings instead (which I took from OP's code, but it likely wasn't the intent there so I edited it). Anyway, that's not the point here - the syntax for the constructor is.


How can I add menu items when importing nodes into Drupal 7 (with the Feeds module)?

Question: I'm importing a site using the Feeds module, and I do not see any way to specify which nodes should get a menu item.  How can I do this?
If the Feeds module cannot do this, is there another way?
Answer: You can try the sandbox project Feeds Menu

Adds mapping elements for menu entries for feeds


Various ways to get month name from inbuilt C library

Question: What are the various ways to get the name of the month corresponding to an integer value [say 0 for Jan,1 for February ,...,11 for December] from inbuilt C/C++ library, I am familiar to strftime.Any other means to do the same ?
Comment: Why would you need more than one method, and why would the standard library provide more than one method?  That would be remarkably inefficient, and that is not the nature of the standard library which is remarkably terse.
Comment: The std::time_put STL class is another way.  Just harder to use.
Comment: On what platforms? nl_langinfo isn't supported on Windows.
Answer: #include <langinfo.h>
#include <locale.h>
#include <stdio.h>
int main() {
    const nl_item nl_abmons[12] = {ABMON_1, ABMON_2, ABMON_3, ABMON_4,
                                   ABMON_5, ABMON_6, ABMON_7, ABMON_8,
                                   ABMON_9, ABMON_10, ABMON_11, ABMON_12};
    const nl_item nl_months[12] = {MON_1, MON_2, MON_3, MON_4, MON_5, MON_6,
                                   MON_7, MON_8, MON_9, MON_10, MON_11, MON_12};
    int i;
    setlocale(LC_ALL, "");
    for (i = 0; i < 12; i++) {
        printf("%d\t%s\t%s\n",
                i+1, nl_langinfo(nl_abmons[i]), nl_langinfo(nl_months[i]));
    }
    return 0;
}

$ cc months.c
$ LANG=ja_JP.utf8 ./a.out
1        1月    1月
2        2月    2月
3        3月    3月
4        4月    4月
5        5月    5月
6        6月    6月
7        7月    7月
8        8月    8月
9        9月    9月
10      10月    10月
11      11月    11月
12      12月    12月
$ LANG=ru_RU.utf8 ./a.out
1       Янв     Январь
2       Фев     Февраль
3       Мар     Март
4       Апр     Апрель
5       Май     Май
6       Июн     Июнь
7       Июл     Июль
8       Авг     Август
9       Сен     Сентябрь
10      Окт     Октябрь
11      Ноя     Ноябрь
12      Дек     Декабрь
$ LANG=de_DE.utf8 ./a.out
1       Jan     Januar
2       Feb     Februar
3       Mär     März
4       Apr     April
5       Mai     Mai
6       Jun     Juni
7       Jul     Juli
8       Aug     August
9       Sep     September
10      Okt     Oktober
11      Nov     November
12      Dez     Dezember

It does so happen in all implementations I know of that MON_1..MON_12 are sequential, so this could be written for (i = 0; i < 12; i++) printf("%d %s\n", i+1, nl_langinfo(MON_1+i)); with the same practical effect, but I don't see that guaranteed in documentation anywhere.
Comment: That's nice !! But could we convert it such that it correspond to integer values ? Ofcourse I don't want to build up a big hash map for MON_{1-12} :)
Comment: NB: nl_langinfo isn't supported on Windows.
Answer: // For Windows systems, using LCID
LCID lcid = MAKELANGID(LANG_FRENCH,SUBLANG_FRENCH_CANADIAN);
TCHAR szMonth[12][20] = {0};
for (int i=0;i<12;i++)
{
    if ( ::GetLocaleInfo(lcid, LOCALE_SMONTHNAME1+i, szMonth[i], ARRAY_COUNT(szMonth[i])) )
        szMonth[i][0]=_toupper(szMonth[i][0]); // For better formatting ( French for instance)
}

Note : The LCID of target language can be read from the exe resources ( with VerQueryValue(...,_T("\VarFileInfo\Translation"),...) , or built with MAKELANGID macro


Get name of Tool Strip Menu Item into messagebox

Question: I have a Tool Strip Menu with an entry named "General". When the form is loaded sub items are added to the "General" entry which are the result of reading the file names of text files in a folder.
I want to be able to capture the names of the sub items and add them to a label in the generic form which is called from clicking on the sub item.
I've tried using MsgBox(DirectCast(sender, ToolStripMenuItem).Text) in an attempt to capture the text initially, however, it just gives me the "General" menu item in the messagebox
I am currently using this code in the DropDownItemClicked event
Any ideas?
Answer: The submenu items are in the collection ToolStripMenuItem.DropDownItems. You can cycle through the collection and select the ToolStripMenuItems. Not every item in the menu is a ToolStripMenuItem (there are separators, buttons, etc.), so you can cycle through with a ToolStripItem.
This example puts all the submenu items in a message box:
Private Sub mnuDraw_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuDraw.Click

Dim s As String = ""
For Each item As ToolStripItem In sender.DropDownItems
  If TypeOf (item) Is ToolStripMenuItem Then s &= item.Text & vbCrLf
  Next item
MsgBox(s)

End Sub

Comment: Thanks, probably being a bit dumb but I'm not entirely sure what you mean
Comment: It's not dumb if you don't have all the information... I'll explain a little better.
Comment: I get it now, thanks - just need to adapt it so it only displays the selected menu item


Flatlist - lista subindo e invadindo espaço do menu

Question: Boa noite, estou com um problema em minha aplicação em react, minha lista (flatlist) quando fica com muitos itens, a lista acaba subindo na página e invadindo o espaço do menu de minha aplicação que esta inserido acima dela.
index.js (Home)
import { StyleSheet, Text, View } from 'react-native';

import Header from '../../components/Header';
import Actions from '../../components/Actions';
import List from '../../components/list';

export default function Home() {
  return (
    <View style={styles.container}>

        <Actions/>

        <Text style={styles.title}>Mapas:</Text>

        <List/>

    </View>

  );
}

const styles = StyleSheet.create({
  container: {
    backgroundColor: '#fafafa',
  },
    title:{
    fontSize: 18,
    fontWeight: 'bold',
    margin: 14,
    marginEnd: 14,
  }
});

Conteúdo das configurações de index.js (List)
const styles = StyleSheet.create({
    container: {
      backgroundColor: '#fafafa',
    },
    list:{
      marginStart: 14,
      marginEnd: 14,
    }

Segue imagem do problema
Estou me embaralhando nesse ajuste, no mais esta tudo correto, alguém pode me explicar onde estou pecando?
Obrigado!
Comment: Ainda procuro uma solução, quando achar posto aqui.
Answer: Consegui resolver, estava esquecendo que tinha definido uma animação nos ícones dos botões que acabei mudando de ideia, porém não tinha removido a seguinte linha:
   marginTop: 10,
    }

Ele estava empurrando minha lista pra cima do menu, após remover o marginTop consegui resolver o problema, fica a dica pra quem ter o mesmo descuido que tive.


Google Map Tilt not working

Question: I am developing a site with some parcels ( layers on google map ) and the client wants the map to be in tilt view. I understand the google api but i don't know why my tilt setting and heading are not taken into consideration.
This is my code creating the map:
map = new google.maps.Map(document.getElementById('map-canvas'), {
    zoom: 18,
    center: new google.maps.LatLng(35.8313284, -82.7251666),
    mapTypeId: google.maps.MapTypeId.SATELLITE,
    heading: 90,
    tilt: 45
});

I see the working examples but i can't get mine to work. here you can see it live
http://sigmalogic.eu/mapdwr/index.html.
I just want to know why the tilt is not working, or heading is good at first but it rotates.
Answer: If you want to avoid getting errors when asking for 45° imagery, you can first test if imagery is available:
if (map.getTilt()) {

    map.setTilt(45);
}

JSFiddle demo
Hope this helps.
Comment: Thank you for this also ... this one is for the future :)
Answer: Google doesn't have 45°-Images everywhere. The Documentation states:

45° Imagery
The Google Maps API supports special 45° imagery for certain
  locations. This high-resolution imagery provides perspective views
  towards each of the cardinal direction (North, South, East, West).
  These images are available at higher zoom levels for supported map
  types.
[...]
The existing google.maps.MapTypeId.SATELLITE and
  google.maps.MapTypeId.HYBRID map types support 45° perspective imagery
  at high zoom levels (where available).

You can see the currently available locations on this map.
Comment: ok i understand, i thought that if it had tilt when searching for it on google maps ( https://firstname.lastname@example.com,-82.7246444,723a,35y,39.14t/data=!3m1!1e3?hl=en-US ) it could have also on my code
Comment: Not everything that works on google maps works with the api, too. As an xample, zoom out as much ach possible on google maps and you'll see the earth as an actual sphere - sadly, you can't do this (and a lot more things) via the api (https://firstname.lastname@example.com,-95.866853,17089823m/data=!3m1!1e3?hl=en-US)

Google Map Tilt not working


Java clientside socket can't regonize heroku server

Question: I have setup a server running using ServerSocket on heroku. I know that heroku defines the port in a system defined variable, and I'm using that as well. Here is the snippet of the server code on Heroku.
ServerSocket serverSocket = null;
try {
   serverSocket = new ServerSocket(Integer.parseInt(System.getenv("PORT"));
   System.out.println("Booted server.  " + Integer.parseInt(System.getenv("PORT"));
   System.out.println(serverSocket);
} catch (IOException e) {
   System.err.println("Could not listen on port: " + Integer.parseInt(System.getenv("PORT"));
   System.exit(1);
}
Socket clientSocket = null;
    try {
        while (true) {
            clientSocket = serverSocket.accept()
            ConnectionHandler c = new ConnectionHandler(clientSocket);
        }

Running that and checking heroku logs shows that the server is running fine,
2013-11-22T03:02:21.940969+00:00 app[web.1]: Booted server.  40506
2013-11-22T03:02:21.953200+00:00 app[web.1]: ServerSocket[addr=0.0.0.0/0.0.0.0,localport=40506]

Next I'm running an android app, that requires to send/receive information. Here is the snippet of code that connects to the port.
clientSocket = new Socket(http://appname.herokuapp.com, 40506);

However I get the following in logcat on the above line:
java.net.UnknownHostException: Unable to resolve host "http://appname.herokuapp.com": No address associated with hostname
at java.net.InetAddress.lookupHostByName(InetAddress.java:424)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
at java.net.InetAddress.getAllByName(InetAddress.java:214)
at java.net.Socket.tryAllAddresses(Socket.java:108)
at java.net.Socket.<init>(Socket.java:177)
at java.net.Socket.<init>(Socket.java:149)
at com.example.taid.FullscreenActivity.CheckAccount(FullscreenActivity.java:241)

What's causing this error? Is that not the correct server address? On the server side, upon accepting a new connection I do have a print statement (testing purposes), and going to the url from web browser it prints the statement, so heroku accepts connection.
Also several things I noticed on Heroku:
1) Every few minutes the port gets incoming connections from a certain ip. During a single run, the ip is same with ports incrementing by 1. What are these connections? Can i stop them?
2) When I use the command to print the variable port (cmd > heroku run echo $PORT), I've realized this port is always different than what my server starts on. So is the problem with this line: System.getenv("PORT") ??
Any help is appreciated, been trying to troubleshoot this for toooooo long.
Answer: You're including a URL in  the hostname field.
You want the hostname:
clientSocket = new Socket("appname.herokuapp.com", 40506);

Comment: Thanks for the prompt reply. Tried changing to this, which makes sense, but didn't make a difference.
Comment: Are you using the actual name of the app here?  I assumed appname is a placedholder.  If you lookup the DNS name of your app, "nslookup YOUR_ACTUAL_APP_NAME.herokuapp.com" - does it resolve?
Comment: Never mind, this actually worked! I just forgot to remove the very last '/' from the string. Although, the server still doesn't get the connection. But that's a different error. Answer accepted.
Comment: @slash I know this is really delayed but I think the port should be 80 or 443. Your application might be deployed at 40506 on the application server but to ping it via the hostname you'll need to go through the Heroku load balancer which has your app deployed at 443
Answer: Couple of thoughts - note that the app hostname is not the name of the machine where your app is running. It's a pointer to Heroku's HTTP routing layer. For that reason, you won't be able to connect directly to that port anyway. Additionally, I believe Heroku uses AWS security groups to restrict network access to the actual dynos. Their network model is designed for HTTP/S access via their routing mesh. Any other kind of network access needs a different hosting solution.


Convergence/divergence of $\sum\limits_{k=0}^{\infty}\sum\limits_{i=0}^k\left(\frac{(-1)^i}{\sqrt{i+1}}\frac{(-1)^{k-i}}{\sqrt{k-i+1}}\right)$

Question: Is the series $C:=\sum\limits_{k=0}^{\infty}\sum\limits_{i=0}^k\left(\frac{(-1)^i}{\sqrt{i+1}}\frac{(-1)^{k-i}}{\sqrt{k-i+1}}\right)$ convergent?
I would say no, because:
Let be $c_k:=\sum\limits_{i=0}^k\frac{(-1)^i}{\sqrt{i+1}}\frac{(-1)^{k-i}}{\sqrt{k-i+1}}$, then we get $c_k=\sum\limits_{i=0}^k\frac{(-1)^{k}}{\sqrt{i+1}\sqrt{k-i+1}}=(-1)^k\sum\limits_{i=0}^k\frac{1}{\sqrt{i+1}\sqrt{k-i+1}}$. As $(c_k)$ is not a null sequence the limit of the partial sums $\lim\limits_{n\to\infty}C_n=\sum\limits_{k=0}^{n}\sum\limits_{i=0}^k\left(\frac{(-1)^i}{\sqrt{i+1}}\frac{(-1)^{k-i}}{\sqrt{k-i+1}}\right)=\sum\limits_{k=0}^{n}(-1)^kc_k$ doesn't exist/ $C$ doesn't converge.
Did I miss something?
Comment: @user2661923 I have edited the question.
Comment: What does "null sequence" signify?  Can you demonstrate (for example) that the sequence $\langle c_k\rangle$ does not go to zero?
Comment: You didn't miss to see something mathematically, but you missed to show it ("as (ck) is not a null sequence").
Answer: Your assertion that $(c_k)$ is not a null sequence is correct, and that is the key step in the proof.
Noting that for $0 \leqslant i \leqslant k$ we have $\sqrt{i+1}\sqrt{k-i+1}\leqslant \sqrt{k+1}\sqrt{k-0+1}= k+1$, it follows that
$$|c_k| = \left|(-1)^k\sum_{i=0}^k \frac{1}{\sqrt{i+1}\sqrt{k-i+1}}\right|= \sum_{i=0}^k \frac{1}{\sqrt{i+1}\sqrt{k-i+1}}\geqslant \sum_{i=0}^k \frac{1}{k+1}= 1$$
Hence, $\limsup_{k \to \infty} |c_k| \geqslant 1$ and, therefore,  $c_k \not\to 0$ as $k \to \infty$.


Remover índices do array

Question: Como remover índices de um array?
Array original
["Torrada" => 4,"Cachorro quente" => 1]

para
[4,1]

Comment: Em *PHP* não seria: `["Torrada" => 4,"Cachorro quente" => 1]` ?
Comment: @NoobSaibot correto
Answer: A função array_values retorna todos os valores de um array:
$Array = ["Torrada" => 4,"Cachorro quente" => 1];
$Valores = array_values($Array);
print_r($Valores);

Saída:
Array
(
    [0] => 4
    [1] => 1
)

Referência

array_values
Comment: Ae deu certo noobsaibot
Comment: No caso erá somente informar `array_values($info['data']);`
Comment: era o print_r que tava acusando o erro... obrigado

Remover índices do array


Getting 'permission-denied' while integrating firebase in React web app

Question: I'm trying to save a documents through react web app, but facing the following issue. I have read the firebase rules documentation.
Here is the code
constructor(props)
  {
    super(props);
    var config = {
      apiKey: "<apiKey>",
      authDomain: "<authDomain>",
      databaseURL: "<databaseURL>",
      projectId: "<projectId>",
      storageBucket: "",
      messagingSenderId: "<messagingSenderId>"
    };
    firebase.initializeApp(config);
  }

and we are triggering button click
onKeyUp(e)
    {
        if(e.keyCode===13 && trim(e.target.value) !== '')
        {
            e.preventDefault();
            let dbCon=this.props.db.database().ref('/messages');
            dbCon.push(
                {
                    message:trim(e.target.value)
                }
            );
            );
        }
    }

Database rules:
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write:if true;
    }
  }
}

we are facing this issue. What am I doing wrong?
Stack Trace:
Uncaught (in promise) Error: PERMISSION_DENIED: Permission denied
    at index.cjs.js:13076
    at exceptionGuard (index.cjs.js:690)
    at Repo../node_modules/@firebase/database/dist/index.cjs.js.Repo.callOnCompleteCallback (index.cjs.js:13067)
    at index.cjs.js:12844
    at index.cjs.js:12019
    at PersistentConnection../node_modules/@firebase/database/dist/index.cjs.js.PersistentConnection.onDataMessage_ (index.cjs.js:12052)
    at Connection../node_modules/@firebase/database/dist/index.cjs.js.Connection.onDataMessage_ (index.cjs.js:11337)
    at Connection../node_modules/@firebase/database/dist/index.cjs.js.Connection.onPrimaryMessageReceived_ (index.cjs.js:11331)
    at WebSocketConnection.onMessage (index.cjs.js:11232)
    at WebSocketConnection../node_modules/@firebase/database/dist/index.cjs.js.WebSocketConnection.appendFrame_ (index.cjs.js:10837)
    at WebSocketConnection../node_modules/@firebase/database/dist/index.cjs.js.WebSocketConnection.handleIncomingFrame (index.cjs.js:10887)
    at WebSocket.mySock.onmessage (index.cjs.js:10784)

Answer: Newbie mistake, was using the newer firestore database instead of using the Realtime database. Changing to the Realtime database fixed the issue.
Comment: can you please elaborate. I think i have the same issue
Comment: Ya understood what you meant. But any idea why not to use the advanced version?? Why not Newer firestore database?
Comment: On the Database page, there will be a drop-down looking thing that says "Cloud Firestorm BETA". Click on that and change it to "Realtime Database".


Questions about Neural Network training (back propagation) in the book PRML (Pattern Recognition and Machine Learning)

Question: I am reading Chapter 5 of PRML. Some symbols don't seem to be clear to me.
In page 243, for the chain rule for partial derivative $\dfrac{\partial E_n}{\partial w_{ji}}=\dfrac{\partial E_n}{\partial a_j}\dfrac{\partial a_j}{\partial w_{ji}}$ (equation (5.50)), a notation is defined as $\delta_j\equiv\dfrac{\partial E_n}{\partial a_j}$ (equation (5.51)). In my understanding $\delta_j$ is the first part in the chain rule. However in equation (5.54), the book mentioned

As we have seen already, for the output units, we have
  $$\delta_k=y_k-t_k$$

Question 1:
$y_k-t_k$ is the error on output unit $k$, which is simply the difference between the $k$th output unit value and the corresponding target value. But, from the definition of the notation $\delta_k$, we should have $$\delta_k=\dfrac{\partial \frac{1}{2}(y_k-t_k)^2}{\partial a_k}=(y_k-t_k)\dfrac{\partial y_k}{\partial a_k}=(y_k-t_k)\dfrac{\partial h(a_k)}{\partial a_k}$$ where $h(a_k)$ is the activation function.
So why in the book $\delta_k=y_k-t_k$??

In page 242, Section 5.3. Error Backpropagation,

Consider a simple linear model where the outputs $y_k$ are linear
  combinations of the input variables $x_i$ so that
  $y_k=\sum_iw_{ki}x_i$. For a particular input pattern $n$, the error
  function is $E_n=\dfrac{1}{2}\sum_k(y_{nk}-t_{nk})^2$, where
  $y_{nk}=y_k(\boldsymbol{x_n},\boldsymbol{w})$. So the gradient of this
  error function with respect to a weight $w_{ij}$ is given by
  $$\frac{\partial E_n}{\partial w_{ji}}=(y_{nj}-t_{nj})x_{ni}$$ which
  can be interpreted as a 'local' computation involving the product of
  an 'error signal' $y_{nj} − t_{nj}$ associated with the output end of
  the link $w_{ji}$ and the variable $x_{ni}$ associated with the input
  end of the link.

Question 2:
I am not clear with the structure of this neural network. The one in the book is a two-layer neural network with linear activation, is it?
Answer: Q1: It seems here $y_k=a_k$, in PRML around eq 5.18

In the regression case, we can view the network as having an output
  activation function that is the identity, so that $y_k = a_k$

Q2: In the discussion on P242 there's only one layer with no activation function, actually the author didn't call it a neural network but a "simple linear model"

Consider first a simple linear model in which the outputs $y_k$ are linear combinations of the input variables $x_i$
Comment: Q1: Isn't the activation function in the context is given in eq. 5.49, i.e., $z_j=h(a_j)$? Also in another book I'm reading `Python Machine Learning - Second Edition`, for a 3-layer MLP with sigmoid activation function on hidden and output units, the error vector of the output layer has a similar form: $\boldsymbol{\delta^{(out)}=a^{(out)}-y}$, where $a^{(out)}$ is the output vector and $y$ is the target vector.
Comment: @Tyler提督九门步军巡捕五营统领 you're right, in the first quote it mentioned the activation function used is the identity function since it's a regression task, so $h(a_j)=a_j$ :)


Why can't I view my home page like I can on a local host

Question: I am trying to upload my website on digital ocean using express, node and react. I can view my website on localhost:3000 but when I run nodemon on the publicip:3000 all I see is /root/website/src/index.html displayed on the page. Here is the server.js file
const express = require('express');
const app = express();

//Set port
const PORT = process.env.PORT || 3000;

//Import path
const path = require('path');

//Static files
app.use(express.static('build'));

//Server will use index.html
app.get('/*', (req, res) => {
    res.send(path.join(__dirname + '/src/index.html'));
});

app.listen(PORT, () => {
    console.log('Listening on port ${PORT}');
});

Comment: use `res.sendFile(path.join(__dirname + '/src/index.html'));`
Answer: If you are using res.send() then it will send the path of the file. And path.join should contain the values separated with commas as it takes the values as string array.
Try this
If you want the actual file to send.
res.sendFile(path.join(__dirname ,"src/index.html"));


Input_shape is None in custom layer

Question: I'm building my own layer in Tensorflow 2.1 and using it in custom model. However when I'm trying to learn something, the layer is trying to build itself when called for the first time, and it needs input_shape to do it. As far as I know, it should compute it because it's getting an actual input, but it seems that input_size is None.
My question is: what I did wrong and how to correct that?
Below I'm attaching an example to reproduce the problem.
My code (MinimalRNNCell is copied from tensorflow website https://www.tensorflow.org/api_docs/python/tf/keras/layers/RNN):
import tensorflow as tf
from tensorflow.keras.layers import Layer
from tensorflow.keras import Model
import numpy as np

class MinimalRNNCell(Layer):

    def __init__(self, units, **kwargs):
        self.units = units
        self.state_size = units
        super(MinimalRNNCell, self).__init__(**kwargs)

    def build(self, input_shape):
        self.kernel = self.add_weight(shape=(input_shape[-1], self.units),
                                      initializer='uniform',
                                      name='kernel')
        self.recurrent_kernel = self.add_weight(
            shape=(self.units, self.units),
            initializer='uniform',
            name='recurrent_kernel')
        self.built = True

    def call(self, inputs, states):
        prev_output = states[0]
        h = K.dot(inputs, self.kernel)
        output = h + K.dot(prev_output, self.recurrent_kernel)
        return output, [output]

class RNNXModel(Model):
    def __init__(self, size):
        super(RNNXModel, self).__init__()
        self.minimalrnn=MinimalRNNCell(size)

    def call(self, inputs):
        out=self.minimalrnn(input)
        return out

x=np.array([[[1,2,3],[4,5,6],[7,8,9]],[[10,11,12],[13,14,15],[16,17,18]]])
y=np.array([[1,2,3],[10,11,12]])

model=RNNXModel(3)
model.compile(optimizer='sgd', loss='mse')
model.fit(x,y,epochs=10, batch_size=1)

Error I'm getting:
Traceback (most recent call last):
  File "/home/.../test.py", line 64, in <module>
    model.fit(x,y,epochs=10, batch_size=1)
  File "/home/.../.venv/lib/python3.6/site-packages/tensorflow_core/python/keras/engine/training.py", line 819, in fit
    use_multiprocessing=use_multiprocessing)
  File "/home/.../.venv/lib/python3.6/site-packages/tensorflow_core/python/keras/engine/training_v2.py", line 235, in fit
    use_multiprocessing=use_multiprocessing)
  File "/home/.../.venv/lib/python3.6/site-packages/tensorflow_core/python/keras/engine/training_v2.py", line 593, in _process_training_inputs
    use_multiprocessing=use_multiprocessing)
  File "/home/.../.venv/lib/python3.6/site-packages/tensorflow_core/python/keras/engine/training_v2.py", line 646, in _process_inputs
    x, y, sample_weight=sample_weights)
  File "/home/.../.venv/lib/python3.6/site-packages/tensorflow_core/python/keras/engine/training.py", line 2346, in _standardize_user_data
    all_inputs, y_input, dict_inputs = self._build_model_with_inputs(x, y)
  File "/home/.../.venv/lib/python3.6/site-packages/tensorflow_core/python/keras/engine/training.py", line 2572, in _build_model_with_inputs
    self._set_inputs(cast_inputs)
  File "/home/.../.venv/lib/python3.6/site-packages/tensorflow_core/python/keras/engine/training.py", line 2659, in _set_inputs
    outputs = self(inputs, **kwargs)
  File "/home/.../.venv/lib/python3.6/site-packages/tensorflow_core/python/keras/engine/base_layer.py", line 773, in __call__
    outputs = call_fn(cast_inputs, *args, **kwargs)
  File "/home/.../.venv/lib/python3.6/site-packages/tensorflow_core/python/autograph/impl/api.py", line 237, in wrapper
    raise e.ag_error_metadata.to_exception(e)
TypeError: in converted code:

    /home/.../test.py:36 call  *
        out=self.minimalrnn(input)
    /home/.../.venv/lib/python3.6/site-packages/tensorflow_core/python/keras/engine/base_layer.py:818 __call__
        self._maybe_build(inputs)
    /home/.../.venv/lib/python3.6/site-packages/tensorflow_core/python/keras/engine/base_layer.py:2116 _maybe_build
        self.build(input_shapes)
    /home/.../test.py:14 build
        self.kernel = self.add_weight(shape=(input_shape[-1], self.units),

    TypeError: 'NoneType' object is not subscriptable

Comment: `out=self.minimalrnn(input)` should probably be `out=self.minimalrnn(inputs)`
Comment: Oh wow. I feel REALLY dumb now. Thank you for spotting this typo.
Comment: It solved None input_size problem, but there's another - but I think it's issue for separate question, I'm linking it for information: https://stackoverflow.com/questions/60402033/states-argument-missing-in-custom-model-using-custom-rnn-layer
Answer: There is a typo (input should be inputs). input is a built-in function (documentation).
class RNNXModel(Model):
    def __init__(self, size):
        super(RNNXModel, self).__init__()
        self.minimalrnn=MinimalRNNCell(size)

    def call(self, inputs):
        out=self.minimalrnn(inputs)  # changed from `input`
        return out

Input_shape is None in custom layer


Redirect contact form on submit

Question: Using Drupal 8 and trying to get the contact form to redirect to the same page after submitting. By default it seem to redirect to the home page.
I have edited my themename.theme file
function themename_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {

  //contact page form
  if ($form_id == 'contact_message_feedback_form') {
    $url = Url::fromRoute('contact.site_page');
    $form_state->setRedirectUrl($url);
  }
}

This throws a bunch of mysql errors. Like so:
Uncaught exception thrown in session handler.

Drupal\Core\Database\DatabaseExceptionWrapper: SQLSTATE[08S01]: Communication link failure: 1153 Got a packet bigger than 'max_allowed_packet' bytes: UPDATE {sessions} SET uid=:db_update_placeholder_0, hostname=:db_update_placeholder_1, session=:db_update_placeholder_2, timestamp=:db_update_placeholder_3 WHERE ( (sid = :db_condition_placeholder_0) ); Array ( [:db_update_placeholder_0] => 1 [:db_update_placeholder_1] => ::1 [:db_update_placeholder_2] => _sf2_attributes|a:1:{s:3:"uid";s:1:"1";}_sf2_flashes|a:0:{}_sf2_meta|a:4:{s:1:"u";i:1454074283;s:1:"c";i:1452243053;s:1:"l";s:7:"2000000";s:1:"s";s:43:"dVseXv540u6wL5GZm_gs6fzuP9qtck-j5A5lexqnaQE";}authorize_page_title|O:48:"Drupal\Core\StringTranslation\TranslatableMarkup":3:{s:9:"*string";s:14:"Update manager";s:12:"*arguments";a:0:{}s:10:"*options";a:0:{}}messages|a:1:{s:6:"status";a:2:{i:0;O:25:"Drupal\Core\Render\Markup":1:{s:9:"*string";s:1020035:"

Redirect contact form on submit


Como funciona o Spliterator no Java 8?

Question: No Java 8 (que foi lançado em março de 2014), há uma nova interface chamada Spliterator. Ela tem um propósito semelhante ao Iterator, mas foi projetada para executar iterações em paralelo.
Entretanto, mesmo após ler bastante sobre esta interface e inclusive ter visto alguns códigos de exemplo, ainda não consigo entender como usá-la. Como o Java 8 nem foi lançado ainda (edit: quando fiz esta pergunta em 2013 ainda não havia sido lançado), atualmente existe pouquíssimo material na internet sobre isso. Uma vez que eu tenha alguma estrutura que eu queira iterar em paralelo (por exemplo: uma árvore de busca), como faço para efetivamente obter uma iteração em paralelo usando o Spliterator?
Answer: O Spliterator parece mais uma classe criada para outras classes mais sofisticadas usarem. A lógica básica está em trySplit(), que tenta dividir os elementos restantes em dois Spliterator: o corrente e um novo, que o método retorna.
Por exemplo:
void <T> showSize(Spliterator<T> sit) {
  System.out.println("Estimated size for sit: "+sit.getExactSizeIfKnown());
  Spliterator<T> sit2 = sit.trySplit();
  System.out.println("New estimated size for sit: "+sit.getExactSizeIfKnown());
  System.out.println("Estimated size for sit2: "+sit2.getExactSizeIfKnown());
  return;
}

O método recebe um Spliterator, sit, imprime o tamanho (isso pode não funcionar), então divide ele em dois com o trySplit(), e imprime os novos tamanhos.
Assumindo que os tamanhos possam ser impressos com precisão, existem duas possibilidades sobre o que se observará:

Um erro do tipo NullPointerException ao chamar um método em sit2, pois não foi possível dividir o Spliterator;
sit e sit2, somados, tem o tamanho que sit tinha originalmente.

Eu pessoalmente não recomendo tentar usar o Spliterator diretamente, pois otimizar esse tipo de coisa é difícil -- por isso mesmo que o Spliterator tem coisas como o tipo de coleção, tamanho estimado, processamento sequencial do restante, o fato do Spliterator não ser thread-safe, etc.
Se você quer paralelismo, use o Stream paralelo. É muito fácil de usar, e toda lógica de otimização já está embutida.
Comment: @GeisonSantos Depende da implementação. Em algo como um `ArrayList`, provavelmente ele divide pela metade.
Comment: *Daniel*, você sabe que critério o método trySplit() usa para fazer essa *divisão*?
Comment: As vezes você precisa _acessar_ um `Spliterator`, como fazer processamento paralelo a partir de um `Iterable`: https://pt.stackoverflow.com/a/345434/64969; na prática, entretanto, só vi como um meio para chamar `StreamSupport`, sem maiores mudanças referentes a isso. Digamos que, apesar de ter acessado, eu não usei de fato o `Spliterator` na resposta, e ele continua sendo uma caixa preta pra mim
Answer: import java.util.Arrays;
import java.util.List;
import java.util.Spliterator;

public class SpliteratorTest {

    public static void main(String[] args) {

        List<String> wordList = Arrays.asList("Apple","Banana", "Orange", "Guava");

        Spliterator<String> spliterator1 = wordList.spliterator();
        Spliterator<String> spliterator2 = spliterator1.trySplit();

        spliterator1.forEachRemaining(System.out::println);
        System.out.println("Traversing the other of the spliterator...");
        spliterator2.forEachRemaining(System.out::println);
    }
}

Saída:
Orange
Guava
Traversing the other of the spliterator...
Apple
Banana

Para mais informação acesse este link.

Como funciona o Spliterator no Java 8?


Clean urls working everywhere except my custom module

Question: I'm attempting to create a custom drupal module, but I can't get clean urls to work. Clean urls have been enabled and are working everywhere else on the site.
I can access my module page using "?q=" but if I remove that and try to access it with the clean url I get a "page not found" error.
I've tried clearing the cache and rebuilding the menus using devel. I've also tried disabling and re-enabling my module.
Here's the code I have in my .module file.

<code>/**
 * @file
 * This example demonstrates how a module can display a page at a given URL.
 */

/**
 * Implements hook_menu().
 */
function page_example_menu() {
  $items['examples/page_example/simple'] = array(
    'title' => 'Simple - no arguments',
    'page callback' => 'page_example_simple',
    'access arguments' => array('access simple page'),
  );

  return $items;
}

/**
 * Constructs a simple example page.
 *
 * @return array
 *    The render array for the simple example page.
 */
function page_example_simple() {
  return array('#markup' => '<p>' . t('Simple page: The quick brown fox jumps over the lazy dog.') . '</p>');
}
</code>
Comment: can you check this page : admin/config/search/clean-urls if clean url is enabled ?
Answer: Turns out the issue was in my company's custom configuration. Certain pages are routed via Drupal while others are handled by a legacy system. All I had to do was add my module's path to our config and everything works now.


PTP 1588 timestamps

Question: In PTP 1588, timestamped packets means the time when first bit of PTP packet leaves the device pin?
Does that mean if that time has to be fed in the packet, PTP stack should know how much time from a given stage in PTP stack till the device pin will be taken by that PTP packet?
so that time can be pre-fed in the packet?
Comment: You need to specify the version. The current IEEE 1588 is not backward compatible with the original, and it compensates for time traversing the network equipment.
Answer: Yes I think the IEEE1588 standard does have a definition where exactly the time stamping point is. It is not so important where exactly this point is, because the delay (as long as it is a constant delay) will be compensated.
Usually when you use PTP, you have a hardware timestamping unit (TSU) which has a digital clock that can be adjusted from software. Timestamping can be either be implemented in the PHY (the chip that drives the wire), or in the MAC (the periphery of the CPU that buffers the frames until the software has time to read them).
When a PTP frame is recognized, usually the current timestamp plus the PTP sequence number and message type are stored into a separate memory for the CPU to fetch later. The CPU will then use this information to adjust the clock of the TSU (usually not the same as to the normal system time seen from the OS). The TSU clock is then used by application-programmed hardware, e.g. to timestamp external signals, or to generate precise pulses. It is usually not used directly by the software, because that would add back many of the unpredictable latencies that were avoided by having hardware timestamping.
You cannot just append the timestamp to the frame, because then the CPU cannot get any transmit timestamps. If the software does any kind of timestamping on the CPU, the precision of PTP is usually lost, because of a lot of uncertainties (like interrupt latency, scheduler latency, queues, etc.)
However, PTP frames also contain a correction field which can be adjusted on the fly by hardware components, e.g. a switch may add the forwarding delay directly into the frame, modifying it on the fly, and calculating a new checksum.
Answer:
OP: In PTP 1588, timestamped packets means the time when first bit of PTP packet leaves the device pin?

... so the it is not just when the "first bit .. leaves", but the beginning of that informative bit: leaving or entering.

Unless otherwise specified in a transport-specific annex to this standard, the message timestamp point for an event message shall be the beginning of the first symbol after the Start of Frame (SOF) delimiter.  IEEE 1588-2008 18.104.22.168 Event message timestamp point

OP: Does that mean if that time has to be fed in the packet, PTP stack should know how much time from a given stage in PTP stack till the device pin will be taken by that PTP packet?  so that time can be pre-fed in the packet?

That is one course approach.
A certainly more accurate, though complex approach is to inject time info in the later parts of the packet.  Any trailing CRC also needs real-time calculation.
1588 does not specify the implementation of how to meets its objective.

PTP 1588 timestamps


Does any polygon with side number $2n$ with $n \ge 2$ form a torus when all pairs of opposite sides are joined? (works for n=2, 3)

Question: Wikipedia's Eisenstein integer; Quotient of C by the Eisenstein integers says:

The quotient of the complex plane C by the lattice containing all Eisenstein integers is a complex torus of real dimension 2. This is one of two tori with maximal symmetry among all such complex tori.[citation needed] This torus can be obtained by identifying each of the three pairs of opposite edges of a regular hexagon. (The other maximally symmetric torus is the quotient of the complex plane by the additive lattice of Gaussian integers, and can be obtained by identifying each of the two pairs of opposite sides of a square fundamental domain, such as [0,1] × [0,1].)

This answer explains and shows how identifying opposite sides of a hexagon produces a torus, as do answers to What surface do we get by joining the opposite edges of a hexagon?
Question: Bringing opposite sides of a quadrilateral and a hexagon both produce a torus. Does any polygon side number $2n$ with $n \ge 2$ form a torus when all pairs of opposite sides are joined?

From the linked answer:

Image source: http://www.math.cornell.edu/~mec/Winter2009/Victor/part1.htm
Answer: The answer is "no" for the very next case $n=4$. In fact the answer is "no" for all cases $n \ge 4$.
I will assume that your intention is to glue opposite sides by a translation isometry of the plane; or to put it another way, to glue them using matching arrows that point in the same direction on the plane, but in opposite directions around the periphery of the polygon. It follows from this assumption that the quotient surface is orientable.
In that case, let me describe what happens in two cases, depending on whether $n$ is even or odd. The outline is: count the vertex cycles; use that to compute the Euler characteristic; and then apply the classification of surfaces.
Here's the outcome:

If $n=2g$ is even, then the $2n$ vertices form $1$ vertex cycle (generalizing the case of the square). The quotient therefore has $1$ vertex, $n$ edges, and $1$ face, thus has Euler characteristic $1-n+1=2-2g$. From the classification of surfaces, it follows that the quotient surface is homeomorphic to the orientable surface of genus $g$.

If $n=2g+1$ is odd, then the $2n$ vertices form two vertex cycles (generalizing the case of the hexagon). The quotient surface therefore has $2$ vertices, $n$ edges, and $1$ face, thus has Euler characteristic $2-n+1 = 2-2g$, and again is homeomorphic to the surface of genus $g$.

So to answer your question: No, not in general. The only cases where opposite side gluing gives the torus are the two cases you know, the square and the hexagon.
Generalizing from $n=2,3$ to all $n \ge 2$ is fraught with peril!
Comment: @uhoh If you have access to a math library, Stillwell's Geometry of Surfaces is a very accessible introduction to the classification and geometry of surfaces.
Comment: That's quite different, and leads to a non-orientable surface. I wouldn't say it *needs* a new question, because there is another option: read up on the proof of the classification of surfaces. That would answer all of your questions.
Comment: Thanks! Yes my plan was to apply the arrows and gluing as shown in the hexagon drawing, but seeing [this comment](https://math.stackexchange.com/questions/4088573/does-any-polygon-with-side-number-2n-with-n-ge-2-form-a-torus-when-all-pair/4089030#comment8449260_4088621) one can point all arrows "counterclockwise" and match them up that way. I assume that would have a different result. Do you think that case needs a new question?
Comment: Got it. I believe there have been some good answers to questions like [How to start reading topology?](https://math.stackexchange.com/q/2311958/284619) and especially [Can anybody recommend me a topology textbook?](https://math.stackexchange.com/q/150556/284619) and I've math libraries available. I've been away from using math for many decades and [sphere eversion](https://mathoverflow.net/q/246851/96907) is essentially now a "bucket list" item for me. ;-)
Answer: The simplest way to figure this out is to triangulate the polygon (add one vertex in the middle for simplicity. Then, the quotient space will have $2n$ triangles, and $3n$ edges. It will have the one central vertex, and so the gluings should somehow result in $n-1$ vertices. Whether this is true or not depends on how you do the gluing, but I leave the rest as an exercise.
Comment: @uhoh Orient the edges counterclockwise. Then, every pair can be glued so the arrows agree or not. If they always agree, the euler characteristic will be $1,$ so you will NOT have a torus (you WILL have a projective plane). Notice that the standard identification for a square has the effect of sending all vertices to one, and even then you might blunder into a klein bottle. So, the answer is closer to "no" than to "yes".
Comment: *Thanks!* "Whether this is true or not depends on how you do the gluing" Does "when all pairs of opposite sides are joined" leave any options? Does the order of the gluing matter perahps? I'll give this some thought, but I'm thinking that the answer to my question is "Yes." Am I far off?
Comment: Oh yes I see, got it. This is really helpful, I'll give this some thought now and keep an eye on the vertices. fyi I've corrected an error in the wording of the question but I don't think it impacts your answer. (side number $2n$ with $n \ge 2$) Also I found [Identifying the two-hole torus with an octagon](https://math.stackexchange.com/q/1239104) but I don't think it's necessarily a duplicate as it is only for $n=4$.


PAGE_FAULT_IN_NONPAGED_AREA when booting Windows 10 from iSCSI network drive

Question: I am trying to set up Windows 10 for diskless boot via iSCSI, as described, for example, here or here.
I am able to run the Windows 10 installer to install Windows on the target iSCSI drive. However, on the first boot from the drive, I get a Blue Screen of Death with the error code PAGE_FAULT_IN_NONPAGED_AREA. Unfortunately, no crash dump is produced (perhaps because the bootloader never got to the point where it could write to the drive?).
How can I diagnose and fix this?
Answer: This appears to happen when the system page file is located on the iSCSI device. While locating the page file on iSCSI worked fine under Windows 7, it appears to be broken in Windows 10. Unfortunately, Windows defaults to setting up a page file on the primary disk, so when the primary disk is iSCSI, it is broken out-of-the-box.
(Note that the stop code PAGE_FAULT_IN_NONPAGED_AREA does not necessarily relate to the system page file in general, despite containing the word "page". This stop code is more like the NT kernel's version of "Segmentation Fault", a general invalid memory access. But, in my specific case, it coincidentally turned out to be related to the page file.)
I was able to solve the problem by disabling the page file entirely. (It also works to locate the page file on a local disk, if one exists, but this is easier to configure after getting the OS up and running with no page file.)
Disabling page file offline
Since your machine is not bootable, you cannot disable the page file through the UI. Luckily, it's easy to disable the page file via the registry. To do so, locate the following registry key, and set its value to be empty:
HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Control\Session Manager\Memory Management\PagingFiles

If your registry contains ControlSet002 and/or CurrentControlSet in addition to ControlSet001, make sure to make the same changes to those.
Editing registry offline
But how do we edit the registry without booting? There are multiple approaches. You could temporarily mount the iSCSI volume from an existing, working Windows machine, or from a Windows Preinstallation Environment (WinPE) that you booted from USB or maybe even from PXE. Many guides exist describing these options.
In order to edit a registry offline (i.e., edit a registry other than the one of the system that is running regedit):

Run regedit ("Registry Editor") normally.
Click on HKEY_LOCAL_MACHINE.
Go to "File > Load Hive...".
Browse to the offline Windows installation, and choose the file Windows\System32\config\SYSTEM.
When prompted, type any arbitrary name, like "OFFLINE_SYSTEM".

The offline registry file will appear in the tree under HKEY_LOCAL_MACHINE with the name you chose. Edits you make to keys within it will usually be saved automatically, although it is advised that you explicitly unload the offline hive before closing regedit to be sure (see Harry Johnston's comment below). This is a very strange UI, but that's apparently how it is done.
Comment: In order to ensure that the changes are saved, you need to explicitly unload the hive when you are done.  (It will sometimes work without doing this, but not always.)
Comment: Thanks, @HarryJohnston! I updated my answer.
Answer: It's worth mentioning that page file works without any problems on Windows 10 up to compilation 1703. Update to newer or clean install of newer versions fail by default, though - as described above.
@KentonVarda's suggestion to turn off page file is valid, but I went another way than offline registry edit.
I have managed to work this problem around by installing Windows first to a local SSD drive. Then I booted it, disabled virtual memory and used SysInternals' tool called Disk2VHD (available at Microsoft site https://docs.microsoft.com/en-us/sysinternals/downloads/disk2vhd) to create VHDX file out of live system while working on it. Then used the resulting VHDX at iSCSI target and voila, it boots via iSCSI without issues.
The only workaround to have a working page file on iSCSI-booted machine I know currently of is to have a local physical disk for the sole purpose of page file.


Matlab ezmesh - plotting a plane that is a function of one variable

Question: I'm plotting planes in matlab using ezmesh. Everything goes fine until I attempt to plot a plane such as z=y -- ezmesh wants a function of two variables. I'd like to continue using ezmesh in my code rather than using something like surf for this one plane... can ezmesh plot this plane?
Answer: This works over here:
ezmesh(@(x,y)y)

The equation z=y acutally is a function of two variables, only it holds for all x, which is expressed by not using x.
Comment: @Brian: You can make a small wrapper: `z=@(y)y; z2=@(x,y)z(y);` and then use `ezmesh(z2)`, or all in one go: `ezmesh(@(x,y)z(y))`
Comment: Ok I see that does work. However I'm using the solve function to produce the equation of a plane, and in this case its outputting a function z = y, which I believe matlab thinks is equivalent to @(y)y. Do you know how I take func=@(y)y and turn it into func=@(x,y)=y so that ezmesh will accept it?
Comment: Thanks Rody -- I'm able to get all of this to work, but for some reason when I let the solve function produce the function z rather than declaring it myself and then use ezmesh(@(x,y)z(y) -- z is the function handle -- I get the error "Index must be a positive integer or logical."
Comment: @Brian: I'm guessing you're using symbolic math?
Comment: Yes, I'm using symbolic math.
Comment: @Brian: OK, well then you can use `z = matlabFunction(z);` which results in `z = @(y)y`, which you can then wrap as above. Does that work?


Unable to login while able to access without login

Question: I am having a strange problem with my drupal website where site is working and anybody is able to surf it properly however the moment I try to login using my admin or account it shows offline message given below. What could be the reason
+++++++++++++
Site off-line
The site is currently not available due to technical problems. Please try again later. Thank you for your understanding.
If you are the maintainer of this site, please check your database settings in the settings.php file and ensure that your hosting provider's database server is running. For more help, see the handbook, or contact your hosting provider.
Comment: Even if site is offline you can able to login by navigating to /user/login page...
Comment: site is working fine and I am able to go to user/login page but the moment I login sites shows offline page
Comment: Did you manage to resolve the issue? If yes, then how?
Answer: As you can not login from in your site the only way to do something is from database end, if you have access to database try doing this to come out of this mess up:
Try to empty the sessions and the cache tables. Not DELETE! Empty them.
then see if you can login from http://www.yoursite.com/?q=user
Or look if your site is in maintenance mode if it is the follow instructions given here: https://www.drupal.org/node/276457
Hope above will work for you and you will get your site back to normal.
Good luck!
Comment: Hi emptied sessions and cache but problem remains. I just see a page with offline message and not able to get inside the admin module. Otherwise website is running fine.
Comment: It seems that some connection problem with database look here if it work for you:
http://drupal.stackexchange.com/questions/24145/site-off-line-due-to-technical-problems-no-extra-info-in-message-what-cause


Link both openblas and mkl library while compiling c++

Question: I want to write a program to compare openblas and mkl library for matrix multiplication but I seem to have a problem while linking both these libraries as they share same function hence gives "confliction error" with g++.
They seem to run individually in different cpp files using
g++ matrixmult_openblas.cpp -I /usr/local/opt/OpenBLAS/include/ -L/usr/local/opt/OpenBLAS/lib -lopenblas

and
g++ matrixmult_mkl.cpp -L${MKLROOT}/lib -Wl,-rpath,${MKLROOT}/lib -lmkl_intel_ilp64 -lmkl_intel_thread -lmkl_core -lmkl_blacs_mpich_ilp64 -liomp5 -lpthread -lm -ldl

How do I compile them in a single cpp file?
I have used namespaces like these
namespace openblas
{
    #include <cblas.h>
}
namespace mkl
{
    #include <mkl.h>
}

When I compile them using both linkers like,
g++ matrixmult.cpp -I /usr/local/opt/OpenBLAS/include/ -L/usr/local/opt/OpenBLAS/lib -lopenblas -L${MKLROOT}/lib -Wl,-rpath,${MKLROOT}/lib -lmkl_intel_ilp64 -lmkl_intel_thread -lmkl_core -lmkl_blacs_mpich_ilp64 -liomp5 -lpthread -lm -ldl

I'm getting errors like

In file included from /opt/intel/compilers_and_libraries_2019.1.144/mac/mkl/include/mkl.h:31:
  /opt/intel/compilers_and_libraries_2019.1.144/mac/mkl/include/mkl_cblas.h:255:6: error: conflicting types for 'cblas_sgemv'
  void cblas_sgemv(const  CBLAS_LAYOUT Layout,
       ^
  /usr/local/opt/OpenBLAS/include/cblas.h:125:6: note: previous declaration is here

Please help me do this.
I want an output file in which I can pass argument 'openblas' or 'mkl' to main function to use whichever library.
Answer:
I'm getting errors like

In file included from /opt/intel/compilers_and_libraries_2019.1.144/mac/mkl/include/mkl.h:31:

/opt/intel/compilers_and_libraries_2019.1.144/mac/mkl/include/mkl_cblas.h:255:6:
    error: conflicting types for 'cblas_sgemv' void cblas_sgemv(const
    CBLAS_LAYOUT Layout, ^ /usr/local/opt/OpenBLAS/include/cblas.h:125:6:
    note: previous declaration is here

You are lucky.  Under other circumstances you might instead have had your program compile successfully without error, and then behave unexpectedly at run time.

How do I compile them in a single cpp file?

You don't.  OpenBLAS and MKL provide routines having the same names and with C linkage.  Even if they had compatible types, the compiled program would use only one of each pair.  You cannot work around this by manipulating declarations or header files, as those need to match the actual compiled functions in order to be of any use.

I want to write a program to compare openblas and mkl library for matrix multiplication

You'll have to settle for writing two programs, one for each library.  Make them as similar as possible, and compare their behavior on the same (or equivalent) inputs.
Comment: Actually, if you don't mind some overhead and just want to compare two libraries you can try GSL. In fact, all its BLAS functions are just wrappers which allow you to have the same code but link different linear algebra subroutines.


How to display custom table data inside views?

Question: I have a custom table created using .install file in my custom module.
+---------------+------------------+------+-----+---------+----------------+
| Field         | Type             | Null | Key | Default | Extra          |
+---------------+------------------+------+-----+---------+----------------+
| id            | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
| first_name    | varchar(255)     | NO   |     | NULL    |                |
| last_name     | varchar(255)     | YES  |     | NULL    |                |
| email_address | varchar(255)     | NO   |     | NULL    |                |
| user_country  | varchar(50)      | NO   |     | NULL    |                |
| user_city     | varchar(50)      | NO   |     | NULL    |                |
| address       | varchar(600)     | NO   |     | NULL    |                |
| gender        | varchar(10)      | NO   |     | NULL    |                |
+---------------+------------------+------+-----+---------+----------------+

And in same module, created form for reading inputs from user and a submit handler for inserting those values inside this schema. It works fine.
But now I need to fetch the data and display in Views. How can I do that? I have created a hook_views_api as:
   function MY_MODULE_views_api() {
  return array(
    'api' => 3,
  );
}

In hook_view_data(),
<?php
function my_module_views_data()
{
$data=array();

 $data['myuser']['id'] = array(
    'title' => t('id'),
    'help' => t('Just a numeric field.'),
    'field' => array(
      'handler' => 'views_handler_field_numeric',
      'click sortable' => TRUE,
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_numeric',
    ),
    'sort' => array(
      'handler' => 'views_handler_sort',
    ),
  );

$data['myuser']['first_name'] = array(
    'title' => t('First Name'),
    'help' => t('To get first Name.'),
    'field' => array(
      'handler' => 'views_handler_field',
      'click sortable' => TRUE,
    ),
    'sort' => array(
      'handler' => 'views_handler_sort',
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_string',
    ),
    'argument' => array(
      'handler' => 'views_handler_argument_string',
    ),
  );

$data['myuser']['last_name'] = array(
    'title' => t('last Name'),
    'help' => t('To get last Name.'),
    'field' => array(
      'handler' => 'views_handler_field',
      'click sortable' => TRUE,
    ),
    'sort' => array(
      'handler' => 'views_handler_sort',
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_string',
    ),
    'argument' => array(
      'handler' => 'views_handler_argument_string',
    ),
  );

$data['myuser']['email_address'] = array(
    'title' => t('Email Address'),
    'help' => t('To get Email Address.'),
    'field' => array(
      'handler' => 'views_handler_field',
      'click sortable' => TRUE,
    ),
    'sort' => array(
      'handler' => 'views_handler_sort',
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_string',
    ),
    'argument' => array(
      'handler' => 'views_handler_argument_string',
    ),
  );

$data['myuser']['user_country'] = array(
    'title' => t('User Country'),
    'help' => t('To get User Country.'),
    'field' => array(
      'handler' => 'views_handler_field',
      'click sortable' => TRUE,
    ),
    'sort' => array(
      'handler' => 'views_handler_sort',
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_string',
    ),
    'argument' => array(
      'handler' => 'views_handler_argument_string',
    ),
  );

$data['myuser']['user_city'] = array(
    'title' => t('User City'),
    'help' => t('To get User City.'),
    'field' => array(
      'handler' => 'views_handler_field',
      'click sortable' => TRUE,
    ),
    'sort' => array(
      'handler' => 'views_handler_sort',
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_string',
    ),
    'argument' => array(
      'handler' => 'views_handler_argument_string',
    ),
  );

 $data['myuser']['address'] = array(
    'title' => t('Address'),
    'help' => t('To get ADdress.'),
    'field' => array(
      'handler' => 'views_handler_field',
      'click sortable' => TRUE,
    ),
    'sort' => array(
      'handler' => 'views_handler_sort',
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_string',
    ),
    'argument' => array(
      'handler' => 'views_handler_argument_string',
    ),
  );

 $data['myuser']['gender'] = array(
    'title' => t('Gender'),
    'help' => t('To get Gender.'),
    'field' => array(
      'handler' => 'views_handler_field',
      'click sortable' => TRUE,
    ),
    'sort' => array(
      'handler' => 'views_handler_sort',
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_string',
    ),
    'argument' => array(
      'handler' => 'views_handler_argument_string',
    ),
  );

}

but now this is not showing up in Add View. What else I have missed? I am searching this days and today its dead line for finishing this. Please need some help on this.
Answer: Just use the Data module that gives you a UI to create a new simple table with fields you have above. Or, you can "adopt" existing MySQL tables into data. Data will then let you easily make Views of the mysql table and setup the hook_views_data properly for you.
If you want to do all that yourself because you cant use Data or 'alpha' contrib modules I recommend looking at Data modules source code to see how they implement the hook functions you're having trouble with.
Also note that in your hook_views_data() you forgot to return $data as in the official API documentation. That could be your problem. Still, you would have custom code that basically is part of the Data module.
Comment: Thanks.. I tried with Data Module. but there was no way for including an existing table.. this table was created in a module.install file. Is it possible to do that with data module. And return $data i have included..
Comment: Umm the Data module can adopt any table not owned by a module created by a schema function in drupal from the url `/admin/structure/data/adopt`. If you made it using `hook_schema` then ok. I recommend checking your hook_data_views function as a mentioned to include a return value.
Comment: Its done.. I had code for all functions in  single mudule file.   When moed to separate module, it worked


How do i calculate the duration of a segment of music with a changing tempo?

Question: I'm writing some music software that allows you to dynamically set the tempo. I'm having trouble calculating the duration of a section if the tempo is gradually increasing or decreasing. For example, if the piece starts on 100bpm and gradually increases to 200bpm by the 10th measure (drastic increase just for ease of numbers), all my calculations seem to be off. I've tried using the distance (in beats) with the change in tempo to figure out the acceleration of the tempo and get the time from that, but that still isn't working. I know it isn't working because I can let it play through the 10 measures and see that its off (sometimes be an entire second). I have confirmed the correct value in other software as well.
Comment: Can you specify how your program 'gradually increases tempo'. What formula do you use? Is it done stepwise (every bar or beat) or smooth (where a 128th note would be slightly shorter than the previous 128th note?)
Comment: Your tempo is in beats per minute, but the time taken comes from the number of minutes per beat. If your bpm goes up as 100, 110, 120, .., 200 the times for each bar will be *approximately* 1/105, 1/115, .. , 1/195, so these will be the numbers to add. If you need better approximations for the duration of each interval please say so.
Comment: Heck, even if your program "gradually increases tempo" smoothly, what's the smooth curve like? Does the rate of tempo change accelerate, decelerate, do both, or stay the same throughout? (I personally like tempo curves that accelerate the rate of tempo change as they go along.)
Comment: It works in a stepwise fashion. I calculate the difference in tempo and increase/decrease the tempo every 512th note(or every few depending on the rate of change) to get to the desired tempo by the end of the section. You can somewhat simulate an acceleration curse. The program allows you to add a point to the track with the vertical axis mapping the tempo and the horizontal axis plotting the beats. So you could plot something close to an acceleration curve.
Answer: The simple answer
Assume that the tempo always changes at a constant rate. In that case, it's sufficient to calculate the average tempo and multiply that by the number of beats involved. However, tempo in this scenario must be given in minutes per beat (i.e., how long does a single beat last) rather than beats per minute. MPB is just the inverse of BPM. For example, 30 BPM = 1/30 MPB; in other words at 30 BPM each beat lasts 2 seconds, which is clearly also the case for 1/30 MPB.
Example
Suppose a piece is in 4/4 time, and there is a tempo increase from 100bpm to 200bpm over the course of 10 measures, which is to say, 40 beats. In other words, at the beginning of the 10 measures each beat lasts .01 minutes (i.e., .01mpb), and at the end of the 10 measures each beat lasts .005 minutes (i.e., .005mpb). Then the average speed is .0075mpb. Over the span of 40 beats, this gives a total time of .3 minutes, or 18 seconds.

The real answer

Since we're trying to calculate total time, we need to know the minutes per beat (mpb), rather than beats per minute (bpm). MPB times the number of beats elapsed gives the amount of time elapsed.

Let f(x) be the MPB at beat x. That is, f(x) = how long a beat takes after x beats have gone by. f(x), therefore, represents beat-speed at a certain time.

Therefore, the total time required to change from one beat-speed to another over n beats is calculated by the integral of f(x) over the interval [0, n].

Example
Suppose a piece is in 4/4 time, and there is a tempo increase from 100bpm to 200bpm over the course of 10 measures, which is to say, 40 beats. In other words, at the beginning of the 10 measures each beat lasts .01 minutes (i.e., .01mpb), and at the end of the 10 measures each beat lasts .005 minutes (i.e., .005mpb). Assume the rate of change in tempo is constant. Then to calculate the tempo (in MPB) at a given beat, we have f(x) = .01 - .005(x/40) = .01 - .000125x. Integration over the interval [0, 40] gives .3 minutes (i.e., 18 seconds). (This can be verified at integral-calculator.com.)
This is confirmed by "the simple answer" above, which is also based on the assumption of a constant rate of tempo change.
Comment: I've often wondered whether tempo step changes should be *logarithmic* like pitch changes, so to double the speed from 100 to 200 bpm in 12 steps, at each step you'd multiply the existing tempo by by 12th root of 2 rather than just adding 8.33 bpm.
Comment: @BrianTHOMAS Interesting. Let's see ... in that case, f(x) = .01 - .005(2^[x/12]). With an assist from [integral-calclator.com](https://www.integral-calculator.com/), the total time for the accelerando would be approximately 0.033 minutes, or nearly 2 seconds. For comparison with the above answer, a 40-beat change would be .01 - .005(2^[x/40]) and take about 0.11 minutes, or 6.6 seconds.
Comment: @BrianThomas - I've often been satisfied with roughly *arithmetic* tempo step changes (e.g. 144 bpm -> 138 bpm -> 130 bpm -> 120 bpm - note that the differences between bpms are 6 bpm -> 8 bpm -> 10 bpm).
Comment: Thank you so much for the explanation. This has been blocking me for quite a while. I never even thought to invert it to MPB.
Answer: Depending on the purpose of the software you are developping, specifically real-time processing or not, my hint may apply to you or rather not. After all, you might be interested nevertheless.
A tick and its duration
If it is not bound to real-time constraints (offline synthesis), i.e. if you know beforehand how long the notes actually are, you can find the amount of the closest distance between all musically relevant events, i.e. note offsets and lengths/releases in a measure, in beats or floating-point shares of a beat.
That minimal distance, dividing the length of a measure in beats, and the resulting quotient again ceiled to the next integer, is the number of ticks in that measure to which you need to assign a length in milliseconds each. The total length of a measure = 60 seconds / how many bpm * beats per measure, needs to be divided by that number, to get the constant duration of a tick. This is the basic understanding.
If you want to get further or not, the earlier you abstract your calculations from bpm, breaking the tempo down into tick durations as shown above, the more flexible you can get to realize a multitude of rhythmic conventions in whatever music style you can think of, without necessarily giving a mechanical feel to your music. You just separate the logical offset and duration of a note, measured in beats and sub-beats, eighths or alike, from the actual durations in seconds, the interface factor between both being the duration of the tick.
Once you are able to calculate an array of tick durations in a measure, you have achieved an higher-order concept of tempo. So, you could even make the tick durations oscillate and modulate in a non-contiguous, but circularly recurring manner to realize swing- and shuffle-like patterns and other elaborate variations of rhythm.
After all, I recommend you think rather in seconds than in minutes because sound processing refers to sampling rate based on the second. In a 4/4 measure with 120bpm, here specifically fourths per minute, you need to calculate 60/120 = 0.5s a tick. Sure, if you have eighth notes (rests) in a measure, you would rather go with 0.25s for each of 8 ticks in the measure. Or 0.03125s per tick if you have got sixty-fourths therein and so forth.
What you actually must do due to the nature of floating point numbers, is capping the closest distance between musical events that your program can resolve, evening out all distances below. Otherwise you might run out of memory as there can occur tiny inaccuracies in calculation, yielding many tiny ticks in a measure that can hardly be mapped to distinct samples at a reasonable sampling rate.
Linear tempo changes
A linear change of the tempo can be realized tick-wise simply by weighted averages of start tempo (say 120bpm) and end tempo of a bar (say 135bpm) using evenly increasing weights from 1.0 to 0.0 for the former and 0.0 to 1.0 for the latter. First, calculate from the tempo indications the tick durations as shown. Then, depending on where the note starts and ends in terms of beats or shares of a beat, you sum the durations of the respective ticks in the array. The border ticks might need a linearly proportional cut-off from the start and the end (that is, shares of them ticks) to restore accuracy again that you lost by ceiling to and calculating with integers.
Having read other answers and comments to the question: Integrals serve you well if you, provided you are not a mathematician, want to stick with linear changes. If you want to go even further, you need to be one, or you need to consider to sum ticks, precalculated time-slices indeed. I guess noone's ear will ever perceive that border ticks have been proportionally cut off as a means of interpolation.
Polynomial gradients
If you are not content with just linear changes, because I guess they could provoke rather mechanical feelings in listeners of your music, you might also consider n-degree polynomials (bézier curves, free-form design) of which you can then set the co-efficient of every degree. This is what I have tried in my own "text-defined sound and music modelling from scratch" software project.
So, in a measure where the shortest occuring musically relevant duration is a sixty-fourth, by tracing in the polynomial gradient G(t) at every step for both the x- and y-dimension, that is at t=0.0, 1/64, 2/64, ..., 64/64=1.0, you calculate a sequence of 64 tick lengths (@y=1.00 == 120bpm):

So, every note and offset of consecutive notes, that cover the 40th tick must get these 60,000ms per minute / (16 ticks per beat * minimum 120bpm * ticks[39]=1.0888 times the minimum value) = 28.7ms summed into its total length. This calculation presumes that a beat is a fourth or 16 sixty-fourths.
(To my own notes to reconstruct graph: r -S "64:120;3,135;5,130")


Error Finding Home page for Drupal 7 Site on Ubuntu Linux

Question: I installed Drupal more or less successfully in /var/www/html on Ubuntu Linux. However when I go to 'localhost' it still just shows the Apache home page. However, if I go anywhere WITHIN my drupal site it works fine. So the home page is the problem. In fact if I click 'home' in the admin toolbar it takes me (again) to the apache home page.
Here's what I set in my 000-default.conf file on Ubuntu:
<VirtualHost *:80>
    . . .
    ServerName  mysite.dev
    ServerAdmin firstname.lastname@example.com
    DocumentRoot /var/www/html

    <Directory /var/www/html>
        AllowOverride All
    </Directory>
    . . .
</VirtualHost>

I tried following the directions here but didn't see any reference to index.htm or .html in my apache2.conf file:
https://www.drupal.org/node/1484514
Not sure what else to try.
Suggestions?
Comment: Purpose of Stack Exchange sites is not giving suggestions, but  answering a well-defined question. We cannot debug a site we don't have access, and listing all the possible causes, hoping to hit the exact one, is not the purpose of this site.
Answer: You need to enable php in your apache conf. You can try
$ sudo a2enmod php5

Answer: Where did you install drupal? in the /html folder? If so, perhaps you need to delete index.html (inside /html folder) which is the page you are seeing. Or did you do /var/www/html/drupal?
I installed my drupal in /var/www/drupal (I created the drupal folder inside /www and left the /html folder alone, untouched).
then in  000-default.conf I have:
ServerAdmin webmaster@localhost
        ServerName mysite.com
        ServerAlias www.mysite.com
        DocumentRoot /var/www/drupal

<Directory /var/www/drupal/>
        Options +FollowSymLinks
        AllowOverride All
        order allow,deny
        allow from all
</Directory>

Comment: Good grief, nevermind. I didn't restart apache after doing the changes. Now it works. Thank you.
Comment: ok, so I have done exactly what you have above except my site is localhost/mysitename instead of mysite.com. I've also changed my links to images and so forth within my drupal site to /sites/default/etc...' and I cleared the cache multiple times. i still just see the image placeholders on every page. when i inspect element the links say /sites/default/etc... on every page. and yet it's not working. Note: I also have a link to my home page on my site that doesn't work. The link url is '/' and when the link is clicked it takes me to a page of folders that shows sitename and html.


Specific permissions for rules components

Question: I created two rules components but i can't find any module to set specific permissions for roles.
I want to let some role's users to allow run the first component but not the second one.
thanks.
Answer: Rules provides a UI to configure access to components based on a permission.

Edit the component
Click to expand "Settings"
Check "Configure access for using this component with a permission"
Answer: Add a condition to your component for User has Roles, change the data selector to site:current-user:roles: and set the roles you require for the component to run.


Condição if/else para marcar/desmarcar checkbox

Question: Gostaria de saber como seria uma condição para desmarcar todos meus ckeckbox.
function marcarDesmarcarTodos() {
    for (i = 0; i <= 500; i++) {
        document.getElementById('seleciona_ativarDesativar_'+i).checked = true;
    }
}

Tentei da seguinte maneira, mas não deu certo.
function marcarDesmarcarTodos() {
    for (i = 0; i <= 500; i++) {
        if (document.getElementById('seleciona_ativarDesativar_'+i) != 'checked') {
            document.getElementById('seleciona_ativarDesativar_'+i).checked = true;
        } else {
            document.getElementById('seleciona_ativarDesativar_'+i).checked = false;
        }
    }
}

Answer: Precisas de ir buscar esses checkbox, por exemplo com:
document.querySelectorAll('input[type=checkbox]');

e depois iterá-los mudando o checked para false.
Agora tens opções diferentes:

Inverter o estado
Forçar todos / nenhum

Inverter o estado:
function marcarDesmarcarTodos() {
    var checkboxes = document.querySelectorAll('input[type=checkbox]');
    for (var i = 0; i < checkboxes.length; i++) {
        checkboxes[i].checked = !checkboxes[i].checked;
    }
}

jsFiddle: http://jsfiddle.net/nwvgyd3d/
Forçar todos / nenhum
Neste caso podes usar uma flag para guardar o estado. Também podia ser guardado no input num data-estado, mas no exemplo uso uma variável para isso.
var estado = false;
function marcarDesmarcarTodos() {
    var checkboxes = document.querySelectorAll('input[type=checkbox]');
    for (var i = 0; i < checkboxes.length; i++) {
        checkboxes[i].checked = !estado;
    }
    estado = !estado;
}

jsFiddle: http://jsfiddle.net/nwvgyd3d/1/
Comment: @MaiconCarraro eu decidí à uns tempos não usar mais o IE8, e o qsa é para me ajudar a lembrar a decisão :)
Comment: Sergio ama querySelectorAll né? aheuhaeuhae fico admirado
Answer: Procure pela função each do JS, usando jQuery...
Seu uso é bem simples:

$("input[type='checkbox']").each(function(){
     this.checked = false;
});

Exemplo
Answer: Voce pode usar essa funcao JS:

function marcarDesmarcar(source) {
  checkboxes = document.getElementsByName('foo');
  for(var i=0, n=checkboxes.length;i<n;i++) {
    checkboxes[i].checked = source.checked;
  }
}
<input type="checkbox" onClick="marcarDesmarcar(this)" /> Marcar e Desmarcar todos

<input type="checkbox" name="foo" value="bar1"> check 1

<input type="checkbox" name="foo" value="bar2"> check 2

<input type="checkbox" name="foo" value="bar3"> check 3

<input type="checkbox" name="foo" value="bar4"> check 4