Parameterization of Negative Binomial for Dynamical System Model Calibration/Fitting

Question: I'm studying about the applications of bayesian inference to fitting dynamical systems to observations.
So the model itself is a deterministic SIR model:
$$
f(R_0,D_{inf})=\begin{cases}
 \frac{dS}{t}&=-\beta S\frac{I}{N}
 \\
 \frac{dI}{t}&=\beta S\frac{I}{N}-\nu I
 \\
 \frac{dR}{t}&=\nu I
 \\
\end{cases}\tag{1}
$$
where $\beta=R_0/D_{inf}$, $\nu=1/D_{inf}$. The parameters we will calibrate/estimate will be $R_0$ and $D_{inf}$.
So the concept is finding the $R_0$ and $D_{inf}$ makes the model outputs, specifically the $I_t$ best fit the data, say $d_t$ and the uncertainty in the fit is captured by some probability distribution, i.e, Poisson:
$$d_t\sim Poisson(I_t)\tag{2}$$
meaning the actual observed time series $d_t$ follows some probability distribution around $I_t$.

Problem
In the case of $Poisson$ distribution, it is relatively easy to construct the likelihood for $R_0$ and $D_{inf}$ since all you have to do is to find $R_0$ and $D_{inf}$ that maximizes the likelihood generated from $(1)$ and $(2)$:
\begin{align*}
L(R_0,D_{inf}|d_1,d_2,\dots,d_n)
&=
\prod_{t=1}^nL(I_t|d_t)
\\
&=
\prod_{t=1}^n\frac{\exp(-I_t)I_t^{d_t}}{d_t!}
\end{align*}
then one could just use the following function for getting the likelihood
dpois(
   x = d_t,
   lambda = I_t
)

But how is this done for negative binomial? Generating likelihood we would have
\begin{align*}
L(R_0,D_{inf}|d_1,d_2,\dots,d_n)
&=\prod_{t=1}^n\frac{\Gamma (d_t+r_t)}{d_t!\Gamma (r_t)}p^{r_t}(1-p)^{d_t}
\end{align*}
where $I_t=\frac{r_t(1-p)}{p}$ would be the mean of the Negative binomial distribution.
how could I use dnbinom() for in this method of parameterization?
dnbinom(
 x=d_t,
 mu = I_t,
 size = ???
)

I'm slightly confused by the documentation and would like help on what should size be.
Please comment as well if this belongs to R Collective (StackOverflow) rather than CrossValidate rather than a straight downvote.
Answer: Checking ?dnbinom, the equivalent parameterisation is: your $d$ is R's x, your $p$ is R's prob, your $r$ is R's size, and your $I$ is R's mu.
mu is the mean, $I_t$ in your case. Then prob = size/(size+mu) (see docs). So
$$
\texttt{size} = r/(r + I_t)
$$
according to your parameterisation.
Comment: so $r$ would be constant throughout the likelihood?
Comment: I was lazy in my notation. What I meant was, where you see and $r_t$, that should be input into to `size` argument of `dnbinom`
Comment: But then $f(R_0,D_{inf})$ only gives us  $I_t$.  Does that mean $\left\{r_1,r_2,\dots,r_n\right\}$ would be another vector needed in the likelihood?
Comment: Tbh, I have no idea what deterministic SIR models etc. are. But I do know how to parameterise `dnbinom`. You might be able to have the $r_t$ as nuisance variables or something in the likelihood but I can't remember how to do that off the top of my head


What does Harm. mean in guitar tabs

Question: In the Nothing Else Matters tab by Metallica on songsterr.com, I came across some notation that I haven't seen before:

What does "Harm." mean in the picture above?
Answer: Harm. Just means to play the harmonics at that fret. The diamond is also the same instruction of playing harmonics at the 12th fret.
The 12th fret has very strong harmonics that are the same note as the string played on, just at higher octaves.  Harmonics in general also have a very distinct tone from just playing the 12th fret.
The strength of the harmonic on the 12th fret is due to how the harmonic series works and the 12th fret aligning with the second harmonic node. I'd recommending looking into the harmonic series if you are interested in this concept as there's a lot going on there.

What does Harm. mean in guitar tabs


Why does Batch Normalization need moving averages besides to track model accuracy?

