Enviar o caminho da imagem do js para o html - DOM

Question: Olá, preciso realizar um exercício simples com nós em js em que tenho que criar as tags de 6 cards e depois enviar o conteúdo desses cards pelo js, acontece que para mim ainda não é simples. Até consigo enviar todos os dados que o exercício propõe manipulando a DOM,e está tudo sendo renderizado na tela, menos as imagens, acredito que o erro está em não passar corretamente o valor do atributo criado 'src',já que, trocando meu arquivo de imagens por um endereço qualquer da internet, a imagem é renderizada:
        let elemento_pai= document.body;
        let divContainer= document.getElementsByClassName('container')
        let divItem = document.querySelectorAll('div')[0];
        let imgUrl = document.getElementsByTagName('img');
        let h2Title = document.getElementsByTagName('h2')[0];
        let textCard = document.getElementsByTagName('p')[0];
        let created = document.getElementsByTagName('p')[0];

        divContainer = document.createElement('div');
            elemento_pai.appendChild(divContainer);
            divContainer.classList.add('container')

        for (let index = 0; index < 6; index++){

            let divItem = document.createElement('div')
            divContainer.appendChild(divItem)
            divItem.classList.add('item')

            let imgUrl = document.createElement('img');
            divItem.appendChild(imgUrl);
            imgUrl.classList.add('imgCard')
            imgUrl.setAttribute('src','https://ciclovivo.com.br/wp-content/uploads/2015/11/12233034_943758819028895_1015830412_n.jpg');
            imgUrl.innerHTML  = listaDeFelinos[index].imgUrl;

            let h2Title = document.createElement('h2');
            divItem.appendChild(h2Title)
            //como renderizar o texto em cada card! O que vai ditar é o index!E a resposta estava na minha cara esse tempo todo!
            h2Title.innerHTML  = listaDeFelinos[index].title;

            let textCard = document.createElement('p');
            divItem.appendChild(textCard);
            textCard.innerHTML  = listaDeFelinos[index].description;

            let created = document.createElement('p');
            divItem.appendChild(created)
            created.innerHTML  = listaDeFelinos[index].createdAt;

            console.log(divContainer, imgUrl, h2Title, textCard, created);
        }

