Finding the volume by Shell method: $y=x^2, y=2-x^2$ about the line x=1

Question: Finding the volume by Shell method: $y=x^2, y=2-x^2$ about the line x = 1
what I get from this after graphing is:
$2\pi \int (1-x)(2-2x^2)dx $
which becomes: $2\pi \int (2-2x^2-2x+2x^3)dx $
integrating that I get:
$2\pi[2x- \frac23x^3-x^2+\frac12x^4]   $ from 0 to 1
my answer is $\frac53\pi$ but my book says the answer is : $\frac{16}3\pi$
could someone tell me where I went wrong? was it the upper lower bounds?
Answer: Hint: the region in the $xy$-plane bounded by the graphs $y=x^2$ and $y=2-x^2$ is symmetric about the $y$-axis, so the projection of this region onto the $x$-axis should be a symmetric interval of the form $[-a,a]$. In this case the points of intersection of the graphs have $x$-coordinates $x=\pm 1$. Thus, your limits of integration should really be from $x=-1$ to $x=1$, not $0$ to $1$.
Comment: Sorry, what I meant to say is, isn't it symmetric about $y = 1$?
Comment: $y= 2-x^2 = x^2$ when $x=\pm 1$ I agree with though.
Comment: @DisplayName Yes it is, but we're not really interested in that symmetry for this problem.
Comment: I was just referring to "is symmetric about the $y$ -axis". Oh I just realised it was meant to say $x$ axis.
Comment: couldn't you do it for one side? from 0-1 since it is symmetrical?
Comment: @Joshhw No you can't, because the integral is not symmetric. Only the region of integration is.
Answer: The limits of the integration is given by where the lines cross each other:
$$ x^2=2-x^2 \Longleftrightarrow x=\pm1 $$
so the limits shold be from -1 to 1.


Assertion fail with Open CV

Question: I'm new to openCV and am trying to get openCV to work my USB webcam on Win7 with Python 3.8. I've got the basic tutorial from here modified from Raspberry Pi cam by the same author here.
which is:
#!/usr/bin/python3

import time
import numpy as np
import cv2

#point to the haar cascade file in the directory
cascPath = "haarcascade.xml"
faceCascade = cv2.CascadeClassifier(cascPath)

#start the camera
video_capture = cv2.VideoCapture(0)

#give camera time to warm up
time.sleep(0.1)

#start video frame capture loop
while True:
  # take the frame, convert it to black and white, and look for facial features
  ret, frame = video_capture.read()

  gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

  # use appropriate flag based on version of OpenCV
  if int(cv2.__version__.split('.')[0]) >= 3:
    cv_flag = cv2.CASCADE_SCALE_IMAGE
  else:
    cv_flag = cv2.cv.CV_HAAR_SCALE_IMAGE

  faces = faceCascade.detectMultiScale(
    gray,
    scaleFactor=1.1,
    minNeighbors=5,
    minSize=(30, 30),
    flags=cv_flag
  )

  #for each face, draw a green rectangle around it and append to the image
  for (x, y, w, h) in faces:
    cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)

  #display the resulting image
  cv2.imshow('Video', frame)

  #set "q" as the key to exit the program when pressed
  if cv2.waitKey(1) & 0xFF == ord('q'):
    break

# clear the stream capture
video_capture.release()
cv2.destroyAllWindows()

It should run out of the box, but I get the error below and I'm not sure why. CV_flag and gray have data and the other parameters are filled. Any ideas.
C:\Users\Ghoul>py D:\LearnPython\open_cv_face_track_test.py -3.8
[ WARN:0] global C:\projects\opencv-python\opencv\modules\videoio\src\cap_msmf.cpp (674)
SourceReaderCB::~SourceReaderCB
 terminating async callback
Traceback (most recent call last):
  File "D:\LearnPython\open_cv_face_track_test.py", line 31, in <module>
    faces = faceCascade.detectMultiScale(
cv2.error: OpenCV(4.1.2) C:\projects\opencv-
python\opencv\modules\objdetect\src\cascadedetect.cpp:1689: error: (-215:Ass
ertion failed) !empty() in function 'cv::CascadeClassifier::detectMultiScale'

Comment: Sounds like it is this problem: https://stackoverflow.com/q/30508922/771848
Comment: you have to use full path to `xml` - lucky there is variable with folder name `cv2.data.haarcascades` - `cv2.CascadeClassifier( os.path.join(cv2.data.haarcascades, cascPath) )`
Comment: Turns out that haarcascade.xml doesn't exist for 2.2 I'm using haarcascade_frontalface_default.xml instead. Let's hope that's ok.
Answer: The faceCascade classifier is empty, which means it was unable to retrieve the classifier from the path provided.
You can replace the line
cascPath = "haarcascade.xml"

with:
cascPath = '../../haarcascade.xml'

where you provide the full path of the xml file for cascPath.

Assertion fail with Open CV


What is the command to load a Soft Input Panel DLL in Windows Mobile 6.5?

Question: I'm trying to test and later build some existing, very old code for a custom soft input panel DLL on Windows Mobile 6.5.
When I compile the code to test in Visual Studio 2008 -- the last version which supports the old eVC project file -- I get a message indicating that only a DLL has been produced and as a result it cannot be executed directly. However, the IDE advises me that I can specify a command to load the DLL. What command should I be using to load a soft input panel DLL?
Answer: The input panel's in Windows CE aren't loaded by any specific program, they're loaded by the OS itself (likely by GWES, but you'd have to walk the CE sources to verify that if you really, really want to know).  The net result of that is that you can't set any "command line" in the debugger to get it to load your SIP.  The downside is that you can't get use the debugger (you could use the Platform Builder debugger if it was generic Windows CE and you had a BSP).
To "register" your InputPanel, you simply need to create the approprate registry entries (documented in MSDN)
<code>HKEY_CURRENT_USER\CLSID\{your object CLSID}
    InprocServer32=reg_sz:"\\Windows\\mysiplib.dll"
    IsSIPInputMethod=reg_sz:"1" ;note this is a string, not a dword
    DefaultIcon=regsz:"\\Windows\\mysiplib.dll,0"
</code>
To get it to "appear", you probably have to go into the Control Panel, under Setings->Personal->Input.
Once loaded, you can't unload the SIP without removing the registry entries and then a soft reset.
Comment: ctacke, I followed your suggestion above on CE7, but when I select my customized SIP keyboard in the Control Panel->Input Panel, it does not save my selection because when I go back to check by opening Control Panel->Input Panel again it uses the default keyboard.  Does that mean my customized SIP dll does not work? thanks
Comment: Sounds like your SIP is not loading.  Maybe it has an error and is failing?
Comment: thank you for responding.  So I have the SIP project that has been working for Windows Mobile and CE6, and now I'm just porting it to CE7 without changing any code except adding new project configuration to compile for CE7 and I can build it successfully with VS2008.  How can I check if the dll cannot load or it has error because I don't receive any feedback from Control Panel->Input Panel.
Comment: Strange.  If it worked under CE 6, I would expect it to still work.  I'd be inclined to look in the WEC 7 source for it's SIP and see if maybe the registry key that it's looking at changed or anything along those lines.  I'd also try the CE 6.0 binary directly under WEC 7
Comment: That is what I am afraid of that they change the registration location, but I haven't found any documentation on Windows Embedded 7 that explains about CE7 SIP.
Comment: I think I need to add one new registry for it to work and it's in HKEY_CURRENT_USER\SIP\Installed"{my object ID}"


Problema com missings na variável peso em amostragem complexa

Question: A presença de missings na variável peso de uma amostragem complexa está impedindo o R de calcular a média. Inicialmente tentei o na.rm = TRUE, porém não deu certo, segue trecho:
svymean(basedados$variavel , svydesign( id = basedados$estrato , weight =
    basedados$peso ),na.rm=TRUE)

Erro em na.weight(data.frame(weights)) : missing values in `weights'

Também testei esta versão e nada:
svymean(dp$Dcoracao , svydesign( id = dp$V0024 , weight = dp$teste , na.rm = TRUE
    ),na.rm=TRUE)

Erro em na.weight(data.frame(weights)) : missing values in `weights'

Depois foi sugerida outra forma, a qual mostra outra mensagem de erro, segue trecho:
svymean(bd$Dcoracao , svydesign(id = bd[which(!is.na(bd$teste)),"V0024"], weight =
   bd[which(!is.na(bd$teste)),"teste"]))

Erro em tapply(1:NROW(x), list(factor(strata)), function(index) { :
    arguments must have same length

Além disso: Mensagens de aviso perdidas:

In x * pweights :
comprimento do objeto maior não é múltiplo do comprimento do objeto menor
In x * pweights :
comprimento do objeto maior não é múltiplo do comprimento do objeto menor
Comment: Já tentou limpar a base antes de usá-la em `svymean` e `svydesign`? Declare uma variável `temp = bd[!is.na(bd$peso),]?` e então rode a pesquisa em cima desses valores.
Comment: Henrique, seria possível colocar os resultados de `summary(bd)`, `str(bd)` na sua pergunta?
Comment: @CarlosCinelli, o problema era mesmo apresença de missings na variável atribuída como Weight, já que eu tinha apenas 12 missings em 62000, transformei-os em zero e continuei. Obrigado pela atenção
Comment: @HenriquePizarro responda a sua pergunta com solução que você encontrou, para não deixar sem resposta.
Comment: @CarlosCinelli, obrigado pelo aviso, sou novo nesta comunidade.
Answer: Aparentemente a variável atribuída ao parâmetro weight não pode conter missings. No meu caso em particular a base continha apenas 12 casos de 62000, portanto atribuí zero aos missings e o comando funcionou normalmente.


GCP - Remote access to server in a different ipsec connection

Question: We would like to access a remote server (customer infrastructure) from our Google Cloud Platform via our on-permises infra (where IPSec is already configured to access to costumer).
Big picture of current solultion
We already configured a GCP route to the remote server using tunnel as next hop but with no success.
Any idea of the way to achieve this?
Answer: Basing in the topology you are sharing:
GCP -> On-prem DC -> Customer DC
You basically need to make sure GCP Cloud VPN configuration from GCP to On-prem DC is properly set up according to the following documentation:
a) Cloud VPN Best Practices.
b) Assuming you are using Dynamic Routing as your type of Cloud VPN in GCP (which is the most recommendable one), double check creation steps, like required permissions and so on.
c) The follow-up steps are very important as well, such as configuring the correct firewall rules on GCP and on-premises. And setting up the on-premise VPN gateway and tunnel properly according to the device/brand you use on-prem.
d) Since you mention you are using IPSec, please make sure which IKE version you are using in GCP and on-prem, and to abide to the GCP exact values for Phase 1 and 2.
Answer: Based on your question I can assume that you have:

working VPN between your on-premise dc and GCP
working VPN between your on-premise DC and customers DC