Question: I was reading the new layer normalization (LN) paper and it mentioned that batch normalization (BN) batch normalization required moving averages. I was re-reading the paper but and it says the moving averages are needed to estimate the accuracy of the model as it trains (by accuracy I take it to mean train, validation, test errors/accuracy). I take the reason for this is so to save time since it probably estimates accuracies of mini batches and just averages it as it goes until the end.
However, the LA paper seems to imply (in the introduction) that activation accuracies are used in BN for some other reason. Why would BN require to store activation statistics at the end of training?
Comment: does [this answer](http://stats.stackexchange.com/a/219907/95569) help (the update part)?
Comment: @dontloo oh, I see that you updated that answer. I guess I missed that. However, I think I need some more details to understand that point, I still feel I don't appreciate why thats important.
Answer: During evaluation, you may just have a single example, i.e. there is no batch to normalize over. In this case, you can use the average activations from training to do the normalization. The moving averages are because we may want to do some evaluation on held-out data while we are still training in order to detect convergence/over-fitting.
Comment: but we can also "do some evaluation on held-out data while we are still training" by dividing by the number of iterations.for example: after 5 iterations we will divide by 5 and after 10 we'll divide by 10 ....etc. am i right?


What is an example of a loss function that is not minimized by the conditional expectation?

Question: From statistical decision theory we know that if we want to minimize EPE (Expected prediction error) it is sufficient to minimize the conditional expectation of the loss function.
$f(x) = argmin_{c} E_{Y \vert X}(L(Y, c) \vert X = x)$
For square loss $L(Y,c) = (Y-c)^2$ the solution is the conditional expectation $c=E(Y \vert X=x)$.
What is an example of a loss function that is not minimized by the conditional expectation? What is it minimized by? It would be great if the example were a loss function that is actually used to some extent and not totally contrived, but everything is welcome.
I think the property of a loss function being minimized by the conditional expectation is known as being p-admissible.
Answer: If the loss function was for example $L(Y,c)=|Y-c|$
then the conditional median would minimise it
i.e. $c$ such that $\mathbb P(Y \le c\mid X=x) \ge \frac12$ and $\mathbb P(Y \ge c\mid X=x) \ge \frac12$
Comment: Extending this, we could use any of the (other) quantile regression loss functions so that the conditional mean does not optimize the loss, even when the error term is symmetric.


Não listar dados duplicados

Question: Tenho duas tabelas, videos e exercicios, onde eu gostaria que não fossem listados os dados que estão nas duas, ou seja, se a chave estrangeira está na outra tabela, o dado não deve ser mostrado na consulta para evitar de ser inserido novamente.
As tabelas:
videos(
  id_video,
  titulo_video,
  src_video,
  descricao_exercicio,
  id_professor_video,
  id_categoria_video,
  data_upload
)

exercicios(
  id_exercicio,
  id_treino_exercicio,
  id_aluno_exercicio,
  dia_exercicio
)

Tentei fazer como a query abaixo mas não deu certo, ele continua mostrando os videos que já foram cadastrados:
SELECT
  exercicios.*,
  videos.*
FROM (
  exercicios INNER JOIN videos
    ON exercicios.id_treino_exercicio = videos.id_video
)
WHERE
  id_professor_video = 1
  AND id_categoria_video = 1
  AND dia_exercicio != 1

Comment: Dê uma olhada em outer join, resolve seu problema?
Comment: ou
Comment: Sem saber a estrutura das suas tabelas, os dados que estão nela e um exemplo de resultado desejado com base nesses dados é impossível te ajudar.
Answer: esse código funcionou do jeito que eu queria, acho que o join n estava dando certo pois n tinha nenhum campo null, mesmo assim obrigado a todos pela atenção.
SELECT * FROM videos v WHERE v.id_video NOT IN (SELECT id_treino_exercicio FROM exercicios) AND id_professor_video = 1 AND id_categoria_video = 1

Não listar dados duplicados


Android List View remove all items

Question: How can I remove all items in my ListView? I have custom adapter and I run this code to remove all the items, but it's not working:
friendList = new ArrayList<FriendRow>();
//Later i call this to remove all the items.
friendList.clear();
adapter.notifyDataSetChanged();

Comment: Try `myListView.setAdapter(null)`
Comment: Actually, this solved my problem, thank you!
Answer: You can do myListView.setAdapter(null).
Answer: Changes to the UI need to be done on the UIThread. Calling notifyDataSetChanged() won't work unless it's called on the UIThread. You could try adding something like:
public void clearAdapter()
{
    runOnUiThread(new Runnable()
    {
      public void run()
      {
        friendList.clear();
        adapter.notifyDataSetChanged();
      }
    };
}

and then calling clearAdapter() when you want to clear it.

Android List View remove all items


Number of samples required to estimate a desired False Positive Rate

Question: I have an algorithm that for each sample $x_i$ returns an anomaly score $0<s_i<1$.
I use cross validation to set a threshold $th$ such that $x_i$ is anomalous if $s_i>th$.
During cross validation the threshold is set in order to have the desired False Positive Rate (FPR).
How many sample do I need to make sure that the threshold I have estimated will return exactly the desired FPR on new data?
For example if I have 10 samples in class 0 an 10 samples in class 1 I will not be able to estimate a FPR of $1\%$  as I would need at least 100 samples in class 0.
Is there a rule or a formula to know how many samples in class 0 do I need to reasonable estimate the threshold of a desired FPR?
Comment: Honestly, it depends on the domain and context. For instance, the different sample size depends on the underlying statistical test between other conditions.
Answer: Is this question simply a re-framing of a power analysis question? Seems like you would answer this by calculating a sample size for a desired alpha, which in itself is an a priori "threshold" acceptable to a given researcher (typically 0.05 in social science).
Comment: Power analysis allows "to determine the sample size required to detect an effect of a given size with a given degree of confidence" (Clay Ford). If you use R, package pwr may be of help. More information on what power analysis is, how can it help you, and how to perform it in R is here: https://cran.r-project.org/web/packages/pwr/vignettes/pwr-vignette.html
Comment: sorry I do not understand.  Can you provide more details?
Answer: In theory [1], the number you need to approach the level of significance for you problem. Nevertheless, consider to include both significance and power levels. Also, consider the potential impact of your FPR results as it may directly change your appropriate level of significance.

The level of significance (referred to as α) defines the strength of identifying an effect when no effect exists, in other words having a false-positive result. A type I error (false-positive) occurs when we wrongly conclude there is a difference, i.e. with an α of 0.05 there is a 5% risk of a false-positive result. The lower the level of α the less likely it is that a type I error will occur. When determining the appropriate level of significance it will be necessary to consider the potential impact of a false-positive result; if the potential impact is serious then a lower level of significance, for example, α = 0.01 (1% risk), might be selected.

[1] Burmeister, E. and Aitken, L.M., 2012. Sample size: How many is enough?. Australian Critical Care, 25(4), pp.271-274.


NameError when inputting string instead of int

Question: I am trying to build a simple program that runs the Collatz Sequence on a number inputted by the user. I am also using this to try and get the hang of using 'try except' statements in Python by throwing a print statement whenever the user inputs a string rather than an integer.
The program works as expected when entering a integer, for example here I input the number 12 and I get the following output:
<code>$ python collatzSequence.py
Enter in a number:
12
6
3
10
5
16
8
4
2
1
</code>
However, when you input a string I get this error:
<code>python collatzSequence.py
Enter in a number:
ddd
Traceback (most recent call last):
  File "collatzSequence.py", line 34, in <module>
    main()
  File "collatzSequence.py", line 25, in main
    numb = input()
  File "<string>", line 1, in <module>
NameError: name 'ddd' is not defined
</code>
When what I want to be able to do is catch when the user enters something that is not an integer and print 'Please enter an integer.'
The following is my code that I have written, I have placed the 'try except' statement inside the collatz() function, I had also tried putting it in the main() function but I got the same result. :
<code># Exploring the 'Collatz Sequence'.

# If number is even, print number // 2 and returns this value.
# If number is odd, print and return 3 * number + 1.
def collatz( number ) :
  # Error handling to make sure number entered is an int.
  try:
    number = int(number)
  except NameError :
    print( 'Please enter an integer.')
    return

  # number is even.
  if number % 2 == 0 :
    print( str(number // 2) )
    return number // 2
  # number is odd.
  else :
    print( str(3 * number + 1) )
    return 3 * number + 1

# Lets user type in an integer and keeps calling collatz() on that number until the funciton returns the value 1.
def main() :
  print( "Enter in a number: " )
  numb = input()

  numb = collatz(numb)
  while numb != 1 :
    numb = collatz(numb)

  if __name__ == "__main__":
    main()
</code>
Thanks for any help anyone can give me with working out what I can do to fix this issue.
Comment: You must put the `try/except` bracket around the line `numb = input()`. It's this line that raises the exception.
Comment: Ah thank you DyZ, that fixed it.
Comment: You should use `raw_input` instead of `input` in Python 2
Comment: Oh ok thanks juanpa, why is that?
Comment: `input` is evaluating whatever the user enters which is dangerous. `raw_input` just gives you whatever they typed with the newline characters already stripped out.
Comment: ah ok, thanks Ryan and Juanpa. I'll make sure to do that instead in the future.
Answer: Thanks to DyZ for the solution to this.
The problem was that I had the 'try except' statement in the wrong spot. I needed to have the 'numb = input()' line in the try statement in the main() function as that is the line that raises the NameError.
I also added a while statement so it would continue to ask for an integer if the user keeps inputting a string. This loop breaks once an int is entered.
The following is the fixed code :
<code># Exploring the 'Collatz Sequence'.

# If number is even, print number // 2 and returns this value.
# If number is odd, print and return 3 * number + 1.
def collatz( number ) :
  number = int(number)

  # number is even.
  if number % 2 == 0 :
    print( str(number // 2) )
    return number // 2
  # number is odd.
  else :
    print( str(3 * number + 1) )
    return 3 * number + 1

# Lets user type in an integer and keeps calling collatz() on that number until the funciton returns the value 1.
def main() :
  print( "Enter in a number: " )

  # Error handling to make sure number entered is an int.
  while True :
    try:
      numb = input()
      break
    except NameError :
      print( 'Please enter an integer.' )

  numb = collatz(numb)
  while numb != 1 :
    numb = collatz(numb)

if __name__ == "__main__":
  main()
</code>
Giving the result:
<code>$ python collatzSequence.py
Enter in a number:
ddd
Please enter an integer.
22
11
34
17
52
26
13
40
20
10
5
16
8
4
2
1
</code>
Thanks again DyZ!


Are the following properties of summation?

Question: In our "textbook" it asks if the following are properties of summations:

$\displaystyle \sum_{n=j}^{k} (c \cdot a_{n}) = c \cdot \displaystyle \sum_{n=j}^{k} (a_{n})$

$\displaystyle \sum_{n=j}^{k} (a_{n} \pm b_{n}) = (\displaystyle \sum_{n=j}^{k} a_{n}) \pm (\displaystyle \sum_{n=j}^{k} b_{n})$

$\displaystyle \sum_{n=j}^{k} (a_{n} \cdot b_{n}) = (\sum_{n=j}^{k} a_{n}) \cdot (\sum_{n=j}^{k} b_{n})$

$\displaystyle \sum_{n=j}^{k} \frac{a_{n}}{b_{n}} = \frac{\displaystyle \sum_{n=j}^{k} a_{n}}{\displaystyle \sum_{n=j}^{k} b_{n}}$

$\displaystyle \sum_{n=0}^{k} a_{n} = \displaystyle \sum_{n=1}^{k+1} a_{n-1}$

$\displaystyle \sum_{n=0}^{k} c = ck$

$\displaystyle \sum_{n=1}^{k} c = ck$

I know that 1 & 2 are true:

$\displaystyle \sum_{n=j}^{k} (c \cdot a_{n}) = c \cdot \displaystyle \sum_{n=j}^{k} (a_{n})$

$\displaystyle \sum_{n=j}^{k} (a_{n} \pm b_{n}) = (\displaystyle \sum_{n=j}^{k} a_{n}) \pm (\displaystyle \sum_{n=j}^{k} b_{n})$

I also know that 3 & 4 are not true:

$\displaystyle \sum_{n=j}^{k} (a_{n} \cdot b_{n}) \ne (\sum_{n=j}^{k} a_{n}) \cdot (\sum_{n=j}^{k} b_{n})$

$\displaystyle \sum_{n=j}^{k} \frac{a_{n}}{b_{n}} \ne \frac{\displaystyle \sum_{n=j}^{k} a_{n}}{\displaystyle \sum_{n=j}^{k} b_{n}}$

I'm not sure if 5 & 6 & 7 are true, though. Are they true, and why or why not?
Comment: Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer.
Comment: Hint: choose a small value like $k=4$ and write out both sides of the (potential) identities. Are they equal without further assumptions? Does this help you understand the general case where $k$ can be arbitrarily large?
Comment: 6 and 7 cannot both be true unless $c=0$
Answer: $(5)$ is true, and it's easy to see why: just list out the terms individually.
$$\begin{align*}
\sum_{n=0}^k a_n &= a_0 + a_1 + a_2 + \cdots + a_k \\
\sum_{n=1}^{k+1} a_{n-1} &= a_{1-1} + a_{2-1} + a_{3-1} + \cdots + a_{k+1-1} \\
&= a_0 + a_1 + a_2 + \cdots a_k
\end{align*}$$
If you're not convinced, try a particular small value of $k$ you can easily handle, like $k=5$.

$(6)$ is not true in full generality, but $(7)$ is. The true identity is
$$\sum_{n=1}^k c = ck$$
(Notice we start at $n=1$, not $n=0$.) This is like the other summations, but the term is constant and does not depend on $n$. Hence, you're sort of plugging in a different $n$ each time into $a_n$, but always just getting $c$ out. Then
$$\sum_{n=1}^k c = \underbrace{c+c+c+\cdots+c}_{\text{$k$ times}} = kc$$
Of course, then
$$\sum_{n=0}^k c = (k+1)c \ne kc$$
(unless $c=0$). In general, a summation $\sum_{n=j}^k a_n$ will have $k-j+1$ terms.


How can I import only one icon from fontawesome?

Question: I'm searching keyboard-arrow-down icon for my Expansion Panel from vuetify
I have installed
"devDependencies": {
    "@fortawesome/fontawesome-free": "^5.5.0",
}

fontawesome-free, but I think it installed all icons and fonts
So Is there are way to import only one icon (keyboard-arrow-down)?
I've searched my node-modules, but I couldn't find it.
Here's my code.
import Vuetify from 'vuetify'
import '@fortawesome/fontawesome-free/css/all.css'

Vue.use(Vuetify, {
  iconfont: 'fa'
 })

Answer: Install the dependencies:
npm i --save @fortawesome/fontawesome-svg-core \
npm i --save @fortawesome/free-solid-svg-icons \
npm i --save @fortawesome/vue-fontawesome

Import individual icons:
import { library } from '@fortawesome/fontawesome-svg-core'
import { faCoffee } from '@fortawesome/free-solid-svg-icons'
import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome'

library.add(faCoffee)

Vue.component('font-awesome-icon', FontAwesomeIcon)

Use it:
<template>

</template>

Vue.js reference documentation
Update
Bundle sizes for reference using Vue CLI 3:
1. Single Icon

File                                 Size               Gzipped

dist/js/chunk-vendors.0ce8e3e3.js    135.62 KiB         46.03 KiB
dist/js/app.d98fb35c.js              2.30 KiB           1.13 KiB

2. All Icons

File                                 Size               Gzipped

dist/js/chunk-vendors.7833710c.js    767.94 KiB         249.05 KiB
dist/js/app.b7f38b90.js              2.36 KiB           1.17 KiB

Comment: You certainly can.
Comment: Can I use it with Vuetify?
Comment: Is it safe to uninstall `@fortawesome/fontawesome-free` then?


API doesn't accept requests.put HTTP call, JSON formatting

Question: I'm trying to make a HTTP call using the Requests HTTP library for Python.
I have this code:
import requests
import json

body = json.dumps({"on": "false"})
url = "http://192.168.100.100/api/0000/lights/4/state"
r = requests.put(url=url, data=body)

However, the API responds with
"error": {
            "type": 7,
            "address": "/lights/4/state/on",
            "description": "invalid value,  true }, for parameter, on"

I'm not entirely sure what the problem is, but it could be that the BODY is getting formatted wrong; r.request.body says
{"on": "false"}

when it should be
{"on": false}

If I take off the quotes from the code I get
NameError: name 'false' is not defined

The call works when done in a browser, so I know the value is correct for this parameter. How can I correctly send this call?
Comment: The boolean false is capitalized in Python: `False`
Answer: Try changing body = json.dumps({"on": "false"}) to body = json.dumps({"on": False})
Notice capitalization on False in python.
Answer: The API might be looking for a json bool as the value for the key on. If that is the case then json.dumps({"on":False}) converts the python bool False to json bool false in the string.
PS: This is also how you would convert python's None to json's null and other json specific keywords.


What is the best way to write bit number in Verilog?

Question: For writing the bit in Verilog, which is better in the following writing:
Let's say 32 bits data and all 32 bits are set to zero:
1) 32'b0
or
2) 32{1'b0} ?
On the other hand, i want to change 5 MSB bit to one:
1) {5'b1,26'b0}
or
2) {5{1'b1},26{1'b0}}
1 or 2 is better? Or they are behave the same? Thanks in advance.
Thanks
Chong Han
Answer: Verilog has good and evil ways of dealing with bit widths of expressions. On the one hand, you can easily assign an expression of a certain width to a variable of another width, and it automatically pads or truncates the expression to fit into the variable. On the other hand, you can assign an expression of a certain width to a variable of another width, and it silently pads or truncates the expression to fit into the variable.
In SystemVerilog, if you want to set all bits of a variable to 0, you write
VariableName = '0;

The expression '0 will be sized to the context of the variable it is being assigned to. There is no need to declare a specific width. But even if you wrote
VariableName = 0;

There is no need to size the 0 because it gets truncated or padded with 0's to fit into variable.
There's no difference in the first 2 expressions you wrote. It comes down to how you view the value as a integral number, or a set of 32 individual bits.
The second two expressions do not represent the same value. {5'b1,26'b0} is 32'h0800_0000 and {5{1'b1},26{1'b0}} is 32'hF800_0000. If you are really looking to set a single bit position, most people order their bits from the LSB starting at 0, and would write something like 32'b1 << 26.


Gerar gráfico mensal

Question: Estou montando um gráfico mensal onde é exibida a soma de despesas e receitas por dia, porém os dados exibidos no gráfico são somente as datas que existem no banco mysql.
Como eu poderia exibir as datas que não existam no banco?
Queria exibir por ex do dia 01 até o dia 31 do mês.
Já tentei fazer um for e alimentar um array mas sem sucesso, alguém poderia me ajudar?
Answer: Com certeza que isto poderia ser resolvido na tua applicação. Mas fica aqui uma alternativa para solucionar isto na base de dados.
Esta é uma solução para um problema bastante conhecido.
select b.Data, a.id, a.valor
from tbl_tabela a
right join
(
    select curdate() - INTERVAL (a.a + (10 * b.a) + (100 * c.a) + (1000 * d.a)) DAY as data
    from (select 0 as a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) as a
    cross join (select 0 as a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) as b
    cross join (select 0 as a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) as c
    cross join (select 0 as a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) as d
) b
  on b.data = a.data
where b.Data between '2015-05-01' and '2015-05-03'

Apenas substitui tbl_tabela, pela tua tabela e ajusta as condições de acordo com as tuas necessidades.
Caso a performance seja um problema (nos testes que fiz, não é de todo um problema), podes pensar em criar uma tabela Calendario com as datas que necessitas.
SQLFiddle

Gerar gráfico mensal


Angular: How to filter by deep object property in array?

Question: I have an objects formatted like this:
id: 1,
name: MyObj
properties: {
  owners: [
  {
    name:owner1,
    location: loc1
  },
  {
    name:owner2,
    location: loc1
  }
 ]
}

Number of owners is different for each object. When I try to filter it using ng-repeat with filter:searchBox and search box inputs
<input name="search-filter" class="form-control" type="search" ng-model="searchBox.properties.title" />
<input name="search-filter" class="form-control" type="search" ng-model="searchBox.properties.owners" />

filtering by title works perfectly, however owners filtering doesn't work at all but I supposed it will filter based on both location and name. What am I doing wrong?
Comment: what you wanted to search in owners object? `name` **OR** location
Comment: @PankajParkar I have another object like this one where owners are not nested in properties, and it works just fine on all owners parameters. However in that case when i try to filter by name or location specifically, i get nothing. I just can't figure out how to do it when owners array is nested. Seems like Angular only goes through a few nested properties
Answer:

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {

$scope.objs =
  {
    id: 1,
    name: 'MyObj',
    properties: {
      owners: [
      {
        name: 'owner1',
        location: 'loc1'
      },
      {
        name: 'owner2',
        location: 'loc2'
      }
     ]
    }
  };

});

<input name="search-filter" class="form-control" type="search" placeholder="Search by location" ng-model="searchBox.properties.location" />
<input name="search-filter" class="form-control" type="search" placeholder="Search by name"   ng-model="searchBox.properties.owners" />

    {{owner}}

Comment: Works perfectly in your snippet but doesn't work at all in my code >_<
Comment: How can I do that? It won't fit in the comment
Answer: You can filter manually
var list = [
  {
    id: 1,
    name: 'MyObj',
    properties: {
      owners: [
      {
        name: 'owner1',
        location: 'loc1'
      },
      {
        name: 'owner2',
        location: 'loc1'
      }
     ]
    }
  }
];

function filter(filter) {
  return list.filter(function(item) {
    return item.properties.owners.find(function(owner) {
      return Object.keys(filter).every(function(key) {
        return filter[key] === owner[key];
      });
    });
  });
}

console.log(filter({ name: 'owner1', location: 'loc1' }));

I used es6 shim for that.


Weak-* convergence on subinterval

Question: If $U_{n} \to U$ weakly* in $BV[0,1]$ is it true that $U_{n}\mid_{[0,\frac{1}{2}]} \to U\mid_{[0,\frac{1}{2}]}$ weakly* in $BV[0,\frac{1}{2}]$?

I'll give some explication. Let $U_{n} \in BV[0,1]$ and $U_n \to U$ weakly*, i.e. for any $y \in C[0,1]$
$$
  \int\limits_{0}^{1} y(t)dU_{n}(t) \to \int\limits_{0}^{1}y(t)dU(t)
$$
Restrictions $U_{n} \mid _{[0,\frac{1}{2}]}, U \mid_{[0,\frac{1}{2}]} \in BV[0,\frac{1}{2}]$. For any $y \in C[0,\frac{1}{2}]$ such that $y(\frac{1}{2}) = 0$ we have
$$
  \int\limits_{0}^{\frac{1}{2}} y(t)dU_{n}(t) \to \int\limits_{0}^{\frac{1}{2}}y(t)dU(t)
$$
But is it true for any $y \in C[0,\frac{1}{2}]$? In other words, it it true, that $U_{n}\mid_{[0,\frac{1}{2}]} \to U\mid_{[0,\frac{1}{2}]}$ weakly*?
Answer: Not if I understand your conventions correctly. Consider $$U_n=\chi_{(1/2+1/n,1]},\quad U=\chi_{(1/2,1]}.$$ In general, you have to be very careful about jump discontinuities at interval endpoints.
**Edit:** More than that, you have to worry about concentrations of variation. Here is another example: Let $U_n(x)=0$ for $x\in\{0,\frac12-\frac1n,\frac12+\frac1n,1\}$, $U_n(\frac12)=1$, and interpolate linearly between the points named. Then $U_n\stackrel*\rightharpoonup0$, but $U_n|_{[0,1/2]}\stackrel*\rightharpoonup\chi_{\{1/2\}}$ (where $\stackrel*\rightharpoonup$ is weak* convergence).
If you wish for a positive result, you have to make more stringent assumptions, such as
$$
  \lim_{\delta\downarrow0}\sup_n \operatorname{TV}(U_n|_{[1/2-\delta,1/2+\delta]})=0.
$$
(I think that should be sufficient.)
Comment: Dear Harald, is it true that if we require additionally the continuity of $U$ in point $\frac{1}{2}$ then the statement will be correct?
Comment: @Nimza: No. See my expanded answer.

Weak-* convergence on subinterval


Using predicate logic to see if P(X) holds

Question: Suppose We have a set called ${A}$ and we let it equal to $A = \{a \in \mathbb{Z} \mid a^2 = 3\}$ and we let ${P(x)}$ be the predicate ${x \in \mathbb{Z} }$
Problems:
1.) ${\forall x \in A }, P(x)$
2.) ${\exists x \in A }, P(x)$
Reasoning:
For both of these problems, The first problem that I see is that equation ${a^2 = 3}$ will never be true for number in the integer set and and since ${a}$ is an integer, it has a blank set.
Thus I reason both can't hold.
Answer: You have good progress. Certainly $A = \emptyset$, so that's good. So statements of the form $\forall x \in \emptyset\, P(x)$ are always true vacuously. On the other hand, statements of the form $\exists x \in \emptyset\, P(x)$ are always false, as they require finding an element of the empty set.


Java Synchronization inside Another Thread

Question: I have a quick question about Java synchronization.
Please assume the following code:
public class Test {
    private String address;
    private int age;

    public synchronized setAddress(String a) {
        address = a;
    }

    public synchronized setAge(int a) {
        age = a;
    }

    public synchronized void start() {
          ...

          listener = new Thread(new Runnable(){
              public void run() {
                      ...
                  setAge(10);
                      ...

                  synchronized(Test.this) {
                      address = null;
                  }
              }
          }
    }
}

I am a little bit unsure about Java synchronization when synchronized method or synchronized block is called inside another thread.
Assume the thread running class Test as A, and
the listener thread B.
Then if I execute the code above, does it guarantee that synchronized method calls and synchronized block are synchronized with the A (the thread running Test class) ?
Thank you for reading.
Answer: No,
The synchronized methods are locking the Test instance, while the synchronized block is locking the Test class object.
See Java synchronized static methods: lock on object or class and Java Synchronized Block for .class
Comment: Read this : http://docs.oracle.com/javase/tutorial/essential/concurrency/

It will make everything much more clear.
Comment: Sorry for my mistake. I just changed Test.class to Test.this. Does it still mean they are not synchronized?
Comment: @so-ju no, in that case they *are* synchronized, since they are locking the same object.
Comment: So, you are saying that synchronized blocks or synchronized methods called inside the listener thread are synchronized with such methods called outside of the listener thread?


create views page using entityreference

Question: I have two custom content types, Speaker and Presentation. Each speaker can have many presentations. I am using the EntityReference module to attach a Speaker to a Presentation.
Using Views, I would like to create a page of Presentations that also lists the Speaker associated with the presentation such the page would look something like:
Presentation 1
details
Attached speaker details

Presentation 2
details
Attached speaker details

Presentation 3
details
Attached speaker details

How do I do that in Views. I followed the EntityReference documentation but it only talks about creating a block for a single node. I want to be able to show multiple Presentation nodes on one page using Views and EntityReference. Thanks in advance for any help anyone can provide.
Answer: I assume that you have your entity reference field (pointing to speaker) on the content type "Presentation" below and that it is called "field_speaker".
In Views add a new View. Choose Show:Content (nodes), of type: Presentation.
Now you have all your presentations listed, with their titles. Let's leave it at that for now.
Open up Advanced to the right and open up Relationships, choose "Entity Reference: Referenced Entity - A bridge to the Content entity that is referenced via field_speaker".
Now we have the same result as before but we will be able to fetch data for the speaker through the relationship in the content type Presentation.
Under fields, click add and add the field called "Content: Title", now you have a dropdown that says "Relationship". Choose the only on available (field_speaker). Click apply.
You now have each presentation listed with it's title and the title of the presentations speaker.
Now you can go ahead and add the fields you wanted, sort the list etc.
Comment: Thank you so much, Pontus!! Exactly what I was looking for.

create views page using entityreference


MS SQL - Joining on two tables with a substringed key in one column

Question: I have a 2 tables I need to join, however on one of the tables I need to extract a key from a varchar field in each row.
Table 1 Description (numeric 18,varchar 4000)
    descriptionid   description
    1               Blah Blah: Queue 1Blah Blah
    2               foobar:Queue 2
    3               rem:Queue 2 -This is a note
    4               Anotherrow: Queue 3
    5               Something else

Table 2 Queue - (numeric 18, varchar 100)
    queueid queue

    123     Queue 1
    124     Queue 2
    127     Queue 3
    129     Queue 4

So I need to produce the output like so
View 3 Queue-Description (numeric 18, numeric 18)
    descriptionid   queueid
    1               123
    2               124
    3               124
    4               127
    5               null

So in table 1 row 1, I need to strip out the value Queue1 from the description, verify it is in the queue table, and lookup the queueid.
I am unable to change the structure of tables 1 and 2.
What ways can this be achieved in MSSQL?
What is the most efficient way to do this in SQL - using MSSQL 2005 here.
Answer:
most efficient way

Well... don't know about that but it is a way.
select T1.descriptionid,
       T2.queueid
from Table1 as T1
  left outer join Table2 as T2
    on T1.description like '%'+T2.queue+'%'

Another way
select T1.descriptionid,
       T2.queueid
from Table1 as T1
  left outer join Table2 as T2
    on charindex(T2.queue, T1.description, 1) > 0

If there are more than one match (see comment by Ed Harper) you can use this to pick the one with the longest match.
select T1.descriptionid,
       T2.queueid
from Table1 as T1
  outer apply (
                 select top 1 T3.queueid
                 from Table2 as T3
                 where charindex(T3.queue, T1.description, 1) > 0
                 order by len(T3.queue) desc
              ) as  T2(queueid)

Comment: Appreciate this may not be the most efficient way, however am accepting it as the answer because I only need to build a reporting table overnight on this.
Comment: Doesn't this risk generating false matches when there are more than 9 queues? 'Queue 11' in a string in table 1 will match both 'Queue 1' and 'Queue 11' in table 2.
Comment: @Ed Harper - You are correct. Added a version that will pick the longest match.
Answer: The most efficient way to do this is to add an extra column to your table and insert the extracted the ID from the string.  You can do this when rows are added and you can process the existing ones fairly easily. But trying to left join like this will be very slow.
Comment: Unfortunately I cannot update these tables. They are for reporting only. Do you have a left join example of how this can be achieved? I could create a new table nightly to report on based on the query.
Answer: In Sql Server 2005 you can extract your queue string using regex.  The Data Extraction section on this page contains an example.
In a stored procedure you can then build an indexed temp table that contains a new column - this allows you to do this without changing the table metadata).
If you can change the table metadata you can:
Trigger the content into another column (on insert).
Or if the information is not needed immediately a daily sql job could extract the information.


Compute cdf and pdf given f(x)

Question: I am having trouble computing the cdf and pdf of the problem below:
Answer: What have you done so far? Anyway, the hint goes like follows:(a) $$F_M(m) = \mathbb{P}[\{M\leq m\}]=\mathbb{P}[\{\mathrm{max}(X_1,X_2,\dots,X_n)\leq m\}]=\mathbb{P}[\{X_1\leq m,X_2 \leq m,\dots,X_n \leq m \}]=\int_{x_1=0}^m \int_{x_2=0}^m \dots \int_{x_n=0}^m f_{X_1,X_2,\dots,X_n}(x_1,x_2,x_3,\dots,x_n) \space \mathrm{d}x_1\mathrm{d}x_2\dots \mathrm{d}x_n$$ and just split it by independence as given, you should get the desired answer. PDF is just the differentiation of CDF.
(b) For this one try using the same trick as in the first one but in a slightly different manner.
Comment: Re (a), while the subscript $M$ in $F_M$ has a precise meaning, the various subscripts appended to the three occurrences of the symbol $P$ have none--actually they might even be misleading. Re (b), I am curious to know whether this "solution" helped the OP at all.

Compute cdf and pdf given f(x)


Expo get unique device id without ejecting

Question: This library allows you to get unique device id / Mac address of Android devices, which doesn't change after reinstallation.
Expo.Constants.deviceId changes after every reinstallation (even if the app version number is the same).
Is there a way to get an unique id for Android that doesn't change after reinstallation (at least for if it's the same version), without ejecting?
Comment: You can find more information about that topic in the Github issue. Looks like this is for privacy reasons not wanted. https://github.com/expo/expo/issues/825
Comment: Does Expo.Constants work both on iOS and Android standalone apps?
Comment: @JeafGilbert yes :D
Comment: Did you found a solution for this?
Comment: does https://github.com/react-native-device-info/react-native-device-info#getuniqueid not provide exactly this?
Comment: Yes, but that requires ejecting from Expo (in the old ejection days).
Comment: `react-native-device-info` will usually not work with Expo unless your using the expo barebone app.
Answer: For Expo IOS theres currently very limited options, Since Apple forbids getting private device info. We will need to create our own unique identifier below.
Solution:
My solution is a combination of uuid and Expo SecureStore works for IOS and Android.
import * as SecureStore from 'expo-secure-store';
import 'react-native-get-random-values';
import { v4 as uuidv4 } from 'uuid';