o conteúdo que precisa ser renderizado em cada card:
const listaDeFelinos = [

    //0
    {
        title: 'Tigre',
        imgUrl: './imagens/tiger.jpg',
        description: 'O tigre (Panthera tigris) é uma das espécies da subfamília pantherine (família Felidae) pertencente ao gênero Panthera. Encontra-se apenas no continente asiático; É um predador carnívoro e é a maior espécie de felídeo do mundo, juntamente com o leão, ambos podem atingir um tamanho comparável ao de fósseis de felinos maiores.',
        createdAt: '2021-06-01T23:12:11.837Z'
    },

    //1
    {
        title: 'Leão',
        imgUrl: './imagens/leon.jpg',
        description: 'O leão (Panthera leo) é um mamífero carnívoro da família Felidae e uma das cinco espécies do gênero Panthera. Os leões selvagens vivem em populações cada vez mais dispersas e fragmentadas na África subsaariana (exceto nas regiões de selva da costa atlântica e na bacia do Congo) e em uma pequena área do noroeste da Índia.',
        createdAt: '2021-05-05T23:12:11.837Z'
    }

Answer: Em vez de definir o innerHTML tens que definir o atributo src.
imgUrl.setAttribute('src', listaDeFelinos[index].imgUrl);


What is the largest sigma-field on R ? And also what is borel sigma field?

Question: I take taking an introductory course on probability and stochastic processes and want to understand the sigma field on R.
What is the largest sigma-field on R ? And also what is the Borel sigma field?
Omega (Sample Space) = R
F' = {phi, omega, (a,inf), (a,b], (-inf,a), [a,inf), (a,b), [a,b], [a,b), {a} }
Is F' a borel sigma field?
Please help.
Answer: What do you mean by largest? One that contains most sets? Well, you can take the power set of $\mathbb{R}$, it is a sigma field. (though a not so interesting one, it contains way too many sets, so it's difficult to define an interesting measure on it)
As for Borel sigma field, this is the smallest sigma field which contains all the open subsets of $\mathbb{R}$. A formal definition-the intersection of all sigma fields on $\mathbb{R}$ which contain all the open sets. (it is easy to check that any intersection of sigma fields is also a sigma field). Now this is really an important sigma field-it isn't too large but still contains all the "good sets".
Comment: What do you mean by all the open subsets? And is the largest sigma field on R an uncountably infinite set?
Comment: The power set of $\mathbb{R}$ has cardinality $2^{|\mathbb{R}|}=2^{2^{\aleph_0}}$. So it's not just uncountable, it is even larger than $\mathbb{R}$. As for open sets, this is the standard definition: a subset $O\subseteq\mathbb{R}$ is open if for every $x\in O$ there is some $\delta>0$ such that the interval $(x-\delta, x+\delta)$ is contained in $O$. ($\delta$ depends on the point $x$). For example, any open interval is open.
Comment: How to find the Borel field on R?
Comment: Well, start by taking all the open sets. Since you want to find a sigma field you need to add all of their complements (which are the closed sets), countable unions and intersections. So this sigma field must also contain countable intersections of open sets and countable unions of closed sets. This collection is still not a sigma field, you again have to take complements, countable unions and intersections of these sets. Then repeat it again and again. Finally, we need to use transfinite induction to prove the process will eventually stop. So yeah, it's not easy.
Comment: please see the new change in question.
Comment: I suppose you defined it for all $a,b\in\mathbb{R}$. No, the set you defined is contained in the Borel sigma field, but still not equal to it. As I said, you need to take countable unions and intersection of such sets, and keep doing that again and again. (formally by transfinite induction). So it's difficult to describe all Borel sets. But yes, the sets you defined are Borel sets, the most basic ones.


Countability of a set: only 2 options?

Question: So I know sets can be countable (bijection between set and $\mathbb{N}$, finite) or uncountable. Is there another option or are all sets either or?
Comment: Well, your question is like: "all the living beings on this planet are humans or non-humans. Is there any other option?" The third excluded principle makes that clear.
Comment: If you believe in classical logic (tertium non datur), then all sets are either or. But there are of course different orders of uncountability.
Comment: There are uncountable sets of different sizes, but yes, every set is either countable or uncountable, and none is both. It's no different from saying that every set either has at most $10$ elements or has more than $10$ elements.
Answer: Once you accept the law of excluded middle, and $\varphi$ is a property which you can express (e.g. countability) every element in the universe either satisfies $\varphi$ or its negation.
Recall the definitions:

$A$ is countable if there is an injection from $A$ into $\Bbb N$.
$A$ is uncountable if it is not countable.

So every set $A$ either satisfies the property "being countable", in which case it is countable; or it doesn't in which case... it is uncountable.
Of course, much like "finite" doesn't tell you much about the cardinality of a set, just that it is finite, being uncountable doesn't tell you much about the cardinality of a set except that it is not countable. There are many uncountable sets of different cardinalities, but they are all uncountable nonetheless (much like there are many irrational numbers with varying algebraic and algebraic-like properties, but they are all irrational numbers nonetheless).
Comment: I understand that, logically, Dedekind-finite infinite sets are uncountable, but I can't help feeling that they are unworthy of the name. By the way, if you use the word "denumerable" to mean "equipollent to $\mathbb N$", as some people do, then by the same logic, finite sets should be nondenumerable. But I don't think anyone actually uses "nondenumerable" to mean "finite or uncountable".
Comment: bof, first of all if you learn more about infinite Dedekind-finite you will learn that they deserve every bit of the name "uncountable". I also never heard anyone uses "non-denumerable". Ever.
Answer: There are varying degrees of uncountability, but since "uncountable" means "not countable," a set is either countable or not, hence either countable or uncountable.
As for the varying degrees, in general $2^A$, the set of all subsets of a set $A$, has a different cardinality than does $A$. So $U = 2^\mathbb N$ is bigger than $\mathbb N$, and $2^U$ is even bigger than $U$, and so on.
Answer: Cantor's theorem says that the cardinality of the power set $2^A$ (the power set is the set of all subsets of a set) of $A$ is larger than the cardinality of $A$. This means that $2^{\Bbb{R}}$ has a larger cardinality than $\Bbb{R}$. But if you take the definition of uncountable to be anything which isn't finite and can't be put into bijection with $\Bbb{N}$ then yes, everything is either at most countable or uncountable. There are an infinite number of different infinite cardinalities though.
We can know surprisingly little about these cardinalities beyond this. It turns out that the continuum hypothesis, which states there are no sets with cardinality between that of the intergers and that of the real numbers (i.e. the continuum) cannot be proven or disproven using ZFC, which is the "standard model" of mathematics.
It can be proven if you assume the Axiom of Choice that the cardinality of the integers is the smallest non-finite cardinal. This is called $\aleph_0$.
It also turns out that if you assume the Axiom of Choice, you know that there is  a smallest cardinality, or cardinal number, which is larger than any given one. The smallest one larger than $\aleph_n$ is called $\aleph_{n+1}$ and then you have a linear ordering on all cardinals. Without AC things are more challenging.
Comment: I think that this answer can be very confusing to someone not already possessing enough knowledge about set theory. (Also since you mention the axiom of choice, the result about $\aleph_0$ being the smallest infinite cardinal also requires some choice.)
Comment: @AsafKaragila I imagine if one knows the proof that the real numbers are uncountable they could probably understand the statement of Cantor's theorem and know about AC. My primary purpose was to link to the wikipedia articles. I added the part about requiring choice for $\aleph_0$.
Comment: Sam, in my universities there is no introductory course to set theory, and one learns these things in some calculus related course. They don't learn Cantor's theorem, just the diagonal argument; they don't learn about the axiom of choice either. In other places, they don't really teach about the axiom of choice nor $\aleph$ numbers in undergrad set theory courses. Just today I had lunch with three professors (one senior, and two starting ones - both of them from visiting) and we had a few words about undergrad set theory being naive and all that.

Countability of a set: only 2 options?


How to graph $f(x)= \frac{1}{2} (e^x + e^{-x})$ without graphing app?

Question:
The function $f$ is defined by $f(x)= \frac{1}{2} (e^x + e^{-x})$, $x \in \Re$.
Show that $f$ has no inverse.

If I am to show that function $f$ has no inverse, I would graph function $f$ and show that it does not pass the horizontal-line test, as a horizontal line passing through the graph would have more than one intersection point.
The problem is, I am not sure how to graph $f(x)= \frac{1}{2} (e^x + e^{-x})$ without using a graphing application. I know how a $y=e^x$ graph looks like, but how do I combine $e^x + e^{-x}$?
I thought of using Piecewise function, but I do not know how to proceed.
Comment: Note that $f(x)=f(-x)$ so... ?
Comment: @DominikKutek it's a reflection on the y-axis....but how can I tell by looking at the function, how a graph looks like? if I don't use a graphing app
Comment: This (real) function is the hyperbolic cosine , and it is an even function. Thus it can't be injective and then it is non-invertible. If you insist in plotting it then care only about $\;x\ge 0\;$ .
Comment: It is easy to see that it's even, no need for graphing it. And because it isn't injective, then it cannot has inverse
Comment: Is it possible to use Piecewise function to graph this?
Answer: We have that
$$\lim_{x\to0^+}\frac{e^x}2=\frac12\;,\;\;\lim_{x\to0^+}\frac{e^{-x}}2=\frac12$$
and then
$$\lim_{x\to\infty}\frac{e^x}2=\infty\;,\;\;\lim_{x\to0^+}\frac{e^{-x}}2=0$$
And all this basically tells you what happens to the graph of the function for $\;x\ge0\;$.
If we add to this that the function is monotonically ascending since
$$f'(x)=\frac12\left(e^x-e^{-x}\right)=\frac{2^{2x}-1}{2e^x}>0\,,$$
Since the exponential is ascending and $\;e^{2x}>e^x\;$, you can see how the positive (and thus also the negative) branch of this function ascend pretty quickly to $\;\infty\;$
Comment: Thank you for your answer, but can you edit some parts because I can't as the editing is less than 6 characters? added an equal sign for the second limit in the first row; edited typo in 'monotonically'; edited $f'(x)$ function in numerator part $e^{2x}$. Thank you
Comment: @gc3941d Thank you, edited.
Answer: Let $f(x) = \frac12(e^x + e^{-x}).$
$f''(x) = \frac12(e^x + e^{-x}) > \frac12(0+0)= 0$ for all $x$, i.e. $f(x)$ is strictly concave.
Also, as pointed out before, $f(x)$ is even: $f(x) = f(-x)$, and this means that the graph can be reflected in the $y-$axis. Concavity along with evenness of $f$ suggests that $f(0)$ is a minimum.
Let's confirm the stationary points of the graph for good measure. $f'(x) = 0 \implies e^x - e^{-x} = 0 \implies e^x = \frac{1}{e^x} \implies e^{2x} = 1 \implies 2x = 0 \implies x=0,$ so $(0,f(0)) = (0,1)$ is the only stationary point and it is a minimum because $f$ is concave.
Also, $\lim_{x \to \infty}f(x) = \lim_{x \to -\infty}f(x) = \infty $, but we are still not done, because we haven't shown that our graph doesn't have asymptotes. But $\lim_{x \to \infty}f'(x) = \lim_{x \to \infty}{ \left(e^x - e^{-x}\right)} = \infty,$ and $\lim_{x \to -\infty}f'(x) = \lim_{x \to -\infty}{ \left(e^x - e^{-x}\right)} = -\infty.$
And now we know what the graph looks like.


Use a colourmap to change line colour

Question: I have a lot of different files (10-20) that I read in x and y data from, then plot as a line.
At the moment I have the standard colors but I would like to use a colormap instead.
I have looked at many different examples but can't get the adjustment for my code right.
I would like the colour to change between each line (rather than along the line) using a colormap such as gist_rainbow i.e. a discrete colourmap
The image below is what I can currently achieve.
This is what I have attempted:
import pylab as py
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rc, rcParams

numlines = 20
for i in np.linspace(0,1, numlines):
    color1=plt.cm.RdYlBu(1)
    color2=plt.cm.RdYlBu(2)

# Extract and plot data
data = np.genfromtxt('OUZ_QRZ_Lin_Disp_Curves')
OUZ_QRZ_per = data[:,1]
OUZ_QRZ_gvel = data[:,0]
plt.plot(OUZ_QRZ_per,OUZ_QRZ_gvel, '--', color=color1, label='OUZ-QRZ')

data = np.genfromtxt('PXZ_WCZ_Lin_Disp_Curves')
PXZ_WCZ_per = data[:,1]
PXZ_WCZ_gvel = data[:,0]
plt.plot(PXZ_WCZ_per,PXZ_WCZ_gvel, '--', color=color2, label='PXZ-WCZ')
# Lots more files will be plotted in the final code
py.grid(True)
plt.legend(loc="lower right",prop={'size':10})
plt.savefig('Test')
plt.show()

Comment: You might find this question/answer related: [Plotting arrows with different color in matplotlib](http://stackoverflow.com/questions/18748328/plotting-arrows-with-different-color-in-matplotlib)
Answer: You could take a few different approaches. On your initial example you color each line specifically with a different color. That works fine if you are able to loop over the data/colors you want to plot. Manually assigning each color, like you do now, is a lot of work, even for 20 lines, but imagine if you have hundred or more. :)
Matplotlib also allows you to edit the default 'color cycle' with your own colors. Consider this example:
numlines = 10

data = np.random.randn(150, numlines).cumsum(axis=0)
plt.plot(data)

This gives the default behavior, and results in:

If you want to use a default Matplotlib colormap, you can use it to retrieve the colors values.
# pick a cmap
cmap = plt.cm.RdYlBu

# get the colors
# if you pass floats to a cmap, the range is from 0 to 1,
# if you pass integer, the range is from 0 to 255
rgba_colors = cmap(np.linspace(0,1,numlines))

# the colors need to be converted to hexadecimal format
hex_colors = [mpl.colors.rgb2hex(item[:3]) for item in rgba_colors.tolist()]

You can then assign the list of colors to the color cycle setting from Matplotlib.
mpl.rcParams['axes.color_cycle'] = hex_colors

Any plot made after this change will automatically cycle through these colors:
plt.plot(data)

Comment: Hi Rutger, I am having trouble with the line: `hex_colors = [mpl.colors.rgb2hex(item[:3]) for item in rgba_colors.tolist()]` I get an error message of `hex_colors = [plt.colors.rgb2hex(item[:3]) for item in rgba_colors.tolist()]
 AttributeError: 'function' object has no attribute 'rgb2hex'` I am not sure how to solve this?
Comment: Try importing matplotlib like: `import matplotlib as mpl`.

Use a colourmap to change line colour


Inequality involving floor function

Question: In the context of a paper I study, I want to prove an inequality. Consider $K,N$ positive integers and $a,b$ positive real numbers basically with $a=0.275$ and $b=1.1$. I try to prove the following
\begin{equation}
-\frac{(\lfloor a\cdot\mathrm{min}\{N,K\}\rfloor)^2}{1-\lfloor a\cdot\mathrm{min}\{N,K\}\rfloor/N}\frac{b\cdot\mathrm{max}\{1,N/K\}}{N}\geq-\mathrm{min}\{N,K\}\frac{ba^2}{1-a\cdot\mathrm{min}\{1,K/N\}}
\end{equation}
Equivalently we have that
\begin{eqnarray}
-\frac{(\lfloor a\cdot\mathrm{min}\{N,K\}\rfloor)^2}{1-\lfloor a\cdot\mathrm{min}\{N,K\}\rfloor/N}b\cdot\mathrm{max}\{1/N,1/K\}&\geq&-\mathrm{min}\{N,K\}\frac{ba^2}{1-a\cdot\mathrm{min}\{1,K/N\}}\\
-\frac{(\lfloor a\cdot\mathrm{min}\{N,K\}\rfloor)^2}{1-\lfloor a\cdot\mathrm{min}\{N,K\}\rfloor/N}b\cdot\mathrm{min}\{N,K\}&\geq&-\mathrm{min}\{N,K\}\frac{ba^2}{1-a\cdot\mathrm{min}\{1,K/N\}}\\
\Leftrightarrow\frac{(\lfloor a\cdot\mathrm{min}\{N,K\}\rfloor)^2}{1-\lfloor a\cdot\mathrm{min}\{N,K\}}/N&\leq&\frac{a^2}{1-a\cdot\mathrm{min}\{1,K/N\}}
\end{eqnarray}
by exploiting
\begin{equation}
\lfloor x\rfloor\geq x-1
\end{equation}
I am trying to compare the denominators so by the above identity
\begin{eqnarray}
\lfloor a\cdot\mathrm{min}\{N,K\}\rfloor/N&\geq&a\cdot\mathrm{min}\{N,K\}/N-1/N\\
\Leftrightarrow-\lfloor a\cdot\mathrm{min}\{N,K\}\rfloor/N&\leq&-a\cdot\mathrm{min}\{N,K\}/N+1/N\\
\Leftrightarrow1-\lfloor a\cdot\mathrm{min}\{N,K\}\rfloor/N&\leq&1-a\cdot\mathrm{min}\{N,K\}/N+1/N\\
\Leftrightarrow1-\lfloor a\cdot\mathrm{min}\{N,K\}\rfloor/N&\leq&1-a\cdot\mathrm{min}\{1,K/N\}+1/N
\end{eqnarray}
but I cannot reach a conclusive result here. Also I am not sure about the second step of the previous series of inequalities.
Comment: It seems that the inequality does not hold when $N=1,K=2,a=10.1, b=11$.
Comment: @mathlove basically in my case $a=0.275$ and $b=1.1$ are fixed but I did not state that in order to simplify the expression. I thought it woulnd't matter. $N,K$ are still arbitrary positive integers, though.
Answer: For $0\lt a\lt 1$ and $b\gt 0$ such that
$$1-\frac{\lfloor a\cdot\min\{N,K\}\rfloor}{N}\not=0\quad\text{and}\quad 1-a\cdot\min\left\{1,\frac KN\right\}\not=0$$
the inequality holds.
$$-\frac{(\lfloor a\cdot\mathrm{min}\{N,K\}\rfloor)^2}{1-\lfloor a\cdot\mathrm{min}\{N,K\}\rfloor/N}\frac{b\cdot\mathrm{max}\{1,N/K\}}{N}\geq-\mathrm{min}\{N,K\}\frac{ba^2}{1-a\cdot\mathrm{min}\{1,K/N\}}\tag1$$
Let us separate it into two cases :
Case 1 : $K\ge N$
$$\begin{align}(1)&\iff -\frac{(\lfloor a\cdot N\rfloor)^2}{1-\frac{\lfloor a\cdot N\rfloor}{N}}\cdot\frac{b\cdot 1}{N}\geq-N\cdot\frac{ba^2}{1-a\cdot 1}\\\\&\iff \frac{\lfloor aN\rfloor^2}{N-\lfloor aN\rfloor}\le \frac{(aN)^2}{N-aN}\tag2\end{align}$$
Multiplying the both sides of $(2)$ by $(N-\lfloor aN\rfloor)(N-aN)\gt 0$ gives
$$\begin{align}(2)&\iff (N-aN)\lfloor aN\rfloor^2\le (aN)^2(N-\lfloor aN\rfloor)\\\\&\iff a^2N^3-a^2N^2\lfloor aN\rfloor-N\lfloor aN\rfloor^2+aN\lfloor aN\rfloor^2\ge 0\\\\&\iff (aN+\lfloor aN\rfloor)(aN-\lfloor aN\rfloor)-a\lfloor aN\rfloor(aN-\lfloor aN\rfloor)\ge 0\\\\&\iff (aN-\lfloor aN\rfloor)(aN+(1-a)\lfloor aN\rfloor)\ge 0\end{align}$$
which holds for $0\lt a\lt 1$.
Case 2 : $K\lt N$
$$\begin{align}(1)&\iff -\frac{(\lfloor aK\rfloor)^2}{1-\frac{\lfloor aK\rfloor}{N}}\cdot\frac{b\cdot\frac NK}{N}\geq -K\cdot\frac{ba^2}{1-a\cdot\frac KN}\\\\&\iff \frac{\lfloor aK\rfloor^2}{N-\lfloor aK\rfloor}\le \frac{(aK)^2}{N-aK}\tag3\end{align}$$
Multiplying the both sides of $(3)$ by $(N-\lfloor aK\rfloor)(N-aK)\gt 0$ gives
$$(3)\iff (aK-\lfloor aK\rfloor)(NaK+(N-aK)\lfloor aK\rfloor)\ge 0$$
which holds for $0\lt a\lt 1$.
Comment: Thanks, it seems that you have a lot of imagination. How did you approach this problem? Those are the kinds of things I usually encounter when I study papers.
Comment: @mgus: You are welcome. Well, first, I found that separating the inequality into two cases should make it easy to deal with since the only thing that matters is the relation between $K$ and $N$. After this, I tried to simplify the inequality (hoping to factorize it) and luckily managed to factorize it. I hope this helps.
Comment: @mgus: In general, it is not very easy to deal with min, max. So, separating an (in)equality into some cases in order to eliminate min, max is a good start especially when many cases are not needed like our inequality.

Inequality involving floor function


Dynamically load .dlls from network share not browsable on client PC -- WCF?

Question: I'm architecting a WPF application using the PnP Composite Application Guidance. The application will be run locally, within our intranet.
Modules will be loaded dynamically based on user roles. The modules must therefore be accessible to the application through a network share, thus accessible from the client machines.
What I'd like to do is keep all the module .dlls in a location not accessible to staff, but still be able to provide them to the composite application when demanded and when the current user is authenticated to use that module.
My thought is to load the .dlls by streaming them down from a WCF service, where the WCF service (on the server) can access the .dll repository, but none of the client machines can access it. Authentication would also be handled by the service.
I suspect that I might be overcomplicating things somehow.
Is this something that can be done with a simple filesystem configuration and programmatically passing credentials when accessing the shared folder? If I do this, would access only be granted to the calling application, or would the logged-on user now be able to navigate to the shared folder?
Is this, in any way, a solved problem with MEF or any other project of which you're aware? (I hope this isn't LMGTFY-worthy -- I haven't been able to come up with anything.)
Answer: At Argonne National Laboratory we keep all sharable DLL and other objects (.INI files, PowerBuilder PBD libraries, application software, etc.)  on a simple and internally public file server and objects are being downloaded over the network on a per need basis as defined by each client/server application. Thus we are minimizing the maintenance of middleware (Oracle Client, PowerBuilder, Java, Microsoft, ODBC, etc.) to a single file server location with basically no software installed on the end user PC. Typically we physically download less than a few KB Registry Keys to the individual end user PC; this includes the full Oracle Client, which if installed on the PC alone would take up 650+ MB disk space and several thousand Registry Keys, and costly to maintain on the enterprise. Instead our Oracle Client on the PC is about 17KB.
The only "software" on the client side are Registry Keys containing variables pointing to server locations (f.ex. ORACLE_HOME:  \<server name>\ORACLE\v10\Ora10g ).
This has been a very cost effective solution we have been using for 10+ years, making all middleware and application software upgrades totally transparent to more than 2000 users Lab wide. Over the years we have done thousands of object upgrades on the central file server without ever having to install a single upgrade on the end user Desktop. Although this has some risks ("thou shall not copy DLLs over the network", etc.) and is a heavily customized solution, it has worked flawlessly for us throughout for a large number of applications and middleware.
This is a somewhat surprisingly simple solution in today's advanced technology, but it has been totally efficient and cost effective for us. Several vendors (Citrix and others) have looked at our solution somewhat perplexed, but every vendor of deployment techniques who have seen our deployment has come to the same conclusion, basically: "you do not need us".
Answer: when loading modules you need to keep in mind that:

Once loaded, an assembly can't be unloaded (unless you unload the entire application domain) - so if users can log in and out using the same instance, you may have a problem.
"the load context" matters (see http://blogs.msdn.com/suzcook/archive/2003/05/29/57143.aspx)  - this may cause problems if you have dependencies between modules or dependencies on assemblies that are not in the "load context"

If the restricted access to dlls is due to a licensing issue, maybe you need to refine the licensing mechanism somehow (not tie it to access to the actual code, but to some other checks)?
Comment: No licensing issues. With respect to users logging in and out using the same instance, I assume that means accessing the .dll over the network? I had in mind actually copying down the .dll to the client machine before loading it. Also, I won't need to unload any assemblies once running. From my reading of the post to which you linked, am I right in thinking that I can copy the .dll beneath the ApplicationBase of the composite application's shell and then load into the "Load context"?
Comment: Hi, about the last question: beneath `ApplicationBase` and inside `PrivateBinPaths`. I can't figure out why you won't let the user have access to the DLL - can the DLL be used without being loaded into your APP? Are you doing the security checks only when loading the DLLs? You should do all the security checking on the server. I guess the point is, since the request of restricting access to code is a bit weird, you should provide the reason behind it, so maybe better solutions can be provided. Even if there's no better solution, I'll be able to stop guessing :-)


Estimate logarithmic complexity

Question: I have data (running time $T$ and problem size $N$). If I suspect that there is a polynomial relationship in the form $T=a N^b$, I can plot a log-log graph and work out the gradient, as stated on the wikipedia article: https://en.wikipedia.org/wiki/Log%E2%80%93log_plot
If I suspect that it has an exponential relationship, I can plot a semi-log graph: https://en.wikipedia.org/wiki/Semi-log_plot
What if I suspect that $T$ and $N$ has logarithmic relationship, $T=log(N)$, what can I use to show this?
What can I do for factorial complexity?
I asked a similar question here: https://math.stackexchange.com/questions/1596617/determine-complexity
But now I'm more interested in finding out how can I estimate different classes of complexity with just experimental data (where the algorithm is possibly too complex to analyse).
Answer: If $T = \log N, N=e^T$ or whatever base of logs you are using, so you can plot on semi-log paper the same way in the reverse sense.
For the more general question, if you have data over a wide enough range it will be obvious.  Logs grow very slowly, polynomials faster, exponentials faster yet.  Factorials are faster than exponentials, but not much.  If you are comparing $1.0000001^n$ with a polynomial it might be hard, but $2^n$ outstrips any reasonable polynomial (say $x^6$) by the time $n=30$
Comment: Good idea, but I don't know the base. Would there be a way to work out the base given just the experimental data?
Comment: Complexity theorists generally don't care about the base, as it is a constant that can be dropped.
Comment: You used the log, so you should know the base.  It doesn't really matter much-my example with $2$ shows what happens there.  If the base is $10$ it grows much faster.  In theory, a polynomial could be $x^{1,000,000}$, and it would take a long time for $2^x$ to outrun it, but we don't see polynomials with that high a degree.  The statement that any exponential (with a base greater than $1$) eventually outstrips any polynomial is correct, but it can take a *long* time.  In reasonable cases the degree is low, the base of the exponential is not so close to $1$ so it doesn't take so long.

Estimate logarithmic complexity


Django queryset by username in user model

Question: I've
models.py
class UserProfile(models.Model):
    user = models.OneToOneField(User) #from contrib.auth,...
    titulo = models.CharField(max_length=50, blank=True, default="")
    descripcion = models.TextField(default="")

    # Valor por defecto, "Pagina de +nombre usuario"
    def save(self, *args, **kwargs):
        if not self.titulo:
            self.titulo = "Pagina de " + self.user.get_username()
        super(UserProfile, self).save(*args, **kwargs)

views.py
 def ShowUserPage(request):
    UsuarioElegido = request.path.split('/')[1]
    UsuarioModel = UserProfile.user.get_user(UsuarioElegido)
    return HttpResponse(UsuarioElegido)

I wanna get "titulo" and "descripcion" of UsuarioElegido. UsuarioElegido is the request.path for example /"root". But I can't get it Help?
getting this error: ReverseSingleRelatedObjectDescriptor' object has no attribute 'get_user'        UsuarioModel = UserProfile.objects.filter(user.username=UsuarioElegido)
but I don't know how to get it. Tried this before
         UsuarioModel = UserProfile.objects.filter(user.username=UsuarioElegido)

EDIT: I've just tried this, but Django can't finde my ShowUserPage in views :/?
def ShowUserPage(request):
    UsuarioElegido = request.path.split('/')[1]
    UsuarioModel = User.objects.get(username=UsuarioElegido)
    UsuarioModel = UserProfile.objects.filter(user=UsuarioModel)
    return HttpResponse(UsuarioElegido)

Comment: Is `UsuarioElegido` the `user` attribute?
Comment: There's quite a long wrong here. Have you done the tutorial? For example, you shouldn't be splitting the path manually; you should use the url pattern to extract the username via regex.
Comment: regex? Oh, I understand, but.. I print it and it works. I should change it as the way you are telling me about.
Answer: First of all, you don't have to analyze request.path on your own and extract all necessary parts of the URL. You can map this using urls.py file. For example like this:
urlpatterns = [
    url(r'^user/(?P<username>\w+)$', views.ShowUserPage),
]

And your ShowUserPage view method that handles this request has following signature:
def ShowUserPage(request, username)

Second, if you want to look for the user by its name, you can use following query:
UserProfile.objects.get( user__username=UsuarioElegido )

It will search by username attribute of the native Django class for User.
Comment: thanks ! Where can I map this using urls.py? I think that I've done it before, but I don't remember... doc?
Answer: Assuming username is unique:
UsuarioModel = UserProfile.objects.get(user__username=UsuarioElegido)

Use __ (double underscore) to follow relations in lookups.
Comment: I've never seen __username
yes is unique is from django auth db


Bitbucket Pipeline trying to get list of files changed compared to

Question: I have the following bash script I use to perform linting checks in a bitbucket pipeline.
#!/bin/bash
set -e

git fetch origin master:refs/remotes/origin/master
FORK_POINT=$(git merge-base HEAD origin/master)
PY_FILES=$(git --no-pager diff --name-only HEAD $FORK_POINT | grep "\.py$")

if [ "$PY_FILES" ]; then
    flake8 $PY_FILES
else
    echo "No *.py files found"
    exit 0
 fi

This was working fine up until December 4th around 4pm UTC. After some experimenting, I have narrowed the problem down to this line
PY_FILES=$(git --no-pager diff --name-only HEAD $FORK_POINT | grep "py$"). When I remove the grep and echo $PY_FILES the script completes successfully but nothing shows up in the log. So, it appears that git --no-pager diff --name-only HEAD $FORK_POINT isn't returning anything when run by the pipeline, which I guess causes grep to error? When I run this locally it is all fine, so git --no-pager diff --name-only HEAD $FORK_POINT should definitely be returning results.
Can anyone help me find out what went wrong here, or advise me on another way I can get a list of python files changed in a branch to run flake8 on?
Comment: to further debug, have your pipeline output the values it has at hand : print the sha1 for HEAD, origin/master and FORK_POINT : `git rev-parse HEAD`, `git rev-parse origin/master`, `echo $FORK_POINT`. Chances are they do not match what you expect.
Comment: @FurtherReading It would be helpful to have the final full solution as the accepted answer rather than the trouble shooting questions as the accepted answer.
Comment: I never got a final solution. The issue only occurred in one repo and I never reproduced it. ~it is a mystery~ but the accepted answer is a good start to troubleshoot.
Answer: It looks like you simply need to debug your pipeline ; one obvious difference between your local clone and the one used by bitbucket pipeline is that you are very probably not working on the same active commit (HEAD).
Have your pipeline output what it is working with :

its active commit : git rev-parse HEAD
its version of origin/master : git rev-parse origin/master
the reuslt of git merge-base : echo $FORK_POINT

From your comments : an empty FORK_POINT could indicate that the pipeline was trigered from a commit which hasn't a common ancestor with origin/master anymore.
Check the history of the remote HEAD :
git log --graph --oneline <sha from the pipeline>

You can for example compare it to the history of origin/master :
git log --graph --oneline <sha> origin/master

Comment: Had a look at these logs. `git rev-parse HEAD` locally gives the hash of the last common ancestor, but on the pipeline it gives the hash of like 2 or 3 commits previous. When you say that i might be working on different commits - I am editing the file here then commiting and pushing it direct to bitbucket, so shouldn't that mean that the commits should be the same?
Comment: the answer lies on how the pipeline is executed : what are the trigger condiftions ? what actions does the pipeline run before executing the code in your script ? that kind of debugging
Comment: It triggers when I push a commit. It runs `pip install flake8==3.8.4` and then the bash. None of that should change the commit right?
Comment: Well : obviously it doesn't checkout the correct commit (not the one you expect at least). You can probably see many of the parameters of the pipeline in the environment when your script is run. The most direct (but verbose) way to view the environement is to add `env | sort` in your script, it could output credentials to things you wouldn't like to store in a persistent log though. Check bitbucket's doc to view what environment variables are useful.
Comment: Note that : `flake8` will run whatever the list of python files you feed him. If the HEAD is wrong, you are probably not scanning the files you should ...
Comment: The Build setup logs show it is checking out the right commit. Adding echos to confirm in the bash show it is correct as well. The only odd thing is `git merge-base HEAD origin/master` fails on the pipeline but doesn't locally. Luckily though `git rev-parse HEAD` gets what I need to get the list. The only mystery is why `git merge-base HEAD origin/master` suddenly started failing.
Comment: Ah, does your pipeline use sparse checkouts ? or turned on sparse checkouts by default ? If the clone inspected by the script does not have the complete history of your HEAD commit, `git merge-base` could fail


Automatically place response item into next request (raw --> x-www-form) (POSTMAN)

Question: In POSTMAN, I'm having difficultly finding a way to place an item received from a JIRA Issue response(JSON) to the next request. BUT placing this item under (x-www-form-urlencoded) as a 'value' in the next request.
I'm including a few screen shots below to give a better visual of what I'm doing. However what I can't seem to figure out is a way to place that item as a value in (x-www.form...) format of the next request from an environment variable standpoing.
Context:
I've set up automation tests in POSTMAN which count any failures, save those failures to a variable. At the end of the Collection run, a JIRA REST API request is sent to create an Issue if those failures > 0.  Furthermore, if the JIRA request is initiated, it will return the JIRA issue link inside the response. I've used an environment variable to get receive the link under "self".

So, whats confusing me is that to send a message to Slack through Slacks API, it goes under the format: x-www-form-urlencoded.  Under this format, there are 3 KEYs needed to successfully send a slack message:
 KEY            VALUE
Token       (Authorization)
Channel     (Channel ID)
Text        (The Message)

I input all the necessary items in its respected places to send a message.  The message works successfully however it does not include the env variable I set in the prior request in the Collection run.  I hope would be that this would add the Jira issue link to the slack message so I'm able to click the link from there.

My question is, why isn't the env variable saving the response data and adding it to the next request which is the Slack Message?
Comment: Did you try `{{Link}}`?
Answer: To use variable in Postman UI, not Postman script (Pre-quest, Test), you need follow the syntax {{variable_name}}. In this case, you should use {{Link}}, not Link


Error in ReactJS setup in Ubuntu 16.04

Question: I tried to follow https://www.tutorialspoint.com/reactjs/reactjs_environment_setup.htm inorder to setup reactJS in my device which has Ubuntu 16.04.
In the end i tried npm start but it results me following error
> email@example.com start /var/www/html/reactjs
> webpack-dev-server --hot

Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
 - configuration.output.path: The provided value "./" is not an absolute path!

npm ERR! Linux 4.10.0-28-generic
npm ERR! argv "/usr/bin/nodejs" "/usr/bin/npm" "start"
npm ERR! node v4.2.6
npm ERR! npm  v3.5.2
npm ERR! code ELIFECYCLE
npm ERR! firstname.lastname@example.com start: `webpack-dev-server --hot`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the email@example.com start script 'webpack-dev-server --hot'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the reactjs package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     webpack-dev-server --hot
npm ERR! You can get information on how to open an issue for this project with:
npm ERR!     npm bugs reactjs
npm ERR! Or if that isn't available, you can get their info via:
npm ERR!     npm owner ls reactjs
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR!     /var/www/html/reactjs/npm-debug.log

My package.json file
{
  "name": "reactjs",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "webpack-dev-server --hot"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "react": "^15.6.1",
    "webpack": "^3.5.4",
    "webpack-dev-server": "^2.7.1"
  }
}

Answer: The most straight forward error message ever.
You can't use relative path in output (I don't remember wheather it was possible in previous versions of webpack). Docs.
output: {
   path: require('path').resolve(__dirname, './path/to/build/folder'),

Comment: @RafinKarki Webpack configuration file.
Answer: Use create-react-app for creating new reactjs application.
Just delete your node_modules folder and reinstall your npm package with npm install.

Error in ReactJS setup in Ubuntu 16.04


how to move next tab menu using button in lwuit?

Question: How to move one tab to another tab using button Click? When I click accept button, it moves to next tab menu.
Can anyone tell me how to do this?
<code>    frmSubscription = new Form();

    String[] subscriptionList = {"15 Days - $12.5", "30 Days - $25", "45 Days - $37.5", "60 Days - $50", "90 Days - $75"};
    cmdBack = new Command((String)locale.get("BACK"));
    cmdExit = new Command((String)locale.get("EXIT"));
    lblLeague = new Label("Premier League");
    lblSubscription = new Label("Subscription");
    lblCurrentPlan = new Label("Current Plan");
    comboSubscription = new ComboBox(subscriptionList);
    deviceWidth = Display.getInstance().getDisplayWidth();
    btnAccept = new Button("Accept");
    btnAccept.setAlignment(Component.CENTER);
    btnAccept.setPreferredW(deviceWidth);

    btnSubscription = new Button("Unsubscription");
    btnCancel = new Button("Cancel");

    flowLayout = new FlowLayout();
    frmSubscription.setLayout(flowLayout);

    btnTermsCond = new Button((String) locale.get("TERM&COND"));
    btnSubscribe = new Button("Subscribe");

    // Terms & conditions container
    txtTermsCondt =  new TextArea((String) locale.get("TERMS & CONDITIONS"));
    txtTermsCondt.setEditable(false);

    termsContainer = new Container(new BoxLayout(BoxLayout.Y_AXIS));
    termsContainer.addComponent(txtTermsCondt);
    termsContainer.addComponent(btnAccept);

    // Subscription container
    subContainer = new Container(new BoxLayout(BoxLayout.Y_AXIS));
    subContainer.addComponent(lblCurrentPlan);
    subContainer.addComponent(comboSubscription);
        acceptContainer = new Container(new BoxLayout(BoxLayout.X_AXIS));
        acceptContainer.addComponent(btnSubscription);
        acceptContainer.addComponent(btnCancel);
    subContainer.addComponent(acceptContainer);

    container = new Container();
    GridLayout gridLayout = new GridLayout(1, 2);
    container.setLayout(gridLayout);
    container.addComponent(lblLeague);
    container.addComponent(lblSubscription);

    tabSubscription = new TabbedPane();
    tabSubscription.addTab("Terms and Conditions", termsContainer );
    tabSubscription.addTab("Unsubscribe", subContainer );

    frmSubscription.addComponent(container);
    frmSubscription.addComponent(tabSubscription);
    btnAccept.addActionListener(this);
    frmSubscription.addCommand(cmdBack);
    frmSubscription.addCommand(cmdExit);
</code>
Answer: <code>if tabSubscription.getSelectedIndex() == 0
   tabSubscription.setSelectedIndex(1);
else
   tabSubscription.setSelectedIndex(0);
frmSubscription.repaint();
</code>
Comment: Correct but I don't think you need a repaint. You might need a revalidate() if the tabs aren't in the center of a border layout and their size changes.
Comment: It is moving to next tab but it display the bottom of the tab page. How can I move up?
Comment: Thanks a lot Pheromix it is working for me and i was searching for it :D


Holomorph of Cyclic $p$-groups

Question: Assume that $G$ is a cyclic $p$-group (or up to isomorphism more explicitly $\mathbb{Z}_{p^r}$). Do you know if there does exist any explicit way to describe the holomorph of the above group? Moreover, do you know if we can say something about the representations of these groups? (modular, non-modular)
Comment: To compute the holomorph of a cyclic group $G$ generated by an element $g$ you need to find the normalizer of the image $L$ of $G$ in the symmetric group $S(G)$ of the permutations given by multiplying on tthe left by elements of $G$. Now $L$ is clearly generated as a group by th permuation given by multiplication by $g$, and that permutation is has a very simple cycle decomposition: it is just one cycle of length $|G|$. Can you compute the normalizer?
Comment: Thank you for your response,i guess the answer is yes for your question, however i didn't try yet. But i don't understand something. This normalizer is isomorphic with the holomorph?
Comment: The holomorph of $\mathbb{Z}_{p^r}$ is the Galois group of $X^{p^r}-p$ over $\mathbb{Q}$. This also gives a representation into $\mathbb{C}$.
Comment: Thank you Clement! Do you know, where can find an analytic proof for the above? Or if it is easy, can you give a hint?
Answer: My representation theory is almost nada.
But the holomorph is, ims, the canonical semi-direct product  $G\rtimes\rm_\varphi  {Aut}G $, with the action  being left multiplication.
So we get  $\mathbb Z_{p^r}\rtimes_\varphi\mathbb Z_{p^r-p^{r-1}} $, unless  $p=2$.

Holomorph of Cyclic $p$-groups


Safe way to upgrade Ruby versions and gemsets in Rails applications

Question: I want to upgrade our Ruby version and a bunch of gems on our production website that we are currently running. We use RVM to manage our Ruby versions and gemsets.
I know how to install a new Ruby version using RVM and install gems in a gemset. I also understand that if I run bundle install it will install my gems into the Ruby version I am running the command from.
Is there some way to pre-create a Ruby version with a gemset in it and then swap my production site to use this new Ruby version and gemset? I know this can be done manually, but is there anyway to do it with a gemfile?
Comment: rvm + git + bundler + capistrano = no problems with version migrations
Comment: I am already using rvm, git and bundler and from my understanding capistrano is used for the deployment process. What I am interested in is the how. I have a live site that is running, how can I create a new ruby version and gemset and then switch it over. Sometimes I run into bundle install problems and it can be quite nerve racking. Changing ruby versions and an entire new gemset is a big thing for us and I want to minimize downtime and risk. Preinstalling the version and gemsets then switching over to that feels safer than just running bundle install. Just how I feel.
Comment: gemgets are depricated, instead them use `bundler`. If you user bundler you can simply switch gem versions any you want. Just make sure that locally your app works well with new gem versions
Comment: Will my server continue to run fine if I switch versions, do a bundle install, then restart my server? Any documentation you could point me to on what you are talking about with bundler?
Comment: If locally your app will work well, then on profuction it shold too
Comment: The point is that is not true in every case. Sometimes your local environment has different things installed or visa versa. In an ideal world they would always be the same. Making that assumption is risky so I am trying to figure out if there is a way to deal with that risk.
Comment: I deployed many server environments for mass media and e commerce and never met issues with gem updating
Answer: Yes, you can specify the Ruby version in the Gemfile:
source 'https://rubygems.org'
ruby '2.1.3'

This allows you to set the version that would be used if you deploy to Heroku, for example. Your question does not detail your production environment, so it's not clear if it can use the Ruby version in the Gemfile.
Locally, the app will run against whichever Ruby version is active with RVM. The only way to know if it will work is to run the specs against the new Ruby version. Your question did not mention specs, but if you have a complete set of specs then this is the proper way to find out if the new Ruby version will work.
Comment: Setting this up and testing everything on my local environment is easy. My question is more around let's say if I update my gemfile and run bundle install and it fails (on prod), how does that affect my currently running site on prod. Note I am running bundle install on prod now in which bundle install could fail since gems require certain software that might be on my local and not on production. Will this failure affect my currently running site? My gemfile is setup like you have in your answer. Is there a way to make sure bundle install passes then make my prod site point to that new gemset?
Comment: I don't get it. Your question seems to revolve around "gems require certain software", but this should be easy to handle. The only "certain software" I can think of is RMagick, Postgres and Mongo. Postgres and Mongo shouldn't be used on Production anyway because they should be separate services. I guess the best thing to do is to create a copy of the Production environment and deploy to it, and see if the app starts. If you have tests and the app starts then it should be OK.
Answer: You can install new versions of Ruby and gem sets all day long without it affecting a running application. Once an application is running, it continues running under the same version of Ruby the entire time.
You can have RVM install new Rubies, manipulate gemsets, etc., as long as you don't remove the version of Ruby the application needs. If the binary disappears your app might crash/lock-up if the system needs to load something that has been deleted.
Comment: Exactly what I was unsure about. Thanks.
Answer: This totally depends on your setup. I am anwsering for a Passenger/Apache setup.
With Passenger and Apache, you can set my PassengerRuby in the Apache Vhost file so it uses that particular version of Ruby, I would set it to your current ruby path and restart Apache like so:
PassengerRuby <path-to-ruby>

Then you you can install your new ruby version and gems, once you install everything you can change the PassengerRuby to the new ruby path and restart Apache. This should migrate your Ruby version smoothly, since you can always fallback to your old Ruby version.


How to populate Combobox with result of Powershell command

Question: Can someone assist on how to fill a combobox with the result of a powershell command?
Im trying to fill a combobox with the result of a "Get" cmdlet but I only get some powershell parameters as result.
$ButtonCollectionSearch.Add_Click({
    $name = $textboxlogonname.text
    $ComboBox = New-Object System.Windows.Forms.ComboBox
    $ComboBox.Width = 400
    $Collections = Get-RDSessionCollection | fl  -Property CollectionName

    Foreach ($Collection in $Collection) {
        $ComboBox.Items.Add($Collection);
    }
    $ComboBox.Location = New-Object System.Drawing.Point(120, 10)
    $main_form.Controls.Add($ComboBox)
})

Comment: Change `... |fl  -Property CollectionName` to `... |Select-Object -Property CollectionName`
Answer: The reason you're getting formatting metadata is that you asked for formatting metadata - by piping all your data through fl (which is a alias for Format-List).
Since we just want the value of the CollectionName, use ForEach-Object -MemberName in place of fl -Property:
$Collections = Get-RDSessionCollection | ForEach-Object -MemberName CollectionName

You'll also want to address the typo in the foreach loop declaration - change:
Foreach ($Collection in $Collection) {

to:
Foreach ($Collection in $Collections) {


How to create a border for SCNNode to indicate its selection in iOS 11 ARKit-Scenekit?

Question: How to draw a border to highlight a SCNNode and indicate to user that the node is selected?
In my project user can place multiple virtual objects and user can select any object anytime. Upon selection i should show the user highlighted 3D object. Is there a way to directly achieve this or draw a border over SCNNode?
Comment: Little hack: open Xcode, create a new project from the `SceneKit` template, open the VC, scroll down. You'll see code for highlighting a node when tapping it.
Answer: You need to add a tap gesture recognizer to the sceneView.
// add a tap gesture recognizer
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTap(_:)))
scnView.addGestureRecognizer(tapGesture)

Then, handle the tap and highlight the node:
@objc
func handleTap(_ gestureRecognize: UIGestureRecognizer) {
    // retrieve the SCNView
    let scnView = self.view as! SCNView

    // check what nodes are tapped
    let p = gestureRecognize.location(in: scnView)
    let hitResults = scnView.hitTest(p, options: [:])
    // check that we clicked on at least one object
    if hitResults.count > 0 {
        // retrieved the first clicked object
        let result = hitResults[0]

        // get its material
        let material = result.node.geometry!.firstMaterial!

        // highlight it
        SCNTransaction.begin()
        SCNTransaction.animationDuration = 0.5

        // on completion - unhighlight
        SCNTransaction.completionBlock = {
            SCNTransaction.begin()
            SCNTransaction.animationDuration = 0.5

            material.emission.contents = UIColor.black

            SCNTransaction.commit()
        }

        material.emission.contents = UIColor.red

        SCNTransaction.commit()
    }
}

The snippet above highlights the whole node. You'd have to adjust it to highlight the borders only, if that's what you're looking for.
Disclaimer:
This code was taken directly from Xcode's template code created when opening a new game (SceneKit) project.
Comment: Since i am new to scenekit can you please let me know how to highlight the border alone?
Comment: What if I have more than one child node? Then I if you tap in multiple child nodes, different different child nodes get highlighted.
Comment: Of course, because this code highlights the one that was tapped!


What is the difference between being in key and improvising solo on scale?

Question: This might be a stupid question but started learning Music theory just now and went making Chord Progressions in a key.
What I don't understand is the difference between Key and Scale ?
Let's say a song is written in key of C major Which gives us chords  as -
1) CMajor
2) Dminor
3) Eminor
4) Fmajor
5) Gmajor
6) Aminor
7) B diminished
My questions are -
1)  So what I understand is , If we are playing in Key of CMajor , we can play only these chords with Whatever Roman Numeral Chord Progression. And if we have to shift the key,  we have to go according to circle of Fifth and that will be Gmajor Key next. Is that correct ?
2) If we are playing in Key of C Major and lets say a solo comes , so the solo will be on a C Major scale or its relative minor A minor Scale but not any other scale?
3) If we are playing in a key, we still play the Open chords in a guitar on first 4 frets , then what's the point of learning all the Patterns and creating chords on lets say Fifth Fret with Amajor Scale ? Are those patterns only for playing Lead ? And we can play simple open chords for Rhythm?
4) When we say We play in a key , that means we can freely use the open chords? Even if we are playing In key of A Major whose pattern 1 root starts on fifth fret of guitar ?
I am confused of all these question and I am an absolute beginner in music theory.
Comment: There are too many different questions contained here for one cohesive answer.
Answer: I will try my best to answer your questions.
1) So what I understand is , If we are playing in Key of CMajor , we can play only these chords with Whatever Roman Numeral Chord Progression. And if we have to shift the key, we have to go according to circle of Fifth and that will be Gmajor Key next. Is that correct ?
A1) To your first question/statement "If we are playing in Key of CMajor , we can play only these chords with Whatever Roman Numeral Chord Progression" I am not sure what to say.  It is somewhat true in the sense that if you play something not in the list you will have "accidentals" that are NOT in key.  However, this is not forbidden.  You are not required to stick only to these chords.  But deviations from them have to smoothly voice lead back into the key.  Here are a couple counter examples.  In Rhythm Changes the basic chords are I --> VI7 --> ii-7 --> V7.  Notice that the 6 chord which is usually minor is major here.  It provides a leading tone to the ii-7.  You could say that the key changed momentarily or that one should treat the key as minor in the ii-7 but you don't need to.  In fact many songs based on these changes do not have an out of key note in the melody yet use the VI7 instead of the vi-7.  This brings me to my second counter example.  One frequently uses cycle extensions to "lead into" chords that are in key.  And example might be I --> iii-7 --> III7 --> vi-7 --> VI7 --> ii-7 --> V7 --> I.  The iii and the vi chords are played "in key" then changed to be a dom 7th for the next chord in sequence until you get to the classic ii-->V-->I.  You can apply this as often or as little as desired.  Formally speaking you might say the key changed with every occurrence of this device.  You can also think of these as "passing chords" containing accidentals. As an aside chord progression and song don't always belong to a fixed key.  We sometimes vamp back and forth between chords that sound good together but have no relation based on key signature or analysis using a fixed key.  As for your second statement in this question "And if we have to shift the key, we have to go according to circle of Fifth and that will be Gmajor Key next" the answer is NO.  You do not have to change key by a 5th.  In fact the most common device I know going back to before classical music is to change to the 4th.  For example from the key of C to the key of F.  In fact you can change key from any starting point to any other key!  There is a great book called Modulations by Reger that outlines just about every possible key change with a smooth chord progression.  This is quite advanced.
2) If we are playing in Key of C Major and lets say a solo comes , so the solo will be on a C Major scale or its relative minor A minor Scale but not any other scale?
A2)  For this most part this is a safe bet, a good starting point.  You can move away from the key in your solo but you'd be wise to respect the structure of the song.  Keys come in comparable sets that share a tetra chord, no surprise these are related by a 5th.  For example the keys of F, C, and G (the IV, I, and V in the key of C) all overlap.  This means you can deviate from one to the other and com back smoothly.  Going much further from the key in many cases licks based on the minor blues scale sound fine even in a major key.  This is a common occurrence in Rock and Jazz.  So in fact you don't need to stay in key or on the major scale of the key but your musical ideas should respect the key.  As you learn more you will come across all sorts of formulaic methods for soloing.  Not worth discussing here since you are just starting.
3) If we are playing in a key, we still play the Open chords in a guitar on first 4 frets , then what's the point of learning all the Patterns and creating chords on lets say Fifth Fret with Amajor Scale ? Are those patterns only for playing Lead ? And we can play simple open chords for Rhythm?
A3) This is a different question altogether.  Everything is important.  The open string chord patterns are very important but so are the movable ones.  They are not just for soloing.  You cannot play all 12 keys with open string chord voicings only, and part of the value of the other chord patterns is the alternate voicing (different order of notes create different harmony).  You definitely want to learn all you can here to be a great rhythm player.
4) When we say We play in a key , that means we can freely use the open chords? Even if we are playing In key of A Major whose pattern 1 root starts on fifth fret of guitar ?
A4) This question is not coherent or clear to me.  I cannot understand what you are asking.  First of all there are keys for which NONE OF THE OPEN CHORDS WORK.  So your first statement is not true.  I am also not quite sure what your second statement means.  The pattern of A major starts on the fifth fret.  This is not true, unless you are referring to a specific method book and I don't know that notation.  The A major scale starts on the open A string in most books.  But if you are referring to the standard major scale starting in the second finger on the low E string then, yes you can still play the open A chord as rhythm.  There is no reason why you need to be in the same position when soloing as you are when playing rhythm.  In fact there are several ways to play each chord and each has a corresponding scale pattern in the same position.  This is sometimes referred to as the C-A-G-E-D system.
Comment: Isn't that Jack black's music project
Answer: You're approaching music theory from the wrong direction.  Take a real piece of music - take LOTS of pieces of music - and see what they actually do.  You'll find that some songs do confine themselves to the notes and chords of a single scale, but many don't.
C, Am, F, C.   The 'four chord trick' behind a lot of simple pop songs of the 50s and 60s.
C7, F7, G7, C7.   The chords of a simple Blues - basis of a whole lot more songs.  Note the non-scale notes included in those chords.  But it's still definitely a Blues in C.
And I could quote many more examples that use many more non-diatonic chords while still being 'In C'.
Your theory book has listed the chords that may be formed from the C major scale.  All very neat and tidy.  I expect it also has a 'circle of 5ths' diagram.  Yes, G major is harmonically close to C major.  But those aren't the ONLY chords that get used in a song 'in C major'.  And G major isn't the ONLY key we can visit.    The book's attempt to lay things out systematically should not be mistaken for a set of rules.   Look at some real songs!
Answer: I suggest learning the formula for building a scale from the chromatic scale and working through that exercise a few times. Then it may help to memorize the notes on each string starting at the nut and naming each note up to the 12th fret. After this is accomplished, it may help you to download a page of guitar neck diagrams from the internet, print it out, and fill in the scale notes across the neck. Hopefully this can help you see a number of different places that you can play a scale. After that, you may choose to study moveable chords, where you'll realize that scales and chords can be played in several different positions on the neck, but it involves learning at least five moveable chord fingering forms and five different scale fingering patterns. At that point you may start to see how scales and keys are related to each other. You've got your work cut out for you. Best of luck.
Answer: Your question asks 4 different things and it's actually quite time consuming to answer. There are already some good answers here. I wanted to focus on one thing:

2) If we are playing in Key of C Major and lets say a solo comes , so the solo will be on a C Major scale or its relative minor A minor Scale but not any other scale?

This depends mostly on the genre you're playing. A genre like jazz follows diatonic conventions of keys and scales quite well, although they can modulate frequently. Other genres like rock and blues tend to throw music theory out of the window. Blues is major and minor at the same time and the harmony uses a lot of accidentals.
When soloing, harmony is king. Your solos should work nicely with the chord you're playing over. I find that soloing is not as simple as music theory makes you think, especially in songs that are not 100% diatonic.


Exchange - how to deliver internal mail externally

Question: Is it possible to tell Exchange 2007 to deliver all mail to a certain domain originating from the same domain, to external MX'es even though it is set to handle mail for the domain? I.e. not deliver it internally, but forward it to another MX.
Details:
We're in the process of migrating, the official MX is still external, it is only Exchange that thinks it's handling the domain. All users have mail aliases at a second domain (also handled by exchange and with MX records pointing to exchange)
I'd like to keep the MX, but forward all mail for selected users to this secondary domain so that Exchange will handle it, and these select users can access their mail. However, any mail sent to other users in the organization should be sent to the external MX, so it will be accessible at the old server
example:

domain1 (primary) is handled by an external server (not Exchange)
domain2 is handled by Exchange, however, Exchange believes it handles domain1 as well

