Cramer's V with missing values gives different results

Question: My questions concern the calculation of the Cramers V to detect  correlation between categorial variables. I 've got a dataset with missing values, but I created a fake dataset for illustration with two variables a and b, one of them containing to NA's.
 a <-  factor(c("M","","F","F","","M","F","F"))
a2 <- factor(a, levels = c('M','F'),labels =c('Male','Female'))
b <- factor(c("y","y","","y","n","n","n","y"))
b2 <- factor(b, levels=c("y","n"),labels=c("yes","no"))
df<-cbind(a2,b2)

The assocstats function gives me the result for the cramers V:
require(vcd)
> tab <-table(a,b)
> assocstats(tab)
                            X^2 df P(> X^2)
Likelihood Ratio 1.7261  4  0.78597
Pearson          1.3333  4  0.85570

Phi-Coefficient   : 0.408
Contingency Coeff.: 0.378
Cramer's V        : 0.289

Now I want to drop the NA's from the levels
   a[a==""]<-NA
    a3 <- droplevels(a)
    levels(a3)

    tab <-table(a,b)
    assocstats(tab)

But everytime I remove NA's the result looks like this:
                    X^2 df P(> X^2)
Likelihood Ratio 0.13844  2  0.93312
Pearson              NaN  2      NaN

Phi-Coefficient   : NaN
Contingency Coeff.: NaN
Cramer's V        : NaN

Also, because I have a large dataset I would like to calculate a matrix of the Cramer V results. I found this code here on stack overflow and it seems to work...
get.V<-function(y){
  col.y<-ncol(y)
  V<-matrix(ncol=col.y,nrow=col.y)
  for(i in 1:col.y){
    for(j in 1:col.y){
      V[i,j]<-assocstats(table(y[,i],y[,j]))$cramer
    }
  }
  return(V)
}

   get.V(tab)

Only that the result is different than that with assocstats function:
   [,1] [,2] [,3]
[1,]  1.0  0.5    1
[2,]  0.5  1.0    1
[3,]  1.0  1.0    1