let uuid = uuidv4();
await SecureStore.setItemAsync('secure_deviceid', JSON.stringify(uuid));
let fetchUUID = await SecureStore.getItemAsync('secure_deviceid');
console.log(fetchUUID)

This solution will work even if app gets reinstalled, or if user switches devices and copy's all data to new device.
(Expo.Constants.deviceId is deprecated and will be removed in Expo SDK 44).
Full Example:
To check if you already stored the uuid in SecureStore
import * as SecureStore from 'expo-secure-store';
import 'react-native-get-random-values';
import { v4 as uuidv4 } from 'uuid';

let uuid = uuidv4();
let fetchUUID = await SecureStore.getItemAsync('secure_deviceid');
  //if user has already signed up prior
  if (fetchUUID) {
    uuid = fetchUUID
  }
await SecureStore.setItemAsync('secure_deviceid', JSON.stringify(uuid));
console.log(uuid)

Comment: I guess the 'secure_deviceid'  kept after app updates but not between installs ?
Comment: It will be kept even for reinstalls since `SecureStore` is stored to the system keychain and according to Expo docs will be kept around "data stored with expo-secure-store can persist across app installs".

https://docs.expo.io/versions/latest/sdk/securestore/
Comment: @IbadUrRehman `uuid` gives a new unique id each time called.
for your case you will need to check if theres already a uuid first and retrieve from `SecureStore`.
Comment: Will it persist between app installs on Android too?
Doc says: Please note that for iOS standalone apps, data stored with expo-secure-store can persist across app installs.