At the external server all mail to someone@domain1 is forwarded to someone@domain2 (Exchange). Here both domains map to the same user.
At Exchange, all mail to anyone@domain1 should not be handled internally, but routed to the external server. The trick is that everything is set up at the Exchange server, but users can be migrated one by one, and start receiving mail at Exchange without other users being affected.
Answer: I don't think this is possible. If Exchange thinks it is the final destination of the mail (if it's an "accepted domain") then it will try to find a mailbox for the recipient. You can set up an "external relay domain" and have the mail forwarded out, but if DNS always tells that mail to come back to you (via the MX record) you will just create a loop.
Docs link: http://technet.microsoft.com/en-us/library/bb124423(EXCHG.80).aspx
Edit: Is the other server an Exchange server? If so, you should be able to migrate mailboxes to the other server, and they will be forwarded to the right one.
Comment: Hi, thanks for your reply! The MX is still not pointing to Exchange, so I don't think there will be any loops
Comment: OK, I read somewhere "Both Internal and External relay will look internally for a matching address
before passing the mail along to the external system.". So your suggestion might not work anyway?
Comment: I'm not sure, can you provide more detail in the question, with a bit about the domains, the mail path, etc.? Cheers.
Comment: I've added some more info, hopefully it makes sense


Configurar git em uma hospedagem compartilhada

