Como desenhar uma reta usando geometria de tartaruga?

Question: Estou tentando complementar minha resposta a uma pergunta sobre interseções de circunferências. Nessa resposta, em dado momento, eu obtenho uma equação da reta na através dos coeficientes a,b,c:
r: a*x + b*y + c = 0

Gostaria de representar essa reta na tela usando tartaruga (turtle), de preferência usando apenas geometria de tartaruga:

baixar/subir a caneta
virar-se para esquerda/direita R graus
andar S passos para frente

No caso, minha tartaruga começa da origem, virada para o sentido positivo do eixo X (virada para eixo X+).
É adequado também retornar ao local de origem da tartaruga após um procedimento de desenho. Após desenhar algo, ficar em uma posição aleatória não me é positivo.
O que tenho
Dependendo da inclinação da reta, eu tenho uma estratégia diferente de como desenhá-la.
Reta horizontal
Representando a reta apenas por (a,b,c), se a == 0, então temos uma reta horizontal, com y = -c/b.
Desse modo, preciso fazer o seguinte:
subir caneta
virar 90° para a esquerda     # fico virado para o eixo Y+
andar -c/b
virar 90° para a direita      # volto a ficar voltado para o eixo X+
baixar caneta
desenha a reta                # voltando ao ponto de partida da reta
subir caneta
virar 90° para a direita      # fico virado para o eixo Y-
andar -c/b                    # retorna para a origem
virar 90° para a esquerda     # volto a ficar voltado para o eixo X+

Em Python, sendo t a tartaruga:
t.penup()
t.left(90)           # fico virado para o eixo Y+
t.forward(-c/b)
t.right(90)          # volto a ficar voltado para o eixo X+
t.pendown()
# desenha a reta e volta a esse mesmo ponto
t.penup()
t.right(90)          # fico virado para o eixo Y-
t.forward(-c/b)      # retorna para a origem
t.left(90)           # volto a ficar voltado para o eixo X+

Reta vertical
Representando a reta apenas por (a,b,c), se b == 0, então temos uma reta vertical, com x = -c/a.
Desse modo, preciso fazer o seguinte:
subir caneta
andar -c/a
virar 90° para a esquerda     # volto a ficar voltado para o eixo Y+
baixar caneta
desenha a reta                # voltando ao ponto de partida da reta
subir caneta
virar 90° para a esquerda     # fico virado para o eixo X-
andar -c/a                    # retorna para a origem
virar 180° para a direita     # volto a ficar voltado para o eixo X+

Em Python, sendo t a tartaruga:
t.penup()
t.forward(-c/a)
t.left(90)           # volto a ficar voltado para o eixo Y+
t.pendown()
# desenha a reta e volta a esse mesmo ponto
t.penup()
t.left(90)           # fico virado para o eixo X-
t.forward(-c/a)      # retorna para a origem
t.right(180)         # volto a ficar voltado para o eixo X+

Reta com inclinação
Representando a reta apenas por (a,b,c), se a != 0 e b != 0, então temos uma reta inclinada que varia tanto no eixo X quanto no eixo Y.
Eu sei que ela intercepta o eixo X quando y = 0, logo esse ponto é (-c/a,0). Em seguida, devo determinar a direção da reta.
Quando a equação da reta está no formato y = m*x + k, então m vale a tangente do ângulo que a reta faz com o eixo X. Esse ângulo é a rotação do quanto no sentido anti-horário é necessário girar para que apontar na direção da reta. Então eu posso obter o ângulo em radianos via math.atan(m). Como m = -a/b, então eu obtenho o ângulo via math.atan(-a/b).
Eu também posso calcular o ângulo sem fazer essa divisão explícita através do math.atan2. Quando x varia b unidades, então y precisa variar -a unidades:
; seja (x0,y0) o ponto inicial da reta e (x1,y1) o ponto da reta obtida deslocando x0 em b unidades
a*x0 + b*y0 + c = 0
a*x1 + b*y1 + c = 0

x1 = x0 + b
; portanto:

a*(x0 + b) + b*y1 + c = 0
a*x0 + a*b + b*y1 + c = 0
a*x0 + a*b + b*y1 + c = a*x0 + b*y0 + c
a*b + b*y1 = b*y0
b*y1 = b*y0 - a*b = b*(y0 - a)
; como b != 0, pois a reta está inclinada:
y1 = y0 - a

; portanto, a inclinação é
(b, -a)

Como demonstrado, a direção da reta aponta para (b, -a), chamar math.atan2(-a, b) retornaria o ângulo adequado para apontar nessa direção.
Após achar o ângulo em radianos, só transformar em graus e usar na tartaruga.
Em Python, abstraindo radians2degree que transforma radianos em graus, ficaria assim para desenhar a reta:
inclinacao = radians2degrees(math.atan2(-a, b))
t.penup()
t.forward(-c/a)      # vai ao ponto em que a reta corte o eixo X
t.left(inclinacao)   # inclina na direção da reta
t.pendown()
# desenha a reta e volta a esse mesmo ponto
t.penup()
t.right(inclinacao)  # fico virado para o eixo X+
t.left(180)          # viro para o eixo X-
t.forward(-c/a)      # retorna para a origem
t.right(180)         # volto a ficar voltado para o eixo X+

Ponto específico de dificuldade
Estando em qualquer lugar da tela, eu consigo desenhar um segmento de tamanho arbitrário. É possível pegar as dimensões da tela em passos de tartaruga através das chamadas t.window_height() e t.window_length(). Eu sei que eu consigo desenhar ocupando a tela (com excedente) desenhando (h**2 + w**2)**0.5 para frente, virando 180°, andando 2 vezes essa distância, depois virando 180° de novo e andando essa distância novamente para voltar à origem do desenho (é necessário rodar 180° para voltar à orientação original). Porém, esse método de desenho inclui um "desperdício" de desenho fora da tela.

A distância (h**2 + w**2)**0.5 é a maior possível entre dois pontos de uma janela retangular: a distância entre o ponto inferior-esquerdo e o superior-direito.

Atualmente, com uma constante de 50 para frente e para trás, eu desenho um pequeno segmento, não a reta inteira:

No caso, eu estava propositadamente testando para obter a equação da reta a partir de circunferências cujos centros tem sempre y = 0, por isso as retas são todas verticais.
Comment: E qual é a dúvida? :D
Comment: @AndersonCarlosWoss desenhar com a tartaruga algo que seja "visualmente" uma reta na tela. Quando digo "visualmente uma reta" é indicando que, na área visual, o segmento desenhado vai até as bordas. Queria desenhar sem exceder até as bordas, excedendo no máximo apenas erro de arredondamento
Comment: @JeffersonQuesado, a minha resposta te ajudou?
Answer: Se você não quer ultrapassar o limite da tela, a opção mais simples seria fazer um loop em que a tartaruga anda pequenos passos enquanto não atinge a borda:
w = turtle.window_width()
h = turtle.window_height()
while abs(t.xcor())<w/2 and abs(t.ycor())<h/2:
    t.fd(5)

outra opção é calcular o tamanho do segmento até atingir a tela. Pro exemplo se y=a*x+b então o valor de x em que a tartaruga atinge a borda superior é x_sup=(h/2-b)/a e para a borda inferior é x_inf=(-h/2-b)/a. Assim sendo, o menor valor de x que a tartaruga pode ter é min(x_sup,x_inf,-w/2), enquanto o maior valor é max(x_sup,x_inf,w/2). Sabendo o maior e o menor valor de x que a tartaruga pode ter, calcule o valor de y com y1 = a*x_max+b e y2 = a*x_max+b. Nesse ponto, para determinar o quanto a sua tartaruga vai andar até atingir o limite basta fazer d1 = math.sqrt((y1-b)**2+x_max**2) e d2 = math.sqrt((y2-b)**2+x_max**2). Termine com:
t.forward(d1)
t.left(180)
t.forward(d1+d2)

Aqui eu estou assumindo que sua tartaruga ja está em (x,y)=(0,b) e apontada para o ângulo certo e que você não quer usar goto


Converter htacces para nginx

Question: Boa tarde estou migrado um servidor Apache para Nginx e tenho um projeto com algumas regras no .htaccess que nao sei como converter para o Nginx
são elas:
<code>RewriteEngine On

RewriteCond %{HTTP_HOST} !^www.
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule .* http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