But nothing is mentionned for Android
Comment: @yemd `SecureStore` for Android is stored in `SharedPreferences` this might be helpful https://stackoverflow.com/questions/24650870/sharedpreferences-values-do-not-persist
Comment: it give different values each time for same device I need to implement same unique id for one device
Comment: the docs say that it will persist on iOS specifically, which implies that it wont for android
Answer: Use Application.androidId from expo-application. Id will not change after reinstall or update. The value may change if a factory reset is performed on the device or if an APK signing key changes.
https://docs.expo.dev/versions/latest/sdk/application/#applicationandroidid
Example:
import * as Application from 'expo-application';
import { Platform } from 'expo-modules-core';
import * as SecureStore from 'expo-secure-store';
import Constants from 'expo-constants';

const getDeviceId = async () => {
  if (Platform.OS === 'android') {
    return Application.androidId;
  } else {
    let deviceId = await SecureStore.getItemAsync('deviceId');

    if (!deviceId) {
      deviceId = Constants.deviceId; //or generate uuid
      await SecureStore.setItemAsync('deviceId', deviceId);
    }

    return deviceId;
  }
}

Comment: For iOS we an use this https://docs.expo.dev/versions/v45.0.0/sdk/application/#applicationgetiosidforvendorasync
Comment: but what about ios? It says it will return null on ios. I need something that works on both platform
Comment: @AbhishekAnand i added an example
Answer: Best way to do is use ANDROID_ID for android or IDFV for iOS.
For Expo here is package: https://docs.expo.dev/versions/latest/sdk/application/#applicationgetiosidforvendorasync
My code:
const newUniqueId = Platform.OS === 'android'
            ? Application.androidId ?? uuid.v4().toString()
            : await Application.getIosIdForVendorAsync() ?? uuid.v4().toString();

let uniqueId = null;
try {
    uniqueId = await SecureStore.getItemAsync('uniqueId');
} catch (error) {
    LoggerService.logToSentry(error);
}

try {
    if (!uniqueId) {
        uniqueId = newUniqueId;
        await SecureStore.setItemAsync('uniqueId', uniqueId);
    }
} catch (error) {
    uniqueId = newUniqueId;
    LoggerService.logToSentry(error);
}

return uniqueId;

If some one use only uuid.v4() and stores with SecureStore after app deletion all data will be deleted except iOS phones. On Android all App data will be deleted with stored keys
Answer: Guess you can use facebook module for this purpose.
https://docs.expo.io/versions/latest/sdk/facebook-ads/#currentdevicehash
Not sure what happens under hood - but looks like it unique between app reinstal, device restart etc.
Comment: Please add all relevant information to your answer instead of linking to external sources
Answer: Just use getuniqueid() method from react-native-device-info. Works on iOS and android to uniquely identify a device .
Comment: This won't work in the Expo managed workflow
Answer: To get the device UniqueId in expo project,

npm install react-native-device-info
expo run:ios or expo run:android

Please note: expo start will throw an error
Comment: Unfortunately you would need to eject expo app to use `react-native-device-info`


File browser error - IMCE

Question: IMCE - http://ufku.com/drupal/imce/7
I am trying to load file browser window via IMCE module on CHOOSE FILE button-(form upload field) click.
My following code loads such window fine from which I can select a file. But once I select the file, it opens a new window and display image file in new window instead of adding that file name in CHOOSE FILE button for me to further save and upload that file to my location (same as normal form file upload does).
Please note that I am not using IMCE in WYSIWYG editor rather a form upload field.
Here is my code;
$form['image_file'] = array(
  '#type' => 'file',
  '#title' => t('File *'),
  '#size' => 20,
  '#description' => t('Please use JPG file only.'),
  '#upload_validators' => array(
    'file_validate_extensions' => array('pdf'),
  ),
  '#upload_location' => 'public://my_image_files/',
  '#attributes' => array('onclick' => "window.open('/imce', '', 'width=760,height=560,resizable=1')"),
);
By following the documentation in http://ufku.com/drupal/imce/7, I have tried using
'/imce?app=myApp|sendto@myFileHandler'
and have created this function to call but no luck.
(function myFileHandler(file, win) {
  alert('FILE UPLOAD myOnloadFunc');
  $('#urlFieldId').val(file.url);//insert file url into the url field
  win.close();//close IMCE
})(window.jQuery, window.Drupal, window.Drupal.bootstrap);
Any idea what I am doing wrong here or perhaps I am missing configuration settings somewhere?
Thanks
Answer: I have achieved this with the following;
1)

'edit-image-file-path-1' is id value for form field 'image_file_path_1'.
2)
$form['image_file_selector'] = array(
  '#markup' => t("
Image File *
Click to choose Image File
"),
);
$form['image_file_path_1'] = array(
  '#type' => 'textfield',
  '#attributes' => array('readonly' => 'readonly'),
  '#default_value' => $result->image_file_path_1,
);

File browser error - IMCE


How to prove a function of two variables is Lebesgue measurable?

Question: Consider the function $f: [0,1]\times [0,1] \rightarrow [-\infty,\infty]$ given by
$$f(x,y) = \frac{x^2-y^2}{(x^2+y^2)^2}, (x,y)\neq (0,0)$$
and $f(x,y) = 0$ when $(x,y) = (0,0)$.
I am trying to show that $f$ is $M\times M$ measurable, where $M$ is the $\sigma$-algebra of Lebesgue measurable sets.
However I am not sure how to show this. I thought maybe if $f$ where continous we would be done, but $f$ is not even continous since as $(x,y)\rightarrow (0,0)$ the function $f$ does not approach $0$.
Must I show that for any $t\in\mathbb{R}$, $f^{-1}(t,\infty)\in M\times M$? This is quite difficult.
How can I show this?
Comment: Is the idea that these are continous functions and so they are $M\times M$ measurable and they are tending to $f$? so $f$ must also be $M\times M$ measurable?
Comment: Hint: Try to use $f_n(x,y)$ :
$$f_n(x,y)=\frac{x^2-y^2}{(x²+y²)^2+1/n}$$
Comment: Yes this is the idea
Answer: You're right that $f$ is only continuous on $\mathbb R^2 - \{ (0,0) \}$, but the omission of the point $\{(0,0) \}$ should not cause any major difficulty.
Let me spell out the logic. Suppose we pick a half-open interval $(a, \infty]$, for some $a \in \mathbb R$. Our task is to show that $f^{-1}(a,\infty]$ is a measurable  with respect to the product measure on $\mathbb R^2$. There are two cases to consider:

$a > 0$: In this case, $f^{-1}(a,\infty] = (f|_{\mathbb R^2 - \{ (0,0)\} })^{-1} (a, \infty]$, which is open because $f|_{\mathbb R^2 - \{ (0,0) \}}$ is a continuous function, hence is a Borel set, hence is measurable with respect to the product of the Lebesgue measures on the two $\mathbb R$ factors.
$a \leq 0$: In this case, $f^{-1}(a, \infty] =  (f|_{\mathbb R^2 - \{ (0,0) \} })^{-1}(a, \infty]\cup \{ (0,0) \}$, which is the union of an open set and the singleton set $\{(0,0)\}$. Both these sets are Borel sets, hence also measurable with respect to the product measure, and therefore, their union is measurable with respect to the product measure too.
Comment: Wait. How do we know that $f^{-1} (a,\infty) = f(a,\infty)$?
Comment: Sorry, that was a typo!
Comment: Ah! Thanks a lot, makes much more sense now. Thanks for the help :)