Question: Tenho uma hospedagem compartilhada na hostgator e na descrição dos planos vi que cliente git é aceito. Entrei em contato com o suporte da Hostgator para entender melhor sobre detalhes do cliente git que eles falam, eis a resposta:
"A diferença entre o Git server e Git Cliente, encontra-se na funcionalidade, onde um cliente Git é apenas um usuário utilizando servidores externos.
Já o Git server, seria utilizado para criar um repositório e fornecer a outros usuários, como não é permitido a utilização de servidores compartilhados como repositório, não é possível realizar o procedimento em planos P,M,Business,Plus e Revendas."
A questão é, tenho um repositório privado no bitbucket, eu consigo configurar o servidor para que ao fazer um push na minha maquina local, automaticamente as alterações são salvas no repositório e replicadas no site?
Comment: Eu não entendi o seu objetivo! Você tem o repositório no Bitbucket... E nos servidores onde rodam a sua aplicação você quer configurar clientes Git para baixarem o código é isso?
Answer: Ola, camarada. já tive o mesmo problema quando trabalhava com gitlab e usava heroku.
Ainda não vi nenhuma forma para resolver isso se não:
-Criar ou sincronizar seu projeto com o repositório remoto(no seu caso firstname.lastname@example.com:public_html/project-name)
-neste caso tera dois ramos de desenvolvimento- origin e do repositorio remoto.
Veja esse artigo, mostra como fazer isso em minimos detalhes: http://www.arlocarreon.com/blog/git/push-git-repo-into-shared-hosting-account-like-hostgator/
ou esse:
https://medium.com/29-degrees/setup-a-git-repository-on-a-shared-hostgator-account-7a7e306ef66f
Espero ter ajudado...
Comment: Elton, poderia trazer a explicação dos procedimentos para a sua resposta? Aqui preferimos que as respostas não dependam de links externos, que podem deixar de funcionar. Obrigado.