RewriteRule ^(.*)/*sitemap.xml$ app.php?path=sitemap.xml [L]

RewriteCond %{REQUEST_URI} .(jpg|jpeg|png|gif)
RewriteCond %{HTTPS}s ^on(s)|

RewriteRule ^imagem/([/a-zA-Z0-9._-]+)$ http%1://outrodominio.com.br/up$

RewriteCond %{REQUEST_URI} !.(jpg|jpeg|png|gif|css|js|zip|log|eot|ttf|woff|svg$
RewriteRule ^(.*)$ app.php?path=$1 [QSA,L]
</code>
preciso de ajuda para criar essas regras no Nginx
Answer: Veja se ajuda:
<code># non-www to www
server {
  listen       80;
  listen       443 ssl;
  server_name  seudominio.com.br;

  return 301 $server_protocol://www.$server_name$request_uri;
}

server {
  listen       80;
  listen       443 ssl;
  server_name  www.seudominio.com.br;

  location / {

    if (-f $request_filename) {
      break;
    }

    if (-d $request_filename) {
      break;
    }

    rewrite ^(.+)$ /app.php?path=$1 last;
  }

  location /imagem/ {

    rewrite ^(.+)$ $server_protocol://outrodominio.com.br/up$1 last;
  }
}
</code>

Converter htacces para nginx


What do the rests in this bar mean?

Question:
I don't understand what the half note rest means at the start of this measure. If it's a half  note rest then why are all the notes in the chord not half notes? Same question for the eight note rest which appears a bit later.
Comment: @eeijlar My reading is that the top voice is the one with stems up, the bottom is with stems down, and the "middle" is as I described, the rests and the dotted-quarter (the durations of all those three "voices" add up to four beats). The fact that two of the voices use stems-down is one of the good reasons not to try to cram more than two into a staff if you can help it.
Comment: Though *wow*, it seems like a not-great idea to have crowded this many voices into a single staff. Very cramped typesetting. So to spell it out, there appear to be three voices at work here, and the middle one has a half rest, an eighth rest, and a dotted-quarter G (assuming this is treble clef).
Comment: Hi, eeijlar, welcome to the site. The linked duplicate, plus other posts linked to it, all address the issue of "multiple voices" written together on a single staff. One of those posts should clarify for you the measure in your question.
Comment: @Aaron: that does answer my question, thank you! How do I know which 'voice' the rest applies to? Is it the first 'voice' or the second?
Comment: @AndyBonner: Three voices! I thought there was two. If there were three, then would that mean the voice two is just made up of rests?? I would have to agree about the typesetting.
Answer:
How do I know which 'voice' the rest applies to? Is it the first 'voice' or the second?

In this measure there are 3 voices, which I separated in the image below. In general it might seem unambiguous, but in practice it's rather clear, since:

each voice consistently uses stems up or down,
notes and rests are aligned horizontally so that their position in the measure is quite obvious,
it is rather uncommon in music for voices to cross (and if they do, a special care needs to be taken to notate it clearly).
Comment: @eeijlar - count the stems -down A E B - that constitutes 4 beats (full bar). The 'middle line' of music must have stems (!), so, the writer decided stems down. Look at where the rests are placed - out of line to where they should be - and that's the clue that makes G the 'middle line'. Stems up/down doesn't *really* matter. It's not the best writing I've ever seen..!
Comment: @eeijlar what Tim said. Also note on the first beat you have low A in one voice, you have a chord in an upper voice, and you have a pause – this clearly indicates there is a third voice.
Comment: that makes sense, except for your second staff. Should the dotted G not be part of the third voice since it has a downward stem?

What do the rests in this bar mean?


Can $f(x) = \sin(nx)\sin(mx)$ $m,n \in \Bbb{N}$ be written as something in $A= \left\{\sum_{n=0}^k a_n \sin(n x): k \in \mathbb{N}\right\}$?

Question: $1.$ Can a product of sine functions $$f(x) = \sin(nx)\sin(mx)$$  $m,n \in \Bbb{N}$ be written as something in the set $$\left\{\sum_{n=0}^k a_n \sin(n x): k \in \mathbb{N}\right\}$$
Asuming $a_n \in \Bbb{R} $?
I beleive not. I beleive it can be written, using trigonometric identities, as a sum of sines and cosines
$$\left\{\sum_{n=0}^k a_n \sin(n x) + \sum_{m=0}^j b_m \cos(m x): n, m \in \mathbb{N}\right\}.$$
$2.$ In the interval $[0, \pi]$ I claim that there don't exist injective functions in $$\left\{\sum_{n=0}^k a_n \sin(n x): k \in \mathbb{N}\right\},$$ because $\sin(nx)$ is not injective in that interval
True/False?
Answer: I'm not sure for a finite series, but f(x) would be periodic, and it is an even function, so it can be written as an infinite sum of cos(n*x) by it's Fourier representation. Apologies if this isn't of any help.


Filling in 2D Array into 3D Array in Java

Question: I want to write a Method where I get a 3x6 workingArray (but might also be 3x5, 3x4...) and a 3x3 (maybe also different size) filteringArray and make an 3D Array (holdArrays) where I put in the first Array to make a square (in this case 3x3), then move one position and put in another 3x3, till the last column of workingArray has been covered.
Somehow I get an nullPointerException in '//affected line' and I can't see why. So I wonder if I do this the right way and I haven't found resources for how to put 2D Arrays into 3D Array.
Example:
1 2 3 4      1 2 3       2 3 4
5 6 7 8  to  5 6 7  and  6 7 8
9 1 2 3      9 1 2       1 2 3

private static void filtering(double[][] workingArray, double[][] filteringArray) {

    // creating amount of holdArrays to work with filterArray
    double[][][] holdArrays = new double[workingArray.length - filteringArray.length + 1][filteringArray.length][];

        // filling in the parted workingArray into holdArrays
        for (int i = 0; i < holdArrays.length; i++) {

            for (int j = 0; j < filteringArray.length; j++) {

                for (int k = 0; k < filteringArray[j].length; k++) {

                    holdArrays[i][j][k] = workingArray[j][k]; //affected line
                }
            }
        }
    }

Comment: You haven't specified the third dimension size while creating holdArrays ?
Comment: My bad. I really missed that. No nullPointerException anymore. Thank you @DeepakPatankar !
Answer: The size of the last dimension is not specified. And since the line
holdArrays[i][j][k] tries to access the kth element which is not there, it throws a Null Pointer Exception.
 double[][][] holdArrays = new double[workingArray.length - filteringArray.length + 1][filteringArray.length][];


difference between convex and concave functions

Question: what is the difference between convex, non-convex, concave and non-concave functions? how will we come to know that the given function is convex or non-convex? and if a function is non-convex then it will necessarily be concave one?
Thanks in advance
Answer: A convex function has one minimum - a nice property, as an optimization algorithm won't get stuck in a local minimum that isn't a global minimum. Take $x^2 - 1$, for example:
A non-convex function is wavy - has some 'valleys' (local minima) that aren't as deep as the overall deepest 'valley' (global minimum). Optimization algorithms can get stuck in the local minimum, and it can be hard to tell when this happens. Take $x^4 + x^3 -2x^2 -2x$, for example:
A concave function is the negative of a convex function. Take $-x^2$, for example:
A non-concave function isn't a widely used term, and it's sufficient to say it's a function that isn't concave - though I've seen it used to refer to non-convex functions. I wouldn't really worry about this one.
Comment: These answers may be deeply confusing to people trying to learn about convexity.  "Has one minimum" does not uniquely characterize convex functions.  Non-convex functions may have unique local minima.
Comment: Why do optimization algorithms get stuck in local optima? We could calculate all optima using the derivative and compare their y-values, no?
Answer: To define a convex function, you need a convex set $X$ as the domain and $\mathbb{R}$ as the codomain.
A function is convex if it satisfies the following property:
$$\forall x_1, x_2 \in X, \forall t \in [0,1], f(tx_1+(1-t)x_2) \le tf(x_1) +(1-t)f(x_2)$$
You should read through the wikipedia page of convex funciton.
In one dimension, you can visualize the dimension as whenever you pick any two points on the domain and connect them using a straight line, the straight line is always equal to or above the graph.

Personally, I find the following property to check convex property to be incredibly useful:
"A continuous, twice differentiable function of several variables is convex on a convex set if and only if its Hessian matrix of second partial derivatives is positive semidefinite on the interior of the convex set."

A function is non-convex if the function is not a convex function.
A function, $g$ is concave if $-g$ is a convex function.
A function is non-concave if the function is not a concave function.

Notice that a function can be both convex and concave at the same time, a straight line is both convex and concave.
A non-convex function need not be a concave function. For example, the function $f(x)=x(x-1)(x+1)$ defined on $[-1,1]$.


Age replacement policy for hard disks and SSDs at servers

Question: I'm planing an age replacement policy for our storage and servers. Most of them are for DBs and some for images (static content) so yes, they have an huge I/O everytime.
Also, we use Samsung 840 Pro SSDs for the RAID Controllers (PERC H700i) as CacheCade.
Are you guys managing the replacement of old hard drives and solid state drives?
Comment: When they fail or begin exhibiting the symptoms of impending failure they get replaced. I've never heard of anyone proactively replacing hard drives based on age.
Answer: We don't proactively replace disks.
Wait until they fail or report prefailure status. This is why you have (hardware) RAID, management agents, failure indication LEDs on the server and a monitoring solution.
Keeping your gear under warranty and maintain your support contracts (within reason), having cold spares of components that fail often (disks, power supplies, RAM) and proactively monitoring the environment will take you much farther.
Comment: @Halfgaar In larger environments and at large enough scale, RAM fails... No way to prevent it.
Comment: Hmm. RAM fails often? The RAM that's good from the start (no memtest errors) seems to hold out forever for me.
Comment: Yeap, RAM fails sometimes :( Power supply fails are easy to avoid when you have redundant power
Answer: We don't proactively replace disks either.  Backblaze recently did a blog post on this subject.  One should note that they primarily use consumer grade drives.


Correlation with ordinal outcome variable and four ordinal (?) independent variables

Question: I have scored student's solutions according to a rubric which is scaled from 1-5. This accounts for the dependent variable. After videoing student's interactions in groups, I have coded the number of times they said four specific words I was interested in (it was a little more complicated than this, but for the sake of understanding). These four factors account for the independent variables. There are 27 samples in the data which include the student's scored argument and the number of times they said each of the four specific words. I am hoping to discover if there is a significant positive or negative correlation between their scored argument and the number of times they said each of the four words. Is there a statistical test for this? I have tried Spearman's rank correlation, but by my understanding I can only use one independent variable for this test. I have included my data below.

Comment: If this is the complete data, it is maybe few cases to investigate four independent variables. But I would see it as more of a regression problem, but start out with some tables and visualizations. Look into ordinal regression, one post is:  https://stats.stackexchange.com/questions/302254/ordinal-regression-logit-probit-complementary-log-log-or-negative-log-log/302256#302256
Comment: You are correct that Spearman correlation looks at the relationship between exactly two variables, but you can just run a Spearman test 4 times, once for each independent variable comparing against the same dependent variable. To be complete, you'll then have to adjust the significance of your results due to multiple hypothesis testing.
Answer: This appears to be too small a sample to obtain anything strongly significant.
Performing simple linear regression gives the following p-values for the slopes on the explanatory variables:
<code>     0.298377646979805
     0.242069284775947
     0.542518498332371
    0.0765452504092274
</code>
and the following coefficients:
<code>     0.150821087611921
    -0.205764501620133
     -0.22273623562583
    -0.449611423943887
</code>
Of if you run the regression with the logarithm of the "scored argument" then you get the following p-values:
<code>     0.293969089451282
     0.290364255905711
     0.499341526214123
    0.0555191236104219
</code>
and the following coefficients:
<code>    0.0454807348691385
   -0.0553966456864823
   -0.0738823488768918
    -0.146133621656525
</code>
(Reasonable as taking logarithms of variables which are always positive often improves inference.)
However, as a commentator pointed out, it's not really appropriate to do simple linear regression when the dependent variable is ordinal / categorical. In this case, an ordinal  multinomial model should be used. See here for further details (Matlab link since I was working in Matlab).
With an ordinal multinomial model we end up with the following p-values on the explanatory variables:
<code>     0.316637233111995
     0.312612749358216
     0.436799749905584
     0.082584197771639
</code>
and the following coefficients:
<code>    -0.238697920928262
     0.293986734960427
    0.0516709598386895
      2.39433385577948
</code>
(Signs have the opposite interpretation to above.)
Comment: I disagree with your point about statistical significance. At a traditional 0.05 significance threshold and 80% power, 27 samples is sufficient to identify a correlation coefficient as low as 0.23, which isn't a particularly strong effect.
Comment: @NuclearWang How did you get 0.23? Using pwr in R I fond 0.51.
Comment: @NuclearWang Don't forget that when I estimate the multinomial model, in total I'm estimating 8 parameters simultaneously (4 offsets for all but one of the categories, plus the 4 slope coefficients).


A Box contains 4 blue, 2 red and 3 black pens. If 3 pens are drawn at random (not replaced) ,whats the prob. of drawing 2 blue & 1 black pen?

Question: This seems to be a straightforward probability question but appears to have 2 contradicting answers :
Solution 1:
Probability of drawing 1 blue pen = 4/9
Probability of drawing another blue pen = 3/8
Probability of drawing 1 black pen = 3/7
Probability of drawing 2 blue pens and 1 black pen = 4/9 * 3/8 * 3/7 = 1/14
Reference (UnderDependent Event example 1) : https://www.mbacrystalball.com/blog/2015/07/03/probability/
Solution 2:
As there are 3 ways we can get the combination of 2 blue + 1 black - i.e ([Blue,Blue,Black],[Blue,Black,Blue],[Black,Blue,Blue]) it should be 3 times 1/14 (above answer).
Reference: https://www.quora.com/A-pack-contains-4-blue-2-red-and-3-black-pens-If-2-pens-are-drawn-at-random-from-the-pack-not-replaced-and-then-another-pen-is-drawn-What-is-the-probability-of-drawing-2-blue-pens-and-1-black-pen
Any idea on which is right?
Answer: The second one is the correct one. The first one is the probability of having the first two draws blue and last draw black. That is different than having two blues and one black in total, i.e.
$$\begin{align}P(\text{2 blue and 1 black}) &= P(Blue, Blue, Black) + P(Blue, Black, Blue) \\&+ P(Black, Blue, Blue)\end{align}$$


sed with negative lookahead in file

Question: I'm trying to replace all occurrences of a string (str) that are not adjacent to an underscore in a file with another string (replacementstr). This does not work-
sed -i 's/^(?!_str_|_str|str_)(str)$/replacementstr/g' /home/somefile.txt

Comment: can you put a sample data and your expected output?
Comment: Which specific version of `sed`? POSIX-baseline sed doesn't support PCRE extensions.
Comment: (`sed -i`, incidentally, is _also_ a non-POSIX extension; the POSIX-standardized in-place editing tools are `ed` and `ex` -- and if you know how to use vim in command mode, you already know `ex`).
Comment: OK will do. Sorry about that.
Answer: You don't need negative lookahead at all for this -- and your resulting state machine will be more efficient without it (meaning you're better off not using it even if your engine did support them).
sed -r 's/(^|[^_])str([^_]|$)/\1replacement\2/g'

Comment: Nice! probably worth mentioning you need `-r` to be able to catch without escaping the parentheses.
Comment: Quite right, that. I was avoiding going into usage because I don't want to (even implicitly) endorse `-i`, but since I'm giving an ERE, it's rather unavoidable.

sed with negative lookahead in file


Como concatenar as Strings em uma consulta Linq

Question: Como faço para concatenar a coluna Sistemas, deixando Sistema, Sistemas 2?
Tenho essa consulta Linq:
var fiscalizacoesBaixadas = (from tb_fiscalizacoes_campo in _context.TB_FISCALIZACOES_CAMPO
             join tb_fiscalizacoes in _context.TB_FISCALIZACOES
                on tb_fiscalizacoes_campo.FIS_ID equals tb_fiscalizacoes.FIS_ID
             join tb_concessionarias in _context.TB_CONCESSIONARIAS
                on tb_fiscalizacoes.CON_ID equals tb_concessionarias.CON_ID
             join tb_municipios in _context.TB_MUNICIPIOS
                on tb_fiscalizacoes_campo.MUN_ID equals tb_municipios.MUN_ID
             join tb_fiscalizacoes_campo_sistemas in _context.TB_FISCALIZACOES_CAMPO_SISTEMAS
                on tb_fiscalizacoes_campo.FIS_ID equals tb_fiscalizacoes_campo_sistemas.FIS_ID
             join tb_sistemas in _context.TB_SISTEMAS
                on tb_fiscalizacoes_campo_sistemas.SIS_ID equals tb_sistemas.SIS_ID
             join tb_fiscalizacoes_campo_ugr in _context.TB_FISCALIZACOES_CAMPO_UGR
                on tb_fiscalizacoes_campo.FIS_ID equals tb_fiscalizacoes_campo_ugr.FIS_ID
             join tb_ugr in _context.TB_UGR
                on tb_fiscalizacoes_campo_ugr.UGR_ID equals tb_ugr.UGR_ID
             select new
             {
                 Id = tb_fiscalizacoes.FIS_ID,
                 Concessionaria = tb_fiscalizacoes.TB_CONCESSIONARIAS.CON_NOME_FANTASIA,
                 Municipio = tb_municipios.MUN_NOME_MUNICIPIO,
                 UGR = tb_ugr.UGR_NOME,
                 Sistemas = tb_sistemas.SIS_NOME,
                 DataInicio = tb_fiscalizacoes_campo.FIC_DATA_INICIO,
                 DataFim = tb_fiscalizacoes_campo.FIC_DATA_FIM
             });
dataGridFiscalizacoes.ItemsSource =fiscalizacoesBaixadas.Distinct().ToList();

Que me traz esses results:

Quando adiciono um GroupBy, as linhas não são mais duplicadas, mas ainda preciso que as Strings sejam concatenadas.
dataGridFiscalizacoes.ItemsSource = fiscalizacoesBaixadas.Distinct().GroupBy(x => x.Id).ToList();

Comment: Qual o motivo do `-1`? Acho que se você não entendeu, deveria me avisar e perguntar.
Answer: Você teria que derivar novamente a lista de retorno, usando o primeiro registro como referencial e agregando os sistemas:
dataGridFiscalizacoes.ItemsSource = fiscalizacoesBaixadas
                    .Distinct()
                    .GroupBy(x => x.Id)
                    .Select(g => new {
                            Id = g.Key,
                            Concessionaria = g.ToList().First().Concessionaria,
                            Municipio = g.ToList().First().Municipio,
                            UGR = g.ToList().First().UGR,
                            Sistemas = g.ToList().Aggregate("", (str, registro) => str + ", " + registro.Sistemas),
                            DataInicio = g.ToList().First().DataInicio,
                            DataFim = g.ToList().First().DataFim
                        }).ToList();

Havendo mais dúvidas, veja esta resposta.
Answer: Adicione um novo Select após o GroupBy concatenando a string que você precisa:
dataGridFiscalizacoes.ItemsSource = fiscalizacoesBaixadas.Distinct().GroupBy(x => x.Id).Select(y => new
{
    Id = y.First().Id,
    Concessionaria = y.First().Concessionaria,
    Municipio = y.First().Municipio,
    UGR = y.First().UGR,
    DataInicio = y.First().DataInicio,
    DataFim = y.First().DataFim,

    // Concatena o campo Sistemas dos registros deste agrupamento.
    Sistemas = string.Join(", ", y.Select(registro => registro.Sistemas))
}).ToList();


Cálculo de valores de tags dinâmicas

Question: Fala galera tudo belezinha com vocês?
Estou mexendo no meu sistema (leia-se laboratório).
Já basicamente criei todo o Back-End, mas no front estou apanhando com alguns tratamentos.
Estou criando uma tela de orçamentos, onde o Usuário vai abrindo novas linhas de forma dinâmica para cada produto acrescentado.
Meu código está assim:

function id(valor_campo) {
  return document.getElementById(valor_campo);
}

function getValor(valor_campo) {
  var valor = document.getElementById(valor_campo).value.replace(',', '.');
  return parseFloat(valor);
}

function multiplica() {
  var total = getValor('qtd') * getValor('valoru');
  id('valort').value = total;
}

$(document).ready(function() {
  var max_fields = 100;
  var x = 1;
  $('#add_field').click(function(e) {
    e.preventDefault(); //prevenir novos clicks
    if (x < max_fields) {
      $('#listas').append('\

\

\
                        <input type="text" name="qtd[]" id="qtd[]" placeholder="N°">	\
                        <input type="text" name="item[]" id="item" placeholder="Descrição do Produto ou Serviço">	\
                        <input type="text" name="valoru[]" onblur="multiplica()" id="valoru[]" placeholder="Valor">	\
                        <input type="text" name="valort[]" id="valort[]" maxlength="100" />	\
                        	\
                        <button type="button" class="btn-danger">Remover</button>	\

\
                ');
      x++;
    }
  });

  $('#listas').on("click", ".remove_campo", function(e) {
    e.preventDefault();
    var tr = $(this).attr('id');

    $('#listas tr.' + tr).remove();
    x--;
  });

});

      Qtd
      Item
      Valor Unitário
      Valor Total
      Ação

      <input type="text" name="qtd[]" id="qtd" placeholder="N°">
      <input type="text" name="item[]" id="item" placeholder="Descrição do Produto ou Serviço" />
      <input type="text" name="valoru[]" id="valoru" onblur="multiplica()" />
      <input type="text" name="valort[]" id="valort" />

Acabei montando com base em dicas de outros usuários daqui. Porém eu quero fazer o cálculo do input qtd multiplicando o valor de valoru mostrando total em valort
Porém quando acrescento outra linha, meu código simplesmente não consegue fazer o cálculo (Imagino que por conta do ID se repetir). Qual seria a melhor forma de contornar isso?
Agradeço a todos que puderem me ajudar.
Um abraço e um bom café quentinho nesse frio =P
Answer: Sim o problema era os id, você já sabia a solução, era só fazer a mesma coisa que fez para remover a linha, usar o x para criar id únicos
Também arrumei a inserção de novas linhas, que, antes, adicionava um tbody na tabela em vez de um tr no corpo da tabela
Outro detalhe,em vez de decrementar o valor de x ao remover uma linha, aumentei o valor de max_fields, para não ter conflito ao criar e excluir linhas

function id(valor_campo) {
  return document.getElementById(valor_campo);
}

function getValor(valor_campo) {
  var valor = document.getElementById(valor_campo).value.replace(',', '.');
  return parseFloat(valor);
}

function multiplica(x) {
  var total = getValor('qtd'+x) * getValor('valoru'+x);
  id('valort'+x).value = total;
}

$(document).ready(function() {
  var max_fields = 100;
  var x = 1;
  $('#add_field').click(function(e) {
    e.preventDefault(); //prevenir novos clicks
    if (x < max_fields) {
      $('#listas').append('\

\
                        <input type="text" name="qtd[]" id="qtd'+x+'" placeholder="N°">	\
                        <input type="text" name="item[]" id="item" placeholder="Descrição do Produto ou Serviço">	\
                        <input type="text" name="valoru[]" onblur="multiplica('+x+')" id="valoru'+x+'" placeholder="Valor">	\
                        <input type="text" name="valort[]" id="valort'+x+'" maxlength="100" />	\
                        	\
                        <button type="button" class="btn-danger">Remover</button>	\
                ');
      x++;
    }
  });

  $('#listas').on("click", ".remove_campo", function(e) {
    e.preventDefault();
    var tr = $(this).attr('id');

    $('#listas tr.' + tr).remove();
    max_fields++;
  });

});

<button id='add_field'>ADD</button>

      Qtd
      Item
      Valor Unitário
      Valor Total
      Ação

      <input type="text" name="qtd[]" id="qtd0" placeholder="N°">
      <input type="text" name="item[]" id="item" placeholder="Descrição do Produto ou Serviço" />
      <input type="text" name="valoru[]" id="valoru0" onblur="multiplica('0')" />
      <input type="text" name="valort0" id="valort0" />

Comment: Ah verdade. Passou completamente despercebido isso. obrigado mesmo pela ajuda.

Cálculo de valores de tags dinâmicas


Firebase Database - Avoid downloading JSON repeatedly on iOS

Question: My use-case for Firebase is slightly different than most. We do not use FB exclusively for our back-end.  We have a large MariaDB server dealing with relations and all data.
Our goal with FB is to allow clients on iOS devices to have their specific data available.  We need to load the data once and then listen for changes to this particular data. Here is a rough overview of how it works:

The main ViewController is loaded
Firebase is initialized and we listen for FIRDataEventTypeChildAdded. (Persistence is enabled)
Firebase loads all matching records. We then loop through and store them locally in the internal SQLite DB.

In the normal userflow, we push other ViewControllers on the screen.  The problem is, once the main ViewController is loaded, FIRDataEventTypeChildAdded fires again for each record.
Questions:

When FIRDataEventTypeChildAdded fires again, is it loading the data from its internal cache (Persistence?) or is it re-downloading everything from the Firebase server? I've used Network Link Conditioner to completely cut the internet connection, and when I do, it does not fire the FIRDataEventTypeChildAdded at all, but as soon as the net comes back, it fires FIRDataEventTypeChildAdded for every single record.
How can I achieve the above where we load all records on login and then only listen for changes to those records? I am already using orderBy and startingAt so if the answer involves one of the above, I cannot add another "hasDownloaded=yes" filter.

Thanks in advance.
Comment: Please share the code you're testing with. Without that it's hard to say anything concrete. See also on [creating an MCVE](http://stackoverflow.com/help/mcve).
Comment: The code doesn't matter in this case.  The problem is that there is no clear definition of how Firebase works behind the scenes.

For the sake of simplicity, I have a ChildAdded and ChildChanged listener in my main ViewController:

Please re-read my questions above as it pertains to understanding if the JSON is downloaded from the server every time the VC is loaded, or if it fetches it from its local cache but still fires the ChildAdded listener.
Comment: It's unclear what the use case is here without seeing how your viewController and Firebase is implemented in code. i.e. *every time the VC is loaded* is highly dependent on the code within the VC. The .childAdded event is intentionally designed to fire one for each child and then for any additional children that are added. It will fire for any new children that are added after reconnecting, however again, it's dependent on your implementation.
Answer: A Firebase reference listener connects to the server once, and stays connected until that query is turned off. As long as the reference being listened to is in memory, there is only one connection made to the database. Once this connection happens, all data will come through as child added data again.
The issue here is not so much with Firebase but that your app is continuously readding listeners to a reference, making the data be redownloaded from the network every time.
So to your first question, yes it is redownloading from the network. To your second, you just need to make sure the Firebase query never leaves memory. This can be done by making your query globally scopes, or simply by not turning off the query when the view controller exits scope (then you need to make sure not to readd multiple queries on subsequent loads).


Exibir apenas valores do array

Question: Eu sou inciante em PHP e estou estudando nesse momento os arrays, e estou com uma duvida boba.
Quando eu imprimo minhas arrays, ela vem dessa forma
Array (
  [0] => Array ( [0] => 10 )
  [1] => Array ( [0] => 20 )
  [2] => Array ( [0] => 30 )
  [3] => Array ( [0] => 40 )
  [4] => Array ( [0] => 50 )
)

Meu interesse é que sejam exibidos apenas os numeros.
10, 20, 30, 40 50

Codigo php
while (($linha = fgetcsv($file)) !== FALSE)
{

  $carros[] = $linha;
  //print_r($linha);

}

fclose($file);
print_r($carros);

Toda ajuda será bem vinda
Comment: De onde vem esse array? Sua pergunta ta muito confusa.
Comment: Eu alterei minha pergunta, pois os sites não me ajudaram.
Answer: Bom, baseando apenas no Array que você mostrou na pergunta, para exibir apenas os valores você pode usar for ou foreach:
$arr = Array (
    0 => Array ( 0 => 10 ),
    1 => Array ( 0 => 20 ),
    2 => Array ( 0 => 30 ),
    3 => Array ( 0 => 40 ),
    4 => Array ( 0 => 50 )
);
foreach($arr as $value){
    echo $value[0]. " ";
}

Veja funcionando: http://ideone.com/kvF17H
Peguei a dica do @Maniero neste post.
Answer: Utilize a função nativa do php
array_values($array);

Exibir apenas valores do array


Convert .cmd file into Windows Service - 1053 Error

Question: I have a file "init.cmd" which has the following commands inside it:
set APP_ROOT=c:/wamp/www/myproj
ringo -b %APP_ROOT%/bin/init.js %APP_ROOT%/app/main.js

The file works fine when run from the command line, but I'd like to turn it into a Windows Service.
So I type:
sc create MyServiceName binPath= c:/wamp/www/myproj/bin/init.cmd
The service is created, but everytime I try to start it, it crashes saying:
Error 1053: The service did not respond to the start or control request in a timely fashion.
I have a similar problem w/ Mongo, which is much simpler.
From a command prompt typing:
c:/mongodb/bin/mongod

successfully starts the mongo server.
But trying to install a service as :
sc create mongo binPath= c:\mongodb\bin\mongod.exe

crashes on start everytime with the same error as above.
Comment: Do you really need it to be a services, or do you just need it to start when the computer starts?  You may be better off setting up a schedule task that is ran when the computer starts.
Answer: You can't create a service pointing at a batch file.  Create the service pointing to the ringo app, then edit the registry and give it the needed parameters.  Set a system wide variable to the value that you need.  That should allow the service to start.
Comment: I have the same problem with Mongo which isn't a batch file.
Comment: It may just be poor error reporting for different reasons.
Comment: Let's forget Mongo for the moment.  Am I able to have the service spawn a batch file AFTER it's been started?  The trouble is that I have to set a variable in the LOCAL scope of the app so a system wide variable will conflict with other apps - hence the batch file.
Comment: No, the service won't be able to run a batch file.  What you could do is throw together a small .NET app and have it set the local variable then launch the app.  Can you run the app under a local user account?  How about setting up an account and setting up a user variable with the correct setting.  That way it won't impact other apps on the system unless they are run under that specific local account.


Dimension formula proof

Question: I got stuck understanding the proof from here (page 1, last line).
Why is $z \in X \cap Y$?
Thanks.
Answer: In the same last line, $z$ is expressed onece as a linear combination  of vectors in $X$ and once as a linear combination of vetcors in$Y$.
Comment: thanks! it makes sense now :)

Dimension formula proof


Interval type for Fourier Analysis on $L^2( [-\pi,\pi) ) $

Question: Why is it that in many texts the natural domain of choice is $L^2 ( [- \pi, \pi) ) $ as opposed to $L^2 ( [- \pi, \pi] ) $? I would to think of the space $L^2 ( [- \pi, \pi] ) $ as the completion of $C_{c}( [- \pi, \pi] )$, so that I can use the fact that trig functions have compact support on the interval $[- \pi,\pi]$, but many books use $[- \pi, \pi)$.
Comment: Probably because you are thinking of functions with period $2\pi$ and for such functions $f(-\pi)=f(\pi)$.  Why can't you just think of $L^2([-\pi,\pi))$ as the completion of $C_c([-\pi,\pi))$?
Comment: @ShawnD because the trig functions have compact support on $[-\pi, \pi]$ when restricted to that interval, and $[-\pi, \pi)$ is not compact. And in which domain do you mean we think of the functions with period $2\pi$?
Comment: I don't understand comment about support of trig functions.  Anyway, a Cauchy sequence of functions on $[-\pi,\pi]$ is still Cauchy when you consider restriction to $[-\pi,\pi)$.  Functions of period $2\pi$ on $\mathbb{R}$ are specified by their value on $[-\pi,\pi)$.
Comment: Don't forget that $L^2$ is not a space of functions but rather consists of *classes* of functions modulo functions that are zero almost everywhere. The single point $\pi$ thus doesn't matter. If you want to think of $L^2$ as a completion you should really work on the (compact) circle *group* $S^1$ and angular measure and complete the space of continuous functions $C(S^1)$ with respect to the $L^2$ norm (the space $C(S^1)$ can be identified with the set of continuous functions $f: [-\pi,\pi] \to \mathbb{C}$ such that $f(-\pi) = f(\pi)$.)
Answer: There is no difference between $L^2([−\pi,\pi))$, $L^2((−\pi,\pi))$ and $L^2([−\pi,\pi])$, because a singleton is a null set. My personal preference is for the latter notation.
But when discussing continuous functions, we pay attention even to single points. The reason to use $[-\pi,\pi)$ is that this interval is in bijection with the circle $S^1$ via $x\mapsto e^{ix}$. Bringing the topology of $S^1$ to $[-\pi,\pi)$, we discover that it is just like the standard topology, with one exception: when a sequence tried to converge to the missing endpoint $\pi$, it converges to $-\pi$ instead. Having made a note of this, we can define $C([-\pi,\pi))$ as the set of functions that are continuous in this circle topology. This is a different space from the space of continuous functions on unmodified interval, $C([-\pi,\pi])$. The latter space contains $f(x)=x$ which is not in $C([-\pi,\pi))$.


Writing a series from 1 ... 8?

Question: I would like to write two expressions.

For each $t$ outputs 1,2,3,4,5,6,7,8 for $t=0,1, \ldots, \infty$.
For each $t$ outputs 1+2+3+4+5+6+7+8 for $t=0,1, \ldots, \infty$.

I have thought about
$$\sum_{t=0}^{\infty} n \qquad 1 \leq n \leq 8$$
but how do I get $n$ to run from 1 ... 8?
Answer: For the series:
I am uncertain about what you mean, but...
$$\sum_{n=1}^{8} n = 1 + 2 +3 +4 + 5+ 6+ 7 + 8$$
In a summation, the variable and its starting value goes on the bottom of the sigma, and the ending value goes on top (so here we let n go from 1 to 8). What then happens is that we evaluate the inside of the summation for each integer n from the starting value to the ending value.
I'm not sure where t comes into it, unless you mean that you want the answer to be independent of t, in which case we just ignore the t completely:
$$ f(t) = \sum_{n=1}^{8} n $$
Alternatively, if you mean you want the t to be the ending value, then:
$$ f(t) = \sum_{n=1}^{t} n $$
For the sequence:
There is no special notation for sequences, so to speak. You could write it as:
$$1, 2, 3, ..., 8$$
What is important is that you include the first term, the last term, and enough other terms to make clear what the pattern is. If we omitted the 3 here, for example, one might misconstrue the sequence as increasing powers of 2, and thus be:
$$1, 2, 4, 8$$
which is not what is wanted.
Answer: For the first expression try,
$$t\mod8 + 1$$
(In a programming language that would be $(t\%8)+1$)
For the second, try
c=t%8 + 1
n = c*(c+1)/2

$$c(c+1)/2$$ is a well known formula for the sum of the first c natural numbers.

Writing a series from 1 ... 8?


Content locking module for Drupal 7

Question: Is there a stable module for content locking (anti-concurrent editing). I found this https://drupal.org/project/content_lock but it's unsupported.
Thanks
Answer: This is already built-in in Drupal 6 and 7, in the function node_validate.
The relevant piece of code is reproduced below:
<code>if (isset($node->nid) && (node_last_changed($node->nid) > $node->changed)) {
  form_set_error('changed', t('This content has been modified by another user, changes cannot be saved.'));
}
</code>
It doesn't lock anything, but it shows the second editor a message, and prevents the second editor from saving and thereby overwriting what the first has done. The second editor can then copy-paste his/her efforts to Notepad or other temporary buffer, reload a fresh version of the node (i.e. a version that contains the first editor edits), add his stuff again, and save.
This warning message serves the same purpose as locking, but IMHO it does it better and less prone to deadlocks.
The problem with an outright lock is that users may open a node edit page but don't actually do any edits.  If they just abandon it (i.e. don't press "Save") it will remain in that state until reset.  Doing it on save is better because it avoids the deadlock situations that may arise from locking something the user may abandon.

Content locking module for Drupal 7


How to Add Image Field in CIVICRM

Question: I am trying to add an Image as Custom field in Civicrm Contact, but the Image Field type is not in the Custom Field section. It has only Field type as File.
How to apply Drupal Image styles for Images uploaded on Civicrm Contact.
I have integrated Civicrm in Drupal 7.
Comment: You might want to post this question in http://civicrm.stackexchange.com
Answer: Well if you want a Drupaly solution you could try installing the CiviCRM Entity module along with the Views in Contact Pages module
With CiviCRM Entity you can add Drupal fields to CiviCRM entities, so you could add you a normal Drupal image field and get all the wonderful goodies Drupal provides such as image styles.
Now this field data would live in Drupal field table not in CiviCRM custom field tables.
You add your field on the CiviCRM Entity Contact entity Manage Fields page at admin/structure/civicrm-entity/civicrm_contact
If you can live with the data being in the Drupal DB, not the CiviCRM db, then this can work for you.
Then if you want to display the image on the CiviCRM backend admin contact summary page, you use the Views in Contact Pages module to create a view that displays the image, along with any other data you want, and put that view either as a tab on the contact page, or a pane on the Summary tab.

How to Add Image Field in CIVICRM


What types of plastic and manufacturing techniques are used to make guitar picks?

Question: Like most guitarists, I'm sure, I have both preferred thicknesses and brands of guitar pick. I have always liked using Jim Dunlop Tortex picks, for instance, as I like the way the plastic wears smoothly. Following these I'm happy to use the generic "shiny-black" picks (e.g. Gibson picks), although these seem more prone to chipping. I don't like using nylon picks, but I can understand why other guitarists like them, particularly when playing acoustic guitar. And I definitely don't like using any type of picks from "pick-cards"; they seem barely better than yoghurt-pot plastic.
Are there significant differences in the types of plastic used for different types/brands of pick?
Are there significant differences in the manufacturing process of different types/brands of pick?
Comment: Thanks for the edit @seseorang. I prefer the way you worded the title too! I was trying to follow the advice of this page: http://meta.stackexchange.com/questions/10647/how-do-i-write-a-good-title but reckon your style is better!
Answer: Are there significant differences in the types of plastic used for different types/brands of pick?
Yes. If, for example, you compare the material properties of the nylon family to the polyoxymethelene family (Of which delrin (or 'tortex') belong) you will see they vary considerably.
The main properties that influence how they perform are:
Friction coefficient – how well the pick 'slides' across the strings (and slides out of your grip!).
Hardness – resistance to wear.
Fracture toughness – energy absorbed up to fracture ('Brittleness')
Young's modulus – stiffness.
Fatigue Limit – pick strokes until failure (chipping or snapping).
The problem is that the pick manufacturers generally don't specify which specific material they use. There are many polymers within the nylon family and their properties vary considerably. If you are interested, asking the manufacturers nicely may get you the specific polymer used, then you can compare pick properties directly somewhere like matweb.com
Or you could ask actual guitarists but you'll have a hard time getting any data that isn't biased and subjective.. eg What a guitarist may interpret as the pick 'gripping' the string may be due to the geometry of the pick and how they hold it rather than the coefficient of friction of the pick material.
Are there significant differences in the manufacturing process of different types/brands of pick?
Handmade picks aside, no. Nearly all picks will be hot pressed from sheet stock. (Imagine putting a sheet of plastic in a waffle iron, that is basically hot pressing. If you change the geometry of the iron you can make plastic picks rather than plastic waffles).
Even though they are all manufactured by the same process there are many variables within that process. Stamping pressure, stamping speed, temperature, rate of heating, rate of cooling (among others) will all effect the final product in some way. After that finishing processes may also be done, coating, printing, smoothing etc
I guess some picks may be injection moulded as not all materials can be hot pressed but I would expect this to be rare or not occur at all.
Comment: Thanks, @Fergus. This is just the kind of info I was looking for! It has always surprised me just how different the various kinds of pick plastic feel. I'm going to try to find out a bit about the picks I really like (mostly out of interest), but this information gets me most of the way there.
Answer: I'm a huge fan of Jazz III's, and I've managed to get them in 4 kinds of plastic. I will give my opinion of these:
Red - Nylon
The classic Red Jazz III is the warmest sounding of the lot, and has the most friction against the strings. These are my favourite as I feel more in control, and prefer the tone. Some people complain about the grip - I've never had issues.
Black - Stiffo
Curiously named "stiffo", they have a brighter sound than the Reds, and feel smoother against the strings. Slightly better grip. Not majorly different overall.
Translucent Yellow - Ultex
The brighest sounding, and these slice through the strings! Shred-heaven with these, if that's your thing. Plenty of attack; the dynamics of your picking are very clear. I don't wear picks out very much, but these are basically indestructible. They don't wear. I loved these when cramming as many notes into a beat was the standard thing to do, but nowadays when I prefer control, I feel these go through the strings a little too well for me. These tend to get a bit slippery during playing, too.
Purple with everyone's favourite tortoise - Tortex
Also a bright sounding pick, and of course a bit different to the usual tortexs given the Jazz III shape, but it's got the same character. Much better grip than all the ones before.
Overall to answer question 1
In my experience, alongside these picks having identical shape/size, the type of plastic used has considerable consequences. I've always been curious about Red Bear picks. These are inexplicably expensive picks which come with a warning to not let them get wet, but they claim to be something to the effect of 'the next best thing to tortoise shell' and it's all apparently down to their unique material. I've never had the luck to try a tortoise shell pick, but given how prized they were, Red Bear picks are certainly enticing.
Comment: Red Bear, and the British "Hawk" brand, are made of casein plastic - derived from milk protein. I love my Hawk picks, and they aren't like other plastics in my opinion.


how to call webservice with https url in android

Question: I am trying to access Webservice with the URL contains HTTPS I am getting No peer certificate error. Following is the error I am getting. Can any one please Help me?
08-04 12:17:52.351: I/ApplicationPackageManager(8068): cscCountry is not German : INS
08-04 12:17:52.875: D/dalvikvm(8068): GC_EXTERNAL_ALLOC freed 60K, 48% free 2801K/5379K, external 504K/517K, paused 47ms
08-04 12:18:08.453: W/KeyCharacterMap(8068): Can't open keycharmap file
08-04 12:18:08.453: W/KeyCharacterMap(8068): Error loading keycharmap file '/system/usr/keychars/sec_keypad.kcm.bin'. hw.keyboards.0.devname='sec_keypad'
08-04 12:18:08.453: W/KeyCharacterMap(8068): Using default keymap: /system/usr/keychars/qwerty.kcm.bin
08-04 12:18:17.656: D/dalvikvm(8068): GC_CONCURRENT freed 198K, 47% free 3005K/5639K, external 617K/1023K, paused 4ms+4ms
08-04 12:18:17.695: W/System.err(8068): javax.net.ssl.SSLPeerUnverifiedException: No peer certificate
08-04 12:18:17.718: W/System.err(8068):     at org.apache.harmony.xnet.provider.jsse.SSLSessionImpl.getPeerCertificates(SSLSessionImpl.java:258)
08-04 12:18:17.718: W/System.err(8068):     at org.apache.http.conn.ssl.AbstractVerifier.verify(AbstractVerifier.java:93)
08-04 12:18:17.718: W/System.err(8068):     at org.apache.http.conn.ssl.SSLSocketFactory.createSocket(SSLSocketFactory.java:381)
08-04 12:18:17.718: W/System.err(8068):     at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:164)
08-04 12:18:17.718: W/System.err(8068):     at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
08-04 12:18:17.718: W/System.err(8068):     at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
08-04 12:18:17.718: W/System.err(8068):     at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:359)
08-04 12:18:17.718: W/System.err(8068):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
08-04 12:18:17.718: W/System.err(8068):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
08-04 12:18:17.718: W/System.err(8068):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
08-04 12:18:17.718: W/System.err(8068):     at com.osi.wolla.login.Login$task.doInBackground(Login.java:223)
08-04 12:18:17.718: W/System.err(8068):     at com.osi.wolla.login.Login$task.doInBackground(Login.java:1)
08-04 12:18:17.718: W/System.err(8068):     at android.os.AsyncTask$2.call(AsyncTask.java:185)
08-04 12:18:17.718: W/System.err(8068):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
08-04 12:18:17.718: W/System.err(8068):     at java.util.concurrent.FutureTask.run(FutureTask.java:138)
08-04 12:18:17.718: W/System.err(8068):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
08-04 12:18:17.718: W/System.err(8068):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
08-04 12:18:17.718: W/System.err(8068):     at java.lang.Thread.run(Thread.java:1019)
08-04 12:18:17.718: I/System.out(8068): response....null
08-04 12:18:17.757: I/System.out(8068): url....https://mywolla.com/mobwebservices/smails_rest.php
08-04 12:18:21.687: W/webserviceCall(8068): Error for URL https://mywolla.com/mobwebservices/smails_rest.php
08-04 12:18:21.687: W/webserviceCall(8068): javax.net.ssl.SSLPeerUnverifiedException: No peer certificate
08-04 12:18:21.687: W/webserviceCall(8068):     at org.apache.harmony.xnet.provider.jsse.SSLSessionImpl.getPeerCertificates(SSLSessionImpl.java:258)
08-04 12:18:21.687: W/webserviceCall(8068):     at org.apache.http.conn.ssl.AbstractVerifier.verify(AbstractVerifier.java:93)
08-04 12:18:21.687: W/webserviceCall(8068):     at org.apache.http.conn.ssl.SSLSocketFactory.createSocket(SSLSocketFactory.java:381)
08-04 12:18:21.687: W/webserviceCall(8068):     at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:164)
08-04 12:18:21.687: W/webserviceCall(8068):     at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
08-04 12:18:21.687: W/webserviceCall(8068):     at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
08-04 12:18:21.687: W/webserviceCall(8068):     at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:359)
08-04 12:18:21.687: W/webserviceCall(8068):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
08-04 12:18:21.687: W/webserviceCall(8068):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
08-04 12:18:21.687: W/webserviceCall(8068):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
08-04 12:18:21.687: W/webserviceCall(8068):     at com.osi.wolla.webserviceCall.getBundle(webserviceCall.java:870)
08-04 12:18:21.687: W/webserviceCall(8068):     at com.osi.wolla.login.Login$task.onPostExecute(Login.java:165)
08-04 12:18:21.687: W/webserviceCall(8068):     at com.osi.wolla.login.Login$task.onPostExecute(Login.java:1)
08-04 12:18:21.687: W/webserviceCall(8068):     at android.os.AsyncTask.finish(AsyncTask.java:417)
08-04 12:18:21.687: W/webserviceCall(8068):     at android.os.AsyncTask.access$300(AsyncTask.java:127)
08-04 12:18:21.687: W/webserviceCall(8068):     at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:429)
08-04 12:18:21.687: W/webserviceCall(8068):     at android.os.Handler.dispatchMessage(Handler.java:99)
08-04 12:18:21.687: W/webserviceCall(8068):     at android.os.Looper.loop(Looper.java:130)
08-04 12:18:21.687: W/webserviceCall(8068):     at android.app.ActivityThread.main(ActivityThread.java:3687)
08-04 12:18:21.687: W/webserviceCall(8068):     at java.lang.reflect.Method.invokeNative(Native Method)
08-04 12:18:21.687: W/webserviceCall(8068):     at java.lang.reflect.Method.invoke(Method.java:507)
08-04 12:18:21.687: W/webserviceCall(8068):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
08-04 12:18:21.687: W/webserviceCall(8068):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
08-04 12:18:21.687: W/webserviceCall(8068):     at dalvik.system.NativeStart.main(Native Method)
08-04 12:18:21.695: D/AndroidRuntime(8068): Shutting down VM
08-04 12:18:21.695: W/dalvikvm(8068): threadid=1: thread exiting with uncaught exception (group=0x40018578)
08-04 12:18:21.695: E/AndroidRuntime(8068): FATAL EXCEPTION: main
08-04 12:18:21.695: E/AndroidRuntime(8068): java.lang.NullPointerException
08-04 12:18:21.695: E/AndroidRuntime(8068):     at java.io.StringReader.<init>(StringReader.java:46)
08-04 12:18:21.695: E/AndroidRuntime(8068):     at com.osi.wolla.xmlParser.parseUser(xmlParser.java:239)
08-04 12:18:21.695: E/AndroidRuntime(8068):     at com.osi.wolla.login.Login$task.onPostExecute(Login.java:168)
08-04 12:18:21.695: E/AndroidRuntime(8068):     at com.osi.wolla.login.Login$task.onPostExecute(Login.java:1)
08-04 12:18:21.695: E/AndroidRuntime(8068):     at android.os.AsyncTask.finish(AsyncTask.java:417)
08-04 12:18:21.695: E/AndroidRuntime(8068):     at android.os.AsyncTask.access$300(AsyncTask.java:127)
08-04 12:18:21.695: E/AndroidRuntime(8068):     at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:429)
08-04 12:18:21.695: E/AndroidRuntime(8068):     at android.os.Handler.dispatchMessage(Handler.java:99)
08-04 12:18:21.695: E/AndroidRuntime(8068):     at android.os.Looper.loop(Looper.java:130)
08-04 12:18:21.695: E/AndroidRuntime(8068):     at android.app.ActivityThread.main(ActivityThread.java:3687)
08-04 12:18:21.695: E/AndroidRuntime(8068):     at java.lang.reflect.Method.invokeNative(Native Method)
08-04 12:18:21.695: E/AndroidRuntime(8068):     at java.lang.reflect.Method.invoke(Method.java:507)
08-04 12:18:21.695: E/AndroidRuntime(8068):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
08-04 12:18:21.695: E/AndroidRuntime(8068):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
08-04 12:18:21.695: E/AndroidRuntime(8068):     at dalvik.system.NativeStart.main(Native Method)

  Here is My code.
   final String URL = "https://mywolla.com/mobwebservices/svalidateuser.php?wsdl";

   String response = null;
            try {

                 HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;

                   DefaultHttpClient client = new DefaultHttpClient();

                   SchemeRegistry registry = new SchemeRegistry();
                   SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
                   socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
                   registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
                   registry.register(new Scheme("https", socketFactory, 443));
                   SingleClientConnManager mgr = new SingleClientConnManager(client.getParams(), registry);
                   DefaultHttpClient httpClient = new DefaultHttpClient(mgr, client.getParams());

                   // Set verifier
                   HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);

                   // Example send http request

                   HttpPost httpPost = new HttpPost(URL);

                   HttpResponse response1 = httpClient.execute(httpPost);

Answer: For development purposes you need to trust all certificates. Use this tutorial (avilyne.com/?p=105)
Add the keystore file to the res/raw directory. and replace the main activity code with the following.
package com.avilyne.android;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;

import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.params.ConnManagerPNames;
import org.apache.http.conn.params.ConnPerRouteBean;
import org.apache.http.conn.scheme.LayeredSocketFactory;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.SingleClientConnManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {

    private static final String SERVICE_URL =
    "https://192.168.2.101:8443/RestWebServiceDemo/rest/person";

    private static final String TAG = "AndroidRESTClientActivity";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void retrieveSampleData(View vw) {

        String sampleURL = SERVICE_URL + "/sample";

        WebServiceTask wst = new WebServiceTask(WebServiceTask.GET_TASK, this,
                "GETting data...");

        wst.execute(new String[] { sampleURL });

    }

    public void clearControls(View vw) {

        EditText edFirstName = (EditText) findViewById(R.id.first_name);
        EditText edLastName = (EditText) findViewById(R.id.last_name);
        EditText edEmail = (EditText) findViewById(R.id.email);

        edFirstName.setText("");
        edLastName.setText("");
        edEmail.setText("");

    }

    public void postData(View vw) {

        EditText edFirstName = (EditText) findViewById(R.id.first_name);
        EditText edLastName = (EditText) findViewById(R.id.last_name);
        EditText edEmail = (EditText) findViewById(R.id.email);

        String firstName = edFirstName.getText().toString();
        String lastName = edLastName.getText().toString();
        String email = edEmail.getText().toString();

        if (firstName.equals("") || lastName.equals("") || email.equals("")) {
            Toast.makeText(this, "Please enter in all required fields.",
                    Toast.LENGTH_LONG).show();
            return;
        }

        WebServiceTask wst = new WebServiceTask(WebServiceTask.POST_TASK, this,
                "Posting data...");

        wst.addNameValuePair("firstName", firstName);
        wst.addNameValuePair("lastName", lastName);
        wst.addNameValuePair("email", email);

        // the passed String is the URL we will POST to
        wst.execute(new String[] { SERVICE_URL });

    }

    public void handleResponse(String response) {

        EditText edFirstName = (EditText) findViewById(R.id.first_name);
        EditText edLastName = (EditText) findViewById(R.id.last_name);
        EditText edEmail = (EditText) findViewById(R.id.email);

        edFirstName.setText("");
        edLastName.setText("");
        edEmail.setText("");

        try {

            JSONObject jso = new JSONObject(response);

            String firstName = jso.getString("firstName");
            String lastName = jso.getString("lastName");
            String email = jso.getString("email");

            edFirstName.setText(firstName);
            edLastName.setText(lastName);
            edEmail.setText(email);

        } catch (Exception e) {
            Log.e(TAG, e.getLocalizedMessage(), e);
        }

    }

    private void hideKeyboard() {

        InputMethodManager inputManager = (InputMethodManager) MainActivity.this
                .getSystemService(Context.INPUT_METHOD_SERVICE);

        inputManager.hideSoftInputFromWindow(MainActivity.this
                .getCurrentFocus().getWindowToken(),
                InputMethodManager.HIDE_NOT_ALWAYS);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

    private class WebServiceTask extends AsyncTask<String, Integer, String> {

        public static final int POST_TASK = 1;
        public static final int GET_TASK = 2;

        private static final String TAG = "WebServiceTask";

        // connection timeout, in milliseconds (waiting to connect)
        // private static final int CONN_TIMEOUT = 3000;

        // socket timeout, in milliseconds (waiting for data)
        // private static final int SOCKET_TIMEOUT = 5000;

        private int taskType = GET_TASK;
        private Context mContext = null;
        private String processMessage = "Processing...";

        private ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();

        private ProgressDialog pDlg = null;

        public WebServiceTask(int taskType, Context mContext,
                String processMessage) {

            this.taskType = taskType;
            this.mContext = mContext;
            this.processMessage = processMessage;
        }

        public void addNameValuePair(String name, String value) {

            params.add(new BasicNameValuePair(name, value));
        }

        private void showProgressDialog() {

            pDlg = new ProgressDialog(mContext);
            pDlg.setMessage(processMessage);
            pDlg.setProgressDrawable(mContext.getWallpaper());
            pDlg.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            pDlg.setCancelable(false);
            pDlg.show();

        }

        @Override
        protected void onPreExecute() {

            hideKeyboard();
            showProgressDialog();

        }

        protected String doInBackground(String... urls) {

            String url = urls[0];
            String result = "";

            HttpResponse response = doResponse(url);

            if (response == null) {
                return result;
            } else {

                try {

                    result = inputStreamToString(response.getEntity()
                            .getContent());

                } catch (IllegalStateException e) {
                    Log.e(TAG, e.getLocalizedMessage(), e);

                } catch (IOException e) {
                    Log.e(TAG, e.getLocalizedMessage(), e);
                }

            }

            return result;
        }

        @Override
        protected void onPostExecute(String response) {

            handleResponse(response);
            pDlg.dismiss();

        }

        // Establish connection and socket (data retrieval) timeouts
        /*
         * private HttpParams getHttpParams() {
         *
         * HttpParams htpp = new BasicHttpParams();
         *
         * HttpConnectionParams.setConnectionTimeout(htpp, CONN_TIMEOUT);
         * HttpConnectionParams.setSoTimeout(htpp, SOCKET_TIMEOUT);
         *
         * return htpp; }
         */

        private HttpResponse doResponse(String url) {

            // Use our connection and data timeouts as parameters for our
            // DefaultHttpClient
            // HttpClient httpclient = new DefaultHttpClient(getHttpParams());

            DefaultHttpClient httpsclient = httpsClient();

            HttpResponse response = null;

            try {
                switch (taskType) {

                case POST_TASK:
                    HttpPost httppost = new HttpPost(url);
                    // Add parameters
                    httppost.setEntity(new UrlEncodedFormEntity(params));

                    response = httpsclient.execute(httppost); // httpclient.execute(httppost);
                    break;
                case GET_TASK:
                    HttpGet httpget = new HttpGet(url);
                    response = httpsclient.execute(httpget); // httpclient.execute(httpget);
                    break;
                }
            } catch (Exception e) {

                Log.e(TAG, e.getLocalizedMessage(), e);

            }

            return response;
        }

        private String inputStreamToString(InputStream is) {

            String line = "";
            StringBuilder total = new StringBuilder();

            // Wrap a BufferedReader around the InputStream
            BufferedReader rd = new BufferedReader(new InputStreamReader(is));

            try {
                // Read response until the end
                while ((line = rd.readLine()) != null) {
                    total.append(line);
                }
            } catch (IOException e) {
                Log.e(TAG, e.getLocalizedMessage(), e);
            }

            // Return full string
            return total.toString();
        }

    }

    private DefaultHttpClient httpsClient() {
        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(new Scheme("http", PlainSocketFactory
                .getSocketFactory(), 80));
        schemeRegistry.register(new Scheme("https", new EasySSLSocketFactory(),
                443));

        HttpParams httpParams = new BasicHttpParams();
        httpParams.setParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 30);
        httpParams.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE,
                new ConnPerRouteBean(30));
        httpParams.setParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, false);
        HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);

        ClientConnectionManager cm = new SingleClientConnManager(httpParams,
                schemeRegistry);
        return new DefaultHttpClient(cm, httpParams);
    }

    private class EasySSLSocketFactory implements LayeredSocketFactory {
        private SSLContext sslcontext = null;

        private SSLContext createEasySSLContext() throws IOException {
            try {
                SSLContext context = SSLContext.getInstance("TLS");
                context.init(null,
                        new TrustManager[] { new EasyX509TrustManager(null) },
                        null);
                return context;
            } catch (Exception e) {
                throw new IOException(e.getMessage());
            }
        }

        private SSLContext getSSLContext() throws IOException {
            if (this.sslcontext == null) {
                this.sslcontext = createEasySSLContext();
            }
            return this.sslcontext;
        }

        /**
         * @see org.apache.http.conn.scheme.SocketFactory#connectSocket(java.net.Socket,
         *      java.lang.String, int, java.net.InetAddress, int,
         *      org.apache.http.params.HttpParams)
         */
        public Socket connectSocket(Socket sock, String host, int port,
                InetAddress localAddress, int localPort, HttpParams params)
                throws IOException, UnknownHostException,
                ConnectTimeoutException {
            int connTimeout = HttpConnectionParams.getConnectionTimeout(params);
            int soTimeout = HttpConnectionParams.getSoTimeout(params);

            InetSocketAddress remoteAddress = new InetSocketAddress(host, port);
            SSLSocket sslsock = (SSLSocket) ((sock != null) ? sock
                    : createSocket());

            if ((localAddress != null) || (localPort > 0)) {
                // we need to bind explicitly
                if (localPort < 0) {
                    localPort = 0; // indicates "any"
                }
                InetSocketAddress isa = new InetSocketAddress(localAddress,
                        localPort);
                sslsock.bind(isa);
            }

            sslsock.connect(remoteAddress, connTimeout);
            sslsock.setSoTimeout(soTimeout);
            return sslsock;

        }

        /**
         * @see org.apache.http.conn.scheme.SocketFactory#createSocket()
         */
        public Socket createSocket() throws IOException {
            return getSSLContext().getSocketFactory().createSocket();
        }

        /**
         * @see org.apache.http.conn.scheme.SocketFactory#isSecure(java.net.Socket)
         */
        public boolean isSecure(Socket socket) throws IllegalArgumentException {
            return true;
        }

        /**
         * @see org.apache.http.conn.scheme.LayeredSocketFactory#createSocket(java.net.Socket,
         *      java.lang.String, int, boolean)
         */
        public Socket createSocket(Socket socket, String host, int port,
                boolean autoClose) throws IOException, UnknownHostException {
            // return getSSLContext().getSocketFactory().createSocket(socket,
            // host, port, autoClose);
            return getSSLContext().getSocketFactory().createSocket(socket,
                    host, port, autoClose);
        }

        // -------------------------------------------------------------------
        // javadoc in org.apache.http.conn.scheme.SocketFactory says :
        // Both Object.equals() and Object.hashCode() must be overridden
        // for the correct operation of some connection managers
        // -------------------------------------------------------------------

        public boolean equals(Object obj) {
            return ((obj != null) && obj.getClass().equals(
                    EasySSLSocketFactory.class));
        }

        public int hashCode() {
            return EasySSLSocketFactory.class.hashCode();
        }

    }

    private class EasyX509TrustManager implements X509TrustManager {
        private X509TrustManager standardTrustManager = null;

        /**
         * Constructor for EasyX509TrustManager.
         */
        public EasyX509TrustManager(KeyStore keystore)
                throws NoSuchAlgorithmException, KeyStoreException {
            super();
            TrustManagerFactory factory = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());
            factory.init(keystore);
            TrustManager[] trustmanagers = factory.getTrustManagers();
            if (trustmanagers.length == 0) {
                throw new NoSuchAlgorithmException("no trust manager found");
            }
            this.standardTrustManager = (X509TrustManager) trustmanagers[0];
        }

        /**
         * @see
         *      javax.net.ssl.X509TrustManager#checkClientTrusted(X509Certificate
         *      [],String authType)
         */
        public void checkClientTrusted(X509Certificate[] certificates,
                String authType) throws CertificateException {
            standardTrustManager.checkClientTrusted(certificates, authType);
        }

        /**
         * @see
         *      javax.net.ssl.X509TrustManager#checkServerTrusted(X509Certificate
         *      [],String authType)
         */
        public void checkServerTrusted(X509Certificate[] certificates,
                String authType) throws CertificateException {
            if ((certificates != null) && (certificates.length == 1)) {
                certificates[0].checkValidity();
            } else {
                standardTrustManager.checkServerTrusted(certificates, authType);
            }
        }

        /**
         * @see javax.net.ssl.X509TrustManager#getAcceptedIssuers()
         */
        public X509Certificate[] getAcceptedIssuers() {
            return this.standardTrustManager.getAcceptedIssuers();
        }

    }
}