Ajustar valores dos eixos num gráfico no Python

Question: Eu estou a tentar retirar os quadrados brancos de um gráfico no Python (usando um Jupyter Notebook no Anaconda). Gostava que o eixo dos xx terminasse em 1,3 e que o eixo dos yy terminasse em 1,2. Tentei ajustar com algumas linhas de código mas fica sempre um espaço em branco à direita e em cima destes números, respetivamente. Como posso arranjar o código de forma a terminar nesses números, nos eixos?
<code>#imagem2 amostra17 triangulo bicamada AFM com spline
import matplotlib.pyplot as plt
from numpy import *
import numpy as np
import pandas as pd
import time
import numpy as np
from scipy.interpolate import interp1d
from scipy.interpolate import make_interp_spline, BSpline

def func(x, pos):  # formatter function takes tick label and tick position
    s = str(x)
    ind = s.index('.')
    return s[:ind] + ',' + s[ind+1:]   # change dot to comma
x_format = tkr.FuncFormatter(func)
plt.rcParams["figure.figsize"] = [14.5,10]
fig, ax =plt.subplots()
ax.xaxis.set_major_formatter(x_format)
ax.yaxis.set_major_formatter(x_format)
x1=np.array([0.00E+00, 1.77E-02, 3.53E-02, 5.30E-02, 7.07E-02, 8.83E-02, 1.06E-01, 1.24E-01, 1.41E-01, 1.59E-01,
             1.77E-01, 1.94E-01, 2.12E-01, 2.30E-01, 2.47E-01, 2.65E-01, 2.83E-01, 3.00E-01, 3.18E-01, 3.36E-01,
             3.53E-01, 3.71E-01, 3.89E-01, 4.06E-01, 4.24E-01, 4.42E-01, 4.59E-01, 4.77E-01, 4.95E-01, 5.12E-01,
             5.30E-01, 5.48E-01, 5.65E-01, 5.83E-01, 6.01E-01, 6.18E-01, 6.36E-01, 6.54E-01, 6.71E-01, 6.89E-01,
             7.07E-01, 7.24E-01, 7.42E-01, 7.60E-01, 7.77E-01, 7.95E-01, 8.13E-01, 8.30E-01, 8.48E-01, 8.66E-01,
             8.83E-01, 9.01E-01, 9.18E-01, 9.36E-01, 9.54E-01, 9.71E-01, 9.89E-01, 1.01E+00, 1.02E+00, 1.04E+00,
             1.06E+00, 1.08E+00, 1.10E+00, 1.11E+00, 1.13E+00, 1.15E+00, 1.17E+00, 1.18E+00, 1.20E+00, 1.22E+00,
             1.24E+00, 1.25E+00, 1.27E+00, 1.29E+00])
y1=np.array([4.58E-01, 8.76E-01, 8.41E-01, 6.54E-01, 5.81E-01, 6.97E-01, 6.62E-01, 9.29E-01, 1.12E+00, 1.01E+00,
             9.74E-01, 9.38E-01, 7.89E-01, 6.41E-01, 7.56E-01, 9.48E-01, 1.03E+00, 1.24E-01, 1.64E-01, 1.70E-01,
             5.88E-02, -5.23E-02, -1.25E-01, -1.23E-01, -4.51E-02, 7.04E-02, 3.50E-02, 1.13E-01, 7.76E-02, -3.22E-02,
             1.59E-01, 1.99E-01, 1.64E-01, 1.66E-01, 2.82E-01, 2.46E-01, 2.22E-02, -1.33E-02, 1.78E-01, 1.85E-01,
             2.25E-01, 3.84E-02, 7.85E-02, 8.10E-02, -1.43E-01, -6.56E-02, 2.02E-01, -2.28E-02, -2.85E-01, -2.23E-01,
             -6.94E-02, -2.95E-02, -6.49E-02, -6.24E-02, 9.11E-02, 3.21E-01, 1.34E-01, -1.66E-01, -3.91E-01, -3.45E-01,
             -4.94E-01, -4.54E-01, -5.27E-01, -5.66E-01, -6.84E-01, -5.67E-01, -6.55E-01, -6.47E-01, -5.43E-01, -7.08E-01,
             -4.73E-01, -5.77E-01, -7.53E-01, -5.41E-01])

xnew = np.linspace(x1.min(), x1.max(), 300)
spl = make_interp_spline(x1, y1, k=3)
curva_smooth = spl(xnew)

plt.plot(xnew, curva_smooth, linestyle='-', linewidth=3, marker='None', color='Black')
df = pd.read_excel('AFMimagem2amostra17_triangulo_bicamada.xlsx', header=None, usecols=[0,1,2,3,4,5,6,7,8], names=['A', 'B', 'C', 'D','E','F','G','H'])
#ax.plot(df['A'], df['B'], label='T. "fria"=340 ºC', linestyle='None', linewidth=3, marker='None', color='Black', markersize=14)
ax.plot(df['C'], df['D'], label='_T. "fria"=340 ºC', linestyle='--', linewidth=3, marker='None', color='Red', markersize=14)
ax.plot(df['E'], df['F'], label='_T. "fria"=340 ºC', linestyle='--', linewidth=3, marker='None', color='Red', markersize=14)
ax.plot(df['G'], df['H'], label='_T. "fria"=340 ºC', linestyle='--', linewidth=3, marker='None', color='Red', markersize=14)
ax.yaxis.grid(b=True, color='black', alpha=0.3, linestyle='-.', linewidth=1)
ax.xaxis.grid(b=True, color='black', alpha=0.3, linestyle='-.', linewidth=1)
ax.set_xlabel('x ($\mu$m)', fontsize=40)
ax.tick_params(axis='x', pad=15)
plt.xticks(np.arange(0.0,1.4,0.1).round(decimals=1))
plt.yticks(np.arange(-0.8,1.3,0.2).round(decimals=1))
ax.set_ylabel('Altura (nm)', fontsize=40)
plt.rc('xtick', labelsize=30)
plt.rc('ytick', labelsize=30)
#ax.set_title('Perfil de temperatura do forno', fontsize=20)
#ax.legend(loc=9,
#          bbox_to_anchor=(.7,.97),
#          labelspacing=2.5,
#          numpoints=1,
#          columnspacing=0.5,
#          ncol=2, fontsize=15,
#          frameon=False)

#trans = ax.get_xaxis_transform() # x em unidades do dado, y em fração do eixo
#ann = ax.annotate('T$_\mathregular{Q}$', xy=(120, 0.5), xycoords=trans, fontsize=20)
#ann = ax.annotate('T$_\mathregular{F}$', xy=(120, 0.35), xycoords=trans, fontsize=20)
#ann = ax.annotate('T$_\mathregular{T}$', xy=(120, 0.25), xycoords=trans, fontsize=20)
#plt.show()
plt.savefig('output.png', dpi=500, bbox_inches='tight')
</code>
Ficheiro Excel 'AFMimagem2amostra17_triangulo_bicamada.xlsx' (não consegui colocar todos os números das primeiras colunas porque não cabiam na foto, mas encontram-se no código em Python):

Gráfico obtido no Python:
Answer: É preciso definir os limites dos eixos.
<code>plt.xlim([0, 1.3])
plt.ylim([-0.8, 1.2])
</code>
Comment: Muito obrigada! Funcionou e já obtive o gráfico certo


Azure Ubuntu VM - Connect Button Disabled

Question: I've created a VM of Ubuntu-16.04 LTS using Resource Manager. VM has been created successfully but the connect and start buttons are disabled. In tutorials, the connect button is already enabled once the VM is created.
Comment: What tutorials? Also this is a better question for superuser.com or one of those sites. No programming here...
Comment: Either superuser or serverfault. But not stackoverflow. And when you repost, include a screenshot of what you're seeing.
Answer: Usually one of the following reasons:

VM doesn't have a public IP address
No GUI on the VM so you need to use SSH

Could also be access to the VM if you don't have the appropriate permissions.


Moving Google Compute VM instances between Networks

Question: Does anyone know how to move an existing VM instance between Google Cloud Networks configured on a project? I know you can specify the Network at the point of creating an new VM, but there doesn't appear to be a facility for changing it once instantiated.
    Any pointers appreciated!
    -Paul
Answer: In order to move an existing GCE VM instance to a different network, you will first need to delete the VM instance while keeping all its disks (--keep-disks all  flag with gcloud command) [1]. Then create a new VM instance with the existing boot disk [2],[3] and attach other disks to the new VM instance if there is any.
All of the above mentioned steps can be done using the Developers Console as well.
Link 1: gcloud compute instances delete NAME --keep-disks all
Link 2: Using an existing root persistent disk
Link 3: gcloud compute instances create
Comment: @user3446361 In that case, could you upvote/accept his answer, to let next users who come on your question know it's the correct one? (you should have a checkmark next to the score of the answer, and you should be able to click on it)
Comment: Can confirm. As of today, 2019-11-22, this is still the only way. An existing instance cannot have a new nic added (or any nics deleted), and nicN network cannot be changed. However flexible the GCE is, it still lacks the good old "unplug this Ethernet cable and plug into a different router" thing, which is so natural with physical machines.


CLLocationManager does not initialize on viewDidLoad

Question: I have a simple objective C app with UIWebView. This is loading an URL in viewDidLoad method and I need to localize this URL BEFORE the loadRequest but my CLLocationManager is calling the didUpdateToLocation method AFTER the loadRequest.
My viewDidLoad method:
- (void)viewDidLoad {
    // execute super method
    [super viewDidLoad];

    // put gray background color
    self.view.backgroundColor = [UIColor lightGrayColor];

    // define itself as UIWebView delegate
    self.webView.delegate = self;

    // define itself as CLLocationManager delegate
    locationManager = [[CLLocationManager alloc] init];

    locationManager.delegate = self;
    locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    [locationManager startUpdatingLocation];

    NSLog(@"LOCALIZED????%@",[self getCustomURL:homeURL]);
    [self.webView loadRequest:[[NSURLRequest alloc] initWithURL:[NSURL URLWithString:[self getCustomURL:homeURL]]]];
}

I'm always getting (null) when calling loadRequest, but just after i'm getting the correct location.
I've tried to separate in a new thread the startUpdatingLocation
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
    [locationManager startUpdatingLocation];
});

Or waiting till getting a correct location:
while (longitude == nil) {
    [locationManager startUpdatingLocation];
}

Any idea how can I get the location before the loadRequest to have the url
Answer: CLLocationManager is an async task. To execute the loadRequest after the location, you need to implement the delegate for the CLLocationManager and then call the loadRequest on the webview
Answer: You can use loadRequest in method from CLLocationManagerDelegate:
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
    ……
    ……
    [self.webView loadRequest:[[NSURLRequest alloc] initWithURL:[NSURL URLWithString:[self getCustomURL:homeURL]]]];
    ……
    ……
}

Also, in iOS8, you need to do couple things to get location:
1) Call requestWhenInUseAuthorization method before startUpdatingLocation:
if ([locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
   [locationManager requestWhenInUseAuthorization];
}
[locationManager startUpdatingLocation];

2) add NSLocationAlwaysUsageDescription or NSLocationWhenInUseUsageDescription key to Info.plist.


How to remove duplicates in view... the return