return full parse object from Parse.Object.save()

Question: I'm finding myself having to write custom PUT routes for objects in my parse-server backend when the client needs to get the full json in the response, not just the updated properties that are returned by the Parse REST API PUT methods. I can achieve this in the example below, but I'd like to do it without having to have the additional .fetch() after the save. Without it, the save only returns the object with the properties that were updated. Is there any way to include the whole objects in the .save() response? I know it's available in the before/afterSave hooks.
function(request, response) {
  habit = Habit.createWithoutData(request.params.habitId);
  return habit.save(request.body, { sessionToken: user.getSessionToken() }).then(function(habit) {
    return habit.fetch();
  }).then(function() {
    response.status(200);
    response.json(habit._toFullJSON());
  }, function(error) {
    response.status(422);
    response.json(error);
});

};
Answer: There's no need to return the saved object, because the caller has it already (by definition, it's what was just saved).  The only thing new is createdAt and id, which can be found in the result.
In the OP, the saved object is request.body.


How to grant user User Points after publishing content, while content's default is unpublished?

Question: I'd like to grant users User Points when their added content of the content type 'Content', which is unpublished by default, is published. I tried this with the Rules module:
- Event: After saving new content
- Elements:
  * Content is of type: Content
  * Content is published
- Actions: Grant points to a user
So, when a user adds 'Content' content, they don't get any User Points and their content is unpublished. My idea was that they'd be granted the points after I - as moderator - had published their content. But apparently, they don't get points after I've done that with the rule I set up. What did I do wrong and how can I solve this?
Answer: I solved my problem by doing this:

Create flag and give flag name as Publish node and grant points to user
Add new rule with event A node has been flagged, under "Publish node and grant points to user"
For actions publish this node and grant points to user use this data selector: flagged-node:author

Special thanks to oneng on Stackoverflow!


C++ mutiple key input or key press/release events

Question: I am writing a game in C++. For it, I need to detect multiple keys being pressed or held at the same time, or detect key press and key release events.
For example, if I hold both the up and right keys, I want to be able to detect this and move the game diagonally. Additionally, currently if I am holding the right key, and I press up, it no longer recognizes that right is being held. I need a way to find when the right key is actually released so it isn't interrupted like this.
I know that sdl2 can recognize multiple keys being pressed or held, but that requires creating a window, and I want this to be entirely within the terminal.
getch() from curses/ncurses additionally doesn't work for this.
What can I use for this? I'd like to avoid Allegro if possible.
Comment: Out of curiosity, why do you want to avoid Allegro?
Comment: Echo all the keyboard and mouse events with timestamp to a queue and process them in a separate thread. Can be engageing task however.
Comment: If you are only interested in knowing if the key is down or up, do not use a queue. Just track the keypresses in the KEY_DOWN and KEY_UP events (or respective events depending on what API you use). If you want your player to customise the keys and therefore want to use most keys on the keyboard, use an array with the key scancode or similar as the index into the array and use 0 for key is up and 1 for key is down. If you only want to track for example the LEFT/RIGHT/UP/DOWN keys, just use a simple bool var. See my answer below
Answer: You don't mention how you are reading key input now and how you are handling the input so this is just a general advice on how to handle key input.
When you detect or handle a key pressed (key down) event for a specific key, set a flag (e.g. keyflags = keyflags | KEY_RIGHT) to indicate the key is down, and unset (delete) the flag on keyup event. This might solve the problem you experience today if you act directly on key presses.
Comment: I understand the flag part, but my question is how do I actually get the input and detect the key down events? I believe SDL2 requires a GUI window to be open - I'd like this to be entirely in the terminal.
Comment: The problem is reading key presses or releases then. As I've said, I've tried `getch` and `sdl2`, neither of which worked for the reasons stated above.
Comment: As stated above, you should use to flag to track pressed and released keys, not act directly on reading the state of the keyboard. You act on key pressed and key released by setting or unsetting the flag for the key in question (the flag can be an array or a simple bool) and in your game loop you check which keys are down by checking the flag.
Comment: And if you use SDL2, you can use the SDL_GetKeyboardState method which essentially do the same thing as I describe above (keep track of key presses and released using an indexed array).


how to use two onChangeText in react native inside textinput

Question: <TextInput
 placeholder="Full Name"
 onChangeText={userName => this.setState({ userName })}
 onChangeText={text => this.validate(text, "username")}
 underlineColorAndroid="transparent"
 style={[
         styles.TextInputStyleClass,
         !this.state.nameValidate ? styles.error : null
       ]}
 blurOnSubmit={false}
 autoFocus={true}
 autoCorrect={true}
 autoCapitalize="none"
 maxLength={25}
/>