Comment: that tutorial is for webservices with url http not for https.
Comment: thanks for your response. But I am not understanding how to generate keystore file.I came to know that to create keystore we need some certificates what are those where can i get. Please help me. I am new to andriod.pleae check the link once http://stackoverflow.com/questions/9531710/problems-with-https-no-peer-certificate-in-android
Comment: you can [generate](http://tomcat.apache.org/tomcat-6.0-doc/ssl-howto.html) the keystore file using java's keytool and use self signed certificates. Import the keystore in your android application as well as the server.
Answer: please use below code:
public class WebAPIRequest {

public static String convertStreamToString(InputStream is)
        throws IOException {
    if (is != null) {
        StringBuilder sb = new StringBuilder();
        String line;
        try {
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(is, "UTF-8"));
            while ((line = reader.readLine()) != null) {
                sb.append(line).append("\n");
            }
        } finally {
            is.close();
        }
        return sb.toString();
    } else {
        return "";
    }
}

public static Document performPost(String url, String body) {
    Document doc = null;

    try {
        HttpParams basicparams = new BasicHttpParams();
        URI uri = new URI(url);
        HttpPost method = new HttpPost(uri);
        int timeoutConnection = 60000;
        HttpConnectionParams.setConnectionTimeout(basicparams,
                timeoutConnection);
        DefaultHttpClient client = new DefaultHttpClient(basicparams);
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        body = body.replaceAll("%20", " ");
        String[] parameters = body.split("&");
        for (int i = 0; i < parameters.length; i++) {
            String[] parameter = parameters[i].split("=");
            if (parameter.length >= 2) {
                nameValuePairs.add(new BasicNameValuePair(parameter[0],
                        parameter[1]));
            }
        }
        method.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        HttpResponse res = client.execute(method);

        InputStream data = res.getEntity().getContent();
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        doc = db.parse(data);
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        // e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (URISyntaxException e) {
        // TODO Auto-generated catch block
        // e.printStackTrace();
    } catch (ParserConfigurationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SAXException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return doc;
}

public static String performRequestAsString(String url, String method,
        List<NameValuePair> params) {
    String value = null;

    try {

        if (method == "POST") {
            // request method is POST
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));

            String paramString = URLEncodedUtils.format(params, "utf-8");
            String sampleurl = url + "" + paramString;
            Log.e("Request_Url", "" + sampleurl);

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            InputStream is = httpEntity.getContent();
            value = convertStreamToString(is);

        } else if (method == "GET") {
            // request method is GET
            DefaultHttpClient httpClient = new DefaultHttpClient();
            String paramString = URLEncodedUtils.format(params, "utf-8");
            url += "" + paramString;
            Log.e("Request_Url", "" + url);
            HttpGet httpGet = new HttpGet(url);

            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            InputStream is = httpEntity.getContent();
            value = convertStreamToString(is);
        }

    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        // e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return value;
}

public static JSONObject makeJsonObjHttpRequest(String url, String method,
        List<NameValuePair> params) {

    InputStream is = null;
    JSONObject jObj = null;
    String json = "";
    // Making HTTP request
    try {

        // check for request method
        if (method == "POST") {
            // request method is POST
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));

            String paramString = URLEncodedUtils.format(params, "utf-8");
            String sampleurl = url + "" + paramString;
            Log.e("Request_Url", "" + sampleurl);

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        } else if (method == "GET") {
            // request method is GET
            DefaultHttpClient httpClient = new DefaultHttpClient();
            String paramString = URLEncodedUtils.format(params, "utf-8");
            url += "" + paramString;
            Log.e("Request_Url", "" + url);
            HttpGet httpGet = new HttpGet(url);

            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
        }

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jObj;

}