Question: I know that this question turn around in Drupal answers but I couldn't get a working answer for my use case.
Here it is: I have a view which is producing duplicate results (and I understand why) but I couldn't find a way to remove them in the hook views_query_alter
This view is requesting nodes with some filters and a left join (Require this relationship) on a field wich contains references to paragraphs (node__field_aw_agenda).  This is this relationship which produce the duplicates.
SELECT "node_field_data"."nid" AS "nid", "node_field_data"."langcode" AS "node_field_data_langcode", DATE_FORMAT(paragraphs_item_field_data_node__field_aw_agenda__paragraph__field_agenda_date.field_agenda_date_value, '%Y%m%d') AS "paragraphs_item_field_data_node__field_aw_agenda__paragraph_", MIN(node_field_data.nid) AS "nid_2", MIN(paragraphs_item_field_data_node__field_aw_agenda.id) AS "paragraphs_item_field_data_node__field_aw_agenda_id"
FROM
{node_field_data} "node_field_data"
LEFT JOIN {node__field_aw_agenda} "node__field_aw_agenda" ON node_field_data.nid = node__field_aw_agenda.entity_id AND node__field_aw_agenda.deleted = '0'
INNER JOIN {paragraphs_item_field_data} "paragraphs_item_field_data_node__field_aw_agenda" ON node__field_aw_agenda.field_aw_agenda_target_id = paragraphs_item_field_data_node__field_aw_agenda.id
LEFT JOIN {node__field_aw_prod_state} "node__field_aw_prod_state" ON node_field_data.nid = node__field_aw_prod_state.entity_id AND node__field_aw_prod_state.deleted = '0'
LEFT JOIN {node__field_aw_images} "node__field_aw_images" ON node_field_data.nid = node__field_aw_images.entity_id AND node__field_aw_images.deleted = '0'
LEFT JOIN {paragraph__field_agenda_date} "paragraphs_item_field_data_node__field_aw_agenda__paragraph__field_agenda_date" ON paragraphs_item_field_data_node__field_aw_agenda.id = paragraphs_item_field_data_node__field_aw_agenda__paragraph__field_agenda_date.entity_id AND paragraphs_item_field_data_node__field_aw_agenda__paragraph__field_agenda_date.deleted = '0'
WHERE ("node_field_data"."status" = '1') AND ("node_field_data"."type" IN ('aw_audiovisu', 'aw_scenicarts')) AND ("node__field_aw_prod_state"."field_aw_prod_state_value" IN ('prem', 'play')) AND ("node_field_data"."langcode" IN ('fr')) AND ("node__field_aw_images"."field_aw_images_target_id" IS NOT NULL)
GROUP BY "node_field_data"."nid", "paragraphs_item_field_data_node__field_aw_agenda__paragraph_", "node_field_data_langcode"
ORDER BY "paragraphs_item_field_data_node__field_aw_agenda__paragraph_" DESC

As you can see, there is a GROUP BY term with several fields in it. This GROUP BY term is added in the following hook
function mymodule_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
  $view_id = $view->id();
  $display_id = $view->current_display;
  if (($view_id == 'my_view') && ($display_id == 'my_display_id')) {
    $query->addField('node_field_data', 'nid', 'nid', [
      'function' => 'groupby',
    ]);
    $query->groupby = ['node_field_data.nid'];
  }
}

Note that this hook is adding only one GROUP BY field ("node_field_data"."nid"), I don't know how this lead to add the other fields ("paragraphs_item_field_data_node__field_aw_agenda__paragraph_", "node_field_data_langcode")
Please do not provide me a solution with hook_views_pre_render() as I am looking for a generic SQL solution
As requested, here is a screenshot of the view UI
Comment: Have you tried turning on distinct in the [query settings](https://i.stack.imgur.com/jGTwi.png)?
Comment: Yes, no result with distinct ON.
Comment: Have you tried Aggregation? That is usually the way to deal with Relationship duplicates, you find what exactly is causing the duplicates, it might be a field that is using the Relationship, and change the Aggregation setting on it to Entity ID instead of Value, or something similar. Your example isn't very readable from Drupal Views perspective, it requires SQL debugging.
Comment: I have tried aggregation without luck: I have tested many options on several fields. The main question is why in `views_query_alter` I set only one field in the `GroupBy` clause but at the end there are multiple fields in the clause.
Comment: Did you solve it in the end? I have the exact same problem
Answer: To remove unnecessary GROUP BY statements added to a query, you can use the unset() function in your hook implementation to remove the unwanted groupings. Here's an updated version of your code that removes the unwanted GROUP BY fields:
function mymodule_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
  $view_id = $view->id();
  $display_id = $view->current_display;
  if (($view_id == 'my_view') && ($display_id == 'my_display_id')) {
    $query->addField('node_field_data', 'nid', 'nid', [
      'function' => 'groupby',
    ]);
    $query->groupby = ['node_field_data.nid'];

    // Remove unwanted GROUP BY fields
    unset($query->groupby['paragraphs_item_field_data_node__field_aw_agenda__paragraph_']);
    unset($query->groupby['node_field_data_langcode']);
  }
}

Comment: Thank you, but unfortunately in this hook, the `$quey->groupby` array is not yet populated by the unwanted groupings. Note also that the line `$query->groupby = ['node_field_data.nid'];` already ensures that there is only one grouping in the `groupby` array
Comment: Good question. In many simpler cases the addField and addGroupBy works; but in some cases extra group by's get added for no apparent reason which break the group fix.


Nada acontece ao chamar arquivo .php via Ajax call em Javascript puro

Question: Estou criando a persistência em servidor MySql para uma aplicação web minha.
Para isso estou usando o xampp e o phpmyadmin. Criei um banco no phpMyAdmin e na minha aplicação, em um javascript eu tenho uma requisição Ajax para um arquivo .php que faz essa comunicação com o servidor.
O que acontece é que, a função AjaxCall no meu .js é chamada, mas o arquivo Php passado pra ela com uma action, é simplesmente ignorado. Não acontece nada com o php. Coloquei echos no .php e nada aparece. Coloquei erros de sintaxe e o navegador nem acusou. Significa que o .php não está sendo acessado... Só que eu não não sei porque.
O meu Js:
function abreConta(){
    var cpf = document.getElementById('cpf').value;
    var agencia = document.getElementById('agencia').value;
    var conta = document.getElementById('conta').value;

    //As variáveis acima são preenchidas corretamente.

    parms = "&cpf"+cpf+"&agencia"+agencia+"&conta"+conta;
    ajaxCall("Persistencia.php?action=abreConta" +parms, mudaView);

}

function mudaView(listaParams){
    window.alert("Sua conta foi aberta com sucesso. Você será redirecionado ao menu inicial");
    mudaMenu("formularioDeAbertura", "menu1");
}

function ajaxCall(stringCall, callback){
    var httpRequest = new XMLHttpRequest;

    httpRequest.onreadystatechange = function(){
    if (httpRequest.readyState === 4) {
        if (httpRequest.status === 200) {
            console.log("Requisicao http em curso");
          callback(httpRequest.responseText);
        }
    }
    };
    httpRequest.open('GET', stringCall);
    httpRequest.send();
}

A pasta da minha aplicação:

O meu Persistencia.php:
<?php

function conectaDB(){
    $con  =  mysqli_connect("localhost","root","","onbank");

    if(!$con){
        echo "
Erro na conexao com a base dados...
";
        echo "
 Erro " . mysqli_connect_errno() . ".
";
        die();
    }
    $con->set_charset("utf8");
    return $con;
}

    if(@$_REQUEST['action'] == "abreConta")     //recupera lista de nomes das cidades
    {

        con = ConectaDB();
        $cpf = $con->real_escape_string($REQUEST['cpf']);
        $agencia = $con->real_escape_string($REQUEST['agencia']);
        $conta = $con->real_escape_string($REQUEST['conta']);

        mysqli_query($con,"INSERT INTO contas (agencia,conta,dono) VALUES('$agencia','$conta', '$cpf');");]
        $con->close();

        //abreConta();
    }

    if(@_REQUEST['action'] == 'buscaContasCliente')
    {
        $cpf = buscaCpf();
        inicializaListaContas($cpf);

    }

    function buscaCpf(){
        $con = ConectaDB();
        $nome = $con->real_escape_string($REQUEST['nome']);

        $result = mysqli_query($con, "SELECT cpf FROM clientes WHERE nome='$nome';");
        return $result;
    }

?>
Meu banco de dados no phpMyAdmin: Não está sendo alterado, devido ao Persistencia.php nao estar sendo executado.

Obs: a coluna saldo possui preenchimento automático com 0.
Na aba Network do f12 aparece o seguinte quando eu abro uma conta:
Comment: Tá mostrando isso no console: `console.log("Requisicao http em curso");`?
Comment: porque a tag phpmyadmin? O que tem a ver com o problema?
Comment: Sim, isso mostra
Comment: @GuilhermeCostamilam tag phpMyAdmin? Aonde?  O phpmyadmin é onde tem o servidor mysql que eu to usando
Comment: O servidor de banco de dados não está no phpmyadmin, ele uma interface que você usa para acessar o bd. Use a tag do phpmyadmin quando o problema estiver relacionado a ele e não por que você usa ele para conferir se algo funcionou ou não
Answer: Você verificou o que está aparecendo no network do broswer? para verificar só precisa clicar em f12 e verificar a aba network. Depois realizar a requisição ajax. Deve aparecer um novo campo, nele provavelmente irá aparecer o erro no código PHP.
Ou você pode também acessar diretamente pelo broswer e verificar se tem algum erro. Nesse seu caso seria: http://localhost/Persistencia.php?action=abreConta. Deve aparecer melhor os erros que estão sendo retornados.
Recomendo também mudar a forma do request, hoje em javascript utilizamos uma forma mais simplificada para fazer Ajax no lado do javascript, veja um exemplo:

Esse é o PHP que está testando esse Javascript, fiz só como demostração:
<?php
$dados = [$_GET["cpf"], $_GET["conta"], $_GET["agencia"]];
echo json_encode($dados);

Quando descobrir qual erro que está dando no PHP você pode atualizar a pergunta se não conseguir resolver.
Comment: Descobri: Na opção "Response" do Network aponta o erro:
Parse error: syntax error, unexpected ']' in C:\xampp\htdocs\AppGA\Persistencia.php on line 24
Comment: Consegui fazer a comunicação!! lol ; Só que a conta foi adicionada na tabela com os parâmetros todos zerados...
Comment: Agora bão retorna nenhum erro no response. Vou debugar com echos pra verificar onde os parâmetros não estão chegando.
Comment: Foi só na primeira tentativa, agora o MySQL está preenchendo as tabelas com todos os valores. Obrigado!!
Answer: O erro está nesta linha:
parms = "&cpf"+cpf+"&agencia"+agencia+"&conta"+conta;

Faltam os sinais de igual = nos parâmetros:
             ↓               ↓                 ↓
parms = "&cpf="+cpf+"&agencia="+agencia+"&conta="+conta;