in the above code, I use two Onchagnetext events but only on event work that calls validation another is not working means not take value. why how to fix it.
how can I use two Onchangetext events?
Comment: Do you want both of them work at the same time?
Answer: You don't need two onChangeText method.
If you want to validate and use setState together then you can do
   ...
   onChangeText={userName => this.setState({ userName },
    () => this.validate(username, 'username)})}

The callback in setState ensures that you are calling the method once the setState has finished updating the state


Dúvida chamar método com If Java

Question: Bom, estou fazendo um projeto da Faculdade e estou iniciando agora em java, a questão é o seguinte, eu tenho 2 tabelas no sql server e 2 classes distintas no java, que seriam pessoa fisica e pessoa juridica, o problema é o seguinte, eu estou tentando criar um if else, que capture um campo chamado tipo_cliente, e que ele defina onde os dados seriam inseridos, mas estou errando sempre no Else.
Ps: O Método de pessoa juridica está em outra classe, gostária de ajuda se possivel.
Segue abaixo o código
if (pessoafisica.getTipo_cliente().trim().equals("Pessoa Fisica")) {
Connection conn = conectarPrepareStatment();
//instrução Sql para inserir o cliente no banco de dados
String sql = "INSERT INTO PessoaFisica (cpf, rg, nome, rua, bairro, cidade, uf, cep, telefone, sexo, data_nascimento, id_fun)";
sql += "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
PreparedStatement stmt = conn.prepareStatement(sql);
//preenchendo os valores
stmt.setString(1, pessoafisica.getCpf());
stmt.setString(2, pessoafisica.getNome());
stmt.setString(3, pessoafisica.getRg());
stmt.setString(4, pessoafisica.getRua());
stmt.setString(5, pessoafisica.getBairro());
stmt.setString(6, pessoafisica.getCidade());
stmt.setString(7, pessoafisica.getUf());
stmt.setString(8, pessoafisica.getCep());
stmt.setString(9, pessoafisica.getTelefone());
stmt.setString(10, pessoafisica.getSexo());
stmt.setString(11, pessoafisica.getData_nascimento());
stmt.setObject(12, pessoafisica.getFuncionario().getId());
//executando
stmt.execute();
stmt.close();
//encerrando a conexão
desconectar();
} else {

E Nesse Else eu gostaria que fosse "chamado" O método de pessoa juridica, que está na classe de dados de pessoa juridica, mas não estou conseguindo.
Answer: Imaginando que sua classe se chama PessoaJuridica e que ela contenha o método inserirDados(), dentro do else você faria assim:
PessoaJuridica pj = new PessoaJuridica() ;
pj.inserirDados();
É essa sua dúvida?
Comment: Aparentemente consegui resolver, ficou assim: } else {
         ClientePessoaJuridicaDados pessoajuridica = new ClientePessoaJuridicaDados();
         pessoajuridica.cadastrarClientePJuridica(pessoajuridica);
Comment: Sim, reflete o exemplo que dei.
Comment: Agora tá ocorrendo outro problema, quando eu abro o construtor, e puxo o método, ele quer gerar outro método mas usando como parametro dados que vem da classe de dados e não da classe básica.
Comment: Crie uma nova pergunta com sua dúvida e, o mais importante, coloque o código que você está usando e especifique onde e qual o erro, ok?
Answer: Estou supondo que o getTipo_cliente volte "Pessoa Juridica", se for diferente, como por exemplo, ter acento, favor alterar.
   Connection conn = conectarPrepareStatment();
                String sql = null;
            if (pessoafisica.getTipo_cliente().trim().equals("Pessoa Fisica")) {

                    //instrução Sql para inserir o cliente no banco de dados
                    sql = "INSERT INTO PessoaFisica (cpf, rg, nome, rua, bairro, cidade, uf, cep, telefone, sexo, data_nascimento, id_fun)";
                    sql += "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
                    PreparedStatement stmt = conn.prepareStatement(sql);
                    //preenchendo os valores
                    stmt.setString(1, pessoafisica.getCpf());
                    stmt.setString(2, pessoafisica.getNome());
                    stmt.setString(3, pessoafisica.getRg());
                    stmt.setString(4, pessoafisica.getRua());
                    stmt.setString(5, pessoafisica.getBairro());
                    stmt.setString(6, pessoafisica.getCidade());
                    stmt.setString(7, pessoafisica.getUf());
                    stmt.setString(8, pessoafisica.getCep());
                    stmt.setString(9, pessoafisica.getTelefone());
                    stmt.setString(10, pessoafisica.getSexo());
                    stmt.setString(11, pessoafisica.getData_nascimento());
                    stmt.setObject(12, pessoafisica.getFuncionario().getId());
            } else if (pessoafisica.getTipo_cliente().trim().equals("Pessoa Juridica")) {
                    Connection conn = conectarPrepareStatment();
                    //instrução Sql para inserir o cliente no banco de dados
                    String sql = "INSERT INTO PessoaJuridica (campos da tabela)";
                    sql += "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
                    PreparedStatement stmt = conn.prepareStatement(sql);
                    //preenchendo os valores
                    stmt.setString(...)
                    //preencha os campos finais
            }
            //executando
            stmt.execute();
            stmt.close();
            //encerrando a conexão
            desconectar();

Outra maneira é exportar o miolo para funções que fazem a inserção.
            if (pessoafisica.getTipo_cliente().trim().equals("Pessoa Fisica")) {

                inserirPessoaFisica(cpf, rg, nome, rua, bairro, cidade, uf, cep, telefone, sexo, data_nascimento, id_fun);
            } else if (pessoafisica.getTipo_cliente().trim().equals("Pessoa Juridica")) {
                inserirPessoaJuridica(campos de pessoa juridica);
            }

            public void inserirPessoaFisica(String cpf , String rg, String nome, String rua, String bairro,
                String cidade, String uf, String cep, String telefone, String sexo, String data_nascimento,
                Object id_fun) throws Exception
                {
                    Connection conn = conectarPrepareStatment();

                    //instrução Sql para inserir o cliente no banco de dados
                    String sql = "INSERT INTO PessoaFisica (cpf, rg, nome, rua, bairro, cidade, uf, cep, telefone, sexo, data_nascimento, id_fun)";
                    sql += "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
                    PreparedStatement stmt = conn.prepareStatement(sql);
                    //preenchendo os valores
                    stmt.setString(1, pessoafisica.getCpf());
                    stmt.setString(2, pessoafisica.getNome());
                    stmt.setString(3, pessoafisica.getRg());
                    stmt.setString(4, pessoafisica.getRua());
                    stmt.setString(5, pessoafisica.getBairro());
                    stmt.setString(6, pessoafisica.getCidade());
                    stmt.setString(7, pessoafisica.getUf());
                    stmt.setString(8, pessoafisica.getCep());
                    stmt.setString(9, pessoafisica.getTelefone());
                    stmt.setString(10, pessoafisica.getSexo());
                    stmt.setString(11, pessoafisica.getData_nascimento());
                    stmt.setObject(12, pessoafisica.getFuncionario().getId());

                    //executando
                    stmt.execute();
                    stmt.close();
                    //encerrando a conexão
                    desconectar();
                }

                public void inserirPessoaJuridica(....) throws Exception
                {
                    Connection conn = conectarPrepareStatment();

                    //instrução Sql para inserir o cliente no banco de dados
                    String sql = "INSERT INTO PessoaJuridica (....nomes de campos....)";
                    sql += "VALUES (...? para cada campo...)";
                    PreparedStatement stmt = conn.prepareStatement(sql);
                    //preenchendo os valores dos campos
                    stmt.setString(1, ....

                    //executando
                    stmt.execute();
                    stmt.close();
                    //encerrando a conexão
                    desconectar();
                }

            }

Dúvida chamar método com If Java


Filtering a set of data based on indices in line

Question: I have a python script that pulls data from an external servers SQL database and sum's the values based on transaction numbers. I've gotten some assistance in cleaning up the result sets - which have been a huge help, but now I've hit another problem.
My original query:
SELECT th.trans_ref_no, th.doc_no, th.folio_yr, th.folio_mo, th.transaction_date, tc.prod_id, tc.gr_gals FROM TransHeader th, TransComponents tc WHERE th.term_id="%s" and th.source="L" and th.folio_yr="%s" and th.folio_mo="%s" and (tc.prod_id="TEXLED" or tc.prod_id="103349" or tc.prod_id="103360" or tc.prod_id="103370" or tc.prod_id="113107" or tc.prod_id="113093")and th.trans_ref_no=tc.trans_ref_no;

Returns a set of data that I've copied a snippet here:
"0520227370","0001063257","2014","01","140101","113107","000002000"
"0520227370","0001063257","2014","01","140101","TEXLED","000002550"
"0520227378","0001063265","2014","01","140101","113107","000001980"
"0520227378","0001063265","2014","01","140101","TEXLED","000002521"
"0520227380","0001063267","2014","01","140101","113107","000001500"
"0520227380","0001063267","2014","01","140101","TEXLED","000001911"
"0520227384","0001063271","2014","01","140101","113107","000003501"
"0520227384","0001063271","2014","01","140101","TEXLED","000004463"
"0520227384","0001063271","2014","01","140101","113107","000004000"
"0520227384","0001063271","2014","01","140101","TEXLED","000005103"
"0520227385","0001063272","2014","01","140101","113107","000007500"
"0520227385","0001063272","2014","01","140101","TEXLED","000009565"
"0520227388","0001063275","2014","01","140101","113107","000002000"
"0520227388","0001063275","2014","01","140101","TEXLED","000002553"

The updated query runs this twice and JOINS the trans_ref_no, which is the first position in the result set, so the first 6 lines get condensed into three, and the last four lines get condensed into two. The problem I'm having is getting transaction number 0520227384 to get condensed to two lines.
SELECT t1.trans_ref_no, t1.doc_no, t1.folio_yr, t1.folio_mo, t1.transaction_date, t1.prod_id, t1.gr_gals, t2.prod_id, t2.gr_gals FROM (SELECT th.trans_ref_no, th.doc_no, th.folio_yr, th.folio_mo, th.transaction_date, tc.prod_id, tc.gr_gals FROM Tms6Data.TransHeader th, Tms6Data.TransComponents tc WHERE th.term_id="00000MA" and th.source="L" and th.folio_yr="2014" and th.folio_mo="01" and (tc.prod_id="103349" or tc.prod_id="103360" or tc.prod_id="103370" or tc.prod_id="113107" or tc.prod_id="113093") and th.trans_ref_no=tc.trans_ref_no) t1 JOIN (SELECT th.trans_ref_no, th.doc_no, th.folio_yr, th.folio_mo, th.transaction_date, tc.prod_id, tc.gr_gals FROM Tms6Data.TransHeader th, Tms6Data.TransComponents tc WHERE th.term_id="00000MA" and th.source="L" and th.folio_yr="2014" and th.folio_mo="01" and tc.prod_id="TEXLED" and th.trans_ref_no=tc.trans_ref_no) t2 ON t1.trans_ref_no = t2.trans_ref_no;

Here is what the new query returns for transaction number 0520227384:
"0520227384","0001063271","2014","01","140101","113107","000003501","TEXLED","000004463"
"0520227384","0001063271","2014","01","140101","113107","000003501","TEXLED","000005103"
"0520227384","0001063271","2014","01","140101","113107","000004000","TEXLED","000004463"
"0520227384","0001063271","2014","01","140101","113107","000004000","TEXLED","000005103"

What I need to get out of this is a set of condensed lines where, in this group, the seconds and third need to be removed:
"0520227384","0001063271","2014","01","140101","113107","000003501","TEXLED","000004463"
"0520227384","0001063271","2014","01","140101","113107","000004000","TEXLED","000005103"

How can I go about filtering these lines from the updated query result set?
Comment: What logic do you have to choose "000004000","TEXLED","000005103"  (line 4) over "000004000","TEXLED","000004463" (line 3), but on the same note choose "000003501","TEXLED","000004463" (line 1) over "000003501","TEXLED","000005103" (line 2)?  One seems to take max and one takes min
Comment: @Twelfth Based on the original query result set. Lines 7-10 are for the same transaction, however, lines 7 and 8 are paired "3501 and 4463" while lines 9 and 10 are paired - "4000 and 5103". You are correct in the statement that it appears to be choosing the max and min, but the resulting data set orders it in that way, so 3501 comes first with a 4463 and 5103, then 4000 with a 4463 and 5103
Answer: i think, the answer is:
(... your heavy sql ..) group by 7

or
(... your heavy sql ..) group by t1.gr_gals

Comment: Not quite sure if that will do it (mysql would probably run it instead of returning an error.  Yay MySQL).  t1.gr_gals and t2.gr_gals are both different, not just t1.gr_gals.
Comment: @Twelfth The main idea is to use group or window function. I'm not sure how it shall be implemented in mysql. I hope my and will help you.
Comment: @SethKoberg That query shall filter rows by value like `"000003501"` (I may mistype exact row). How your result looks like?
Comment: trying this, the query removes three out of the four transactions in the result set instead of removing only 2. Could it be expanded to something along the lines of `group by 7 where t1.trans_ref_no = t2.trans_ref_no`?
Comment: @akaRem On further inspection, your suggestion didn't remove three, of the results for transaction `0520227384` but it created two with different values in column 7 `000003501' and `000004000`, and the same value in column 9. `"0520227384","0001063271","2014","01","140101","113107","000003501","TEXLED","000004463"` is the first instance for this transaction number and `"0520227384","0001063271","2014","01","140101","113107","000004000","TEXLED","000004463"` is the second instance.
Comment: @SethKoberg Is that what you want? Or not? If not, explain, what you want to get more clearly, please.
Comment: @akaRem - Looking at the original data set, lines 7-8 need to be joined to create `"0520227384","0001063271","2014","01","140101","113107","000003501","TEXLED","000004463"` and lines 9 and 10 need to be joined to create `"0520227384","0001063271","2014","01","140101","113107","000004000","TEXLED","000005103"`


How to differentiate $x\sqrt{x}$

Question: How could one differentiate $x\sqrt{x}$?
I know $[\sqrt{x}]' = \dfrac{1}{2\sqrt{x}}$
Comment: Do you know the product rule for derivatives?
Comment: Or you can write $x\sqrt x=x^{\frac 32}$ and use the power law.
Comment: Note the in the answers you have 2 different approaches: (1) $x^{\frac{2}{3}}$ and use the *power rule*. (2) $x \times \sqrt{x}$ and use the *product rule*.
Answer: $\sqrt{x}=x^{1/2}$, so just differentiate $x^{3/2}$, i.e. $\frac{d}{dx}x\sqrt{x}=\frac{3}{2}\sqrt{x}$.
Answer: Product rule: $$(fg)'= f'g + fg'$$
Take $f=x$ and $g=\sqrt x$
You know $f'=1$ so
$$
(fg)'(x)= \sqrt{x} + \frac{x}{2\sqrt{x}}.
$$

How to differentiate $x\sqrt{x}$


What does chord-suffix mean?

Question: I would like to know how to play extended/add chords on the guitar, for example Cadd9 here. I want to systematize chords and draw diagrams of them.

What does "Сadd9" or "С+9" mean? Can chords such as "C+10" or "С-5" exist?
What does "A/C" mean? Can "A/A" or "B/A" exist?

Where can I see diagrams of chords?
Comment: be careful with the answers for this question. there is no real standard for naming conventions and you may get a different answer for some symbols from a "jazzer" then someone that studied classically or is a "rocker". for example you may have capitol M for major and lower for m but other might thing a - is minor. some will use a triangle for something, i don't know...  that being said some things will be standard, just beware
Comment: this page is a good start: https://en.wikipedia.org/wiki/Chord_names_and_symbols_(popular_music)
Comment: I found notes of scale table http://i.pinimg.com/474x/35/f5/d5/35f5d540d8532e7121e284af71001e23--jazz-guitar-guitar-chords.jpg or http://www.pinterest.com/pin/456763587191336852
Answer: Cadd9 is a C major triad with the 9th note from that scale added. C E G D. C+9 is rather a different beast. It has an augmented 5th note, and because it's a 9th, will include the m7 too. Thus C E G# Bb D. Don't be fooled into thinking 'add' and '+' are the same!
C+10 wouldn't make a lot of sense, since usually the affected numbers are 5, 7, 9, 11 13, but would be C E G# E, not sounding any different from a standard C augmented (C+).
The '-' sign usually means 'minor', so -5 can't exist.
A/C would be an A major chord, with a C as the bass under it. Strange sounding again!. Yes, A/B is used a fair bit, in jazz, and A/C# is just the first inversion of A major, with the third at the bottom.
There are many sites which show 'chord boxes', some more accurate and helpful than others. Have a look at some chord theory, which will help you understand what's in this and other answers, and clear up some of your misunderstandings. We all had (and still have) some ourselves!
Basic formula: start with triad (CEG). For 'add' the commonest one is 9. So add D. Yes, it's 2 as well, but doesn't sound good against the 3 (D again!), or sus 4, using F to replace E.
The '+' augments an interval. Usually P5. So C+ uses C E G#, where G# is aug.5. With a '7' in the chord, if it's major 7, it uses the major 7 note (surprise!) so C E G B. If it's dominant 7, it uses m7, so C E G Bb. If it's m7, it uses min. triad - C Eb G - with m7 of Bb.
Comment: Actually, C+9 means a C augmented chord (C E G#) extended up to the ninth. A 9 implies a dominant 7th (just as a 13 implies a 9th and a 7th), so a C+9 spelled out is C, E, G#, Bb, D. If you wanted a C E G Bb D#, you would notate it as C7#9. In jazz music, we often use "alt" ("altered") as a shorthand to describe b9 and #9 extensions with or without augmented or diminished triads.
Comment: @JayCarlson - thanks for that. Yes, it's correct. I have seen C #9, (not C#9), and fallen foul of that one! Edited.
Comment: Please read edit for edification.
Answer: "A/C" means "A major with C as the bass note". I guess you could technically have "A/A" but it would be a little redundant because it would just mean "A major with A as the root note" (aka just "A major"). "A/B" is certainly a valid chord, albeit a little unusual-sounding.
Regarding "Cadd9", this means "C major with major 9th added", or the chord C E G D. This is as opposed to C9, which is C E G Bb D (Bb meaning "B flat") - the 9th is added to the top of the chord, rather than just adding notes until you get to the 9th.
I'm not sure what you expect something like C-5 to be. Technically it means "C minor" but is a very weird way of writing it; the - symbol can be used to signify a minor chord (though it's pretty uncommon to see it written like that) and it's usually just a given that the 5th is there.
The most common symbols are things like b (flat), # (sharp), + (augmeted) and o (diminished). Wikipedia can be a good source of knowledge for things like this.
In terms of chord diagrams, just a quick google search will tell you countless ways of playing the chord you're looking for on your chosen instrument.
Comment: perhaps that C-5 was meant to be C5 (like a power chord). Only some styles of music will use the - to mean minor.
Comment: @b3ko maybe. The question wasn't clear so I thought I'd mention what it technically means just in case. I linked to the Wikipedia article if OP is interested in any further reading though :-)
Answer: Interesting thread. Good comments!

perhaps that C-5 was meant to be C5 (like a power chord).

[edit] Yes! I overlooked that earlier. I use that notation where needed; "C5" being open-5th power chord; no 3rd. Thanks for the reminder. :-)
I agree with James, "A/A" is totally redundant. It's not wrong in any academic sense, but is unnecessary in any conventional situation. The default is always "no inversion". The "bass note" of chord X major, X minor, X whatever, is always X unless otherwise specified.
"A/B" is certainly a valid chord. :-)
Yep. At a glance, that construct appears to be an A major triad played over the 2nd degree (B) of the chord scale. However, 99,999 times out of 100,000, it fulfills the the usual harmonic function of a B7 chord, because it's not an A chord at all: it's a variation of a B dominant 7th chord. Specifically, it is a B(9)sus4.
(The A major triad up top is the triad based on flat-seven of the bass note, B, which is the REAL root of the chord. In other keys: Bb/C, Eb/F, E/F#, etc. The denominator is the root.)
Rarely will you see B(9)sus4 on a lead sheet. Typically it will be A/B or F#m7/B; both fulfill the same function as B7sus4 (even though none of the three are are literally equivalent).
Both forms are EXTREMELY COMMON V-of-I chords in popular songs. I'd say that way, WAY more than half of all R&B, Soul, and soft rock tunes of the '60s, '70s, and '80s utilize that construct when a five-of-something chord is needed. Sit at your piano, play an Em7 chord with your right hand, a lower A with your left, and resolve it to some sort of D (such as D, D6, Dmaj7, Dm, Dm7, Dm9). Whatever you do, it will probably sound somewhat familiar. :-)
On a guitar, it's the easiest barre chord you'll ever play: Mute the low E, and barre all the other strings at (say) the 5th fret -- and that's it. You've got a C/D (more accurately, Am7/D) which makes a nice five-of some form of G or Gm. The root will be on the A string. (There are other forms, of course, but they are beyond the scope of this comment.)
BTW, the little triangle is shorthand for "major", the context virtually always being a Major 7th chord:
CΔ7 = C major 7th chord, (a C-E-G-B tetrad in the inversion of your choice). :-)
I also agree with James' caution about standards. They exist, and though they are not universal or immutable, it behooves us to adhere to them as best we can. Sometimes, context can reveal the meaning of an otherwise ambiguous operator.
For example The "+" can mean "add" but more often means "augmented" or "sharp" (example: D7+5 is a D7 aug 5th; D7+9 would be synonymous with D7#9).
The "-" is often shorthand for "minor" (e.g. "E-7", an E minor 7th chord) but could also be used to mean:

"diminish"  : e.g. "D-5", meaning "D flat-5th", not "D without a 5th" or
"flat" ("E7-9", meaning "E dominant 7th chord with a flat9th". Note that in this case, the minus sign means "ADD a flat 9th to the chord".

I hope this is useful, and not too confusing.
Comment: Not seen '+' as meaning 'add' yet. And while logic says '-' should mean dim., not seen that either. Have seen '-' to depict flatten a note - but that doesn't always make it diminished.
Comment: *perhaps that C-5 was meant to be C5* - no, I see that C+5 exists, is this cause that C-5 exists?
Comment: @nick_n_a `C-` is an uncommon way of writing "C minor". The opposite symbol to `-` is `Δ` (ie "major"). Thinking of `+` and `-` as mathematical symbols will cause you a lot of headaches. Look at the link I posted in my answer for more info on symbols in musical notation.

What does chord-suffix mean?


Measure Rate Of Convergence For Quadrature Methods

Question:
Hi.
I'm trying to measure the rate of convergence of trap/midpoint/simpson rule for approximating the integral of (x+1261/1500)^4 between 0 and 5.
From this graph, how would I measure the rate of convergence of each method?
I am using R to produce these graphs.
Answer: Approximate these lines per linear regression to the form
$$
\log({\rm error})=c-p\log(N)
$$
then $p$ resp. the closest integer is the order of the method.
You could also try to directly read $p$ off of the slopes in the log-lg-graph.
Comment: Thank you so much I will let you know how I get on :)