You said that you can't connect from GCP to the customer's network. That means traffic going from GCP to customer gets dropped at some point - either due to improper routing or much simpler thing like firewalls (check GCP Firewall in particular to make sure it doesn't block the traffic).
Double check those because one of them is the culprit here.


proportion of primes in a polynomial sequence

Question: It is conjectured (Bunyakovsky) that when $P(x)$ is a polynomial from $\mathbb{Z}[X]$, irreducible, with positive leading coefficient and so that the integers $P(n)$ , $n\gt0$  do not share a common factor different from $1$, then there are infinitely many primes in the sequence $P(n)$ , $n\gt0$ .
But what about the proportion (density) of those primes? It seems that it can vary a lot, even when the degree of the polynomial is not changed.
For instance, for degree $10$, let $$P(x)=1-x+x^2-x^3+x^4-x^5+x^6-x^7+x^8-x^9+x^{10}$$
and  $$Q(x)=-691+2073 x-287 x^2-3285 x^3+1420 x^4+2310 x^5-1190 x^6-1050 x^7+525 x^8+525 x^9+105 x^{10}$$
there are more than $60$ values of $n$ below $1000$, for which $P(n)$ is prime, whereas in the same range, $Q(n)$ is prime only when $n=129$ or $n=539$.
Can somebody find another such polynomial sequence, with an even lesser proportion of primes?
Comment: Certainly, the frequency will depend on how many roots of the polynomial modulo $2$,$3$,$5$, etc. For example, if $p(x)$ has no roots modulo $2$, that will be very different from the case where $p(0)$ or $p(1)$ is even, since we will won't even be able to try half of the values $n$. Same can happen for $p=3,5$. Etc. You can can force it so that there are no values under $1000$ just using Chinese remainder theorem.
Comment: If you continue the calculation out far enough, the density of primes represented by any univariate polynomial should be zero. Nothing to prevent one polynomial doing much better than another one initially.
Comment: I think there is a generalized version of Szemeredi's Theorem for polynomials by Vitaly Burgelson that you would be interested in.
Comment: $n^6+1091$ is composite for all $n$, $1\le n\le3095$, but prime for $n=3096$. $x^{12}+488669$, similarly, for $n=616980$. You probably want to look up the Bateman-Horn conjecture.
Comment: @SandeepSilwal Bergelson*
Comment: @GerryMyerson $n^6+1091$ is first prime for $n=3906$, not 3096.
Comment: @Rosie, yes. Apologies for the typo.
Answer: Chinese remainder theorem.
Pick $R(x)$ with positive coefficients so that $$\begin{align}
R(x)&\equiv x^9(x-2)\pmod 3\\
R(x)&\equiv x^7(x-1)(x-2)(x-3)\pmod 5\\
R(x)&\equiv x^5(x-1)(x-2)(x-4)(x-5)(x-6)\pmod 7\\
R(x)&\equiv (x-1)(x-2)(x-3)(x-4)(x-5)(x-6)(x-7)(x-8)(x-9)(x-10)\\&\equiv x^{10}-1\pmod {11}
\end{align}
$$
Then $R(n)$ will be divisible by one of $3,5,7,11$ unless $n\equiv 1\pmod 3,4\pmod 5,$ etc. This means the only $n$ we need to check is $n\equiv 1144\pmod {1155=3\cdot5\cdot7\cdot 11}$. So in particular, $R(n)$ is not prime for $n=0,1,2,3\dots,2298$.
Note, the above polynomials are not hard to compute, since, for example, $$\begin{align}
(x-1)(x-2)(x-4)(x-5)(x-6)&\equiv\frac{x^6-3^6}{x-3}
\\&\equiv x^5+3x^4+3^2x^3+3^3x^2+3^4x+3^5\\
&\equiv x^5+3x^4+3x^3+6x^2+4x+5\pmod 7
\end{align}$$
On the other hand, your first $P(x)$ is the polynomial for the primitive $22$nd roots of unity, which means that if $p\mid P(n)$ then $n$ is a primitive $22$nd root of unity, modulo $p$. That can only happen if $p\equiv 1\pmod {22}$, so, in particular, $P(n)\equiv 0\pmod {2,3,5,7}$ is not possible, and the only eliminated value modulo $11$ is $10$. This gives a far larger set of prospective value of $n$.
Comment: thank you. I have to look carefully to your detailed explanation, since I am not very familiar with the congruences for polynomials. I think I understand the general idea though.
Comment: Does this mean that as long as there is no limit constrain on the degree, it is possible to find a integer polynomial that take infinitely many prime values, but with the first one being as big as one want?  and what about the case when the degree of the polynomial is limited?
Comment: As far as I know, we don't know that *any* polynomial of degree $2$ or more takes infinitely many prime values, so it's hard to answer that question.
Comment: ok. I should say "as long as there is no limit constrain on the degree, it is possible to find an integer polynomial that _conjecturally_ take infinitely many prime values, but with the first one being as big as one want...".
Comment: well, now I think that this should be true even when the degree of the polynomial is fixed, under the assumption that there is no bound to the gap between two consecutive primes. right?
Answer: The single-polynomial case of the Bateman-Horn conjecture says that if $f$ satisfies the Buniakowsky conditions then the number of integers $n$, $1\le n<x$, such that $f(n)$ is prime is asymptotic to $C(f)n/\log n$, where $$C(f)={1\over{\rm deg}\,f}\prod_p\left(1-{1\over p}\right)^{-1}\left(1-{N_f(p)\over p}\right)$$ where the product is over primes $p$, and $N_f(p)$ is the number of solutions of $f(n)\equiv0\pmod p$.


What fingering to use for Ornithology on piano?

Question: I'm trying to play ornithology on piano and was wondering what fingering would be best for the first line. Whatever I try seems uncomfortable...
Thanks!
Answer: The "obvious" fingering would be
2 | 1 2 3 4 - 5 3 4 5 4 | 3 1
If you don't like that, you could try starting with your thumb. Then play another note with your thumb under your fingers, so you don't run out of fingers before your get to the top note - i.e.
1 | 2 3 1 4 - 5 3 4 5 4 | 3 1 or
1 | 2 1 3 4 - 5 3 4 5 4 | 3 1
or you might prefer
1 | 2 3 1 3 - 4 2 3 4 3 | 2 1 or
1 | 2 1 2 3 - 4 2 3 4 3 | 2 1
Answer: Start with your thumb on the D and then move it up to G and play the rest in that position. It might take a bit of work to transition cleanly, but that is the easiest way.
Answer: Apart from the anacrucis D, the first phrase ranges between G and the upper D. All that can be played with thumb on G, up to pinky on D. The easiest seems to be to play the first D and move the whole hand sideways to the new position.


Shortest path in directed graph with cycles of negative length

Question: Is there an algorithm for finding the shortest path in a directed graph which includes cycles of negative length? The constraint is that each node can only be visited once, so the solution exists.
I'm aware of the Bellman-Ford algorithm, but it fails when negative cycles are present. It's also clear that traversing negative cycles forever makes the problem ill-defined, so I'm constraining the path to visit each node at most once.
Is there such an algorithm? And is there an off-the-shelf implementation I can use?
---EDIT---
As requested below, here's the actual application:
Given an input image containing handwriting, I can estimate probabilities of stroke directions at each pixel:

Then, I can put the pixels into a graph, and find the path of the pen:

See how the "l" is missed out? If I can set the adjacent weights to be negative, the optimal path will traverse all letters. But negative weights create negative cycles.
Comment: There is probably a better explanation but here is a counter-example where there is no efficient solution: Assume all link cost are negative. Then your problem boils down to [finding the longest path](https://en.wikipedia.org/wiki/Longest_path_problem) (collecting as many negative cost as possible) which is NP-hard.
Comment: `And is there an off-the-shelf implementation I can use?` - most probably but it depends on the language you are working on. Python should have one of those off the shelf.
Comment: @SomeDude I'm language agnostic, python is fine. But what's the algorithm?
Comment: @SaiBot NP-hard problems can still have decent solutions for average-case complexity, and my graphs aren't fully connected. Is there an algorithm you know?
Answer: You are right that the Bellman-Ford algorithm fails in this case. You can refer section 2 of this resource. It discusses the problem for an undirected graph and works based on Edmonds' Minimum Weight Perfect Matching Algorithm. In fact, you might be interested in this question, which is very similar to yours.
When the graph is a directed one, then as @SaiBot pointed out, the problem reduces to an NP Hard problem, and there is no efficient solution possible.
Comment: Not exactly, but they are related in the sense that the Hamilton Path Problem can be reduced to the longest path problem. You might be interested in [this wikipedia article.](https://en.wikipedia.org/wiki/Longest_path_problem#NP-hardness)
Comment: Interesting. So is this the "Hamilton Path Problem"?


How to calculate mutual information

Question: I study about Mutual Information but I confuse about that. I study in this paper that mutual information is:$$I(x,y)=\iint p(x,y)\log\frac{p(x,y)}{p(x)p(y)}\,\mathrm dx\mathrm dy,$$
where $x, y$ are two vectors, $p(x,y)$ is the joint probabilistic density, $p(x)$ and $p(y)$ are the marginal probabilistic densities. MI is used to quantify both the relevance and the redundancy.
For understanding the MI, I have provided a small dataset like this:
$$
\begin{matrix}
&f_1&f_2 &f_3\\
c_2  & -1 & 0 & 1\\
c_1  &  0 & 1 & -1\\
c_1 &  1 &-1 & 0\\
c_2  &  0 & 1 & 1
\end{matrix}
$$
where $f_1,f_2,f_3$ are 3 features for classification and $c_1, c_2$ are my classes.

How can I calculate  joint probabilistic density, $p(x,y)$ in this example?
Can any one explain how can i calculate mutual information in this example using of above equation, $I(x,y)$?
Answer: Take the first feature $f_1$ and build the join histogram $(feature\ state,class\ state)$. Your features have $3$ possible states $\{-1,0,1\}$, classes have $2$ possible states $\{c=1,c=2\}$. To build the histogram simply count the join occurrences:
\begin{array}{|c|c|c|}
\hline
 & c=1 & c=2 \\
\hline
f_1=-1 & 0 & 1 \\
\hline
f_1=0 & 1 & 1 \\
\hline
f_1=+1 & 1 & 0 \\
\hline
\end{array}
You see that $f_1=0$ is uninformative, because $c=1$ or $c=2$ are possible with equal probability. However if $f_1=-1$, with the data we have, it is a priori $c=2$ (because you have zero count for $c=1$). Mutual informative exactly quantify this. To compute it, you must first normalize your 2D histogram such that $\sum h_{ij}=1$ and you must compute marginals $p(feature)$ and $p(class)$
$$
p(feature,class)=\left(\begin{array}{cc}
0 & \frac{1}{4} \\
\frac{1}{4}  & \frac{1}{4} \\
\frac{1}{4} & 0 \\
\end{array}\right),\ p(feature)=\left(\begin{array}{c}
\frac{1}{4} \\
\frac{1}{2} \\
\frac{1}{4} \\
\end{array}\right),\ p(class)=\left(\frac{1}{2},\ \frac{1}{2}\right)
$$
then compute: $I(x,y)=\int\int p(x,y) \frac{\log p(x,y)}{ p(x) \cdot p(y)}dxdy$ as follows:
$$
I(feature, class)=\sum_{i=1,2,3}\sum_{j=1,2}p(feature\ i,class\ j)\log\frac{p(feature\ i,class\ j)}{p(feature\ i)p(class\ j)}
$$
Then repeat the same computation for feature $f_2$ and $f_3$. The one with the highest mutual information is the most discriminative for guessing the class.
Answer: Sure. You have 3 natural bins, $\{\{-1\},\{0\},\{1\}\}$ (sometimes the bin-division is not so easy. It can even be the hardest part, say for example you have floating point numbers and no natural bounds of data.).
Discrete set makes our double integral a double sum.
Let us estimate $p(x,y)$
we start $f_1,c_1$: we have two measurements, one 0 and one 1, density becomes $\{0,1/2,1/2\}$
Now do the same for all others.
For $p(x)$ we just count all $f_1$ regardless of $k$ in $c_k$:
for 1: we have 1 "-1"s, 2 "0"s and 1 "1"s this gives us density $\{1/4,2/4,1/4\}$ for $f_1$. Now continue for the others.
For $p(y)$ you do the same counting but row-wise instead of column-wise.
Once you have calculated estimates for $p(x,y)$, $p(x)$, $p(y)$, you just plug in the values and calculate the double sum.
Comment: Thanks so much, you say " we have two measurements, one 0 and one 1, density becomes {0,1/2,1/2}", Can you give me how? I think it must be {1/2,1/2}
Comment: @Saeed : We observe value 0 and 1 once each. 2 observations in total. Then we guess probability for 0 is 1/2 and probability for 1 is 1/2 (and probability for -1 is 0/2)
Comment: We have 3 bins, we must have 3 values in value space of density function.

How to calculate mutual information


The function $g$ is such that $g(x) = 3x^2 - 12$ for $x <q$, find the greatest possible value of $q$.

Question: This question is from CIE A Level Maths (9709) May/June 2016 Q10ii.
The answer is $q = -2$, but I don't get how it is done.
Anyone, please help me and explain to me. Thank you.
Comment: Nothing prevents $g(x)=3x^2-12$ for all $x\in \Bbb R$, so $q$ is not bounded in any way
Comment: Surely there is more to the question than that.
Comment: The question makes no sense.  You can set q to anything and say the function is that for any value of x less than q.  There is no restriction or criterion.  The question simply makes no sense.
Comment: Is there any more information given? It seems like more information is necessary for the solution.
Comment: There are so many past papers to search for in that year and season. Why don't you specify what paper it is?
Comment: could you find a link to your question? There are too many "May/June 2016 Q10ii" one of them is as https://www.8mundo.com/file?id=3353147 and seems to come close to the statement of your question, but does not seem to be exactly your question. There is a lon glist at https://www.8mundo.com/post/cie-a-level-mathematics-9709-past-question-papers-and-marking-schemes-mayjune-2016-octnov-2016-8508328
Comment: @Mirko I think that you found the right question paper!
Comment: The correct statement is now a comment to the correct answer ... of course the OP could have provided it, and formatted it properly, hopefully this will happen in their future posts
Answer: Thanks to Mirko, now we have a complete statement of Q10:

The function $f$ is such that $f(x)=2x+3$ for $x\geq 0$. The function $g$ is such that $g(x)=ax^2+b$ for $x\leq q$, where $a$, $b$ and $q$ are constants. The function $f\circ g$ is such that $(f\circ g)(x)=6x^2−21$ for $x\leq q$.
  (i) Find the values of $a$ and $b$.
  (ii) Find the greatest possible value of $q$. [2]
  It is now given that $q=-3$.
  (iii) Find the range of $f\circ g$.
  (iv) Find an expression for $(f\circ g)^{-1}(x)$ and state the domain of $(f\circ g)^{-1}$.

OP solved Q10(i) and found that $g(x)=3x^2-12$.
Q10(ii) is asking the greatest possible value of $q$ such that $f(g(x))=6x^2-21$ is defined for $x\leq q$ (here $f(x)=2x+3$ is defined for $x\geq 0$). Therefore the composition is possible if $g(x)\geq 0$. Hence we should find the greatest possible value of $q$ such that $g(x)\geq 0$ FOR ALL $x\leq q$.
By solving the inequality we get that $g(x)\geq 0$ iff $x\in (-\infty,-2]\cup [2,+\infty)$. So what is $q$?
Comment: you mean OP found $g(x)=3x^2-12$, not $g(x)=3x^2+12$. I see now what they mean in that paper, indeed it is the right paper, where by $fg(x)$ they mean composition, $(f\circ g)(x)$, it makes sense now. (And of course $q=-2$ the OP already knew that :)
Comment: @ Mirko yes, thanks
Comment: To make it self-contained, here is the statement. The function $f$ is such that $f(x)=2x+3$ for $x\ge0$. The function $g$ is such that $g(x)=ax^2+b$ for $x\le q$, where $a,b$ and $q$ are constants. The function $fg$ is such that $fg(x) = 6x^2−21$ for $x\le q$. (i) Find the values of $a$ and $b$. [3],
(ii) Find the greatest possible value of $q$. [2],
It is now given that $q=−3$.
(iii) Find the range of $fg$. [1],
(iv) Find an expression for $(fg)^{−1}(x)$ and state the domain of $(fg)^{−1}$, [3].


C++ function pointer to self

Question: Is there a way to have a function pointer to the function that's getting it.
It should work like this:
void foo()
{
        assert(<self-pointer> == &foo);
}

(moved form comment):
I want a macro that can log something and add the place where the log came from to it. For this I want to use an id, which I thought I could make the function's pointer.
Comment: C++20 has [std::source_location::current()](https://en.cppreference.com/w/cpp/utility/source_location/current).
Comment: This is [XY problem](http://xyproblem.info/). Please explain why do you need this!
Comment: You just did no? `&foo`
Comment: I guess he needs something like `this` for class, but for function.
Comment: @463035818_is_not_a_number AFAIK `__function__` in an old extension and one should use `__func__` nowadays.
Comment: You mean without naming it explicitly? That is, "" would be the same in foo() and bar()? (Then, I don't think there is a way.)
Comment: I suppose in C++ you could create a functor, i.e. a class that has an `operator()` which contains the actual functionality. Because you are in a class you can use `this`.
Comment: @MarekR I want a macro that can log something and add the place where the log came from to it. For this I want to use an id, which I thought I could make the function's pointer.
Comment: Just use `__LINE__` and the like in the macro.
Comment: `__function__` is the name of the function, though thats a string. There was a similar question recently about calling the function by using `__function__`, which is also not possible. Anyhow, for logging you do not need the function pointer. Out of curiosity, what would you do with the pointer if you could get it?
Comment: Thank you for giving me some input. I've reconsidered and decided to use `__func__` instead.
Comment: You'll need the caller to pass the caller's function address into the `foo` function, or some token like a `char const*` which may be more useful.  Otherwise, you might considering resorting to platform specific solutions.  Boost [Stacktrace](https://www.boost.org/doc/libs/1_76_0/doc/html/stacktrace.html) abstracts platform specific solutions for several platforms.
Answer: Note OP comment that he creates a logger.
In C++20  std::source_location::current() has been introduced so macros can be avoided. Linked documentation has nice example.
Before C++20 to create a logger you have to use macros:

__LINE__ -  current line number
__func__ - current function name
__FILE__ - current file name

https://stackoverflow.com/a/597081/1387438
Comment: Thank you. I've accepted the other answer as yours doesn't answer the question in the title, but I've decided to use `__func__`(standard version) instead(as I don't have true access to c++ 20 yet). +1.
Comment: @NikitaDemodov So what you need is a string, which is just the name of the function, instead of a function pointer to itself.
Comment: @Yves No, I just needed a way to be able to identify where the log came from -- a sort of id. But now I've reconsidered to the string version instead.
Comment: @NikitaDemodov If so, what you need is to locate an exception. You should make this clear in your question, otherwise your question is a XY problem. In fact, there has been many great log library, which can tell you where an exception comes from, when it is thown, etc, it can even tell you the line number of throwning the exception.
Comment: @NikitaDemodov  https://stackoverflow.com/questions/6692238/better-logging-library-for-c
Comment: @NikitaDemodov If you want to create a logger by yourself to finish your homework, it's not hard. But if you want to create a logger that can be used in the real project, I would say it's very hard. You have to consider many things, such as thread-safe, performance etc. Basically, a real logger should at least be thread-safe and have a good performance, as logger always has lots of IO events, you have to use some OS-level technique, such as sharing memory to get a better performance... Anyway, it's hard...
Answer: There are no equivalent of this (about class instance) for function/method.

C++ function pointer to self


Can a CloudWatch Custom Metric be a variable instead of a hard-coded string

Question: I have created a AWS custom metric in CloudWatch. I am using NodeJs Lambda function to create a custom metric along with dimensions. I would like to know if we can pass variable value to dimensions instead of string (hardcoded strings). Does dimension values accept anything other then string value?
This works:
var params = {
    MetricData: [
      {
        MetricName: 'PAGES_VISITED',
        Dimensions: [
          {
            Name: 'UNIQUE_PAGES',
            Value: '**URLS**'
          },
        ],
        Unit: 'None',
        Value: 1.0
      },
    ],
    Namespace: 'SITE/TRAFFIC'
  }

But I want to pass something like this:
MetricData: [
    {
      MetricName: 'PAGES_VISITED',
      Dimensions: [
        {
          Name: 'MessageAttributes',
          Value: msgattr
        },
        {
          Name: 'CompanyName',
          Value: process.env.CompanyName
        },
        {
          Name: 'short_description',
          Value: message
        },
      ],
      Unit: 'None',
      Value: 10.0
    },
  ],

Answer: Yes, that will work fine.
The Value variables for Dimensions can only be strings, but you can provide those strings by referencing variables.
To see the result, simply print(params) and you will see that the values from the variables have been stored.
Comment: I can see the printed value, but when I pass the variable to Dimension value i see following error:
Error InvalidParameterType: Expected params.MetricData[0].Dimensions[0].Value to be a string
Comment: What is it showing for the `MessageAttributes` value? Is it showing it as a string?


insert array arguments via php into mysql

Question: I followed some threads here, but I can't see what am I doing wrong:
$friends = array
(
        array("yaron","levi","email@example.com"),
        array("david","chohen","firstname.lastname@example.com"),
        array("michal","rubin","firstname.lastname@example.com"),
        array("dafna","mishal","email@example.com"),
        array("tamar","mishal","firstname.lastname@example.com")
);

if(is_array($friends)){

    $sql = array();
    foreach( $friends as $row ) {
                $sql[] = '("'.mysql_real_escape_string($row['firstname']).'","'.mysql_real_escape_string($row['lastname']).'","'.mysql_real_escape_string($row['email']).'")';
    }
    mysql_query('INSERT INTO MyGuests (firstname,lastname,email) VALUES '.implode(',', $sql));

}

Answer: You will get undefined index error because your array has no index by firstname, lastname & so on.. Also enclose values by single quotes during imploding. This should help
if(is_array($friends)){
    $sql = array();
    foreach( $friends as $row ) {
        $sql[] = mysql_real_escape_string($row[0]);
        $sql[] = mysql_real_escape_string($row[1]);
        $sql[] = mysql_real_escape_string($row[2]);
        $values = "'".implode("','", $sql)."'";
        mysql_query("INSERT INTO MyGuests (firstname,lastname,email) VALUES(".$values.")");
    }
}

Comment: the problem is that the query runs on each loop round...
FYI - stil not working :(
Answer: change your friends array for:
$friends = array(
    array("firstname"=>"yaron", "lastname"=>"levi",  "email"=>"email@example.com"),
    array("firstname"=>"david", "lastname"=>"chohen","email"=>"email@example.com"),
    array("firstname"=>"michal","lastname"=>"rubin", "email"=>"firstname.lastname@example.com"),
    array("firstname"=>"dafna", "lastname"=>"mishal","email"=>"firstname.lastname@example.com"),
    array("firstname"=>"tamar", "lastname"=>"mishal","email"=>"firstname.lastname@example.com")
);

With this change, your script will be work successfully!


Get nearest location with elasticsearch

Question: I'm building an application that requires elasticsearch to find the nearest location based on latitude and longitude. At the moment I'm able to do this based on a GeoPoint and a maximum distance in kilometers.
<code>@Override
public List<CityDefinition> findCitiesNearby(GeoPoint geo, double distance, String source) {
    LOGGER.info("<findCitiesNearby>");

    FilterBuilder filterBuilderGeo = FilterBuilders.geoDistanceFilter("geo").point(geo.getLat(), geo.getLon()).distance(distance, DistanceUnit.KILOMETERS);

    SearchQuery q = new NativeSearchQueryBuilder()
            .withFilter(filterBuilderGeo);

    List<CityDefinition> fields = esOps.queryForList(q, CityDefinition.class);

    return fields;
}
</code>
This works almost perfect but instead of searching within a given distance I want elastic to return the nearest location no matter the distance. Is this possible? If it is, how do I do this?
Answer: You could sort by distance, rather than filter.
Something along those lines should work:
<code>public List<CityDefinition> findCitiesNearby(GeoPoint geo, double distance, String source) {
    GeoDistanceSortBuilder geoDistanceSort = SortBuilders.geoDistanceSort("geo").point(geo.lat(), geo.lon())
            .unit(DistanceUnit.KILOMETERS).sortMode("ASC")
            .geoDistance(GeoDistance.PLANE);

    final int limit = 1; // if you want only the single nearest result.
    SearchQuery q = new NativeSearchQueryBuilder()
            .withSort(geoDistanceSort)
            .withPageable(new PageRequest(0, limit))
            .build();

    List<CityDefinition> fields = esOps.queryForList(q, CityDefinition.class);

    return fields;
}
</code>
Answer: Apparently it's possible to just remove the distance part.
<code>@Override
public List<CityDefinition> findCitiesNearby(GeoPoint geo, double distance, String source) {
    LOGGER.info("<findCitiesNearby>");

    //FilterBuilder filterBuilderGeo = FilterBuilders.geoDistanceFilter("geo").point(geo.getLat(), geo.getLon()).distance(distance, DistanceUnit.KILOMETERS);

    FilterBuilder filterBuilderGeo = FilterBuilders.geoDistanceFilter("geo").point(geo.getLat(), geo.getLon());

    SearchQuery q = new NativeSearchQueryBuilder()
            .withFilter(filterBuilderGeo);

    List<?> fields = esOps.queryForList(q, CityDefinition.class);

    return (List<CityDefinition>) fields;
}
</code>
Comment: could you  share more about information how to use the elastic search with location please? How should the data  will mapped in the ES?
Comment: @ImanTumorang I thinks I'm not the right person to explain everything on how ES works with GEO related problems. What I can do is provide you some related docs:

https://www.elastic.co/guide/en/elasticsearch/reference/2.4/geo-point.html

https://www.elastic.co/guide/en/elasticsearch/reference/2.4/geo-queries.html

This should get you on the right track!

Get nearest location with elasticsearch


Confused about installing Apache Solr

Question: This is pretty embarrassing but I gotta start somewhere, right? This concerns about installing Apache Solr.
I've seen the instructions when trying to install Apache Solr and each one starts off with installing Java. I'm confused since I'm using Bluehost for webhosting (http://drupal.org/hosting). Does that mean I need to install Java on my server? There's also the thing about the terminal but I've never seen the terminal in my hosting's Cpanel. Help.
Edit: By terminal does that mean SSH? Because I can have that enabled in cPanel. It would be nice if there were a simple tutorial for cPanel's users like me. :-)
Comment: Terminal usually refers to a Unix-style command line interface that you run on your computer. Linux and Mac OS X support it natively though Windows requires add-on software such as Cygwin. That said, you would use a terminal window to connect with your server over SSH, which is a secure communications protocol.
Comment: Possible duplicate - http://drupal.stackexchange.com/questions/7035/apache-solr-integration-on-shared-hosting-with-cpanel
Answer: Yet that's true. If you want to use apachesolr for your own you have to run a java server.
Alternative there are some services which you can pay to host apachesolr for you.
Some examples:

acquia
drupalconcept
Comment: I see, so it has to be a java server. So that means I'll need to get a second hosting that has java. Any suggestions? Drupalconcept seems to be non-English.
Comment: You could in theory run them on the same server, solr is fairly advanced , you need lots of content to make it worthwile, are you sure you need it for your solution?
Comment: I have a few big projects in the pipeline and because of that Search has become one of my main priorities. For much smaller sites which Drupal module do you think would be best? Nothing of the Solr caliber.
Comment: If you need a simple search use core search module, for everything else you need some kind of shell access. Oh perhaps http://drupal.org/project/luceneapi could work as well
Comment: For a non-english site i recommended acquia, even i never used it before. There are sure other providers as well, but you can google them for your own.

Confused about installing Apache Solr


objc[29733]: Swift class extensions and categories on Swift classes are not allowed to have +load methods xcode 10.2 running on ios 12.2

Question: I updated my Xcode to Version 10.2 (10E125) and my existing swift project crashes with "objc[29733]: Swift class extensions and categories on Swift classes are not allowed to have +load methods" while running in iPhoneX simulator 12.2
Answer: Apparently in iOS 12.2 you can't use anymore + (void) load.
You should refactor your code to use __attribute__ instead of + (void) load.
The old answer was given incorrectly but has good talk material to understand the problem.
I ask to any Developer to give a better answer that this one. I reckon my lack of knowledge is a speed bump on this answer but my idea is to at least start giving some insight on how to solve it!
If at least one developer can make is code work, my job here is done :)
===============================Old Answer==================================
It's a known bug.
It seems the new 12.2 don't allow some method's to load swift modules.
A Fix was already made, let's hope it enters the react native 59.3. (Fingers Crossed.)
For more information:
https://github.com/facebook/react-native/issues/24139
There are some temporary work arounds pls check the link above.
=============================EDIT old answer===============================
react-native 59.3 was released a few moments ago with this bug fixed, pls update.
Comment: Yes it is Swift but if you use Swift in React-Native, you get this error.
Answer: For anyone encountering this error in a React Native project with Xcode 10.2, check that you are using version 0.59.3 or later of react-native, which includes a fix for this issue, which is related to using RCT_EXTERN_MODULE for Swift classes.
Answer: This issue was due to incompatible version of pod library for Xcode 10.2. Solved by updating all the library with version compatible to Xcode 10.2.


How do I set the drums notation style in LilyPond?

Question: LilyPond documentation lists several different drum notation styles (like agostini, weinberg).
These are to be selected by setting the drumStyleTable in context DrumVoice. I would like to use the weinberg-drums-style.
I am currently using the shorthand \drums command, instead of \new DrumStaff.
Where exactly should I put something like:
\set DrumStaff.drumStyleTable = #(alist->hash-table weinberg-drums-style)

And what would be the most convenient syntax?
I've seen different examples in the Cookbook, the documentation, and the mailing lists but had no luck so far using any of those with v2.23.12.
I would like to stick with the \drums syntax, if possible.
Answer: Since you appear to want this as a global setting, you'd place it in the respective \layout block, such as:
\layout {
  \context {
    \DrumStaff
    drumStyleTable = #(alist->hash-table weinberg-drums-style)
  }
}

Indeed, your statement can actually also be used directly there as:
\layout {
  \set DrumStaff.drumStyleTable = #(alist->hash-table weinberg-drums-style)
}

but the meaning is subtly different since this variant will also affect all contexts that contain an \alias "DrumStaff" declaration.
Comment: How many individual drum kits are you scoring for?
Answer: Place the \set command inside the block it is referring to.
But, you don't need to call a hash-table explicitly because you aren't using a custom drumStyleTable; theweinberg-drums-style is predefined.
So you should get something like this:
\drums {
    \set DrumStaff.drumStyleTable = #weinberg-drums-style
        bd4 hh sn hh |
}

which is equivalent to:
\new DrumStaff {
    \set DrumStaff.drumStyleTable = #weinberg-drums-style
    \drummode {
        bd4 hh sn hh |
     }
}

Comment: More precisely, it's equivalent to `\new DrumStaff \drummode { \set ... }`, with `\set` *inside* drum mode. It doesn't matter in this example, but if the value the property is being set to is something like a drum name, it can matter.
Comment: @ABOUSAMRAJean - really? Okay, good point.
Comment: Excellent! Thank you! So simple. I obviously missed something in my experiments. Embarrassingly, I'm the one who implemented the weinberg style but never knew how to activate it and kept using my custom definition file until I finally found some time to convert the sheets.


Do std::strings end in '\0' when initialized with a string literal?

Question: I know string objects aren't null terminated but why should this work?
std::string S("Hey");
for(int i = 0; S[i] != '\0'; ++i)
   std::cout << S[i];

So the constructor copies the null terminator as well, but does not increment the length? Why does it bother?
Comment: I reopened the question because OP knew about `std::string` is not null terminated but confused about the behavior of `std::string::operator[]`.
Comment: `std::string` does not smell like C.
Comment: Check this: http://stackoverflow.com/questions/39725183/difference-between-string-empty-and-string0-0/39725242
Answer:
So the constructor copies the null terminator as well, but does not increment the length?

As you've known that std::string doesn't contain the null character (and it doesn't copy the null character here).
The point is that you're using std::basic_string::operator[]. According to C++11, std::basic_string::operator[] will return a null character when specified index is equivalent to size().

If pos == size(), a reference to the character with value CharT() (the null character) is returned.
For the first (non-const) version, the behavior is undefined if this character is modified to any value other than charT().
Answer: std::string stores its data internally in the form of a null-terminated C-string, but in normal usage does not allow you to access the null terminator.
For example, if I assign the value "Hello, World!" to a string, the internal buffer will look like this:
std::string myString("Hello, World!");

// Internal Buffer...
// [ H | e | l | l | o | , |   | W | o | r | d | ! | \0 ]
//                                                   ^ Null terminator.

In this example, the null terminator was NOT copied from the end of the string literal, but added internally by std::string.
As @songyuanyao mentions in his answer, the result of this is that myString[myString.size()]; returns '\0'.
So why does std::string assign a null terminator to the end of the string? It certainly doesn't have to support one, because you can add '\0' to a string and it is included in the string:
std::string myString;
myString.size();              // 0
myString.push_back('\0');
myString.size();              // 1

The reason for this behavior is to support the std::string::c_str() function. The c_str() function is required to return a null-terminated const char *. The most efficient way to do this is to simply return a pointer to the internal buffer, but in order to do that the internal buffer must include a null terminator character at the end of the string. Since C++11, strings are required to include the null terminator to support this.
P.S. While not strictly part of your question, it should be pointed out that the loop from your question might NOT return a full string if your string includes null characters:
std::string S("Hey");
S.push_back('\0');
S.append("Jude");

for(int i = 0; S[i] != '\0'; ++i)
    std::cout << S[i];

// Only "Hey" is printed!

Answer:
std::string Overload: The std::string class has a special way to store its length, so it doesn't need null-termination like C-style strings. You can use S[i] to access characters directly, and the loop works without '\0'.

Efficient Handling: The std::string constructor doesn't add a null terminator when creating the string because it uses a smarter length management method. This approach is more efficient for handling and manipulating strings.
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


Autocovariances and Autocorrelations of Processes

Question: I have two questions that are related to calculating autocovariances and autocorrelations of processes.
Let's say we have a simple process:
$y_t = ε_t + ε_{t-1}$
$ε_{t} =$ standard normal random variable
To calculate the lag 1 autocovariance, we'll do the following:
$Cov(y_t,y_{t-1}) $
$= Cov(ε_t + ε_{t-1}, ε_{t-1} + ε_{t-2})$
$=Cov(ε_{t-1},ε_{t-1})$
$=1*1*1$
$=1$
To calculate $Cov(ε_{t-1},ε_{t-1})$, I know you can take the coefficient in front of each $ε_{t-1}$ and multiply it by the variance of ε_{t-1} to get 1*1*1.  So I know I can do this little trick to get the covariance, but I don't understand why you do this.  Why can you just make this multiplication to get the covariance?
Which brings me to my next question.  For the same process, can you do the same things to calculate the lag 1 autocorrelation?
$Cor(y_t,y_{t-1}) $
$= Cor(ε_t + ε_{t-1}, ε_{t-1} + ε_{t-2})$
$=Cor(ε_{t-1},ε_{t-1})$
$=???$
If I can use this same method for autocorrelation, what trick can I use to calculate $=Cor(ε_{t-1},ε_{t-1})$?
Comment: Do you know the definition of correlation?
Answer: You have $Cov(X,X)=Var(X)$, and if $X$ and $Y$ are independent then $Cov(X,Y) = 0$ and $Var(X+Y)=Var(X)+Var(Y)$, so
$Cor(y_t,y_{t-1})=\dfrac{Cov(y_t,y_{t-1})}{\sqrt{Var(y_t)}\sqrt{Var(y_{t-1})}}$
$=\dfrac{Cov(\varepsilon_t + \varepsilon_{t-1}, \varepsilon_{t-1} + \varepsilon_{t-2})}{\sqrt{Var(\varepsilon_t + \varepsilon_{t-1})}\sqrt{Var(\varepsilon_{t-1} + \varepsilon_{t-2})}}$
$=\dfrac{Cov(\varepsilon_t , \varepsilon_{t-1})+Cov(\varepsilon_t , \varepsilon_{t-2})+Cov( \varepsilon_{t-1}, \varepsilon_{t-1} )+Cov( \varepsilon_{t-1},  \varepsilon_{t-2})}{\sqrt{Var(\varepsilon_t + \varepsilon_{t-1})}\sqrt{Var(\varepsilon_{t-1} + \varepsilon_{t-2})}}$
$=\dfrac{0+0+Var(\varepsilon_{t-1})+0}{\sqrt{Var(\varepsilon_t) + Var(\varepsilon_{t-1})}\sqrt{Var(\varepsilon_{t-1}) + Var(\varepsilon_{t-2})}}$ by independence
$=\dfrac{V}{\sqrt{V + V}\sqrt{V + V}}=\dfrac{1}{2}$
where $V=Var(\varepsilon_t)= Var(\varepsilon_{t-1}) =  Var(\varepsilon_{t-2})$.
Answer: The point is that $Cov(X+Y,Y+Z) = Cov(X,Y)+Cov(X,Z)+Cov(Y,Y)+Cov(Y,Z)$: covariance is bilinear.  $Cov(X,Y)$, $Cov(X,Z)$, $Cov(Y,Z)$ are $0$ if $X,Y,Z$ are independent.
The covariance of a random variable and itself is the same as the variance of that random variable (look at the definitions, you'll see they are the same).  A standard normal random variable has variance $1$.
As for correlation, assuming you mean the Pearson correlation, the definition of that is $Cor(X,Y) = Cov(X,Y)/(\sigma_X \sigma_Y)$.  But correlation is not bilinear: $Cor(X+Y,Y+Z) \ne Cor(X,Y) + Cor(X,Z) + Cor(Y,Y) + Cor(Y,Z)$ because the standard deviations are different.


Create Fragment with Class Object

Question: We can do that:
val fragment = SomeFragment()
val args = Bundle()
args.putString("Key_Value", "String_Value")
fragment.arguments = args

And we can take it from Fragment like this:
arguments.getString("String_key","Default Value")

My question is can we pass a class object as parameter?
val some_object = SomeClass()
args.put("Key_Value", some_object )

Answer: You can pass something that's parcelable (Don't do this with classes like Activities, Fragments etc. )
See this answer: https://stackoverflow.com/a/33649155/7968986
Or pass something that identifies that class, for example it's possible to pass the Classname as a String and then inside the fragment call stuff like startActivity if it's a Activity / Android related class that you shouldn't pass (or parcelize)
See this answer: https://stackoverflow.com/a/39676049/7968986
In general the class is not allowed to be too big if it's parcelized, so in some cases you need other solutions
Comment: First one (with Parcelable) is did the trick. Thanks a lot.
Comment: Glad I could help

Create Fragment with Class Object


Multiple linear regression vs. Time Series

Question: I have sale data for 3 years by week.I need to predict sales for the next year by week.
The business requested that some categorical values and numeric values (so for example category, product quantity offered and amount of weekly traffic) are included as coefficients that they can change for next year and accordingly the projection would change. This would be very easy with a multiple linear regression model. (I was planning on training the model on 2 years and testing it on the 3rd)
Since my data is definitely seasonal, I thought that I need to use a time series model. (I was thinking ARIMA, but any other recommendation is welcomed). However, in the past when I used ARIMA, I just had a timestamp and predicted the value at a future timestamp, without other coefficients that could be changed by the user.
It might be my misunderstanding of time series models, but is there a combination of a model that can have adjustable coefficients like a multilinear regression model yet does account for seasonality?
Or would extrapoliation be the way to go?
I looked at those two questions, but they don't help me directly.
Linear regression vs Time series analysis
Time Series Forecasting vs Linear Regression Extrapolation
Answer: The most popular methods for time series forecasting are ARIMA and Holt-Winters. Holt-Winters is simpler and computationally less expensive. It is especially designed for seasonality. If you use ARIMA you must use seasonal ARIMA. Some studies show that, in real life data, Holt-Winters and seasonal ARIMA not only have a similar accuracy but predict similar values (http://webarchive.nationalarchives.gov.uk/20160105160709/http://www.ons.gov.uk/ons/guide-method/ukcemga/ukcemga-publications/publications/archive/from-holt-winters-to-arima-modelling--measuring-the-impact-on-forecasting-errors-for-components-of-quarterly-estimates-of-public-service-output.pdf).
Your problem is multi-variate time series, not just $y(t)$ but $y(X,t)$.
An idea is to try something like a linear regression with time varying coefficients. Think of a linear model without time : $y(X)=\beta X$ where $\beta$ is a vector. Then introduce time : $y(X,t)=\beta(t) X$. Then see $\beta(t)$ as a vector time series.
But you can't observe $\beta(t)$.
I have not read any article addressing this problem even though it is somehow a problem of growing importance : studying time and other parameters together.
If at each time you have a lot of (y,X) samples covering well the possible values of X, then you could possibly estimate $\beta(t)$ at every time and then apply a time series method to this vector. But I guess you data is not like this.
Added:
The ultimate solution where you can really work on $\beta(t)$ as a hidden parameter is the Kalman filter. If $\beta(t)$ is just a random walk, then the state of Kalman filter is just $\beta(t)$ and this would be not so difficult to implement, using observations to update the filter. Next step would be to use an ARIMA or HW model inside the filter but this starts being hardcore maths. I don't know of anything like this packaged as an easy-to-use tool. You can read more about it: What are disadvantages of state-space models and Kalman Filter for time-series modelling?
Answer: "Studying time and other parameters together" is the subject of Transfer Functions . See http://www.math.cts.nthu.edu.tw/download.php?filename=569_fe0ff1a2.pdf&dir=publish&title=Ruey+S.+Tsay-Lec1 AND Transfer function in forecasting models - interpretation AND https://onlinecourses.science.psu.edu/stat510/node/75 AND my comments in this discussion Autocorrelation and heteroskedasticity in time series data.... AND http://autobox.com/cms/images/dllupdate/TFFLOW.png for the steps in the analysis.


Gagliardo-Nirenberg interpolation inequalities on a bounded domain

Question: In the original paper of Nirenberg, the following inequality is proven : if $\frac{1}{p} = \frac{j}{n} + \left( \frac{1}{r} - \frac{m}{n} \right) \alpha + \frac{1 - \alpha}{q}$ and $\frac{j}{m} \leq \alpha < 1$ (I put $< 1$ to avoid the "second exceptional case"), then
$$\| \mathrm{D}^{j} u \|_{L^{p}} \leq C_{1} \| \mathrm{D}^{m} u \|_{L^{r}}^{\alpha} \| u \|_{L^{q}}^{1 - \alpha} + C_{2} \| u \|_{L^{s}} $$
where $s > 0$ is arbitrary and the norms are on $L^p$ spaces over a bounded Lipschitz domain $\Omega$ in $\mathbb R^n$. If $\Omega = \mathbb R^n$ instead, there is no need for the second term in the right-hand side.
Nonetheless, in Brézis, Functional Analysis, Sobolev Spaces and Partial Differential Equations several examples of this inequality are mentioned in a bounded domain without the second term.
Do someone know if this is wrong or if the original inequality is not optimal ?
Thanks
Answer: Oh, sorry I got it : Brézis mentions the inequality with $W^{m,r}$ instead of only the $L^r$ norm of $D^m u$, like this
$$\| \mathrm{D}^{j} u \|_{L^{p}} \leq C_{1} \| u \|_{W^{m,r}}^{\alpha} \| u \|_{L^{q}}^{1 - \alpha} $$
So in fact I guess he just uses $s = q$, and writes $\|u\|_{L^q} = \|u\|_{L^q}^\alpha \|u\|_{L^q}^{1-\alpha}$ and controls one term with the Rellich embedding and factorizes.
I leave the question here if someone has the same problem one day, hopefully I'll save him some time...


Como obter valores para popular um dropdown dinamicamente

Question: Estou desenvolvendo em .NET MVC e na minha aplicação, possuo um formulário que cadastra pessoas via Ajax. Esse elemento cadastrado devera aparecer em uma lista dropdown, ele deverá aparecer dinamicamente sem atualizar a página, alguém conhece alguma forma de fazer isso?
Não consigo obter os nomes na minha lista dropdown sem atualizar! Teria alguma forma de quando clicar no dropdown ele mostrasse os itens inseridos no campo anterior?
Answer: Dependendo da complexidade da sua tela eu sugiro utilizar Javascript para tal, porém a seguir fiz um exemplo com uma alternativa diferente, para lhe dar algumas ideias, espero que lhe ajude:
Adicione o arquivo ao seu header:

Código do controle:
public static class DropDownDB
{
   public static List<string> Nomes = new List<string> { "Nome 1", "Nome 2", "Nome 3" };
}

public class DropDownController : Controller
{
   public ActionResult Index()
   {
      return View();
   }

   [HttpPost]
   public ActionResult Index(string nome)
   {
      DropDownDB.Nomes.Add(nome);
      return MeuDrop();
   }

   public ActionResult MeuDrop()
   {
      return PartialView("MeuDrop", new SelectList(DropDownDB.Nomes));
   }
}

Da View:
@model string

@using (Ajax.BeginForm(null, new AjaxOptions { HttpMethod = "Post", InsertionMode = InsertionMode.Replace, UpdateTargetId = "replaceDiv", OnSuccess = "$('.text').val('');" }))
{
   <input type="text" name="nome" />
   <button type="submit">Adicionar</button>
}

   @Html.Action("MeuDrop")

E da Partial View criada para o dropdown:
@model SelectList
@DateTime.Now
@Html.DropDownList("drop", Model)


ESXi 4.0 - cannot copy files

Question: I am unable to copy files or make directories on my installation of VMWare ESXi 4.0. I have done so in the past (copied an iso onto a datastore). But something has changed and I have no idea what.

I cannot copy using the datastore browser (get a dialog saying "Expected a PUT_FILE_DONE message. Got SESSION_COMPLETE").
I cannot create a directory through datastore browser (get a dialog saying "Cannot complete file creation operation").
When I ssh to the ESXi server I cannot create files or folders under /vmfs/volumes. But I can manipulate files elswhere (including /vmfs).

Here are the permissions for the directories (I am logged in as root).

    ~ # ls -lh /vmfs/volumes/
drwxr-xr-t    1 root     root         1.2k Sep  3 12:19 4a76f260-36b7eb85-c3b3-0024e8314929
drwxr-xr-x    1 root     root            8 Jan  1  1970 4a76f261-d6190a9e-3b89-0024e8314929
drwxr-xr-t    1 root     root         1.4k Sep 22 10:38 4a76f262-4ac21f0a-6bc1-0024e8314929
l---------    0 root     root         1.9k Jan  1  1970 Hypervisor1 -> c42ce27f-eb8d7f70-7f70-0e7a85e8edc4
l---------    0 root     root         1.9k Jan  1  1970 Hypervisor2 -> bbf1477b-4aec1d8c-caa5-5e8720bebd85
l---------    0 root     root         1.9k Jan  1  1970 Hypervisor3 -> efd8efe3-03bc1cbf-15e0-080efd9e7379
drwxr-xr-x    1 root     root            8 Jan  1  1970 bbf1477b-4aec1d8c-caa5-5e8720bebd85
drwxr-xr-x    1 root     root            8 Jan  1  1970 c42ce27f-eb8d7f70-7f70-0e7a85e8edc4
l---------    0 root     root         1.9k Jan  1  1970 datastore1 -> 4a76f260-36b7eb85-c3b3-0024e8314929
l---------    0 root     root         1.9k Jan  1  1970 datastore2 -> 4a76f262-4ac21f0a-6bc1-0024e8314929
drwxr-xr-x    1 root     root            8 Jan  1  1970 efd8efe3-03bc1cbf-15e0-080efd9e7379
~ # touch /vmfs/foo.txt
~ # touch /vmfs/volumes/foo.txt
touch: /vmfs/volumes/foo.txt: Operation not permitted

I've googled and found nothing helpful. Does anyone out there have an idea as to what is going on?
Thanks in Advance.
Pete.
Comment: Try: touch /vmfs/volumes/datastore1/foo.txt
Comment: Can you post a df and vdf output also?  It may be that vmfs/volumes is on another datastore and is mounted read only or has other problems...
Answer: Dumb Question, but do you get the same error when going through the vsphere client? I have one instance where the vsphere client automatically fixed the mistaken permission setting on the ISO directory and was available to the device again correctly.
Comment: I couldn't get it work any which way. I wish something I did would fix the permissions.

ESXi 4.0 - cannot copy files


How to create form on users account page?

Question: I used hook_user_view_aler() to add some info to user's page.
 $account['summary']['member_five'] = array(
    '#type' => 'user_profile_item',
    '#title' => t('I do'),
    '#markup' => 'Real magic',
  );

  $account['summary']['member_six'] = array(
    '#type' => 'textfield',
    '#title' => t('Name'),
    '#default_value' => '',
    '#size' => 30,
    '#maxlength' => 60,
    '#required' => TRUE,
  );

  $account['summary']['member_seven'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
  );

Also I added form elements and they do appear but I couldn't submit it. hook_user_view_aler_submit() obviously is too much and it doesn't work. Is there any way to create form on user's page?
Answer: You'll have to define a form function using the drupal form API
See this tutorial for more info on how to make your own forms.
So the actual form function would look something like this
MY_FORM_FUNCTION($form, &$form_state){
  // Build form array here
  return $form;
}

MY_FORM_FUNCTION_validate($form, &$form_state){
  // Validate function here
}

MY_FORM_FUNCTION_submit($form, &$form_state){
  // Submit function here
}

Now in the tutorial they use HOOK_menu to display the form on a page. But you can call drupal_get_form('MY_FORM_FUNCTION') from everywhere and generate a render array for the form.
So this would show your form on the user page via HOOK_user_view_alter
 $account['form'] = drupal_get_form('MY_FORM_FUNCTION');


Meaning of @GeneratedValue with strategy of TABLE

Question: The JPA specification gives the following explanation of the annotation @GeneratedValue(strategy=TABLE):

The TABLE generator type value indicates that the persistence provider must assign primary keys for the entity using an underlying database table to ensure uniqueness.

But what does "using an underlying database table" mean in practice? Does it mean using an auxiliary table? Or by scanning the entity-table to find an ID not in use? Or something else?
Comment: An answer by http://stackoverflow.com/users/416206/james, http://stackoverflow.com/a/10091167/545127, says "only every 100 inserts will lock the row **in the sequence table**", suggesting use of an auxiliary table.
Answer: Check out JavaDoc for TableGenerator, it has a nice example of how it works:
Example 1:
@Entity public class Employee {
    ...
    @TableGenerator(
        name="empGen",
        table="ID_GEN",
        pkColumnName="GEN_KEY",
        valueColumnName="GEN_VALUE",
        pkColumnValue="EMP_ID",
        allocationSize=1)
    @Id
    @GeneratedValue(strategy=TABLE, generator="empGen")
    int id;
    ...
}

Example 2:
@Entity public class Address {
    ...
    @TableGenerator(
        name="addressGen",
        table="ID_GEN",
        pkColumnName="GEN_KEY",
        valueColumnName="GEN_VALUE",
        pkColumnValue="ADDR_ID")
    @Id
    @GeneratedValue(strategy=TABLE, generator="addressGen")
    int id;
    ...
}

Basically ID_GEN is an internal (non-business) table of key-value pairs. Every time JPA wants to generate ID it queries that database:
SELECT GEN_VALUE
FROM ID_GEN
WHERE GEN_KEY = ...

and incremenets the GEN_VALUE column. This mechanism can be used to emulate sequences or to take even further control of generated ids.
Answer: In the case of EclipseLink, it uses an auxiliary table. The documentation says

By default, EclipseLink chooses the TABLE strategy using a table named SEQUENCE, with SEQ_NAME and SEQ_COUNT columns


Do inputs to a Neural Network need to be in [-1,1]?

Question: I want to create an weather forecast using Neural Networks. All the examples I saw used only values [-1,1] as an input. Is it also possible to use bigger values (like air pressure, degree calcius of the last couple of days,...) as inputs and get an number as output?
Thank you
Comment: Speaking in general for classification algorithms and not just neural networks any variable like the ones you suggest can be used for classification.  Any such variables that help separate the classes should be included.  Even binary tree calssifier use continuous variable dichotomizing by finding split points.
Answer: You can normalize the values so that you use, for example,
$$\frac{AP - AP_0}{AP_1-AP_0}$$
where $AP$ is the current air pressure, $AP_0$ is the air pressure value you want sent to $0$, and $AP_1$ is the air pressure value you want sent to $1$.
It is ok if your inputs occasionally go a bit outside $[-1,1]$.
It is dangerous if an input is usually small, but has some occasional extreme values. Then it might be better to split the input into more than one input value, or to remove the outliers and accept that the neural network has a restricted context of applicability. Rescaling so that the outliers are between $-1$ and $1$ won't fix the problem.
Comment: Scaling data **DOES** make a difference. 1. Fields with larger values will initially have a bigger impact on the network than smaller fields, as the networks are initialized with random numbers drawn uniformly. Over time the weight updates will scale the features but this requires more effort. 2. Gradient descent has a very hard time with unnormalized data as it squashes the error curve making it eliptical and thus very slow to navigate.  So if you are using gradient descent this can be a big issue. 3. The sigmoid function has a very small gradient for large inputs (and very negatives ones).
Comment: They don't have to be boundaries. They are reference values so that most values get scaled to the range you want. So, for temperatures, you could use $T_1 = 35$, $T_0 = -5$, even though it occasionally goes over $35$ or under $-5$ degrees Celsius. It's not terrible if the range is larger by a factor of $2$, but try not to be off by a factor of $10$ or it may slow down the training.
Comment: The training methods are not scale-invariant, so scaling does affect how rapidly you train even if you don't saturate the nodes.
Comment: Here is a source that could help: ftp://ftp.sas.com/pub/neural/FAQ2.html#A_std
Comment: So AP0 and AP1 are like my boundries for air pressure values?
Comment: Theoretically, scaling your data should not make a difference for neural networks. It just means that the optimal weights will also be scaled. In practice it could make a difference because floating point representations are not exact, i. e. when you have huge input, your weights will be very small and a little change maybe could not be represented. On the other hand, you usually have sigmoid activation functions, which tend to saturate for large inputs and then will only adjust slowly during training. That means, scaling your data often accelerates training.


JQuery ajax success fired twice, because of .done callback

Question: I have some legacy code, which aborts ajax requests in a scenario & then after user-response, resends that request.
function resendLastAjaxRequest(ajaxRequest, ajaxSettings){
    if(ajaxSettings != undefined){
        $.ajax(ajaxSettings).done(function ( data ) {
            ajaxSettings.success(data);
        });
    }

Now, the above code fires the success handler for the request twice, but's its been there for more than a year & no one encountered it. Is it because of jquery version updates. We're currently using 2.0.3
I don't know when exactly was jquery updated, but may be in earlier versions done was fired instead of success.
Did some digging but couldn't find any reason why it might have worked for so long, please help.
Update
what is difference between success and .done() method of $.ajax
It contains a comment saying

ok, it's jQuery 1.8 :) Since $.ajax return a promise from jQuery 1.5
  this is a simple substitution for a matter of consistency (using the
  interface of deferred): done() take place of success(), fail() for
  error() and always() for complete()

that means if done is called, then we have to trigger success explicitly. This might be the reason why it worked for so long. But now, before the done fires the success handler is already called & then the done callback calls the success handler again.
Any suggestions on how to change/modify the code such that success is called only once ?
EDIT
ajaxSettings looks like this :
accepts: Object
async: true
cache: false
complete: function (request, status)
contentType: "application/x-www-form-urlencoded; charset=UTF-8"
contents: Object
converters: Object
crossDomain: false
dataTypes: Array[1]
error: function (request, status){flatOptions: Object global: true hasContent: false isLocal: false jsonp: "callback"
jsonpCallback: function (){var e=hn.pop()||x.expando+"_"+Yt++;return this[e]=!0,e}loadingdisplay: trueprocessData: true
responseFields: Object
success: function (htmlData) {type: "GET"

Comment: I don't know for the old jQuery version but it seems to be the good behaviour now. You have a method 'success' in the object you pass to the ajax call, so this method will be invoked as a callback when the ajax request will succeed. And in the .done promise you also invoke this success method. You need to choose just one of them to make it works fine.
Comment: If it's below the **1.5**, I think `.done()` wasn't implemented, so the `success` method is invoked as a callback then `.done` throw an error in the console without breaking anything (like _"undefined is not a function"_). So in this case, you have an error in the console and only one callback function called.
Comment: can you show your `ajaxSettings` object
Comment: @OxyDesign yes, that's the fix but I'm more concerned about, how did it worked so long ?
Comment: What was the previous version used before you changed for 2.0.3 ?
Comment: trying to find out...
Comment: With 1.4.4, http://jsfiddle.net/OxyDesign/1jmL9282/ : 1 error in the console (because of `.done()`) and only 1 callback (`success` method)
Answer: Like I said in the comments, I think previously you had a jQuery version lower than 1.5 (without .done() implemented) so the success method is invoked as a callback then .done() throw an error in the console without breaking anything (like undefined is not a function). So in this case, you have an error in the console and only one callback function called.
Demo with jQuery 1.4.4 : jsfiddle
In the console :

1 error : undefined is not a function (because of .done())

and

1 log : Object (datas from the call)


Atualizar conteúdo de DIV

Question: É possível fazer a atualização do conteúdo de uma DIV? Eu tenho uma DIV em que eu pego dados presentes nos cookies do navegador e faço um foreach para a listagem dos itens dos cookies mostrando eles para o usuário. Nessa mesma página eu tenho um botão que ao clicar chama uma função adicionando mais um item aos cookies, mas se eu abrir várias abas do navegador e adicionar outros itens aos cookies ele não faz a listagem atualizada da página atual. A minha intenção é que quando eu clicar no botão "Adicionar itens" ele atualize os itens já listados e mostre ele para o usuário. Abaixo código de listagem dos cookies para o usuário:

    <?php
        $myCookies = $this->getCookie('myCookies');
        foreach ($myCookies as $dados):?>

<?php echo $dados ?>

    <?php endforeach; ?>

Quando eu clicar no botão
Adicionar Itens
 eu precisaria que acontecesse um refresh na div lista para atualizar os itens que já estão nos cookies que foram adicionados em outras abas.
Para atualizar via Jquery eu tentei isso, mas sem sucesso.
$("#mydiv").load(location.href + "#mydiv");

Comment: Sim, usando jquery + ajax. De qualquer forma, adicione na pergunta o que você já fez para que facilite ajudar no seu caso em especifico.
Comment: Possível duplicata de [Mudar o conteúdo da div sem dar refresh na página](http://pt.stackoverflow.com/a/80892/13561), responde a pergunta do título, mas não responde a parte sobre *cookies* e múltiplas abas, sugiro uma edição, explicando melhor essa parte do problema
Comment: @DiegoFelipe atualizei a pergunta
Answer: Resolvido
 $.ajax({
         url: "exemplo.php",
         type: 'GET',
         success: function(html){
             var headline = $(html).find('#mydiv');
             $('#mydiv').html(headline);
         }
 });

Atualizar conteúdo de DIV


Cast return type in postsharp

Question: I want to use PostSharp follow code:
class Program
{
    [PostModerator]
    public static ReturnState<Person> GetPerson()
    {
        return new ReturnState<Person>() { Result = new Person { Id = 2, Name = "Gholzam" }, Succeed = true };
    }

    static void Main(string[] args)
    {
        var personAttempt= GetPerson();
        Console.WriteLine("Test ok");
        Console.ReadKey();
    }
}

in PostModerator I use follow code:
[Serializable]
public class PostModeratorAttribute : OnMethodBoundaryAspect
{
    public override void OnEntry(MethodExecutionArgs args)
    {
        args.ReturnValue = new ReturnState<object> { Succeed=false };//Star
        args.FlowBehavior = FlowBehavior.Return;

        for (int counter = 0; counter < args.Arguments.Count; counter++)
        {
            Console.WriteLine("arg{0} is {1}",counter,args.Arguments[counter]);
        }
        Console.WriteLine("On Entry");
    }
}

I have cast exception when I return new ReturnState<object>.. and Postshop try cast to ReturnState<Person> but can't.
Comment: And the exact exception details are...?
Comment: This method doesn't make a lot of sense? What are u trying to achieve? Because as it shows there you are just overiding your return value as soon as the method is entered? Why would you want to do that?
Comment: Next to that, you can make an abstract type, change your method to public static ReturnState GetPerson() Then your type Person that is derived from AbstractType (which you should give a meaningfull name.) Will be able to be returned. And in postsharp you will be able to return something in the likes of ReturnSate
Answer: Yes, that's because you're creating a ReturnState<object>, which isn't a ReturnState<Person>.
Options:

Change your PostModerateAttribute to find out the correct return type, and create an instance of that instead.
Hard-code PostModerateAttribute to return ReturnState<Person>
Change the return type (and expression) of your object to ReturnState<object>
Comment: I want to return anonymous type ,I can't use your options.
Comment: @Amirhosseingholzam: Why not? You can construct an instance of an anonymous type by reflection, which falls into option 1. Note that your question doesn't show an anonymous type at all.
Comment: You right. Options 1 is correct ,I know that but reflection is slow.
Comment: @Amirhosseingholzam: There are ways to make it not particularly slow - such as building (and then reusing) a delegate to create the instance. But your question seems to be changing a lot, and you shouldn't assume that something is too slow before you've actually tried it.
Comment: Thanks a lot @Jon Skeet, You can show me a good reference for this case.
Comment: @Amirhosseingholzam: Not easily, with so much of the question up in the air - we don't know what `ReturnState` looks like, whether it could be changed to that `Succeed` doesn't need to be explicitly set, etc. I suggest you try doing this the simple way first, check the performance, then post a new question if it's too slow.

Cast return type in postsharp


Classe abstrata e propriedades em C#?

Question: Ola, pessoal!
Seguinte, criei uma classe abstrata chamada Tabelas, onde classes de tabelas básicas do sistema herdarão dessa classe abstrata. Como Bairro, Cidade, Estados, categoria, etc..
O código da classe  abstrata está assim:
public abstract class Tabelas
{

    public int Id { get; set; }
    public string Nome { get; set; }

    public virtual int IdEstado { get; set; }
    public virtual int IdCidade { get; set; }
}

Acontece que, por exemplo, a classe Categoria que herda da abstrata, não contem os Campos IdEstado e IdCidade. Mas ao instanciá-la, o objeto faz referencia (acessa) essas duas propriedades. O mesmo acontece com a Classe Bairro, onde é para acessar apenas IdCidade, acessa também IdEstado.
Como implementar isso de forma mais performatica? Eu tenho que criar mais duas novas classes abstratas com IdEstado e IdCidade respectivamente, ou não definir esses dois atributos na classe abstrata, e sim definir somente na classe derivada?
Desculpe se fui confuso.
Obrigado.
Comment: É, está confuso. Talvez por isso que esteja com dificuldade para entender. Repense e tente escrever de uma forma menos confusa. Aí quem sabe vai até entender. Do jeito que está é difícil responder alguma coisa, teria que chutar o que você quer. Releia o texto escrito. Você já deve ter percebido que não faz muito sentido o que está escrito. Se você arrumar, fica mais fácil ajudar.
Comment: A classe abstracta só deve ter métodos e propriedades que devam existir **em todas** as derivadas. Ao criar a derivadas acrescente aqueles que lhe são relacionados.
Comment: Eu me pergunto até se você precisa realmente de uma classe abstrata. Quanto aos campos, herança faz isso, você precisa rever seus conceitos de modelagem para o projeto pelo exemplo, me parece que você tem vários objetos que precisam ser identificados por tipo e instância no sistema, algo como uma classe basica para todos (like Object). É isso?
Answer: Você está vivenciando um problema bem comum que acontece quando vemos na herança uma solução para reutilização de código: fica difícil achar na cadeia hierárquica a classe certa para publicar um atributo ou comportamento e, por não encontrarmos a classe ideal, o membro acaba aparecendo onde deve e também onde não deve.
Herança é aplicável para obter polimorfismo em uma relação hierárquica. Se a relação não for hierárquica, usar interfaces pode ser mais adequado (e muitas vezes é mais adequado mesmo quando o relacionamento é naturalmente hierárquico).
Não é porque um atributo ou comportamento é útil em mais de um objeto que devemos usar herança para reaproveitá-lo ou "reutilizá-lo".
Para encontrar a modelagem ideal, investigue mais a fundo o problema. Qual problema você quer resolver com esta hierarquia? Quais são todas as entidades envolvidas?
Considere ainda se você realmente precisa que os objetos na cadeia assumam a forma uns dos outros (polimorfismo) ou se você está apenas tentando reutilizar código (ou pior: reutilizar apenas declarações de membros).
Pelas entidades listadas na pergunta, dá para concluir que o que você precisa é representar cada uma destas entidades na sua forma mais específica ("Categoria", "Estado", "Cidade" e "Bairro"), e precisa também representar todas elas na forma de Tabela.
Neste caso, esta modelagem atende e não sofre do problema de membros aparecendo onde não devem:
interface Tabela
    int Id
    string Nome

class Categoria : Tabela
    int Id // implementação exigida pela interface Tabela
    string Nome // implementação exigida pela interface Tabela

class Estado : Tabela
    int Id // implementação exigida pela interface Tabela
    string Nome // implementação exigida pela interface Tabela

class Cidade: Tabela
    int IdEstado

    int Id // implementação exigida pela interface Tabela
    string Nome // implementação exigida pela interface Tabela

class Bairro : Tabela
    int IdCidade

    int Id // implementação exigida pela interface Tabela
    string Nome // implementação exigida pela interface Tabela

Classe abstrata e propriedades em C#?


How to create a "scorched area" on a 3D terrain?

Question: i'm experimenting a bit with C# and XNA. Going through the advanced "Riemers tutorials" helped me a lot, but i want to make my terrain even better. I have a simple game where player controls a tank and destroys other buildings and tanks. I would like to somehow draw the effects of the explosion on the terrain. The effect i want can be seen in many new games, for example HERE in the lower right corner you can see two dark spots on the ground (some explosion occured there a while ago probably). This is exactly what i want to achieve.
Could someone point me in the right direction? I think multitexturing will be needed, but when it came to this i found myself a little bit lost (all the stuff with pixel shaders...). Is this the only way? And if so, could someone help me understand how can i make it to work? Or are there other approaches? Thanks.
EDIT: Forgot to say that i'm not familiar with 3d graphics theory. Everything i know is based on brief tutorials, so a more detailed explanation might be needed. Currently i have no idea how would i draw something on an already textured surface.
Answer: You may want to check out this blog, it goes hand-in-hand with the Riemers tutorials. http://allenwp.com/blog/2010/05/06/simple-fast-gpu-driven-multi-textured-terrain/.
Hopefully this can get you pointed in the right direction, there is a pretty good walkthrough here.
Comment: Thanks! This is perfect. Will award the bounty as soon as it will be possible.
Answer: I haven't used XNA, but I believe what you're looking for is covered in this forum thread http://forums.xna.com/forums/p/34339/198791.aspx
Comment: Thanks for the link, but to be honest this does not help me much. I'm not familiar with 3d graphics theory so i'm looking for a more detailed explanation.


I don't know why the core modules in node js are not being recognized within my project using IntelliJ Idea (2016)

Question: I keep getting the error: Cannot find module 'serve-favicon.' This error occurs not just for serve-favicon but for all core modules which also includes 'body-parser', 'cookie-parser', etc.  I am using IntelliJ IDEA (version: 2016).  I already enabled the Node.js Core library, and I have been able to use core modules in other projects successfully.  What is different about this project however, is that I pulled it from github.  Do I need to install another plugin? If yes, which one? Do I need to add another package?
Answer: serve-favicon, body-parser, cookie-parser are not node.js core modules.
You will need to install these dependencies from npm registry. To install these dependencies, you will need to run
npm install <package-name> --save

If you have pulled the project from github, chances are there will be a package.json file with a list of dependencies. In that case, all you need to do is run npm install from the project folder.


Para que serve o Yield?

Question: Há já algum tempo que tenho escrito alguns scripts básicos com o Python, em alguns tutoriais às vezes é-me apresentado o yield, que normalmente surge em estruturas de repetição comumente while. Para que serve? E como usar?
Answer: O Python tem especificidades próprias mas essencialmente em todas linguagens funcionam igual. Ele cria um generator, ou seja, cria uma lista de dados que vão sendo consumidos sob demanda. Em geral é usado para dar melhores abstrações ao código. Tudo que se faz com ele, dá para fazer sem ele de forma muito semelhante, mas expondo o mecanismo de geração dos dados.
Ele retorna um valor mantendo o estado de onde parou. Quando executa de novo ele continua de onde parou. Ele controla o estado de um enumerador entre execuções da função.
def impar(elems):
    for i in elems:
        if i % 2:
            yield i

for x in impar(range(1000)):

Fonte.
Este código imprimirá todos os ímpares de 0 à 1000. Ele vai chamar o método 500 vezes, cada vez trará um número ímpar. O compilador/biblioteca montará a estruturá interna para saber em que número ele está em cada chamada.
Claro que tem uma variável escondida que sobrevive além do ambiente interno da função. Então esse i não começa de novo em cada chamada da função. Note que você pode chamar a função impar() sem saber como ela faz a seleção internamente.
Este exemplo é simples e óbvio, mas pense em coisas mais complexas. Você abstrai melhor. Você diz que vai chamar um método que filtra os ímpares para você. Não interessa como. O que você vai fazer com a informação gerada é problema seu. A função com o yield tem responsabilidade única de gerar a informação.
Outro exemplo:
def numeros():
    yield 1
    yield 2
    yield 3

print numeros()
print numeros()
print numeros()

Coloquei no GitHub para referência futura.
Isto imprimirá 1, 2 e 3.
Veja explicações em C# e PHP.
Comment: É ao contrário. A ideia do come, é boa, vai pegando uma semente cada vez. Mas é com interrupções. O `yield` é um `return`, ele encerra a execução, ele interrompe. Mas o saco de sementes continua lá do jeito que você deixou. Não começa um saco novo toda vez que chamar, como ocorreria no `return`. Não precisa ser uma estrutura de repetição, mas precisa ter uma sequência de dados.
Comment: Sim, totalmente. Editei para dar um exemplo diferente.
Comment: Em poucas palavras, o `yield` _"come"_ alguns dos valores contidos numa estrutura de repetição, sem causar interrupções, é isto ?
Comment: No caso, interrupções controladas ?
Comment: Deu para entender, obrigado pelo tempo.
Comment: Por ser um exemplo didático seria mais interessante simplificar ao máximo a sintaxe. Ao passar o construtor para o for ao invés de impar(range(1000)) usar impar(1000), ou seja, o "range" vai para dentro do def, o que confunde menos.
Comment: Vale a pena ver esse [vídeo](https://www.youtube.com/watch?v=vOMtQ4ocMGI&ab_channel=CoreySchafer) pra complementar ainda mais a resposta
Answer: Complementando a resposta de Maniero, algumas características do yield:
Yield no Python é usado sempre que você precisa definir uma função de gerador de algo.
Você não pode usar yield fora de um generator function.
Quando você usa a instrução yield dentro de uma função, ela se transforma em uma função geradora.
Função geradora é uma função que retorna mais do que um valor - retorna uma série de valores.
Um uso comum é dentro de loops, como por exemplo:
for value in simpleGeneratorFun():
     print(value)

E a declaração da nossa função geradora seria algo assim:
def simpleGeneratorFun():
    for i in range (1, 4):
        yield i

Sempre que a instrução yield ocorre dentro da função  geradora, o programa pausa a execução e retorna o valor para o chamador. No exemplo acima, ela retorna um value no for.
O yield retém o estado da função onde ela é pausada (ao retornar o value).
Da próxima vez, quando um chamador chamar a função geradora - no nosso caso, o for - o corpo da função executará a instrução de onde ela foi pausada, em vez de executar a primeira instrução.
Você pode chamar a função geradora, contanto que não tenha atingido sua última declaração, ou seja, na primeira vez que chamar simpleGeneratorFun() ela vai retornar 1. Na segunda, irá retornar 2, até chegar em 4.
Resumido, um pouco editado para melhor entendimento e traduzido de:
https://www.csestack.org/python-yield-vs-return-explained-detail-examples/
Answer: o yield faz parte do protocolo de iteradores do python, ele evita vc ter que criar o elemento iterável efetivamente, tornando seu código mais escalável, poupando memória principalmente.
Como exemplo, imagine que vc tem uma lista de números inteiros e queira um loop não por esses números e sim pelo quadrado deles. Uma solução natural seria criar uma lista iterando por cada elemento da primeira e alocando em cada posição o quadrado do valor. Neste caso, vc terá uma nova lista criada alocando memória que pode facilmente explodir dependendo do número de elementos de sua lista fonte.
No caso das GENERATOR FUNCTIONS (definição de funções que utilizam yield e não return), elas retornam um GENERATOR OBJECT que no fundo no fundo é um iterator. Este iterator consegue salvar o estado atual do objeto acessando o próximo a partir do anterior, com isso vc não precisa em momento algum alocar sua lista inteira. Os valores são acessados sob demanda em um loop ou através da build-in function next(). Ao utilizar o yield sua função funciona como uma corrotina, na primeira vez que é chamada, a função começa executar desde sua primeira linha, ao chegar no yield ela para retornando o valor definido ao ser chamada novamente ela começa a rodar da linha seguinte ao yield com isso ela consegue funcionar como um iterador.
Outra forma de criar interator's em python é através da orientação a objetos utilizando os dunder methods iter e next.
Vou colocar a fonte de um livro muito bom sobre este tópico.
Powerful Python: The Most Impactful Patterns, Features and Development Strategies Modern Python Provides

Para que serve o Yield?


failing pipeline with a valid jenkins script "No such static method found: staticMethod"

Question: i am trying to implement jenkins script for monitoring slaves agents
following this article: "https://www.jenkins.io/doc/book/managing/nodes/"
i ran this script in the jenkins script consul successfully but i keep failing when i run it inside a pipeline
import hudson.node_monitors.*
import hudson.slaves.*
import java.*
import javax.activation.*
import thread.*
import java.lang.*

def getEnviron(computer) {
   def env
   def thread = Thread.start("Getting env from ${computer.name}", { env = computer.environment })
   thread.join(2000)
   if (thread.isAlive()) thread.interrupt()
   env
}

def slaveAccessible(computer) {
    getEnviron(computer)?.get('PATH') != null
}

def numberOfflineNodes = 0
def numberNodes = 0

pipeline {
    parameters {
         string(name: 'Slack_channel',
           description: 'OTT DevOps channel',
           defaultValue: '#ott-devops-team')
    }
    environment {
   // Slack configuration
   SLACK_COLOR_DANGER  = '#E01563'
   SLACK_COLOR_INFO    = '#6ECADC'
   SLACK_COLOR_UNSTABLE    = '#E01563'
   SLACK_COLOR_WARNING = '#FFC300'
   SLACK_COLOR_GOOD    = '#3EB991'
   }

    agent {label "master"}
    stages {
        stage('monitor and restart slave agents') {
            steps {
                script {

                    def jenkins = Hudson.instance

                    for (slave in jenkins.slaves) {
                       def computer = slave.computer
                       numberNodes ++
                       println ""
                       println "Checking computer ${computer.name}:"
                       def isOK = (slaveAccessible(computer) && !computer.offline)
                       if (isOK) {
                         println "\t\tOK, got PATH back from slave ${computer.name}."
                         println('\tcomputer.isOffline: ' + slave.getComputer().isOffline());
                         println('\tcomputer.isTemporarilyOffline: ' + slave.getComputer().isTemporarilyOffline());
                         println('\tcomputer.getOfflineCause: ' + slave.getComputer().getOfflineCause());
                         println('\tcomputer.offline: ' + computer.offline);

                       } else {
                         numberOfflineNodes ++
                         println "  ERROR: can't get PATH from slave ${computer.name}."
                         println('\tcomputer.isOffline: ' + slave.getComputer().isOffline());
                         println('\tcomputer.isTemporarilyOffline: ' + slave.getComputer().isTemporarilyOffline());
                         println('\tcomputer.getOfflineCause: ' + slave.getComputer().getOfflineCause());
                         println('\tcomputer.offline: ' + computer.offline);
                         if (slave.getComputer().isTemporarilyOffline()) {
                          if (!slave.getComputer().getOfflineCause().toString().contains("Disconnected by")) {
                             computer.setTemporarilyOffline(false, slave.getComputer().getOfflineCause())
                          }
                         } else {
                             computer.connect(true)
                         }
                       }
                     }
                    println ("Number of Offline Nodes: " + numberOfflineNodes)
                    println ("Number of Nodes: " + numberNodes)
                }
            }
        }
    }
   post {
   aborted {
     echo "Sending message to Slack"
     slackSend (color: "${env.SLACK_COLOR_WARNING}",
                channel: "${params.Slack_channel}",
                message: "*ABORTED:* Job ${env.JOB_NAME} build ${env.BUILD_NUMBER} \n More info at: ${env.BUILD_URL}")
   } // aborted
   unstable {
     echo "Sending message to Slack"
     slackSend (color: "${env.SLACK_COLOR_UNSTABLE}",
                channel: "${params.Slack_channel}",
                message: "*UNSTABLE:* Job ${env.JOB_NAME} build ${env.BUILD_NUMBER} \n More info at: ${env.BUILD_URL} in ${params.ENV}")
   } // unstable
   failure {
     echo "Sending message to Slack"
     slackSend (color: "${env.SLACK_COLOR_DANGER}",
                channel: "${params.Slack_channel}",
                message: "*FAILED:* Job ${env.JOB_NAME} build ${env.BUILD_NUMBER} \n More info at: ${env.BUILD_URL} ")
   } // failure
   success {
     echo "Sending message to Slack"
     slackSend (color: "${env.SLACK_COLOR_GOOD}",
                channel: "${params.Slack_channel}",
                message: "*SUCCESS:* Job ${env.JOB_NAME} build ${env.BUILD_NUMBER} \n More info at: ${env.BUILD_URL} ")
   } // success
  } // post
}

the error code is:
org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: No such static method found: staticMethod java.lang.Thread start org.codehaus.groovy.runtime.GStringImpl org.jenkinsci.plugins.workflow.cps.CpsClosure2
    at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SandboxInterceptor.onStaticCall(SandboxInterceptor.java:182)
    at org.kohsuke.groovy.sandbox.impl.Checker$2.call(Checker.java:187)
    at org.kohsuke.groovy.sandbox.impl.Checker.checkedStaticCall(Checker.java:191)
    at org.kohsuke.groovy.sandbox.impl.Checker.checkedCall(Checker.java:98)
    at com.cloudbees.groovy.cps.sandbox.SandboxInvoker.methodCall(SandboxInvoker.java:17)
    at WorkflowScript.getEnviron(WorkflowScript:12)
    at WorkflowScript.slaveAccessible(WorkflowScript:19)
    at WorkflowScript.run(WorkflowScript:56)
    at ___cps.transform___(Native Method)
    at com.cloudbees.groovy.cps.impl.ContinuationGroup.methodCall(ContinuationGroup.java:84)
    at com.cloudbees.groovy.cps.impl.FunctionCallBlock$ContinuationImpl.dispatchOrArg(FunctionCallBlock.java:113)
    at com.cloudbees.groovy.cps.impl.FunctionCallBlock$ContinuationImpl.fixArg(FunctionCallBlock.java:83)
    at sun.reflect.GeneratedMethodAccessor307.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.cloudbees.groovy.cps.impl.ContinuationPtr$ContinuationImpl.receive(ContinuationPtr.java:72)
    at com.cloudbees.groovy.cps.impl.ClosureBlock.eval(ClosureBlock.java:46)
    at com.cloudbees.groovy.cps.Next.step(Next.java:83)
    at com.cloudbees.groovy.cps.Continuable$1.call(Continuable.java:174)
    at com.cloudbees.groovy.cps.Continuable$1.call(Continuable.java:163)
    at org.codehaus.groovy.runtime.GroovyCategorySupport$ThreadCategoryInfo.use(GroovyCategorySupport.java:129)
    at org.codehaus.groovy.runtime.GroovyCategorySupport.use(GroovyCategorySupport.java:268)
    at com.cloudbees.groovy.cps.Continuable.run0(Continuable.java:163)
    at org.jenkinsci.plugins.workflow.cps.SandboxContinuable.access$001(SandboxContinuable.java:18)
    at org.jenkinsci.plugins.workflow.cps.SandboxContinuable.run0(SandboxContinuable.java:51)
    at org.jenkinsci.plugins.workflow.cps.CpsThread.runNextChunk(CpsThread.java:186)
    at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.run(CpsThreadGroup.java:370)
    at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.access$200(CpsThreadGroup.java:93)
    at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup$2.call(CpsThreadGroup.java:282)
    at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup$2.call(CpsThreadGroup.java:270)
    at org.jenkinsci.plugins.workflow.cps.CpsVmExecutorService$2.call(CpsVmExecutorService.java:66)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at hudson.remoting.SingleLaneExecutorService$1.run(SingleLaneExecutorService.java:131)
    at jenkins.util.ContextResettingExecutorService$1.run(ContextResettingExecutorService.java:28)
    at jenkins.security.ImpersonatingExecutorService$1.run(ImpersonatingExecutorService.java:59)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
Finished: FAILURE

using the same script inside the http://jenkins_home/script is working fine
there is no waiting approval requests in the /scriptApproval/
Answer: The exception comes from the script security plugin.
You will see under Manage Jenkins -> In-process Script Approval (or surf to <your-jenkins-host>/scriptApproval) the line(s) you need to approve in order to run the script.
If there are multiple offending lines you will need to repeat this process until all security requirements are satisfied.
Another way is to disable the groovy sandbox in the pipeline altogether (right under the script box when you configure the pipeline), but unless you're testing it's best to leave it ticked.
Comment: hi
i configured it without sandbox but its still failing for the same reason
i done have any requests in the /scriptApproval as well
Comment: For the sake of the experiment you can disable the script security plugin temporarily, because this is the source of the exception (maybe a bug in the version you have?). Then you can re-run the pipeline and see if the build's output is any different