public static JSONArray makeJsonArryHttpRequest(String url, String method,
        List<NameValuePair> params) {

    InputStream is = null;
    JSONArray jArray = null;
    String json = "";
    // Making HTTP request
    try {

        // check for request method
        if (method == "POST") {
            // request method is POST
            // defaultHttpClient

            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));

            String paramString = URLEncodedUtils.format(params, "utf-8");
            String sampleurl = url + "" + paramString;
            Log.e("Request_Url", "" + sampleurl);

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        } else if (method == "GET") {
            // request method is GET
            DefaultHttpClient httpClient = new DefaultHttpClient();
            String paramString = URLEncodedUtils.format(params, "utf-8");
            url += "" + paramString;
            Log.e("Request_Url", "" + url);
            HttpGet httpGet = new HttpGet(url);

            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
        }

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        jArray = new JSONArray(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jArray;

}

}


Find the conformal maps from $\Omega =\left \{ z\in\mathbb{C}:|z|>1,Re(z)>0, \text{ and } Im(z)>0 \right \}$ to the unit disk

Question: Find all the conformal mappings from $\Omega$ to the unit disk,where
$\Omega=\{z\in\mathbb{C}: |z|>1, Re(z)>0, Im(z)>0 \}$.
Such that the image of $1+i$ is $0$.
I figured out that by taking the composition of
$T_1=iz+z$ (Or I guess $z^2$ will also work).
$T_2=\frac{1}{2}(z+\frac{1}{z})$
$T_3= \frac{i-z}{i+z}$
We can map the $\Omega$ to the unit disk.
But it doesn't satisfy the condition that $i+1\to 0$ .
Can I alter my answer to get the desired result or is there a totally a new approach.
Comment: When you say "all the conformal mappings", are there any restrictions like the mapping must be injective?
Comment: Did you look at the [Schwarz–Christoffel_mapping](https://en.wikipedia.org/wiki/Schwarz–Christoffel_mapping) obtained by sampling $n$ points on the circle to obtain a polygonal domain, the limit as $n \to \infty$ should have a simple formula
Comment: $z \mapsto z^2$ does not map $\Omega$ to $\mathbb C \setminus D_1(0)$.
Answer: To find one such mapping, first apply $z \mapsto z^2$. Then apply the Joukowsky transform $J$. Since $J(e^{i t}) = \cos t$, consider what the boundary of $\Omega$ is mapped to.


Serializing unknown types

Question: Ok, I'll try to explain more clearly what I tried here
I understand that protobuf is a protocol that works with known types, you serialize an object of a given type which contains data that you also know.
I would really like to know if there's a way with Marc's implementation to serialize [ProtoMember] of type object, which could point to an instance of a basic type or a collection that's already managed by the library.
Looks like it's not, but I'm a bit frustrated because I feel Marc's library could do it, considering all the reflection/gen stuffs it's already doing.
It wouldn't be fully compliant with the protocol, but I don't care as I'm using the same libraries on both ends in a close circuit fashion.
I really need to serialize, for instance, a Dictionary<int, string> from a ProtoMember of type Object.
Answer: For single objects, there is a hack in place - DynamicType=true on the [ProtoMember]. It isn't pretty, and it isn't clever, and it isn't what I would call "reliable". I would strongly suggest finding just about any alternative approach. It also does not work with lists. The inheritance support is much better, and one neat trick is generic inheritance, i.e.
[ProtoContract]
[ProtoInclude(1, typeof(Foo<int>))]
[ProtoInclude(2, typeof(Foo<string>))]
[ProtoInclude(3, typeof(Foo<Customer>))]
// etc for expected types
public abstract class Foo {
    public abstract object Value { get; }
}
[ProtoContract]
public sealed class Foo<T> : Foo {
    public override object Value { get { return TypedValue; } }
    [ProtoMember(1)]
    public T TypedValue {get;set;}
}

and serialize a Foo instead of an object.
Comment: Thank you for the answer. The thing is the property Value can reference an object which type is really decided at run-time (a string, int, List, Dictionary, etc.) so this trick doesn't work I guess. I didn't know about DynamicType but if it's not working on collection it won't work too.
Answer: What about the serialization of primitive types from ProtoMembers defined as objects? I recall  an issue dating from 2011 on this subject (https://code.google.com/p/protobuf-net/issues/detail?id=175), do we have any update on this?
What I'm trying to do is to maintain compatibility with files that were serialized using the BinaryFormatter class from .NET.
(sorry for writing this here, I don't have enough rep to add a comment or something like that)

Serializing unknown types


plotting part of data using violin plot and the other part as stripchart (stripplot)

Question: I an trying to plot 6 groups, in which 3 has a good amount of counts (ranging from 20 to 400) and the rest 3 have very small counts (1 to 9). I want to plot the distribution of a continuous variable within each of these 6 groups and be very honest in the plot about the dramatically different sizes of the groups. I am thinking about generating violin plot for the 3 groups with larger counts to show both the median and the dispersion, and for the low-count groups, plot stripchart to show individual data points.
Could anyone kindly help me find a way to do such a hybrid plot?
Other plot suggestions are also welcome.
Comment: In some particular package?
Answer: Here's a basic one done in R:
<code># make some data
y1=rnorm(1,10);y2=rnorm(5,9);y3=rnorm(9,10.5)
y4=rnorm(20,9.5);y5=rnorm(90,11);y6=rnorm(400,10.25,2)

# do the plot
plot(y=rep(6,length(y6)),x=y6,ylim=c(0,7),
  xlim=c(min(y1,y2,y3,y4,y5,y6),max(y1,y2,y3,y4,y5,y6)),
  type="n",xlab="",ylab="",yaxt="n")
stripchart(x=list(y1=y1,y2=y2,y3=y3),at=c(1,2,3),add=TRUE,pch=1)
vioplot(y4,y5,y6,at=c(4,5,6),add=TRUE,horizontal=TRUE)
axis(2,at=1:6,labels=c("y1","y2","y3","y4","y5","y6"))
</code>


TokenMismatchException in VerifyCsrfToken.php while submiting through edittable

Question: I have used edittable jquery plugin:
Name	<td class="name" data-pk="<?php echo auth()->user()->id;?>" data-url="{{url('/edit/name')}}">{{auth()->user()->name}}

and, $('.name').editable();
This route: Route::post('/edit/name', 'EditController@name');
And the controller:
 public function name(Request $request)
    {
        $update=User::find()->where(['id'=>$request->pk])->first();
        $update->name=$request->value;
        $update->update();
    }

But i got TokenMismatchException error: How can i pass token while using jquery x-editable plugin?
Answer: In laravel, for post request you have to pass the csrf token value as well. Its a security mechanism provided by laravel. To remove this error, try this:
<input type="hidden" name="_token" value="{{ csrf_token() }}">

put this hidden field inside your form tag, its value is also posted when form is submitted.
Reference
For ajax:
$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});

Comment: this worked after adding token in html meta tag.thanks.
Comment: but, i don't have a form.
Comment: I don't know if that uses ajax. this is the plugin i have used. https://vitalets.github.io/x-editable/
Comment: Sounds great :)
Answer: Try to add below line in form html code
<input type="hidden" name="_token" value="{{ csrf_token() }}">

I hope it works.
Comment: but, i don't have a form.