Sem os =, o PHP não está recebendo os valores.
Comment: Coloque `console.log(httpRequest.responseText);` pra ver o que retorna.
Comment: Já tentou colocar um `echo "qualquer coisa";` no final do PHP, antes do `?>`?
Comment: Ah, entendi. Mas corrigi isso e não adiantou. Não mudou nada :(
Comment: Mas está mostrando o console.log na resposta do Ajax?


HTML Form input value not updating in javascript function

Question: I have a simple HTML form which has an event listener binded to it and when you click on the button inside the form that has a class of 'booking__form__counter--increase' this should increase the input field value by 1. It calls a javascript function named 'increaseCounter()' I declare a variable that points to this value but when i try to use the variable to increment it, it doesn't work. If i use the methods in the variable directly it works? I am missing something simple here but i cannot work out what.

let bookingForm = document.querySelector('.booking__form');

bookingForm.addEventListener('click', function (e) {

  let target = e.target;
  let inputCounterValue = target.parentElement.firstElementChild.value;
  let inputMaxCounterValue = target.parentElement.firstElementChild.dataset.maxCount;
  let showCounterValue = target.parentElement.firstElementChild.nextElementSibling.textContent;

  if (target.classList.contains('booking__form__counter--increase')) {
      increaseCounter();
  }

  function increaseCounter() {
    if (inputCounterValue === inputMaxCounterValue) {
      return;
    } else {
      //does not update
      inputCounterValue++;
      showCounterValue = inputCounterValue;
      //this does update
      target.parentElement.firstElementChild.value++;
      target.parentElement.firstElementChild.nextElementSibling.textContent = target.parentElement.firstElementChild.value;
    }
  }
});
<form class="booking__form">

          Arrival Date

            0

              <svg class="fal fa-chevron-up"></svg>

              <svg class="fal fa-chevron-down"></svg>

          Nights

            <input type="hidden" name="duration" value="1" data-max-count="21">
            1

              <svg class="fal fa-chevron-up"></svg>

              <svg class="fal fa-chevron-down"></svg>

          Adults

            <input type="hidden" name="adults" value="1" data-max-count="8">
            1

              <svg class="fal fa-chevron-up"></svg>

              <svg class="fal fa-chevron-down"></svg>

          Children

              <input type="hidden" name="children" value="0" data-max-count="5">
            0

              <svg class="fal fa-chevron-up"></svg>

              <svg class="fal fa-chevron-down"></svg>

</form>

UPDATED Javascript
I have had a play around and added my updated javascript below which now seems to be working ok. I removed the data attributes 'data-max-count' and just added in the 'max' attribute and changed the variable decelerations around.
let bookingForm = document.querySelector('.booking__form');
bookingForm.addEventListener('click', function (e) {
    let target = e.target;
    let input = target.parentElement.firstElementChild;
    let displayValue = target.parentElement.firstElementChild.nextElementSibling;

    if (target.classList.contains('booking__form__counter--increase')) {
        increaseCounter();
    } else if (target.classList.contains('booking__form__counter--decrease')) {
        decreaseCounter();
    }

    function increaseCounter() {
        if (input.value === input.max) {
            return;
        } else {
            input.value++;
            displayValue.textContent = input.value;
        }
    }
});

Comment: That is because in JavaScript, primitives (strings, numbers, booleans, etc.) are assigned by value not by reference.
Answer: I re-wrote your js and it now works.
You had some issues with your selectors and the way you updated the values.
I associated the max-count with the hidden input you have there and read the data-max-count attribute value. If this is not present then the auto-increment doesn't work because I set the initial value of inputMaxCounterValue equal to 0.
Keep in mind that I only update what the user sees and not the input value.
let bookingForm = document.querySelector('.booking__form');
bookingForm.addEventListener('click', function (e) {
let target = e.target;
let parentElem = target.parentElement;
let inputCounterValue = 0;
let valueContainer = parentElem.querySelector('.booking__form__counter--value');
if (typeof valueContainer.textContent!=="undefined") {
  inputCounterValue = parseInt(valueContainer.textContent,10);
}

if (target.classList.contains('booking__form__counter--increase')) {
    increaseCounter(valueContainer);
}

function increaseCounter(element) {
  let inputMaxCounterValue = 0;
  let parentElem = target.parentElement;

  if (typeof parentElem.querySelector('input')!=="undefined" && parentElem.querySelector('input')!==null) {
    inputMaxCounterValue = parentElem.querySelector('input').getAttribute("data-max-count");
  }
if (inputCounterValue === inputMaxCounterValue) {
    return;
} else {
    //does not update
    inputCounterValue++;
    showCounterValue = inputCounterValue;
    //this does update
    element.textContent = inputCounterValue;
}

Comment: thanks very much for this, it worked great. I have just updated my post with my own way as well which seemed to work ok.


Is there a way to store data from a DataReader directly into a List

Question: I'm creating a datareader from a SqlCommand and I currently store this information in a class with the following
    private object PopulateObjectWithFields(SqlDataReader read, Type className)
    {
        var gd = Activator.CreateInstance(className);
        for (int i = 0; i < read.FieldCount; i++)
        {
            var type = gd.GetType();

            var fi = type.GetField(read.GetName(i));
            if (fi != null)
            {
                if (!Convert.IsDBNull(read[i]))
                {
                    try
                    {
                        fi.SetValue(gd, read[i]);
                    }
                    catch
                    {
                        throw new Exception(string.Format("Unable to set {0}. Class type {1}. DB Type {2}", read.GetName(i), fi.FieldType.Name, read[i].GetType().Name));
                    }
                }
            }
            else
            {
                var pi = type.GetProperty(read.GetName(i));
                if (pi != null)
                {
                    if (!Convert.IsDBNull(read[i]))
                    {
                        try
                        {
                            pi.SetValue(gd, read[i]);
                        }
                        catch
                        {
                            throw new Exception(string.Format("Unable to set {0}. Class type {1}. DB Type {2}", read.GetName(i), fi.FieldType.Name, read[i].GetType().Name));
                        }
                    }
                }
            }
        }
        return gd;
    }

This works perfectly. What I would like now is to put it in a List<class>, but I can't seem to get it right to create a List<class> dynamically.
Can someone maybe help me out with the syntax?
var MyList = List<MyClass> //This should be dynamically created

using(var reader = cmd.ExecuteReader())
{
      while (reader.Read())
      {
           MyList.Add(PopulateObjectWithFields(read, MyClass));
      }
}

LET ME CLARIFY
I don't know what columns is going to be in the reader, and I don't know what class is going to be passed in. I have a generic method that needs to populate ANY reader to ANY class as long as the column names match the property of fields in the class
Comment: http://stackoverflow.com/questions/1464883/how-can-i-easily-convert-datareader-to-listt
Comment: Also note your solution can be improved in performance - you use reflection to get list of properties for every single row; you can prepare list of reflected properties upfront and reuse the mapping.
Comment: Can you make it a generic method instead of passing in the `Type` as a parameter?
Comment: I have one like that as well, I use `var gdtype = Assembly.GetExecutingAssembly().GetTypes().First(t => t.Name == className);` to get the type from a string, so it does not really matter
Comment: Guys, I need a generic way of creating the LIST. not mapping or converting anything. I want a dynamic way of creating the `List`
Comment: For just creating instance of generic list - see http://stackoverflow.com/questions/11509695/generic-list-by-using-reflection
Comment: Better to use an existing ORM than trying to create your own.
Answer: You should use generics:
private T PopulateObjectWithFields<T>(SqlDataReader read) where T : new()

The implementation of your method stays the same, except that you use T instead of MyClass, and that you can instantiate the type directly using the constructor:
var gd = new T();

From there, you can easily store your objects in your list:
var MyList = List<MyClass> //This should be dynamically created

using(var reader = cmd.ExecuteReader())
{
      while (reader.Read())
      {
           MyList.Add(PopulateObjectWithFields<MyClass>(read);
      }
}

Comment: Ok, although it is a good answer, that is not what I'm looking for. I want to create the the `List` dynamically, so I want to get a List without specifying the type. The `PopulateObjectWithFields`, although not as neat as yours, is currently working fine
Comment: @Jaques Why do you need that? Generics is the way to go.
Comment: @Jaques Oh I think I understand now. How do you get "MyClass" in first place, from a string? If so, then indeed generics don't solve your issue. But then, do you need a strongly typed list, since you don't have static typing information in first place? It's hard to tell with the bit of code your shown, but maybe a `List` is enough for your use case
Comment: I use `var gdtype = Assembly.GetExecutingAssembly().GetTypes().First(t => t.Name == className);` to get the class from a string. I've tried List but it gave me a lot of issues, specifically when I try to use the values in a combobox or something


mail gt marked as spam by gmail, any solutions?

Question: i am using php code to send a mail with an attachment in my web application. all are working fine expect gmail marked it as spam. my code is look like below.
<code>move_uploaded_file($_FILES["file"]["tmp_name"],$path . $_FILES["file"]["name"]);
        $filename = $_FILES["file"]["name"];
        //$path = "upload/";
        $from_name = $_POST['name'];
        $from_mail = $_POST['email'];
        $mailto = $replyto = "firstname.lastname@example.com";
        $subject = "Resume";
        $message = $_POST['msg'];
        $to = "firstname.lastname@example.com";

        $file = $path.$filename;
        $file_size = filesize($file);
        $handle = fopen($file, "r");
        $content = fread($handle, $file_size);
        fclose($handle);
        $content = chunk_split(base64_encode($content));
        $uid = md5(uniqid(time()));
        $name = basename($file);
        $header = "From: ".$from_name." <".$from_mail.">\r\n";
        $header .= "Reply-To: ".$replyto."\r\n";
        $header .= "MIME-Version: 1.0\r\n";
        $header .= "Content-Type: multipart/mixed; boundary=\"".$uid."\"\r\n\r\n";
        $header .= "This is a multi-part message in MIME format.\r\n";
        $header .= "--".$uid."\r\n";
        $header .= "Content-type:text/html; charset=iso-8859-1\r\n";
        $header .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
        $header .= $message."\r\n\r\n";
        $header .= "--".$uid."\r\n";
        $header .= "Content-Type: application/octet-stream; name=\"".$filename."\"\r\n"; // use different content types here
        $header .= "Content-Transfer-Encoding: base64\r\n";
        $header .= "Content-Disposition: attachment; filename=\"".$filename."\"\r\n\r\n";
        $header .= $content."\r\n\r\n";
        $header .= "--".$uid."--";
        if (mail($mailto, $subject, "", $header)) {
            echo "mail send ... OK"; // or use booleans here
        } else {
            echo "mail send ... ERROR!";
        }
</code>
Please help me
Answer: the mail() function isn't exactly known to create the most perfect mails . Spam filters are very picky about mail headers, it's no easy task to build them all correctly yourself. better use a smtp library that creates the mail messages with all important headers (like phpmailer )
also make sure the server you send the mails from has a good IP reputation and correct mail setup (HELO / reverse DNS  etc)


SubConsulta MySql

Question: Tenho uma tabela de funcionários que tem apenas três colunas, NOME, CARGO e SALARIO, quero montar um consulta que me traga toda esta tabela e nela contenha o maior valor de salário para o cargo. Totalizando 4 Colunas (NOME, CARGO, SALARIO e MAIOR_SALARIO_P_CARGO. Isto é para verificar a variação.
Comment: Dê mais informações. Qual a tabela onde está o quarto campo. Qual a relação entre elas?
Comment: Dica: para editar esta pergunta, use o link de [edit] acima.
Answer: SELECT
    T1.NOME,
    T1.CARGO,
    T1.SALARIO_ATUAL,
    (
        SELECT MAX(SALARIO_ATUAL)
        FROM TABELA T2
        WHERE T2.CARGO = T1.CARGO
    ) AS MAIOR_SALARIO_PARA_CARGO
FROM TABELA T1

Answer: Respostas:
SubQuery
SELECT a.nome, a.cargo, a.salario, (select max(salario) from tbsalarios b where b.cargo = a.cargo) maiorsalario FROM tbsalarios a

JOIN
SELECT a.nome,
       a.cargo,
       a.salario,
       b.maior
FROM tbsalarios a
LEFT JOIN
      (select max(salario) maior, cargo from tbsalarios group by cargo) as b on b.cargo = a.cargo

SubConsulta MySql


Rails beginner config/routes.rb issue

Question: I am having a little trouble understanding what config/routes actually routes to. For example lets say I started a brand new project and generated a Users controller and edited my config/routes.rb to look like this:

config/routes.rb

SampleApp::Application.routes.draw do

match '/signup', to: 'users#new'

end

I start the server and as expected, it says I don't have a "new" action in my Users controller. I create one:

 users_controller.rb

 class UsersController < ApplicationController

 def new
 end

I refresh the page and as expected it tells me I need a users/new template. So my question is: do my view templates always have to be the same as the controller and action names in "(controller name)/(action name)" format (in this case users/new.html.erb)? Is it not possible to name my template something random (e.g. users/rubyonrailsmeetup.html.erb instead of users/new.html.erb) if have a controller action linked to one of the site's functions?
Also, does adding "resources :users" to config/routes.rb by default match the view template file names with the behavior I mentioned above so that views must be named after their "controller/action" names?
Sorry for the bother, I'm just trying to figure out what's part of Rails' magic and what isn't.
Answer: Rails attempts to render the template with the same name as the action by default, if no other render or redirect is invoked in the controller action. Basically, there's an implicit render :action at the end of every controller action.
But you can override this easily enough by adding an explicit render, e.g.,
render :rubyonrailsmeetup

Edit for clarity: this call to render goes in the controller code, not in config/routes
Comment: Also, it's just `render :rubyonrailsmeetup` if the view `rubyonrailsmeetup.html.erb` is in /views/users -- you don't need to specify that it's a users template. You *can*, however, render a view from a directory that isn't users by specifying the path (relative to /views/), e.g., `render 'events/rubyonrailsmeetup'` would look for views/events/rubyonrailsmeetup.html.erb
Comment: ooooo so it would be `match '/signup', to: 'users#new', render :users/rubyonrailsmeetup` to override the default, which is `render :users/new` in this case?
Comment: you can add the render line at the end of the action... if you want to override
Comment: ahhh I am starting to understand. thanks guys. so the config/routes goes to the controller first, and if there is no `render` in the action, then by default it just goes to the views with the filename "(controller)/(action).html.erb" correct?
Comment: Yep, you got it. Also, a redirect will prevent it from rendering that template as well (as you'd probably expect).
Answer:
do my view templates always have to be the same as the controller and action names in "(controller name)/(action name)" format

These are defaults, you can render any view from the action by giving render :view_file_rel_path at the end of the action

does adding "resources :users" to config/routes.rb by default match the view template file names

Anything added in routes.rb is directly related upto controllers only, i.e. it matches the request and maps it to the controller/action. Logic of view comes only inside the action code
Comment: but a lot of the time the actions in the controller are left blank (e.g. for static pages that require no interaction with the database). so in those cases the view would be determined by the "default" you're meaning right?
Comment: yup the view to be rendered is always determined by the default i.e. 'controller_name/action_name.html' unless you have written `render` explicitly in your action..

Rails beginner config/routes.rb issue


How to import the node class into a title field of a view?

Question: I installed the Node Class module. I have a view, where the node class should be imported into the title field of the view.
How can I achieve this?
Answer: As far as I understand, you want to add a class name to the title field of your nodes listed in a view. (1) Views provide this functionality by default:

Adds the class to the selected html element,  is by default.
It can be used as a field wrapper.
(2) In case this is not suitable for you, you may very well use view's "rewrite results" :

It can be used to wrap the field's text.
(3) Lastly there is always the preprocess_views_view_fields solution where you can edit your field's attributes:
if($view->name == 'view-name') {
  $vars['fields']['title']->wrapper_prefix = '
';
}

It can be used as a field wrapper.
Comment: The thing is, for each node the used class may be different, or some times no class may be used.

in that case, how it will update dynamically for each node titles in the views.

what i actually want is, I need to highlight some entries highlighted in a calendar view. for that, i planned to use dynamic class
Comment: @JaseerKinangattil, this is far far away from your original question...However the (3) case will meet your needs. Place all your logic in that hook. You must have some logic that decides when to add a class or not. If that logic is based on the field of the [node_class](https://www.drupal.org/project/node_class) module, you can [node_load](https://api.drupal.org/api/drupal/modules!node!node.module/function/node_load/7) the node you like (use this `$view->result[0]->nid`) and retrieve any class from there. Then add any class or leave blank to/the `wrapper_prefix`


Declaration and assigning value to a variable inside the scope and trying to obtain it from the ouside doesn't work while only assigning does

Question: After along gap, I've returned back to learning JavaScript. Here is an example of what I was trying to say in the title
function randomFunction(){
   for(i = 0; i < 10; i++){
      x = i;
   }
   return x;
}

console.log(randomFunction());

This returns the value of x without any error but instead of x = i, if I used let x = i;, now x is undefined error is shown. It is defined, right? I mean let x = 5; defines and assigns value both at the same time, then shouldn't let x = i do the same? Or can I only assign values and not variables to x (i being another variable).
Plus I had another question as well, can you call a function, that first was declared as a function which accepts parameters, without providing any parameters? for example,
function randomFunction(x){
   return "Hello World";
}

console.log(randomFunction());

While testing that specific function only, I do get Hello World in return but when I use similar idea in other projects, I get some sort of error (I can't remember what the error was though). I just wanted to know can I do that? So that I can rule that out as not being the problem and look for bug somewhere else.
Comment: `"num1 + num2"` is a literal string.  `this.num1 + this.num2` is an expression.
Comment: It's important to explain what you mean by "working". What did you expect to happen? What did happen? In your example, variables are undefined, the code doesn't run for reasons other than you're asking about, so there are roadblocks you're putting up to people actually helping--but yes, likely the problem is you're using a string when you meant to write a JS expression (possibly among other things--who knows?). See [mcve].
Comment: `this.result = "num1 + num2";` assigns the literal string `"num1 +  num2"`, as I'm sure you've observed. You need it without the quotes if you want to actually add two numeric values. (That still won't work but I'll leave you to figure that out yourself.)
Comment: shouldn't the output should be num1 + num2 then. Still not working
Comment: Check the other comments. Plus you added the click listener to an empty `p` tag - are you clicking the button expecting it to work?
Comment: To get button element you need `document.getElementById("button")`
Comment: All of a sudden, it's working now. What an embarassment!!
Comment: @Taplar `"num1 + num2"` is also an expression.
Comment: @DavidConrad Not a mathematical one.
Answer: So a couple of things went wrong here:

Don't use the literal string "this.num1 + this.num2" but use the expression that take the variables and sum them together this.num1 + this.num2.
You used event listener on element that is not appeared on the screen, so how can you click it? You probably meant to use the click event on the id button and not the demo.
As a  rule of thumb, I don't think it's good to involve UI logic with your classes logic. For future use, it usually better to keep them separated.

Good Luck

class Sum {
  constructor(num1, num2) {
    this.num1 = num1;
    this.num2 = num2;
  }

  add() {
    this.result = this.num1 + this.num2;
  }
}

const s = new Sum(6, 7);
document.getElementById("button").addEventListener("click", () => {
  s.add();
  displayResult(s.result);
});

function displayResult(result) {
  document.getElementById("demo").innerText = result;
}
<button id="button">Click</button>

Answer: You don't nee the quotes in the add function and you are missing. this before the nums
this.result = this.num1 + this.num2

But as you are passing in strings to the constructor it will just concatenated the values so the output will be "ab"
If those were supposed to be variables it should be:
var a = 5;
var b = 7;

const s = new Sum(a, b);

Answer: Here your code:

class Sum {
  constructor(num1, num2) {
    this.num1 = num1;
    this.num2 = num2;
  }

  add() {
    this.result = this.num1 + this.num2;
  }

  displayResult() {
    document.getElementById("demo").innerText = this.result;
  }
}

const s = new Sum("a", "b");
document.getElementById("button").addEventListener("click", () => {
  s.add();
  s.displayResult();
});
    <button id="button">Click</button>


What is synthetic geometry?

Question: What is synthetic geometry? Could you provide a short (i.e. a paragraph or two, not much longer) explanation in general elementary terms? In particular, I hope to be able to understand the contrast between synthetic and analytical (invariant-theoretic?) approaches in the end.
Wikipedia's definition is a bit too advanced for me.
Comment: @rghthndsd Wikipedia's definition is too advanced. I don't really understand the difference between analytical and synthetic as it is discussed in that article.
Comment: Have you tried Wikipedia?
Comment: I assume you want an explanation that differs from [wikipedia](http://en.wikipedia.org/wiki/Synthetic_geometry). Or perhaps wikipedia is too advanced? Please be more specific.
Comment: do you know how to do geometry with coordinates?
Comment: "Synthetic" just means *axiomatic* in this context.
Answer: Depending on the education you've had, the difference is likely basically that between your school algebra and geometry courses. In a first geometry course you usually get a list of axioms for points and lines (a straight line segment can be drawn between any two points ,etc.) Then you create proofs of properties of figures in the plane using these axioms, without ever writing down any algebraic equations. Specifically, you never use coordinates on the plane in doing this sort of geometry, which is what is called synthetic.
The ancient Greeks took synthetic geometry in the plane and 3-dimensional space to an amazing level, much further than almost anyone learns today. For example, they understood the "conic sections," that is, parabolas, ellipses, (circles,) and hyperbolas, almost completely. But today you usually think of a parabola, for instance, as being the graph of an equation
$y=ax^2+bx+c$. It's this equation, which requires choosing a pair of coordinate axes on the plane and a unit length on each axis, that's what analytic geometry uses that synthetic geometry avoids. The synthetic-analytic distinction is still very visible in modern geometric research, even though the particular questions of interest have changed drastically.

What is synthetic geometry?


what's the `4161` modifier mean in java.lang.reflect.Method

Question: i'm using java reflection to get method which are annotated with a specific Annotation . it returns two method , the one with modifier 4161 belongs to the interface . but i check the modifier specifications and can't find it anywhere ... help needed , tks :)
Comment: i didn't realise `4161` is a combination modifier and i've googled `4161`  no relative result found at all .  the duplicate you post is for those who have already know combination modifier .
Answer: The modifiers integer is basically a combination of integer flags that form a bit field. You can use the static Modifier.toString() method to get a textual representation. If you would use this method, it would tell you that 4161 stands for public volatile, and it would be wrong.
To break it down, the bit field represented by 4161 is composed of 3 integer flags: 1, 64 and 4096. Looking up these values in the Modifier Javadoc, it will tell you that 1 stands for public and 64 stands for volatile. Surprising, because methods cannot be declared as volatile, and what about 4096? It's not even in the list!
The answer can be found in the JVM specification, where we find that:

4096 (0x1000) indicates a synthetic method, i.e. a method that is not present in the source code.
64 (0x0040) not only represents the volatile access modifier, but can also be used to signify that a method is a bridge method, i.e. a method that is generated by the compiler.

The conclusion is then that a method with a modifiers value of 4161 is a public synthetic bridge method. This article provides a fairly comprehensive overview.
Comment: @Vulcan Appears to be a synthetic flag: https://stackoverflow.com/questions/8540768/when-is-the-jvm-bytecode-access-modifier-flag-0x1000-hex-synthetic-set Will add to answer.
Comment: It's probably not a volatile method, but a bridge method. The value 0x40 is defined twice, once as `VOLATILE`, once as `BRIDGE`. See explanation [here](http://stas-blogspot.blogspot.com/2010/03/java-bridge-methods-explained.html). You could call `Method.isBridge()` to find out.
Comment: The `public` bit is `0x0001` and the `volatile` bit is `0x0040`, so what's the other `0x1000` bit correspond to, where (`4161` is `0x1041`)? The greatest bit in the [modifier values](https://docs.oracle.com/javase/7/docs/api/constant-values.html#java.lang.reflect.Modifier.ABSTRACT) is only `0x0800`.
Comment: thanks for your reply ,  can you give a further explanation about `public volatile` , is this identify the `public` method in `Interface` ?