This can not be right, because I get this result every time, even when changing the number of observations... what is wrong with this code?
Conclusion:I don't know which one of the result is right. I have a large dataset with a lot of NA's in it. The first asocstat result and the code give different results, altough there is no big difference,because the code only creates a matrix. The second asocstat function gives only NaN.I cant detect any errors... Can somebody help me?
Comment: since you aren't defining `""` as a level in a2 and b2, isn't that the data you want (ie, you don't need to create a3: `a[a==""]<-NA; a3 <- droplevels(a)`)? when you make a table, you must explicitly use `table(..., useNA = 'ifany')` in order to keep NAs, so in effect you are already excluding them. So `assocstats(table(a2,b2))` should work
Comment: In my dataset I have a level " " and I have to remove them with droplevels, that why I created this data set this way, I don't want to keep NA's. And I don't understand why the asocstats function creates NaN when removing them
Comment: I think you got NaN cause you removed them in a and dropped the levels for a3 but you did not do the same for b
Comment: Use `complete.cases` to index a dataframe. Don't just omit NA's from single vectors.
Answer: You don't have to replace the "" with NA if you are using factors--any unique value that you don't define in levels will be converted to NA by factor
a <-  factor(c("M","","F","F","","M","F","F"))
a2 <- factor(a, levels = c('M','F'),labels =c('Male','Female'))

a
# [1] M   F F   M F F
# Levels:  F M
a2
# [1] Male   <NA>   Female Female <NA>   Male   Female Female
# Levels: Male Female

b <- factor(c("y","y","","y","n","n","n","y"))
b2 <- factor(b, levels=c("y","n"),labels=c("yes","no"))

(df <- cbind(a2,b2))

#      a2 b2
# [1,]  1  1
# [2,] NA  1
# [3,]  2 NA
# [4,]  2  1
# [5,] NA  2
# [6,]  1  2
# [7,]  2  2
# [8,]  2  1

Above, you're creating a matrix which loses all the labels that you created with factor. I think you want a data frame:
(df <- data.frame(a2,b2))

#       a2   b2
# 1   Male  yes
# 2   <NA>  yes
# 3 Female <NA>
# 4 Female  yes
# 5   <NA>   no
# 6   Male   no
# 7 Female   no
# 8 Female  yes

require('vcd')
(tab <- table(a2,b2, useNA = 'ifany'))
#          b2
# a2       yes no <NA>
#   Male     1  1    0
#   Female   2  1    1
#   <NA>     1  1    0

(tab <- table(a2,b2))
#          b2
# a2       yes no
#   Male     1  1
#   Female   2  1

You need to explicitly tell table if you want to see NA values in the table. Otherwise, it will drop them by default so that you are already "excluding" them when you use assocstats:
assocstats(tab)

#                      X^2 df P(> X^2)
# Likelihood Ratio 0.13844  1  0.70983
# Pearson          0.13889  1  0.70939
#
# Phi-Coefficient   : 0.167
# Contingency Coeff.: 0.164
# Cramer's V        : 0.167

For get.V just pass the data frame or matrix, not the table:
get.V <- function(y) {
  col.y <- ncol(y)
  V <- matrix(ncol=col.y,nrow=col.y)
  for(i in 1:col.y){
    for(j in 1:col.y){
      V[i,j] <- assocstats(table(y[,i],y[,j]))$cramer
    }
  }
  return(V)
}

get.V(df)

#           [,1]      [,2]
# [1,] 1.0000000 0.1666667
# [2,] 0.1666667 1.0000000

Comment: OK thanks! I think I found the error. I want to remove ` "" ` from a variable and I do  `var[var==""]<-NA
var <- droplevels(var)`
then  I want to select the dataframe with the categ variables I transformed without the empty levels :
`cat <-subset(data,select=c(var, var1, var2))'
b <-table(var,var1)
assocstats(b) ` but this dataframe still contains the variables with the empty levels! What can I do to replace them in the dataframe with the transformed variables??
Comment: you can do the entire data frame at once: `data[data == ''] <- NA`
Comment: For the get.V function output matrix, Is there a way that it replaces the column and row numbers of the matrix by the original column and row names from the dataframe ("yes", "no", "M", "F")?
Comment: I'm not sure what you mean with the example. each of the two columns (and each of the two rows) of the matrix would be yes/no or M/F. Do you mean you want the names of the data frame in the colnames of the matrix? like `V <- matrix(ncol = col.y, nrow = col.y, dimnames = list(names(y), names(y)))` instead of `V <- matrix(ncol=col.y,nrow=col.y)` ?


How To Pass Taxonomy Term (Name) to Filtered View (ID) - Drupal 7

Question: I have a custom view (page) created using Views in Drupal 7.
It contains a taxonomy field and an (exposed) taxonomy filter. When viewing the custom page/view, it works exactly as needed and a user can select a taxonomy filter to limit results accordingly. For example, the default view is /books and the user, via the exposed filter can select /books?book_type[]=21 to show only the books that have taxonomy ID 21.
The problem I am experiencing is that I need a second custom view (essentially a series of thumbnails, each depicting a different 'book_type') to link directly to the /books?book_type[]=21 URL path. Within this second view, I have added the appropriate taxonomy field and via the Rewrite Results option of the field, I have selected Output This Field as a Link and inserted books?book_type[]=[field_book_taxonomy], where [field_book_taxonomy] is the referenced taxonomy field.
When I view this thumbnail page, the link works, but the URL contains the taxonomy name rather than ID. So whilst I need /books?book_type[]=21, the page receives /books?book_type[]=ficton.
I have tried various Contextual Filters, including Term Name converted to ID, but the URL always passes name and the page therefore returns "An illegal choice has been detected".
Ideally I would like to retain the path /books?book_type[]=ficton on the initial view and have this interpreted successfully by the actual filtered view.
Please can someone offer a pointer as to where I am going wrong with this?
Thank you.
Answer: I don't think it is possible to pass term name,instead of term id, as value for exposed filter. But if you are fine with passing term id in your second view then while rewriting the output check the replacement patterns available there you will see the term id.
Like if your field name is field_book_taxonomy then in your replacement patterns you will see two patterns like [field_book_taxonomy] and [field_book_taxonomy-tid], choose the later one.
Comment: Hi. Initially thought -tid was missing, but I was looking at a rendered version of the taxonomy term in the view, rather than the term itself. Thanks for pointing me in the right direction; sending the -tid pattern looks like it will do the trick.
Comment: Indeed it works perfectly, thanks again for the pointer, I appreciate it.


Expandable Lists with Django

Question: I'm currently developing a small web app with Django, where user can search for cards in a trading card game and the results shall be shown in a list. Since there could be quite a lot of results returned I thought of doing a dynamic list where only 50 items a time are shown and then the user can select the next 50 results via a button.
Is there a specific Django way of doing this?
This his how the page currently looks like (and I would prefer to have the button for the next results on the end of the page):
Comment: You can take a look at pagination: https://docs.djangoproject.com/en/2.2/topics/pagination/
Comment: @Landcross: Ah exactly what I was looking for, thanks!
Comment: As well as pagination from core Django as mentioned by @Landcross, I would throw a mention the way of [Django Tables2](https://github.com/jieter/django-tables2) which may be a little heavyweight if you just want to display the objects as a list, but has options for filtering, pagination, export etc
Comment: Does this answer your question? [Django paginate for django 2](https://stackoverflow.com/questions/50449329/django-paginate-for-django-2)
Comment: @PyPingu: Interesting alternative to Landcross comment, thanks I'll have a look at it
Answer: The comment from @Landcross (see first comment) was the solution I was looking for:
https://docs.djangoproject.com/en/2.2/topics/pagination/
And @PyPingu posted an interesting alternative with
https://github.com/jieter/django-tables2

Expandable Lists with Django


Problema com heranças e classes no Ruby

Question: Eu tenho esse código. Não consigo imprimir a variável do editor no método incrementNameTitle, ela não está sendo exibida. O resultado é o seguinte:
Editora: Em Chamas - Collins!
class Editora
   attr_accessor :nameEditora
   def initialize(nameEditora)
      @nameEditora = nameEditora
   end
   def incrementNameTitle
      puts "Editora #{@nameEditora}: #{@title} - #{@author}!"
   end
end

class Book < Editora
   attr_accessor :title, :author
   def initialize(title, author)
      @title = title
      @author = author
   end
end

book = Book.new("Em Chamas", "Collins")
editora = Editora.new('LucasLivros')

puts book.incrementNameTitle

Comment: Você instanciou as classes separadamente, então por que utilizar herança? Um livro **é uma** editora?
Comment: Hum, estou aprendendo POO então não entendi direito seu comentário. Como eu posso acessar as variáveis title e author na classe Book?
Comment: Herança deve ser utilizado para criar subtipos, ou uma especialização de uma abstração. Ao fazer `Book` herdar de `Editora` você basicamente está definindo que um livro é um subtipo de uma editora. Isso não faz sentido. Talvez o que faria mais sentido aí é composição - e quem sabe você pode ler mais a fundo sobre ela.
Comment: Ok! Muito obrigado!
Comment: Como eu poderia fazer pra conseguir acessar o nome da editora junto ao nome e autor do livro?
Answer: Como o Woss comentou na sua pergunta, você está a fazer uma herança, quando na verdade, o que você precisa aqui é uma composição.
Você pode alterar o construtor do livro para receber uma editora:
class Book
   # code omitted...
   def initialize(title, author, editora)
     # code omitted...

Depois disso, você define o método incrementNameTitle em Book, como agora você está a receber a editora no construtor, você terá acesso ao que quiser.

Problema com heranças e classes no Ruby


Nginx won't start -- .sock file not found/no such directory

Question:
I'm trying to run my django application using uwsgi and nginx. It's been working for the past month, but today I edited file in the /sites-enabled/ dir and now nginx won't start.
Here are the error logs from nginx

Update
Was able to get nginx running again by removing the .sock file from my /sites-enabled directory. Still would like to know what this error message means--a google search of the answer turns up nothing of usefulness.
Comment: Post your nginx.conf and confguration file for that site. It's giving you fairly clear error messages though, have you tried looking where the error messages said to look?
Answer: I'm answering your updated question, about why this caused a problem. Without seeing your configuration files this is mostly a guess. I think your nginx.conf has a line something like this in it
<code>include /etc/nginx/enabled-sites/*;
</code>
In that directory referenced you probably had the studentprogress.sock file. Nginx picked up the file and tried to interpret it as configuration. As it wasn't a valid Nginx configuration file it caused an error.
Comment: Ah that makes sense now. That is indeed what my config file looks like. Not sure why the file gives that error, even though it works for uWSGI
Comment: Since you didn't post the contents of any of your files it's very difficult to answer that question. Please accept this answer if it helped solve your question.


How to determine (and explain) the sum of angles without measuring?

Question: Below is a photo of the angles/triangles in which I am working on determining the sum of the angles without measuring. The angles are a,b,c,d,e,f.

I understand that angles are formed my intersecting lines and I see many intersecting lines in this image.  The angles in a triangle add to 180 degrees and I see 3 labeled triangles.  Also, I know that if parallel lines are cut by transversal lines, then the corresponding angles are equal.
I'm confused on how to determine the sum of the angles a+b+c+d+e+f without measuring.  I also don't know how I would explain my reasoning. I know the theorems but combining all of the knowledge into a reason is difficult. Where do I even begin?
Comment: Hint. There's a theorem about the sum of the two angles remote from one vertex of a triangle - think about the exterior angle there. Hint for a second method: think about how much you must turn as you walk around that path from $a$ back to $a$ and a little further.
Comment: @B. Barnes answer would be 360 degrees
Comment: And how is that your reasoning?
Answer: Call the angles of the three outer triangles $a, b, g$; $c, d , h$; and $e, f, i$, respectively. Then
$$a + b + c + d + e + f = (a + b + g) + (c + d + h) + (e + f + i) - (g + h + i) = 3 \times 180^{\circ} - 180^{\circ} = 360^{\circ},$$
where we've used the fact that $g, h, i$ are also the angles of the inner triangle.
Answer: On the picture below:
$$\color{red}{\text{red angle}} + \color{orange}{\text{orange angle}} + \color{blue}{\text{blue angle}}=180^\circ$$
And
$$\begin{align}
\color{red}{\text{red angle}}+a+b=180^\circ&\implies
\color{red}{\text{red angle}}=180^\circ-a-b\\
\color{blue}{\text{blue angle}}+c+d=180^\circ&\implies
\color{blue}{\text{blue angle}}=180^\circ-c-d\\
\color{orange}{\text{orange angle}}+e+f=180^\circ&\implies
\color{orange}{\text{orange angle}}=180^\circ-e-f
\end{align}$$
Hence
$$180^\circ-a-b+180^\circ-c-d+180^\circ-e-f=180^\circ$$
$$a+b+c+d+e+f=360^\circ$$
Answer: Triangle w/ angle a and b has remaining angle we will call x.
Triangle w/ angle c and d has remaining angle we will call y.
Triangle w/ angle e and f has remaining angle we will call z.
The 'middle triangle' has angle x, y and z by vertical angles.
The middle triangle tells us that x + y + z = 180.
We also know that
a + b + x = 180
c + d + y = 180
e + f + z = 180
So it is elementary from here: 3 x 180 - (x + y + z) = 2 x 180 = 360.


Am I statistically allowed to use a binomial family here -> is my data truly independent?

Question: I'm having trouble with finding the most suitable analysis for my data. I'm investigating the behaviour of wild animals in nature. More specifically, I'm looking at animals scavenging from carcasses left out in nature and whether or not the animal is a bird or mammal (no other possibilities). So I basically watched video's of all the animals and behaviours at the 34 carcasses, then filtered for only animals performing a scavenging event. Then I counted the number of birds and mammals per carcass performing such a scavenging event, so basically: is the animal a bird (YES/NO)? Because the data were taken from different national parks, I use Area as a random effect.
The idea is that I want to test the effect of overhead cover on the proportion bird/mammal. Data to reproduce:
df_prop_birds_eating <- data.frame(Birds = c(2, 111, 10, 0, 0, 1, 12, 80, 58, 21, 34, 185, 2, 19, 66, 0, 4, 15, 360, 9, 54, 253, 67, 37, 1, 0, 0, 0, 0, 78, 38, 183, 1, 0),
                                   Mammals = c(5, 154, 6, 104, 11, 34, 44, 31, 40, 4, 3, 203, 91, 33, 68, 105, 151, 50, 107, 9, 0, 0, 1, 31, 9, 29, 195, 143, 304, 496, 422, 136, 131, 64),
                                   ProportionBirdsScavenging = c(0.292016806722689, 0.421254162042175, 0.621323529411765, 0.0147058823529412, 0.0147058823529412, 0.042436974789916, 0.222689075630252, 0.71422893481717, 0.589135654261705, 0.83, 0.906597774244833, 0.477486355366889, 0.0355787476280835, 0.369343891402715, 0.492756804214223, 0.0147058823529412, 0.039753320683112, 0.23868778280543, 0.762910945962968, 0.5, 0.985294117647059, 0.985294117647059, 0.971020761245675, 0.542820069204152, 0.111764705882353, 0.0147058823529412, 0.0147058823529412, 0.0147058823529412, 0.0147058823529412, 0.146597663455626, 0.0948849104859335, 0.571501014198783, 0.0220588235294118, 0.0147058823529412),
                                   pointWeight = c(7, 265, 16, 104, 11, 35, 56, 111, 98, 25, 37, 388, 93, 52, 134, 105, 155, 65, 467, 18, 54, 253, 68, 68, 10, 29, 195, 143, 304, 574, 460, 319, 132, 64),
                                   pointWeight_scaled = c(0.0000001, 0.45502650952381, 0.0158731142857143, 0.171075920634921, 0.00705477301587302, 0.0493828111111111, 0.0864198444444444, 0.183421598412698, 0.160493911111111, 0.0317461285714286, 0.0529101476190476, 0.671957704761905, 0.15167556984127, 0.0793651714285714, 0.223985968253968, 0.172839588888889, 0.261023001587302, 0.102292858730159, 0.811287496825397, 0.0194004507936508, 0.0828925079365079, 0.43386249047619, 0.107583863492063, 0.107583863492063, 0.00529110476190476, 0.0388008015873016, 0.331569731746032, 0.239858982539683, 0.523809571428571, 1, 0.798941819047619, 0.550264595238095, 0.220458631746032, 0.10052919047619),
                                   OverheadCover = c(0.7, 0.671, 0.6795, 0.79, 0.62, 0.62, 0.6413, 0.089, 0.4603, 0.04, 0.0418, 0.46, 0.5995, 0.532, 0.65, 0.6545, 0.74, 0.74, 0.02, 0.02, 0, 0, 0, 0.45, 0.8975, 0.92, 0.89, 0.86, 0.69, 0.755, 0.775, 0.585, 0.585, 0.55),
                                   Area = c("Markiezaat", "Hamert", "Hamert", "Hamert", "Hamert", "Hamert", "Hamert", "Hamert", "Hamert", "KempenBroek", "KempenBroek", "KempenBroek", "KempenBroek", "KempenBroek", "KempenBroek", "KempenBroek", "KempenBroek", "KempenBroek", "Markiezaat", "Markiezaat", "Markiezaat", "Markiezaat", "Markiezaat", "Meinweg", "Meinweg", "Meinweg", "PlankenWambuis", "PlankenWambuis", "PlankenWambuis", "PlankenWambuis", "PlankenWambuis", "Valkenhorst", "Valkenhorst", "KempenBroek"))

Previously I used a beta distribution on the manually calculated transformed proportions (so no true 0's or 1's), with a weight argument.
myglmm <- glmmTMB(ProportionBirdsScavenging ~ OverheadCover + (1|Area), data = df_prop_birds_eating, beta_family(link = "logit"), weights = pointWeight_scaled)

However, recently I found out that I actually am using discrete count data and I created the need for weights by converting my raw data into proportions. I solved the problem by analysing the data directly, thereby avoiding any need for weights at all.
I tried the following binomial distribution, with cbind(Birds, Mammals) as response variable.
myglmmbino <- glmmTMB(cbind(Birds, Mammals) ~ OverheadCover + (1|Area), data = df_prop_birds_eating, family = binomial)

One of the assumptions of using a binomial family is that the data should be independent. It's basically whether or not the probability of a bird scavenging affects the probability of a mammal scavenging, right? I find this difficult to say. I statistically checked with a Chi Square test. Is this a valid way? Here we have to reject the null hypothesis, so does that mean that they are dependent on each other?
tbl <- cbind(df_prop_birds_eating$Birds, df_prop_birds_eating$Mammals)
chisq.test(tbl, simulate.p.value = TRUE)
# Pearson's Chi-squared test with simulated p-value (based on 2000 replicates)
#
# data:  tbl
# X-squared = 2356.7, df = NA, p-value = 0.0004998

As far as I know, the other assumptions are met -> Each trial of the experiment has two possible outcomes (Bird or Mammal) and the probability of success is the same for each trial.
My true question is whether or not I am allowed to use the binomial family here.
Comment: I think you need to be a little more cautious about what you mean by independent. You want the observations to be conditionally independent, given your model.  So that Chi-squared test on the top level data won't help. You think that the proportion of birds is conditional on the overhead cover and the area?   What other non-independence do you think you might have missed?
Comment: Really interesting question. I take it every carcass has scavenging animals?    And you don't feel the need to model the total number of scavenging animals?
Comment: Yes, every carcass has scavenging animals. And no, I don't feel the need to model the total number of scavenging animals, I'm only interested in the proportion bird / not bird. You are absolutely right: doing a Chi-squared test on the top level data won't give me what I'm looking for, since it is conditional on ```OverheadCover``` and ```Area```. I don't have any other variables in my dataset which I expect the proportion of birds is conditional on. Is there a way of testing for independence which controls for the effect of ```OverheadCover``` and ```Area```?
Answer: If you are sure that at each event you did not count the same bird or mammal twice or more, then I think your approach using the binomial family is correct. From my point of view, you measure the proportion of birds (compared to non-birds) coming to a carcass. Each carcass seems to be independent of each other and your main predictor (OverheadCover) varies between carcass events. So I would consider that you can safely use the binomial distribution in your case. For me, the correct syntax to specify the model is the one with cbind() and no weights.
Comment: Ecologically, I expect your data to be non-independent. If, for example, a big mammal is at the carcass, no small bird will come near it. Hence the probability of observing birds at the carcarss is dependent on whether you observe big mammals there. Does that matter for your question? If you want to know, what the proportion of birds at a carcass is, and nothing more, it does not matter why they are there (or not), only to which proportion. So to me the independence strongly rests on *which hypothesis exactly* you want to test.
Comment: @Peter, I did not fully understand. If you counted several events per individual at the same carcass (but on different videos), you may fall in the trap of non-independence. If such is the case, I would rerun the analysis after keeping only one event maximum per individual for each carcass. Ecologically, for me, it is not so clear that there is always competition between different species of scavengers: I have already seen several species of birds and mammals scavenging at the same time the same carcass. For this aspect, you will have to use your domain knowledge to justify your approach.
Comment: Thanks for your reply. My data consists of cameratrap video's. Whenever an animal arrives, it starts recording for 60s. If an animal performs a scavenging event, it gets noted ("Bird"/"Mammal"). It can, however, happen (and is definitely the case sometimes) that one individual animal stays scavenging for several minutes, therefore resulting in several scavenging events in a row from one individual. However, I'm sure that, as you state, _at_ each event (i.e., video) I did not count the same bird or mammal twice or more. Just counted _several events_ per individual. Does this change your answer?
Comment: Interesting. For this study I hypothesise that the probability of a carcass being scavenged by birds is influenced by overhead cover. Since, most bird scavengers are visual predators, I expect overhead cover to be affecting this proportion. So basically, I'm only interested in the measured proportion of birds in relation with the overhead cover. I don't have data to test for the interspecific competition which is probably going on at the carcasses. This study is purely observational and I won't be able to say anything about causation -- only the fact that the results support the hypothesis.
Comment: Also, if there was a lot of interspecific competition going on (the presence of one group scares away the other), one would expect the model to be overdispersed. But, this is not the case.
Comment: @ KrisAnathema, I have some carcasses where hundreds of animals are recorded scavenging. For every video the first and second behavioural element is noted (although I'm only interested in 'scavenging'). Between video's there is an interval of 2 seconds before it starts scanning again. So the video's are not technically continuous, there is at least a small interval between. If one individual bird was scavenging for 10 minutes in a row, I'd have 10 counts of birds scavenging. Thank you all for your thoughts.


Need block context in hook_form_alter

Question: I'm trying to get my module to work: it replicates an exposed filter of a view into a block to display on other pages. Altering the form generally works, but it unfortunately works globally, ie. my changes are also applied to the original filter form on the views page.  That's because I use a simple checking of $delta which does not give me a context - sort of module signature that embedded the form.
I tried both hook_form_alter and hook_form_FORMID_alter - the variables passed to those functions don't seem to carry that info though.
Is there a way to get this kind of context?
Answer: If you are displaying this block on only certain pages, looking at $_GET['q'] or arg(#) will tell you that path or one of its arguments, so maybe you can switch on that?  eg, path/to/my/page is in $_GET['q'] and arg(2)=='my'.  Note that paths to nodes are system paths, not aliases, so the path might be just node/# but you can do a drupal_get_path_alias() to find it if need be.  If you are displaying the block only on certain node types, you can grab $node=menu_get_object() and then switch on $node->type as an example as well.  In fact, if you do it that way, $node->path should already point to the aliased path, and it's already cached for your performance pleasure :)
Oh, and failing all the above, you could do all of this in a custom module block, too, eg, in there do something like:
$block['subject']='// subject goes here';
// do the hook form alter
$content=views_embed_view( // the view in question );
$block['content']=$content;

return $block;

All of the php above presumes D6, minor changes apply to D7, but since it is being called in the block itself, the form alter should only change the view there (unless it is also being displayed elsewhere on the same page)
Comment: Well, this of course popped into my mind, but this seem to be not scalable. I thought we had something more versatile. But I noticed that controls have an array labeled #theme which contains some kind of a context: views_exposed_form__[view-name]__block_1. This could probably be tested with a strpos - closer, although still not perfect.
Comment: indeed.  a lot of times print_r()'s of arguments will shed some light on a lot of hidden information inside a $view.

Need block context in hook_form_alter


Create a bullet list item using PDFBox

Question: I am using PDFBox 2.0 to do a HTML to PDF conversion. This is going quite well, except that I am stuck at converting the list item tag to a bullet (black, round, disc).
The official Unicode bullet character is U+2022, however none of the fonts in PDFBox support characters above the 8-bit range. I have tried embedding and using some of the fonts in the Windows font folder "C:\Windows\Fonts", but they do not seem to support more than 8-bit either.
PDFBox has a class called PDListAttributeObject which seems to have something to do with lists and bullets, but I cannot find any examples of how to use it.
So, my questions are:

Can I use PDListAttributeObject in PDFBox to write a bullet character to the contentstream? and if so, how?
Are there any standard Windows fonts that can render a bullet character?
Any other suggestions on how to get a bullet character written to a PDF?
Comment: Doesn't work with 1.8, you'll need 2.0, see https://stackoverflow.com/questions/25525213/how-to-write-unicode-text-to-pdf-with-pdfbox
Comment: I am using 2.0. Sorry, forgot to mention that..
Comment: Then please edit your question to mention that you're using 2.0. Have you looked at the EmbeddedFonts.java example? https://svn.apache.org/viewvc/pdfbox/trunk/examples/src/main/java/org/apache/pdfbox/examples/pdmodel/EmbeddedFonts.java?view=markup&sortby=date
Comment: I have now tried the EmbeddedFonts.java example. I can get the bullet character using that specific font. This will serve my purpose fine :-)
Comment: Just to clarify, can I then only use the LiberationSans-Regular.ttf font to render a bullet?.
Comment: Glad it works. If you like, answer your question yourself, so that it will help others :-)
Comment: You can use any font that has the symbol.
Comment: OK, thanks. Is there any way to see if a Windows font has that symbol? Other than trial and error?
Comment: PDType0Font.hasGlyph()
Answer: The solution, in this case, was to use the font included with PDFBox 2.0 (LiberationSans-Regular.ttf).
As a follow-up, I will now try to check which standard Windows fonts can render the bullet character. Perhaps by iterating over the fonts in the Windows/Fonts folder and checking using the PDType0Font.hasGlyph() method.
Thanks Tilman :-)

Create a bullet list item using PDFBox


Selecting subdocument in mongoose with a $

Question: This is my document structure:
"event": {
    "attendants": {
        "seekers": [
            {
                "$oid": "5bcdabd27e51de001576d289"
            },
            {
                "$oid": "5bc9b39c1a48dd0d7d521924"
            },
        ],
        "employers": [
            {
                "id": {
                    "$oid": "5bcda6477e51de001576d287"
                },
                "boothVisits": []
            },
            {
                "id": {
                    "$oid": "5bd0787e0f64cd001563ddbf"
                },
                "boothVisits": [
                    {
                        "$oid": "5bcda6477e51de001576d287"
                    },
                    {
                        "$oid": "5bd0787e0f64cd001563ddbf"
                    },
                ]
            },
        ]
    },
}

I need to select events in which current user's id is in the employers table. But there is the boothVisits as well there which prevents a simple in check. This is what I tried to do
Event.find().where('attendants.employers.$.id').equals(req.user._id).catch(e => console.log(e)),

But it ain't working. What am I missing? I'm assuming I'm using the $ in a wrong way.
Comment: So do you want the whole document to be returned or a specific employer that matched?
Comment: The whole event where the employer id is in the `attendants.employers` array
Answer: IF the whole document to be returned then you do not need to use $.
Simply use as below:
const mongoose = require('mongoose');
Event.find({"attendants.employers.id": mongoose.Types.ObjectId(req.user._id)}),

This will check id under employers array if found then the whole event will be returned.
Comment: Thanks! I was overthinking it lol. I edited the answer so it matches the question + added mongoose for people who wouldn't know where the ObjectId came from


Mean and Variance of "white noise" integral

Question: I have to find the mean and variance of "white noise" - Brownian motion of
$$ X = \int^1_0 t dW(t)$$
So we start the mean:
$$ E[X] = E[\int^1_0 tdW(t)] $$
I'm thinking this way:
$$ E[X] = tW(1) - tW(0) - \int^1_0 1W(t)dt $$
Then I'm not sure where to go next as the mean of $W(t)$ is $0.$
Comment: Hint: Think of the integral as a sum and find the expectation. Assume the limit can be passed through the expectation. For variance, use the same trick.
Comment: Also Integration by parts doesn't work the same way for Ito integrals.
Comment: I'm having a hard time setting it up with the sum part. Can you show me how you would set it up? Thank you.
Comment: Sure and is this for a measure theory class? If not, you can be fairly loose with passing the expectation through the limit.
Comment: No, it's for a modeling class! We're learning about white noise and Brownian motion, and we were just introduced to integrating things in that regard. We did learn that $E[\int^b_a f(t) dW(t)] = 0$ but what's throwing me off is the $t$ here in my question.
Comment: Worth checking: https://math.stackexchange.com/q/2791245/532409
Answer: Sketch:
$$E[\int_0^1 t dW(t)] \sim E[\sum_{i=0}^{N - 1} \frac{i}{N} [W(\frac{i+1}{N}) - W(\frac{i}{N})]$$
$$E[\sum_{i=0}^{N - 1} \frac{i}{N} [W(\frac{i+1}{N}) - W(\frac{i}{N})] = \sum_{i=0}^{N - 1} \frac{i}{N}E[W(\frac{i+1}{N}) - W(\frac{i}{N})]$$
$$\sum_{i=0}^{N - 1} \frac{i}{N}E[W(\frac{i+1}{N}) - W(\frac{i}{N})] = \sum_{i=0}^{N - 1} \frac{i}{N}\cdot0 = 0$$
Assuming we can pass the expectation through the limit, we get:
$E[\int_0^1 t dW(t)] = 0$
For Variance,
$$Var(\int_0^1 t dW(t)) \sim \sum_{i=0}^{N - 1} \frac{i^2}{N^2}Var[W(\frac{i+1}{N}) - W(\frac{i}{N})]$$
By independence.
$$\sum_{i=0}^{N - 1} \frac{i^2}{N^2}Var[W(\frac{i+1}{N}) - W(\frac{i}{N})] = \sum_{i=0}^{N - 1} \frac{i^2}{N^2}\frac{1}{N}$$
The above looks a lot like the expression:
$$\int_0^1 t^2 dt$$
Which is equivalent in the limit.
Therefore: $$Var(\int_0^1 t dW(t)) = \int_0^1 t^2 dt = \frac{1}{3}$$
This result is based Ito Isometry FYI, which is the fundamental theorem of stochastic calculus.
$$E[(\int_0^T f(t)dW(t))^2] = \int_0^T f(t)^2dt$$
Comment: Wow! Thank you so so much! It makes sense!


Gráfico criado incorretamente

Question: Olá,
Eu estou treinando a criação de gráficos no Python com matplotlib. Para isso, estou importando um HTML com histórico de ações da WEGE3.
df_history = pd.read_html("https://br.financas.yahoo.com/quote/WEGE3.SA/history?p=WEGE3.SA")

Tirei os duplicados (só haviam 2):
df_remove = df_history[0].drop_duplicates(subset=['Data'])

E tirei a última linha:
yy = df_remove['Fechamento*'].drop(100)
xx = df_remove['Data'].drop(100)

Defini as labels:
plt.xlabel('Data')
plt.ylabel('Preço')

O problema acontece aqui: Quando eu vou exibir o gráfico, ele fica errado. Eu aumentei o tamanho só para eu ver se os valores de X e Y apareciam corretos no grafico e aparecem, mas o desenho do gráfico mesmo, está errado:
f = plt.figure()
f.set_figwidth(28)
f.set_figheight(28)
plt.plot(xx, yy)
plt.show()

Este é o gráfico (errado) que aparece:

Para confirmar se o gráfico está certo ou errado, eu peguei os mesmo dados e coloquei no Excel.
Este seria o gráfico correto:

Eu perdi um tempo tentando analisar mas eu não encontrei onde está o problema.
Não sei se esta informação é relevante mas, eu estou executando este código no Google Colab.
Obrigado.
Comment: Não seria melhor fazer o gráfico a partir  do [csv](https://query1.finance.yahoo.com/v7/finance/download/WEGE3.SA?period1=1577853285&period2=1609475685&interval=1d&events=history&includeAdjustedClose=true) disponibilizado na própria página de HTML importada?
Comment: Com o CVS deu certo. Mas como meu objetivo é treinar, eu gostaria de entender o meu erro usando o HTML mesmo :)
Answer: O que está acontecendo é que tanto xx quanto yy estão preenchidos com strings, ao invés de valores numéricos ou de data. Por isso, quando você plota, matplotlib só está vendo texto. Para resolver, basta converter para os tipos adequados:

yy pode ser convertido para uma série de inteiros usando o método to_numeric(). Precisa também usar o argumento errors='coerce', porque tem alguns valores não disponíveis que não podem ser convertidos diretamente para inteiro.
xx está com a data escrita por extenso, em português. Talvez funcione num programa como o excel (se ele estiver em português), mas pra converter pra um formato de data que o python entenda você teria que criar uma função dedicada. A alternativa é usar os valores como estão, aí a função plot() vai usá-los como labels do eixo x.

O código fica assim:
# define um tamanho maior para a figura, caso contrário fica impossível de ler os labels
plt.figure(figsize = (20,10))

# plot com os valores de xx no eixo x e yy convertido para inteiros no eixo y
plt.plot(xx, pd.to_numeric(yy, errors='coerce'))

# rotação de 60 graus dos labels para tornar legível
plt.xticks(rotation = 60)

# mostra a figura
plt.show()

Resulta na seguinte figura:

Repare que ficou com uma descontinuidade, referente a um dia em que não tinha a cotação disponível (o argumento errors='coerce' fez que fosse convertido para NaN).

Gráfico criado incorretamente


Configuring firewall centOS

Question: Hi I am trying to configure my ip tables...but I can't seem to make this work...  I'm not sure why (this is my first dedicated server)
-A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 80 -j ACCEPT
-A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 443 -j ACCEPT
-A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 21 -j ACCEPT
-A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 25 -j ACCEPT
-A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 53 -j ACCEPT
-A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 80 -j ACCEPT
-A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 110 -j ACCEPT
-A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 843-j ACCEPT
-A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 443 -j ACCEPT
-A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 465 -j ACCEPT
-A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 646 -j ACCEPT
-A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 993-j ACCEPT
-A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 995-j ACCEPT
-A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 7777 -j ACCEPT
-A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 3306 -j ACCEPT
-A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 10009 -j ACCEPT
-A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 7778 -j ACCEPT
-A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 25565 -j ACCEPT
-A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 8765 -j ACCEPT
-A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 8766 -j ACCEPT

This is what I have in there now...default....
# Firewall configuration written by system-config-securitylevel
# Manual customization of this file is not recommended.
*filter
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
:RH-Firewall-1-INPUT - [0:0]
-A INPUT -j RH-Firewall-1-INPUT
-A FORWARD -j RH-Firewall-1-INPUT
-A RH-Firewall-1-INPUT -i lo -j ACCEPT
-A RH-Firewall-1-INPUT -p icmp --icmp-type any -j ACCEPT
-A RH-Firewall-1-INPUT -p 50 -j ACCEPT
-A RH-Firewall-1-INPUT -p 51 -j ACCEPT
-A RH-Firewall-1-INPUT -p udp --dport 5353 -d 18.104.22.168 -j ACCEPT
-A RH-Firewall-1-INPUT -p udp -m udp --dport 631 -j ACCEPT
-A RH-Firewall-1-INPUT -p tcp -m tcp --dport 631 -j ACCEPT
-A RH-Firewall-1-INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
-A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 22 -j ACCEPT
-A RH-Firewall-1-INPUT -j REJECT --reject-with icmp-host-prohibited
COMMIT

I put it just above COMMIT.
Those are all the ports I need open.
I'm using centOS 5.7 64bit.
Answer: They look OK, but don't put them in just before COMMIT; put them one line earlier, before -A RH-Firewall-1-INPUT -j REJECT --reject-with icmp-host-prohibited.  Otherwise processing will never get to your new rules.
Don't forget a service iptables restart once you've done it.
Comment: Hurray it worked! Thanks :) Another small issue was with a few of the -j didn't have a space. :D

Configuring firewall centOS


/var and /home folders clogged up on cPanel (Linux)

Question: Recently the /var and /home folders have been clogging up on my server and I received a 'critical error' email saying that the /home folder was 100% full. I managed to fix it using the LVExtend command but I was just wondering how I can find out what was clogging the directories up? Are there logs of some sort?
I have a dedicated server w/ root access so I have full control. What can I do to prevent this from happening again as it's already happened twice?
Thanks,
James
Answer: /home is usually user files.
/var has mysql, mail, log files etc
Do you have space limits for accounts in cpanel?
Ran these commands to see what is using the most space:
du -h -s /home/*
du -h -s /var/*
Comment: Hi Hawk, thanks for that. We limit account space on the server and the account which caused the issue only used about 4% of its allocated space. He has 110GB of disk space. He has lots of cron jobs, which may have caused the issue. The home folder was 100% full and /var was 97% full.
Comment: Here's the /var command output; 44M /var/cache
429M /var/cpanel
0 /var/cvs
0 /var/db
0 /var/empty
0 /var/games
26G /var/lib
0 /var/local
4.0K /var/lock
886M /var/log
0 /var/mail
240K /var/named
0 /var/nis
0 /var/opt
0 /var/preserve
64K /var/profiles
300K /var/run
1006M /var/softaculous
4.3G /var/spool
676K /var/tmp
32K /var/www
0 /var/yp
Answer: Disks get full because files get written to them.  To find what's using the space in a partition, du (for "Disk Usage") is the tool.  I like to use:
du -hx --max-depth=1 /home

Because it limits itself to the partition of interest (-x) and doesn't give you excessive verbosity.  If you just want a sorted list of space hogs, you can add |sort -h to the end of that command.
Once you've got that info, you can drill down into excessively-large looking directories to see where the usage is happening (/home/foo, /home/foo/suspicious, etc etc).  What counts as "excessively-large looking" is a judgement you, as the admin, need to make based on the expected usage of your server.
Finding who/what is responsible for creating the files you consider to be excessive can be a little tricky.  Using ls -l will show the ownership of the file(s), which is the first piece of info.  If it's a regular user, then the problem could be cron jobs, a webapp the user is running, or a manually-invoked local command.  That's something you'll have to discover for yourself, as it's your box.  If the files are owned by root or another system user, then it's a system process and you get to hunt the culprit down (you should know what's running on your system and what it does, so it should be fairly easy).
As far as preventing it from happening again, if it's a user causing the problems, your options are:

Per-user quotas;
Penalising users for excess usage;
Proper capacity planning.

If it's a system process:

Managing disk usage of system process properly;
Proper capacity planning.

Based on your comment on Hawk's answer, the problem may be a capacity planning issue.  If you're giving users enough space that they're storing 110GB of data and only using 4% of their quota, you need bigger disks (much, much bigger disks).  If you're relying on overcommit to make money, sooner or later you're going to get bitten in the arse.
Comment: Hello, thanks for your very informative answer! Why would I need to get bigger disks if he's only used 4% of his 110GB allowance? :-)
Comment: Because if you're running out space when the user's only used 4% of their 110GB allowance (or 4.4GB, by my calcuation), then you're going to have a real hard time if the user actually decides to use the other 105.6GB you've given them.  Multiply this by the (presumable) rest of your customer base, and you're in a bit of a pickle.
Answer: There are no logs tracking creation / changes to every file on the system.
du (and sort?) will give you stats on the size of files, but it'll be a huge list - have a look at 'find' to locate files which have been changed recently.


App rejected for using an icon that is an "Apple trademark image"

Question: I just got rejected from the App Store for this reason:

We've reviewed your app and determined that we cannot post this version of your iPhone application to the App Store because of an Apple trademark image.
You may not use the Apple Logo or any other Apple-owned graphic symbol, logo, or icon on or in connection with web sites, products, packaging, manuals, promotional/advertising materials, or for any other purpose except pursuant to an express written trademark license from Apple, such as a reseller agreement.

Now, I believe the infringing image is this one - however it is clearly NOT an iPhone and it's used to help you find your friends phones around you.. my artist drew it, it's not an iPhone.

The "infringing Apple trademark image" is shown above
What can I do about this?? This is ridiculous.
Comment: this IS sad but IMO this isnt programming related and doesnt really belong on SO
Comment: You should first engage conversation with apple on the app rejection screen to ask exactly what image is problematic.
Comment: Get rid of the little circle at the bottom, that should make it look different enough from an iphone for them
Comment: This question appears to be off-topic because it is in no way related to a practical programming problem in the scope of the site.
Comment: You can not do anything about it i guess, you have an artist, so he could make a new one and better one seems to me.
Comment: It may not be an iPhone to you but as far as Apple see it, it looks like an iPhone. I also think it looks like an iPhone because of the button at the bottom.
Comment: This is not off-topic. It is a reasonable question faced by a software developer to an audience that may certainly be able to help. Stack Overflow is slowly being destroyed by individuals who have nothing better to do than to be pedantic about questions.
Comment: for me I have just removed the screen shot that has the apple logo ,, and reply to the apple in resolution center ,, 1 hour later they approved , without new release build
Answer: Have a look at iPod, iPhone, and iPad Icons section of the Licensing and Trademarks Developer website.
I'm attaching the Apple's iPhone icon that caused rejection.

There is nothing you can do about it. You have to redesign the icon so it does not look similar to Apple's one.
UPDATE
I found another example of iPhone image on Apple's website that could have been the reason for rejection.
Comment: We redesigned it to look like an Android phone instead, let's see what happens..
Comment: @user3597601 what happened?
Answer: If you have an image that has the likeness of an iPhone in it, I can almost guarantee you that's the reason it got rejected. I recall reading a book where a guy developed an app with an iPhone image in it, and got rejected. My suggestion is to use something else, so long as it's not Apple related, and I bet you'll be fine.
Please refer:https://www.apple.com/legal/intellectual-property/guidelinesfor3rdparties.html
Comment: for me I have just removed the screen shot that has the apple logo ,, and reply to the apple in resolution center ,,


LSTM with TFIDF as input, dimension error

Question: I am trying to run LSTM with TFIDF as input, but getting an error. I have TFIDF with each entry of 11915 dimensions
Code is as follows:
## Creating model
model=Sequential()
model.add(Bidirectional(LSTM(100, input_shape=(1, 11915),return_sequences=True)))
model.add(Dropout(0.3))
model.add(Dense(1,activation='sigmoid'))
model.build(input_shape=(1, 11915))
model.compile(loss='binary_crossentropy',optimizer='adam',metrics=['accuracy'])
print(model.summary())

Error is as follows
Input 0 of layer bidirectional_27 is incompatible with the layer: expected ndim=3, found ndim=2. Full shape received: [1, 11915]
I am new to this area, any help will be highly appreciated. It will be really nice if someone writes a dummy code for running Bidirectional LSTM on such an input
My input is tfidf of 10229*11915. I want to do fake news detection using LSTM on TFIDF as input
Answer: this is a complete working example
# create fake data
n_sample = 10229
X = np.random.uniform(0,1, (n_sample,11915))
y = np.random.randint(0,2, n_sample)

# expand X to 3D
X = X.reshape(X.shape[0],1,X.shape[-1])

model=Sequential()
model.add(Bidirectional(LSTM(100, return_sequences=False), input_shape=(1, 11915)))
model.add(Dropout(0.3))
model.add(Dense(1, activation='sigmoid'))

model.compile(loss='binary_crossentropy',optimizer='adam',metrics=['accuracy'])
print(model.summary())

model.fit(X,y, epochs=3, batch_size=256)

the error occurs because probably u didn't manage your data correctly. take care also to define the first layer correctly and return_sequences=False because your output is 2D
Comment: Your answer solves my problem. Thanks a lot.
Answer: You want to specify your input_shape in the Bidirectional layer:
model.add(Bidirectional(LSTM(100, return_sequences=True), input_shape=(1, 11915)))


Find $a$ for which $(a-3)(a-7)$ is a perfect square

Question: The only solutions seem to be 3 and 7 but I can't prove that there are no others.
Context:
Find every value for integer a, for which $x^2-(a+5)x+5a+1$ expression can be factored as $(x+b)(x+c)$ where b and c are integers.
$x=\frac{a+5 \pm \sqrt{(a-3)(a-7)}}{2}$
(In a pre-calc book, btw. Real solutions only (don't know if it matters))
I have no idea where to start, forgive me for not having any real attempts.
Answer: Alternative approach:
Let $~b = (a-5) \implies ~(a-3) \times (a-7) = b^2 - 4.~$
So, you are looking for some integer $~b,~$ other than $~b = \pm 2,~$ such that $~b^2 - 4~ = n^2 \implies b^2 - n^2 = 4,~$ for some integer $~n.$
If such a solution $~(b,n)~$ exists, then it must also exist with $~b,n \in \Bbb{Z_{\geq 0}},~$ with $~b > n.$
So, there must exist a $~k \in \Bbb{Z^+}~$ such that $~b = n+k \implies 4 = (n+k)^2 - n^2 = 2nk + k^2.~$
Since $~4~$ is an even number, $~k^2~$ must also be even, which implies that $~k~$ is even.  So, the smallest possible value for $~k~$ is $~k = 2.~$
Then, this implies that $~4 \geq 2n(2) + (2)^2 = 4n + 4.~$
This requires that $~n = 0,~$ which implies that $~b^2 = 4 \implies b = \pm 2.~$  So, no solution other than $~b = \pm 2~$ is possible.
Answer: To answer your question: when can $(a-3)(a-7)$ be a perfect square?
Suppose
$$(a-3)(a-7)=k^2, $$
for some integer $k$. Then
$$a^2-10a+21-k^2=0.$$
This implies that
$$a = \dfrac{10\pm\sqrt{100-4(21-k^2)}}{2},$$
implying that
$$a = \dfrac{10\pm 2\sqrt{4+k^2}}{2}.$$
As $a$ has to be an integer, we look for values of $k$ for which$\sqrt{4+k^2}$ is a perfect square. This is quite easy as
$$k^2+4 = m^2 \implies 4 = (m-k)(m+k).$$
Following are the possibilities now:
$(m-k, m+k)=(\pm1,\pm4); (m-k, m+k)=(\pm2,\pm2); (m-k,m+k)=(\pm4,\pm1)$.
The first and last cases can be easily discarded as the solutions to which are not integers. Thus, we are left with the option $(m-k, m+k) = (\pm2,\pm2)$. Solving this, we would get $m=\pm2$ and $k=0$. Thus
$$(a-3)(a-7)=0,$$
implying that $a=3, 7$ are the only solutions.
$\textbf{Note.}$ I really did not notice the comment of Will Jagy in the comments which runs on the similar lines as that of this. I just noticed it after writing this answer.
Comment: By the way, there are also negative possibilities, such as (-1; -4) (-2;-2).
Comment: Oh. Yes! Indeed. Rightly pointed out. But the result would be the same as $k=0$. I shall edit the answer. Thanks for pointing out.
Answer: Find all integers $a$ such that $$x^2-(a+5)x+5a+1=(x+b)(x+c)$$ where $b,c$ are integers
The roots of the quadratic are $-b$ and $-c$, therefore
$$(b+5)(c+5)=b c + 5(b+c)+25=5a+1+5(-a-5)+25=1$$
Either
$b+5=c+5=1$ in which case $b=c=-4$ and $a=3$
or
$b+5=c+5=-1$ in which case $b=c=-6$ and $a=7$


Change the sorting order used for Book nodes

Question: How can I change the order used for Book nodes, which by default is based on weight and title?
I have a set of nodes displayed inside a page that use a structured book. I want to display them ordered by weight and random, instead of weight and name.
The book is used to structure different types of local companies and restaurants.
I have traced the code looking for a solution, but it's a bit messy for me.
Is there a hook that could be helpful to achieve this?
Answer: You should checkout the Book helper module.

The Book helper module enables additional features from Drupal's menu system to improve the ordering of a book's pages. This module also allows administrators to further customize a book's navigation block.
Features

Enhances the book outline manager
Adds 'enable' checkbox (aka hidden) to the manage book outline page
Adds an 'Order' tab (node/%/order) to a book's main page
Adds 'administer own book outlines' permission for ordering books from a book's main page
Removes the 'Outline' tab from all nodes
Removes the book fieldset from node edit pages if the content type does not allowed book outlines
Removes 'add child page' and 'printer-friendly version'
Removes book navigation
Customizes visibility of a book's navigation elements
Automatically 'Create new book' for selected content types
Includes 'Book (inline) navigation' block that can be easily positioned after a node's content
Disables new revisions from being created when a book's node title is updated
Displays a warning when deleting a book page (node/%/delete) that has child pages


how can I use the output of a sample to use in another sample?

Question: In my problem for example, when a user flips a coin, depending on the flip, they can roll a d4 die, or a d6. (so heads can equal d6 and tails can equal d4 so to speak).  From there I need to use Monte Carlo simulation to find the expected roll (the answer is 3 but we need to write the code for it).
roll <- function(){

  d4 <- sample(1:4,1)
  d6 <- sample(1:6,1)

  dice <- sample(c(d4, d6),1)
  coin <- sample(c("H","T"),1)

  sum(which(coin == "H") & which(dice == d4))

}

mean(replicate(10000, roll()))

I could use a little to nudge to the right direction
Comment: You are going to tell your instructor you got help on Stack Overflow, right?
Comment: Yeah, the class is probability and statistics, and not due untill Tuesday, I have been working on the problems during the weekend and got stuck on this one in particular.

I got stuck on mostly on the fact I cant use if statements or loops (I should have stated that in the problem, my apologies)
Comment: but `ifelse()` is allowed ... ?  (I can appreciate why instructors put constraints on solutions, but sometimes it seems a bit silly; you could do something like `r <- sample(0:1,1); r*sample(4,1) + (1-r)*sample(6,1)` ....)  Do you have any clues about what direction they intended you to go when they forbade `if` statements ... ?
Comment: Ya I emailed him about it and said the coin isnt really needed  and the quetion just has awkward wording.  All I needed was the die vector
Answer: I think you want something along the lines of
coin <- sample(c("H","T"),1)
if (coin=="H") {
   return(sample(1:4,1))
} else {
   return(sample(1:6,1))
}

You don't really need the else clause to be stated explicitly (because the code will only get past the if statement if coin != "H").
This could be done more compactly, at the cost of legibility (you don't need to store the results in coin temporarily, especially since you're only using that piece of information once). Or it could be done less compactly (and a little more like your original code) by storing d4 and d6 and then if (coin=="H") { return(d4) } else { return(d6) }.
It's very tempting to start code-golfing (e.g. sample(sample(c(4,6),1),1)) ... or r <- sample(0:1,1); r*sample(4,1) + (1-r)*sample(6,1) or ...
Answer: The sum(which(coin == "H") & which(dice == d4)) is not selecting the dice based on the coin. Use something like res <- ifelse(coin == "H", d6, d4) to select which dice roll you want to use based on the coin flip.
This is giving an output of ~3:
roll <- function(){

  d4 <- sample(1:4,1)
  d6 <- sample(1:6,1)

  dice <- sample(c(d4, d6),1)
  coin <- sample(c("H","T"),1)

  res <- ifelse(coin == "H", d6, d4)
  return(res)
}

mean(replicate(10000, roll()))

Comment: `ifelse()` is OK but `if` is probably preferable if you're really only going to be testing a scalar expression ...
Comment: fair enough. `res <- if (coin=="H") d6 else d4` works nicely but is (I think) confusing to newbies.
Comment: There are lots of ways of doing it, and your approach is probably what I would go with. I was just trying to make minimal changes to the original code.


Kusto: Run a query for a list of unique id numbers

Question: I am a C programmer and new to Kusto.
I am running a Kusto query which gives me the result for a direct search on a unique id number. How do I run that query for a list of id numbers. In C I would use a for loop for the range of items in the array of list but I do not know how to translate that logic in Kusto.
Query:
let startdate = ago(5d); let enddate = ago(1m);
DataBase
| where messageType != "Beacon"
| where timestamp between (startdate..enddate)
| where uniqueId == "26ca68"
| project uniqueId, timestamp

I wish to run the above query for a list of 25 unique Id numbers.
Thank you.
Answer: you can use the in() operator: https://learn.microsoft.com/en-us/azure/kusto/query/inoperator
for example:
let IDs = dynamic(["abc", "def", "ghi"]); // replace/add IDs
let startdate = ago(5d);
let enddate = ago(1m);
DataBase
| where messageType != "Beacon"
| where timestamp between (startdate..enddate)
| where uniqueId in (IDs) // <----
| project uniqueId, timestamp

Comment: Thank you for the solution.


*ngFor won't work when used in imported component

Question: Error I'm getting:

Can't bind to 'ngforOf' since it isn't a known property of 'div'.
  ("]*ngfor="let item of [1, 2, 3]"> {{item}} ")

Description:
I encountered a strange problem, I was trying to use *ngFor in my application but it won't work in any possible combination. I tried using BrowserModule, CommonModule. Both failed. Any ideas why I can't get this to work?
nav.component.ts
import {OnInit, Component} from '@angular/core';

@Component({
    selector: 'global-nav',
    template: `

            {{item}}

    `
})

export class NavComponent implements OnInit {

    private navigation;

    constructor() {
        this.navigation =
        [
            {
                "href": "#homepage",
                "label": "Homepage"
            }
        ]
    }
    ngOnInit() {

    }
}

app.module.ts
import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { CommonModule } from '@angular/common';
import { BrowserModule } from '@angular/platform-browser';
import { RouterModule, Routes } from '@angular/router';

import { AppComponent } from './app.component';

import { NavComponent } from './components/global/nav/nav.component';
import { MainComponent } from './components/main/main.component';

const appRoutes: Routes = [
  {
    path: '',
    component: MainComponent,
    data: { title: 'Homepage' }
  },
  {
    path: '**',
    redirectTo: '',
    pathMatch: 'full'
  }
];

@NgModule({
  declarations: [
    AppComponent,
    NavComponent,
    MainComponent
  ],
  imports: [
    RouterModule.forRoot(
      appRoutes
    ),
    BrowserModule
  ],
  providers: [],
  schemas: [ CUSTOM_ELEMENTS_SCHEMA ],
  bootstrap: [ AppComponent ]
})
export class AppModule {}

app.component.ts
No need for it only code for setting up title.
package.json
{
  "name": "",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "build": "webpack -p",
    "watch": "webpack -p -w"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@types/core-js": "^0.9.42",
    "@types/node": "^8.0.12",
    "babel-core": "^6.25.0",
    "babel-loader": "^7.1.1",
    "babel-preset-env": "^1.6.0",
    "copy-webpack-plugin": "^4.0.1",
    "css-loader": "^0.28.4",
    "file-loader": "^0.11.2",
    "html-loader": "^0.5.1",
    "node-sass": "^4.5.3",
    "postcss-loader": "^2.0.6",
    "precss": "^2.0.0",
    "progress-bar-webpack-plugin": "^1.9.3",
    "pug": "^2.0.0-rc.3",
    "pug-html-loader": "^1.1.5",
    "pug-loader": "^2.3.0",
    "raw-loader": "^0.5.1",
    "sass-loader": "^6.0.6",
    "style-loader": "^0.18.2",
    "ts-loader": "^2.2.2",
    "typescript": "^2.4.1",
    "url-loader": "^0.5.9",
    "webpack": "^3.0.0"
  },
  "dependencies": {
    "@angular/common": "^4.3.6",
    "@angular/compiler": "^4.3.6",
    "@angular/core": "^4.3.6",
    "@angular/forms": "^4.3.6",
    "@angular/http": "^4.3.6",
    "@angular/platform-browser": "^4.3.6",
    "@angular/platform-browser-dynamic": "^4.3.6",
    "@angular/router": "^4.3.6",
    "core-js": "^2.5.1",
    "rxjs": "^5.4.3",
    "zone.js": "^0.8.17"
  }
}

I'm running out of ideas and I can't find anything about this.  Maybe someone here can help me with this.
Fixed:
Webpack was making my templates into lowercase. And so all my *ngFor became *ngfor

*ngFor won't work when used in imported component
Comment: haver you tried adding `trackBy: $index` to your *ngFor?
Comment: @Roysh not before but now I did, the same effect but it added `Can't bind to 'ngforTrackBy' since it isn't a known property of 'div'.`
Comment: Update your packages
Comment: its not the template syntax... that works fine in one of mine. Must be the setup / system / npm modules
Comment: @Vega It was the first thing I did. No effect.
Comment: what I would do:
save the array as parameter in your controller: `private numArr = [1, 2, 3];`
Then in the template ``
Comment: @wheelerI just added package.json if you want to take a look at it.
Comment: @Roysh I tried that as well, same effect.
Comment: Compare this project to yours : https://stackblitz.com/edit/angular-xhpehh?file=app%2Fapp.module.ts.
Comment: If you get the error `Can't bind to 'ngforOf'` then you wrote `*ngfor` instead of `*ngFor`
Comment: fixed, looks like webpack was in fault. @amal found a webpack related issue.
Answer: Could you try changing the order of imports on the AppModule so that BrowserModule comes before the RouterModule ?
EDIT/UPDATE (for visibility):
Looks like it is related to this issue.
Comment: This gives no effect.
Comment: Just noted this upon @yurzui's comment. Feels like it is related to this [issue](https://github.com/webpack-contrib/html-loader/issues/67).
Comment: I just added options from this comment https://github.com/webpack-contrib/html-loader/issues/67#issuecomment-277502048 to my html-loader options in my webpack config.
Comment: Nice to know that fixed it!
Comment: Just curious, did you have to change the `html-loader` config as part of the fix as mentioned in the link?


Semantic equivalence of synchronized method and Semaphore(1, true)?

Question: Are the following two method definitions semantically equivalent? Why? Why not?
Version A:
private static synchronized void foo() {
    bar();
}

Version B:
private static Semaphore available = new Semaphore(1, true);
private static void foo() {
    available.acquire();
    try {
        bar();
    }
    finally {
       available.release();
    }
}

Answer: Yes, except

that the first one synchronizes on the class, and that there might be other parts of the code that synchronize on the same class.
that the semaphore could be fair, whereas synchronization is not
that the thread blocked in semaphore.acquire could be interrupted, causing an InterruptedException to be thrown. Your code doesn't compile as is: you must handle this exception somehow, whereas you don't have to using synchronized.
Comment: Also, a semaphore could be released from another thread than the one that acquired it. (see [Semaphore](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Semaphore.html) javadocs)
Answer: I would say no - Java synchronized block is not guaranteed to preserve order, i.e. it is not fair.
new Semaphore(1, true) is fair (true argument).


Magento : Detail page quantity box is not working

Question: Here is my site detail page
http://ametrade.dev.icyberking.com/index.php/jp-3004242.html
The cart item quantity box is not adding more than one item to the cart no matter whatever quantity is added written to the box i have search through google but did't find any working solution to my problem i also found below link for the same problem but i have nothing that i can do wtih this.. please help
Magento quantity field doesn't work
Answer: The problem is that in the HTML layout the input field "qty" is not inside the "add to cart" form. Therefore, the data entered into that field is not even posted (detectable with firebug). You should check the page layout and make sure the field is within the form tags.


How to harmonise sharps or flats key

Question: As I know the pattern to harmonise the key are 1 3 &5 , but how do you harmonise the sharps or flats ? As I tried the 1 3&5 pattern in keyboard and it doesn't sounds good. Thanks
Comment: Could we get you to further elaborate on your question? It is a bit unclear as is.
Answer: Harmonising using 1,3,5 is using the first, third and fifth of a scale to make a triad. Generally, that scale will be a major or minor. So, for example, you could use C,E,G from the C major scale, or E,G,B from the E minor scale. The sharps and flats work in exactly the same way. Take F,A,C, making an F major, and sharpen each, F#,A#,C#, to make F# major. Flats the same. Lets take A major - A,C#,E. To make Ab major, it's Ab,C natural,Eb. We've flattened the A and E, and effectively flattened the C# by taking it down a semitone to C. Any key with # or b in it will use those specific notes as 1,3,5 to make a triad.
In any particular key, you can also use 2,4,6 or 3,5,7 or 4,6,8 or 5,7,9 or 6,8,10 or 7,9,11. All these will make the 3 major, 3 minor and 1 diminished triads for that key.

How to harmonise sharps or flats key


Autocomplete extender not populating

Question: I am trying to utilize the Ajax Auto Complete Extender with a WCF service that is hosted in the web project.  The service is reached and I have verified that results are returned with fiddler, however the text box associated with the auto complete extender is never populated.
The service contract is as follows:
[ScriptService]
[ServiceContract(Namespace = "")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public interface ICertificateService
{
    [System.Web.Services.WebMethod]
    [System.Web.Script.Services.ScriptMethod]
    [WebInvoke(Method = "POST",
        BodyStyle = WebMessageBodyStyle.Wrapped,
        ResponseFormat = WebMessageFormat.Json)]
    List<string> GetCompletionList(string prefixText, int count);
}

The implementation is just returning a populated list of string.
The aspx is as follows:
<asp:TextBox runat="server" ID="aceInstructors"></asp:TextBox>
<ajaxToolkit:AutoCompleteExtender runat="server"
                                  ID="autoCompleteInstructor"
                                  TargetControlID="aceInstructors"
                                  ServiceMethod="GetCompletionList"
                                  ServicePath="../../CertificateService"
                                  MinimumPrefixLength="1"
                                  CompletionInterval="1000"
                                  EnableCaching="true" CompletionSetCount="5">
                        <Animations>
                            <OnShow>  <HideAction Visible="true" /> </OnShow>
                            <OnHide> <HideAction Visible="false" /> </OnHide>
                        </Animations>

The route for the service is configured in Global.asax as follows:
private void RegisterRoutes()
    {
        RouteTable.Routes.Add(new ServiceRoute("CertificateService", new WebServiceHostFactory(), typeof(CertificateService)));
    }

As stated before I can hot the service and I get a response in JSON format when I watch in fiddler.  The following is the Raw response:
HTTP/1.1 200 OK
Server: Cassini/220.127.116.11
Date: Mon, 12 Sep 2011 16:44:16 GMT
X-AspNet-Version: 4.0.30319
Content-Length: 68
Cache-Control: private
Content-Type: application/json; charset=utf-8
Connection: Close

{"GetCompletionListResult":["Alpha","Beta","Gamma","Delta","Omega"]}

Something possibly worth noting is that if I omit the ResponseFormat from the Service contract, the reult is returned in XML Format and the text box is populated with a very long list undefined
Am I missing something basic?
Answer: The problem was addressed here.  The issue that I needed to resolve seemed to revolve around the way JSON is wrapped and returned.  It appears that the ajax tool kit autocomplete extender is expecting the JSON content to be '.d wrapped'.  This was accomplished by following the configuration settings in the provided link.
It should also be noted that there is an Ajax-Enabled WCF project template that adds these web.config settings...knowing that probably would have saved some time.

Autocomplete extender not populating


Firebase image upload with swift

Question: When i run code, completion handler block does not working.When line work mediaFolder.child(userId!).putData(data, metadata: nil) { (metadata, error) in image file upload in storage but code does not running in block. This is my code :
if let data = self.profileImage.image?.jpegData(compressionQuality: 0.5)
{
    mediaFolder.child(userId!).putData(data, metadata: nil) { (metadata, error) in
    if error != nil {
      // errror
    }
    else {
      //enter code here
    }
}

Answer: Please see below code to upload image data to Storage and get the download url
var imgData: NSData = NSData(data: UIImageJPEGRepresentation((self.img_Photo?.image)!, 0.5)!)
self.uploadProfileImageToFirebase(data: imgData)

func uploadProfileImageToFirebase(data:NSData){
    let randomPic = parentVC?.randomString(length: 10)
    let storageRef = Storage.storage().reference().child("Profile_Pics").child("\(userId ?? randomPic).jpg")
    if data != nil {
        storageRef.putData(data as Data, metadata: nil, completion: { (metadata, error) in
            if(error != nil){
                print(error)
                return
            }
            guard let userID = Auth.auth().currentUser?.uid else {
                return
            }
            // Fetch the download URL
            storageRef.downloadURL { url, error in
                if let error = error {
                    // Handle any errors
                    if(error != nil){
                        print(error)
                        return
                    }
                } else {
                    // Get the download URL for 'images/stars.jpg'

                    let urlStr:String = (url?.absoluteString) ?? ""
                    print(urlStr)
                }
            }
        })
    }

Firebase image upload with swift


É possível executar um aplicativo .EXE a partir de um Windows Service?

Question: Este é um trecho do código:
protected override void OnStart(string[] args)
{
    Process.Start(@"C:\path\<file.exe>");
}

protected override void OnStop()
{
}

Eu gostaria de poder executar um programa .exe dentro do onStart(), porém, usando o método de Process.Start() não funciona. Tem outra forma de fazer isto? Caso sim, qual seria?
Comment: Não entendi o que você quer dizer com interno. Você quer que o seu windows service execute/abra outro programa ou que ele interaja com ele?
Answer: Isso não é possível. Serviços do Windows não podem executar aplicativos executáveis ou invocá-los, diferente de aplicativos do Windows como Winforms, Console ou WPF. Seu código vai funcionar em qualquer aplicação que não seja um serviço do Windows.
O Windows tem um mecanismo de segurança com que faz que serviços sejam executados em sessões isoladas do contexto do usuário, portanto, não existe um contexto de onde iniciar o executável.
Executáveis do Windows somente são iniciados em um contexto, seja administrador, sistema ou qualquer usuário. Como um serviço não está em contexto específico, e sim uma sessão isolada, não há onde executar o aplicativo.
Existe uma maneira insegura e não recomendada de executar um executável a partir de um serviço: injetando o executável em um processo já existente. Portanto, isso pode tornar o sistema instável e passará a ser considerado um malware desde então. Mais detalhes nesta resposta do Stack Overflow.
Comment: Uhm, entendi. Obrigado amigo, muito esclarecedor. Vou analisar a resposta que você indicou.
Answer: Tenta isso:
<<AVISO>> Não sei se vai funcionar pois Serviços possuem um mecanismo de isolamento que não permitem invocar janelas. Não sei se isso se aplica a processos sem janelas. Caso funcione de um retorno nos comentários
Instancie a classe Process antes de usar o método Start e use a propriedade StratInfo para configurar a inicialização do processo.
   Process processo;

   protected override void OnStart(string[] args)
   {
        try
        {
            processo = new Process()

            // Não exibe o shell
            processo.StartInfo.UseShellExecute = false;

            // Carrega o caminho do seu arquivo
            processo.StartInfo.FileName = @"C:\path\<file.exe>";

            //Não criar janela de processo
            processo.StartInfo.CreateNoWindow = true;

            // Inicializar o processo
            processo.Start();

        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }
   }

Caso seu processo persista por todo o seu serviço:
   protected override void OnStop()
   {
       processo.Kill();
   }

Comment: Primeiro, obrigado por responder.

Sobre sua resposta, eu já havia tentado desta maneira porém não obtive sucesso.


Access Form Validation from Outside directive

Question: I am beginner in angular.I have form which has validation that enable the save button only on validation pass
<input type="submit" value="Save" ng-disabled="!frmRegister.$valid" />

I have directive which will take care of form submission globally.
app.directive('mysavebtn',function(){
            return {
                restrict : "E",
                scope :{
                },
                controller : function($scope){

                },
                link : function(scope,elem,attr){

                },
                template : '
'
                 +'<input type="submit" ng-disabled="!frmRegister.$valid" value="Directive Save"  />'
           +'
'
            }
        });

But Directive save button always disabled even when form is valid!!!.Note:      I keep save button inside form to know the validation
Please check here in working example
How do i get access Form validation from mysavebtn directive ? Please advice.
Answer: If you are using an isolated scope inside your  directive you can pass the state of the form validity inside that scope using '=' notation (2-way binding). For that purpose you need to modify the HTML of your directive a bit:
<mysavebtn form-valid="frmRegister.$valid"></mysavebtn>

and also JS:
app.directive('mysavebtn', function() {
  return {
    restrict: "E",
    scope: {
      formValid: "="
    },
    controller: function($scope) {

    },
    link: function(scope, elem, attr) {

    },
    template: '
' + '<input type="submit" ng-disabled="!formValid" value="Directive Save"  />' + '
'
  }
});

Now the form validity state is available inside the directive's template through
the formValid variable.
See the working PLNK.
For more information read Angular directive guide.
Answer: One of the recommended ways of inter-directive communication and best practice is to use require to get access to other directive controller (form directive in this case).
I modified your plnkr: http://plnkr.co/edit/rGxmu7M33Ftb52MobzdK?p=preview
app.directive('mysavebtn', function () {
  return {
    restrict: 'E',
    require: '^form',
    scope: {},
    link: function(scope, elem, attrs, formCtrl) {
      scope.formCtrl = formCtrl;
    },
    template: '
' +
      '<input type="submit" ng-disabled="!formCtrl.$valid" value="Directive Save"  />' +
    '
'
  }
});

Place your mysavebtn into form so it has access to it. You now have access to the whole form API and have much more possibilities.
BTW: Creating binding for this is unnecessary (as in the now accepted other answer).


Looking for a couple of injections

Question: This is an extension of my last question I guess.  If I'm not following protocol in that regard I sincerely apologize!
Basically, I'm considering the set of all functions from the positive integers to itself, and the set of all functions from the positive integers to the set {0,1}.  I want to show that they have the same cardinality, but wanting to show it isn't helping me do it!  One injection is simple inclusion, but I can't find the other.  Any tips/hints?
Answer: Explicit injections are overrated. You actually have the knowledge to finish on your own, without writing this injection...
You already know that every function from $\mathbb Z^+$ to itself is a subset of the countable set $\mathbb Z^+\times\mathbb Z^+$. In particular this means that the collection of all functions from the positive integers to itself is a subset of $\mathcal P(\mathbb{Z^+\times Z^+})$.
Now you can use the fact that $\mathbb{|Z^+\times Z^+|=|Z^+|}$ and conclude that the power sets are equipotent, and therefore $\left|2^{\mathbb Z^+}\right|=\left|\mathbb{\left(Z^+\right)^{Z^+}}\right|$, as wanted.
If you still insist on finding this injection, let $\varphi\colon\mathbb{Z^+\times Z^+\to Z^+}$ be a bijection.
Now map $f\colon\mathbb Z^+\to\mathbb Z^+$ to the following function $G_f\colon\mathbb Z^+\to\{0,1\}$: $$G_f(\varphi(a,b))=1\iff (a,b)\in f$$
Show that $G_f$ is an injective function, it's not too hard but requires some element chasing and bookkeeping.
Comment: Hmm, I'm having a bit of trouble filling in the logic that connects the first part of your last sentence to the stuff after the "therefore." (after your edit, it's a middle sentence.)
Comment: @AsinglePANCAKE: The set of all functions is a subset of the power set of a countable set. Therefore its cardinality is less or equal to that of $\mathcal P(\mathbb Z^+)$. On the other hand it is not smaller since, as you pointed out, we have the obvious inclusion. *Therefore* equality ensues.
Comment: Wait, so you're saying that the power set of Z+ and the set of all functions from Z+ to {0,1} are the same thing?
Comment: @AsinglePANCAKE: Yes. The bijection between them is easy to achieve: characteristic functions. $A\mapsto \chi_A$, where $\chi_A(x)=1\iff x\in A$.
Comment: Thanks!  Literally just proved the bijection a few seconds before you answered.
Comment: Also $\mathbb R_{++}$ is object-oriented  $\mathbb R$

Looking for a couple of injections


Problema para enviar dados do PHP para o banco de dados

Question: Estou começando com PHP e estou com problema para enviar para o banco de dados, infelizmente não consigo encontrar o erro, se alguém puder ajudar, grato.
O HTML está assim:
<form method="post" action="blog.php"  >
                    <input style="font-family:'open sans',sans-serif;font-size:20px;color:#212121"type="text" name="titulo" placeholder="Título" required />

                    <input type="text" name="texto" placeholder="Texto"  required />

                    <input style="background-color:red;color:white" type="submit" name="submit" value="enviar" />
                </form>

E o PHP assim:
<?php
$titulo = $_POST ['titulo'];
$texto = $_POST ['texto'];
$imagem = "imagem";
echo "$titulo";

$conexao = mysqli_connect("localhost", "root", "", "blog");

mysqli_query($conexao, "INSERT INTO postagens (titulo,texto,imagem) VALUES ('$titulo','$texto,'$imagem')");

echo "Sucesso";
?>

O nome do banco é 'Blog' e da tabela 'postagens'.
Comment: Quais os textos que aparecem na tela? Dá alguma mensagem de erro?
Answer: <?php
// verificação do metodo post
if ( $_SERVER['REQUEST_METHOD'] == "POST" )
{
    // obtendo os dados do form
        $titulo = $_POST['titulo'];
        $texto  = $_POST['texto'];
        $imagem = "imagem";
        echo "Título: ".$titulo."
";

    // realizando a conexão
        $conexao = mysqli_connect("localhost", "root", "", "blog");
        $query   = mysqli_query($conexao, "INSERT INTO postagens(titulo,texto,imagem) VALUES ('$titulo','$texto','$imagem')");

    // se executar a query
        if ($query)
        {
            echo "Sucesso";

        }else
        {
            echo "[ERRO]: ".mysqli_connect_error($conexao);
        }
}
?>

Veja se isto resolve o teu problema.
Comment: Cara, resolveu sim, valeu mesmo!
Comment: @Alisson fico feliz que tenha resolvido seu problema, marque a resposta como correta para ajudar próximos usuários com o mesmo.
Answer: Está faltando uma aspas simples depois de $texto na query, tente colocar pra ver se funciona
mysqli_query($conexao, "INSERT INTO postagens (titulo,texto,imagem) VALUES ('$titulo','$texto','$imagem')");

Answer: <?php
$titulo = $_POST ['titulo'];
$texto = $_POST ['texto'];

$conexao = mysqli_connect("localhost", "root", "", "blog");

echo "Sucesso";

mysqli_query($conexao, "INSERT INTO postagens (titulo,texto) VALUES ("{$titulo}","{$texto}"));

Tente essa query, ela deve funcionar, mas tire a imagem inicialmente, porque pra fazer o upload da imagem você precisará fazer alterações tanto no seu HTML quanto no PHP.
Comment: E por quê acha que assim funcionará? O PHP consegue interpretar as variáveis dentro de uma *string* definida por aspas duplas; as chaves são necessárias apenas com expressões. Aliás, você quebrou a sua *string* ao utilizar aspas duplas dentro da mesma, o que geraria erro de sintaxe. E o campo de imagem está com um valor constante, então não vejo, por enquanto, alguma relação com o problema.
Comment: Na verdade eu não acho que vai funcionar. Sempre faço assim e funciona.


How to get customer's uploaded file through gravity forms.

Question: I need to get the attachment files from upload file feature provided in Gravity forms.
E.g. I have asked the user to send the scanned copy of their resume using Gravityforms upload feature. It's working fine but I need to know where gravity forms is storing the files? (Pathinfo).
Answer: It's the physical files are the wp-content folder under uploads. You can also change the default path using the gform_upload_path function. https://docs.gravityforms.com/gform_upload_path/
However you can get the exact link from the entry management / entry details page.


How can I make a bar chart? Swift

Question: in my App I'm using CoreData to save and summarize Integers. Now I want to present these Integers in a simple but handsome looking bar chart. It has to show the highest count per the day it was saved into the entity.
Do someone have a simple example of Code I can use? Thank's in advance
Answer: What I have mostly been using is Charts (https://github.com/danielgindi/Charts).It is free for use under Apache-2.0 License and offers great customizability. You can view their source code for something more specific and also there are great project examples there.
Answer: As @KristijanK said Charts is one of the popular frameworks you can link and use. If you're unsure where to start, follow the demos provided in the repo as a scaffolding and go from there. Observe how a chart gets instantiated and the data set is being fed.
For example, if you want to use a pie chart to show the proportion of the highest count per day among the entities, import Charts first, instantiate the chart @IBOutlet var chartView: PieChartView!, and input your data let set = PieChartDataSet(entries: entries, label: "Entry Count").
One notable thing to pay attention to are the formatters.  You will most likely want to customize the units of the x-axis or the y-axis depending on what type of charts and graphs you use according to the type of your data set.  For example, a chart showing data per 1000 km is going to be different from data per 1 litre. Use the formatter classes to create a custom method to convert the unit to whatever you want.
Answer: You can use this file for simple drawing no need to import extra library such as Charts. Try and play with below code you will learn new things. Happy coding.
extension CGFloat {
    func radians() -> CGFloat {
        let b = CGFloat(M_PI) * (self/180)
        return b
    }
}

extension UIBezierPath {
    convenience init(circleSegmentCenter center:CGPoint, radius:CGFloat, startAngle:CGFloat, endAngle:CGFloat)
    {
        self.init()
        self.moveToPoint(CGPointMake(center.x, center.y))
        self.addArcWithCenter(center, radius:radius, startAngle:startAngle.radians(), endAngle: endAngle.radians(), clockwise:true)
        self.closePath()
    }
}

func pieChart(pieces:[(UIBezierPath, UIColor)], viewRect:CGRect) -> UIView {
    var layers = [CAShapeLayer]()
    for p in pieces {
        let layer = CAShapeLayer()
        layer.path = p.0.CGPath
        layer.fillColor = p.1.CGColor
        layer.strokeColor = UIColor.whiteColor().CGColor
        layers.append(layer)
    }
    let view = UIView(frame: viewRect)
    for l in layers {

        view.layer.addSublayer(l)

    }
    return view
}

let rectSize = CGRectMake(0,0,400,400)
let centrePointOfChart = CGPointMake(CGRectGetMidX(rectSize),CGRectGetMidY(rectSize))
let radius:CGFloat = 100
let piePieces = [(UIBezierPath(circleSegmentCenter: centrePointOfChart, radius: radius, startAngle: 250, endAngle: 360),UIColor.brownColor()), (UIBezierPath(circleSegmentCenter: centrePointOfChart, radius: radius, startAngle: 0, endAngle: 200),UIColor.orangeColor()), (UIBezierPath(circleSegmentCenter: centrePointOfChart, radius: radius, startAngle: 200, endAngle: 250),UIColor.lightGrayColor())]
pieChart(piePieces, viewRect: CGRectMake(0,0,400,400))

How can I make a bar chart? Swift


Ambassador load-balancer is empty

Question: I am new to Ambassador and trying to debug some installation issues.
I am following these instructions https://www.getambassador.io/docs/edge-stack/latest/tutorials/getting-started/ and getting stuck at step 3
My load balancer does not seem to connect properly $LB_ENDPOINT is empty
<code>"status": {
        "loadBalancer": {}
    }
</code>
One big problem is that I do not know how to access the logs. All of my pods seem to be operating as expected(?)
Configuration:
I am using a bare metal installation of Kubernetes with 4 nodes.
Kubernetes v1.23.1
Cilium v1.11.0
Comment: you might want to show your config together with the question so people can more easily help you without blindly guessing.
Comment: @vautee I have added details. Is this what you are looking for?
Answer: Since I am using a bare metal installation, these instructions fixed it for me
https://www.getambassador.io/docs/edge-stack/latest/topics/install/bare-metal/

Ambassador load-balancer is empty


Session timeout when using signalr

Question: I have a web app that is used mainly for monitoring a system. It uses signalr to "server-push" updates from the server to refresh the display. The page also has some buttons which also uses the same signalr connection to send data to the server.
The problem is signalr uses a separate connection so the session expires after the session timeout even when it is regularly sending and receiving data from the server.
Is this the "correct" way to use signalr? Or should I just use signalr to inform the client of updates and have the client do an ajax post to retrieve the data?
What about the session timeout issue? Do I have to create a client-side timer to regularly make a "keep-alive" ajax post?
Answer: You should be able to workaround the session timeout issue by sending a request every 5 minutes (anything lower than your cookie timeout), to your webserver (just any random page). We're actually going to implement something to improve this in of SignalR 2.0.
Comment: does this problem solved in latest release? I don't want to do requests, because I've set timeout of forms authentication and just want to update state when user are really working on application.
Comment: @davidfowl I have the same issue although I've upgraded to SignalR 2.2.0, do you have any idea to resolve such a problem?
Comment: Was this resolved? Still looking for using sessions timeout and signalr
Comment: @dfowler Any update on this. I have the same question as the above comment.

Session timeout when using signalr


Display textfield as clickable link

Question: I am trying to make textfields clickable so it would appear as link. What would be the best solution for this? I tried Link module, but it is not what I am looking for. This is how I got my textfield written:
<code>$form['element4']['link4'] = array(
        '#type' => 'textfield',
        '#title' => t('link for 4th div'),
        '#description' => t('your link'),
    );
</code>
I need for it to stay textfield as user can input his value, but I want it to be displayed lets say in blue color and so that you could click on it. How could I do this in the most simple way?
Comment: Do you want to make field label as clickable and field value as textfield?
Answer: What you need is the #ajax property of the Form API. Have a look at this page to find the answer to your question:
https://www.drupal.org/node/1256510

Display textfield as clickable link


Symmetry behind Taylor expansion

Question: We consider the function $f:\mathbb R^2 \to \mathbb C.$
$$f(x,y) = 2i \sum_{k=0}^2 \zeta^k \sin\left( \frac{x\bar \zeta^k-y\zeta^k}{2i} \right)$$
where $\zeta= e^{2\pi i/3}$ is the third root of unity
I computed using Mathematica the Taylor expansion at $x=y=0$ up to order $8$
$f(x,y) = \left(-\frac{y^5}{640}\right)+x
\left(3+\frac{y^6}{15360}\right)+x^2 \left(-\frac{3
y}{8}-\frac{y^7}{860160}\right)+x^3
\left(\frac{y^2}{64}+\frac{y^8}{82575360}\right)+x^4
\left(-\frac{y^3}{3072}\right)+x^5
\left(\frac{y^4}{245760}\right)+x^6
\left(-\frac{y^5}{29491200}\right)+x^7
\left(\frac{1}{107520}+\frac{y^6}{4954521600}\right)+x^8
\left(-\frac{y}{3440640}-\frac{y^7}{1109812838400}\right)+O\left(x^9+y^9
\right).$$
Then since the function is anti-symmetric by switching both $x,y$, we only get products of odd order in $x^iy^j$, i.e. $i+j$ is odd.
However, there is another feature that is more subtle for me to explain. For a given power in $x$ we have some $y^i$ and then a term $y^{i+6}$ appearing. Why do we have these jumps of order $6$ in the expansion?
Please let me know if you have any questions.
Comment: Why the edit link?
Comment: The function is just the sum indexed from $0$ to $2$? If so, I would just expand the few pieces to its exponential form.
Comment: @DecarbonatedOdes indeed, but if I would write it as exponentials, I am not sure how to see this $y^6$ thing this way any better...
Comment: The coefficient of $x^a y^b$ in the multivariable Taylor expansion is a factorial term times the $a$-th derivative with respect to $x$ of the $b$-th derivative with respect to $y$ of $f(x,y)$. So the real question is why are all but every sixth derivative zero at $(x,y) = (0,0)$?
Answer: Overview. Your problem is connected to the general problem of constructing analytic functions that possess prescribed symmetries. One trick for creating such functions is to average "any" analytic function over the action of all elements of the  desired symmetry group.  This trick compels the Taylor coefficients  of the symmetrized function to have some special symmetrical patterns.
Details. The crux of the matter is that the derived function $\partial f/\partial x$ is loosely speaking a symmetrization of $h(x,y)=\cos(\frac{x-y}{2i})$ under the action of a finite group generated by powers of $\zeta$.
More precisely you can verify the identity
(1) $f_x= g(x,y)=\sum_{k=0}^2 h( \zeta^{-k} x, \zeta^k y)$
Consider the  implications of the symmetry
(2) $h(-x,-y)=h(x,y)$
on the Taylor expansion
(3) $h(x,y)= \sum_{m,n\geq 0} c_{m,n} x^m y^n$
Deduce that $c_{m,n} =(-1)^{n+m} c_{m,n}$.
That is
(4)  $c_{m,n}=0$ unless $n$ and $m$ have the same parity (either both even, or both odd).
Substitute  (3) into (1) to deduce that
$g(x,y)= \sum_{k=0}^2 h(  \zeta^{-k} x, \zeta^k y)$ satisfies
(5) $g(x,y)= \sum_{m,n\geq 0}  c_{m,n}  x^m y^m (\sum_{k=0}^2 \zeta^{k(n-m)})$.
The rightmost sum is a three-term geometric series consisting of three consecutive powers of  $\zeta^{n-m}$.
That geometric series vanishes unless $n-m \equiv 0 $(mod 3).
Thus the non-vanishing terms in the Taylor expansion of $g(x,y)$ consist only  of those terms for which
(6) $n \equiv m$ (mod 3).
But as noted in (4),  the additional requirement that $n$ and $m$ must have the same parity  forces the condition that $c_{m,n}=0$ unless $n\equiv m $(mod 6).
Finally, this pattern satisfied by $f_x$ naturally leads to the pattern that you noted about $f$ itself. (Just integrate the series for $f_x$ term-wise to obtain $f$.)

Symmetry behind Taylor expansion


Find probability and expectation

Question: 18 boys and 2 girls are made to stand in a line in a random order.Let $X$ be the number of boys standing in between the girls .Find $P[X=5]$ and $E[X]$. I proceed in this way:
Note that $$P[X=0]=\frac{19.18!.2!}{20!}=\frac{19-0}{20\choose2}$$
$$P[X=1]=\frac{18.18!.2!}{20!}=\frac{19-1}{20\choose2}$$$$P[X=2]=\frac{17.18!.2!}{20!}=\frac{19-2}{20\choose2}$$So, $$P[X=x]=\frac{19-x}{20\choose2}$$,$x=0(1)18.$
so.$$P[X=5]=\frac{19-5}{20\choose2}=0.0737$$ and $$E[X]=\sum_{x=0}^{18}x.\frac{19-x}{20\choose2}=6$$
Comment: **Crosspost**: http://math.stackexchange.com/q/178084/7003
Answer: You're right.
There's a clever way of obtaining the expectation: add a third girl and arrange all $21$ people into a circle, then randomly break the circle at one of the girls to form a line.  This produces an identical distribution for $X$. But now there is an evident circular symmetry, which shows immediately that the expected number of boys between each of the three pairs of two adjacent girls (including the pair remaining in the line) is the same.  Because there are $18$ boys, that expectation must be $18/3 = 6$.
Edit
This argument can also be applied to find probabilities: the chance that $X\ge x$ must, by the same symmetry, be the chance that the first $x$ people in line are boys. Equivalently, the girls must be in the remaining $20-x$ positions, which can occur in $\binom{20-x}{2}$ distinct equiprobable ways out of all the $\binom{20}{2}$ possible pairs of positions.  Whence we find
$$\Pr[X=x] = \Pr[X\ge x] - \Pr[X\ge x+1] = \frac{\binom{20-x}{2}-\binom{20-(x+1)}{2}}{\binom{20}{2}} = \frac{19-x}{\binom{20}{2}}$$
for $x=0, 1, \ldots, 19$.  When $x=5$, this value is $14/190 \approx 0.0736842$.

Find probability and expectation


Alea GPU Memory Allocation Limit

Question: I am using Alea GPU with a GTX-1081ti, which has 11GB of global memory.
When I use the Alea Gpu.Default.Allocate method to allocate memory on the GPU, when I get up near 3+ GB I get an "out of memory" error.
My code is:
private static int Length = 2147000000;
...
var gpu = Gpu.Default;
gpu.Allocate<int>(Length);

This should allocate about 8GB of GPU RAM, but it gives a CUDA out of memory exception. I've tried lower Length values, and based on the report from Task Manager the GPU Dedicated Memory only goes up to around 3 GB before it gets the error.
However, when I do the same with raw CUDA code (outside of Alea), my limit is a bit over 80% of 11 GB, or almost 9 GB (since W10 limits the allocation).
Does anyone know why I'm getting an "out of memory" error at only 3 GB?
Thanks.
Comment: Wow, thanks much. I feel so stupid. It was x86. Now it works fine.
Comment: Suggestion: specify 1) Current Windows OS bit mode (x86 or x64), 2) How you're compiling the projects: AnyCPU, X86 only, x64 only.
Answer: (Putting into an answer since it seems to have solved your issue)
It sounds like you may be compiling in 32 bit mode.  Make sure you are are using a 64-bit OS and compiling in 64-bit mode. You wouldn't be the first to accidentally compile in 32-bit mode :)

Alea GPU Memory Allocation Limit


How to implement some super admin feature to facilitate password retrieval for existing users?

Question: I'm aware that Drupal 7 saves the user's password in a more compact way and it's really hard (impossible?) to convert such password back to a human readable text format (even not into database).
Actually I do not want to implement any hack to Drupal, but it's a requirement that a super admin can somehow view the username along with its password for any user. Super admin is a trust worthy role and actually will help through secured communication media to other users after forgetting their password.
So there is a need to create a block to show all the usernames with their corresponding password, which can only be used by a super admin.
Any suggestions about how I could implement all this?
Note:  Users are not allowed to reset passwords, I just want only super admin can access their usernames and passwords and then re-assign to other user if any of them forgot his password.
Comment: MD5 is used by Drupal 6 and earlier. Drupal 8 and Drupal 7 use SHA512 with a salt.
Answer: You can't. Drupal passwords are hashed, not encrypted, the key difference being hashes are one-way.
With Drupal 6's non-salted MD5 hashes, a rainbow table might get you there, but with D7's salted SHA512 hashes would be much tougher. The time spent trying to do this would be better spent trying to find an alternative to your need of listing all user/pass.
Answer: You can't.
Passwords are saved encrypted so that they can't be easily recovered in their clear format.
Beyond that you could use the password reset mechanism and reset the passwords. That's the closest that you will get to what you want.
Comment: how to use this mechanism, can you elaborate this?
Comment: You can do this via drush. Check http://www.drushcommands.com/drush-7x/user/user-password
Comment: Also check from the api documentation the password related fonctions :  https://api.drupal.org/api/drupal/modules%21user%21user.module/7
Comment: thats for password reset but i dont want to reset. I just want to show in plain text.
Comment: As I said in my answer, you can't. The closest you'll get is resetting them.